Example usage for javax.security.sasl Sasl createSaslServer

List of usage examples for javax.security.sasl Sasl createSaslServer

Introduction

In this page you can find the example usage for javax.security.sasl Sasl createSaslServer.

Prototype

public static SaslServer createSaslServer(String mechanism, String protocol, String serverName,
        Map<String, ?> props, javax.security.auth.callback.CallbackHandler cbh) throws SaslException 

Source Link

Document

Creates a SaslServer for the specified mechanism.

Usage

From source file:backtype.storm.messaging.netty.SaslNettyServer.java

SaslNettyServer(String topologyName, byte[] token) throws IOException {
    LOG.debug("SaslNettyServer: Topology token is: " + topologyName + " with authmethod "
            + SaslUtils.AUTH_DIGEST_MD5);

    try {//from   w  w w . ja v  a 2  s . c  o  m

        SaslDigestCallbackHandler ch = new SaslNettyServer.SaslDigestCallbackHandler(topologyName, token);

        saslServer = Sasl.createSaslServer(SaslUtils.AUTH_DIGEST_MD5, null, SaslUtils.DEFAULT_REALM,
                SaslUtils.getSaslProps(), ch);

    } catch (SaslException e) {
        LOG.error("SaslNettyServer: Could not create SaslServer: " + e);
    }

}

From source file:com.delphix.session.sasl.DigestServer.java

@Override
public SaslServer create(String protocol, String server) throws SaslException {
    CallbackHandler handler = new DigestServerHandler();
    return Sasl.createSaslServer(getMechanism(), protocol, server, getProperties(), handler);
}

From source file:com.zimbra.cs.security.sasl.GssAuthenticator.java

@Override
public boolean initialize() throws IOException {
    Krb5Keytab keytab = getKeytab(LC.krb5_keytab.value());
    if (keytab == null) {
        sendFailed("mechanism not supported");
        return false;
    }// w  ww .j av  a  2 s.co m
    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;
}

From source file:com.ettrema.ldap.LdapConnection.java

protected void _handleRequest(byte[] inbuf, int offset) throws IOException {
    //dumpBer(inbuf, offset);
    BerDecoder reqBer = new BerDecoder(inbuf, 0, offset);
    int currentMessageId = 0;
    try {/*from  ww  w. j ava 2  s  .c  o m*/
        reqBer.parseSeq(null);
        currentMessageId = reqBer.parseInt();
        int requestOperation = reqBer.peekByte();

        if (requestOperation == Ldap.LDAP_REQ_BIND) {
            reqBer.parseSeq(null);
            responseHandler.setVersion(reqBer.parseInt());
            userName = reqBer.parseString(responseHandler.isLdapV3());
            if (reqBer.peekByte() == (Ber.ASN_CONTEXT | Ber.ASN_CONSTRUCTOR | 3)) {
                // SASL authentication
                reqBer.parseSeq(null);
                // Get mechanism, usually DIGEST-MD5
                String mechanism = reqBer.parseString(responseHandler.isLdapV3());

                byte[] serverResponse;
                CallbackHandler callbackHandler = new CallbackHandler() {

                    @Override
                    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                        // look for username in callbacks
                        for (Callback callback : callbacks) {
                            if (callback instanceof NameCallback) {
                                userName = ((NameCallback) callback).getDefaultName();
                                // get password from session pool
                                password = userFactory.getUserPassword(userName);
                            }
                        }
                        // handle other callbacks
                        for (Callback callback : callbacks) {
                            if (callback instanceof AuthorizeCallback) {
                                ((AuthorizeCallback) callback).setAuthorized(true);
                            } else if (callback instanceof PasswordCallback) {
                                if (password != null) {
                                    ((PasswordCallback) callback).setPassword(password.toCharArray());
                                }
                            }
                        }
                    }
                };
                int status;
                if (reqBer.bytesLeft() > 0 && saslServer != null) {
                    byte[] clientResponse = reqBer.parseOctetString(Ber.ASN_OCTET_STR, null);
                    serverResponse = saslServer.evaluateResponse(clientResponse);
                    status = Ldap.LDAP_SUCCESS;

                    LogUtils.debug(log, "LOG_LDAP_REQ_BIND_USER", currentMessageId, userName);
                    user = userFactory.getUser(userName, password);
                    LogUtils.debug(log, "LOG_LDAP_REQ_BIND_SUCCESS");

                } else {
                    Map<String, String> properties = new HashMap<String, String>();
                    properties.put("javax.security.sasl.qop", "auth,auth-int");
                    saslServer = Sasl.createSaslServer(mechanism, "ldap",
                            client.getLocalAddress().getHostAddress(), properties, callbackHandler);
                    serverResponse = saslServer.evaluateResponse(EMPTY_BYTE_ARRAY);
                    status = Ldap.LDAP_SASL_BIND_IN_PROGRESS;
                }
                responseHandler.sendBindResponse(currentMessageId, status, serverResponse);

            } else {
                password = reqBer.parseStringWithTag(Ber.ASN_CONTEXT, responseHandler.isLdapV3(), null);

                if (userName.length() > 0 && password.length() > 0) {
                    log.debug("LOG_LDAP_REQ_BIND_USER", currentMessageId, userName);
                    try {
                        user = userFactory.getUser(userName, password);
                        LogUtils.debug(log, "LOG_LDAP_REQ_BIND_SUCCESS");
                        responseHandler.sendClient(currentMessageId, Ldap.LDAP_REP_BIND, Ldap.LDAP_SUCCESS, "");
                    } catch (IOException e) {
                        LogUtils.debug(log, "LOG_LDAP_REQ_BIND_INVALID_CREDENTIALS");
                        responseHandler.sendClient(currentMessageId, Ldap.LDAP_REP_BIND,
                                Ldap.LDAP_INVALID_CREDENTIALS, "");
                    }
                } else {
                    LogUtils.debug(log, "LOG_LDAP_REQ_BIND_ANONYMOUS", currentMessageId);
                    // anonymous bind
                    responseHandler.sendClient(currentMessageId, Ldap.LDAP_REP_BIND, Ldap.LDAP_SUCCESS, "");
                }
            }

        } else if (requestOperation == Ldap.LDAP_REQ_UNBIND) {
            log.debug("LOG_LDAP_REQ_UNBIND", currentMessageId);
            if (user != null) {
                user = null;
            }
        } else if (requestOperation == Ldap.LDAP_REQ_SEARCH) {
            reqBer.parseSeq(null);
            String dn = reqBer.parseString(responseHandler.isLdapV3());
            int scope = reqBer.parseEnumeration();
            /*
             * int derefAliases =
             */
            reqBer.parseEnumeration();
            int sizeLimit = reqBer.parseInt();
            if (sizeLimit > 100 || sizeLimit == 0) {
                sizeLimit = 100;
            }
            int timelimit = reqBer.parseInt();
            /*
             * boolean typesOnly =
             */
            reqBer.parseBoolean();
            LdapFilter ldapFilter = ldapParser.parseFilter(reqBer, user, userName);
            Set<String> returningAttributes = ldapParser.parseReturningAttributes(reqBer);
            SearchRunnable searchRunnable = new SearchRunnable(userFactory, propertyMapper, currentMessageId,
                    dn, scope, sizeLimit, timelimit, ldapFilter, returningAttributes, responseHandler, user,
                    searchManager);
            if (Ldap.BASE_CONTEXT.equalsIgnoreCase(dn) || Ldap.OD_USER_CONTEXT.equalsIgnoreCase(dn)
                    || Ldap.OD_USER_CONTEXT_LION.equalsIgnoreCase(dn)) {
                // launch search in a separate thread
                searchManager.beginAsyncSearch(this, currentMessageId, searchRunnable);
            } else {
                // no need to create a separate thread, just run
                searchManager.search(this, searchRunnable);
            }

        } else if (requestOperation == Ldap.LDAP_REQ_ABANDON) {
            searchManager.abandonSearch(this, currentMessageId, reqBer);
        } else {
            LogUtils.debug(log, "LOG_LDAP_UNSUPPORTED_OPERATION", requestOperation);
            responseHandler.sendClient(currentMessageId, Ldap.LDAP_REP_RESULT, Ldap.LDAP_OTHER,
                    "Unsupported operation");
        }
    } catch (IOException e) {
        responseHandler.dumpBer(inbuf, offset);
        try {
            responseHandler.sendErr(currentMessageId, Ldap.LDAP_REP_RESULT, e);
        } catch (IOException e2) {
            log.debug("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT", e2);
        }
        throw e;
    }
}

From source file:io.milton.ldap.LdapConnection.java

protected void _handleRequest(byte[] inbuf, int offset) throws IOException {
    //dumpBer(inbuf, offset);
    BerDecoder reqBer = new BerDecoder(inbuf, 0, offset);
    int currentMessageId = 0;
    try {//from  w w w. jav a 2s.c o m
        reqBer.parseSeq(null);
        currentMessageId = reqBer.parseInt();
        int requestOperation = reqBer.peekByte();

        if (requestOperation == Ldap.LDAP_REQ_BIND) {
            reqBer.parseSeq(null);
            responseHandler.setVersion(reqBer.parseInt());
            userName = reqBer.parseString(responseHandler.isLdapV3());
            log.info("Bind user name: " + userName);
            if (reqBer.peekByte() == (Ber.ASN_CONTEXT | Ber.ASN_CONSTRUCTOR | 3)) {
                // SASL authentication
                reqBer.parseSeq(null);
                // Get mechanism, usually DIGEST-MD5
                String mechanism = reqBer.parseString(responseHandler.isLdapV3());

                byte[] serverResponse;
                CallbackHandler callbackHandler = new CallbackHandler() {

                    @Override
                    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                        // look for username in callbacks
                        for (Callback callback : callbacks) {
                            if (callback instanceof NameCallback) {
                                userName = ((NameCallback) callback).getDefaultName();
                                // get password from session pool
                                password = userFactory.getUserPassword(userName);
                            }
                        }
                        // handle other callbacks
                        for (Callback callback : callbacks) {
                            if (callback instanceof AuthorizeCallback) {
                                ((AuthorizeCallback) callback).setAuthorized(true);
                            } else if (callback instanceof PasswordCallback) {
                                if (password != null) {
                                    ((PasswordCallback) callback).setPassword(password.toCharArray());
                                }
                            }
                        }
                    }
                };
                int status;
                if (reqBer.bytesLeft() > 0 && saslServer != null) {
                    byte[] clientResponse = reqBer.parseOctetString(Ber.ASN_OCTET_STR, null);
                    serverResponse = saslServer.evaluateResponse(clientResponse);
                    status = Ldap.LDAP_SUCCESS;

                    LogUtils.debug(log, "LOG_LDAP_REQ_BIND_USER", currentMessageId, userName);
                    user = userFactory.getUser(userName, password);
                    if (user != null) {
                        LogUtils.debug(log, "LOG_LDAP_REQ_BIND_SUCCESS");
                    } else {
                        LogUtils.debug(log, "LOG_LDAP_REQ_BIND", "No user! " + userName);
                    }

                } else {
                    Map<String, String> properties = new HashMap<String, String>();
                    properties.put("javax.security.sasl.qop", "auth,auth-int");
                    saslServer = Sasl.createSaslServer(mechanism, "ldap",
                            client.getLocalAddress().getHostAddress(), properties, callbackHandler);
                    serverResponse = saslServer.evaluateResponse(EMPTY_BYTE_ARRAY);
                    status = Ldap.LDAP_SASL_BIND_IN_PROGRESS;
                }
                responseHandler.sendBindResponse(currentMessageId, status, serverResponse);

            } else {
                password = reqBer.parseStringWithTag(Ber.ASN_CONTEXT, responseHandler.isLdapV3(), null);

                if (userName.length() > 0 && password.length() > 0) {
                    log.debug("LOG_LDAP_REQ_BIND_USER", currentMessageId, userName);
                    try {
                        user = userFactory.getUser(userName, password);
                        LogUtils.debug(log, "LOG_LDAP_REQ_BIND_SUCCESS");
                        responseHandler.sendClient(currentMessageId, Ldap.LDAP_REP_BIND, Ldap.LDAP_SUCCESS, "");
                    } catch (IOException e) {
                        LogUtils.debug(log, "LOG_LDAP_REQ_BIND_INVALID_CREDENTIALS");
                        responseHandler.sendClient(currentMessageId, Ldap.LDAP_REP_BIND,
                                Ldap.LDAP_INVALID_CREDENTIALS, "");
                    }
                } else {
                    LogUtils.debug(log, "LOG_LDAP_REQ_BIND_ANONYMOUS", currentMessageId);
                    // anonymous bind
                    responseHandler.sendClient(currentMessageId, Ldap.LDAP_REP_BIND, Ldap.LDAP_SUCCESS, "");
                }
            }

        } else if (requestOperation == Ldap.LDAP_REQ_UNBIND) {
            log.debug("LOG_LDAP_REQ_UNBIND", currentMessageId);
            if (user != null) {
                user = null;
            }
        } else if (requestOperation == Ldap.LDAP_REQ_SEARCH) {
            reqBer.parseSeq(null);
            String dn = reqBer.parseString(responseHandler.isLdapV3());
            log.info("Parsed DN: " + dn);
            int scope = reqBer.parseEnumeration();
            /*
             * int derefAliases =
             */
            reqBer.parseEnumeration();
            int sizeLimit = reqBer.parseInt();
            if (sizeLimit > 100 || sizeLimit == 0) {
                sizeLimit = 100;
            }
            int timelimit = reqBer.parseInt();
            /*
             * boolean typesOnly =
             */
            reqBer.parseBoolean();
            LdapFilter ldapFilter = ldapParser.parseFilter(reqBer, user, userName);
            Set<String> returningAttributes = ldapParser.parseReturningAttributes(reqBer);
            SearchRunnable searchRunnable = new SearchRunnable(userFactory, propertyMapper, currentMessageId,
                    dn, scope, sizeLimit, timelimit, ldapFilter, returningAttributes, responseHandler, user,
                    searchManager);
            if (Ldap.BASE_CONTEXT.equalsIgnoreCase(dn) || Ldap.OD_USER_CONTEXT.equalsIgnoreCase(dn)
                    || Ldap.OD_USER_CONTEXT_LION.equalsIgnoreCase(dn)) {
                // launch search in a separate thread
                searchManager.beginAsyncSearch(this, currentMessageId, searchRunnable);
            } else {
                // no need to create a separate thread, just run
                searchManager.search(this, searchRunnable);
            }

        } else if (requestOperation == Ldap.LDAP_REQ_ABANDON) {
            searchManager.abandonSearch(this, currentMessageId, reqBer);
        } else {
            LogUtils.debug(log, "LOG_LDAP_UNSUPPORTED_OPERATION", requestOperation);
            responseHandler.sendClient(currentMessageId, Ldap.LDAP_REP_RESULT, Ldap.LDAP_OTHER,
                    "Unsupported operation");
        }
    } catch (IOException e) {
        responseHandler.dumpBer(inbuf, offset);
        try {
            responseHandler.sendErr(currentMessageId, Ldap.LDAP_REP_RESULT, e);
        } catch (IOException e2) {
            log.debug("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT", e2);
        }
        throw e;
    }
}

From source file:org.apache.giraph.comm.netty.SaslNettyServer.java

/**
 * Constructor/*ww w .jav a2 s. c om*/
 *
 * @param secretManager supplied by SaslServerHandler.
 */
public SaslNettyServer(JobTokenSecretManager secretManager) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("SaslNettyServer: Secret manager is: " + secretManager);
    }
    /*if[HADOOP_1_SECRET_MANAGER]
    else[HADOOP_1_SECRET_MANAGER]*/
    try {
        secretManager.checkAvailableForRead();
    } catch (StandbyException e) {
        LOG.error("SaslNettyServer: Could not read secret manager: " + e);
    }
    /*end[HADOOP_1_SECRET_MANAGER]*/
    try {
        SaslDigestCallbackHandler ch = new SaslNettyServer.SaslDigestCallbackHandler(secretManager);
        saslServer = Sasl.createSaslServer(SaslNettyServer.AuthMethod.DIGEST.getMechanismName(), null,
                SaslRpcServer.SASL_DEFAULT_REALM, SaslRpcServer.SASL_PROPS, ch);
    } catch (SaslException e) {
        LOG.error("SaslNettyServer: Could not create SaslServer: " + e);
    }
}

From source file:org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferEncryptor.java

/**
 * Factory method for DNs, where the nonce, keyId, and encryption key are not
 * yet known. The nonce and keyId will be sent by the client, and the DN
 * will then use those pieces of info and the secret key shared with the NN
 * to determine the encryptionKey used for the SASL handshake/encryption.
 * /*from w w w  .  j ava2 s.c  o  m*/
 * Establishes a secure connection assuming that the party on the other end
 * has the same shared secret. This does a SASL connection handshake, but not
 * a general-purpose one. It's specific to the MD5-DIGEST SASL mechanism with
 * auth-conf enabled. In particular, it doesn't support an arbitrary number of
 * challenge/response rounds, and we know that the client will never have an
 * initial response, so we don't check for one.
 *
 * @param underlyingOut output stream to write to the other party
 * @param underlyingIn input stream to read from the other party
 * @param blockPoolTokenSecretManager secret manager capable of constructing
 *        encryption key based on keyId, blockPoolId, and nonce
 * @return a pair of streams which wrap the given streams and encrypt/decrypt
 *         all data read/written
 * @throws IOException in the event of error
 */
public static IOStreamPair getEncryptedStreams(OutputStream underlyingOut, InputStream underlyingIn,
        BlockPoolTokenSecretManager blockPoolTokenSecretManager, String encryptionAlgorithm)
        throws IOException {

    DataInputStream in = new DataInputStream(underlyingIn);
    DataOutputStream out = new DataOutputStream(underlyingOut);

    Map<String, String> saslProps = Maps.newHashMap(SASL_PROPS);
    saslProps.put("com.sun.security.sasl.digest.cipher", encryptionAlgorithm);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Server using encryption algorithm " + encryptionAlgorithm);
    }

    SaslParticipant sasl = new SaslParticipant(Sasl.createSaslServer(MECHANISM, PROTOCOL, SERVER_NAME,
            saslProps, new SaslServerCallbackHandler(blockPoolTokenSecretManager)));

    int magicNumber = in.readInt();
    if (magicNumber != ENCRYPTED_TRANSFER_MAGIC_NUMBER) {
        throw new InvalidMagicNumberException(magicNumber);
    }
    try {
        // step 1
        performSaslStep1(out, in, sasl);

        // step 2 (server-side only)
        byte[] remoteResponse = readSaslMessage(in);
        byte[] localResponse = sasl.evaluateChallengeOrResponse(remoteResponse);
        sendSaslMessage(out, localResponse);

        // SASL handshake is complete
        checkSaslComplete(sasl);

        return sasl.createEncryptedStreamPair(out, in);
    } catch (IOException ioe) {
        if (ioe instanceof SaslException && ioe.getCause() != null
                && ioe.getCause() instanceof InvalidEncryptionKeyException) {
            // This could just be because the client is long-lived and hasn't gotten
            // a new encryption key from the NN in a while. Upon receiving this
            // error, the client will get a new encryption key from the NN and retry
            // connecting to this DN.
            sendInvalidKeySaslErrorMessage(out, ioe.getCause().getMessage());
        } else {
            sendGenericSaslErrorMessage(out, ioe.getMessage());
        }
        throw ioe;
    }
}

From source file:org.apache.hadoop.io.crypto.bee.key.sasl.KeySaslServer.java

public KeySaslServer(UUID uuid, KeyToken keyToken) throws SaslException {
    this.uuid = uuid;
    this.keyToken = keyToken;
    propsServer.put(Sasl.QOP, "auth-conf,auth-int,auth");
    saslSrv = Sasl.createSaslServer("DIGEST-MD5", SaslUtil.KEY_SERVICE, SaslUtil.KEY_REALM, propsServer,
            new ServerCallbackHandler(this.keyToken));
    saslAuthStatus = SaslUtil.SaslAuthStatus.AUTH_PROCESSING;
    this.ttl = new java.util.Date().getTime() + SaslUtil.SASL_ENTRY_TTL;
}

From source file:org.wildfly.security.sasl.entity.EntityTest.java

@Test
public void testServerAuthIndirect_Server() throws Exception {
    Map<String, Object> props = new HashMap<String, Object>();

    // No properties are set, an appropriate EntitySaslServer should be returned
    SaslServer server = Sasl.createSaslServer(SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC,
            "TestProtocol", "TestServer", props, null);
    assertEquals(EntitySaslServer.class, server.getClass());
    assertEquals(SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC, server.getMechanismName());

    // If we set SERVER_AUTH to true even though a unilateral mechanism is specified, no server should be returned
    props.put(Sasl.SERVER_AUTH, Boolean.toString(true));
    server = Sasl.createSaslServer(SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC, "TestProtocol",
            "TestServer", props, null);
    assertNull(server);// ww w .j  a v a2  s .c om
}

From source file:org.wso2.andes.server.security.auth.manager.PrincipalDatabaseAuthenticationManager.java

public SaslServer createSaslServer(String mechanism, String localFQDN) throws SaslException {
    return Sasl.createSaslServer(mechanism, "AMQP", localFQDN, _serverCreationProperties.get(mechanism),
            _callbackHandlerMap.get(mechanism));
}