Search in sources :

Example 11 with GSSName

use of org.ietf.jgss.GSSName in project OpenAM by OpenRock.

the class WindowsDesktopSSO method authenticateToken.

private void authenticateToken(final byte[] kerberosToken, final Set<String> trustedRealms) throws AuthLoginException, GSSException, Exception {
    debug.message("In authenticationToken ...");
    Subject.doAs(serviceSubject, new PrivilegedExceptionAction() {

        public Object run() throws Exception {
            GSSContext context = GSSManager.getInstance().createContext((GSSCredential) null);
            if (debug.messageEnabled()) {
                debug.message("Context created.");
            }
            byte[] outToken = context.acceptSecContext(kerberosToken, 0, kerberosToken.length);
            if (outToken != null) {
                if (debug.messageEnabled()) {
                    debug.message("Token returned from acceptSecContext: \n" + DerValue.printByteArray(outToken, 0, outToken.length));
                }
            }
            if (!context.isEstablished()) {
                debug.error("Cannot establish context !");
                throw new AuthLoginException(amAuthWindowsDesktopSSO, "context", null);
            } else {
                if (debug.messageEnabled()) {
                    debug.message("Context established !");
                }
                GSSName user = context.getSrcName();
                final String userPrincipalName = user.toString();
                // expected default behaviour.
                if (!trustedRealms.isEmpty()) {
                    boolean foundTrustedRealm = false;
                    for (final String trustedRealm : trustedRealms) {
                        if (isTokenTrusted(userPrincipalName, trustedRealm)) {
                            foundTrustedRealm = true;
                            break;
                        }
                    }
                    if (!foundTrustedRealm) {
                        debug.error("Kerberos token for " + userPrincipalName + " not trusted");
                        final String[] data = { userPrincipalName };
                        throw new AuthLoginException(amAuthWindowsDesktopSSO, "untrustedToken", data);
                    }
                }
                // perform the search.
                if (lookupUserInRealm) {
                    String org = getRequestOrg();
                    String userValue = getUserName(userPrincipalName);
                    String userName = searchUserAccount(userValue, org);
                    if (userName != null && !userName.isEmpty()) {
                        storeUsernamePasswd(userValue, null);
                    } else {
                        String[] data = { userValue, org };
                        debug.error("WindowsDesktopSSO.authenticateToken: " + ": Unable to find the user " + userValue);
                        throw new AuthLoginException(amAuthWindowsDesktopSSO, "notfound", data);
                    }
                }
                if (debug.messageEnabled()) {
                    debug.message("WindowsDesktopSSO.authenticateToken:" + "User authenticated: " + user.toString());
                }
                if (user != null) {
                    setPrincipal(userPrincipalName);
                }
            }
            context.dispose();
            return null;
        }
    });
}
Also used : GSSName(org.ietf.jgss.GSSName) GSSCredential(org.ietf.jgss.GSSCredential) GSSContext(org.ietf.jgss.GSSContext) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) IdRepoException(com.sun.identity.idm.IdRepoException) PrivilegedActionException(java.security.PrivilegedActionException) GSSException(org.ietf.jgss.GSSException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException)

Example 12 with GSSName

use of org.ietf.jgss.GSSName in project calcite-avatica by apache.

the class HttpServerSpnegoWithoutJaasTest method testAuthenticatedClientsAllowed.

@Test
public void testAuthenticatedClientsAllowed() throws Exception {
    // Create the subject for the client
    final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(SpnegoTestUtil.CLIENT_PRINCIPAL, clientKeytab);
    final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    // Make sure the subject has a principal
    assertFalse(clientPrincipals.isEmpty());
    // Get a TGT for the subject (might have many, different encryption types). The first should
    // be the default encryption type.
    Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
    assertFalse(privateCredentials.isEmpty());
    KerberosTicket tgt = privateCredentials.iterator().next();
    assertNotNull(tgt);
    LOG.info("Using TGT with etype: {}", tgt.getSessionKey().getAlgorithm());
    // The name of the principal
    final String principalName = clientPrincipals.iterator().next().getName();
    // Run this code, logged in as the subject (the client)
    byte[] response = Subject.doAs(clientSubject, new PrivilegedExceptionAction<byte[]>() {

        @Override
        public byte[] run() throws Exception {
            // Logs in with Kerberos via GSS
            GSSManager gssManager = GSSManager.getInstance();
            Oid oid = new Oid(SpnegoTestUtil.JGSS_KERBEROS_TICKET_OID);
            GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
            GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);
            // Passes the GSSCredential into the HTTP client implementation
            final AvaticaCommonsHttpClientSpnegoImpl httpClient = new AvaticaCommonsHttpClientSpnegoImpl(httpServerUrl, credential);
            return httpClient.send(new byte[0]);
        }
    });
    // We should get a response which is "OK" with our client's name
    assertNotNull(response);
    assertEquals("OK " + SpnegoTestUtil.CLIENT_PRINCIPAL, new String(response, StandardCharsets.UTF_8));
}
Also used : GSSName(org.ietf.jgss.GSSName) KerberosTicket(javax.security.auth.kerberos.KerberosTicket) Oid(org.ietf.jgss.Oid) Subject(javax.security.auth.Subject) KrbException(org.apache.kerby.kerberos.kerb.KrbException) GSSCredential(org.ietf.jgss.GSSCredential) GSSManager(org.ietf.jgss.GSSManager) AvaticaCommonsHttpClientSpnegoImpl(org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientSpnegoImpl) Principal(java.security.Principal) Test(org.junit.Test)

Example 13 with GSSName

use of org.ietf.jgss.GSSName in project calcite-avatica by apache.

the class HttpServerSpnegoWithJaasTest method testAuthenticatedClientsAllowed.

@Test
public void testAuthenticatedClientsAllowed() throws Exception {
    Assume.assumeThat("Test disabled on Windows", File.separatorChar, is('/'));
    // Create the subject for the client
    final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(SpnegoTestUtil.CLIENT_PRINCIPAL, clientKeytab);
    final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    // Make sure the subject has a principal
    assertFalse(clientPrincipals.isEmpty());
    // Get a TGT for the subject (might have many, different encryption types). The first should
    // be the default encryption type.
    Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
    assertFalse(privateCredentials.isEmpty());
    KerberosTicket tgt = privateCredentials.iterator().next();
    assertNotNull(tgt);
    LOG.info("Using TGT with etype: {}", tgt.getSessionKey().getAlgorithm());
    // The name of the principal
    final String principalName = clientPrincipals.iterator().next().getName();
    // Run this code, logged in as the subject (the client)
    byte[] response = Subject.doAs(clientSubject, new PrivilegedExceptionAction<byte[]>() {

        @Override
        public byte[] run() throws Exception {
            // Logs in with Kerberos via GSS
            GSSManager gssManager = GSSManager.getInstance();
            Oid oid = new Oid(SpnegoTestUtil.JGSS_KERBEROS_TICKET_OID);
            GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
            GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);
            // Passes the GSSCredential into the HTTP client implementation
            final AvaticaCommonsHttpClientSpnegoImpl httpClient = new AvaticaCommonsHttpClientSpnegoImpl(httpServerUrl, credential);
            return httpClient.send(new byte[0]);
        }
    });
    // We should get a response which is "OK" with our client's name
    assertNotNull(response);
    assertEquals("OK " + SpnegoTestUtil.CLIENT_PRINCIPAL, new String(response, StandardCharsets.UTF_8));
}
Also used : GSSName(org.ietf.jgss.GSSName) KerberosTicket(javax.security.auth.kerberos.KerberosTicket) Oid(org.ietf.jgss.Oid) Subject(javax.security.auth.Subject) KrbException(org.apache.kerby.kerberos.kerb.KrbException) GSSCredential(org.ietf.jgss.GSSCredential) GSSManager(org.ietf.jgss.GSSManager) AvaticaCommonsHttpClientSpnegoImpl(org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientSpnegoImpl) Principal(java.security.Principal) Test(org.junit.Test)

Example 14 with GSSName

use of org.ietf.jgss.GSSName in project wildfly by wildfly.

the class JBossNegotiateScheme method authenticate.

/**
     * Produces Negotiate authorization Header based on token created by processChallenge.
     *
     * @param credentials Never used be the Negotiate scheme but must be provided to satisfy common-httpclient API. Credentials
     *        from JAAS will be used instead.
     * @param request The request being authenticated
     *
     * @throws AuthenticationException if authorization string cannot be generated due to an authentication failure
     *
     * @return an Negotiate authorization Header
     */
@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (state == State.TOKEN_GENERATED) {
        // hack for auto redirects
        return new BasicHeader("X-dummy", "Token already generated");
    }
    if (state != State.CHALLENGE_RECEIVED) {
        throw new IllegalStateException("Negotiation authentication process has not been initiated");
    }
    try {
        String key = null;
        if (isProxy()) {
            key = ExecutionContext.HTTP_PROXY_HOST;
        } else {
            key = HttpCoreContext.HTTP_TARGET_HOST;
        }
        HttpHost host = (HttpHost) context.getAttribute(key);
        if (host == null) {
            throw new AuthenticationException("Authentication host is not set " + "in the execution context");
        }
        String authServer;
        if (!this.stripPort && host.getPort() > 0) {
            authServer = host.toHostString();
        } else {
            authServer = host.getHostName();
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("init " + authServer);
        }
        final Oid negotiationOid = new Oid(SPNEGO_OID);
        final GSSManager manager = GSSManager.getInstance();
        final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
        final GSSContext gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null, DEFAULT_LIFETIME);
        gssContext.requestMutualAuth(true);
        gssContext.requestCredDeleg(true);
        if (token == null) {
            token = new byte[0];
        }
        token = gssContext.initSecContext(token, 0, token.length);
        if (token == null) {
            state = State.FAILED;
            throw new AuthenticationException("GSS security context initialization failed");
        }
        state = State.TOKEN_GENERATED;
        String tokenstr = new String(base64codec.encode(token));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending response '" + tokenstr + "' back to the auth server");
        }
        CharArrayBuffer buffer = new CharArrayBuffer(32);
        if (isProxy()) {
            buffer.append(AUTH.PROXY_AUTH_RESP);
        } else {
            buffer.append(AUTH.WWW_AUTH_RESP);
        }
        buffer.append(": Negotiate ");
        buffer.append(tokenstr);
        return new BufferedHeader(buffer);
    } catch (GSSException gsse) {
        state = State.FAILED;
        if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.NO_CRED)
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN)
            throw new AuthenticationException(gsse.getMessage(), gsse);
        // other error
        throw new AuthenticationException(gsse.getMessage());
    }
}
Also used : GSSName(org.ietf.jgss.GSSName) AuthenticationException(org.apache.http.auth.AuthenticationException) BufferedHeader(org.apache.http.message.BufferedHeader) CharArrayBuffer(org.apache.http.util.CharArrayBuffer) Oid(org.ietf.jgss.Oid) GSSException(org.ietf.jgss.GSSException) InvalidCredentialsException(org.apache.http.auth.InvalidCredentialsException) HttpHost(org.apache.http.HttpHost) GSSManager(org.ietf.jgss.GSSManager) GSSContext(org.ietf.jgss.GSSContext) BasicHeader(org.apache.http.message.BasicHeader)

Example 15 with GSSName

use of org.ietf.jgss.GSSName in project undertow by undertow-io.

the class SpnegoAuthenticationTestCase method testSpnegoSuccess.

@Test
public void testSpnegoSuccess() throws Exception {
    final TestHttpClient client = new TestHttpClient();
    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
    HttpResponse result = client.execute(get);
    assertEquals(StatusCodes.UNAUTHORIZED, result.getStatusLine().getStatusCode());
    Header[] values = result.getHeaders(WWW_AUTHENTICATE.toString());
    String header = getAuthHeader(NEGOTIATE, values);
    assertEquals(NEGOTIATE.toString(), header);
    HttpClientUtils.readResponse(result);
    Subject clientSubject = login("jduke", "theduke".toCharArray());
    Subject.doAs(clientSubject, new PrivilegedExceptionAction<Void>() {

        @Override
        public Void run() throws Exception {
            GSSManager gssManager = GSSManager.getInstance();
            GSSName serverName = gssManager.createName("HTTP/" + DefaultServer.getDefaultServerAddress().getHostString(), null);
            GSSContext context = gssManager.createContext(serverName, SPNEGO, null, GSSContext.DEFAULT_LIFETIME);
            byte[] token = new byte[0];
            boolean gotOur200 = false;
            while (!context.isEstablished()) {
                token = context.initSecContext(token, 0, token.length);
                if (token != null && token.length > 0) {
                    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
                    get.addHeader(AUTHORIZATION.toString(), NEGOTIATE + " " + FlexBase64.encodeString(token, false));
                    HttpResponse result = client.execute(get);
                    Header[] headers = result.getHeaders(WWW_AUTHENTICATE.toString());
                    if (headers.length > 0) {
                        String header = getAuthHeader(NEGOTIATE, headers);
                        byte[] headerBytes = header.getBytes(StandardCharsets.US_ASCII);
                        // FlexBase64.decode() returns byte buffer, which can contain backend array of greater size.
                        // when on such ByteBuffer is called array(), it returns the underlying byte array including the 0 bytes
                        // at the end, which makes the token invalid. => using Base64 mime decoder, which returnes directly properly sized byte[].
                        token = Base64.getMimeDecoder().decode(ArrayUtils.subarray(headerBytes, NEGOTIATE.toString().length() + 1, headerBytes.length));
                    }
                    if (result.getStatusLine().getStatusCode() == StatusCodes.OK) {
                        Header[] values = result.getHeaders("ProcessedBy");
                        assertEquals(1, values.length);
                        assertEquals("ResponseHandler", values[0].getValue());
                        HttpClientUtils.readResponse(result);
                        assertSingleNotificationType(EventType.AUTHENTICATED);
                        gotOur200 = true;
                    } else if (result.getStatusLine().getStatusCode() == StatusCodes.UNAUTHORIZED) {
                        assertTrue("We did get a header.", headers.length > 0);
                        HttpClientUtils.readResponse(result);
                    } else {
                        fail(String.format("Unexpected status code %d", result.getStatusLine().getStatusCode()));
                    }
                }
            }
            assertTrue(gotOur200);
            assertTrue(context.isEstablished());
            return null;
        }
    });
}
Also used : GSSName(org.ietf.jgss.GSSName) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) Subject(javax.security.auth.Subject) GeneralSecurityException(java.security.GeneralSecurityException) TestHttpClient(io.undertow.testutils.TestHttpClient) Header(org.apache.http.Header) GSSManager(org.ietf.jgss.GSSManager) GSSContext(org.ietf.jgss.GSSContext) Test(org.junit.Test)

Aggregations

GSSName (org.ietf.jgss.GSSName)31 GSSManager (org.ietf.jgss.GSSManager)24 Oid (org.ietf.jgss.Oid)20 GSSException (org.ietf.jgss.GSSException)19 GSSContext (org.ietf.jgss.GSSContext)16 GSSCredential (org.ietf.jgss.GSSCredential)13 Subject (javax.security.auth.Subject)9 Principal (java.security.Principal)7 PrivilegedActionException (java.security.PrivilegedActionException)6 IOException (java.io.IOException)4 Test (org.junit.Test)4 KerberosTicket (javax.security.auth.kerberos.KerberosTicket)3 KrbException (org.apache.kerby.kerberos.kerb.KrbException)3 ExtendedGSSContext (com.sun.security.jgss.ExtendedGSSContext)2 LoginContext (javax.security.auth.login.LoginContext)2 LoginException (javax.security.auth.login.LoginException)2 SaslException (javax.security.sasl.SaslException)2 SaslServer (javax.security.sasl.SaslServer)2 AvaticaCommonsHttpClientSpnegoImpl (org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientSpnegoImpl)2 AuthenticationException (org.apache.hadoop.security.authentication.client.AuthenticationException)2