Search in sources :

Example 36 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler in project jdk8u_jdk by JetBrains.

the class RefreshKrb5Config method main.

public static void main(String[] args) throws LoginException, IOException {
    Map<String, String> principals = new HashMap<>();
    principals.put(USER_PRINCIPAL, USER_PASSWORD);
    principals.put(KRBTGT_PRINCIPAL, null);
    System.setProperty("java.security.krb5.conf", KRB5_CONF_FILENAME);
    // start a local KDC, and save krb5 config
    KDC kdc = KDC.startKDC(HOST, null, REALM, principals, null, null);
    KDC.saveConfig(KRB5_CONF_FILENAME, kdc, "max_retries = 1");
    System.setProperty("java.security.auth.login.config", TEST_SRC + File.separator + "refreshKrb5Config.jaas");
    CallbackHandler handler = new Helper.UserPasswordHandler(USER, USER_PASSWORD);
    // set incorrect KDC
    System.out.println("java.security.krb5.kdc = " + NOT_EXISTING_HOST);
    System.setProperty("java.security.krb5.kdc", NOT_EXISTING_HOST);
    System.out.println("java.security.krb5.realm = " + REALM);
    System.setProperty("java.security.krb5.realm", REALM);
    try {
        new LoginContext("Refreshable", handler).login();
        throw new RuntimeException("Expected exception not thrown");
    } catch (LoginException le) {
        System.out.println("Expected login failure: " + le);
    }
    // reset properties
    System.out.println("Reset java.security.krb5.kdc");
    System.clearProperty("java.security.krb5.kdc");
    System.out.println("Reset java.security.krb5.realm");
    System.clearProperty("java.security.krb5.realm");
    // login with not-refreshable config
    try {
        new LoginContext("NotRefreshable", handler).login();
        throw new RuntimeException("Expected exception not thrown");
    } catch (LoginException le) {
        System.out.println("Expected login failure: " + le);
    }
    // login with refreshable config
    new LoginContext("Refreshable", handler).login();
    System.out.println("Test passed");
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) LoginContext(javax.security.auth.login.LoginContext) HashMap(java.util.HashMap) LoginException(javax.security.auth.login.LoginException)

Example 37 with CallbackHandler

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

the class OpenEJBJaasPasswordAuthenticator method authenticate.

@Override
public boolean authenticate(final String username, final String password, final ServerSession session) {
    try {
        final Subject subject = new Subject();
        final LoginContext loginContext = new LoginContext(getDomain(), subject, new CallbackHandler() {

            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (final Callback callback : callbacks) {
                    if (callback instanceof NameCallback) {
                        ((NameCallback) callback).setName(username);
                    } else if (callback instanceof PasswordCallback) {
                        ((PasswordCallback) callback).setPassword(password.toCharArray());
                    } else {
                        throw new UnsupportedCallbackException(callback);
                    }
                }
            }
        });
        loginContext.login();
        session.setAttribute(USERNAME_KEY, username);
        session.setAttribute(LOGIN_CONTEXT_KEY, loginContext);
        return true;
    } catch (Exception e) {
        LOGGER.debug("can't log using username '" + username + "'", e);
        return false;
    }
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) LoginContext(javax.security.auth.login.LoginContext) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) IOException(java.io.IOException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) Subject(javax.security.auth.Subject) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) IOException(java.io.IOException)

Example 38 with CallbackHandler

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

the class JAASLoginInterceptor method handleMessage.

public void handleMessage(final Message message) throws Fault {
    if (allowNamedPrincipals) {
        SecurityContext sc = message.get(SecurityContext.class);
        if (sc != null && sc.getUserPrincipal() != null && sc.getUserPrincipal().getName() != null) {
            return;
        }
    }
    CallbackHandler handler = getFirstCallbackHandler(message);
    if (handler == null && !allowAnonymous) {
        throw new AuthenticationException("Authentication required but no authentication information was supplied");
    }
    try {
        LoginContext ctx = new LoginContext(getContextName(), null, handler, loginConfig);
        ctx.login();
        Subject subject = ctx.getSubject();
        String name = getUsername(handler);
        message.put(SecurityContext.class, createSecurityContext(name, subject));
        // This allows other code to retrieve the subject using pure JAAS
        if (useDoAs) {
            Subject.doAs(subject, new PrivilegedAction<Void>() {

                @Override
                public Void run() {
                    InterceptorChain chain = message.getInterceptorChain();
                    if (chain != null) {
                        chain.doIntercept(message);
                    }
                    return null;
                }
            });
        }
    } catch (LoginException ex) {
        String errorMessage = "Authentication failed: " + ex.getMessage();
        LOG.log(Level.FINE, errorMessage, ex);
        if (reportFault) {
            AuthenticationException aex = new AuthenticationException(errorMessage);
            aex.initCause(ex);
            throw aex;
        }
        throw new AuthenticationException("Authentication failed (details can be found in server log)");
    }
}
Also used : InterceptorChain(org.apache.cxf.interceptor.InterceptorChain) CallbackHandler(javax.security.auth.callback.CallbackHandler) LoginContext(javax.security.auth.login.LoginContext) SecurityContext(org.apache.cxf.security.SecurityContext) LoginException(javax.security.auth.login.LoginException) Subject(javax.security.auth.Subject)

Example 39 with CallbackHandler

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

the class SamlRedirectBindingFilter method signRequest.

/**
 * Sign a request according to the redirect binding spec for Web SSO
 */
private void signRequest(String authnRequest, String relayState, UriBuilder ub) throws Exception {
    Crypto crypto = getSignatureCrypto();
    if (crypto == null) {
        LOG.fine("No crypto instance of properties file configured for signature");
        throw ExceptionUtils.toInternalServerErrorException(null, null);
    }
    String signatureUser = getSignatureUsername();
    if (signatureUser == null) {
        LOG.fine("No user configured for signature");
        throw ExceptionUtils.toInternalServerErrorException(null, null);
    }
    CallbackHandler callbackHandler = getCallbackHandler();
    if (callbackHandler == null) {
        LOG.fine("No CallbackHandler configured to supply a password for signature");
        throw ExceptionUtils.toInternalServerErrorException(null, null);
    }
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(signatureUser);
    X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType);
    if (issuerCerts == null) {
        throw new Exception("No issuer certs were found to sign the request using name: " + signatureUser);
    }
    String sigAlgo = SSOConstants.RSA_SHA1;
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
    String jceSigAlgo = "SHA1withRSA";
    LOG.fine("automatic sig algo detection: " + pubKeyAlgo);
    if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
        sigAlgo = SSOConstants.DSA_SHA1;
        jceSigAlgo = "SHA1withDSA";
    }
    LOG.fine("Using Signature algorithm " + sigAlgo);
    ub.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, StandardCharsets.UTF_8.name()));
    // Get the password
    WSPasswordCallback[] cb = { new WSPasswordCallback(signatureUser, WSPasswordCallback.SIGNATURE) };
    callbackHandler.handle(cb);
    String password = cb[0].getPassword();
    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey(signatureUser, password);
    // Sign the request
    Signature signature = Signature.getInstance(jceSigAlgo);
    signature.initSign(privateKey);
    String requestToSign = SSOConstants.SAML_REQUEST + "=" + authnRequest + "&" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, StandardCharsets.UTF_8.name());
    signature.update(requestToSign.getBytes(StandardCharsets.UTF_8));
    byte[] signBytes = signature.sign();
    String encodedSignature = Base64.getEncoder().encodeToString(signBytes);
    ub.queryParam(SSOConstants.SIGNATURE, URLEncoder.encode(encodedSignature, StandardCharsets.UTF_8.name()));
}
Also used : Crypto(org.apache.wss4j.common.crypto.Crypto) CallbackHandler(javax.security.auth.callback.CallbackHandler) PrivateKey(java.security.PrivateKey) Signature(java.security.Signature) CryptoType(org.apache.wss4j.common.crypto.CryptoType) WSPasswordCallback(org.apache.wss4j.common.ext.WSPasswordCallback) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException)

Example 40 with CallbackHandler

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

the class AbstractSAMLTokenProvider method signToken.

protected void signToken(SamlAssertionWrapper assertion, RealmProperties samlRealm, STSPropertiesMBean stsProperties, KeyRequirements keyRequirements) throws Exception {
    // Initialise signature objects with defaults of STSPropertiesMBean
    Crypto signatureCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    SignatureProperties signatureProperties = stsProperties.getSignatureProperties();
    String alias = stsProperties.getSignatureUsername();
    if (samlRealm != null) {
        // callbackhandler and alias of STSPropertiesMBean is ignored
        if (samlRealm.getSignatureCrypto() != null) {
            LOG.fine("SAMLRealm signature keystore used");
            signatureCrypto = samlRealm.getSignatureCrypto();
            callbackHandler = samlRealm.getCallbackHandler();
            alias = samlRealm.getSignatureAlias();
        }
        // SignatureProperties can be defined independently of SignatureCrypto
        if (samlRealm.getSignatureProperties() != null) {
            signatureProperties = samlRealm.getSignatureProperties();
        }
    }
    // Get the signature algorithm to use
    String signatureAlgorithm = keyRequirements.getSignatureAlgorithm();
    if (signatureAlgorithm == null) {
        // If none then default to what is configured
        signatureAlgorithm = signatureProperties.getSignatureAlgorithm();
    } else {
        List<String> supportedAlgorithms = signatureProperties.getAcceptedSignatureAlgorithms();
        if (!supportedAlgorithms.contains(signatureAlgorithm)) {
            signatureAlgorithm = signatureProperties.getSignatureAlgorithm();
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("SignatureAlgorithm not supported, defaulting to: " + signatureAlgorithm);
            }
        }
    }
    // Get the c14n algorithm to use
    String c14nAlgorithm = keyRequirements.getC14nAlgorithm();
    if (c14nAlgorithm == null) {
        // If none then default to what is configured
        c14nAlgorithm = signatureProperties.getC14nAlgorithm();
    } else {
        List<String> supportedAlgorithms = signatureProperties.getAcceptedC14nAlgorithms();
        if (!supportedAlgorithms.contains(c14nAlgorithm)) {
            c14nAlgorithm = signatureProperties.getC14nAlgorithm();
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("C14nAlgorithm not supported, defaulting to: " + c14nAlgorithm);
            }
        }
    }
    // If alias not defined, get the default of the SignatureCrypto
    if ((alias == null || "".equals(alias)) && (signatureCrypto != null)) {
        alias = signatureCrypto.getDefaultX509Identifier();
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("Signature alias is null so using default alias: " + alias);
        }
    }
    // Get the password
    String password = null;
    if (callbackHandler != null) {
        WSPasswordCallback[] cb = { new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE) };
        LOG.fine("Creating SAML Token");
        callbackHandler.handle(cb);
        password = cb[0].getPassword();
    }
    LOG.fine("Signing SAML Token");
    boolean useKeyValue = signatureProperties.isUseKeyValue();
    assertion.signAssertion(alias, password, signatureCrypto, useKeyValue, c14nAlgorithm, signatureAlgorithm, signatureProperties.getDigestAlgorithm());
}
Also used : Crypto(org.apache.wss4j.common.crypto.Crypto) CallbackHandler(javax.security.auth.callback.CallbackHandler) SignatureProperties(org.apache.cxf.sts.SignatureProperties) WSPasswordCallback(org.apache.wss4j.common.ext.WSPasswordCallback)

Aggregations

CallbackHandler (javax.security.auth.callback.CallbackHandler)196 Crypto (org.apache.wss4j.common.crypto.Crypto)82 Element (org.w3c.dom.Element)70 PasswordCallbackHandler (org.apache.cxf.sts.common.PasswordCallbackHandler)60 Document (org.w3c.dom.Document)60 IOException (java.io.IOException)49 Callback (javax.security.auth.callback.Callback)43 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)42 TokenValidator (org.apache.cxf.sts.token.validator.TokenValidator)38 PasswordCallback (javax.security.auth.callback.PasswordCallback)36 SAMLTokenValidator (org.apache.cxf.sts.token.validator.SAMLTokenValidator)36 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)34 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)33 ArrayList (java.util.ArrayList)31 CustomTokenPrincipal (org.apache.wss4j.common.principal.CustomTokenPrincipal)31 Subject (javax.security.auth.Subject)29 JAXBElement (javax.xml.bind.JAXBElement)29 TokenRequirements (org.apache.cxf.sts.request.TokenRequirements)29 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)28 HashMap (java.util.HashMap)27