Search in sources :

Example 41 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler in project ddf by codice.

the class UsernameTokenValidator method validateToken.

/**
     * Validate a Token using the given TokenValidatorParameters.
     */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOGGER.debug("Validating UsernameToken");
    if (parser == null) {
        throw new IllegalStateException("XMLParser must be configured.");
    }
    if (failedLoginDelayer == null) {
        throw new IllegalStateException("Failed Login Delayer must be configured");
    }
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    Crypto sigCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    requestData.setCallbackHandler(callbackHandler);
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(ReceivedToken.STATE.INVALID);
    response.setToken(validateTarget);
    if (!validateTarget.isUsernameToken()) {
        return response;
    }
    //
    // Turn the JAXB UsernameTokenType into a DOM Element for validation
    //
    UsernameTokenType usernameTokenType = (UsernameTokenType) validateTarget.getToken();
    JAXBElement<UsernameTokenType> tokenType = new JAXBElement<>(QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameTokenType);
    Document doc = DOMUtils.createDocument();
    Element rootElement = doc.createElement("root-element");
    List<String> ctxPath = new ArrayList<>(1);
    ctxPath.add(UsernameTokenType.class.getPackage().getName());
    Element usernameTokenElement = null;
    ParserConfigurator configurator = parser.configureParser(ctxPath, UsernameTokenValidator.class.getClassLoader());
    try {
        parser.marshal(configurator, tokenType, rootElement);
        usernameTokenElement = (Element) rootElement.getFirstChild();
    } catch (ParserException ex) {
        LOGGER.info("Unable to parse username token", ex);
        return response;
    }
    //
    try {
        boolean allowNamespaceQualifiedPasswordTypes = requestData.isAllowNamespaceQualifiedPasswordTypes();
        UsernameToken ut = new UsernameToken(usernameTokenElement, allowNamespaceQualifiedPasswordTypes, new BSPEnforcer());
        // The parsed principal is set independent whether validation is successful or not
        response.setPrincipal(new CustomTokenPrincipal(ut.getName()));
        if (ut.getPassword() == null) {
            failedLoginDelayer.delay(ut.getName());
            return response;
        }
        Credential credential = new Credential();
        credential.setUsernametoken(ut);
        //Only this section is new, the rest is copied from the apache class
        Set<Map.Entry<String, Validator>> entries = validators.entrySet();
        for (Map.Entry<String, Validator> entry : entries) {
            try {
                entry.getValue().validate(credential, requestData);
                validateTarget.setState(ReceivedToken.STATE.VALID);
                break;
            } catch (WSSecurityException ex) {
                LOGGER.debug("Unable to validate user against {}" + entry.getKey(), ex);
            }
        }
        if (ReceivedToken.STATE.INVALID.equals(validateTarget.getState())) {
            failedLoginDelayer.delay(ut.getName());
            return response;
        }
        //end new section
        Principal principal = createPrincipal(ut.getName(), ut.getPassword(), ut.getPasswordType(), ut.getNonce(), ut.getCreated());
        response.setPrincipal(principal);
        response.setTokenRealm(null);
        validateTarget.setState(ReceivedToken.STATE.VALID);
        validateTarget.setPrincipal(principal);
    } catch (WSSecurityException ex) {
        LOGGER.debug("Unable to validate token.", ex);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) Document(org.w3c.dom.Document) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) JAASUsernameTokenValidator(org.apache.wss4j.dom.validate.JAASUsernameTokenValidator) RequestData(org.apache.wss4j.dom.handler.RequestData) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) ParserException(org.codice.ddf.parser.ParserException) Credential(org.apache.wss4j.dom.validate.Credential) UsernameTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType) BSPEnforcer(org.apache.wss4j.common.bsp.BSPEnforcer) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) JAXBElement(javax.xml.bind.JAXBElement) ParserConfigurator(org.codice.ddf.parser.ParserConfigurator) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Validator(org.apache.wss4j.dom.validate.Validator) JAASUsernameTokenValidator(org.apache.wss4j.dom.validate.JAASUsernameTokenValidator) TokenValidator(org.apache.cxf.sts.token.validator.TokenValidator) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Principal(java.security.Principal)

Example 42 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler in project storm by apache.

the class PlainSaslTransportPlugin method getServerTransportFactory.

@Override
protected TTransportFactory getServerTransportFactory() throws IOException {
    //create an authentication callback handler
    CallbackHandler serverCallbackHandler = new PlainServerCallbackHandler();
    if (Security.getProvider(SaslPlainServer.SecurityProvider.SASL_PLAIN_SERVER) == null) {
        Security.addProvider(new SaslPlainServer.SecurityProvider());
    }
    //create a transport factory that will invoke our auth callback for digest
    TSaslServerTransport.Factory factory = new TSaslServerTransport.Factory();
    factory.addServerDefinition(PLAIN, AuthUtils.SERVICE, "localhost", null, serverCallbackHandler);
    LOG.info("SASL PLAIN transport factory will be used");
    return factory;
}
Also used : TSaslServerTransport(org.apache.thrift.transport.TSaslServerTransport) CallbackHandler(javax.security.auth.callback.CallbackHandler) LoggerFactory(org.slf4j.LoggerFactory) TTransportFactory(org.apache.thrift.transport.TTransportFactory)

Example 43 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler in project jetty.project by eclipse.

the class JAASLoginService method login.

/* ------------------------------------------------------------ */
@Override
public UserIdentity login(final String username, final Object credentials, final ServletRequest request) {
    try {
        CallbackHandler callbackHandler = null;
        if (_callbackHandlerClass == null) {
            callbackHandler = new CallbackHandler() {

                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                    for (Callback callback : callbacks) {
                        if (callback instanceof NameCallback) {
                            ((NameCallback) callback).setName(username);
                        } else if (callback instanceof PasswordCallback) {
                            ((PasswordCallback) callback).setPassword((char[]) credentials.toString().toCharArray());
                        } else if (callback instanceof ObjectCallback) {
                            ((ObjectCallback) callback).setObject(credentials);
                        } else if (callback instanceof RequestParameterCallback) {
                            RequestParameterCallback rpc = (RequestParameterCallback) callback;
                            if (request != null)
                                rpc.setParameterValues(Arrays.asList(request.getParameterValues(rpc.getParameterName())));
                        } else
                            throw new UnsupportedCallbackException(callback);
                    }
                }
            };
        } else {
            Class<?> clazz = Loader.loadClass(_callbackHandlerClass);
            callbackHandler = (CallbackHandler) clazz.newInstance();
        }
        //set up the login context
        //TODO jaspi requires we provide the Configuration parameter
        Subject subject = new Subject();
        LoginContext loginContext = new LoginContext(_loginModuleName, subject, callbackHandler);
        loginContext.login();
        //login success
        JAASUserPrincipal userPrincipal = new JAASUserPrincipal(getUserName(callbackHandler), subject, loginContext);
        subject.getPrincipals().add(userPrincipal);
        return _identityService.newUserIdentity(subject, userPrincipal, getGroups(subject));
    } catch (LoginException e) {
        LOG.warn(e);
    } catch (IOException e) {
        LOG.warn(e);
    } catch (UnsupportedCallbackException e) {
        LOG.warn(e);
    } catch (InstantiationException e) {
        LOG.warn(e);
    } catch (IllegalAccessException e) {
        LOG.warn(e);
    } catch (ClassNotFoundException e) {
        LOG.warn(e);
    }
    return null;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) ObjectCallback(org.eclipse.jetty.jaas.callback.ObjectCallback) IOException(java.io.IOException) Subject(javax.security.auth.Subject) ObjectCallback(org.eclipse.jetty.jaas.callback.ObjectCallback) RequestParameterCallback(org.eclipse.jetty.jaas.callback.RequestParameterCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) LoginContext(javax.security.auth.login.LoginContext) PasswordCallback(javax.security.auth.callback.PasswordCallback) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) RequestParameterCallback(org.eclipse.jetty.jaas.callback.RequestParameterCallback)

Example 44 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler in project Smack by igniterealtime.

the class XMPPTCPConnection method proceedTLSReceived.

/**
     * The server has indicated that TLS negotiation can start. We now need to secure the
     * existing plain connection and perform a handshake. This method won't return until the
     * connection has finished the handshake or an error occurred while securing the connection.
     * @throws IOException 
     * @throws CertificateException 
     * @throws NoSuchAlgorithmException 
     * @throws NoSuchProviderException 
     * @throws KeyStoreException 
     * @throws UnrecoverableKeyException 
     * @throws KeyManagementException 
     * @throws SmackException 
     * @throws Exception if an exception occurs.
     */
@SuppressWarnings("LiteralClassName")
private void proceedTLSReceived() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException, KeyManagementException, SmackException {
    SSLContext context = this.config.getCustomSSLContext();
    KeyStore ks = null;
    KeyManager[] kms = null;
    PasswordCallback pcb = null;
    SmackDaneVerifier daneVerifier = null;
    if (config.getDnssecMode() == DnssecMode.needsDnssecAndDane) {
        SmackDaneProvider daneProvider = DNSUtil.getDaneProvider();
        if (daneProvider == null) {
            throw new UnsupportedOperationException("DANE enabled but no SmackDaneProvider configured");
        }
        daneVerifier = daneProvider.newInstance();
        if (daneVerifier == null) {
            throw new IllegalStateException("DANE requested but DANE provider did not return a DANE verifier");
        }
    }
    if (context == null) {
        final String keyStoreType = config.getKeystoreType();
        final CallbackHandler callbackHandler = config.getCallbackHandler();
        final String keystorePath = config.getKeystorePath();
        if ("PKCS11".equals(keyStoreType)) {
            try {
                Constructor<?> c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class);
                String pkcs11Config = "name = SmartCard\nlibrary = " + config.getPKCS11Library();
                ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes(StringUtils.UTF8));
                Provider p = (Provider) c.newInstance(config);
                Security.addProvider(p);
                ks = KeyStore.getInstance("PKCS11", p);
                pcb = new PasswordCallback("PKCS11 Password: ", false);
                callbackHandler.handle(new Callback[] { pcb });
                ks.load(null, pcb.getPassword());
            } catch (Exception e) {
                LOGGER.log(Level.WARNING, "Exception", e);
                ks = null;
            }
        } else if ("Apple".equals(keyStoreType)) {
            ks = KeyStore.getInstance("KeychainStore", "Apple");
            ks.load(null, null);
        //pcb = new PasswordCallback("Apple Keychain",false);
        //pcb.setPassword(null);
        } else if (keyStoreType != null) {
            ks = KeyStore.getInstance(keyStoreType);
            if (callbackHandler != null && StringUtils.isNotEmpty(keystorePath)) {
                try {
                    pcb = new PasswordCallback("Keystore Password: ", false);
                    callbackHandler.handle(new Callback[] { pcb });
                    ks.load(new FileInputStream(keystorePath), pcb.getPassword());
                } catch (Exception e) {
                    LOGGER.log(Level.WARNING, "Exception", e);
                    ks = null;
                }
            } else {
                ks.load(null, null);
            }
        }
        if (ks != null) {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            try {
                if (pcb == null) {
                    kmf.init(ks, null);
                } else {
                    kmf.init(ks, pcb.getPassword());
                    pcb.clearPassword();
                }
                kms = kmf.getKeyManagers();
            } catch (NullPointerException npe) {
                LOGGER.log(Level.WARNING, "NullPointerException", npe);
            }
        }
        // If the user didn't specify a SSLContext, use the default one
        context = SSLContext.getInstance("TLS");
        final SecureRandom secureRandom = new java.security.SecureRandom();
        X509TrustManager customTrustManager = config.getCustomX509TrustManager();
        if (daneVerifier != null) {
            // User requested DANE verification.
            daneVerifier.init(context, kms, customTrustManager, secureRandom);
        } else {
            TrustManager[] customTrustManagers = null;
            if (customTrustManager != null) {
                customTrustManagers = new TrustManager[] { customTrustManager };
            }
            context.init(kms, customTrustManagers, secureRandom);
        }
    }
    Socket plain = socket;
    // Secure the plain connection
    socket = context.getSocketFactory().createSocket(plain, host, plain.getPort(), true);
    final SSLSocket sslSocket = (SSLSocket) socket;
    // Immediately set the enabled SSL protocols and ciphers. See SMACK-712 why this is
    // important (at least on certain platforms) and it seems to be a good idea anyways to
    // prevent an accidental implicit handshake.
    TLSUtils.setEnabledProtocolsAndCiphers(sslSocket, config.getEnabledSSLProtocols(), config.getEnabledSSLCiphers());
    // Initialize the reader and writer with the new secured version
    initReaderAndWriter();
    // Proceed to do the handshake
    sslSocket.startHandshake();
    if (daneVerifier != null) {
        daneVerifier.finish(sslSocket);
    }
    final HostnameVerifier verifier = getConfiguration().getHostnameVerifier();
    if (verifier == null) {
        throw new IllegalStateException("No HostnameVerifier set. Use connectionConfiguration.setHostnameVerifier() to configure.");
    } else if (!verifier.verify(getXMPPServiceDomain().toString(), sslSocket.getSession())) {
        throw new CertificateException("Hostname verification of certificate failed. Certificate does not authenticate " + getXMPPServiceDomain());
    }
    // Set that TLS was successful
    secureSocket = sslSocket;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) SSLSocket(javax.net.ssl.SSLSocket) SmackDaneProvider(org.jivesoftware.smack.util.dns.SmackDaneProvider) CertificateException(java.security.cert.CertificateException) PasswordCallback(javax.security.auth.callback.PasswordCallback) KeyManager(javax.net.ssl.KeyManager) SmackDaneVerifier(org.jivesoftware.smack.util.dns.SmackDaneVerifier) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) FailedNonzaException(org.jivesoftware.smack.XMPPException.FailedNonzaException) XmppStringprepException(org.jxmpp.stringprep.XmppStringprepException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) XMPPException(org.jivesoftware.smack.XMPPException) ConnectionException(org.jivesoftware.smack.SmackException.ConnectionException) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) StreamErrorException(org.jivesoftware.smack.XMPPException.StreamErrorException) NoResponseException(org.jivesoftware.smack.SmackException.NoResponseException) IOException(java.io.IOException) SmackException(org.jivesoftware.smack.SmackException) StreamManagementException(org.jivesoftware.smack.sm.StreamManagementException) AlreadyLoggedInException(org.jivesoftware.smack.SmackException.AlreadyLoggedInException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) StreamIdDoesNotMatchException(org.jivesoftware.smack.sm.StreamManagementException.StreamIdDoesNotMatchException) StreamManagementNotEnabledException(org.jivesoftware.smack.sm.StreamManagementException.StreamManagementNotEnabledException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) SecurityRequiredByServerException(org.jivesoftware.smack.SmackException.SecurityRequiredByServerException) AlreadyConnectedException(org.jivesoftware.smack.SmackException.AlreadyConnectedException) NoSuchProviderException(java.security.NoSuchProviderException) FileInputStream(java.io.FileInputStream) SmackDaneProvider(org.jivesoftware.smack.util.dns.SmackDaneProvider) Provider(java.security.Provider) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManager(javax.net.ssl.TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) ByteArrayInputStream(java.io.ByteArrayInputStream) X509TrustManager(javax.net.ssl.X509TrustManager) SSLSocket(javax.net.ssl.SSLSocket) Socket(java.net.Socket)

Example 45 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler in project Smack by igniterealtime.

the class SASLAuthentication method authenticate.

/**
     * Performs SASL authentication of the specified user. If SASL authentication was successful
     * then resource binding and session establishment will be performed. This method will return
     * the full JID provided by the server while binding a resource to the connection.<p>
     *
     * The server may assign a full JID with a username or resource different than the requested
     * by this method.
     *
     * @param username the username that is authenticating with the server.
     * @param password the password to send to the server.
     * @param authzid the authorization identifier (typically null).
     * @param sslSession the optional SSL/TLS session (if one was established)
     * @throws XMPPErrorException
     * @throws SASLErrorException
     * @throws IOException
     * @throws SmackException
     * @throws InterruptedException
     */
public void authenticate(String username, String password, EntityBareJid authzid, SSLSession sslSession) throws XMPPErrorException, SASLErrorException, IOException, SmackException, InterruptedException {
    currentMechanism = selectMechanism(authzid);
    final CallbackHandler callbackHandler = configuration.getCallbackHandler();
    final String host = connection.getHost();
    final DomainBareJid xmppServiceDomain = connection.getXMPPServiceDomain();
    synchronized (this) {
        if (callbackHandler != null) {
            currentMechanism.authenticate(host, xmppServiceDomain, callbackHandler, authzid, sslSession);
        } else {
            currentMechanism.authenticate(username, host, xmppServiceDomain, password, authzid, sslSession);
        }
        final long deadline = System.currentTimeMillis() + connection.getReplyTimeout();
        while (!authenticationSuccessful && saslException == null) {
            final long now = System.currentTimeMillis();
            if (now >= deadline)
                break;
            // Wait until SASL negotiation finishes
            wait(deadline - now);
        }
    }
    if (saslException != null) {
        if (saslException instanceof SmackException) {
            throw (SmackException) saslException;
        } else if (saslException instanceof SASLErrorException) {
            throw (SASLErrorException) saslException;
        } else {
            throw new IllegalStateException("Unexpected exception type", saslException);
        }
    }
    if (!authenticationSuccessful) {
        throw NoResponseException.newWith(connection, "successful SASL authentication");
    }
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) SASLErrorException(org.jivesoftware.smack.sasl.SASLErrorException) DomainBareJid(org.jxmpp.jid.DomainBareJid)

Aggregations

CallbackHandler (javax.security.auth.callback.CallbackHandler)89 IOException (java.io.IOException)38 Callback (javax.security.auth.callback.Callback)36 PasswordCallback (javax.security.auth.callback.PasswordCallback)30 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)27 HashMap (java.util.HashMap)25 Subject (javax.security.auth.Subject)24 NameCallback (javax.security.auth.callback.NameCallback)22 LoginContext (javax.security.auth.login.LoginContext)17 LoginException (javax.security.auth.login.LoginException)15 Test (org.junit.Test)15 Map (java.util.Map)10 URL (java.net.URL)8 RealmCallback (javax.security.sasl.RealmCallback)7 QName (javax.xml.namespace.QName)6 Service (javax.xml.ws.Service)6 WSS4JOutInterceptor (org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor)6 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)5 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)5 TokenValidatorResponse (org.apache.cxf.sts.token.validator.TokenValidatorResponse)5