Search in sources :

Example 11 with GSSManager

use of org.ietf.jgss.GSSManager in project jdk8u_jdk by JetBrains.

the class ServiceCredsCombination method check.

/**
     * Checks the correct bound
     * @param a get a creds for this principal, null for default one
     * @param b expected name, null for still unbound, "NOCRED" for no creds
     * @param objs princs, keys and keytabs in the subject
     */
private static void check(final String a, String b, Object... objs) throws Exception {
    Subject subj = new Subject();
    for (Object obj : objs) {
        if (obj instanceof KerberosPrincipal) {
            subj.getPrincipals().add((KerberosPrincipal) obj);
        } else if (obj instanceof KerberosKey || obj instanceof KeyTab) {
            subj.getPrivateCredentials().add(obj);
        }
    }
    final GSSManager man = GSSManager.getInstance();
    try {
        String result = Subject.doAs(subj, new PrivilegedExceptionAction<String>() {

            @Override
            public String run() throws GSSException {
                GSSCredential cred = man.createCredential(a == null ? null : man.createName(r(a), null), GSSCredential.INDEFINITE_LIFETIME, GSSUtil.GSS_KRB5_MECH_OID, GSSCredential.ACCEPT_ONLY);
                GSSName name = cred.getName();
                return name == null ? null : name.toString();
            }
        });
        if (!Objects.equals(result, r(b))) {
            throw new Exception("Check failed: getInstance(" + a + ") has name " + result + ", not " + b);
        }
    } catch (PrivilegedActionException e) {
        if (!"NOCRED".equals(b)) {
            throw new Exception("Check failed: getInstance(" + a + ") is null " + ", but not one with name " + b);
        }
    }
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) GSSName(org.ietf.jgss.GSSName) PrivilegedActionException(java.security.PrivilegedActionException) Subject(javax.security.auth.Subject) PrivilegedActionException(java.security.PrivilegedActionException) GSSException(org.ietf.jgss.GSSException) KerberosKey(javax.security.auth.kerberos.KerberosKey) GSSException(org.ietf.jgss.GSSException) KeyTab(javax.security.auth.kerberos.KeyTab) GSSCredential(org.ietf.jgss.GSSCredential) GSSManager(org.ietf.jgss.GSSManager)

Example 12 with GSSManager

use of org.ietf.jgss.GSSManager 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 GSSManager

use of org.ietf.jgss.GSSManager 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 GSSManager

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

the class GSSTestClient method getName.

// Public methods --------------------------------------------------------
/**
     * Retrieves the name of calling identity (based on given gssCredential) retrieved from {@link GSSTestServer}.
     *
     * @param gssCredential
     * @return
     * @throws IOException
     * @throws GSSException
     */
public String getName(final GSSCredential gssCredential) throws IOException, GSSException {
    LOGGER.trace("getName() called with GSSCredential:\n" + gssCredential);
    // Create an unbound socket
    final Socket socket = new Socket();
    GSSContext gssContext = null;
    try {
        socket.connect(new InetSocketAddress(host, port), GSSTestConstants.SOCKET_TIMEOUT);
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        LOGGER.debug("Sending NAME command.");
        dos.writeInt(GSSTestConstants.CMD_NAME);
        dos.flush();
        GSSManager manager = GSSManager.getInstance();
        gssContext = manager.createContext(manager.createName(spn, null), Constants.KERBEROS_V5, gssCredential, GSSContext.DEFAULT_LIFETIME);
        //            gssContext.requestCredDeleg(true);
        gssContext.requestMutualAuth(true);
        gssContext.requestConf(true);
        gssContext.requestInteg(true);
        byte[] token = new byte[0];
        while (!gssContext.isEstablished()) {
            token = gssContext.initSecContext(token, 0, token.length);
            if (token != null) {
                dos.writeInt(token.length);
                dos.write(token);
                dos.flush();
            }
            if (!gssContext.isEstablished()) {
                token = new byte[dis.readInt()];
                dis.readFully(token);
            }
        }
        token = new byte[dis.readInt()];
        dis.readFully(token);
        MessageProp msgProp = new MessageProp(false);
        final byte[] nameBytes = gssContext.unwrap(token, 0, token.length, msgProp);
        return new String(nameBytes, GSSTestConstants.CHAR_ENC);
    } catch (IOException e) {
        LOGGER.error("IOException occurred.", e);
        throw e;
    } finally {
        try {
            socket.close();
        } catch (IOException e) {
            LOGGER.error("IOException occurred", e);
        }
        if (gssContext != null) {
            try {
                gssContext.dispose();
            } catch (GSSException e) {
                LOGGER.error("GSSException occurred", e);
            }
        }
    }
}
Also used : GSSException(org.ietf.jgss.GSSException) InetSocketAddress(java.net.InetSocketAddress) DataOutputStream(java.io.DataOutputStream) GSSContext(org.ietf.jgss.GSSContext) GSSManager(org.ietf.jgss.GSSManager) MessageProp(org.ietf.jgss.MessageProp) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream) Socket(java.net.Socket)

Example 15 with GSSManager

use of org.ietf.jgss.GSSManager 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)

Aggregations

GSSManager (org.ietf.jgss.GSSManager)31 GSSName (org.ietf.jgss.GSSName)24 Oid (org.ietf.jgss.Oid)21 GSSContext (org.ietf.jgss.GSSContext)18 GSSException (org.ietf.jgss.GSSException)17 GSSCredential (org.ietf.jgss.GSSCredential)14 Subject (javax.security.auth.Subject)12 PrivilegedActionException (java.security.PrivilegedActionException)8 Principal (java.security.Principal)7 IOException (java.io.IOException)6 LoginException (javax.security.auth.login.LoginException)5 LoginContext (javax.security.auth.login.LoginContext)4 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)3 KerberosTicket (javax.security.auth.kerberos.KerberosTicket)3 SaslException (javax.security.sasl.SaslException)3 Test (org.junit.Test)3 FileOutputStream (java.io.FileOutputStream)2 URISyntaxException (java.net.URISyntaxException)2 KerberosKey (javax.security.auth.kerberos.KerberosKey)2 KerberosPrincipal (javax.security.auth.kerberos.KerberosPrincipal)2