Example usage for javax.security.auth.callback CallbackHandler handle

List of usage examples for javax.security.auth.callback CallbackHandler handle

Introduction

In this page you can find the example usage for javax.security.auth.callback CallbackHandler handle.

Prototype

void handle(Callback[] callbacks) throws java.io.IOException, UnsupportedCallbackException;

Source Link

Document

Retrieve or display the information requested in the provided Callbacks.

Usage

From source file:org.apache.ws.security.processor.ReferenceListProcessor.java

/**
 * Retrieves a secret key (session key) from a already parsed EncryptedKey
 * element/*from  w w w .  j av a 2s .c  om*/
 * 
 * This method takes a security token reference (STR) element and checks if
 * it contains a Reference element. Then it gets the vale of the URI
 * attribute of the Reference and uses the retrieved value to lookup an
 * EncrypteKey element to get the decrypted session key bytes. Using the
 * algorithm parameter these bytes are converted into a secret key.
 * 
 * This method requires that the EncyrptedKey element is already available,
 * thus requires a strict layout of the security header. This method
 * supports EncryptedKey elements within the same message.
 * 
 * @param secRefToken The element containing the STR
 * @param algorithm A string that identifies the symmetric decryption algorithm
 * @param crypto Crypto instance to obtain key
 * @param cb CAllback handler to obtain the key passwords
 * @return The secret key for the specified algorithm
 * @throws WSSecurityException
 */
private SecretKey getKeyFromSecurityTokenReference(Element secRefToken, String algorithm, Crypto crypto,
        CallbackHandler cb) throws WSSecurityException {

    SecurityTokenReference secRef = new SecurityTokenReference(secRefToken);
    byte[] decryptedData = null;

    if (secRef.containsReference()) {
        Reference reference = secRef.getReference();
        String uri = reference.getURI();
        String id = uri;
        if (id.charAt(0) == '#') {
            id = id.substring(1);
        }
        Processor p = wsDocInfo.getProcessor(id);
        if (p instanceof EncryptedKeyProcessor) {
            EncryptedKeyProcessor ekp = (EncryptedKeyProcessor) p;
            decryptedData = ekp.getDecryptedBytes();
        } else if (p instanceof DerivedKeyTokenProcessor) {
            DerivedKeyTokenProcessor dkp = (DerivedKeyTokenProcessor) p;
            decryptedData = dkp.getKeyBytes(WSSecurityUtil.getKeyLength(algorithm));
        } else if (p instanceof SAMLTokenProcessor) {
            SAMLTokenProcessor samlp = (SAMLTokenProcessor) p;
            SAMLKeyInfo keyInfo = SAMLUtil.getSAMLKeyInfo(samlp.getSamlTokenElement(), crypto, cb);
            // TODO Handle malformed SAML tokens where they don't have the 
            // secret in them
            decryptedData = keyInfo.getSecret();
        } else if (p instanceof KerberosTokenProcessor) {
            KerberosTokenProcessor krbp = (KerberosTokenProcessor) p;
            WSParameterCallback param = new WSParameterCallback(WSParameterCallback.KDC_DES_AES_FACTOR);
            int factor = 0;
            try {
                Callback[] callbacks = new Callback[] { param };
                cb.handle(callbacks);
                factor = param.getIntValue();
            } catch (Exception e) {
                //Ignore
                log.error("Error while executing parameter callback", e);
            }

            byte[] secret = krbp.getLastPrincipalFound().getSessionKey();
            if (factor > 1) {
                byte[] newSecret = new byte[secret.length * factor];
                int j = 0;
                for (int i = 0; i < newSecret.length; i++) {
                    newSecret[i] = secret[j++];
                    if (j == secret.length)
                        j = 0;
                }
                decryptedData = newSecret;
            } else {
                decryptedData = secret;
            }

            krbPricipal = krbp.getLastPrincipalFound();
        } else {
            // Try custom token
            WSPasswordCallback pwcb = new WSPasswordCallback(id, WSPasswordCallback.CUSTOM_TOKEN);
            try {
                Callback[] callbacks = new Callback[] { pwcb };
                cb.handle(callbacks);
            } catch (Exception e) {
                throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword", new Object[] { id },
                        e);
            }
            decryptedData = pwcb.getKey();

            if (decryptedData == null) {
                throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "unsupportedKeyId");
            }
        }
    } else if (secRef.containsKeyIdentifier()) {
        if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
            Element token = secRef.getKeyIdentifierTokenElement(secRefToken.getOwnerDocument(), wsDocInfo, cb);

            if (crypto == null) {
                throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
            }
            SAMLKeyInfo keyInfo = SAMLUtil.getSAMLKeyInfo(token, crypto, cb);
            // TODO Handle malformed SAML tokens where they don't have the 
            // secret in them
            decryptedData = keyInfo.getSecret();
        } else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
            Element token = secRef.getKeyIdentifierTokenElement(secRefToken.getOwnerDocument(), wsDocInfo, cb);
            if (crypto == null) {
                throw new WSSecurityException(0, "noSigCryptoFile");
            }
            SAML2KeyInfo keyInfo = SAML2Util.getSAML2KeyInfo(token, crypto, cb);
            decryptedData = keyInfo.getSecret();
        } else {
            String sha = secRef.getKeyIdentifierValue();

            WSPasswordCallback pwcb = new WSPasswordCallback(secRef.getKeyIdentifierValue(), null,
                    secRef.getKeyIdentifierValueType(), WSPasswordCallback.ENCRYPTED_KEY_TOKEN);

            try {
                Callback[] callbacks = new Callback[] { pwcb };
                cb.handle(callbacks);
            } catch (Exception e) {
                throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword", new Object[] { sha },
                        e);
            }
            decryptedData = pwcb.getKey();
        }
    } else {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "noReference");
    }
    return WSSecurityUtil.prepareSecretKey(algorithm, decryptedData);
}

From source file:org.apache.ws.security.processor.SignatureProcessor.java

/**
 * Verify the WS-Security signature./*from w w w  .  j a va2  s .c om*/
 * 
 * The functions at first checks if then <code>KeyInfo</code> that is
 * contained in the signature contains standard X509 data. If yes then
 * get the certificate data via the standard <code>KeyInfo</code> methods.
 * 
 * Otherwise, if the <code>KeyInfo</code> info does not contain X509 data, check
 * if we can find a <code>wsse:SecurityTokenReference</code> element. If yes, the next
 * step is to check how to get the certificate. Two methods are currently supported
 * here:
 * <ul>
 * <li> A URI reference to a binary security token contained in the <code>wsse:Security
 * </code> header.  If the dereferenced token is
 * of the correct type the contained certificate is extracted.
 * </li>
 * <li> Issuer name an serial number of the certificate. In this case the method
 * looks up the certificate in the keystore via the <code>crypto</code> parameter.
 * </li>
 * </ul>
 * 
 * The methods checks is the certificate is valid and calls the
 * {@link org.apache.xml.security.signature.XMLSignature#checkSignatureValue(X509Certificate) 
 * verification} function.
 *
 * @param elem        the XMLSignature DOM Element.
 * @param crypto      the object that implements the access to the keystore and the
 *                    handling of certificates.
 * @param returnCert  verifyXMLSignature stores the certificate in the first
 *                    entry of this array. The caller may then further validate
 *                    the certificate
 * @param returnElements verifyXMLSignature adds the wsu:ID attribute values for
 *               the signed elements to this Set
 * @param cb CallbackHandler instance to extract key passwords
 * @return the subject principal of the validated X509 certificate (the
 *         authenticated subject). The calling function may use this
 *         principal for further authentication or authorization.
 * @throws WSSecurityException
 */
protected Principal verifyXMLSignature(Element elem, Crypto crypto, X509Certificate[] returnCert,
        Set returnElements, List protectedElements, byte[][] signatureValue, CallbackHandler cb,
        WSDocInfo wsDocInfo) throws WSSecurityException {
    if (log.isDebugEnabled()) {
        log.debug("Verify XML Signature");
    }
    long t0 = 0, t1 = 0, t2 = 0;
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }

    XMLSignature sig = null;
    try {
        sig = new XMLSignature(elem, null);
    } catch (XMLSecurityException e2) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "noXMLSig", null, e2);
    }

    sig.addResourceResolver(EnvelopeIdResolver.getInstance());

    KeyInfo info = sig.getKeyInfo();
    UsernameToken ut = null;
    DerivedKeyToken dkt = null;
    SAMLKeyInfo samlKi = null;
    SAML2KeyInfo saml2Ki = null;
    String customTokenId = null;
    java.security.PublicKey publicKey = null;
    X509Certificate[] certs = null;
    boolean validateCertificateChain = false;
    boolean kerbThumbPrint = false;
    X509Certificate cert = null;

    try {
        cert = info.getX509Certificate();
    } catch (KeyResolverException ignore) {
        if (log.isDebugEnabled()) {
            log.debug(ignore);
        }
    }

    if (info != null && info.containsKeyValue()) {
        try {
            publicKey = info.getPublicKey();
        } catch (Exception ex) {
            throw new WSSecurityException(ex.getMessage(), ex);
        }
    } else if (info != null && cert != null) {
        certs = new X509Certificate[] { cert };
    } else if (info != null) {
        Node node = WSSecurityUtil.getDirectChild(info.getElement(),
                SecurityTokenReference.SECURITY_TOKEN_REFERENCE, WSConstants.WSSE_NS);
        if (node == null) {
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo");
        }
        SecurityTokenReference secRef = new SecurityTokenReference((Element) node);
        //
        // Here we get some information about the document that is being
        // processed, in particular the crypto implementation, and already
        // detected BST that may be used later during dereferencing.
        //
        if (secRef.containsReference()) {
            org.apache.ws.security.message.token.Reference ref = secRef.getReference();
            Element krbToken = secRef.getTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);

            if (krbToken.getAttribute("ValueType").equals(
                    "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#GSS_Kerberosv5_AP_REQ")) {

                KerberosTokenProcessor krbp = new KerberosTokenProcessor(this.returnResults);
                return krbp.verifyXMLSignature(elem, crypto, returnCert, returnElements, protectedElements,
                        signatureValue, cb);
            }

            String uri = ref.getURI();
            if (uri.charAt(0) == '#') {
                uri = uri.substring(1);
            }
            Processor processor = wsDocInfo.getProcessor(uri);
            if (processor == null) {
                Element token = secRef.getTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);
                //
                // at this point check token type: Binary, SAML, EncryptedKey, Custom
                //
                QName el = new QName(token.getNamespaceURI(), token.getLocalName());
                if (el.equals(WSSecurityEngine.binaryToken)) {
                    certs = getCertificatesTokenReference(token, crypto);
                    if (certs != null && certs.length > 1) {
                        validateCertificateChain = true;
                    }
                } else if (el.equals(WSSecurityEngine.SAML_TOKEN)) {
                    samlKi = SAMLUtil.getSAMLKeyInfo(token, crypto, cb);
                    certs = samlKi.getCerts();
                    secretKey = samlKi.getSecret();
                } else if (el.equals(WSSecurityEngine.SAML2_TOKEN)) {
                    saml2Ki = SAML2Util.getSAML2KeyInfo(token, crypto, cb);
                    certs = saml2Ki.getCerts();
                    secretKey = saml2Ki.getSecret();

                } else if (el.equals(WSSecurityEngine.ENCRYPTED_KEY)) {
                    if (crypto == null) {
                        throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
                    }
                    EncryptedKeyProcessor encryptKeyProcessor = new EncryptedKeyProcessor();
                    encryptKeyProcessor.handleEncryptedKey(token, cb, crypto);
                    secretKey = encryptKeyProcessor.getDecryptedBytes();
                } else {
                    // Try custom token through callback handler
                    // try to find a custom token
                    String id = secRef.getReference().getURI();
                    if (id.charAt(0) == '#') {
                        id = id.substring(1);
                    }
                    WSPasswordCallback pwcb = new WSPasswordCallback(id, WSPasswordCallback.CUSTOM_TOKEN);
                    try {
                        Callback[] callbacks = new Callback[] { pwcb };
                        cb.handle(callbacks);
                    } catch (Exception e) {
                        throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword",
                                new Object[] { id }, e);
                    }

                    secretKey = pwcb.getKey();
                    customTokenId = id;
                    if (secretKey == null) {
                        throw new WSSecurityException(WSSecurityException.INVALID_SECURITY,
                                "unsupportedKeyInfo", new Object[] { el.toString() });
                    }
                }
            } else if (processor instanceof UsernameTokenProcessor) {
                ut = ((UsernameTokenProcessor) processor).getUt();
                if (ut.isDerivedKey()) {
                    secretKey = ut.getDerivedKey();
                } else {
                    secretKey = ut.getSecretKey(secretKeyLength);
                }
            } else if (processor instanceof BinarySecurityTokenProcessor) {
                certs = ((BinarySecurityTokenProcessor) processor).getCertificates();
                if (certs != null && certs.length > 1) {
                    validateCertificateChain = true;
                }
            } else if (processor instanceof EncryptedKeyProcessor) {
                EncryptedKeyProcessor ekProcessor = (EncryptedKeyProcessor) processor;
                secretKey = ekProcessor.getDecryptedBytes();
                customTokenId = ekProcessor.getId();
            } else if (processor instanceof SecurityContextTokenProcessor) {
                SecurityContextTokenProcessor sctProcessor = (SecurityContextTokenProcessor) processor;
                secretKey = sctProcessor.getSecret();
                customTokenId = sctProcessor.getIdentifier();
            } else if (processor instanceof DerivedKeyTokenProcessor) {
                DerivedKeyTokenProcessor dktProcessor = (DerivedKeyTokenProcessor) processor;
                String signatureMethodURI = sig.getSignedInfo().getSignatureMethodURI();
                dkt = dktProcessor.getDerivedKeyToken();
                int keyLength = (dkt.getLength() > 0) ? dkt.getLength()
                        : WSSecurityUtil.getKeyLength(signatureMethodURI);

                secretKey = dktProcessor.getKeyBytes(keyLength);
            } else if (processor instanceof SAMLTokenProcessor) {
                if (crypto == null) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
                }
                SAMLTokenProcessor samlp = (SAMLTokenProcessor) processor;
                samlKi = SAMLUtil.getSAMLKeyInfo(samlp.getSamlTokenElement(), crypto, cb);
                certs = samlKi.getCerts();
                secretKey = samlKi.getSecret();
                publicKey = samlKi.getPublicKey();
            } else if (processor instanceof SAML2TokenProcessor) {
                if (crypto == null)
                    throw new WSSecurityException(0, "noSigCryptoFile");
                SAML2TokenProcessor samlp = (SAML2TokenProcessor) processor;
                saml2Ki = SAML2Util.getSAML2KeyInfo(samlp.getSamlTokenElement(), crypto, cb);
                certs = saml2Ki.getCerts();
                secretKey = saml2Ki.getSecret();
            }
        } else if (secRef.containsX509Data() || secRef.containsX509IssuerSerial()) {
            certs = secRef.getX509IssuerSerial(crypto);
        } else if (secRef.containsKeyIdentifier()) {
            if (secRef.getKeyIdentifierValueType().equals(SecurityTokenReference.ENC_KEY_SHA1_URI)) {
                String id = secRef.getKeyIdentifierValue();
                WSPasswordCallback pwcb = new WSPasswordCallback(id, null,
                        SecurityTokenReference.ENC_KEY_SHA1_URI, WSPasswordCallback.ENCRYPTED_KEY_TOKEN);
                try {
                    Callback[] callbacks = new Callback[] { pwcb };
                    cb.handle(callbacks);
                } catch (Exception e) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword",
                            new Object[] { id }, e);
                }
                secretKey = pwcb.getKey();
            } else if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
                Element token = secRef.getKeyIdentifierTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);

                samlKi = SAMLUtil.getSAMLKeyInfo(token, crypto, cb);
                certs = samlKi.getCerts();
                secretKey = samlKi.getSecret();
                publicKey = samlKi.getPublicKey();
            } else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
                Element token = secRef.getKeyIdentifierTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);
                saml2Ki = SAML2Util.getSAML2KeyInfo(token, crypto, cb);
                certs = saml2Ki.getCerts();
                secretKey = saml2Ki.getSecret();
            } else {
                certs = secRef.getKeyIdentifier(crypto);
                if (certs == null && secRef.containsKerberosThumbprint()) {
                    secretKey = secRef.getKerberosSession().getSessionKey().getEncoded();
                    kerbThumbPrint = true;
                }
            }
        } else {
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo",
                    new Object[] { node.toString() });
        }
    } else {
        if (crypto == null) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
        }
        if (crypto.getDefaultX509Alias() != null) {
            certs = crypto.getCertificates(crypto.getDefaultX509Alias());
        } else {
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo");
        }
    }
    if (tlog.isDebugEnabled()) {
        t1 = System.currentTimeMillis();
    }
    if ((certs == null || certs.length == 0 || certs[0] == null) && secretKey == null && publicKey == null
            && !kerbThumbPrint) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
    }
    if (certs != null) {
        try {
            for (int i = 0; i < certs.length; i++) {
                certs[i].checkValidity();
            }
        } catch (CertificateExpiredException e) {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "invalidCert", null, e);
        } catch (CertificateNotYetValidException e) {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "invalidCert", null, e);
        }
    }
    //
    // Delegate verification of a public key to a Callback Handler
    //
    if (publicKey != null) {
        PublicKeyCallback pwcb = new PublicKeyCallback(publicKey);
        try {
            Callback[] callbacks = new Callback[] { pwcb };
            cb.handle(callbacks);
            if (!pwcb.isVerified()) {
                throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION, null, null, null);
            }
        } catch (Exception e) {
            throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION, null, null, e);
        }
    }
    try {
        boolean signatureOk = false;
        if (certs != null) {
            signatureOk = sig.checkSignatureValue(certs[0]);
        } else if (publicKey != null) {
            signatureOk = sig.checkSignatureValue(publicKey);
        } else {
            signatureOk = sig.checkSignatureValue(sig.createSecretKey(secretKey));
        }
        if (signatureOk) {
            if (tlog.isDebugEnabled()) {
                t2 = System.currentTimeMillis();
                tlog.debug("Verify: total= " + (t2 - t0) + ", prepare-cert= " + (t1 - t0) + ", verify= "
                        + (t2 - t1));
            }
            signatureValue[0] = sig.getSignatureValue();
            //
            // Now dig into the Signature element to get the elements that
            // this Signature covers. Build the QName of these Elements and
            // return them to caller
            //
            SignedInfo si = sig.getSignedInfo();
            int numReferences = si.getLength();
            for (int i = 0; i < numReferences; i++) {
                Reference siRef;
                try {
                    siRef = si.item(i);
                } catch (XMLSecurityException e3) {
                    throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e3);
                }
                String uri = siRef.getURI();
                if (uri != null && !"".equals(uri)) {

                    Element se = null;
                    try {
                        Transforms transforms = siRef.getTransforms();
                        for (int j = 0; j < transforms.getLength(); j++) {
                            Transform transform = transforms.item(j);
                            // We have some transforming to do before we can 
                            // determine the protected element.
                            if (STRTransform.implementedTransformURI.equals(transform.getURI())) {

                                XMLSignatureInput signatureInput = siRef.getContentsBeforeTransformation();

                                if (signatureInput.isElement()) {
                                    // The signature was already validated,
                                    // meaning that this element was already
                                    // parsed.  We can therefore be pretty
                                    // confident that this constructor will work.
                                    SecurityTokenReference secTokenRef = new SecurityTokenReference(
                                            (Element) signatureInput.getSubNode());

                                    // Use the utility to extract the element (or
                                    // generate a new one in some cases) from the
                                    // message.
                                    se = STRTransformUtil.dereferenceSTR(transform.getDocument(), secTokenRef,
                                            wsDocInfo);
                                } else {
                                    // The internal impl of Reference changed.
                                    // We expect it to return the signature input
                                    // based on a node/element.
                                    throw new WSSecurityException(WSSecurityException.FAILURE);
                                }
                            }
                        }
                    } catch (XMLSecurityException e) {
                        log.warn("Error processing signature coverage elements.", e);
                        throw new WSSecurityException(WSSecurityException.FAILURE);
                    }

                    if (se == null) {
                        se = WSSecurityUtil.getElementByWsuId(elem.getOwnerDocument(), uri);
                    }
                    if (se == null) {
                        se = WSSecurityUtil.getElementByGenId(elem.getOwnerDocument(), uri);
                    }
                    if (se == null) {
                        throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
                    }
                    WSDataRef ref = new WSDataRef(uri);
                    ref.setWsuId(uri);
                    ref.setName(new QName(se.getNamespaceURI(), se.getLocalName()));
                    ref.setProtectedElement(se);
                    ref.setXpath(ReferenceListProcessor.getXPath(se));
                    ref.setAlgorithm(si.getSignatureMethodURI());
                    ref.setDigestAlgorithm(siRef.getMessageDigestAlgorithm().getAlgorithmURI());
                    protectedElements.add(ref);
                    returnElements.add(WSSecurityUtil.getIDFromReference(uri));
                } else {
                    // This is the case where the signed element is identified 
                    // by a transform such as XPath filtering
                    // We add the complete reference element to the return 
                    // elements
                    returnElements.add(siRef);
                }
            }

            // Algorithms used for signature and c14n
            signatureMethod = si.getSignatureMethodURI();
            c14nMethod = si.getCanonicalizationMethodURI();

            if (certs != null) {
                returnCert[0] = certs[0];
                if (validateCertificateChain) {
                    certificates = certs;
                }
                return certs[0].getSubjectX500Principal();
            } else if (publicKey != null) {
                return new PublicKeyPrincipal(publicKey);
            } else if (ut != null) {
                WSUsernameTokenPrincipal principal = new WSUsernameTokenPrincipal(ut.getName(), ut.isHashed());
                principal.setNonce(ut.getNonce());
                principal.setPassword(ut.getPassword());
                principal.setCreatedTime(ut.getCreated());
                return principal;
            } else if (dkt != null) {
                WSDerivedKeyTokenPrincipal principal = new WSDerivedKeyTokenPrincipal(dkt.getID());
                principal.setNonce(dkt.getNonce());
                principal.setLabel(dkt.getLabel());
                principal.setLength(dkt.getLength());
                principal.setOffset(dkt.getOffset());
                String basetokenId = null;
                SecurityTokenReference securityTokenReference = dkt.getSecurityTokenReference();
                if (securityTokenReference.containsReference()) {
                    basetokenId = securityTokenReference.getReference().getURI();
                    if (basetokenId.charAt(0) == '#') {
                        basetokenId = basetokenId.substring(1);
                    }
                } else {
                    // KeyIdentifier
                    basetokenId = securityTokenReference.getKeyIdentifierValue();
                }
                principal.setBasetokenId(basetokenId);
                return principal;
            } else if (samlKi != null) {
                final SAMLAssertion assertion = samlKi.getAssertion();
                CustomTokenPrincipal principal = new CustomTokenPrincipal(assertion.getId());
                principal.setTokenObject(assertion);
                return principal;

            } else if (saml2Ki != null) {
                Assertion assertion = saml2Ki.getAssertion();
                CustomTokenPrincipal principal = new CustomTokenPrincipal(assertion.getID());
                principal.setTokenObject(assertion);
                return principal;
            } else if (secretKey != null) {
                // This is the custom key scenario
                CustomTokenPrincipal principal = new CustomTokenPrincipal(customTokenId);
                return principal;
            } else {
                throw new WSSecurityException("Cannot determine principal");
            }
        } else {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
        }
    } catch (XMLSignatureException e1) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e1);
    }
}

From source file:org.apache.ws.security.processor.UsernameTokenProcessor.java

/**
 * Check the UsernameToken element. Depending on the password type
 * contained in the element the processing differs. If the password type
 * is digested, then retrieve a password from the callback handler and
 * authenticate the UsernameToken here.//from   w  w  w. ja v  a  2s .  co  m
 * <p/>
 * If the password is in plaintext or any other yet unknown password type
 * then delegate the password validation to the callback class. Note that for unknown
 * password types an exception is thrown if WSSConfig.getHandleCustomPasswordTypes()
 * is set to false (as it is by default). The security engine hands over all necessary
 * data to the callback class via the WSPasswordCallback object. The usage parameter of
 * WSPasswordCallback is set to <code>USERNAME_TOKEN_UNKNOWN</code>.
 *
 * @param token the DOM element that contains the UsernameToken
 * @param cb    the reference to the callback object
 * @return WSUsernameTokenPrincipal that contain data that an application
 *         may use to further validate the password/user combination.
 * @throws WSSecurityException
 */
public WSUsernameTokenPrincipal handleUsernameToken(Element token, CallbackHandler cb)
        throws WSSecurityException {
    if (cb == null) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "noCallback");
    }
    //
    // Parse the UsernameToken element
    //
    ut = new UsernameToken(token, allowNamespaceQualifiedPasswordTypes);
    ut.setPasswordsAreEncoded(passwordsAreEncoded);
    String user = ut.getName();
    String password = ut.getPassword();
    String nonce = ut.getNonce();
    String createdTime = ut.getCreated();
    String pwType = ut.getPasswordType();
    if (log.isDebugEnabled()) {
        log.debug("UsernameToken user " + user);
        log.debug("UsernameToken password type " + pwType);
    }

    Callback[] callbacks = new Callback[1];
    String origPassword = null;

    //
    // If the UsernameToken is hashed, then retrieve the password from the callback handler 
    // and compare directly. If the UsernameToken is in plaintext or of some unknown type,
    // then delegate authentication to the callback handler
    //
    if (ut.isHashed()) {
        WSPasswordCallback pwCb = new WSPasswordCallback(user, null, pwType, WSPasswordCallback.USERNAME_TOKEN);
        callbacks[0] = pwCb;
        try {
            cb.handle(callbacks);
        } catch (IOException e) {
            if (log.isDebugEnabled()) {
                log.debug(e);
            }
            throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION, null, null, e);
        } catch (UnsupportedCallbackException e) {
            if (log.isDebugEnabled()) {
                log.debug(e);
            }
            throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION, null, null, e);
        }
        origPassword = pwCb.getPassword();
        if (origPassword == null) {
            if (log.isDebugEnabled()) {
                log.debug("Callback supplied no password for: " + user);
            }
            throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
        }
        String passDigest;
        if (passwordsAreEncoded) {
            passDigest = UsernameToken.doPasswordDigest(nonce, createdTime, Base64.decode(origPassword));
        } else {
            passDigest = UsernameToken.doPasswordDigest(nonce, createdTime, origPassword);
        }
        if (!passDigest.equals(password)) {
            throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
        }
        ut.setRawPassword(origPassword);
    } else {
        if (!WSConstants.PASSWORD_TEXT.equals(pwType) && pwType != null && !handleCustomPasswordTypes) {
            if (log.isDebugEnabled()) {
                log.debug("Authentication failed as handleCustomUsernameTokenTypes is false");
            }
            throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
        }
        WSPasswordCallback pwCb = new WSPasswordCallback(user, password, pwType,
                WSPasswordCallback.USERNAME_TOKEN_UNKNOWN);
        callbacks[0] = pwCb;
        try {
            cb.handle(callbacks);
        } catch (IOException e) {
            if (log.isDebugEnabled()) {
                log.debug(e);
            }
            throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION, null, null, e);
        } catch (UnsupportedCallbackException e) {
            if (log.isDebugEnabled()) {
                log.debug(e);
            }
            throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION, null, null, e);
        }
        origPassword = pwCb.getPassword();
        ut.setRawPassword(origPassword);
    }
    WSUsernameTokenPrincipal principal = new WSUsernameTokenPrincipal(user, ut.isHashed());
    principal.setNonce(nonce);
    principal.setPassword(password);
    principal.setCreatedTime(createdTime);
    principal.setPasswordType(pwType);

    return principal;
}

From source file:org.apache.ws.security.processor.X509Util.java

protected static SecretKey getSharedKey(Element keyInfoElem, String algorithm, CallbackHandler cb)
        throws WSSecurityException {
    String keyName = null;// ww  w .j av a  2s .c o m
    Element keyNmElem = (Element) WSSecurityUtil.getDirectChild(keyInfoElem, "KeyName", WSConstants.SIG_NS);
    if (keyNmElem != null) {
        keyNmElem.normalize();
        Node tmpN = keyNmElem.getFirstChild();
        if (tmpN != null && tmpN.getNodeType() == Node.TEXT_NODE) {
            keyName = tmpN.getNodeValue();
        }
    }
    if (keyName == null) {
        throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "noKeyname");
    }
    WSPasswordCallback pwCb = new WSPasswordCallback(keyName, WSPasswordCallback.KEY_NAME);
    Callback[] callbacks = new Callback[1];
    callbacks[0] = pwCb;
    try {
        cb.handle(callbacks);
    } catch (IOException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword", new Object[] { keyName }, e);
    } catch (UnsupportedCallbackException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword", new Object[] { keyName }, e);
    }
    byte[] decryptedData = pwCb.getKey();
    if (decryptedData == null) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword", new Object[] { keyName });
    }
    return WSSecurityUtil.prepareSecretKey(algorithm, decryptedData);
}

From source file:org.apache.ws.security.saml.SAMLUtil.java

public static SAMLKeyInfo getSAMLKeyInfo(SAMLAssertion assertion, Crypto crypto, CallbackHandler cb)
        throws WSSecurityException {

    //First ask the cb whether it can provide the secret
    WSPasswordCallback pwcb = new WSPasswordCallback(assertion.getId(), WSPasswordCallback.CUSTOM_TOKEN);
    if (cb != null) {
        try {//from   w  w w.jav a2s .  co  m
            cb.handle(new Callback[] { pwcb });
        } catch (Exception e1) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noKey",
                    new Object[] { assertion.getId() }, e1);
        }
    }

    byte[] key = pwcb.getKey();

    if (key != null) {
        return new SAMLKeyInfo(assertion, key);
    } else {
        Iterator statements = assertion.getStatements();
        while (statements.hasNext()) {
            SAMLStatement stmt = (SAMLStatement) statements.next();
            if (stmt instanceof SAMLAttributeStatement) {
                SAMLAttributeStatement attrStmt = (SAMLAttributeStatement) stmt;
                SAMLSubject samlSubject = attrStmt.getSubject();
                Element kiElem = samlSubject.getKeyInfo();

                NodeList children = kiElem.getChildNodes();
                int len = children.getLength();

                for (int i = 0; i < len; i++) {
                    Node child = children.item(i);
                    if (child.getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    QName el = new QName(child.getNamespaceURI(), child.getLocalName());
                    if (el.equals(WSSecurityEngine.ENCRYPTED_KEY)) {

                        EncryptedKeyProcessor proc = new EncryptedKeyProcessor();
                        proc.handleEncryptedKey((Element) child, cb, crypto, null);

                        return new SAMLKeyInfo(assertion, proc.getDecryptedBytes());
                    } else if (el.equals(new QName(WSConstants.WST_NS, "BinarySecret"))) {
                        Text txt = (Text) child.getFirstChild();
                        return new SAMLKeyInfo(assertion, Base64.decode(txt.getData()));
                    }
                }

            } else if (stmt instanceof SAMLAuthenticationStatement) {
                SAMLAuthenticationStatement authStmt = (SAMLAuthenticationStatement) stmt;
                SAMLSubject samlSubj = authStmt.getSubject();
                if (samlSubj == null) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLToken",
                            new Object[] { "for Signature (no Subject)" });
                }

                Element e = samlSubj.getKeyInfo();
                X509Certificate[] certs = null;
                try {
                    KeyInfo ki = new KeyInfo(e, null);

                    if (ki.containsX509Data()) {
                        X509Data data = ki.itemX509Data(0);
                        XMLX509Certificate certElem = null;
                        if (data != null && data.containsCertificate()) {
                            certElem = data.itemCertificate(0);
                        }
                        if (certElem != null) {
                            X509Certificate cert = certElem.getX509Certificate();
                            certs = new X509Certificate[1];
                            certs[0] = cert;
                            return new SAMLKeyInfo(assertion, certs);
                        }
                    }

                } catch (XMLSecurityException e3) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLSecurity",
                            new Object[] { "cannot get certificate (key holder)" }, e3);
                }

            } else {
                throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLSecurity",
                        new Object[] { "cannot get certificate or key " });
            }
        }

        throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLSecurity",
                new Object[] { "cannot get certificate or key " });

    }

}

From source file:org.opensc.pkcs11.PKCS11SessionStore.java

/**
 * This method allows you to authenticate you against the token, if the initial call to
 * {@link #open(LoadStoreParameter)} did not contain a
 * ProtectionParameter. This may be use in order to search for a certificate on a token
 * without entering a PIN.//ww w . j a va  2  s  .co m
 * 
 * @param param The protection parameters used to do normal (user) authentication.
 * 
 * @see PKCS11LoadStoreParameter#getProtectionParameter()
 */
public void authenticate(ProtectionParameter param) throws IOException {
    this.protectionParameter = param;

    try {
        if (this.protectionParameter instanceof PasswordProtection) {
            changeEvent(PKCS11EventCallback.PIN_AUTHENTICATION_IN_PROGRESS);
            PasswordProtection pp = (PasswordProtection) this.protectionParameter;

            this.session.loginUser(pp.getPassword());
            changeEvent(PKCS11EventCallback.AUHENTICATION_SUCEEDED);
        } else if (this.protectionParameter instanceof CallbackHandlerProtection) {
            CallbackHandlerProtection cbhp = (CallbackHandlerProtection) this.protectionParameter;

            char[] pin = null;
            // do authenticate with the protected auth method of the token,
            // if this is possible, otherwise use the callback to authenticate. 
            if (this.slot.hasTokenProtectedAuthPath()) {
                changeEvent(PKCS11EventCallback.HW_AUTHENTICATION_IN_PROGRESS);
            } else {
                changeEvent(PKCS11EventCallback.WAITING_FOR_SW_PIN);

                CallbackHandler cbh = cbhp.getCallbackHandler();

                PasswordCallback pcb = new PasswordCallback("Please enter the user pin:", false);
                cbh.handle(new Callback[] { pcb });

                pin = pcb.getPassword();
                changeEvent(PKCS11EventCallback.PIN_AUTHENTICATION_IN_PROGRESS);
            }

            this.session.loginUser(pin);
            changeEvent(PKCS11EventCallback.AUHENTICATION_SUCEEDED);
        }
    } catch (UnsupportedCallbackException e) {
        throw new PKCS11Exception("PasswordCallback is not supported", e);
    }
}

From source file:org.opensc.pkcs11.PKCS11SessionStore.java

/**
 * This method allows you to authenticate you against the token as the security officer
 * for read/write access to the token, if the initial call to
 * {@link #open(LoadStoreParameter)} did not contain a SO
 * ProtectionParameter./*  w  w w.  j a  va2s .  co m*/
 * 
 * @param param The protection parameters used to do SO (security officer) authentication.
 * 
 * @see PKCS11LoadStoreParameter#getSOProtectionParameter()
 */
public void authenticateSO(ProtectionParameter param) throws IOException {
    try {
        if (param instanceof PasswordProtection) {
            PasswordProtection pp = (PasswordProtection) param;

            changeEvent(PKCS11EventCallback.SO_PIN_AUTHENTICATION_IN_PROGRESS);
            this.session.loginSO(pp.getPassword());
            changeEvent(PKCS11EventCallback.SO_AUHENTICATION_SUCEEDED);
        } else if (param instanceof CallbackHandlerProtection) {
            CallbackHandlerProtection cbhp = (CallbackHandlerProtection) param;

            char[] pin = null;
            // do authenticate with the protected auth method of the token,
            // if this is possible, otherwise use the callback to authenticate.
            if (this.slot.hasTokenProtectedAuthPath()) {
                changeEvent(PKCS11EventCallback.SO_HW_AUTHENTICATION_IN_PROGRESS);
            } else {
                changeEvent(PKCS11EventCallback.WAITING_FOR_SW_SO_PIN);

                CallbackHandler cbh = cbhp.getCallbackHandler();

                PasswordCallback pcb = new PasswordCallback("Please enter the SO pin:", false);
                cbh.handle(new Callback[] { pcb });
                pin = pcb.getPassword();
                changeEvent(PKCS11EventCallback.SO_PIN_AUTHENTICATION_IN_PROGRESS);
            }

            this.session.loginSO(pin);
            changeEvent(PKCS11EventCallback.SO_AUHENTICATION_SUCEEDED);
        }
    } catch (UnsupportedCallbackException e) {
        throw new PKCS11Exception("PasswordCallback is not supported", e);
    }
}

From source file:org.sakaiproject.nakamura.lite.jackrabbit.SparseLoginModule.java

@Override
protected void doInit(CallbackHandler callbackHandler, Session session,
        @SuppressWarnings("rawtypes") Map options) throws LoginException {
    try {//from  w w  w  .j av a  2 s.  c  o  m
        SessionImpl sessionImpl = (SessionImpl) session;
        SparseMapUserManager userManager = (SparseMapUserManager) sessionImpl.getUserManager();
        org.sakaiproject.nakamura.api.lite.Session sparseSession = userManager.getSession();

        LoginModulePlugin[] modules = Activator.getLoginModules();
        for (int i = 0; i < modules.length; i++) {
            modules[i].doInit(callbackHandler, session, options);
        }

        CredentialsCallback cb = new CredentialsCallback();
        try {
            callbackHandler.handle(new Callback[] { cb });
        } catch (IOException e1) {
            LOGGER.warn(e1.getMessage(), e1);
        } catch (UnsupportedCallbackException e1) {
            LOGGER.warn(e1.getMessage(), e1);
        }
        authenticator = sparseSession.getAuthenticator();
    } catch (StorageClientException e) {
        throw new LoginException(e.getMessage());
    } catch (AccessDeniedException e) {
        throw new LoginException(e.getMessage());
    } catch (RepositoryException e) {
        throw new LoginException(e.getMessage());
    }

}