org.apache.hadoop.security.authentication.util.KerberosUtil Java Examples

The following examples show how to use org.apache.hadoop.security.authentication.util.KerberosUtil. 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: KerberosConfiguration.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
  Map<String, String> options = new HashMap<String, String>();
  options.put("keyTab", keytab);
  options.put("principal", principal);
  options.put("useKeyTab", "true");
  options.put("storeKey", "true");
  options.put("doNotPrompt", "true");
  options.put("useTicketCache", "true");
  options.put("renewTGT", "true");
  options.put("refreshKrb5Config", "true");
  options.put("isInitiator", Boolean.toString(isInitiator));
  String ticketCache = System.getenv("KRB5CCNAME");
  if (ticketCache != null) {
    options.put("ticketCache", ticketCache);
  }
  options.put("debug", "true");

  return new AppConfigurationEntry[]{
      new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
          AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
          options)
  };
}
 
Example #2
Source File: KerberosConfiguration.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
  Map<String, String> options = new HashMap<String, String>();
  options.put("keyTab", keytab);
  options.put("principal", principal);
  options.put("useKeyTab", "true");
  options.put("storeKey", "true");
  options.put("doNotPrompt", "true");
  options.put("useTicketCache", "true");
  options.put("renewTGT", "true");
  options.put("refreshKrb5Config", "true");
  options.put("isInitiator", Boolean.toString(isInitiator));
  String ticketCache = System.getenv("KRB5CCNAME");
  if (ticketCache != null) {
    options.put("ticketCache", ticketCache);
  }
  options.put("debug", "true");

  return new AppConfigurationEntry[]{
      new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
          AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
          options)
  };
}
 
Example #3
Source File: KerberosTestUtils.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
  Map<String, String> options = new HashMap<String, String>();
  options.put("keyTab", KerberosTestUtils.getKeytabFile());
  options.put("principal", principal);
  options.put("useKeyTab", "true");
  options.put("storeKey", "true");
  options.put("doNotPrompt", "true");
  options.put("useTicketCache", "true");
  options.put("renewTGT", "true");
  options.put("refreshKrb5Config", "true");
  options.put("isInitiator", "true");
  String ticketCache = System.getenv("KRB5CCNAME");
  if (ticketCache != null) {
    options.put("ticketCache", ticketCache);
  }
  options.put("debug", "true");

  return new AppConfigurationEntry[]{
    new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
                              AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
                              options),};
}
 
Example #4
Source File: KerberosTestUtils.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
  Map<String, String> options = new HashMap<String, String>();
  options.put("keyTab", KerberosTestUtils.getKeytabFile());
  options.put("principal", principal);
  options.put("useKeyTab", "true");
  options.put("storeKey", "true");
  options.put("doNotPrompt", "true");
  options.put("useTicketCache", "true");
  options.put("renewTGT", "true");
  options.put("refreshKrb5Config", "true");
  options.put("isInitiator", "true");
  String ticketCache = System.getenv("KRB5CCNAME");
  if (ticketCache != null) {
    options.put("ticketCache", ticketCache);
  }
  options.put("debug", "true");

  return new AppConfigurationEntry[]{
    new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
                              AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
                              options),};
}
 
Example #5
Source File: HadoopKerberosName.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Set the static configuration to get the rules.
 * <p/>
 * IMPORTANT: This method does a NOP if the rules have been set already.
 * If there is a need to reset the rules, the {@link KerberosName#setRules(String)}
 * method should be invoked directly.
 * 
 * @param conf the new configuration
 * @throws IOException
 */
public static void setConfiguration(Configuration conf) throws IOException {
  final String defaultRule;
  switch (SecurityUtil.getAuthenticationMethod(conf)) {
    case KERBEROS:
    case KERBEROS_SSL:
      try {
        KerberosUtil.getDefaultRealm();
      } catch (Exception ke) {
        throw new IllegalArgumentException("Can't get Kerberos realm", ke);
      }
      defaultRule = "DEFAULT";
      break;
    default:
      // just extract the simple user name
      defaultRule = "RULE:[1:$1] RULE:[2:$1]";
      break; 
  }
  String ruleString = conf.get(HADOOP_SECURITY_AUTH_TO_LOCAL, defaultRule);
  setRules(ruleString);
}
 
Example #6
Source File: TestWebDelegationToken.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
  Map<String, String> options = new HashMap<String, String>();
  options.put("principal", principal);
  options.put("keyTab", keytab);
  options.put("useKeyTab", "true");
  options.put("storeKey", "true");
  options.put("doNotPrompt", "true");
  options.put("useTicketCache", "true");
  options.put("renewTGT", "true");
  options.put("refreshKrb5Config", "true");
  options.put("isInitiator", "true");
  String ticketCache = System.getenv("KRB5CCNAME");
  if (ticketCache != null) {
    options.put("ticketCache", ticketCache);
  }
  options.put("debug", "true");

  return new AppConfigurationEntry[]{
      new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
          AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
          options),};
}
 
Example #7
Source File: TestWebDelegationToken.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
  Map<String, String> options = new HashMap<String, String>();
  options.put("principal", principal);
  options.put("keyTab", keytab);
  options.put("useKeyTab", "true");
  options.put("storeKey", "true");
  options.put("doNotPrompt", "true");
  options.put("useTicketCache", "true");
  options.put("renewTGT", "true");
  options.put("refreshKrb5Config", "true");
  options.put("isInitiator", "true");
  String ticketCache = System.getenv("KRB5CCNAME");
  if (ticketCache != null) {
    options.put("ticketCache", ticketCache);
  }
  options.put("debug", "true");

  return new AppConfigurationEntry[]{
      new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
          AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
          options),};
}
 
Example #8
Source File: HadoopKerberosName.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Set the static configuration to get the rules.
 * <p/>
 * IMPORTANT: This method does a NOP if the rules have been set already.
 * If there is a need to reset the rules, the {@link KerberosName#setRules(String)}
 * method should be invoked directly.
 * 
 * @param conf the new configuration
 * @throws IOException
 */
public static void setConfiguration(Configuration conf) throws IOException {
  final String defaultRule;
  switch (SecurityUtil.getAuthenticationMethod(conf)) {
    case KERBEROS:
    case KERBEROS_SSL:
      try {
        KerberosUtil.getDefaultRealm();
      } catch (Exception ke) {
        throw new IllegalArgumentException("Can't get Kerberos realm", ke);
      }
      defaultRule = "DEFAULT";
      break;
    default:
      // just extract the simple user name
      defaultRule = "RULE:[1:$1] RULE:[2:$1]";
      break; 
  }
  String ruleString = conf.get(HADOOP_SECURITY_AUTH_TO_LOCAL, defaultRule);
  setRules(ruleString);
}
 
Example #9
Source File: KerberosTestUtils.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
  Map<String, String> options = new HashMap<String, String>();
  options.put("keyTab", KerberosTestUtils.getKeytabFile());
  options.put("principal", principal);
  options.put("useKeyTab", "true");
  options.put("storeKey", "true");
  options.put("doNotPrompt", "true");
  options.put("useTicketCache", "true");
  options.put("renewTGT", "true");
  options.put("refreshKrb5Config", "true");
  options.put("isInitiator", "true");
  String ticketCache = System.getenv("KRB5CCNAME");
  if (ticketCache != null) {
    options.put("ticketCache", ticketCache);
  }
  options.put("debug", "true");

  return new AppConfigurationEntry[]{
    new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
                              AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
                              options),};
}
 
Example #10
Source File: PxfUserGroupInformationTest.java    From pxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testReloginFromKeytabThrowsExceptionOnLoginFailure() throws Exception {
    expectedException.expect(KerberosAuthException.class);
    expectedException.expectMessage("Login failure for principal: principal from keytab keytab");

    user.setLogin(mockLoginContext);
    PowerMockito.mockStatic(KerberosUtil.class);
    when(KerberosUtil.hasKerberosKeyTab(subject)).thenReturn(true);
    when(KerberosUtil.getKrb5LoginModuleName()).thenReturn("com.sun.security.auth.module.Krb5LoginModule");  // need for login

    when(mockTGT.getServer()).thenReturn(nonTgtPrincipal); // ticket is not from krbtgt, so not valid

    ugi = new UserGroupInformation(subject);
    ugi.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS);
    // leave user.lastLogin at 0 to simulate old login
    session = new LoginSession("config", "principal", "keytab", ugi, subject, 1);

    // train to return another LoginContext when it is constructed during re-login
    mockAnotherLoginContext = PowerMockito.mock(LoginContext.class);
    PowerMockito.whenNew(LoginContext.class).withAnyArguments().thenReturn(mockAnotherLoginContext);
    doThrow(new LoginException("foo")).when(mockAnotherLoginContext).login(); // simulate login failure

    PxfUserGroupInformation.reloginFromKeytab(serverName, session);
}
 
Example #11
Source File: KerberosTestUtils.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
  Map<String, String> options = new HashMap<String, String>();
  options.put("keyTab", KerberosTestUtils.getKeytabFile());
  options.put("principal", principal);
  options.put("useKeyTab", "true");
  options.put("storeKey", "true");
  options.put("doNotPrompt", "true");
  options.put("useTicketCache", "true");
  options.put("renewTGT", "true");
  options.put("refreshKrb5Config", "true");
  options.put("isInitiator", "true");
  String ticketCache = System.getenv("KRB5CCNAME");
  if (ticketCache != null) {
    options.put("ticketCache", ticketCache);
  }
  options.put("debug", "true");

  return new AppConfigurationEntry[]{
    new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
                              AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
                              options),};
}
 
Example #12
Source File: PxfUserGroupInformationTest.java    From pxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testReloginFromKeytabFailsNoKeytab() throws KerberosAuthException {
    expectedException.expect(KerberosAuthException.class);
    expectedException.expectMessage("loginUserFromKeyTab must be done first");

    user.setLogin(mockLoginContext);
    PowerMockito.mockStatic(KerberosUtil.class);
    when(KerberosUtil.hasKerberosKeyTab(subject)).thenReturn(true);
    when(KerberosUtil.getKrb5LoginModuleName()).thenReturn("com.sun.security.auth.module.Krb5LoginModule");
    ugi = new UserGroupInformation(subject);
    ugi.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS);
    // leave user.lastLogin at 0 to simulate old login
    session = new LoginSession("config", "principal", null, ugi, subject, 1);

    PxfUserGroupInformation.reloginFromKeytab(serverName, session);
}
 
Example #13
Source File: PxfUserGroupInformationTest.java    From pxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testReloginFromKeytabFailsNoLogin() throws KerberosAuthException {
    expectedException.expect(KerberosAuthException.class);
    expectedException.expectMessage("loginUserFromKeyTab must be done first");

    user.setLogin(null); // simulate missing login context for the user
    PowerMockito.mockStatic(KerberosUtil.class);
    when(KerberosUtil.hasKerberosKeyTab(subject)).thenReturn(true);
    when(KerberosUtil.getKrb5LoginModuleName()).thenReturn("com.sun.security.auth.module.Krb5LoginModule");
    ugi = new UserGroupInformation(subject);
    ugi.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS);
    // leave user.lastLogin at 0 to simulate old login
    session = new LoginSession("config", "principal", "keytab", ugi, subject, 1);

    PxfUserGroupInformation.reloginFromKeytab(serverName, session);
}
 
Example #14
Source File: KDCFixture.java    From elasticsearch-hadoop with Apache License 2.0 6 votes vote down vote up
@Override
protected void before() throws Throwable {
    Properties conf = MiniKdc.createConf();
    conf.setProperty(MiniKdc.ORG_NAME, "BUILD.ELASTIC");
    conf.setProperty(MiniKdc.ORG_DOMAIN, "CO");
    kdc = new MiniKdc(conf, temporaryFolder.newFolder());
    kdc.start();

    /*
     * So, this test suite is run alongside other suites that are initializing static state
     * all throughout the Hadoop code with the assumption that Kerberos doesn't exist, and
     * no one in this JVM will ever care about it existing. KerberosName has a static field
     * set once and left as-is at class loading time. That field contains the default realm
     * as specified by the JVM's krb5 conf file. MiniKdc adds a test conf file to the JVM
     * properties after it starts up. We need to smash the glass and update the defaultRealm
     * field on the KerberosName class or else Hadoop will not be able to map a Kerberos
     * Principal Name to a regular user name with the DEFAULT rule.
     */
    Field defaultRealm = KerberosName.class.getDeclaredField("defaultRealm");
    defaultRealm.setAccessible(true);
    previousDefaultRealm = (String) defaultRealm.get(null);
    defaultRealm.set(null, KerberosUtil.getDefaultRealm());
}
 
Example #15
Source File: KerberosAuthenticationHandler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
  Map<String, String> options = new HashMap<String, String>();
  if (IBM_JAVA) {
    options.put("useKeytab",
        keytab.startsWith("file://") ? keytab : "file://" + keytab);
    options.put("principal", principal);
    options.put("credsType", "acceptor");
  } else {
    options.put("keyTab", keytab);
    options.put("principal", principal);
    options.put("useKeyTab", "true");
    options.put("storeKey", "true");
    options.put("doNotPrompt", "true");
    options.put("useTicketCache", "true");
    options.put("renewTGT", "true");
    options.put("isInitiator", "false");
  }
  options.put("refreshKrb5Config", "true");
  String ticketCache = System.getenv("KRB5CCNAME");
  if (ticketCache != null) {
    if (IBM_JAVA) {
      options.put("useDefaultCcache", "true");
      // The first value searched when "useDefaultCcache" is used.
      System.setProperty("KRB5CCNAME", ticketCache);
      options.put("renewTGT", "true");
      options.put("credsType", "both");
    } else {
      options.put("ticketCache", ticketCache);
    }
  }
  if (LOG.isDebugEnabled()) {
    options.put("debug", "true");
  }

  return new AppConfigurationEntry[]{
      new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
                              AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
                              options),};
}
 
Example #16
Source File: KerberosAuthenticationHandler.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
  Map<String, String> options = new HashMap<String, String>();
  if (IBM_JAVA) {
    options.put("useKeytab",
        keytab.startsWith("file://") ? keytab : "file://" + keytab);
    options.put("principal", principal);
    options.put("credsType", "acceptor");
  } else {
    options.put("keyTab", keytab);
    options.put("principal", principal);
    options.put("useKeyTab", "true");
    options.put("storeKey", "true");
    options.put("doNotPrompt", "true");
    options.put("useTicketCache", "true");
    options.put("renewTGT", "true");
    options.put("isInitiator", "false");
  }
  options.put("refreshKrb5Config", "true");
  String ticketCache = System.getenv("KRB5CCNAME");
  if (ticketCache != null) {
    if (IBM_JAVA) {
      options.put("useDefaultCcache", "true");
      // The first value searched when "useDefaultCcache" is used.
      System.setProperty("KRB5CCNAME", ticketCache);
      options.put("renewTGT", "true");
      options.put("credsType", "both");
    } else {
      options.put("ticketCache", ticketCache);
    }
  }
  if (LOG.isDebugEnabled()) {
    options.put("debug", "true");
  }

  return new AppConfigurationEntry[]{
      new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
                              AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
                              options),};
}
 
Example #17
Source File: SecureClientLogin.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
	AppConfigurationEntry KEYTAB_KERBEROS_LOGIN = new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(), LoginModuleControlFlag.REQUIRED, kerberosOptions);
	if (usePassword) {
		AppConfigurationEntry KERBEROS_PWD_SAVER = new AppConfigurationEntry(KrbPasswordSaverLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, kerberosOptions);
		return new AppConfigurationEntry[] { KERBEROS_PWD_SAVER, KEYTAB_KERBEROS_LOGIN };
	}
	else {
		return new AppConfigurationEntry[] { KEYTAB_KERBEROS_LOGIN };
	}
}
 
Example #18
Source File: MiscUtil.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
	Map<String, String> options = new HashMap<String, String>();
	if (IBM_JAVA) {
		options.put("useKeytab", keytab.startsWith("file://") ? keytab
				: "file://" + keytab);
		options.put("principal", principal);
		options.put("credsType", "acceptor");
	} else {
		options.put("keyTab", keytab);
		options.put("principal", principal);
		options.put("useKeyTab", "true");
		options.put("storeKey", "true");
		options.put("doNotPrompt", "true");
		options.put("useTicketCache", "true");
		options.put("renewTGT", "true");
		options.put("isInitiator", "false");
	}
	options.put("refreshKrb5Config", "true");
	String ticketCache = System.getenv("KRB5CCNAME");
	if (ticketCache != null) {
		if (IBM_JAVA) {
			options.put("useDefaultCcache", "true");
			// The first value searched when "useDefaultCcache" is used.
			System.setProperty("KRB5CCNAME", ticketCache);
			options.put("renewTGT", "true");
			options.put("credsType", "both");
		} else {
			options.put("ticketCache", ticketCache);
		}
	}
	if (logger.isDebugEnabled()) {
		options.put("debug", "true");
	}

	return new AppConfigurationEntry[] { new AppConfigurationEntry(
			KerberosUtil.getKrb5LoginModuleName(),
			AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
			options), };
}
 
Example #19
Source File: PhoenixEmbeddedDriver.java    From phoenix with Apache License 2.0 5 votes vote down vote up
/**
 * Computes the default kerberos realm if one is available. If one cannot be computed, null
 * is returned.
 *
 * @return The default kerberos realm, or null.
 */
static String getDefaultKerberosRealm() {
    try {
        return KerberosUtil.getDefaultRealm();
    } catch (Exception e) {
        if (LOGGER.isDebugEnabled()) {
            // Include the stacktrace at DEBUG
            LOGGER.debug(REALM_EQUIVALENCY_WARNING_MSG, e);
        } else {
            // Limit the content at WARN
            LOGGER.warn(REALM_EQUIVALENCY_WARNING_MSG);
        }
    }
    return null;
}
 
Example #20
Source File: KerberosKeytabSPNegoScheme.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] generateToken(byte[] input, String authServer, Credentials credentials) {
    Set<Principal> principals = new HashSet<>();
    principals.add(credentials.getUserPrincipal());
    Subject subject = new Subject(false, principals, new HashSet<>(), new HashSet<>());

    try {
        LoginContext loginContext = new LoginContext("", subject, null,
            new KerberosConfiguration(credentials.getUserPrincipal().getName(),
                ((KerberosKeytabCredentials) credentials).getKeytab()));
        loginContext.login();
        Subject loggedInSubject = loginContext.getSubject();

        return Subject.doAs(loggedInSubject, new PrivilegedExceptionAction<byte[]>() {

            public byte[] run() throws UnknownHostException, ClassNotFoundException, GSSException,
                IllegalAccessException, NoSuchFieldException {
                GSSManager gssManager = GSSManager.getInstance();
                String servicePrincipal = KerberosUtil.getServicePrincipal("HTTP", authServer);
                Oid serviceOid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                GSSName serviceName = gssManager.createName(servicePrincipal, serviceOid);
                Oid mechOid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                GSSContext gssContext = gssManager.createContext(serviceName, mechOid, null, 0);
                gssContext.requestCredDeleg(true);
                gssContext.requestMutualAuth(true);
                return gssContext.initSecContext(input, 0, input.length);
            }

        });
    } catch (PrivilegedActionException | LoginException e) {
        throw new RuntimeException(e);
    }
}
 
Example #21
Source File: TestSecureLogins.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultRealmValid() throws Throwable {
  String defaultRealm = KerberosUtil.getDefaultRealm();
  assertNotEmpty("No default Kerberos Realm",
      defaultRealm);
  LOG.info("Default Realm '{}'", defaultRealm);
}
 
Example #22
Source File: TestSecureLogins.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultRealmValid() throws Throwable {
  String defaultRealm = KerberosUtil.getDefaultRealm();
  assertNotEmpty("No default Kerberos Realm",
      defaultRealm);
  LOG.info("Default Realm '{}'", defaultRealm);
}
 
Example #23
Source File: PxfUserGroupInformationTest.java    From pxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReloginFromKeytabValidTGTWillExpireSoon() throws Exception {
    user.setLogin(mockLoginContext);
    PowerMockito.mockStatic(KerberosUtil.class);
    when(KerberosUtil.hasKerberosKeyTab(subject)).thenReturn(true);
    when(KerberosUtil.getKrb5LoginModuleName()).thenReturn("com.sun.security.auth.module.Krb5LoginModule");  // need for login

    when(mockTGT.getServer()).thenReturn(tgtPrincipal);

    // TGT validity started 1 hr ago, valid for another 10 mins, we are at 6/7 or 85% > 80% of renew window
    when(mockTGT.getStartTime()).thenReturn(new Date(nowMs - 3600 * 1000L));
    when(mockTGT.getEndTime()).thenReturn(new Date(nowMs + 600 * 1000L));

    ugi = new UserGroupInformation(subject);
    ugi.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS);
    // leave user.lastLogin at 0 to simulate old login
    session = new LoginSession("config", "principal", "keytab", ugi, subject, 1);

    // train to return another LoginContext when it is constructed during re-login
    mockAnotherLoginContext = PowerMockito.mock(LoginContext.class);
    PowerMockito.whenNew(LoginContext.class).withAnyArguments().thenReturn(mockAnotherLoginContext);

    PxfUserGroupInformation.reloginFromKeytab(serverName, session);

    assertNotSame(mockLoginContext, user.getLogin());
    assertSame(mockAnotherLoginContext, user.getLogin());
    assertTrue(user.getLastLogin() > 0); // login timestamp is updated

    verify(mockLoginContext).logout();
    verify(mockAnotherLoginContext).login();
}
 
Example #24
Source File: PxfUserGroupInformationTest.java    From pxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReloginFromKeytabNoValidTGT() throws Exception {

    assertEquals(1, subject.getPrivateCredentials().size()); // subject has 1 ticket

    user.setLogin(mockLoginContext);
    PowerMockito.mockStatic(KerberosUtil.class);
    when(KerberosUtil.hasKerberosKeyTab(subject)).thenReturn(true);
    when(KerberosUtil.getKrb5LoginModuleName()).thenReturn("com.sun.security.auth.module.Krb5LoginModule");  // need for login

    when(mockTGT.getServer()).thenReturn(nonTgtPrincipal); // ticket is not from krbtgt, so not valid

    ugi = new UserGroupInformation(subject);
    ugi.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS);
    // leave user.lastLogin at 0 to simulate old login
    session = new LoginSession("config", "principal", "keytab", ugi, subject, 1);

    // train to return another LoginContext when it is constructed during re-login
    mockAnotherLoginContext = PowerMockito.mock(LoginContext.class);
    PowerMockito.whenNew(LoginContext.class).withAnyArguments().thenReturn(mockAnotherLoginContext);

    PxfUserGroupInformation.reloginFromKeytab(serverName, session);

    assertNotSame(mockLoginContext, user.getLogin());
    assertSame(mockAnotherLoginContext, user.getLogin());
    assertTrue(user.getLastLogin() > 0); // login timestamp is updated

    /* subject's non-TGT ticket has been removed, in reality another one would be created by login process,
     * but we are not mocking it here.
     */
    assertTrue(subject.getPrivateCredentials().isEmpty());

    verify(mockLoginContext).logout();
    verify(mockAnotherLoginContext).login();
    verify(mockTGT).destroy(); // subject's non-TGT ticket has been destroyed
}
 
Example #25
Source File: PxfUserGroupInformationTest.java    From pxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReloginFromKeytabNoopTGTValidForLongTime() throws KerberosAuthException {
    user.setLogin(mockLoginContext);
    PowerMockito.mockStatic(KerberosUtil.class);
    when(KerberosUtil.hasKerberosKeyTab(subject)).thenReturn(true);
    when(KerberosUtil.getKrb5LoginModuleName()).thenReturn("com.sun.security.auth.module.Krb5LoginModule");

    when(mockTGT.getServer()).thenReturn(tgtPrincipal);

    // TGT validity started 1 hr ago, valid for another 1 hr from now, we are at 50% of renew window
    when(mockTGT.getStartTime()).thenReturn(new Date(nowMs - 3600 * 1000L));
    when(mockTGT.getEndTime()).thenReturn(new Date(nowMs + 3600 * 1000L));

    ugi = new UserGroupInformation(subject);
    ugi.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS);
    // leave user.lastLogin at 0 to simulate old login
    session = new LoginSession("config", "principal", "keytab", ugi, subject, 1);

    PxfUserGroupInformation.reloginFromKeytab(serverName, session);

    verifyZeroInteractions(mockLoginContext);
}
 
Example #26
Source File: PxfUserGroupInformationTest.java    From pxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReloginFromKeytabNoopInsufficientTimeElapsed() throws KerberosAuthException {
    user.setLogin(mockLoginContext);
    PowerMockito.mockStatic(KerberosUtil.class);
    when(KerberosUtil.hasKerberosKeyTab(subject)).thenReturn(true);
    ugi = new UserGroupInformation(subject);
    ugi.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS);
    user.setLastLogin(nowMs); // simulate just logged in
    // set 33 secs between re-login attempts
    session = new LoginSession("config", "principal", "keytab", ugi, subject, 55000L);

    PxfUserGroupInformation.reloginFromKeytab(serverName, session);

    verifyZeroInteractions(mockLoginContext); // proves noop
}
 
Example #27
Source File: PxfUserGroupInformationTest.java    From pxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReloginFromKeytabNoopForNonKeytab() throws KerberosAuthException {
    user.setLogin(mockLoginContext);
    PowerMockito.mockStatic(KerberosUtil.class);
    when(KerberosUtil.hasKerberosKeyTab(subject)).thenReturn(false); // simulate no keytab for subject
    ugi = new UserGroupInformation(subject);
    ugi.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS);
    session = new LoginSession("config", "principal", "keytab", ugi, subject, 1);

    PxfUserGroupInformation.reloginFromKeytab(serverName, session);

    verifyZeroInteractions(mockLoginContext); // proves noop
}
 
Example #28
Source File: PxfUserGroupInformationTest.java    From pxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReloginFromKeytabNoopForNonKerberos() throws KerberosAuthException {
    user.setLogin(mockLoginContext);
    PowerMockito.mockStatic(KerberosUtil.class);
    when(KerberosUtil.hasKerberosKeyTab(subject)).thenReturn(true);
    ugi = new UserGroupInformation(subject);
    // do NOT set authentication method of UGI to KERBEROS, will cause NOOP for relogin
    session = new LoginSession("config", "principal", "keytab", ugi, subject, 1);

    PxfUserGroupInformation.reloginFromKeytab(serverName, session);

    verifyZeroInteractions(mockLoginContext); // proves noop
}
 
Example #29
Source File: TestKerberosAuthenticationHandler.java    From hadoop with Apache License 2.0 4 votes vote down vote up
public void testRequestWithAuthorization() throws Exception {
  String token = KerberosTestUtils.doAsClient(new Callable<String>() {
    @Override
    public String call() throws Exception {
      GSSManager gssManager = GSSManager.getInstance();
      GSSContext gssContext = null;
      try {
        String servicePrincipal = KerberosTestUtils.getServerPrincipal();
        Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
        GSSName serviceName = gssManager.createName(servicePrincipal,
            oid);
        oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
        gssContext = gssManager.createContext(serviceName, oid, null,
                                                GSSContext.DEFAULT_LIFETIME);
        gssContext.requestCredDeleg(true);
        gssContext.requestMutualAuth(true);

        byte[] inToken = new byte[0];
        byte[] outToken = gssContext.initSecContext(inToken, 0, inToken.length);
        Base64 base64 = new Base64(0);
        return base64.encodeToString(outToken);

      } finally {
        if (gssContext != null) {
          gssContext.dispose();
        }
      }
    }
  });

  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

  Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION))
    .thenReturn(KerberosAuthenticator.NEGOTIATE + " " + token);
  Mockito.when(request.getServerName()).thenReturn("localhost");
  
  AuthenticationToken authToken = handler.authenticate(request, response);

  if (authToken != null) {
    Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                                       Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
    Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);

    Assert.assertEquals(KerberosTestUtils.getClientPrincipal(), authToken.getName());
    Assert.assertTrue(KerberosTestUtils.getClientPrincipal().startsWith(authToken.getUserName()));
    Assert.assertEquals(getExpectedType(), authToken.getType());
  } else {
    Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                                       Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
    Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  }
}
 
Example #30
Source File: PxfUserGroupInformation.java    From pxf with Apache License 2.0 4 votes vote down vote up
private HadoopConfiguration(String keytabPrincipal, String keytabFile) {
    this.keytabFile = keytabFile;
    this.keytabPrincipal = keytabPrincipal;

    String ticketCache = System.getenv("HADOOP_JAAS_DEBUG");
    if ("true".equalsIgnoreCase(ticketCache)) {
        BASIC_JAAS_OPTIONS.put("debug", "true");
    }

    OS_SPECIFIC_LOGIN = new AppConfigurationEntry(OS_LOGIN_MODULE_NAME, AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, BASIC_JAAS_OPTIONS);
    HADOOP_LOGIN = new AppConfigurationEntry(UserGroupInformation.HadoopLoginModule.class.getName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, BASIC_JAAS_OPTIONS);
    USER_KERBEROS_OPTIONS = new HashMap<>();
    if (PlatformName.IBM_JAVA) {
        USER_KERBEROS_OPTIONS.put("useDefaultCcache", "true");
    } else {
        USER_KERBEROS_OPTIONS.put("doNotPrompt", "true");
        USER_KERBEROS_OPTIONS.put("useTicketCache", "true");
    }

    ticketCache = System.getenv("KRB5CCNAME");
    if (ticketCache != null) {
        if (PlatformName.IBM_JAVA) {
            System.setProperty("KRB5CCNAME", ticketCache);
        } else {
            USER_KERBEROS_OPTIONS.put("ticketCache", ticketCache);
        }
    }

    USER_KERBEROS_OPTIONS.put("renewTGT", "true");
    USER_KERBEROS_OPTIONS.putAll(BASIC_JAAS_OPTIONS);
    USER_KERBEROS_LOGIN = new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(), AppConfigurationEntry.LoginModuleControlFlag.OPTIONAL, USER_KERBEROS_OPTIONS);
    KEYTAB_KERBEROS_OPTIONS = new HashMap<>();
    if (PlatformName.IBM_JAVA) {
        KEYTAB_KERBEROS_OPTIONS.put("credsType", "both");
    } else {
        KEYTAB_KERBEROS_OPTIONS.put("doNotPrompt", "true");
        KEYTAB_KERBEROS_OPTIONS.put("useKeyTab", "true");
        KEYTAB_KERBEROS_OPTIONS.put("storeKey", "true");
    }

    KEYTAB_KERBEROS_OPTIONS.put("refreshKrb5Config", "true");
    KEYTAB_KERBEROS_OPTIONS.putAll(BASIC_JAAS_OPTIONS);
    KEYTAB_KERBEROS_LOGIN = new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, KEYTAB_KERBEROS_OPTIONS);
    SIMPLE_CONF = new AppConfigurationEntry[]{OS_SPECIFIC_LOGIN, HADOOP_LOGIN};
    USER_KERBEROS_CONF = new AppConfigurationEntry[]{OS_SPECIFIC_LOGIN, USER_KERBEROS_LOGIN, HADOOP_LOGIN};
    KEYTAB_KERBEROS_CONF = new AppConfigurationEntry[]{KEYTAB_KERBEROS_LOGIN, HADOOP_LOGIN};
}