Search in sources :

Example 16 with SaslException

use of javax.security.sasl.SaslException in project Openfire by igniterealtime.

the class ExternalClientSaslServer method evaluateResponse.

@Override
public byte[] evaluateResponse(byte[] response) throws SaslException {
    if (isComplete()) {
        throw new IllegalStateException("Authentication exchange already completed.");
    }
    // There will be no further steps. Either authentication succeeds or fails, but in any case, we're done.
    complete = true;
    final Connection connection = session.getConnection();
    Certificate[] peerCertificates = connection.getPeerCertificates();
    if (peerCertificates == null || peerCertificates.length < 1) {
        throw new SaslException("No peer certificates.");
    }
    final KeyStore keyStore = connection.getConfiguration().getIdentityStore().getStore();
    final KeyStore trustStore = connection.getConfiguration().getTrustStore().getStore();
    final X509Certificate trusted = CertificateManager.getEndEntityCertificate(peerCertificates, keyStore, trustStore);
    if (trusted == null) {
        throw new SaslException("Certificate chain of peer is not trusted.");
    }
    // Process client identities / principals.
    final ArrayList<String> principals = new ArrayList<>();
    principals.addAll(CertificateManager.getClientIdentities(trusted));
    String principal;
    switch(principals.size()) {
        case 0:
            principal = "";
            break;
        default:
            Log.debug("More than one principal found, using the first one.");
        // intended fall-through;
        case 1:
            principal = principals.get(0);
            break;
    }
    // Process requested user name.
    String username;
    if (response != null && response.length > 0) {
        username = new String(response, StandardCharsets.UTF_8);
    } else {
        username = null;
    }
    if (username == null || username.length() == 0) {
        // cause an authorization failure.
        for (String princ : principals) {
            final String mappedUsername = AuthorizationManager.map(princ);
            if (!mappedUsername.equals(princ)) {
                username = mappedUsername;
                principal = princ;
                break;
            }
        }
        if (username == null || username.length() == 0) {
            // Still no username.  Punt.
            username = principal;
        }
        Log.debug("No username requested, using: {}", username);
    }
    // Its possible that either/both username and principal are null here. The providers should not allow a null authorization
    if (AuthorizationManager.authorize(username, principal)) {
        Log.debug("Principal {} authorized to username {}", principal, username);
        authorizationID = username;
        // Success!
        return null;
    }
    throw new SaslException();
}
Also used : Connection(org.jivesoftware.openfire.Connection) ArrayList(java.util.ArrayList) SaslException(javax.security.sasl.SaslException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 17 with SaslException

use of javax.security.sasl.SaslException in project AuthMeReloaded by AuthMe.

the class OAuth2SaslClient method evaluateChallenge.

public byte[] evaluateChallenge(byte[] challenge) throws SaslException {
    if (isComplete) {
        // Empty final response from server, just ignore it.
        return new byte[] {};
    }
    NameCallback nameCallback = new NameCallback("Enter name");
    Callback[] callbacks = new Callback[] { nameCallback };
    try {
        callbackHandler.handle(callbacks);
    } catch (UnsupportedCallbackException e) {
        throw new SaslException("Unsupported callback: " + e);
    } catch (IOException e) {
        throw new SaslException("Failed to execute callback: " + e);
    }
    String email = nameCallback.getName();
    byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", email, oauthToken).getBytes();
    isComplete = true;
    return response;
}
Also used : NameCallback(javax.security.auth.callback.NameCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) IOException(java.io.IOException) SaslException(javax.security.sasl.SaslException)

Example 18 with SaslException

use of javax.security.sasl.SaslException in project alluxio by Alluxio.

the class PlainSaslServer method evaluateResponse.

@Override
public byte[] evaluateResponse(byte[] response) throws SaslException {
    Preconditions.checkState(!mCompleted, "PLAIN authentication has completed");
    Preconditions.checkArgument(response != null, "Received null response");
    try {
        // parse the response
        // message = [authorizationId] UTF8NUL authenticationId UTF8NUL passwd'
        // authorizationId may be empty,then the authorizationId = authenticationId
        String payload;
        try {
            payload = new String(response, "UTF-8");
        } catch (Exception e) {
            throw new IllegalArgumentException("Received corrupt response", e);
        }
        String[] parts = payload.split("", 3);
        // validate response
        if (parts.length != 3) {
            throw new IllegalArgumentException("Invalid message format, parts must contain 3 items");
        }
        String authorizationId = parts[0];
        String authenticationId = parts[1];
        String passwd = parts[2];
        Preconditions.checkState(authenticationId != null && !authenticationId.isEmpty(), "No authentication identity provided");
        Preconditions.checkState(passwd != null && !passwd.isEmpty(), "No password provided");
        if (authorizationId == null || authorizationId.isEmpty()) {
            authorizationId = authenticationId;
        } else if (!authorizationId.equals(authenticationId)) {
            // TODO(dong): support impersonation
            throw new UnsupportedOperationException("Impersonation is not supported now.");
        }
        NameCallback nameCallback = new NameCallback("User");
        nameCallback.setName(authenticationId);
        PasswordCallback passwordCallback = new PasswordCallback("Password", false);
        passwordCallback.setPassword(passwd.toCharArray());
        AuthorizeCallback authCallback = new AuthorizeCallback(authenticationId, authorizationId);
        Callback[] cbList = { nameCallback, passwordCallback, authCallback };
        mHandler.handle(cbList);
        if (!authCallback.isAuthorized()) {
            throw new SaslException("AuthorizeCallback authorized failure");
        }
        mAuthorizationId = authCallback.getAuthorizedID();
    } catch (Exception e) {
        throw new SaslException("Plain authentication failed: " + e.getMessage(), e);
    }
    mCompleted = true;
    return null;
}
Also used : NameCallback(javax.security.auth.callback.NameCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) AuthorizeCallback(javax.security.sasl.AuthorizeCallback) Callback(javax.security.auth.callback.Callback) PasswordCallback(javax.security.auth.callback.PasswordCallback) SaslException(javax.security.sasl.SaslException) SaslException(javax.security.sasl.SaslException) AuthorizeCallback(javax.security.sasl.AuthorizeCallback)

Example 19 with SaslException

use of javax.security.sasl.SaslException in project ats-framework by Axway.

the class InetSmtpConnection method authenticate.

// -- Authentication --
/**
     * Authenticates the connection using the specified SASL mechanism,
     * username, and password.
     * @param mechanism a SASL authentication mechanism, e.g. LOGIN, PLAIN,
     * CRAM-MD5, GSSAPI
     * @param username the authentication principal
     * @param password the authentication credentials
     * @return true if authentication was successful, false otherwise
     */
public boolean authenticate(String mechanism, String username, String password) throws IOException {
    try {
        String[] m = new String[] { mechanism };
        CallbackHandler ch = new SaslCallbackHandler(username, password);
        // Avoid lengthy callback procedure for GNU Crypto
        HashMap<String, String> p = new HashMap<String, String>();
        p.put("gnu.crypto.sasl.username", username);
        p.put("gnu.crypto.sasl.password", password);
        SaslClient sasl = Sasl.createSaslClient(m, null, "smtp", socket.getInetAddress().getHostName(), p, ch);
        if (sasl == null) {
            // Fall back to home-grown SASL clients
            if ("LOGIN".equalsIgnoreCase(mechanism)) {
                sasl = new SaslLogin(username, password);
            } else if ("PLAIN".equalsIgnoreCase(mechanism)) {
                sasl = new SaslPlain(username, password);
            } else if ("CRAM-MD5".equalsIgnoreCase(mechanism)) {
                sasl = new SaslCramMD5(username, password);
            } else {
                return false;
            }
        }
        StringBuffer cmd = new StringBuffer(AUTH);
        cmd.append(' ');
        cmd.append(mechanism);
        if (sasl.hasInitialResponse()) {
            cmd.append(' ');
            byte[] init = sasl.evaluateChallenge(new byte[0]);
            if (init.length == 0) {
                cmd.append('=');
            } else {
                cmd.append(new String(BASE64.encode(init), "US-ASCII"));
            }
        }
        send(cmd.toString());
        while (true) {
            switch(getAllResponses()) {
                case 334:
                    try {
                        byte[] c0 = response.getBytes("US-ASCII");
                        // challenge
                        byte[] c1 = BASE64.decode(c0);
                        byte[] r0 = sasl.evaluateChallenge(c1);
                        // response
                        byte[] r1 = BASE64.encode(r0);
                        out.write(r1);
                        out.write(0x0d);
                        out.flush();
                        log.trace("> " + new String(r1, "US-ASCII"));
                    } catch (SaslException e) {
                        // Error in SASL challenge evaluation - cancel exchange
                        out.write(0x2a);
                        out.write(0x0d);
                        out.flush();
                        log.trace("> *");
                    }
                    break;
                case 235:
                    String qop = (String) sasl.getNegotiatedProperty(Sasl.QOP);
                    if ("auth-int".equalsIgnoreCase(qop) || "auth-conf".equalsIgnoreCase(qop)) {
                        InputStream is = socket.getInputStream();
                        is = new BufferedInputStream(is);
                        is = new SaslInputStream(sasl, is);
                        is = new CRLFInputStream(is);
                        in = new LineInputStream(is);
                        OutputStream os = socket.getOutputStream();
                        os = new BufferedOutputStream(os);
                        os = new SaslOutputStream(sasl, os);
                        out = new CRLFOutputStream(os);
                    }
                    return true;
                default:
                    return false;
            }
        }
    } catch (SaslException e) {
        log.error(e.getMessage(), e);
        // No provider for mechanism
        return false;
    } catch (RuntimeException e) {
        log.error(e.getMessage(), e);
        // No javax.security.sasl classes
        return false;
    }
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) SaslCallbackHandler(gnu.inet.util.SaslCallbackHandler) SaslInputStream(gnu.inet.util.SaslInputStream) HashMap(java.util.HashMap) CRLFInputStream(gnu.inet.util.CRLFInputStream) BufferedInputStream(java.io.BufferedInputStream) LineInputStream(gnu.inet.util.LineInputStream) SaslInputStream(gnu.inet.util.SaslInputStream) InputStream(java.io.InputStream) BufferedOutputStream(java.io.BufferedOutputStream) MessageOutputStream(gnu.inet.util.MessageOutputStream) OutputStream(java.io.OutputStream) SaslOutputStream(gnu.inet.util.SaslOutputStream) CRLFOutputStream(gnu.inet.util.CRLFOutputStream) SaslException(javax.security.sasl.SaslException) CRLFOutputStream(gnu.inet.util.CRLFOutputStream) SaslClient(javax.security.sasl.SaslClient) SaslPlain(gnu.inet.util.SaslPlain) SaslOutputStream(gnu.inet.util.SaslOutputStream) BufferedInputStream(java.io.BufferedInputStream) SaslCramMD5(gnu.inet.util.SaslCramMD5) SaslCallbackHandler(gnu.inet.util.SaslCallbackHandler) CRLFInputStream(gnu.inet.util.CRLFInputStream) LineInputStream(gnu.inet.util.LineInputStream) BufferedOutputStream(java.io.BufferedOutputStream) SaslLogin(gnu.inet.util.SaslLogin)

Example 20 with SaslException

use of javax.security.sasl.SaslException in project zm-mailbox by Zimbra.

the class GssAuthenticator method initialize.

@Override
public boolean initialize() throws IOException {
    Krb5Keytab keytab = getKeytab(LC.krb5_keytab.value());
    if (keytab == null) {
        sendFailed("mechanism not supported");
        return false;
    }
    debug("keytab file = %s", keytab.getFile());
    final String host;
    if (LC.krb5_service_principal_from_interface_address.booleanValue()) {
        String localSocketHostname = localAddress.getCanonicalHostName().toLowerCase();
        if (localSocketHostname.length() == 0 || Character.isDigit(localSocketHostname.charAt(0)))
            localSocketHostname = LC.zimbra_server_hostname.value();
        host = localSocketHostname;
    } else {
        host = LC.zimbra_server_hostname.value();
    }
    KerberosPrincipal kp = new KerberosPrincipal(getProtocol() + '/' + host);
    debug("kerberos principal = %s", kp);
    Subject subject = getSubject(keytab, kp);
    if (subject == null) {
        sendFailed();
        return false;
    }
    debug("subject = %s", subject);
    final Map<String, String> props = getSaslProperties();
    if (DEBUG && props != null) {
        String qop = props.get(Sasl.QOP);
        debug("Sent QOP = " + (qop != null ? qop : "auth"));
    }
    try {
        mSaslServer = (SaslServer) Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {

            @Override
            public Object run() throws SaslException {
                return Sasl.createSaslServer(getMechanism(), getProtocol(), host, props, new GssCallbackHandler());
            }
        });
    } catch (PrivilegedActionException e) {
        sendFailed();
        getLog().warn("Could not create SaslServer", e.getCause());
        return false;
    }
    return true;
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) PrivilegedActionException(java.security.PrivilegedActionException) SaslException(javax.security.sasl.SaslException) Krb5Keytab(com.zimbra.cs.security.kerberos.Krb5Keytab) Subject(javax.security.auth.Subject)

Aggregations

SaslException (javax.security.sasl.SaslException)70 IOException (java.io.IOException)24 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)12 NameCallback (javax.security.auth.callback.NameCallback)11 Callback (javax.security.auth.callback.Callback)6 PasswordCallback (javax.security.auth.callback.PasswordCallback)6 SaslClient (javax.security.sasl.SaslClient)6 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)5 InvalidKeyException (java.security.InvalidKeyException)5 LoginException (javax.security.auth.login.LoginException)5 AuthorizeCallback (javax.security.sasl.AuthorizeCallback)5 RpcException (org.apache.drill.exec.rpc.RpcException)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 PrivilegedActionException (java.security.PrivilegedActionException)4 CallbackHandler (javax.security.auth.callback.CallbackHandler)4 GSSException (org.ietf.jgss.GSSException)4 UserNotFoundException (org.jivesoftware.openfire.user.UserNotFoundException)4 ByteString (com.google.protobuf.ByteString)3 Principal (java.security.Principal)3 SaslServer (javax.security.sasl.SaslServer)3