Java Code Examples for org.ietf.jgss.GSSManager#createContext()

The following examples show how to use org.ietf.jgss.GSSManager#createContext() . 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: KerberizedClient.java    From elasticsearch-shield-kerberos-realm with Apache License 2.0 6 votes vote down vote up
GSSContext initGSS() throws Exception {
    final GSSManager MANAGER = GSSManager.getInstance();

    final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() {
        @Override
        public GSSCredential run() throws GSSException {
            return MANAGER.createCredential(null, GSSCredential.DEFAULT_LIFETIME, KrbConstants.SPNEGO, GSSCredential.INITIATE_ONLY);
        }
    };

    final GSSCredential clientcreds = Subject.doAs(initiatorSubject, action);

    final GSSContext context = MANAGER.createContext(MANAGER.createName(acceptorPrincipal, GSSName.NT_USER_NAME, KrbConstants.SPNEGO),
            KrbConstants.SPNEGO, clientcreds, GSSContext.DEFAULT_LIFETIME);

    //TODO make configurable
    context.requestMutualAuth(true);
    context.requestConf(true);
    context.requestInteg(true);
    context.requestReplayDet(true);
    context.requestSequenceDet(true);
    context.requestCredDeleg(false);

    return context;
}
 
Example 2
Source File: TdsCore.java    From jTDS with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Initializes the GSS context and creates the initial token.
 */
private byte[] createGssToken()
   throws GSSException, UnknownHostException
{
   GSSManager manager = GSSManager.getInstance();

   // Oids for Kerberos5
   Oid mech = new Oid( "1.2.840.113554.1.2.2" );
   Oid nameType = new Oid( "1.2.840.113554.1.2.2.1" );

   // Canonicalize hostname to create SPN like MIT Kerberos does
   String host = InetAddress.getByName( socket.getHost() ).getCanonicalHostName();
   int port = socket.getPort();

   GSSName serverName = manager.createName( "MSSQLSvc/" + host + ":" + port, nameType );

   Logger.println( "GSS: Using SPN " + serverName );

   _gssContext = manager.createContext( serverName, mech, null, GSSContext.DEFAULT_LIFETIME );
   _gssContext.requestMutualAuth( true );  // FIXME: may fail, check via _gssContext.getMutualAuthState()

   byte[] token = _gssContext.initSecContext( new byte[0], 0, 0 );
   Logger.println( "GSS: Created GSS token (length: " + token.length + ")" );

   return token;
}
 
Example 3
Source File: KeycloakSPNegoSchemeFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public ByteArrayHolder run() throws Exception {
    byte[] token = input;
    if (token == null) {
        token = new byte[0];
    }
    GSSManager manager = getManager();
    String httPrincipal = kerberosConfig.getServerPrincipal().replaceFirst("/.*@", "/" + authServer + "@");
    GSSName serverName = manager.createName(httPrincipal, null);
    GSSContext gssContext = manager.createContext(
            serverName.canonicalize(oid), oid, null, GSSContext.DEFAULT_LIFETIME);
    gssContext.requestMutualAuth(true);
    gssContext.requestCredDeleg(true);
    byte[] outputToken = gssContext.initSecContext(token, 0, token.length);

    ByteArrayHolder result = new ByteArrayHolder();
    result.bytes = outputToken;
    return result;
}
 
Example 4
Source File: GGSSchemeBase.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
protected byte[] generateGSSToken(
                                   final byte[] input,
                                   final Oid oid ) throws GSSException {

    byte[] token = input;
    if (token == null) {
        token = new byte[0];
    }
    GSSManager manager = getManager();

    GSSName serverName = manager.createName(servicePrincipalName, servicePrincipalOid);

    GSSContext gssContext = manager.createContext(serverName.canonicalize(oid),
                                                  oid,
                                                  null,
                                                  GSSContext.DEFAULT_LIFETIME);
    gssContext.requestMutualAuth(true);
    gssContext.requestCredDeleg(true);
    // Get client to login if not already done
    return gssClient.negotiate(gssContext, token);
}
 
Example 5
Source File: Kerb5Context.java    From jcifs-ng with GNU Lesser General Public License v2.1 5 votes vote down vote up
Kerb5Context ( String host, String service, String name, int userLifetime, int contextLifetime, String realm ) throws GSSException {
    GSSManager manager = GSSManager.getInstance();
    GSSCredential clientCreds = null;
    Oid mechOid = JGSS_KRB5_MECH_OID;
    if ( realm != null ) {
        this.serviceName = manager.createName(service + "/" + host + "@" + realm, JGSS_KRB5_NAME_OID, mechOid);
    }
    else {
        this.serviceName = manager.createName(service + "@" + host, GSSName.NT_HOSTBASED_SERVICE, mechOid);
    }

    if ( log.isDebugEnabled() ) {
        log.debug("Service name is " + this.serviceName);
    }

    if ( name != null ) {
        this.clientName = manager.createName(name, GSSName.NT_USER_NAME, mechOid);
        clientCreds = manager.createCredential(this.clientName, userLifetime, mechOid, GSSCredential.INITIATE_ONLY);
    }
    else {
        this.clientName = null;
    }

    this.gssContext = manager.createContext(this.serviceName, mechOid, clientCreds, contextLifetime);

    this.gssContext.requestAnonymity(false);
    this.gssContext.requestSequenceDet(false);
    this.gssContext.requestConf(false);
    this.gssContext.requestInteg(false);
    this.gssContext.requestReplayDet(false);

    // per spec these should be set
    this.gssContext.requestMutualAuth(true);
    this.gssContext.requestCredDeleg(true);
}
 
Example 6
Source File: SPNEGOAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected GSSContext establishContext() throws GSSException, IOException {
    GSSManager manager = GSSManager.getInstance();

    Oid[] supportedMechs = new Oid[] { KerberosConstants.KRB5_OID, KerberosConstants.SPNEGO_OID };
    GSSCredential gssCredential = manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, supportedMechs, GSSCredential.ACCEPT_ONLY);
    GSSContext gssContext = manager.createContext(gssCredential);

    byte[] inputToken = Base64.decode(spnegoToken);
    byte[] respToken = gssContext.acceptSecContext(inputToken, 0, inputToken.length);
    responseToken = Base64.encodeBytes(respToken);

    return gssContext;
}
 
Example 7
Source File: JgssIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Before
public void setUp() throws SaslException, GSSException {
    GSSManager manager = GSSManager.getInstance();
    serverContext = manager.createContext((GSSCredential) null);
    String serverPrinciple = SERVER_PRINCIPAL;
    GSSName serverName = manager.createName(serverPrinciple, null);
    Oid krb5Oid = new Oid(MECHANISM);
    clientContext = manager.createContext(serverName, krb5Oid, (GSSCredential) null, GSSContext.DEFAULT_LIFETIME);
    clientContext.requestMutualAuth(true);
    clientContext.requestConf(true);
    clientContext.requestInteg(true);
}
 
Example 8
Source File: Test5653.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
        throws Exception {

    Oid oldOid = new Oid("1.3.6.1.5.6.2");
    new OneKDC(null).writeJAASConf();

    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    GSSManager m = GSSManager.getInstance();
    boolean found = false;

    // Test 1: the getMechsForName() method accepts it.
    for (Oid tmp: m.getMechsForName(oldOid)) {
        if (tmp.equals(GSSUtil.GSS_KRB5_MECH_OID)) {
            found = true;
            break;
        }
    }
    if (!found) {
        throw new Exception("Cannot found krb5 mech for old name type");
    }

    // Test 2: the createName() method accepts it.
    GSSName name = m.createName("[email protected]", oldOid);

    // Test 3: its getStringNameType() output is correct
    if (!name.getStringNameType().equals(GSSName.NT_HOSTBASED_SERVICE)) {
        throw new Exception("GSSName not correct name type");
    }

    // Test 4: everything still works.
    GSSContext c1 = m.createContext(
            name,
            GSSUtil.GSS_KRB5_MECH_OID,
            null,
            GSSContext.DEFAULT_LIFETIME);
    byte[] token = c1.initSecContext(new byte[0], 0, 0);

    Context s;
    s = Context.fromJAAS("server");
    s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);
    s.x().acceptSecContext(token, 0, token.length);
}
 
Example 9
Source File: Test5653.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
        throws Exception {

    Oid oldOid = new Oid("1.3.6.1.5.6.2");
    new OneKDC(null).writeJAASConf();

    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    GSSManager m = GSSManager.getInstance();
    boolean found = false;

    // Test 1: the getMechsForName() method accepts it.
    for (Oid tmp: m.getMechsForName(oldOid)) {
        if (tmp.equals(GSSUtil.GSS_KRB5_MECH_OID)) {
            found = true;
            break;
        }
    }
    if (!found) {
        throw new Exception("Cannot found krb5 mech for old name type");
    }

    // Test 2: the createName() method accepts it.
    GSSName name = m.createName("[email protected]", oldOid);

    // Test 3: its getStringNameType() output is correct
    if (!name.getStringNameType().equals(GSSName.NT_HOSTBASED_SERVICE)) {
        throw new Exception("GSSName not correct name type");
    }

    // Test 4: everything still works.
    GSSContext c1 = m.createContext(
            name,
            GSSUtil.GSS_KRB5_MECH_OID,
            null,
            GSSContext.DEFAULT_LIFETIME);
    byte[] token = c1.initSecContext(new byte[0], 0, 0);

    Context s;
    s = Context.fromJAAS("server");
    s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);
    s.x().acceptSecContext(token, 0, token.length);
}
 
Example 10
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));
}
 
Example 11
Source File: Test5653.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
        throws Exception {

    Oid oldOid = new Oid("1.3.6.1.5.6.2");
    new OneKDC(null).writeJAASConf();

    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    GSSManager m = GSSManager.getInstance();
    boolean found = false;

    // Test 1: the getMechsForName() method accepts it.
    for (Oid tmp: m.getMechsForName(oldOid)) {
        if (tmp.equals(GSSUtil.GSS_KRB5_MECH_OID)) {
            found = true;
            break;
        }
    }
    if (!found) {
        throw new Exception("Cannot found krb5 mech for old name type");
    }

    // Test 2: the createName() method accepts it.
    GSSName name = m.createName("[email protected]", oldOid);

    // Test 3: its getStringNameType() output is correct
    if (!name.getStringNameType().equals(GSSName.NT_HOSTBASED_SERVICE)) {
        throw new Exception("GSSName not correct name type");
    }

    // Test 4: everything still works.
    GSSContext c1 = m.createContext(
            name,
            GSSUtil.GSS_KRB5_MECH_OID,
            null,
            GSSContext.DEFAULT_LIFETIME);
    byte[] token = c1.initSecContext(new byte[0], 0, 0);

    Context s;
    s = Context.fromJAAS("server");
    s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);
    s.x().acceptSecContext(token, 0, token.length);
}
 
Example 12
Source File: Test5653.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
        throws Exception {

    Oid oldOid = new Oid("1.3.6.1.5.6.2");
    new OneKDC(null).writeJAASConf();

    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    GSSManager m = GSSManager.getInstance();
    boolean found = false;

    // Test 1: the getMechsForName() method accepts it.
    for (Oid tmp: m.getMechsForName(oldOid)) {
        if (tmp.equals(GSSUtil.GSS_KRB5_MECH_OID)) {
            found = true;
            break;
        }
    }
    if (!found) {
        throw new Exception("Cannot found krb5 mech for old name type");
    }

    // Test 2: the createName() method accepts it.
    GSSName name = m.createName("[email protected]", oldOid);

    // Test 3: its getStringNameType() output is correct
    if (!name.getStringNameType().equals(GSSName.NT_HOSTBASED_SERVICE)) {
        throw new Exception("GSSName not correct name type");
    }

    // Test 4: everything still works.
    GSSContext c1 = m.createContext(
            name,
            GSSUtil.GSS_KRB5_MECH_OID,
            null,
            GSSContext.DEFAULT_LIFETIME);
    byte[] token = c1.initSecContext(new byte[0], 0, 0);

    Context s;
    s = Context.fromJAAS("server");
    s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);
    s.x().acceptSecContext(token, 0, token.length);
}
 
Example 13
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 14
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 15
Source File: Test5653.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
        throws Exception {

    Oid oldOid = new Oid("1.3.6.1.5.6.2");
    new OneKDC(null).writeJAASConf();

    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    GSSManager m = GSSManager.getInstance();
    boolean found = false;

    // Test 1: the getMechsForName() method accepts it.
    for (Oid tmp: m.getMechsForName(oldOid)) {
        if (tmp.equals(GSSUtil.GSS_KRB5_MECH_OID)) {
            found = true;
            break;
        }
    }
    if (!found) {
        throw new Exception("Cannot found krb5 mech for old name type");
    }

    // Test 2: the createName() method accepts it.
    GSSName name = m.createName("[email protected]", oldOid);

    // Test 3: its getStringNameType() output is correct
    if (!name.getStringNameType().equals(GSSName.NT_HOSTBASED_SERVICE)) {
        throw new Exception("GSSName not correct name type");
    }

    // Test 4: everything still works.
    GSSContext c1 = m.createContext(
            name,
            GSSUtil.GSS_KRB5_MECH_OID,
            null,
            GSSContext.DEFAULT_LIFETIME);
    byte[] token = c1.initSecContext(new byte[0], 0, 0);

    Context s;
    s = Context.fromJAAS("server");
    s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);
    s.x().acceptSecContext(token, 0, token.length);
}
 
Example 16
Source File: AbstractSpnegoAuthSupplier.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Create and return a service ticket token for a given service principal
 * name
 *
 * @param authPolicy
 * @param spn
 * @return service ticket token
 * @throws GSSException
 * @throws LoginException
 */
private byte[] getToken(AuthorizationPolicy authPolicy,
                        String spn,
                        Oid oid,
                        Message message) throws GSSException,
    LoginException {

    GSSCredential delegatedCred =
        (GSSCredential)message.getContextualProperty(GSSCredential.class.getName());

    Subject subject = null;
    if (authPolicy != null && delegatedCred == null) {
        String contextName = authPolicy.getAuthorization();
        if (contextName == null) {
            contextName = "";
        }

        if (!(StringUtils.isEmpty(authPolicy.getUserName())
            && StringUtils.isEmpty(contextName) && loginConfig == null)) {
            CallbackHandler callbackHandler = getUsernamePasswordHandler(
                authPolicy.getUserName(), authPolicy.getPassword());
            LoginContext lc = new LoginContext(contextName, null, callbackHandler, loginConfig);
            lc.login();
            subject = lc.getSubject();
        }
    }

    GSSManager manager = GSSManager.getInstance();
    GSSName serverName = manager.createName(spn, serviceNameType);

    GSSContext context = manager
            .createContext(serverName.canonicalize(oid), oid, delegatedCred, GSSContext.DEFAULT_LIFETIME);

    context.requestCredDeleg(isCredDelegationRequired(message));

    // If the delegated cred is not null then we only need the context to
    // immediately return a ticket based on this credential without attempting
    // to log on again
    final byte[] token = new byte[0];
    if (delegatedCred != null) {
        return context.initSecContext(token, 0, token.length);
    }

    decorateSubject(subject);

    try {
        return Subject.doAs(subject, new CreateServiceTicketAction(context, token));
    } catch (PrivilegedActionException e) {
        if (e.getCause() instanceof GSSException) {
            throw (GSSException) e.getCause();
        }
        LOG.log(Level.SEVERE, "initSecContext", e);
        return null;
    }
}
 
Example 17
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 18
Source File: Test5653.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
        throws Exception {

    Oid oldOid = new Oid("1.3.6.1.5.6.2");
    new OneKDC(null).writeJAASConf();

    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    GSSManager m = GSSManager.getInstance();
    boolean found = false;

    // Test 1: the getMechsForName() method accepts it.
    for (Oid tmp: m.getMechsForName(oldOid)) {
        if (tmp.equals(GSSUtil.GSS_KRB5_MECH_OID)) {
            found = true;
            break;
        }
    }
    if (!found) {
        throw new Exception("Cannot found krb5 mech for old name type");
    }

    // Test 2: the createName() method accepts it.
    GSSName name = m.createName("[email protected]", oldOid);

    // Test 3: its getStringNameType() output is correct
    if (!name.getStringNameType().equals(GSSName.NT_HOSTBASED_SERVICE)) {
        throw new Exception("GSSName not correct name type");
    }

    // Test 4: everything still works.
    GSSContext c1 = m.createContext(
            name,
            GSSUtil.GSS_KRB5_MECH_OID,
            null,
            GSSContext.DEFAULT_LIFETIME);
    byte[] token = c1.initSecContext(new byte[0], 0, 0);

    Context s;
    s = Context.fromJAAS("server");
    s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);
    s.x().acceptSecContext(token, 0, token.length);
}
 
Example 19
Source File: Test5653.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
        throws Exception {

    Oid oldOid = new Oid("1.3.6.1.5.6.2");
    new OneKDC(null).writeJAASConf();

    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    GSSManager m = GSSManager.getInstance();
    boolean found = false;

    // Test 1: the getMechsForName() method accepts it.
    for (Oid tmp: m.getMechsForName(oldOid)) {
        if (tmp.equals(GSSUtil.GSS_KRB5_MECH_OID)) {
            found = true;
            break;
        }
    }
    if (!found) {
        throw new Exception("Cannot found krb5 mech for old name type");
    }

    // Test 2: the createName() method accepts it.
    GSSName name = m.createName("[email protected]", oldOid);

    // Test 3: its getStringNameType() output is correct
    if (!name.getStringNameType().equals(GSSName.NT_HOSTBASED_SERVICE)) {
        throw new Exception("GSSName not correct name type");
    }

    // Test 4: everything still works.
    GSSContext c1 = m.createContext(
            name,
            GSSUtil.GSS_KRB5_MECH_OID,
            null,
            GSSContext.DEFAULT_LIFETIME);
    byte[] token = c1.initSecContext(new byte[0], 0, 0);

    Context s;
    s = Context.fromJAAS("server");
    s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);
    s.x().acceptSecContext(token, 0, token.length);
}
 
Example 20
Source File: GSSAPIAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
public AuthenticationMechanismOutcome run() throws GSSException {
    NegotiationContext negContext = exchange.getAttachment(NegotiationContext.ATTACHMENT_KEY);
    if (negContext == null) {
        negContext = new NegotiationContext();
        exchange.putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext);
    }

    GSSContext gssContext = negContext.getGssContext();
    if (gssContext == null) {
        GSSManager manager = GSSManager.getInstance();

        GSSCredential credential = manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, mechanisms, GSSCredential.ACCEPT_ONLY);

        gssContext = manager.createContext(credential);

        negContext.setGssContext(gssContext);
    }

    byte[] respToken = gssContext.acceptSecContext(challenge.array(), challenge.arrayOffset(), challenge.writerIndex());
    negContext.setResponseToken(respToken);

    if (negContext.isEstablished()) {

        if (respToken != null) {
            // There will be no further challenge but we do have a token so set it here.
            exchange.addResponseHeader(WWW_AUTHENTICATE,
                    NEGOTIATE_PREFIX + FlexBase64.encodeString(respToken, false));
        }
        IdentityManager identityManager = securityContext.getIdentityManager();
        final Account account = identityManager.verify(new GSSContextCredential(negContext.getGssContext()));
        if (account != null) {
            securityContext.authenticationComplete(account, name, false);
            return AuthenticationMechanismOutcome.AUTHENTICATED;
        } else {
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
    } else {
        // This isn't a failure but as the context is not established another round trip with the client is needed.
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }
}