Java Code Examples for org.ietf.jgss.GSSContext#isEstablished()

The following examples show how to use org.ietf.jgss.GSSContext#isEstablished() . 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: LockOutRealm.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Principal authenticate(GSSContext gssContext, boolean storeCreds) {
    if (gssContext.isEstablished()) {
        String username = null;
        GSSName name = null;
        try {
            name = gssContext.getSrcName();
        } catch (GSSException e) {
            log.warn(sm.getString("realmBase.gssNameFail"), e);
            return null;
        }

        username = name.toString();

        Principal authenticatedUser = super.authenticate(gssContext, storeCreds);

        return filterLockedAccounts(username, authenticatedUser);
    }

    // Fail in all other cases
    return null;
}
 
Example 2
Source File: HTTPSpnegoAuthenticator.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
private static String getUsernameFromGSSContext(final GSSContext gssContext, final boolean strip, final Logger logger) {
    if (gssContext.isEstablished()) {
        GSSName gssName = null;
        try {
            gssName = gssContext.getSrcName();
        } catch (final GSSException e) {
            logger.error("Unable to get src name from gss context", e);
        }

        if (gssName != null) {
            String name = gssName.toString();
            return stripRealmName(name, strip);
        } else {
            logger.error("GSS name is null");
        }
    } else {
        logger.error("GSS context not established");
    }

    return null;
}
 
Example 3
Source File: LockOutRealm.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Principal authenticate(GSSContext gssContext, boolean storeCreds) {
    if (gssContext.isEstablished()) {
        String username = null;
        GSSName name = null;
        try {
            name = gssContext.getSrcName();
        } catch (GSSException e) {
            log.warn(sm.getString("realmBase.gssNameFail"), e);
            return null;
        }
        
        username = name.toString();
        
        Principal authenticatedUser = super.authenticate(gssContext, storeCreds);
            
        return filterLockedAccounts(username, authenticatedUser);
    }
    
    // Fail in all other cases
    return null;
}
 
Example 4
Source File: KerberosRealm.java    From elasticsearch-shield-kerberos-realm with Apache License 2.0 6 votes vote down vote up
private static String getUsernameFromGSSContext(final GSSContext gssContext, final boolean strip, final ESLogger logger) {
    if (gssContext.isEstablished()) {
        GSSName gssName = null;
        try {
            gssName = gssContext.getSrcName();
        } catch (final GSSException e) {
            logger.error("Unable to get src name from gss context", e);
        }

        if (gssName != null) {
            String name = gssName.toString();

            return stripRealmName(name, strip);

        }
    }

    return null;
}
 
Example 5
Source File: LockOutRealm.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Principal authenticate(GSSContext gssContext, boolean storeCreds) {
    if (gssContext.isEstablished()) {
        String username = null;
        GSSName name = null;
        try {
            name = gssContext.getSrcName();
        } catch (GSSException e) {
            log.warn(sm.getString("realmBase.gssNameFail"), e);
            return null;
        }
        
        username = name.toString();
        
        if (isLocked(username)) {
            // Trying to authenticate a locked user is an automatic failure
            registerAuthFailure(username);
            
            log.warn(sm.getString("lockOutRealm.authLockedUser", username));
            return null;
        }

        Principal authenticatedUser =
                super.authenticate(gssContext, storeCreds);
        
        if (authenticatedUser == null) {
            registerAuthFailure(username);
        } else {
            registerAuthSuccess(username);
        }
        return authenticatedUser;
    }
    
    // Fail in all other cases
    return null;
}
 
Example 6
Source File: SPNEGOAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean run() throws Exception {
    GSSContext gssContext = null;
    try {
        if (log.isTraceEnabled()) {
            log.trace("Going to establish security context");
        }

        gssContext = establishContext();
        logAuthDetails(gssContext);

        if (gssContext.isEstablished()) {
            if (gssContext.getSrcName() == null) {
                log.warn("GSS Context accepted, but no context initiator recognized. Check your kerberos configuration and reverse DNS lookup configuration");
                return false;
            }

            authenticatedKerberosPrincipal = gssContext.getSrcName().toString();

            if (gssContext.getCredDelegState()) {
                delegationCredential = gssContext.getDelegCred();
            }

            return true;
        } else {
            return false;
        }
    } finally {
        if (gssContext != null) {
            gssContext.dispose();
        }
    }
}
 
Example 7
Source File: CombinedRealm.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Principal authenticate(GSSContext gssContext, boolean storeCred) {
    if (gssContext.isEstablished()) {
        Principal authenticatedUser = null;
        String username = null;

        GSSName name = null;
        try {
            name = gssContext.getSrcName();
        } catch (GSSException e) {
            log.warn(sm.getString("realmBase.gssNameFail"), e);
            return null;
        }

        username = name.toString();

        for (Realm realm : realms) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authStart",
                        username, realm.getClass().getName()));
            }

            authenticatedUser = realm.authenticate(gssContext, storeCred);

            if (authenticatedUser == null) {
                if (log.isDebugEnabled()) {
                    log.debug(sm.getString("combinedRealm.authFail",
                            username, realm.getClass().getName()));
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(sm.getString("combinedRealm.authSuccess",
                            username, realm.getClass().getName()));
                }
                break;
            }
        }
        return authenticatedUser;
    }

    // Fail in all other cases
    return null;
}
 
Example 8
Source File: DrillSpnegoLoginService.java    From Bats with Apache License 2.0 4 votes vote down vote up
private UserIdentity spnegoLogin(Object credentials) {

    String encodedAuthToken = (String) credentials;
    byte[] authToken = B64Code.decode(encodedAuthToken);
    GSSManager manager = GSSManager.getInstance();

    try {
      // Providing both OID's is required here. If we provide only one,
      // we're requiring that clients provide us the SPNEGO OID to authenticate via Kerberos.
      Oid[] knownOids = new Oid[2];
      knownOids[0] = new Oid("1.3.6.1.5.5.2"); // spnego
      knownOids[1] = new Oid("1.2.840.113554.1.2.2"); // kerberos

      GSSName gssName = manager.createName(spnegoConfig.getSpnegoPrincipal(), null);
      GSSCredential serverCreds = manager.createCredential(gssName, GSSCredential.INDEFINITE_LIFETIME,
          knownOids, GSSCredential.ACCEPT_ONLY);
      GSSContext gContext = manager.createContext(serverCreds);

      if (gContext == null) {
        logger.debug("SPNEGOUserRealm: failed to establish GSSContext");
      } else {
        while (!gContext.isEstablished()) {
          authToken = gContext.acceptSecContext(authToken, 0, authToken.length);
        }

        if (gContext.isEstablished()) {
          final String clientName = gContext.getSrcName().toString();
          final String realm = clientName.substring(clientName.indexOf(64) + 1);

          // Get the client user short name
          final String userShortName = new HadoopKerberosName(clientName).getShortName();

          logger.debug("Client Name: {}, realm: {} and shortName: {}", clientName, realm, userShortName);
          final SystemOptionManager sysOptions = drillContext.getOptionManager();
          final boolean isAdmin = ImpersonationUtil.hasAdminPrivileges(userShortName,
              ExecConstants.ADMIN_USERS_VALIDATOR.getAdminUsers(sysOptions),
              ExecConstants.ADMIN_USER_GROUPS_VALIDATOR.getAdminUserGroups(sysOptions));

          final Principal user = new DrillUserPrincipal(userShortName, isAdmin);
          final Subject subject = new Subject();
          subject.getPrincipals().add(user);

          if (isAdmin) {
            return this._identityService.newUserIdentity(subject, user, DrillUserPrincipal.ADMIN_USER_ROLES);
          } else {
            return this._identityService.newUserIdentity(subject, user, DrillUserPrincipal.NON_ADMIN_USER_ROLES);
          }
        }
      }
    } catch (GSSException gsse) {
      logger.warn("Caught GSSException trying to authenticate the client", gsse);
    } catch (IOException ex) {
      logger.warn("Caught IOException trying to get shortName of client user", ex);
    }
    return null;
  }
 
Example 9
Source File: Socks5LogicHandler.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Encodes the authentication packet for supported authentication methods.
 * 
 * @param request the socks proxy request data
 * @return the encoded buffer
 * @throws GSSException when something fails while using GSSAPI
 */
private IoBuffer encodeGSSAPIAuthenticationPacket(final SocksProxyRequest request) throws GSSException {
    GSSContext ctx = (GSSContext) getSession().getAttribute(GSS_CONTEXT);
    if (ctx == null) {
        // first step in the authentication process
        GSSManager manager = GSSManager.getInstance();
        GSSName serverName = manager.createName(request.getServiceKerberosName(), null);
        Oid krb5OID = new Oid(SocksProxyConstants.KERBEROS_V5_OID);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Available mechs:");
            for (Oid o : manager.getMechs()) {
                if (o.equals(krb5OID)) {
                    LOGGER.debug("Found Kerberos V OID available");
                }
                LOGGER.debug("{} with oid = {}", manager.getNamesForMech(o), o);
            }
        }

        ctx = manager.createContext(serverName, krb5OID, null, GSSContext.DEFAULT_LIFETIME);

        ctx.requestMutualAuth(true); // Mutual authentication
        ctx.requestConf(false);
        ctx.requestInteg(false);

        getSession().setAttribute(GSS_CONTEXT, ctx);
    }

    byte[] token = (byte[]) getSession().getAttribute(GSS_TOKEN);
    if (token != null) {
        LOGGER.debug("  Received Token[{}] = {}", token.length, ByteUtilities.asHex(token));
    }
    IoBuffer buf = null;

    if (!ctx.isEstablished()) {
        // token is ignored on the first call
        if (token == null) {
            token = new byte[32];
        }

        token = ctx.initSecContext(token, 0, token.length);

        // Send a token to the server if one was generated by
        // initSecContext
        if (token != null) {
            LOGGER.debug("  Sending Token[{}] = {}", token.length, ByteUtilities.asHex(token));

            getSession().setAttribute(GSS_TOKEN, token);
            buf = IoBuffer.allocate(4 + token.length);
            buf.put(new byte[] { SocksProxyConstants.GSSAPI_AUTH_SUBNEGOTIATION_VERSION,
                    SocksProxyConstants.GSSAPI_MSG_TYPE });

            buf.put(ByteUtilities.intToNetworkByteOrder(token.length, 2));
            buf.put(token);
        }
    }

    return buf;
}
 
Example 10
Source File: CombinedRealm.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Principal authenticate(GSSContext gssContext, boolean storeCreds) {
    if (gssContext.isEstablished()) {
        Principal authenticatedUser = null;
        String username = null;
        
        GSSName name = null;
        try {
            name = gssContext.getSrcName();
        } catch (GSSException e) {
            log.warn(sm.getString("realmBase.gssNameFail"), e);
            return null;
        }
        
        username = name.toString();

        for (Realm realm : realms) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authStart",
                        username, realm.getInfo()));
            }

            authenticatedUser = realm.authenticate(gssContext, storeCreds);

            if (authenticatedUser == null) {
                if (log.isDebugEnabled()) {
                    log.debug(sm.getString("combinedRealm.authFail",
                            username, realm.getInfo()));
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(sm.getString("combinedRealm.authSuccess",
                            username, realm.getInfo()));
                }
                break;
            }
        }
        return authenticatedUser;
    }
    
    // Fail in all other cases
    return null;
}
 
Example 11
Source File: PropertyBasedSpnegoLoginService.java    From calcite-avatica with Apache License 2.0 4 votes vote down vote up
@Override public UserIdentity login(String username, Object credentials,
    ServletRequest request) {
  String encodedAuthToken = (String) credentials;
  byte[] authToken = B64Code.decode(encodedAuthToken);

  GSSManager manager = GSSManager.getInstance();
  try {
    // http://java.sun.com/javase/6/docs/technotes/guides/security/jgss/jgss-features.html
    Oid spnegoOid = new Oid("1.3.6.1.5.5.2");
    Oid krb5Oid = new Oid("1.2.840.113554.1.2.2");
    GSSName gssName = manager.createName(serverPrincipal, null);
    // CALCITE-1922 Providing both OIDs is the bug in Jetty we're working around. By specifying
    // only one, we're requiring that clients *must* provide us the SPNEGO OID to authenticate
    // via Kerberos which is wrong. Best as I can tell, the SPNEGO OID is meant as another
    // layer of indirection (essentially is equivalent to setting the Kerberos OID).
    GSSCredential serverCreds = manager.createCredential(gssName,
        GSSCredential.INDEFINITE_LIFETIME, new Oid[] {krb5Oid, spnegoOid},
        GSSCredential.ACCEPT_ONLY);
    GSSContext gContext = manager.createContext(serverCreds);

    if (gContext == null) {
      LOG.debug("SpnegoUserRealm: failed to establish GSSContext");
    } else {
      while (!gContext.isEstablished()) {
        authToken = gContext.acceptSecContext(authToken, 0, authToken.length);
      }
      if (gContext.isEstablished()) {
        String clientName = gContext.getSrcName().toString();
        String role = clientName.substring(clientName.indexOf('@') + 1);

        LOG.debug("SpnegoUserRealm: established a security context");
        LOG.debug("Client Principal is: {}", gContext.getSrcName());
        LOG.debug("Server Principal is: {}", gContext.getTargName());
        LOG.debug("Client Default Role: {}", role);

        SpnegoUserPrincipal user = new SpnegoUserPrincipal(clientName, authToken);

        Subject subject = new Subject();
        subject.getPrincipals().add(user);

        return _identityService.newUserIdentity(subject, user, new String[]{role});
      }
    }
  } catch (GSSException gsse) {
    LOG.warn("Caught GSSException trying to authenticate the client", gsse);
  }

  return null;
}
 
Example 12
Source File: CombinedRealm.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Principal authenticate(GSSContext gssContext, boolean storeCreds) {
    if (gssContext.isEstablished()) {
        Principal authenticatedUser = null;
        String username = null;
        
        GSSName name = null;
        try {
            name = gssContext.getSrcName();
        } catch (GSSException e) {
            log.warn(sm.getString("realmBase.gssNameFail"), e);
            return null;
        }
        
        username = name.toString();

        for (Realm realm : realms) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authStart",
                        username, realm.getInfo()));
            }

            authenticatedUser = realm.authenticate(gssContext, storeCreds);

            if (authenticatedUser == null) {
                if (log.isDebugEnabled()) {
                    log.debug(sm.getString("combinedRealm.authFail",
                            username, realm.getInfo()));
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(sm.getString("combinedRealm.authSuccess",
                            username, realm.getInfo()));
                }
                break;
            }
        }
        return authenticatedUser;
    }
    
    // Fail in all other cases
    return null;
}
 
Example 13
Source File: AbstractSpnegoNegotiatorTest.java    From elasticsearch-hadoop with Apache License 2.0 4 votes vote down vote up
@Test
public void testSuccessfulNegotiate() throws IOException, GSSException, InterruptedException {
    // Mechanisms
    final GSSManager gssManager = GSSManager.getInstance();
    final Oid spnegoOid = new Oid("1.3.6.1.5.5.2");

    // Configure logins
    Configuration configuration = new Configuration();
    SecurityUtil.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS, configuration);
    UserGroupInformation.setConfiguration(configuration);

    // Login as Server
    UserGroupInformation server = UserGroupInformation.loginUserFromKeytabAndReturnUGI(KerberosSuite.PRINCIPAL_SERVER, KEYTAB_FILE.getAbsolutePath());
    final GSSName gssServicePrincipalName = gssManager.createName(KerberosSuite.PRINCIPAL_SERVER, GSSName.NT_USER_NAME);
    final GSSCredential gssServiceCredential = server.doAs(new PrivilegedExceptionAction<GSSCredential>() {
        @Override
        public GSSCredential run() throws Exception {
            return gssManager.createCredential(
                    gssServicePrincipalName,
                    GSSCredential.DEFAULT_LIFETIME,
                    spnegoOid,
                    GSSCredential.ACCEPT_ONLY
            );
        }
    });
    final GSSContext serverCtx = gssManager.createContext(gssServiceCredential);

    // Login as Client and Create negotiator
    UserGroupInformation client = UserGroupInformation.loginUserFromKeytabAndReturnUGI(KerberosSuite.PRINCIPAL_CLIENT, KEYTAB_FILE.getAbsolutePath());
    final SpnegoNegotiator spnegoNegotiator = client.doAs(new PrivilegedExceptionAction<SpnegoNegotiator>() {
        @Override
        public SpnegoNegotiator run() throws Exception {
            return new SpnegoNegotiator(KerberosSuite.PRINCIPAL_CLIENT, KerberosSuite.PRINCIPAL_SERVER);
        }
    });

    byte[] token = new byte[0];
    boolean authenticated = false;

    for (int idx = 0; idx < 100; idx++) {
        if (!spnegoNegotiator.established()) {
            if (token.length > 0) {
                spnegoNegotiator.setTokenData(Base64.encodeBase64String(token));
            }
            String baseToken = client.doAs(new PrivilegedExceptionAction<String>() {
                @Override
                public String run() throws Exception {
                    return spnegoNegotiator.send();
                }
            });
            token = Base64.decodeBase64(baseToken);
        }

        if (!spnegoNegotiator.established() && serverCtx.isEstablished()) {
            fail("Server is established, but client is not.");
        }

        if (!serverCtx.isEstablished()) {
            final byte[] currentToken = token;
            token = server.doAs(new PrivilegedExceptionAction<byte[]>() {
                @Override
                public byte[] run() throws Exception {
                    return serverCtx.acceptSecContext(currentToken, 0, currentToken.length);
                }
            });
        }

        if (serverCtx.isEstablished() && spnegoNegotiator.established()) {
            authenticated = true;
            break;
        }
    }

    assertThat(authenticated, is(true));
    assertThat(serverCtx.isEstablished(), is(true));
    assertThat(spnegoNegotiator.established(), is(true));

    spnegoNegotiator.close();
    assertThat(spnegoNegotiator.established(), is(false));
}
 
Example 14
Source File: AbstractSpnegoNegotiatorTest.java    From elasticsearch-hadoop with Apache License 2.0 4 votes vote down vote up
@Test
public void testSuccessfulNegotiateWithRealmName() throws IOException, GSSException, InterruptedException {
    // Mechanisms
    final GSSManager gssManager = GSSManager.getInstance();
    final Oid spnegoOid = new Oid("1.3.6.1.5.5.2");

    // Configure logins
    Configuration configuration = new Configuration();
    SecurityUtil.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS, configuration);
    UserGroupInformation.setConfiguration(configuration);

    // Login as Server
    UserGroupInformation server = UserGroupInformation.loginUserFromKeytabAndReturnUGI(withRealm(KerberosSuite.PRINCIPAL_SERVER), KEYTAB_FILE.getAbsolutePath());
    final GSSName gssServicePrincipalName = gssManager.createName(withRealm(KerberosSuite.PRINCIPAL_SERVER), GSSName.NT_USER_NAME);
    final GSSCredential gssServiceCredential = server.doAs(new PrivilegedExceptionAction<GSSCredential>() {
        @Override
        public GSSCredential run() throws Exception {
            return gssManager.createCredential(
                    gssServicePrincipalName,
                    GSSCredential.DEFAULT_LIFETIME,
                    spnegoOid,
                    GSSCredential.ACCEPT_ONLY
            );
        }
    });
    final GSSContext serverCtx = gssManager.createContext(gssServiceCredential);

    // Login as Client and Create negotiator
    UserGroupInformation client = UserGroupInformation.loginUserFromKeytabAndReturnUGI(withRealm(KerberosSuite.PRINCIPAL_CLIENT), KEYTAB_FILE.getAbsolutePath());
    final SpnegoNegotiator spnegoNegotiator = client.doAs(new PrivilegedExceptionAction<SpnegoNegotiator>() {
        @Override
        public SpnegoNegotiator run() throws Exception {
            return new SpnegoNegotiator(withRealm(KerberosSuite.PRINCIPAL_CLIENT), withRealm(KerberosSuite.PRINCIPAL_SERVER));
        }
    });

    byte[] token = new byte[0];
    boolean authenticated = false;

    for (int idx = 0; idx < 100; idx++) {
        if (!spnegoNegotiator.established()) {
            final byte[] sendToken = token;
            String baseToken = client.doAs(new PrivilegedExceptionAction<String>() {
                @Override
                public String run() throws Exception {
                    if (sendToken.length > 0) {
                        return spnegoNegotiator.send(Base64.encodeBase64String(sendToken));
                    } else {
                        return spnegoNegotiator.send();
                    }
                }
            });
            token = Base64.decodeBase64(baseToken);
        }

        if (!spnegoNegotiator.established() && serverCtx.isEstablished()) {
            fail("Server is established, but client is not.");
        }

        if (!serverCtx.isEstablished()) {
            final byte[] currentToken = token;
            token = server.doAs(new PrivilegedExceptionAction<byte[]>() {
                @Override
                public byte[] run() throws Exception {
                    return serverCtx.acceptSecContext(currentToken, 0, currentToken.length);
                }
            });
        }

        if (serverCtx.isEstablished() && spnegoNegotiator.established()) {
            authenticated = true;
            break;
        }
    }

    assertThat(authenticated, is(true));
    assertThat(serverCtx.isEstablished(), is(true));
    assertThat(spnegoNegotiator.established(), is(true));

    spnegoNegotiator.close();
    assertThat(spnegoNegotiator.established(), is(false));
}