Search in sources :

Example 31 with SaslException

use of javax.security.sasl.SaslException in project CorfuDB by CorfuDB.

the class PlainTextSaslServer method evaluateResponse.

@Override
public byte[] evaluateResponse(byte[] response) throws SaslException {
    String[] tokens;
    try {
        tokens = new String(response, "UTF-8").split("");
    } catch (UnsupportedEncodingException ue) {
        throw new SaslException("Unsupported charset");
    }
    if (tokens.length != 3) {
        throw new SaslException("Malformed plain text response received");
    }
    verify(tokens[0], tokens[1], tokens[2]);
    return null;
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) SaslException(javax.security.sasl.SaslException)

Example 32 with SaslException

use of javax.security.sasl.SaslException in project jdk8u_jdk by JetBrains.

the class SaslOutputStream method close.

public void close() throws IOException {
    SaslException save = null;
    try {
        // Dispose of SaslClient's state
        sc.dispose();
    } catch (SaslException e) {
        // Save exception for throwing after closing 'in'
        save = e;
    }
    // Close underlying output stream
    super.close();
    if (save != null) {
        throw save;
    }
}
Also used : SaslException(javax.security.sasl.SaslException)

Example 33 with SaslException

use of javax.security.sasl.SaslException in project zookeeper by apache.

the class SaslQuorumAuthLearner method authenticate.

@Override
public void authenticate(Socket sock, String hostName) throws IOException {
    if (!quorumRequireSasl) {
        // let it through, we don't require auth
        LOG.info("Skipping SASL authentication as {}={}", QuorumAuth.QUORUM_LEARNER_SASL_AUTH_REQUIRED, quorumRequireSasl);
        return;
    }
    SaslClient sc = null;
    String principalConfig = SecurityUtils.getServerPrincipal(quorumServicePrincipal, hostName);
    try {
        DataOutputStream dout = new DataOutputStream(sock.getOutputStream());
        DataInputStream din = new DataInputStream(sock.getInputStream());
        byte[] responseToken = new byte[0];
        sc = SecurityUtils.createSaslClient(learnerLogin.getSubject(), principalConfig, QuorumAuth.QUORUM_SERVER_PROTOCOL_NAME, QuorumAuth.QUORUM_SERVER_SASL_DIGEST, LOG, "QuorumLearner");
        if (sc.hasInitialResponse()) {
            responseToken = createSaslToken(new byte[0], sc, learnerLogin);
        }
        send(dout, responseToken);
        QuorumAuthPacket authPacket = receive(din);
        QuorumAuth.Status qpStatus = QuorumAuth.Status.getStatus(authPacket.getStatus());
        while (!sc.isComplete()) {
            switch(qpStatus) {
                case SUCCESS:
                    responseToken = createSaslToken(authPacket.getToken(), sc, learnerLogin);
                    // we're done; don't expect to send another BIND
                    if (responseToken != null) {
                        throw new SaslException("Protocol error: attempting to send response after completion");
                    }
                    break;
                case IN_PROGRESS:
                    responseToken = createSaslToken(authPacket.getToken(), sc, learnerLogin);
                    send(dout, responseToken);
                    authPacket = receive(din);
                    qpStatus = QuorumAuth.Status.getStatus(authPacket.getStatus());
                    break;
                case ERROR:
                    throw new SaslException("Authentication failed against server addr: " + sock.getRemoteSocketAddress());
                default:
                    LOG.warn("Unknown status:{}!", qpStatus);
                    throw new SaslException("Authentication failed against server addr: " + sock.getRemoteSocketAddress());
            }
        }
        // Validate status code at the end of authentication exchange.
        checkAuthStatus(sock, qpStatus);
    } finally {
        if (sc != null) {
            try {
                sc.dispose();
            } catch (SaslException e) {
                LOG.error("SaslClient dispose() failed", e);
            }
        }
    }
    return;
}
Also used : DataOutputStream(java.io.DataOutputStream) QuorumAuthPacket(org.apache.zookeeper.server.quorum.QuorumAuthPacket) DataInputStream(java.io.DataInputStream) SaslException(javax.security.sasl.SaslException) SaslClient(javax.security.sasl.SaslClient)

Example 34 with SaslException

use of javax.security.sasl.SaslException in project zookeeper by apache.

the class SaslQuorumAuthServer method authenticate.

@Override
public void authenticate(Socket sock, DataInputStream din) throws SaslException {
    DataOutputStream dout = null;
    SaslServer ss = null;
    try {
        if (!QuorumAuth.nextPacketIsAuth(din)) {
            if (quorumRequireSasl) {
                throw new SaslException("Learner not trying to authenticate" + " and authentication is required");
            } else {
                // let it through, we don't require auth
                return;
            }
        }
        byte[] token = receive(din);
        int tries = 0;
        dout = new DataOutputStream(sock.getOutputStream());
        byte[] challenge = null;
        ss = SecurityUtils.createSaslServer(serverLogin.getSubject(), QuorumAuth.QUORUM_SERVER_PROTOCOL_NAME, QuorumAuth.QUORUM_SERVER_SASL_DIGEST, serverLogin.callbackHandler, LOG);
        while (!ss.isComplete()) {
            challenge = ss.evaluateResponse(token);
            if (!ss.isComplete()) {
                // limited number of retries.
                if (++tries > MAX_RETRIES) {
                    send(dout, challenge, QuorumAuth.Status.ERROR);
                    LOG.warn("Failed to authenticate using SASL, server addr: {}, retries={} exceeded.", sock.getRemoteSocketAddress(), tries);
                    break;
                }
                send(dout, challenge, QuorumAuth.Status.IN_PROGRESS);
                token = receive(din);
            }
        }
        // Authentication exchange has completed
        if (ss.isComplete()) {
            send(dout, challenge, QuorumAuth.Status.SUCCESS);
            LOG.info("Successfully completed the authentication using SASL. learner addr: {}", sock.getRemoteSocketAddress());
        }
    } catch (Exception e) {
        try {
            if (dout != null) {
                // send error message to the learner
                send(dout, new byte[0], QuorumAuth.Status.ERROR);
            }
        } catch (IOException ioe) {
            LOG.warn("Exception while sending failed status", ioe);
        }
        // handshake.
        if (quorumRequireSasl) {
            LOG.error("Failed to authenticate using SASL", e);
            throw new SaslException("Failed to authenticate using SASL: " + e.getMessage());
        } else {
            LOG.warn("Failed to authenticate using SASL", e);
            LOG.warn("Maintaining learner connection despite SASL authentication failure." + " server addr: {}, {}: {}", new Object[] { sock.getRemoteSocketAddress(), QuorumAuth.QUORUM_SERVER_SASL_AUTH_REQUIRED, quorumRequireSasl });
            // let it through, we don't require auth
            return;
        }
    } finally {
        if (ss != null) {
            try {
                ss.dispose();
            } catch (SaslException e) {
                LOG.error("SaslServer dispose() failed", e);
            }
        }
    }
    return;
}
Also used : DataOutputStream(java.io.DataOutputStream) SaslServer(javax.security.sasl.SaslServer) IOException(java.io.IOException) SaslException(javax.security.sasl.SaslException) LoginException(javax.security.auth.login.LoginException) IOException(java.io.IOException) SaslException(javax.security.sasl.SaslException)

Example 35 with SaslException

use of javax.security.sasl.SaslException in project zookeeper by apache.

the class SecurityUtils method createSaslServer.

/**
 * Create an instance of a SaslServer. It will return null if there is an exception.
 *
 * @param subject subject
 * @param protocol protocol
 * @param serverName server name
 * @param callbackHandler login callback handler
 * @param LOG logger
 * @return sasl server object
 */
public static SaslServer createSaslServer(final Subject subject, final String protocol, final String serverName, final CallbackHandler callbackHandler, final Logger LOG) {
    if (subject != null) {
        // principal name and hostname from zk server's subject.
        if (subject.getPrincipals().size() > 0) {
            try {
                final Object[] principals = subject.getPrincipals().toArray();
                final Principal servicePrincipal = (Principal) principals[0];
                // e.g. servicePrincipalNameAndHostname :=
                // "zookeeper/myhost.foo.com@FOO.COM"
                final String servicePrincipalNameAndHostname = servicePrincipal.getName();
                int indexOf = servicePrincipalNameAndHostname.indexOf("/");
                // e.g. servicePrincipalName := "zookeeper"
                final String servicePrincipalName = servicePrincipalNameAndHostname.substring(0, indexOf);
                // e.g. serviceHostnameAndKerbDomain :=
                // "myhost.foo.com@FOO.COM"
                final String serviceHostnameAndKerbDomain = servicePrincipalNameAndHostname.substring(indexOf + 1, servicePrincipalNameAndHostname.length());
                indexOf = serviceHostnameAndKerbDomain.indexOf("@");
                // e.g. serviceHostname := "myhost.foo.com"
                final String serviceHostname = serviceHostnameAndKerbDomain.substring(0, indexOf);
                // TODO: should depend on zoo.cfg specified mechs, but if
                // subject is non-null, it can be assumed to be GSSAPI.
                final String mech = "GSSAPI";
                LOG.debug("serviceHostname is '" + serviceHostname + "'");
                LOG.debug("servicePrincipalName is '" + servicePrincipalName + "'");
                LOG.debug("SASL mechanism(mech) is '" + mech + "'");
                boolean usingNativeJgss = Boolean.getBoolean("sun.security.jgss.native");
                if (usingNativeJgss) {
                    // """
                    try {
                        GSSManager manager = GSSManager.getInstance();
                        Oid krb5Mechanism = new Oid("1.2.840.113554.1.2.2");
                        GSSName gssName = manager.createName(servicePrincipalName + "@" + serviceHostname, GSSName.NT_HOSTBASED_SERVICE);
                        GSSCredential cred = manager.createCredential(gssName, GSSContext.DEFAULT_LIFETIME, krb5Mechanism, GSSCredential.ACCEPT_ONLY);
                        subject.getPrivateCredentials().add(cred);
                        LOG.debug("Added private credential to service principal name: '{}'," + " GSSCredential name: {}", servicePrincipalName, cred.getName());
                    } catch (GSSException ex) {
                        LOG.warn("Cannot add private credential to subject; " + "clients authentication may fail", ex);
                    }
                }
                try {
                    return Subject.doAs(subject, new PrivilegedExceptionAction<SaslServer>() {

                        public SaslServer run() {
                            try {
                                SaslServer saslServer;
                                saslServer = Sasl.createSaslServer(mech, servicePrincipalName, serviceHostname, null, callbackHandler);
                                return saslServer;
                            } catch (SaslException e) {
                                LOG.error("Zookeeper Server failed to create a SaslServer to interact with a client during session initiation: ", e);
                                return null;
                            }
                        }
                    });
                } catch (PrivilegedActionException e) {
                    // TODO: exit server at this point(?)
                    LOG.error("Zookeeper Quorum member experienced a PrivilegedActionException exception while creating a SaslServer using a JAAS principal context:", e);
                }
            } catch (IndexOutOfBoundsException e) {
                LOG.error("server principal name/hostname determination error: ", e);
            }
        } else {
            // TODO: use 'authMech=' value in zoo.cfg.
            try {
                SaslServer saslServer = Sasl.createSaslServer("DIGEST-MD5", protocol, serverName, null, callbackHandler);
                return saslServer;
            } catch (SaslException e) {
                LOG.error("Zookeeper Quorum member failed to create a SaslServer to interact with a client during session initiation", e);
            }
        }
    }
    return null;
}
Also used : GSSName(org.ietf.jgss.GSSName) PrivilegedActionException(java.security.PrivilegedActionException) SaslServer(javax.security.sasl.SaslServer) Oid(org.ietf.jgss.Oid) SaslException(javax.security.sasl.SaslException) GSSException(org.ietf.jgss.GSSException) GSSCredential(org.ietf.jgss.GSSCredential) GSSManager(org.ietf.jgss.GSSManager) Principal(java.security.Principal)

Aggregations

SaslException (javax.security.sasl.SaslException)75 IOException (java.io.IOException)24 NameCallback (javax.security.auth.callback.NameCallback)11 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)11 SaslClient (javax.security.sasl.SaslClient)7 PrivilegedActionException (java.security.PrivilegedActionException)6 Callback (javax.security.auth.callback.Callback)6 PasswordCallback (javax.security.auth.callback.PasswordCallback)6 LoginException (javax.security.auth.login.LoginException)6 SaslServer (javax.security.sasl.SaslServer)6 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)5 InvalidKeyException (java.security.InvalidKeyException)5 AuthorizeCallback (javax.security.sasl.AuthorizeCallback)5 RpcException (org.apache.drill.exec.rpc.RpcException)5 GSSException (org.ietf.jgss.GSSException)5 DataOutputStream (java.io.DataOutputStream)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 Principal (java.security.Principal)4 CallbackHandler (javax.security.auth.callback.CallbackHandler)4 GSSCredential (org.ietf.jgss.GSSCredential)4