Example usage for org.w3c.dom Element getOwnerDocument

List of usage examples for org.w3c.dom Element getOwnerDocument

Introduction

In this page you can find the example usage for org.w3c.dom Element getOwnerDocument.

Prototype

public Document getOwnerDocument();

Source Link

Document

The Document object associated with this node.

Usage

From source file:org.apache.ws.security.message.TestMessageTransformer.java

public static Element duplicateEncryptedDataInWsseWrapperHeader(Element saaj, boolean moveReferenceList) {
    if (moveReferenceList) {
        moveReferenceList(saaj);//from ww w.  j a va  2s .c o m
    }
    Element body = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"),
            true);
    Element encData = getFirstChildElement(body,
            new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedData"), true);
    Element newEncData = createNewEncryptedData(encData);
    Element sh = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Header"),
            true);
    Element signature = getFirstChildElement(sh, new QName("http://www.w3.org/2000/09/xmldsig#", "Signature"),
            true);

    Node wsseHeader = signature.getParentNode();
    Node newWsseHeader = wsseHeader.cloneNode(false);
    Node cur = wsseHeader.getFirstChild();
    String newId = newEncData.getAttributeNS(null, "Id");
    while (!cur.isSameNode(signature)) {
        cur = copyHeadersAndUpdateRefList(cur, newWsseHeader, newId);
    }
    Element wrapper = encData.getOwnerDocument().createElementNS(null, "a");
    wrapper.appendChild(newEncData);
    newWsseHeader.appendChild(wrapper);
    while (cur != null) {
        cur = copyHeadersAndUpdateRefList(cur, newWsseHeader, newId);
    }

    if (!moveReferenceList) {
        updateEncryptedKeyRefList(newWsseHeader, newId);
    }

    Node parent = wsseHeader.getParentNode();
    parent.removeChild(wsseHeader);
    parent.appendChild(newWsseHeader);
    print(saaj.getOwnerDocument());
    return newEncData;
}

From source file:org.apache.ws.security.message.TestMessageTransformer.java

public static Element duplicateEncryptedDataInExternalWrapperElement(Element saaj, boolean moveReferenceList) {
    if (moveReferenceList) {
        moveReferenceList(saaj);// ww w  .  j  av a  2 s .c o  m
    }
    Element body = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"),
            true);
    Element encData = getFirstChildElement(body,
            new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedData"), true);
    Element newEncData = createNewEncryptedData(encData);
    Element sh = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Header"),
            true);
    Element wsseHeader = getFirstChildElement(sh,
            new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                    "Security"),
            true);

    Node newWsseHeader = wsseHeader.cloneNode(false);
    Node cur = wsseHeader.getFirstChild();
    String newId = newEncData.getAttributeNS(null, "Id");
    while (cur != null) {
        cur = copyHeadersAndUpdateRefList(cur, newWsseHeader, newId);
    }
    sh.removeChild(wsseHeader);
    sh.appendChild(newWsseHeader);

    if (!moveReferenceList) {
        updateEncryptedKeyRefList(newWsseHeader, newId);
    }

    Element wrapper = encData.getOwnerDocument().createElementNS(null, "a");
    wrapper.setAttributeNS("http://schemas.xmlsoap.org/soap/envelope/", "mustUnderstand", "0");
    wrapper.setAttributeNS("http://schemas.xmlsoap.org/soap/envelope/", "actor", "foo");
    wrapper.appendChild(newEncData);
    sh.appendChild(wrapper);
    print(saaj.getOwnerDocument());
    return newEncData;
}

From source file:org.apache.ws.security.message.TestMessageTransformer.java

public static Element addEncryptedDataWithEmbeddedEncryptedKeyInWsseHeader(Element saaj) {
    moveReferenceList(saaj);//from  w w  w .ja v a2  s  .co  m
    Element body = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"),
            true);
    Element encData = getFirstChildElement(body,
            new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedData"), true);

    Element newEncData = (Element) encData.cloneNode(true);
    String newId = newEncData.getAttributeNS(null, "Id") + "b";
    newEncData.setAttributeNS(null, "Id", newId);

    Element encKey = getFirstChildElement(saaj, new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedKey"),
            true);
    Element newEncKey = (Element) encKey.cloneNode(true);
    String newEcId = newEncKey.getAttributeNS(null, "Id") + "b";
    newEncKey.setAttributeNS(null, "Id", newEcId);

    Element keyInfo = getFirstChildElement(newEncData,
            new QName("http://www.w3.org/2000/09/xmldsig#", "KeyInfo"), true);
    Element str = getFirstChildElement(newEncData,
            new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                    "SecurityTokenReference"),
            true);
    keyInfo.replaceChild(newEncKey, str);

    Element wsseHeader = getFirstChildElement(saaj,
            new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                    "Security"),
            true);

    Node newWsseHeader = wsseHeader.cloneNode(false);
    Node cur = wsseHeader.getFirstChild();

    while (cur != null) {
        cur = copyHeadersAndUpdateRefList(cur, newWsseHeader, newId);
    }
    newWsseHeader.appendChild(newEncData);

    Node parent = wsseHeader.getParentNode();
    parent.removeChild(wsseHeader);
    parent.appendChild(newWsseHeader);
    print(saaj.getOwnerDocument());
    return newEncData;

}

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

public List<WSSecurityEngineResult> handleToken(Element elem, RequestData request, WSDocInfo wsDocInfo)
        throws WSSecurityException {
    if (log.isDebugEnabled()) {
        log.debug("Found EncryptedData element");
    }//from   w  w w.j  a v a 2  s  . c  o  m
    Element kiElem = WSSecurityUtil.getDirectChildElement(elem, "KeyInfo", WSConstants.SIG_NS);
    // KeyInfo cannot be null
    if (kiElem == null) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, "noKeyinfo");
    }

    String symEncAlgo = X509Util.getEncAlgo(elem);
    // Check BSP compliance
    if (request.getWssConfig().isWsiBSPCompliant()) {
        checkBSPCompliance(symEncAlgo);
    }

    // Get the Key either via a SecurityTokenReference or an EncryptedKey
    Element secRefToken = WSSecurityUtil.getDirectChildElement(kiElem, "SecurityTokenReference",
            WSConstants.WSSE_NS);
    Element encryptedKeyElement = WSSecurityUtil.getDirectChildElement(kiElem, WSConstants.ENC_KEY_LN,
            WSConstants.ENC_NS);

    if (elem != null && request.isRequireSignedEncryptedDataElements()) {
        WSSecurityUtil.verifySignedElement(elem, elem.getOwnerDocument(), wsDocInfo.getSecurityHeader());
    }

    SecretKey key = null;
    List<WSSecurityEngineResult> encrKeyResults = null;
    Principal principal = null;
    if (secRefToken != null) {
        STRParser strParser = new SecurityTokenRefSTRParser();
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put(SecurityTokenRefSTRParser.SIGNATURE_METHOD, symEncAlgo);
        strParser.parseSecurityTokenReference(secRefToken, request, wsDocInfo, parameters);
        byte[] secretKey = strParser.getSecretKey();
        principal = strParser.getPrincipal();
        key = WSSecurityUtil.prepareSecretKey(symEncAlgo, secretKey);
    } else if (encryptedKeyElement != null) {
        EncryptedKeyProcessor encrKeyProc = new EncryptedKeyProcessor();
        encrKeyResults = encrKeyProc.handleToken(encryptedKeyElement, request, wsDocInfo);
        byte[] symmKey = (byte[]) encrKeyResults.get(0).get(WSSecurityEngineResult.TAG_SECRET);
        key = WSSecurityUtil.prepareSecretKey(symEncAlgo, symmKey);
    } else {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, "noEncKey");
    }

    // Check for compliance against the defined AlgorithmSuite
    AlgorithmSuite algorithmSuite = request.getAlgorithmSuite();
    if (algorithmSuite != null) {
        AlgorithmSuiteValidator algorithmSuiteValidator = new AlgorithmSuiteValidator(algorithmSuite);

        if (principal instanceof WSDerivedKeyTokenPrincipal) {
            algorithmSuiteValidator
                    .checkDerivedKeyAlgorithm(((WSDerivedKeyTokenPrincipal) principal).getAlgorithm());
            algorithmSuiteValidator
                    .checkEncryptionDerivedKeyLength(((WSDerivedKeyTokenPrincipal) principal).getLength());
        }
        algorithmSuiteValidator.checkSymmetricKeyLength(key.getEncoded().length);
        algorithmSuiteValidator.checkSymmetricEncryptionAlgorithm(symEncAlgo);
    }

    // initialize Cipher ....
    XMLCipher xmlCipher = null;
    try {
        xmlCipher = XMLCipher.getInstance(symEncAlgo);
        xmlCipher.setSecureValidation(true);
        xmlCipher.init(XMLCipher.DECRYPT_MODE, key);
    } catch (XMLEncryptionException ex) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, ex);
    }
    Node previousSibling = elem.getPreviousSibling();
    Node parent = elem.getParentNode();
    try {
        xmlCipher.doFinal(elem.getOwnerDocument(), elem, false);
    } catch (Exception e) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e);
    }

    WSDataRef dataRef = new WSDataRef();
    dataRef.setWsuId(elem.getAttributeNS(null, "Id"));
    dataRef.setAlgorithm(symEncAlgo);
    dataRef.setContent(false);

    Node decryptedNode;
    if (previousSibling == null) {
        decryptedNode = parent.getFirstChild();
    } else {
        decryptedNode = previousSibling.getNextSibling();
    }
    if (decryptedNode != null && Node.ELEMENT_NODE == decryptedNode.getNodeType()) {
        dataRef.setProtectedElement((Element) decryptedNode);
    }
    dataRef.setXpath(ReferenceListProcessor.getXPath(decryptedNode));

    WSSecurityEngineResult result = new WSSecurityEngineResult(WSConstants.ENCR,
            Collections.singletonList(dataRef));
    result.put(WSSecurityEngineResult.TAG_ID, elem.getAttributeNS(null, "Id"));
    wsDocInfo.addResult(result);
    wsDocInfo.addTokenElement(elem);

    WSSConfig wssConfig = request.getWssConfig();
    if (wssConfig != null) {
        // Get hold of the plain text element
        Element decryptedElem;
        if (previousSibling == null) {
            decryptedElem = (Element) parent.getFirstChild();
        } else {
            decryptedElem = (Element) previousSibling.getNextSibling();
        }
        QName el = new QName(decryptedElem.getNamespaceURI(), decryptedElem.getLocalName());
        Processor proc = request.getWssConfig().getProcessor(el);
        if (proc != null) {
            if (log.isDebugEnabled()) {
                log.debug("Processing decrypted element with: " + proc.getClass().getName());
            }
            List<WSSecurityEngineResult> results = proc.handleToken(decryptedElem, request, wsDocInfo);
            List<WSSecurityEngineResult> completeResults = new ArrayList<WSSecurityEngineResult>();
            if (encrKeyResults != null) {
                completeResults.addAll(encrKeyResults);
            }
            completeResults.add(result);
            completeResults.addAll(0, results);
            return completeResults;
        }
    }
    encrKeyResults.add(result);
    return encrKeyResults;
}

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

public ArrayList handleEncryptedKey(Element xencEncryptedKey, CallbackHandler cb, Crypto crypto,
        PrivateKey privateKey) throws WSSecurityException {
    long t0 = 0, t1 = 0, t2 = 0;
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }//from www. ja v  a 2s.  c  o m
    // need to have it to find the encrypted data elements in the envelope
    Document doc = xencEncryptedKey.getOwnerDocument();

    // lookup xenc:EncryptionMethod, get the Algorithm attribute to determine
    // how the key was encrypted. Then check if we support the algorithm

    Node tmpE = null; // short living Element used for lookups only
    tmpE = (Element) WSSecurityUtil.getDirectChild((Node) xencEncryptedKey, "EncryptionMethod",
            WSConstants.ENC_NS);
    if (tmpE != null) {
        this.encryptedKeyTransportMethod = ((Element) tmpE).getAttribute("Algorithm");
    }
    if (this.encryptedKeyTransportMethod == null) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, "noEncAlgo");
    }
    Cipher cipher = WSSecurityUtil.getCipherInstance(this.encryptedKeyTransportMethod);
    //
    // Well, we can decrypt the session (symmetric) key. Now lookup CipherValue, this is the 
    // value of the encrypted session key (session key usually is a symmetrical key that encrypts
    // the referenced content). This is a 2-step lookup
    //
    Element xencCipherValue = null;
    tmpE = (Element) WSSecurityUtil.getDirectChild((Node) xencEncryptedKey, "CipherData", WSConstants.ENC_NS);
    if (tmpE != null) {
        xencCipherValue = (Element) WSSecurityUtil.getDirectChild(tmpE, "CipherValue", WSConstants.ENC_NS);
    }
    if (xencCipherValue == null) {
        throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "noCipher");
    }

    if (privateKey == null) {
        Element keyInfo = (Element) WSSecurityUtil.getDirectChild((Node) xencEncryptedKey, "KeyInfo",
                WSConstants.SIG_NS);
        String alias;
        if (keyInfo != null) {
            Element secRefToken = (Element) WSSecurityUtil.getDirectChild(keyInfo, "SecurityTokenReference",
                    WSConstants.WSSE_NS);
            //
            // EncryptedKey must a a STR as child of KeyInfo, KeyName  
            // valid only for EncryptedData
            //
            //  if (secRefToken == null) {
            //      secRefToken = (Element) WSSecurityUtil.getDirectChild(keyInfo,
            //              "KeyName", WSConstants.SIG_NS);
            //  }
            if (secRefToken == null) {
                throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "noSecTokRef");
            }
            SecurityTokenReference secRef = new SecurityTokenReference(secRefToken);
            //
            // Well, at this point there are several ways to get the key.
            // Try to handle all of them :-).
            //
            alias = null;
            //
            // handle X509IssuerSerial here. First check if all elements are available,
            // get the appropriate data, check if all data is available.
            // If all is ok up to that point, look up the certificate alias according
            // to issuer name and serial number.
            // This method is recommended by OASIS WS-S specification, X509 profile
            //
            if (secRef.containsX509Data() || secRef.containsX509IssuerSerial()) {
                alias = secRef.getX509IssuerSerialAlias(crypto);
                if (log.isDebugEnabled()) {
                    log.debug("X509IssuerSerial alias: " + alias);
                }
            }
            //
            // If wsse:KeyIdentifier found, then the public key of the attached cert was used to
            // encrypt the session (symmetric) key that encrypts the data. Extract the certificate
            // using the BinarySecurity token (was enhanced to handle KeyIdentifier too).
            // This method is _not_ recommended by OASIS WS-S specification, X509 profile
            //
            else if (secRef.containsKeyIdentifier()) {
                X509Certificate[] certs = null;
                if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
                    Element token = secRef.getKeyIdentifierTokenElement(doc, docInfo, cb);

                    if (crypto == null) {
                        throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
                    }
                    SAMLKeyInfo samlKi = SAMLUtil.getSAMLKeyInfo(token, crypto, cb);
                    certs = samlKi.getCerts();
                } else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
                    Element token = secRef.getKeyIdentifierTokenElement(doc, docInfo, cb);
                    if (crypto == null) {
                        throw new WSSecurityException(0, "noSigCryptoFile");
                    }
                    SAML2KeyInfo samlKi = SAML2Util.getSAML2KeyInfo(token, crypto, cb);
                    certs = samlKi.getCerts();
                } else {
                    certs = secRef.getKeyIdentifier(crypto);
                }
                if (certs == null || certs.length < 1 || certs[0] == null) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "noCertsFound",
                            new Object[] { "decryption (KeyId)" });
                }
                //
                // Here we have the certificate. Now find the alias for it. Needed to identify
                // the private key associated with this certificate
                //
                alias = crypto.getAliasForX509Cert(certs[0]);
                cert = certs[0];
                if (log.isDebugEnabled()) {
                    log.debug("cert: " + certs[0]);
                    log.debug("KeyIdentifier Alias: " + alias);
                }
            } else if (secRef.containsReference()) {
                Element bstElement = secRef.getTokenElement(doc, null, cb);

                // at this point ... check token type: Binary
                QName el = new QName(bstElement.getNamespaceURI(), bstElement.getLocalName());
                if (el.equals(WSSecurityEngine.binaryToken)) {
                    X509Security token = new X509Security(bstElement);
                    String value = bstElement.getAttribute(WSSecurityEngine.VALUE_TYPE);
                    if (!X509Security.X509_V3_TYPE.equals(value) || (token == null)) {
                        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_SECURITY_TOKEN,
                                "unsupportedBinaryTokenType", new Object[] { "for decryption (BST)" });
                    }
                    cert = token.getX509Certificate(crypto);
                    if (cert == null) {
                        throw new WSSecurityException(WSSecurityException.FAILURE, "noCertsFound",
                                new Object[] { "decryption" });
                    }
                    //
                    // Here we have the certificate. Now find the alias for it. Needed to identify
                    // the private key associated with this certificate
                    //
                    alias = crypto.getAliasForX509Cert(cert);
                    if (log.isDebugEnabled()) {
                        log.debug("BST Alias: " + alias);
                    }
                } else {
                    throw new WSSecurityException(WSSecurityException.UNSUPPORTED_SECURITY_TOKEN,
                            "unsupportedBinaryTokenType", null);
                }
                //
                // The following code is somewhat strange: the called crypto method gets
                // the keyname and searches for a certificate with an issuer's name that is
                // equal to this keyname. No serialnumber is used - IMHO this does
                // not identifies a certificate. In addition neither the WSS4J encryption
                // nor signature methods use this way to identify a certificate. Because of that
                // the next lines of code are disabled.  
                //
                // } else if (secRef.containsKeyName()) {
                //    alias = crypto.getAliasForX509Cert(secRef.getKeyNameValue());
                //    if (log.isDebugEnabled()) {
                //        log.debug("KeyName alias: " + alias);
                //    }
            } else {
                throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "unsupportedKeyId");
            }
        } else if (crypto.getDefaultX509Alias() != null) {
            alias = crypto.getDefaultX509Alias();
        } else {
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "noKeyinfo");
        }
        //
        // At this point we have all information necessary to decrypt the session
        // key:
        // - the Cipher object intialized with the correct methods
        // - The data that holds the encrypted session key
        // - the alias name for the private key
        //
        // Now use the callback here to get password that enables
        // us to read the private key
        //
        WSPasswordCallback pwCb = new WSPasswordCallback(alias, WSPasswordCallback.DECRYPT);
        try {
            Callback[] callbacks = new Callback[] { pwCb };
            cb.handle(callbacks);
        } catch (IOException e) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword", new Object[] { alias }, e);
        } catch (UnsupportedCallbackException e) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword", new Object[] { alias }, e);
        }
        String password = pwCb.getPassword();
        if (password == null) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword", new Object[] { alias });
        }

        try {
            privateKey = crypto.getPrivateKey(alias, password);
        } catch (Exception e) {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e);
        }
    }

    try {
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
    } catch (Exception e1) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e1);
    }

    try {
        encryptedEphemeralKey = getDecodedBase64EncodedData(xencCipherValue);
        decryptedBytes = cipher.doFinal(encryptedEphemeralKey);
    } catch (IllegalStateException e2) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e2);
    } catch (Exception e2) {
        decryptedBytes = getRandomKey(getDataRefURIs(xencCipherValue), xencEncryptedKey.getOwnerDocument(),
                docInfo);
    }

    if (tlog.isDebugEnabled()) {
        t1 = System.currentTimeMillis();
    }

    // At this point we have the decrypted session (symmetric) key. According
    // to W3C XML-Enc this key is used to decrypt _any_ references contained in
    // the reference list
    // Now lookup the references that are encrypted with this key
    //
    Element refList = (Element) WSSecurityUtil.getDirectChild((Node) xencEncryptedKey, "ReferenceList",
            WSConstants.ENC_NS);
    ArrayList dataRefs = new ArrayList();
    if (refList != null) {
        for (tmpE = refList.getFirstChild(); tmpE != null; tmpE = tmpE.getNextSibling()) {
            if (tmpE.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }
            if (!tmpE.getNamespaceURI().equals(WSConstants.ENC_NS)) {
                continue;
            }
            if (tmpE.getLocalName().equals("DataReference")) {
                String dataRefURI = ((Element) tmpE).getAttribute("URI");
                if (dataRefURI.charAt(0) == '#') {
                    dataRefURI = dataRefURI.substring(1);
                }
                WSDataRef dataRef = decryptDataRef(doc, dataRefURI, decryptedBytes);
                dataRefs.add(dataRef);
            }
        }
        return dataRefs;
    }

    if (tlog.isDebugEnabled()) {
        t2 = System.currentTimeMillis();
        tlog.debug(
                "XMLDecrypt: total= " + (t2 - t0) + ", get-sym-key= " + (t1 - t0) + ", decrypt= " + (t2 - t1));
    }

    return null;
}

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

/**
 * Dereferences and decodes encrypted data elements.
 * //from  w w  w  . ja v a2 s .c o m
 * @param elem contains the <code>ReferenceList</code> to the encrypted
 *             data elements
 * @param cb the callback handler to get the key for a key name stored if
 *           <code>KeyInfo</code> inside the encrypted data elements
 */
private ArrayList handleReferenceList(Element elem, CallbackHandler cb, Crypto crypto)
        throws WSSecurityException {
    Node tmpE = null;
    ArrayList dataRefUris = new ArrayList();
    for (tmpE = elem.getFirstChild(); tmpE != null; tmpE = tmpE.getNextSibling()) {
        if (tmpE.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }
        if (!tmpE.getNamespaceURI().equals(WSConstants.ENC_NS)) {
            continue;
        }
        if (tmpE.getLocalName().equals("DataReference")) {
            String dataRefURI = ((Element) tmpE).getAttribute("URI");
            if (dataRefURI.charAt(0) == '#') {
                dataRefURI = dataRefURI.substring(1);
            }
            WSDataRef dataRef = decryptDataRefEmbedded(elem.getOwnerDocument(), dataRefURI, cb, crypto);
            dataRefUris.add(dataRef);
        }
    }

    return dataRefUris;
}

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  a2 s .c  o  m
 * 
 * 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./*w ww  . j a  va2 s  .com*/
 * 
 * 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.str.EncryptedKeySTRParser.java

/**
 * Parse a SecurityTokenReference element and extract credentials.
 * /*from w w  w .j a va2s  .c o  m*/
 * @param strElement The SecurityTokenReference element
 * @param data the RequestData associated with the request
 * @param wsDocInfo The WSDocInfo object to access previous processing results
 * @param parameters A set of implementation-specific parameters
 * @throws WSSecurityException
 */
public void parseSecurityTokenReference(Element strElement, RequestData data, WSDocInfo wsDocInfo,
        Map<String, Object> parameters) throws WSSecurityException {
    Crypto crypto = data.getDecCrypto();
    WSSConfig config = data.getWssConfig();
    boolean bspCompliant = true;
    if (config != null) {
        bspCompliant = config.isWsiBSPCompliant();
    }

    SecurityTokenReference secRef = new SecurityTokenReference(strElement, bspCompliant);

    String uri = null;
    if (secRef.containsReference()) {
        uri = secRef.getReference().getURI();
        if (uri.charAt(0) == '#') {
            uri = uri.substring(1);
        }
        referenceType = REFERENCE_TYPE.DIRECT_REF;
    } else if (secRef.containsKeyIdentifier()) {
        uri = secRef.getKeyIdentifierValue();
        if (SecurityTokenReference.THUMB_URI.equals(secRef.getKeyIdentifierValueType())) {
            referenceType = REFERENCE_TYPE.THUMBPRINT_SHA1;
        } else {
            referenceType = REFERENCE_TYPE.KEY_IDENTIFIER;
        }
    }

    WSSecurityEngineResult result = wsDocInfo.getResult(uri);
    if (result != null) {
        processPreviousResult(result, secRef, data, wsDocInfo, bspCompliant);
    } else if (secRef.containsKeyIdentifier()) {
        if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())
                || WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
            AssertionWrapper assertion = SAMLUtil.getAssertionFromKeyIdentifier(secRef, strElement, data,
                    wsDocInfo);
            if (bspCompliant) {
                BSPEnforcer.checkSamlTokenBSPCompliance(secRef, assertion);
            }
            SAMLKeyInfo samlKi = SAMLUtil.getCredentialFromSubject(assertion, data, wsDocInfo, bspCompliant);
            certs = samlKi.getCerts();
        } else {
            if (bspCompliant) {
                BSPEnforcer.checkBinarySecurityBSPCompliance(secRef, null);
            }
            certs = secRef.getKeyIdentifier(crypto);
        }
    } else if (secRef.containsX509Data() || secRef.containsX509IssuerSerial()) {
        referenceType = REFERENCE_TYPE.ISSUER_SERIAL;
        certs = secRef.getX509IssuerSerial(crypto);
    } else if (secRef.containsReference()) {
        Element bstElement = secRef.getTokenElement(strElement.getOwnerDocument(), wsDocInfo,
                data.getCallbackHandler());

        // at this point ... check token type: Binary
        QName el = new QName(bstElement.getNamespaceURI(), bstElement.getLocalName());
        if (el.equals(WSSecurityEngine.BINARY_TOKEN)) {
            X509Security token = new X509Security(bstElement);
            if (bspCompliant) {
                BSPEnforcer.checkBinarySecurityBSPCompliance(secRef, token);
            }
            certs = new X509Certificate[] { token.getX509Certificate(crypto) };
        } else {
            throw new WSSecurityException(WSSecurityException.UNSUPPORTED_SECURITY_TOKEN,
                    "unsupportedBinaryTokenType", null);
        }
    }

    if (LOG.isDebugEnabled() && certs != null && certs[0] != null) {
        LOG.debug("cert: " + certs[0]);
    }
}

From source file:org.apache.ws.security.util.WSSecurityUtil.java

/**
 * create a new element in the same namespace <p/>
 * /*from w  w  w . ja va 2 s . c om*/
 * @param parent for the new element
 * @param localName of the new element
 * @return the new element
 */
private static Element createElementInSameNamespace(Element parent, String localName) {
    String qName = localName;
    String prefix = parent.getPrefix();
    if (prefix != null && prefix.length() > 0) {
        qName = prefix + ":" + localName;
    }

    String nsUri = parent.getNamespaceURI();
    return parent.getOwnerDocument().createElementNS(nsUri, qName);
}