List of usage examples for org.w3c.dom Element getLocalName
public String getLocalName();
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 ww w. j a va2 s . co 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(); }/*ww w . j a v a 2 s . com*/ // 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.SignatureProcessor.java
/** * Verify the WS-Security signature./*from w ww.j a va 2 s. co m*/ * * 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.saml.ext.OpenSAMLUtil.java
/** * Convert a SAML Assertion from a DOM Element to an XMLObject * * @param root of type Element/* w ww. j a va 2 s . co m*/ * @return XMLObject * @throws UnmarshallingException */ public static XMLObject fromDom(Element root) throws WSSecurityException { if (root == null) { LOG.debug("Attempting to unmarshal a null element!"); throw new WSSecurityException("Error unmarshalling a SAML assertion"); } Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(root); if (unmarshaller == null) { LOG.debug("Unable to find an unmarshaller for element: " + root.getLocalName()); throw new WSSecurityException("Error unmarshalling a SAML assertion"); } try { return unmarshaller.unmarshall(root); } catch (UnmarshallingException ex) { throw new WSSecurityException("Error unmarshalling a SAML assertion", ex); } }
From source file:org.apache.ws.security.str.EncryptedKeySTRParser.java
/** * Parse a SecurityTokenReference element and extract credentials. * /*from w w w. j a v a 2 s. 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
/** * find a child element with given namespace and local name <p/> * //from w ww . ja v a 2 s.c o m * @param parent the node to start the search * @param namespaceUri of the element * @param localName of the element * @return the found element or null if the element does not exist */ private static Element findChildElement(Element parent, String namespaceUri, String localName) { NodeList children = parent.getChildNodes(); int len = children.getLength(); for (int i = 0; i < len; i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { Element elementChild = (Element) child; if (namespaceUri.equals(elementChild.getNamespaceURI()) && localName.equals(elementChild.getLocalName())) { return elementChild; } } } return null; }
From source file:org.apache.xml.security.keys.keyresolver.implementations.RetrievalMethodResolver.java
/** * Retrieves a x509Certificate from the given information * @param e/*from w w w. j a va 2s .com*/ * @param BaseURI * @param storage * @return * @throws KeyResolverException */ private static X509Certificate resolveCertificate(Element e, String BaseURI, StorageResolver storage) throws KeyResolverException { if (log.isDebugEnabled()) { log.debug("Now we have a {" + e.getNamespaceURI() + "}" + e.getLocalName() + " Element"); } // An element has been provided if (e != null) { return KeyResolver.getX509Certificate(e, BaseURI, storage); } return null; }
From source file:org.apache.xml.security.keys.keyresolver.implementations.RetrievalMethodResolver.java
/** * Retrieves a PublicKey from the given information * @param e/*from ww w .jav a 2s. c o m*/ * @param BaseURI * @param storage * @return * @throws KeyResolverException */ private static PublicKey resolveKey(Element e, String BaseURI, StorageResolver storage) throws KeyResolverException { if (log.isDebugEnabled()) { log.debug("Now we have a {" + e.getNamespaceURI() + "}" + e.getLocalName() + " Element"); } // An element has been provided if (e != null) { return KeyResolver.getPublicKey(e, BaseURI, storage); } return null; }
From source file:org.apache.xml.security.signature.Reference.java
/** * Build a {@link Reference} from an {@link Element} * * @param element <code>Reference</code> element * @param BaseURI the URI of the resource where the XML instance was stored * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs. * We need this because the Manifest has the individual {@link ResourceResolver}s which have * been set by the user/*from w ww . jav a 2 s .c o m*/ * @throws XMLSecurityException */ protected Reference(Element element, String BaseURI, Manifest manifest) throws XMLSecurityException { super(element, BaseURI); this.baseURI = BaseURI; Element el = XMLUtils.getNextElement(element.getFirstChild()); if (Constants._TAG_TRANSFORMS.equals(el.getLocalName()) && Constants.SignatureSpecNS.equals(el.getNamespaceURI())) { transforms = new Transforms(el, this.baseURI); el = XMLUtils.getNextElement(el.getNextSibling()); } digestMethodElem = el; digestValueElement = XMLUtils.getNextElement(digestMethodElem.getNextSibling()); this.manifest = manifest; }
From source file:org.apache.xml.security.signature.XMLSignature.java
/** * This will parse the element and construct the Java Objects. * That will allow a user to validate the signature. * * @param element ds:Signature element that contains the whole signature * @param BaseURI URI to be prepended to all relative URIs * @throws XMLSecurityException/* www . j av a 2 s .c om*/ * @throws XMLSignatureException if the signature is badly formatted */ public XMLSignature(Element element, String BaseURI) throws XMLSignatureException, XMLSecurityException { super(element, BaseURI); // check out SignedInfo child Element signedInfoElem = XMLUtils.getNextElement(element.getFirstChild()); // check to see if it is there if (signedInfoElem == null) { Object exArgs[] = { Constants._TAG_SIGNEDINFO, Constants._TAG_SIGNATURE }; throw new XMLSignatureException("xml.WrongContent", exArgs); } // create a SignedInfo object from that element this.signedInfo = new SignedInfo(signedInfoElem, BaseURI); // get signedInfoElem again in case it has changed signedInfoElem = XMLUtils.getNextElement(element.getFirstChild()); // check out SignatureValue child this.signatureValueElement = XMLUtils.getNextElement(signedInfoElem.getNextSibling()); // check to see if it exists if (signatureValueElement == null) { Object exArgs[] = { Constants._TAG_SIGNATUREVALUE, Constants._TAG_SIGNATURE }; throw new XMLSignatureException("xml.WrongContent", exArgs); } // <element ref="ds:KeyInfo" minOccurs="0"/> Element keyInfoElem = XMLUtils.getNextElement(signatureValueElement.getNextSibling()); // If it exists use it, but it's not mandatory if (keyInfoElem != null && keyInfoElem.getNamespaceURI().equals(Constants.SignatureSpecNS) && keyInfoElem.getLocalName().equals(Constants._TAG_KEYINFO)) { this.keyInfo = new KeyInfo(keyInfoElem, BaseURI); } this.state = MODE_VERIFY; }