Java Code Examples for org.apache.hadoop.security.authentication.util.KerberosName#setRules()

The following examples show how to use org.apache.hadoop.security.authentication.util.KerberosName#setRules() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestProxyUserSpnegoHttpServer.java    From hbase with Apache License 2.0 6 votes vote down vote up
protected static Configuration buildSpnegoConfiguration(Configuration conf,
    String serverPrincipal, File serverKeytab) {
  KerberosName.setRules("DEFAULT");

  conf.setInt(HttpServer.HTTP_MAX_THREADS, TestHttpServer.MAX_THREADS);

  // Enable Kerberos (pre-req)
  conf.set("hbase.security.authentication", "kerberos");
  conf.set(HttpServer.HTTP_UI_AUTHENTICATION, "kerberos");
  conf.set(HttpServer.HTTP_SPNEGO_AUTHENTICATION_PRINCIPAL_KEY, serverPrincipal);
  conf.set(HttpServer.HTTP_SPNEGO_AUTHENTICATION_KEYTAB_KEY, serverKeytab.getAbsolutePath());

  conf.set(HttpServer.HTTP_SPNEGO_AUTHENTICATION_ADMIN_USERS_KEY, PRIVILEGED_PRINCIPAL);
  conf.set(HttpServer.HTTP_SPNEGO_AUTHENTICATION_PROXYUSER_ENABLE_KEY, "true");
  conf.set("hadoop.security.authorization", "true");

  conf.set("hadoop.proxyuser.wheel.hosts", "*");
  conf.set("hadoop.proxyuser.wheel.users", PRIVILEGED_PRINCIPAL + "," + UNPRIVILEGED_PRINCIPAL);
  return conf;
}
 
Example 2
Source File: TestThriftSpnegoHttpServer.java    From hbase with Apache License 2.0 6 votes vote down vote up
private static void addSecurityConfigurations(Configuration conf) {
  KerberosName.setRules("DEFAULT");

  HBaseKerberosUtils.setKeytabFileForTesting(serverKeytab.getAbsolutePath());

  conf.setBoolean(THRIFT_SUPPORT_PROXYUSER_KEY, true);
  conf.setBoolean(Constants.USE_HTTP_CONF_KEY, true);

  conf.set(Constants.THRIFT_KERBEROS_PRINCIPAL_KEY, serverPrincipal);
  conf.set(Constants.THRIFT_KEYTAB_FILE_KEY, serverKeytab.getAbsolutePath());

  HBaseKerberosUtils.setSecuredConfiguration(conf, serverPrincipal, spnegoServerPrincipal);
  conf.set("hadoop.proxyuser.hbase.hosts", "*");
  conf.set("hadoop.proxyuser.hbase.groups", "*");
  conf.set(Constants.THRIFT_SPNEGO_PRINCIPAL_KEY, spnegoServerPrincipal);
  conf.set(Constants.THRIFT_SPNEGO_KEYTAB_FILE_KEY, spnegoServerKeytab.getAbsolutePath());
}
 
Example 3
Source File: TestThriftSpnegoHttpFallbackServer.java    From hbase with Apache License 2.0 6 votes vote down vote up
private static void addSecurityConfigurations(Configuration conf) {
  KerberosName.setRules("DEFAULT");

  HBaseKerberosUtils.setKeytabFileForTesting(serverKeytab.getAbsolutePath());

  conf.setBoolean(THRIFT_SUPPORT_PROXYUSER_KEY, true);
  conf.setBoolean(Constants.USE_HTTP_CONF_KEY, true);

  conf.set(Constants.THRIFT_KERBEROS_PRINCIPAL_KEY, serverPrincipal);
  conf.set(Constants.THRIFT_KEYTAB_FILE_KEY, serverKeytab.getAbsolutePath());

  HBaseKerberosUtils.setSecuredConfiguration(conf, spnegoServerPrincipal,
    spnegoServerPrincipal);
  conf.set("hadoop.proxyuser.HTTP.hosts", "*");
  conf.set("hadoop.proxyuser.HTTP.groups", "*");
  conf.set(Constants.THRIFT_KERBEROS_PRINCIPAL_KEY, spnegoServerPrincipal);
}
 
Example 4
Source File: TestUserGroupInformation.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test (timeout = 30000)
public void testEnsureInitWithRules() throws IOException {
  String rules = "RULE:[1:RULE1]";

  // trigger implicit init, rules should init
  UserGroupInformation.reset();
  assertFalse(KerberosName.hasRulesBeenSet());
  UserGroupInformation.createUserForTesting("someone", new String[0]);
  assertTrue(KerberosName.hasRulesBeenSet());
  
  // set a rule, trigger implicit init, rule should not change 
  UserGroupInformation.reset();
  KerberosName.setRules(rules);
  assertTrue(KerberosName.hasRulesBeenSet());
  assertEquals(rules, KerberosName.getRules());
  UserGroupInformation.createUserForTesting("someone", new String[0]);
  assertEquals(rules, KerberosName.getRules());
}
 
Example 5
Source File: StormRangerPlugin.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Override
synchronized public void init() {
	if (!initialized) {
		// mandatory call to base plugin
		super.init();
		// One time call to register the audit hander with the policy engine.
		super.setResultProcessor(new RangerDefaultAuditHandler(getConfig()));
		// this needed to set things right in the nimbus process
		if (KerberosName.getRules() == null) {
			KerberosName.setRules("DEFAULT");
		}

		initialized = true;
		LOG.info("StormRangerPlugin initialized!");
	}
}
 
Example 6
Source File: KmsKeyMgr.java    From ranger with Apache License 2.0 6 votes vote down vote up
private Subject getSubjectForKerberos(String provider) throws Exception {
	String userName = getKMSUserName(provider);
	String password = getKMSPassword(provider);
	String nameRules = PropertiesUtil.getProperty(NAME_RULES);
	if (StringUtils.isEmpty(nameRules)) {
		KerberosName.setRules("DEFAULT");
		nameRules = "DEFAULT";
	} else {
		KerberosName.setRules(nameRules);
	}
	Subject sub = new Subject();
	String rangerPrincipal = SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(ADMIN_USER_PRINCIPAL), PropertiesUtil.getProperty(HOST_NAME));
	if (checkKerberos()) {
		if (SecureClientLogin.isKerberosCredentialExists(rangerPrincipal, PropertiesUtil.getProperty(ADMIN_USER_KEYTAB))) {
			sub = SecureClientLogin.loginUserFromKeytab(rangerPrincipal, PropertiesUtil.getProperty(ADMIN_USER_KEYTAB), nameRules);
		} else {
			sub = SecureClientLogin.loginUserWithPassword(userName, password);
		}
	} else {
		sub = SecureClientLogin.login(userName);
	}
	return sub;
}
 
Example 7
Source File: TestUserGroupInformation.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test (timeout = 30000)
public void testEnsureInitWithRules() throws IOException {
  String rules = "RULE:[1:RULE1]";

  // trigger implicit init, rules should init
  UserGroupInformation.reset();
  assertFalse(KerberosName.hasRulesBeenSet());
  UserGroupInformation.createUserForTesting("someone", new String[0]);
  assertTrue(KerberosName.hasRulesBeenSet());
  
  // set a rule, trigger implicit init, rule should not change 
  UserGroupInformation.reset();
  KerberosName.setRules(rules);
  assertTrue(KerberosName.hasRulesBeenSet());
  assertEquals(rules, KerberosName.getRules());
  UserGroupInformation.createUserForTesting("someone", new String[0]);
  assertEquals(rules, KerberosName.getRules());
}
 
Example 8
Source File: TestUserGroupInformation.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test (timeout = 30000)
public void testSetConfigWithRules() {
  String[] rules = { "RULE:[1:TEST1]", "RULE:[1:TEST2]", "RULE:[1:TEST3]" };

  // explicitly set a rule
  UserGroupInformation.reset();
  assertFalse(KerberosName.hasRulesBeenSet());
  KerberosName.setRules(rules[0]);
  assertTrue(KerberosName.hasRulesBeenSet());
  assertEquals(rules[0], KerberosName.getRules());

  // implicit init should honor rules already being set
  UserGroupInformation.createUserForTesting("someone", new String[0]);
  assertEquals(rules[0], KerberosName.getRules());

  // set conf, should override
  conf.set(HADOOP_SECURITY_AUTH_TO_LOCAL, rules[1]);
  UserGroupInformation.setConfiguration(conf);
  assertEquals(rules[1], KerberosName.getRules());

  // set conf, should again override
  conf.set(HADOOP_SECURITY_AUTH_TO_LOCAL, rules[2]);
  UserGroupInformation.setConfiguration(conf);
  assertEquals(rules[2], KerberosName.getRules());
  
  // implicit init should honor rules already being set
  UserGroupInformation.createUserForTesting("someone", new String[0]);
  assertEquals(rules[2], KerberosName.getRules());
}
 
Example 9
Source File: TestSpnegoHttpServer.java    From hbase with Apache License 2.0 5 votes vote down vote up
private static Configuration buildSpnegoConfiguration(Configuration conf, String serverPrincipal,
    File serverKeytab) {
  KerberosName.setRules("DEFAULT");

  conf.setInt(HttpServer.HTTP_MAX_THREADS, TestHttpServer.MAX_THREADS);

  // Enable Kerberos (pre-req)
  conf.set("hbase.security.authentication", "kerberos");
  conf.set(HttpServer.HTTP_UI_AUTHENTICATION, "kerberos");
  conf.set(HttpServer.HTTP_SPNEGO_AUTHENTICATION_PRINCIPAL_KEY, serverPrincipal);
  conf.set(HttpServer.HTTP_SPNEGO_AUTHENTICATION_KEYTAB_KEY, serverKeytab.getAbsolutePath());

  return conf;
}
 
Example 10
Source File: TestSecureRESTServer.java    From hbase with Apache License 2.0 5 votes vote down vote up
private static void updateKerberosConfiguration(Configuration conf,
    String serverPrincipal, String spnegoPrincipal, File serverKeytab) {
  KerberosName.setRules("DEFAULT");

  // Enable Kerberos (pre-req)
  conf.set("hbase.security.authentication", "kerberos");
  conf.set(RESTServer.REST_AUTHENTICATION_TYPE, "kerberos");
  // User to talk to HBase as
  conf.set(RESTServer.REST_KERBEROS_PRINCIPAL, serverPrincipal);
  // User to accept SPNEGO-auth'd http calls as
  conf.set("hbase.rest.authentication.kerberos.principal", spnegoPrincipal);
  // Keytab for both principals above
  conf.set(RESTServer.REST_KEYTAB_FILE, serverKeytab.getAbsolutePath());
  conf.set("hbase.rest.authentication.kerberos.keytab", serverKeytab.getAbsolutePath());
}
 
Example 11
Source File: SecureClientLogin.java    From ranger with Apache License 2.0 5 votes vote down vote up
public synchronized static Subject loginUserFromKeytab(String user, String path, String nameRules) throws IOException {
	try {
		Subject subject = new Subject();
		SecureClientLoginConfiguration loginConf = new SecureClientLoginConfiguration(true, user, path);
		LoginContext login = new LoginContext("hadoop-keytab-kerberos", subject, null, loginConf);
		KerberosName.setRules(nameRules);
		subject.getPrincipals().add(new User(user, AuthenticationMethod.KERBEROS, login));
		login.login();
		return login.getSubject();
	} catch (LoginException le) {
		throw new IOException("Login failure for " + user + " from keytab " + path, le);
	}
}
 
Example 12
Source File: TestUserGroupInformation.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test (timeout = 30000)
public void testSetConfigWithRules() {
  String[] rules = { "RULE:[1:TEST1]", "RULE:[1:TEST2]", "RULE:[1:TEST3]" };

  // explicitly set a rule
  UserGroupInformation.reset();
  assertFalse(KerberosName.hasRulesBeenSet());
  KerberosName.setRules(rules[0]);
  assertTrue(KerberosName.hasRulesBeenSet());
  assertEquals(rules[0], KerberosName.getRules());

  // implicit init should honor rules already being set
  UserGroupInformation.createUserForTesting("someone", new String[0]);
  assertEquals(rules[0], KerberosName.getRules());

  // set conf, should override
  conf.set(HADOOP_SECURITY_AUTH_TO_LOCAL, rules[1]);
  UserGroupInformation.setConfiguration(conf);
  assertEquals(rules[1], KerberosName.getRules());

  // set conf, should again override
  conf.set(HADOOP_SECURITY_AUTH_TO_LOCAL, rules[2]);
  UserGroupInformation.setConfiguration(conf);
  assertEquals(rules[2], KerberosName.getRules());
  
  // implicit init should honor rules already being set
  UserGroupInformation.createUserForTesting("someone", new String[0]);
  assertEquals(rules[2], KerberosName.getRules());
}
 
Example 13
Source File: TestingTools.java    From gcp-token-broker with Apache License 2.0 4 votes vote down vote up
static void initHadoop() {
    Configuration conf = new Configuration();
    conf.set("hadoop.security.authentication", "kerberos");
    UserGroupInformation.setConfiguration(conf);
    KerberosName.setRules("DEFAULT");
}
 
Example 14
Source File: TestGetImageServlet.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Test
public void testIsValidRequestor() throws IOException {
  Configuration conf = new HdfsConfiguration();
  KerberosName.setRules("RULE:[1:$1]\nRULE:[2:$1]");
  
  // Set up generic HA configs.
  conf.set(DFSConfigKeys.DFS_NAMESERVICES, "ns1");
  conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_HA_NAMENODES_KEY_PREFIX,
      "ns1"), "nn1,nn2");
  
  // Set up NN1 HA configs.
  conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY,
      "ns1", "nn1"), "host1:1234");
  conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY,
      "ns1", "nn1"), "hdfs/[email protected]");
  
  // Set up NN2 HA configs.
  conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY,
      "ns1", "nn2"), "host2:1234");
  conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY,
      "ns1", "nn2"), "hdfs/[email protected]");
  
  // Initialize this conf object as though we're running on NN1.
  NameNode.initializeGenericKeys(conf, "ns1", "nn1");
  
  AccessControlList acls = Mockito.mock(AccessControlList.class);
  Mockito.when(acls.isUserAllowed(Mockito.<UserGroupInformation>any())).thenReturn(false);
  ServletContext context = Mockito.mock(ServletContext.class);
  Mockito.when(context.getAttribute(HttpServer2.ADMINS_ACL)).thenReturn(acls);
  
  // Make sure that NN2 is considered a valid fsimage/edits requestor.
  assertTrue(ImageServlet.isValidRequestor(context,
      "hdfs/[email protected]", conf));
  
  // Mark atm as an admin.
  Mockito.when(acls.isUserAllowed(Mockito.argThat(new ArgumentMatcher<UserGroupInformation>() {
    @Override
    public boolean matches(Object argument) {
      return ((UserGroupInformation) argument).getShortUserName().equals("atm");
    }
  }))).thenReturn(true);
  
  // Make sure that NN2 is still considered a valid requestor.
  assertTrue(ImageServlet.isValidRequestor(context,
      "hdfs/[email protected]", conf));
  
  // Make sure an admin is considered a valid requestor.
  assertTrue(ImageServlet.isValidRequestor(context,
      "[email protected]", conf));
  
  // Make sure other users are *not* considered valid requestors.
  assertFalse(ImageServlet.isValidRequestor(context,
      "[email protected]", conf));
}
 
Example 15
Source File: TestJHSDelegationTokenSecretManager.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Test
 public void testRecovery() throws IOException {
   Configuration conf = new Configuration();
   HistoryServerStateStoreService store =
       new HistoryServerMemStateStoreService();
   store.init(conf);
   store.start();
   JHSDelegationTokenSecretManagerForTest mgr =
       new JHSDelegationTokenSecretManagerForTest(store);
   mgr.startThreads();

   MRDelegationTokenIdentifier tokenId1 = new MRDelegationTokenIdentifier(
       new Text("tokenOwner"), new Text("tokenRenewer"),
       new Text("tokenUser"));
   Token<MRDelegationTokenIdentifier> token1 =
       new Token<MRDelegationTokenIdentifier>(tokenId1, mgr);

   MRDelegationTokenIdentifier tokenId2 = new MRDelegationTokenIdentifier(
       new Text("tokenOwner"), new Text("tokenRenewer"),
       new Text("tokenUser"));
   Token<MRDelegationTokenIdentifier> token2 =
       new Token<MRDelegationTokenIdentifier>(tokenId2, mgr);
   DelegationKey[] keys = mgr.getAllKeys();
   long tokenRenewDate1 = mgr.getAllTokens().get(tokenId1).getRenewDate();
   long tokenRenewDate2 = mgr.getAllTokens().get(tokenId2).getRenewDate();
   mgr.stopThreads();

   mgr = new JHSDelegationTokenSecretManagerForTest(store);
   mgr.recover(store.loadState());
   List<DelegationKey> recoveredKeys = Arrays.asList(mgr.getAllKeys());
   for (DelegationKey key : keys) {
     assertTrue("key missing after recovery", recoveredKeys.contains(key));
   }
   assertTrue("token1 missing", mgr.getAllTokens().containsKey(tokenId1));
   assertEquals("token1 renew date", tokenRenewDate1,
       mgr.getAllTokens().get(tokenId1).getRenewDate());
   assertTrue("token2 missing", mgr.getAllTokens().containsKey(tokenId2));
   assertEquals("token2 renew date", tokenRenewDate2,
       mgr.getAllTokens().get(tokenId2).getRenewDate());

   mgr.startThreads();
   mgr.verifyToken(tokenId1, token1.getPassword());
   mgr.verifyToken(tokenId2, token2.getPassword());
   MRDelegationTokenIdentifier tokenId3 = new MRDelegationTokenIdentifier(
       new Text("tokenOwner"), new Text("tokenRenewer"),
       new Text("tokenUser"));
   Token<MRDelegationTokenIdentifier> token3 =
       new Token<MRDelegationTokenIdentifier>(tokenId3, mgr);
   assertEquals("sequence number restore", tokenId2.getSequenceNumber() + 1,
       tokenId3.getSequenceNumber());
   mgr.cancelToken(token1, "tokenOwner");

   // Testing with full principal name
   MRDelegationTokenIdentifier tokenIdFull = new MRDelegationTokenIdentifier(
       new Text("tokenOwner/localhost@LOCALHOST"), new Text("tokenRenewer"),
       new Text("tokenUser"));
   KerberosName.setRules("RULE:[1:$1]\nRULE:[2:$1]");
   Token<MRDelegationTokenIdentifier> tokenFull = new Token<MRDelegationTokenIdentifier>(
       tokenIdFull, mgr);
   // Negative test
   try {
     mgr.cancelToken(tokenFull, "tokenOwner");
   } catch (AccessControlException ace) {
     assertTrue(ace.getMessage().contains(
         "is not authorized to cancel the token"));
   }
   // Succeed to cancel with full principal
   mgr.cancelToken(tokenFull, tokenIdFull.getOwner().toString());

   long tokenRenewDate3 = mgr.getAllTokens().get(tokenId3).getRenewDate();
   mgr.stopThreads();

   mgr = new JHSDelegationTokenSecretManagerForTest(store);
   mgr.recover(store.loadState());
   assertFalse("token1 should be missing",
       mgr.getAllTokens().containsKey(tokenId1));
   assertTrue("token2 missing", mgr.getAllTokens().containsKey(tokenId2));
   assertEquals("token2 renew date", tokenRenewDate2,
       mgr.getAllTokens().get(tokenId2).getRenewDate());
   assertTrue("token3 missing", mgr.getAllTokens().containsKey(tokenId3));
   assertEquals("token3 renew date", tokenRenewDate3,
       mgr.getAllTokens().get(tokenId3).getRenewDate());

   mgr.startThreads();
   mgr.verifyToken(tokenId2, token2.getPassword());
   mgr.verifyToken(tokenId3, token3.getPassword());
   mgr.stopThreads();
}
 
Example 16
Source File: TestGetImageServlet.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Test
public void testIsValidRequestor() throws IOException {
  Configuration conf = new HdfsConfiguration();
  KerberosName.setRules("RULE:[1:$1]\nRULE:[2:$1]");
  
  // Set up generic HA configs.
  conf.set(DFSConfigKeys.DFS_NAMESERVICES, "ns1");
  conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_HA_NAMENODES_KEY_PREFIX,
      "ns1"), "nn1,nn2");
  
  // Set up NN1 HA configs.
  conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY,
      "ns1", "nn1"), "host1:1234");
  conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY,
      "ns1", "nn1"), "hdfs/[email protected]");
  
  // Set up NN2 HA configs.
  conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY,
      "ns1", "nn2"), "host2:1234");
  conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY,
      "ns1", "nn2"), "hdfs/[email protected]");
  
  // Initialize this conf object as though we're running on NN1.
  NameNode.initializeGenericKeys(conf, "ns1", "nn1");
  
  AccessControlList acls = Mockito.mock(AccessControlList.class);
  Mockito.when(acls.isUserAllowed(Mockito.<UserGroupInformation>any())).thenReturn(false);
  ServletContext context = Mockito.mock(ServletContext.class);
  Mockito.when(context.getAttribute(HttpServer2.ADMINS_ACL)).thenReturn(acls);
  
  // Make sure that NN2 is considered a valid fsimage/edits requestor.
  assertTrue(ImageServlet.isValidRequestor(context,
      "hdfs/[email protected]", conf));
  
  // Mark atm as an admin.
  Mockito.when(acls.isUserAllowed(Mockito.argThat(new ArgumentMatcher<UserGroupInformation>() {
    @Override
    public boolean matches(Object argument) {
      return ((UserGroupInformation) argument).getShortUserName().equals("atm");
    }
  }))).thenReturn(true);
  
  // Make sure that NN2 is still considered a valid requestor.
  assertTrue(ImageServlet.isValidRequestor(context,
      "hdfs/[email protected]", conf));
  
  // Make sure an admin is considered a valid requestor.
  assertTrue(ImageServlet.isValidRequestor(context,
      "[email protected]", conf));
  
  // Make sure other users are *not* considered valid requestors.
  assertFalse(ImageServlet.isValidRequestor(context,
      "[email protected]", conf));
}
 
Example 17
Source File: TestJHSDelegationTokenSecretManager.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Test
 public void testRecovery() throws IOException {
   Configuration conf = new Configuration();
   HistoryServerStateStoreService store =
       new HistoryServerMemStateStoreService();
   store.init(conf);
   store.start();
   JHSDelegationTokenSecretManagerForTest mgr =
       new JHSDelegationTokenSecretManagerForTest(store);
   mgr.startThreads();

   MRDelegationTokenIdentifier tokenId1 = new MRDelegationTokenIdentifier(
       new Text("tokenOwner"), new Text("tokenRenewer"),
       new Text("tokenUser"));
   Token<MRDelegationTokenIdentifier> token1 =
       new Token<MRDelegationTokenIdentifier>(tokenId1, mgr);

   MRDelegationTokenIdentifier tokenId2 = new MRDelegationTokenIdentifier(
       new Text("tokenOwner"), new Text("tokenRenewer"),
       new Text("tokenUser"));
   Token<MRDelegationTokenIdentifier> token2 =
       new Token<MRDelegationTokenIdentifier>(tokenId2, mgr);
   DelegationKey[] keys = mgr.getAllKeys();
   long tokenRenewDate1 = mgr.getAllTokens().get(tokenId1).getRenewDate();
   long tokenRenewDate2 = mgr.getAllTokens().get(tokenId2).getRenewDate();
   mgr.stopThreads();

   mgr = new JHSDelegationTokenSecretManagerForTest(store);
   mgr.recover(store.loadState());
   List<DelegationKey> recoveredKeys = Arrays.asList(mgr.getAllKeys());
   for (DelegationKey key : keys) {
     assertTrue("key missing after recovery", recoveredKeys.contains(key));
   }
   assertTrue("token1 missing", mgr.getAllTokens().containsKey(tokenId1));
   assertEquals("token1 renew date", tokenRenewDate1,
       mgr.getAllTokens().get(tokenId1).getRenewDate());
   assertTrue("token2 missing", mgr.getAllTokens().containsKey(tokenId2));
   assertEquals("token2 renew date", tokenRenewDate2,
       mgr.getAllTokens().get(tokenId2).getRenewDate());

   mgr.startThreads();
   mgr.verifyToken(tokenId1, token1.getPassword());
   mgr.verifyToken(tokenId2, token2.getPassword());
   MRDelegationTokenIdentifier tokenId3 = new MRDelegationTokenIdentifier(
       new Text("tokenOwner"), new Text("tokenRenewer"),
       new Text("tokenUser"));
   Token<MRDelegationTokenIdentifier> token3 =
       new Token<MRDelegationTokenIdentifier>(tokenId3, mgr);
   assertEquals("sequence number restore", tokenId2.getSequenceNumber() + 1,
       tokenId3.getSequenceNumber());
   mgr.cancelToken(token1, "tokenOwner");

   // Testing with full principal name
   MRDelegationTokenIdentifier tokenIdFull = new MRDelegationTokenIdentifier(
       new Text("tokenOwner/localhost@LOCALHOST"), new Text("tokenRenewer"),
       new Text("tokenUser"));
   KerberosName.setRules("RULE:[1:$1]\nRULE:[2:$1]");
   Token<MRDelegationTokenIdentifier> tokenFull = new Token<MRDelegationTokenIdentifier>(
       tokenIdFull, mgr);
   // Negative test
   try {
     mgr.cancelToken(tokenFull, "tokenOwner");
   } catch (AccessControlException ace) {
     assertTrue(ace.getMessage().contains(
         "is not authorized to cancel the token"));
   }
   // Succeed to cancel with full principal
   mgr.cancelToken(tokenFull, tokenIdFull.getOwner().toString());

   long tokenRenewDate3 = mgr.getAllTokens().get(tokenId3).getRenewDate();
   mgr.stopThreads();

   mgr = new JHSDelegationTokenSecretManagerForTest(store);
   mgr.recover(store.loadState());
   assertFalse("token1 should be missing",
       mgr.getAllTokens().containsKey(tokenId1));
   assertTrue("token2 missing", mgr.getAllTokens().containsKey(tokenId2));
   assertEquals("token2 renew date", tokenRenewDate2,
       mgr.getAllTokens().get(tokenId2).getRenewDate());
   assertTrue("token3 missing", mgr.getAllTokens().containsKey(tokenId3));
   assertEquals("token3 renew date", tokenRenewDate3,
       mgr.getAllTokens().get(tokenId3).getRenewDate());

   mgr.startThreads();
   mgr.verifyToken(tokenId2, token2.getPassword());
   mgr.verifyToken(tokenId3, token3.getPassword());
   mgr.stopThreads();
}
 
Example 18
Source File: LogsearchKRBAuthenticationFilter.java    From ambari-logsearch with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain filterChain) throws IOException, ServletException {
  HttpServletRequest httpRequest = (HttpServletRequest) request;
  if (requestMatcher.matches(httpRequest)) {
    logger.debug("LogsearchKRBAuthenticationFilter public filter path >>>>" + httpRequest.getPathInfo());
    SecurityContextImpl securityContextImpl = (SecurityContextImpl) httpRequest.getSession(true).getAttribute("SPRING_SECURITY_CONTEXT");
    Authentication existingAuth = null;
    if (securityContextImpl != null) {
      existingAuth = securityContextImpl.getAuthentication();
    }
    if (!isLoginRequest(httpRequest) && spnegoEnable
      && (existingAuth == null || !existingAuth.isAuthenticated())) {
      KerberosName.setRules(logSearchSpnegoConfig.getNameRules());
      String userName = getUsernameFromRequest(httpRequest);
      if ((existingAuth == null || !existingAuth.isAuthenticated())
        && (StringUtils.isNotEmpty(userName))) {
        // --------------------------- To Create Logsearch Session--------------------------------------
        // if we get the userName from the token then log into logsearch using the same user
        final List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority(DEFAULT_USER_ROLE));
        final UserDetails principal = new User(userName, "", grantedAuths);
        final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
          principal, "", grantedAuths);
        WebAuthenticationDetails webDetails = new WebAuthenticationDetails(
          httpRequest);
        ((AbstractAuthenticationToken) finalAuthentication)
          .setDetails(webDetails);
        Authentication authentication = this
          .authenticate(finalAuthentication);
        authentication = getGrantedAuthority(authentication);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        request.setAttribute("spnegoEnabled", true);
        logger.info("Logged into Logsearch as = " + userName);
      } else {
        try {
          super.doFilter(request, response, filterChain);
        } catch (Exception e) {
          logger.error("Error LogsearchKRBAuthenticationFilter : " + e.getMessage());
        }
      }
    } else {
      filterChain.doFilter(request, response);
    }
  } else {
    filterChain.doFilter(request, response);
  }
}
 
Example 19
Source File: AbstractSecureRegistryTest.java    From big-c with Apache License 2.0 3 votes vote down vote up
/**
 * Init hadoop security by setting up the UGI config
 */
public static void initHadoopSecurity() {

  UserGroupInformation.setConfiguration(CONF);

  KerberosName.setRules(kerberosRule);
}
 
Example 20
Source File: AbstractSecureRegistryTest.java    From hadoop with Apache License 2.0 3 votes vote down vote up
/**
 * Init hadoop security by setting up the UGI config
 */
public static void initHadoopSecurity() {

  UserGroupInformation.setConfiguration(CONF);

  KerberosName.setRules(kerberosRule);
}