ws-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From cohei...@apache.org
Subject svn commit: r1051143 [1/2] - in /webservices/wss4j/trunk/src: main/java/org/apache/ws/security/ main/java/org/apache/ws/security/handler/ main/java/org/apache/ws/security/message/token/ main/java/org/apache/ws/security/processor/ main/java/org/apache/w...
Date Mon, 20 Dec 2010 15:22:01 GMT
Author: coheigea
Date: Mon Dec 20 15:22:01 2010
New Revision: 1051143

URL: http://svn.apache.org/viewvc?rev=1051143&view=rev
Log:
[WSS-232] - Moved all SecurityTokenReference key derivation into a new interface
 - Added implementations for the various processors that require this
 - There's still some work to be done to cleanup this change

Added:
    webservices/wss4j/trunk/src/main/java/org/apache/ws/security/str/
    webservices/wss4j/trunk/src/main/java/org/apache/ws/security/str/DerivedKeyTokenSTRParser.java
    webservices/wss4j/trunk/src/main/java/org/apache/ws/security/str/EncryptedKeySTRParser.java
    webservices/wss4j/trunk/src/main/java/org/apache/ws/security/str/STRParser.java
    webservices/wss4j/trunk/src/main/java/org/apache/ws/security/str/SecurityTokenRefSTRParser.java
    webservices/wss4j/trunk/src/main/java/org/apache/ws/security/str/SignatureSTRParser.java
Modified:
    webservices/wss4j/trunk/src/main/java/org/apache/ws/security/WSDocInfo.java
    webservices/wss4j/trunk/src/main/java/org/apache/ws/security/handler/WSHandler.java
    webservices/wss4j/trunk/src/main/java/org/apache/ws/security/message/token/DerivedKeyToken.java
    webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java
    webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/EncryptedKeyProcessor.java
    webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/ReferenceListProcessor.java
    webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/SignatureProcessor.java
    webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/TimestampProcessor.java
    webservices/wss4j/trunk/src/test/java/org/apache/ws/security/components/crypto/CryptoProviderTest.java

Modified: webservices/wss4j/trunk/src/main/java/org/apache/ws/security/WSDocInfo.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/src/main/java/org/apache/ws/security/WSDocInfo.java?rev=1051143&r1=1051142&r2=1051143&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/main/java/org/apache/ws/security/WSDocInfo.java (original)
+++ webservices/wss4j/trunk/src/main/java/org/apache/ws/security/WSDocInfo.java Mon Dec 20 15:22:01 2010
@@ -84,6 +84,7 @@ public class WSDocInfo {
      *  - SecurityContextToken element
      *  - UsernameToken element
      *  - DerivedKeyToken element
+     *  - Timestamp element
      * @param elem is the token element to store
      */
     public void addTokenElement(Element elem) {

Modified: webservices/wss4j/trunk/src/main/java/org/apache/ws/security/handler/WSHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/src/main/java/org/apache/ws/security/handler/WSHandler.java?rev=1051143&r1=1051142&r2=1051143&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/main/java/org/apache/ws/security/handler/WSHandler.java (original)
+++ webservices/wss4j/trunk/src/main/java/org/apache/ws/security/handler/WSHandler.java Mon Dec 20 15:22:01 2010
@@ -34,7 +34,6 @@ import org.apache.ws.security.components
 import org.apache.ws.security.message.WSSecHeader;
 import org.apache.ws.security.message.token.SignatureConfirmation;
 import org.apache.ws.security.message.token.Timestamp;
-import org.apache.ws.security.processor.SignatureProcessor;
 import org.apache.ws.security.util.Loader;
 import org.apache.ws.security.util.StringUtil;
 import org.apache.ws.security.util.WSSecurityUtil;
@@ -1088,29 +1087,6 @@ public abstract class WSHandler {
     }
 
     /**
-     * Evaluate whether a given certificate should be trusted.
-     * Hook to allow subclasses to implement custom validation methods however they see fit.
-     * <p/>
-     * Policy used in this implementation:
-     * 1. Search the keystore for the transmitted certificate
-     * 2. Search the keystore for a connection to the transmitted certificate
-     * (that is, search for certificate(s) of the issuer of the transmitted certificate
-     * 3. Verify the trust path for those certificates found because the search for the issuer 
-     * might be fooled by a phony DN (String!)
-     *
-     * @param cert the certificate that should be validated against the keystore
-     * @return true if the certificate is trusted, false if not (AxisFault is thrown for exceptions
-     * during CertPathValidation)
-     * @throws WSSecurityException
-     * @Deprecated Trust is verified on signature certificates in the SignatureProcessor by default
-     */
-    protected boolean verifyTrust(X509Certificate cert, RequestData reqData) 
-        throws WSSecurityException {
-        return SignatureProcessor.verifyTrust(cert, reqData.getSigCrypto());
-    }
-    
-    
-    /**
      * Evaluate whether a timestamp is considered valid on the receivers' side. Hook to
      * allow subclasses to implement custom validation methods however they see fit.
      * 

Modified: webservices/wss4j/trunk/src/main/java/org/apache/ws/security/message/token/DerivedKeyToken.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/src/main/java/org/apache/ws/security/message/token/DerivedKeyToken.java?rev=1051143&r1=1051142&r2=1051143&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/main/java/org/apache/ws/security/message/token/DerivedKeyToken.java (original)
+++ webservices/wss4j/trunk/src/main/java/org/apache/ws/security/message/token/DerivedKeyToken.java Mon Dec 20 15:22:01 2010
@@ -189,6 +189,15 @@ public class DerivedKeyToken {
     }
     
     /**
+     * Returns the SecurityTokenReference element of the derived key token
+     *
+     * @return the Security Token Reference element of the derived key token
+     */
+    public Element getSecurityTokenReferenceElement() {
+        return elementSecurityTokenReference;
+    }
+    
+    /**
      * This adds a property into
      * /DerivedKeyToken/Properties
      *

Modified: webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java?rev=1051143&r1=1051142&r2=1051143&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java (original)
+++ webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java Mon Dec 20 15:22:01 2010
@@ -21,25 +21,17 @@ package org.apache.ws.security.processor
 
 import org.apache.ws.security.WSConstants;
 import org.apache.ws.security.WSDocInfo;
-import org.apache.ws.security.WSPasswordCallback;
 import org.apache.ws.security.WSSConfig;
 import org.apache.ws.security.WSSecurityEngineResult;
 import org.apache.ws.security.WSSecurityException;
 import org.apache.ws.security.components.crypto.Crypto;
 import org.apache.ws.security.message.token.DerivedKeyToken;
-import org.apache.ws.security.message.token.Reference;
-import org.apache.ws.security.message.token.SecurityTokenReference;
-import org.apache.ws.security.message.token.UsernameToken;
-import org.apache.ws.security.saml.SAMLKeyInfo;
-import org.apache.ws.security.saml.SAMLUtil;
+import org.apache.ws.security.str.DerivedKeyTokenSTRParser;
+import org.apache.ws.security.str.STRParser;
 import org.w3c.dom.Element;
 
-import javax.security.auth.callback.Callback;
 import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.UnsupportedCallbackException;
 
-import java.io.IOException;
-import java.security.cert.X509Certificate;
 import java.util.List;
 
 /**
@@ -60,7 +52,17 @@ public class DerivedKeyTokenProcessor im
         
         // Deserialize the DKT
         DerivedKeyToken dkt = new DerivedKeyToken(elem);
-        byte[] secret = extractSecret(wsDocInfo, dkt, cb, crypto);
+        byte[] secret = null;
+        Element secRefElement = dkt.getSecurityTokenReferenceElement();
+        if (secRefElement != null) {
+            STRParser strParser = new DerivedKeyTokenSTRParser();
+            strParser.parseSecurityTokenReference(
+                secRefElement, null, crypto, cb, wsDocInfo, null
+            );
+            secret = strParser.getSecretKey();
+        } else {
+            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "noReference");
+        }
         
         String tempNonce = dkt.getNonce();
         if (tempNonce == null) {
@@ -83,192 +85,5 @@ public class DerivedKeyTokenProcessor im
         return new java.util.ArrayList<WSSecurityEngineResult>(0);
     }
 
-    /**
-     * @param wsDocInfo
-     * @param dkt
-     * @return the secret, as an array of bytes
-     * @throws WSSecurityException
-     */
-    private byte[] extractSecret(
-        WSDocInfo wsDocInfo, 
-        DerivedKeyToken dkt, 
-        CallbackHandler cb, 
-        Crypto crypto
-    ) throws WSSecurityException {
-        SecurityTokenReference str = dkt.getSecurityTokenReference();
-        if (str != null) {
-            String uri = null;
-            String keyIdentifierValueType = null;
-            String keyIdentifierValue = null;
-            
-            WSSecurityEngineResult result = null;
-            if (str.containsReference()) {
-                Reference ref = str.getReference();
-                uri = ref.getURI();
-                if (uri.charAt(0) == '#') {
-                    uri = uri.substring(1);
-                }
-                result = wsDocInfo.getResult(uri);
-            } else {
-                // Contains key identifier
-                keyIdentifierValue = str.getKeyIdentifierValue();
-                keyIdentifierValueType = str.getKeyIdentifierValueType();
-                result = wsDocInfo.getResult(keyIdentifierValue);
-            }
-            
-            if (result != null) {
-                int action = ((Integer)result.get(WSSecurityEngineResult.TAG_ACTION)).intValue();
-                if (WSConstants.UT == action) {
-                    UsernameToken usernameToken = 
-                        (UsernameToken)result.get(WSSecurityEngineResult.TAG_USERNAME_TOKEN);
-                    return usernameToken.getDerivedKey();
-                } else if (WSConstants.ENCR == action) {
-                    return (byte[])result.get(WSSecurityEngineResult.TAG_DECRYPTED_KEY);
-                } else if (WSConstants.SCT == action) {
-                    return (byte[])result.get(WSSecurityEngineResult.TAG_SECRET);
-                } else if (WSConstants.ST_UNSIGNED == action) {
-                    Element samlElement = wsDocInfo.getTokenElement(uri);
-                    SAMLKeyInfo keyInfo = 
-                        SAMLUtil.getSAMLKeyInfo(samlElement, crypto, cb);
-                    // TODO Handle malformed SAML tokens where they don't have the 
-                    // secret in them
-                    return keyInfo.getSecret();
-                } else {
-                    throw new WSSecurityException(
-                        WSSecurityException.FAILED_CHECK, "unsupportedKeyId"
-                    );
-                }
-            } else if (result == null && uri != null) {
-                // Now use the callback and get it
-                return getSecret(cb, uri);
-            } else if (keyIdentifierValue != null && keyIdentifierValueType != null) {
-                X509Certificate[] certs = str.getKeyIdentifier(crypto);
-                if (certs == null || certs.length < 1 || certs[0] == null) {
-                    return this.getSecret(cb, keyIdentifierValue, keyIdentifierValueType); 
-                } else {
-                    return this.getSecret(cb, crypto, certs);
-                }
-            } else {
-                throw new WSSecurityException(
-                    WSSecurityException.FAILED_CHECK, "unsupportedKeyId"
-                );
-            }
-        } else {
-            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "noReference");
-        }
-    }
-
-    private byte[] getSecret(CallbackHandler cb, String id) throws WSSecurityException {
-        if (cb == null) {
-            throw new WSSecurityException(WSSecurityException.FAILURE, "noCallback");
-        }
-
-        WSPasswordCallback callback = 
-            new WSPasswordCallback(id, WSPasswordCallback.SECURITY_CONTEXT_TOKEN);
-        try {
-            Callback[] callbacks = new Callback[]{callback};
-            cb.handle(callbacks);
-        } catch (IOException e) {
-            throw new WSSecurityException(
-                WSSecurityException.FAILURE, 
-                "noKey",
-                new Object[] {id}, 
-                e
-            );
-        } catch (UnsupportedCallbackException e) {
-            throw new WSSecurityException(
-                WSSecurityException.FAILURE,
-                "noKey",
-                new Object[] {id}, 
-                e
-            );
-        }
-
-        return callback.getKey();
-    }
-    
-    private byte[] getSecret(
-        CallbackHandler cb, 
-        String keyIdentifierValue, 
-        String keyIdentifierType
-    ) throws WSSecurityException {
-        if (cb == null) {
-            throw new WSSecurityException(WSSecurityException.FAILURE, "noCallback");
-        }
-        
-        WSPasswordCallback pwcb = 
-            new WSPasswordCallback(
-                keyIdentifierValue, null, keyIdentifierType, WSPasswordCallback.ENCRYPTED_KEY_TOKEN
-            );
-        try {
-            Callback[] callbacks = new Callback[]{pwcb};
-            cb.handle(callbacks);
-        } catch (IOException e) {
-            throw new WSSecurityException(
-                WSSecurityException.FAILURE, 
-                "noKey",
-                new Object[] {keyIdentifierValue}, 
-                e
-            );
-        } catch (UnsupportedCallbackException e) {
-            throw new WSSecurityException(
-                WSSecurityException.FAILURE, 
-                "noKey",
-                new Object[] {keyIdentifierValue}, 
-                e
-            );
-        }
-            
-        return pwcb.getKey();
-    }
-    
-    private byte[] getSecret(
-        CallbackHandler cb,
-        Crypto crypto,
-        X509Certificate certs[]
-    ) throws WSSecurityException {
-        if (cb == null) {
-            throw new WSSecurityException(WSSecurityException.FAILURE, "noCallback");
-        }
-
-        String alias = crypto.getAliasForX509Cert(certs[0]);
-
-        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}
-            );
-        }
-
-        java.security.Key privateKey;
-        try {
-            privateKey = crypto.getPrivateKey(alias, password);
-            return privateKey.getEncoded();
-        } catch (Exception e) {
-            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e);
-        }
-    }
-
 
 }

Modified: webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/EncryptedKeyProcessor.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/EncryptedKeyProcessor.java?rev=1051143&r1=1051142&r2=1051143&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/EncryptedKeyProcessor.java (original)
+++ webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/EncryptedKeyProcessor.java Mon Dec 20 15:22:01 2010
@@ -26,14 +26,12 @@ import org.apache.ws.security.WSDataRef;
 import org.apache.ws.security.WSDocInfo;
 import org.apache.ws.security.WSPasswordCallback;
 import org.apache.ws.security.WSSConfig;
-import org.apache.ws.security.WSSecurityEngine;
 import org.apache.ws.security.WSSecurityEngineResult;
 import org.apache.ws.security.WSSecurityException;
 import org.apache.ws.security.components.crypto.Crypto;
 import org.apache.ws.security.message.token.SecurityTokenReference;
-import org.apache.ws.security.message.token.X509Security;
-import org.apache.ws.security.saml.SAMLKeyInfo;
-import org.apache.ws.security.saml.SAMLUtil;
+import org.apache.ws.security.str.EncryptedKeySTRParser;
+import org.apache.ws.security.str.STRParser;
 import org.apache.ws.security.util.Base64;
 import org.apache.ws.security.util.WSSecurityUtil;
 import org.w3c.dom.Document;
@@ -48,7 +46,6 @@ import javax.crypto.SecretKey;
 import javax.security.auth.callback.Callback;
 import javax.security.auth.callback.CallbackHandler;
 import javax.security.auth.callback.UnsupportedCallbackException;
-import javax.xml.namespace.QName;
 
 import java.io.IOException;
 import java.security.PrivateKey;
@@ -98,8 +95,7 @@ public class EncryptedKeyProcessor imple
             throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "noCipher");
         }
         
-        String alias = 
-            getAliasFromEncryptedKey(elem, decCrypto, elem.getOwnerDocument(), cb, wsDocInfo);
+        String alias = getAliasFromEncryptedKey(elem, decCrypto, cb, wsDocInfo);
         PrivateKey privateKey = getPrivateKeyFromKeyInfo(decCrypto, cb, alias);
         X509Certificate[] certs = decCrypto.getCertificates(alias);
 
@@ -147,7 +143,7 @@ public class EncryptedKeyProcessor imple
      * @return a byte array containing the decoded data
      * @throws WSSecurityException
      */
-    public static byte[] getDecodedBase64EncodedData(Element element) throws WSSecurityException {
+    private static byte[] getDecodedBase64EncodedData(Element element) throws WSSecurityException {
         StringBuilder sb = new StringBuilder();
         Node node = element.getFirstChild();
         while (node != null) {
@@ -167,7 +163,6 @@ public class EncryptedKeyProcessor imple
     private String getAliasFromEncryptedKey(
         Element xencEncryptedKey,
         Crypto crypto,
-        Document doc,
         CallbackHandler cb,
         WSDocInfo wsDocInfo
     ) throws WSSecurityException {
@@ -177,7 +172,28 @@ public class EncryptedKeyProcessor imple
             );
         String alias = null;
         if (keyInfo != null) {
-            alias = getAliasFromKeyInfo(keyInfo, crypto, doc, cb, wsDocInfo);
+            Element strElement = 
+                WSSecurityUtil.getDirectChildElement(
+                    keyInfo,
+                    SecurityTokenReference.SECURITY_TOKEN_REFERENCE,
+                    WSConstants.WSSE_NS
+                );
+            if (strElement == null) {
+                throw new WSSecurityException(
+                    WSSecurityException.INVALID_SECURITY, "noSecTokRef"
+                );
+            }
+            STRParser strParser = new EncryptedKeySTRParser();
+            strParser.parseSecurityTokenReference(strElement, null, crypto, cb, wsDocInfo, null);
+            X509Certificate[] certs = strParser.getCertificates();
+            if (certs == null || certs.length < 1 || certs[0] == null) {
+                throw new WSSecurityException(
+                    WSSecurityException.FAILURE,
+                    "noCertsFound", 
+                    new Object[] {"decryption (KeyId)"}
+                );
+            }
+            alias = crypto.getAliasForX509Cert(certs[0]);
         } else if (crypto.getDefaultX509Alias() != null) {
             alias = crypto.getDefaultX509Alias();
         } else {
@@ -246,170 +262,6 @@ public class EncryptedKeyProcessor imple
     
     
     /**
-     * @return Get the alias of the public key from the KeyInfo element
-     */
-    private String getAliasFromKeyInfo(
-        Element keyInfo,
-        Crypto crypto,
-        Document doc,
-        CallbackHandler cb,
-        WSDocInfo wsDocInfo
-    ) throws WSSecurityException {
-        Element secRefToken = 
-            WSSecurityUtil.getDirectChildElement(
-                keyInfo, "SecurityTokenReference", WSConstants.WSSE_NS
-            );
-        //
-        // EncryptedKey must have 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 :-).
-        //
-        String alias = null;
-        X509Certificate[] certs = 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()) {
-            if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) { 
-                Element token = 
-                    secRef.getKeyIdentifierTokenElement(doc, wsDocInfo, cb);
-                
-                if (crypto == null) {
-                    throw new WSSecurityException(
-                        WSSecurityException.FAILURE, "noSigCryptoFile"
-                    );
-                }
-                SAMLKeyInfo samlKi = SAMLUtil.getSAMLKeyInfo(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]);
-            if (log.isDebugEnabled()) {
-                log.debug("cert: " + certs[0]);
-                log.debug("KeyIdentifier Alias: " + alias);
-            }
-        } else if (secRef.containsReference()) {
-            if (wsDocInfo != null) {
-                String uri = secRef.getReference().getURI();
-                WSSecurityEngineResult result = wsDocInfo.getResult(uri);
-                
-                if (result != null) {
-                    int action = ((Integer)result.get(WSSecurityEngineResult.TAG_ACTION)).intValue();
-                    if (WSConstants.BST == action) {
-                        certs = 
-                            (X509Certificate[])result.get(
-                                WSSecurityEngineResult.TAG_X509_CERTIFICATES
-                            );
-                    } else {
-                        throw new WSSecurityException(
-                            WSSecurityException.UNSUPPORTED_SECURITY_TOKEN,
-                            "unsupportedBinaryTokenType",
-                            null
-                        );
-                    }
-                }
-            }
-            if (certs == null) {
-                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.BINARY_TOKEN)) {
-                    X509Security token = new X509Security(bstElement);
-                    if (token == null) {
-                        throw new WSSecurityException(
-                            WSSecurityException.UNSUPPORTED_SECURITY_TOKEN,
-                            "unsupportedBinaryTokenType",
-                            new Object[] {"for decryption (BST)"}
-                        );
-                    }
-                    certs = new X509Certificate[]{token.getX509Certificate(crypto)};
-                } else {
-                    throw new WSSecurityException(
-                        WSSecurityException.UNSUPPORTED_SECURITY_TOKEN,
-                        "unsupportedBinaryTokenType",
-                        null
-                    );
-                }
-            }
-            if (certs == null || certs[0] == 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(certs[0]);
-            if (log.isDebugEnabled()) {
-                log.debug("BST Alias: " + alias);
-            }
-            //
-            // 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"
-            );
-        }
-        return alias;
-    }
-    
-    /**
      * Decrypt all data references
      */
     private List<WSDataRef> decryptDataRefs(

Modified: webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/ReferenceListProcessor.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/ReferenceListProcessor.java?rev=1051143&r1=1051142&r2=1051143&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/ReferenceListProcessor.java (original)
+++ webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/ReferenceListProcessor.java Mon Dec 20 15:22:01 2010
@@ -23,7 +23,6 @@ import java.util.ArrayList;
 import java.util.List;
 
 import javax.crypto.SecretKey;
-import javax.security.auth.callback.Callback;
 import javax.security.auth.callback.CallbackHandler;
 
 import org.apache.commons.logging.Log;
@@ -31,16 +30,12 @@ import org.apache.commons.logging.LogFac
 import org.apache.ws.security.WSConstants;
 import org.apache.ws.security.WSDataRef;
 import org.apache.ws.security.WSDocInfo;
-import org.apache.ws.security.WSPasswordCallback;
 import org.apache.ws.security.WSSConfig;
 import org.apache.ws.security.WSSecurityEngineResult;
 import org.apache.ws.security.WSSecurityException;
 import org.apache.ws.security.components.crypto.Crypto;
-import org.apache.ws.security.message.token.DerivedKeyToken;
-import org.apache.ws.security.message.token.Reference;
-import org.apache.ws.security.message.token.SecurityTokenReference;
-import org.apache.ws.security.saml.SAMLKeyInfo;
-import org.apache.ws.security.saml.SAMLUtil;
+import org.apache.ws.security.str.STRParser;
+import org.apache.ws.security.str.SecurityTokenRefSTRParser;
 import org.apache.ws.security.util.WSSecurityUtil;
 import org.apache.xml.security.encryption.XMLCipher;
 import org.apache.xml.security.encryption.XMLEncryptionException;
@@ -70,6 +65,7 @@ public class ReferenceListProcessor impl
         List<WSDataRef> dataRefs = handleReferenceList(elem, cb, decCrypto, wsDocInfo);
         WSSecurityEngineResult result = 
             new WSSecurityEngineResult(WSConstants.ENCR, dataRefs);
+        wsDocInfo.addTokenElement(elem);
         wsDocInfo.addResult(result);
         return java.util.Collections.singletonList(result);
     }
@@ -150,8 +146,12 @@ public class ReferenceListProcessor impl
         if (secRefToken == null) {
             symmetricKey = X509Util.getSharedKey(keyInfoElement, symEncAlgo, cb);
         } else {
-            symmetricKey = 
-                getKeyFromSecurityTokenReference(secRefToken, symEncAlgo, crypto, cb, wsDocInfo);
+            STRParser strParser = new SecurityTokenRefSTRParser();
+            strParser.parseSecurityTokenReference(
+                secRefToken, symEncAlgo, crypto, cb, wsDocInfo, null
+            );
+            byte[] secretKey = strParser.getSecretKey();
+            symmetricKey = WSSecurityUtil.prepareSecretKey(symEncAlgo, secretKey);
         }
         
         return 
@@ -266,132 +266,6 @@ public class ReferenceListProcessor impl
         return null;
     }
 
-    /**
-     * Retrieves a secret key (session key) from a already parsed EncryptedKey
-     * element
-     * 
-     * 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 EncryptedKey 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,
-        WSDocInfo wsDocInfo
-    ) 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);
-            }
-            WSSecurityEngineResult result = wsDocInfo.getResult(id);
-            if (result != null) {
-                int action = ((Integer)result.get(WSSecurityEngineResult.TAG_ACTION)).intValue();
-                if (WSConstants.ENCR == action) {
-                    decryptedData = (byte[])result.get(WSSecurityEngineResult.TAG_DECRYPTED_KEY);
-                } else if (WSConstants.DKT == action) {
-                    DerivedKeyToken dkt = 
-                        (DerivedKeyToken)result.get(WSSecurityEngineResult.TAG_DERIVED_KEY_TOKEN);
-                    byte[] secret = 
-                        (byte[])result.get(WSSecurityEngineResult.TAG_SECRET);
-                    decryptedData = dkt.deriveKey(WSSecurityUtil.getKeyLength(algorithm), secret);
-                } else if (WSConstants.ST_UNSIGNED == action) {
-                    Element samlElement = wsDocInfo.getTokenElement(id);
-                    SAMLKeyInfo keyInfo = 
-                        SAMLUtil.getSAMLKeyInfo(samlElement, crypto, cb);
-                    // TODO Handle malformed SAML tokens where they don't have the 
-                    // secret in them
-                    decryptedData = keyInfo.getSecret();
-                } else if (WSConstants.SCT == action) {
-                    decryptedData = (byte[])result.get(WSSecurityEngineResult.TAG_SECRET);
-                }
-            } 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 {
-                String keyIdentifierValue = secRef.getKeyIdentifierValue();
-                WSPasswordCallback pwcb = 
-                    new WSPasswordCallback(
-                        keyIdentifierValue,
-                        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[] {keyIdentifierValue}, 
-                        e
-                    );
-                }
-                decryptedData = pwcb.getKey();
-            }
-        } else {
-            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "noReference");
-        }
-        return WSSecurityUtil.prepareSecretKey(algorithm, decryptedData);
-    }
-    
     
     /**
      * @param decryptedNode the decrypted node

Modified: webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/SignatureProcessor.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/SignatureProcessor.java?rev=1051143&r1=1051142&r2=1051143&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/SignatureProcessor.java (original)
+++ webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/SignatureProcessor.java Mon Dec 20 15:22:01 2010
@@ -21,34 +21,24 @@ package org.apache.ws.security.processor
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
-import org.apache.ws.security.CustomTokenPrincipal;
 import org.apache.ws.security.PublicKeyCallback;
 import org.apache.ws.security.PublicKeyPrincipal;
 import org.apache.ws.security.WSConstants;
 import org.apache.ws.security.WSDataRef;
 import org.apache.ws.security.WSDocInfo;
-import org.apache.ws.security.WSPasswordCallback;
 import org.apache.ws.security.WSSConfig;
-import org.apache.ws.security.WSSecurityEngine;
 import org.apache.ws.security.WSSecurityEngineResult;
 import org.apache.ws.security.WSSecurityException;
 import org.apache.ws.security.WSUsernameTokenPrincipal;
 import org.apache.ws.security.components.crypto.Crypto;
 import org.apache.ws.security.message.DOMURIDereferencer;
-import org.apache.ws.security.message.token.BinarySecurity;
-import org.apache.ws.security.message.token.DerivedKeyToken;
-import org.apache.ws.security.message.token.PKIPathSecurity;
-import org.apache.ws.security.message.token.SecurityContextToken;
 import org.apache.ws.security.message.token.SecurityTokenReference;
-import org.apache.ws.security.message.token.UsernameToken;
-import org.apache.ws.security.message.token.X509Security;
-import org.apache.ws.security.saml.SAMLKeyInfo;
-import org.apache.ws.security.saml.SAMLUtil;
+import org.apache.ws.security.str.STRParser;
+import org.apache.ws.security.str.SignatureSTRParser;
 import org.apache.ws.security.transform.STRTransform;
 import org.apache.ws.security.transform.STRTransformUtil;
 import org.apache.ws.security.util.WSSecurityUtil;
 
-import org.opensaml.SAMLAssertion;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -69,33 +59,21 @@ import javax.xml.crypto.dsig.XMLSignatur
 import javax.xml.crypto.dsig.XMLValidateContext;
 import javax.xml.crypto.dsig.dom.DOMValidateContext;
 import javax.xml.crypto.dsig.keyinfo.KeyInfo;
-import javax.xml.crypto.dsig.keyinfo.KeyValue;
 import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
+import javax.xml.crypto.dsig.keyinfo.KeyValue;
 
-import javax.xml.namespace.QName;
-
-import java.math.BigInteger;
 import java.security.Key;
 import java.security.PublicKey;
 import java.security.Principal;
-import java.security.cert.CertificateExpiredException;
-import java.security.cert.CertificateNotYetValidException;
 import java.security.cert.X509Certificate;
 import java.util.List;
 
 public class SignatureProcessor implements Processor {
     private static Log log = LogFactory.getLog(SignatureProcessor.class.getName());
     
-    private X509Certificate[] certs;
-    
-    private byte[] signatureValue;
-    
-    private KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance("DOM");
     private XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
-
-    private String signatureMethod;
     
-    private String c14nMethod;
+    private KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance("DOM");
 
     public List<WSSecurityEngineResult> handleToken(
         Element elem, 
@@ -108,31 +86,177 @@ public class SignatureProcessor implemen
         if (log.isDebugEnabled()) {
             log.debug("Found signature element");
         }
-        List<WSDataRef> protectedRefs = new java.util.ArrayList<WSDataRef>();
-        Principal lastPrincipalFound = null;
-        
-        try {
-            lastPrincipalFound = 
-                verifyXMLSignature(
-                    elem, crypto, protectedRefs, cb, wsDocInfo, wsc
+        Element keyInfoElement = 
+            WSSecurityUtil.getDirectChildElement(
+                elem,
+                "KeyInfo",
+                WSConstants.SIG_NS
+            );
+        X509Certificate[] certs = null;
+        Principal principal = null;
+        PublicKey publicKey = null;
+        byte[] secretKey = null;
+        String signatureMethod = getSignatureMethod(elem);
+        if (keyInfoElement == null) {
+            certs = getDefaultCerts(crypto);
+            principal = certs[0].getSubjectX500Principal();
+        } else {
+            Element strElement = 
+                WSSecurityUtil.getDirectChildElement(
+                    keyInfoElement,
+                    SecurityTokenReference.SECURITY_TOKEN_REFERENCE,
+                    WSConstants.WSSE_NS
+                );
+            if (strElement == null) {
+                publicKey = parseKeyValue(keyInfoElement);
+                principal = validatePublicKey(cb, publicKey);
+            } else {
+                STRParser strParser = new SignatureSTRParser();
+                strParser.parseSecurityTokenReference(
+                    strElement, signatureMethod, crypto, cb, wsDocInfo, wsc
                 );
-        } catch (WSSecurityException ex) {
-            throw ex;
+                strParser.validateCredentials();
+                principal = strParser.getPrincipal();
+                certs = strParser.getCertificates();
+                publicKey = strParser.getPublicKey();
+                secretKey = strParser.getSecretKey();
+            }
         }
+        
+        //
+        // Check that we have a certificate, a public key or a secret key with which to
+        // perform signature verification
+        //
+        if ((certs == null || certs.length == 0 || certs[0] == null) 
+            && secretKey == null
+            && publicKey == null) {
+            throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
+        }
+        
+        XMLSignature xmlSignature = 
+            verifyXMLSignature(elem, certs, publicKey, secretKey, signatureMethod, wsDocInfo);
+        byte[] signatureValue = xmlSignature.getSignatureValue().getValue();
+        String c14nMethod = xmlSignature.getSignedInfo().getCanonicalizationMethod().getAlgorithm();
+        List<WSDataRef> dataRefs =  
+            buildProtectedRefs(
+                elem.getOwnerDocument(), xmlSignature.getSignedInfo(), wsDocInfo
+            );
+        
         int actionPerformed = WSConstants.SIGN;
-        if (lastPrincipalFound instanceof WSUsernameTokenPrincipal) {
+        if (principal instanceof WSUsernameTokenPrincipal) {
             actionPerformed = WSConstants.UT_SIGN;
         }
 
         WSSecurityEngineResult result = new WSSecurityEngineResult(
-                actionPerformed, lastPrincipalFound,
-                certs, protectedRefs, signatureValue);
+                actionPerformed, principal,
+                certs, dataRefs, signatureValue);
         result.put(WSSecurityEngineResult.TAG_SIGNATURE_METHOD, signatureMethod);
         result.put(WSSecurityEngineResult.TAG_CANONICALIZATION_METHOD, c14nMethod);
         result.put(WSSecurityEngineResult.TAG_ID, elem.getAttribute("Id"));
         wsDocInfo.addResult(result);
         return java.util.Collections.singletonList(result);
     }
+    
+    /**
+     * Get the default certificates from the KeyStore
+     * @param crypto The Crypto object containing the default alias
+     * @return The default certificates
+     * @throws WSSecurityException
+     */
+    private X509Certificate[] getDefaultCerts(
+        Crypto crypto
+    ) throws WSSecurityException {
+        if (crypto == null) {
+            throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
+        }
+        if (crypto.getDefaultX509Alias() != null) {
+            return crypto.getCertificates(crypto.getDefaultX509Alias());
+        } else {
+            throw new WSSecurityException(
+                WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo"
+            );
+        }
+    }
+    
+    private PublicKey parseKeyValue(
+        Element keyInfoElement
+    ) throws WSSecurityException {
+        KeyValue keyValue = null;
+        try {
+            //
+            // Look for a KeyValue object
+            //
+            keyValue = getKeyValue(keyInfoElement);
+        } catch (javax.xml.crypto.MarshalException ex) {
+            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, ex);
+        } 
+
+        if (keyValue != null) {
+            try {
+                //
+                // Look for a Public Key in Key Value
+                //
+                return keyValue.getPublicKey();
+            } catch (java.security.KeyException ex) {
+                log.error(ex.getMessage(), ex);
+                throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, ex);
+            }     
+        } else {
+            throw new WSSecurityException(
+                    WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo"
+            );
+        }
+    }
+    
+    /**
+     * Get the KeyValue object from the KeyInfo DOM element if it exists
+     */
+    private KeyValue getKeyValue(
+        Element keyInfoElement
+    ) throws MarshalException {
+        XMLStructure keyInfoStructure = new DOMStructure(keyInfoElement);
+        KeyInfo keyInfo = keyInfoFactory.unmarshalKeyInfo(keyInfoStructure);
+        List<?> list = keyInfo.getContent();
+
+        for (int i = 0; i < list.size(); i++) {
+            XMLStructure xmlStructure = (XMLStructure) list.get(i);
+            if (xmlStructure instanceof KeyValue) {
+                return (KeyValue)xmlStructure;
+            }
+        }
+        return null;
+    }
+    
+    /**
+     * Validate a public key via a CallbackHandler
+     * @param cb The CallbackHandler object
+     * @param publicKey The PublicKey to validate
+     * @return A PublicKeyPrincipal object encapsulating the public key after successful 
+     *         validation
+     * @throws WSSecurityException
+     */
+    private static Principal validatePublicKey(
+        CallbackHandler cb,
+        PublicKey publicKey
+    ) throws WSSecurityException {
+        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
+            );
+        }
+        return new PublicKeyPrincipal(publicKey);
+    }
+    
 
     /**
      * Verify the WS-Security signature.
@@ -165,232 +289,18 @@ public class SignatureProcessor implemen
      *         principal for further authentication or authorization.
      * @throws WSSecurityException
      */
-    protected Principal verifyXMLSignature(
+    private XMLSignature verifyXMLSignature(
         Element elem,
-        Crypto crypto,
-        List<WSDataRef> protectedRefs,
-        CallbackHandler cb,
-        WSDocInfo wsDocInfo,
-        WSSConfig wssConfig
+        X509Certificate[] certs,
+        PublicKey publicKey,
+        byte[] secretKey,
+        String signatureMethod,
+        WSDocInfo wsDocInfo
     ) throws WSSecurityException {
         if (log.isDebugEnabled()) {
             log.debug("Verify XML Signature");
         }
         
-        byte[] secretKey = null;
-        PublicKey publicKey = null;
-        Principal principal = null;
-        KeyValue keyValue = null;
-        boolean validateCertificateChain = false;
-        
-        Element keyInfoElement = 
-            WSSecurityUtil.getDirectChildElement(
-                elem,
-                "KeyInfo",
-                WSConstants.SIG_NS
-            );
-        
-        if (keyInfoElement != null) {
-            Element strElement = 
-                WSSecurityUtil.getDirectChildElement(
-                    keyInfoElement,
-                    SecurityTokenReference.SECURITY_TOKEN_REFERENCE,
-                    WSConstants.WSSE_NS
-                );
-            if (strElement == null) {
-                try {
-                    //
-                    // Look for a KeyValue object
-                    //
-                    keyValue = getKeyValue(keyInfoElement);
-                } catch (javax.xml.crypto.MarshalException ex) {
-                    throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, ex);
-                } 
-
-                if (keyValue != null) {
-                    try {
-                        //
-                        // Look for a Public Key in Key Value
-                        //
-                        publicKey = keyValue.getPublicKey();
-                        principal = validatePublicKey(cb, publicKey);
-                    } catch (java.security.KeyException ex) {
-                        log.error(ex.getMessage(), ex);
-                        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, ex);
-                    }     
-                } else {
-                    throw new WSSecurityException(
-                        WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo"
-                    );
-                }
-            } else {
-                SecurityTokenReference secRef = new SecurityTokenReference(strElement);
-                //
-                // 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();
-                    
-                    String uri = ref.getURI();
-                    if (uri.charAt(0) == '#') {
-                        uri = uri.substring(1);
-                    }
-                    WSSecurityEngineResult result = wsDocInfo.getResult(uri);
-                    if (result == null) {
-                        Element token = secRef.getTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);
-                        QName el = new QName(token.getNamespaceURI(), token.getLocalName());
-                        if (el.equals(WSSecurityEngine.BINARY_TOKEN)) {
-                            certs = getCertificatesTokenReference(token, crypto);
-                            if (certs != null && certs.length > 1) {
-                                validateCertificateChain = true;
-                            }
-                        } else if (el.equals(WSSecurityEngine.SAML_TOKEN)) {
-                            if (crypto == null) {
-                                throw new WSSecurityException(
-                                    WSSecurityException.FAILURE, "noSigCryptoFile"
-                                );
-                            }
-                            SAMLKeyInfo samlKi = SAMLUtil.getSAMLKeyInfo(token, crypto, cb);
-                            certs = samlKi.getCerts();
-                            secretKey = samlKi.getSecret();
-                            principal = createPrincipalFromSAMLKeyInfo(samlKi);
-                        } else if (el.equals(WSSecurityEngine.ENCRYPTED_KEY)){
-                            EncryptedKeyProcessor proc = 
-                                new EncryptedKeyProcessor();
-                            WSDocInfo docInfo = new WSDocInfo(token.getOwnerDocument());
-                            List<WSSecurityEngineResult> encrResult =
-                                proc.handleToken(token, null, crypto, cb, docInfo, null);
-                            secretKey = 
-                                (byte[])encrResult.get(0).get(
-                                    WSSecurityEngineResult.TAG_DECRYPTED_KEY
-                                );
-                            principal = new CustomTokenPrincipal(token.getAttribute("Id"));
-                        } else {
-                            String id = secRef.getReference().getURI();
-                            secretKey = getSecretKeyFromCustomToken(id, cb);
-                            principal = new CustomTokenPrincipal(id);
-                        }
-                    } else {
-                        int action = ((Integer)result.get(WSSecurityEngineResult.TAG_ACTION)).intValue();
-                        if (WSConstants.UT == action) {
-                            UsernameToken usernameToken = 
-                                (UsernameToken)result.get(WSSecurityEngineResult.TAG_USERNAME_TOKEN);
-                            
-                            if (usernameToken.isDerivedKey()) {
-                                secretKey = usernameToken.getDerivedKey();
-                            } else {
-                                secretKey = usernameToken.getSecretKey(wssConfig.getSecretKeyLength());
-                            }
-                            principal = usernameToken.createPrincipal();
-                        } else if (WSConstants.BST == action) {
-                            certs = 
-                                (X509Certificate[])result.get(WSSecurityEngineResult.TAG_X509_CERTIFICATES);
-                            if (certs != null && certs.length > 1) {
-                                validateCertificateChain = true;
-                            }
-                        } else if (WSConstants.ENCR == action) {
-                            secretKey = (byte[])result.get(WSSecurityEngineResult.TAG_DECRYPTED_KEY);
-                            String id = (String)result.get(WSSecurityEngineResult.TAG_ID);
-                            principal = new CustomTokenPrincipal(id);
-                        } else if (WSConstants.SCT == action) {
-                            secretKey = (byte[])result.get(WSSecurityEngineResult.TAG_SECRET);
-                            SecurityContextToken sct = 
-                                (SecurityContextToken)result.get(
-                                    WSSecurityEngineResult.TAG_SECURITY_CONTEXT_TOKEN
-                                );
-                            principal = new CustomTokenPrincipal(sct.getIdentifier());
-                        } else if (WSConstants.DKT == action) {
-                            DerivedKeyToken dkt = 
-                                (DerivedKeyToken)result.get(WSSecurityEngineResult.TAG_DERIVED_KEY_TOKEN);
-                            int keyLength = dkt.getLength();
-                            if (keyLength <= 0) {
-                                String signatureMethodURI = getSignatureMethod(elem);
-                                keyLength = WSSecurityUtil.getKeyLength(signatureMethodURI);
-                            }
-                            byte[] secret = (byte[])result.get(WSSecurityEngineResult.TAG_SECRET);
-                            secretKey = dkt.deriveKey(keyLength, secret); 
-                            principal = dkt.createPrincipal();
-                        } else if (WSConstants.ST_UNSIGNED == action) {
-                            if (crypto == null) {
-                                throw new WSSecurityException(
-                                    WSSecurityException.FAILURE, "noSigCryptoFile"
-                                );
-                            }
-                            Element samlElement = wsDocInfo.getTokenElement(uri);
-                            SAMLKeyInfo keyInfo = 
-                                SAMLUtil.getSAMLKeyInfo(samlElement, crypto, cb);
-                            certs = keyInfo.getCerts();
-                            secretKey = keyInfo.getSecret();
-                            publicKey = keyInfo.getPublicKey();
-                            principal = createPrincipalFromSAMLKeyInfo(keyInfo);
-                        }
-                    }
-                } 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();
-                        secretKey = getSecretKeyFromEncKeySHA1KI(id, cb);
-                        principal = new CustomTokenPrincipal(id);
-                    } else if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) { 
-                        Element token = 
-                            secRef.getKeyIdentifierTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);
-                        
-                        if (crypto == null) {
-                            throw new WSSecurityException(
-                                WSSecurityException.FAILURE, "noSigCryptoFile"
-                            );
-                        }
-                        SAMLKeyInfo samlKi = SAMLUtil.getSAMLKeyInfo(token, crypto, cb);
-                        certs = samlKi.getCerts();
-                        secretKey = samlKi.getSecret();
-                        publicKey = samlKi.getPublicKey();
-                        principal = createPrincipalFromSAMLKeyInfo(samlKi);
-                    } else {
-                        certs = secRef.getKeyIdentifier(crypto);
-                    }
-                } else {
-                    throw new WSSecurityException(
-                        WSSecurityException.INVALID_SECURITY,
-                        "unsupportedKeyInfo", 
-                        new Object[]{strElement.toString()}
-                    );
-                }
-            }
-        } else {
-            principal = getDefaultPrincipal(crypto);
-        }
-        //
-        // Check that we have a certificate, a public key or a secret key with which to
-        // perform signature verification
-        //
-        if ((certs == null || certs.length == 0 || certs[0] == null) 
-            && secretKey == null
-            && publicKey == null) {
-            throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
-        }
-        
-        //
-        // Validate certificates and verify trust
-        //
-        validateCertificates(certs);
-        if (certs != null) {
-            if (principal == null) {
-                principal = certs[0].getSubjectX500Principal();
-            }
-            boolean trust = false;
-            if (!validateCertificateChain || certs.length == 1) {
-                trust = verifyTrust(certs[0], crypto);
-            } else if (validateCertificateChain && certs.length > 1) {
-                trust = verifyTrust(certs, crypto);
-            }
-            if (!trust) {
-                throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
-            }
-        }
-
         //
         // Perform the signature verification and build up a List of elements that the
         // signature refers to
@@ -401,9 +311,9 @@ public class SignatureProcessor implemen
         } else if (publicKey != null) {
             key = publicKey;
         } else {
-            String signatureMethod = getSignatureMethod(elem);
             key = WSSecurityUtil.prepareSecretKey(signatureMethod, secretKey);
         }
+        
         XMLValidateContext context = new DOMValidateContext(key, elem);
         context.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
         URIDereferencer dereferencer = new DOMURIDereferencer();
@@ -414,13 +324,7 @@ public class SignatureProcessor implemen
             XMLSignature xmlSignature = signatureFactory.unmarshalXMLSignature(context);
             boolean signatureOk = xmlSignature.validate(context);
             if (signatureOk) {
-                signatureValue = xmlSignature.getSignatureValue().getValue();
-                protectedRefs = 
-                    buildProtectedRefs(
-                        elem.getOwnerDocument(), xmlSignature.getSignedInfo(), wsDocInfo, protectedRefs
-                    );
-                
-                return principal;
+                return xmlSignature;
             } else {
                 //
                 // Log the exact signature error
@@ -454,277 +358,6 @@ public class SignatureProcessor implemen
     
     
     /**
-     * Validate an array of certificates by checking the validity of each cert
-     * @param certsToValidate The array of certificates to validate
-     * @throws WSSecurityException
-     */
-    public static void validateCertificates(
-        X509Certificate[] certsToValidate
-    ) throws WSSecurityException {
-        if (certsToValidate != null && certsToValidate.length > 0) {
-            try {
-                for (int i = 0; i < certsToValidate.length; i++) {
-                    certsToValidate[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
-                );
-            }
-        }
-    }
-    
-    
-    /**
-     * Evaluate whether a given certificate should be trusted.
-     * 
-     * Policy used in this implementation:
-     * 1. Search the keystore for the transmitted certificate
-     * 2. Search the keystore for a connection to the transmitted certificate
-     * (that is, search for certificate(s) of the issuer of the transmitted certificate
-     * 3. Verify the trust path for those certificates found because the search for the issuer 
-     * might be fooled by a phony DN (String!)
-     *
-     * @param cert the certificate that should be validated against the keystore
-     * @return true if the certificate is trusted, false if not
-     * @throws WSSecurityException
-     */
-    public static boolean verifyTrust(X509Certificate cert, Crypto crypto) 
-        throws WSSecurityException {
-
-        // If no certificate was transmitted, do not trust the signature
-        if (cert == null) {
-            return false;
-        }
-
-        String subjectString = cert.getSubjectX500Principal().getName();
-        String issuerString = cert.getIssuerX500Principal().getName();
-        BigInteger issuerSerial = cert.getSerialNumber();
-
-        if (log.isDebugEnabled()) {
-            log.debug("Transmitted certificate has subject " + subjectString);
-            log.debug(
-                "Transmitted certificate has issuer " + issuerString + " (serial " 
-                + issuerSerial + ")"
-            );
-        }
-
-        //
-        // FIRST step - Search the keystore for the transmitted certificate
-        //
-        if (crypto.isCertificateInKeyStore(cert)) {
-            return true;
-        }
-
-        //
-        // SECOND step - Search for the issuer of the transmitted certificate in the 
-        // keystore or the truststore
-        //
-        String[] aliases = crypto.getAliasesForDN(issuerString);
-
-        // If the alias has not been found, the issuer is not in the keystore/truststore
-        // As a direct result, do not trust the transmitted certificate
-        if (aliases == null || aliases.length < 1) {
-            if (log.isDebugEnabled()) {
-                log.debug(
-                    "No aliases found in keystore for issuer " + issuerString 
-                    + " of certificate for " + subjectString
-                );
-            }
-            return false;
-        }
-
-        //
-        // THIRD step
-        // Check the certificate trust path for every alias of the issuer found in the 
-        // keystore/truststore
-        //
-        for (int i = 0; i < aliases.length; i++) {
-            String alias = aliases[i];
-
-            if (log.isDebugEnabled()) {
-                log.debug(
-                    "Preparing to validate certificate path with alias " + alias 
-                    + " for issuer " + issuerString
-                );
-            }
-
-            // Retrieve the certificate(s) for the alias from the keystore/truststore
-            X509Certificate[] certs = crypto.getCertificates(alias);
-
-            // If no certificates have been found, there has to be an error:
-            // The keystore/truststore can find an alias but no certificate(s)
-            if (certs == null || certs.length < 1) {
-                throw new WSSecurityException(
-                    "Could not get certificates for alias " + alias
-                );
-            }
-
-            //
-            // Form a certificate chain from the transmitted certificate
-            // and the certificate(s) of the issuer from the keystore/truststore
-            //
-            X509Certificate[] x509certs = new X509Certificate[certs.length + 1];
-            x509certs[0] = cert;
-            for (int j = 0; j < certs.length; j++) {
-                x509certs[j + 1] = certs[j];
-            }
-
-            //
-            // Use the validation method from the crypto to check whether the subjects' 
-            // certificate was really signed by the issuer stated in the certificate
-            //
-            if (crypto.validateCertPath(x509certs)) {
-                if (log.isDebugEnabled()) {
-                    log.debug(
-                        "Certificate path has been verified for certificate with subject " 
-                        + subjectString
-                    );
-                }
-                return true;
-            }
-        }
-
-        if (log.isDebugEnabled()) {
-            log.debug(
-                "Certificate path could not be verified for certificate with subject " 
-                + subjectString
-            );
-        }
-        return false;
-    }
-    
-
-    /**
-     * Evaluate whether the given certificate chain should be trusted.
-     * 
-     * @param certificates the certificate chain that should be validated against the keystore
-     * @return true if the certificate chain is trusted, false if not
-     * @throws WSSecurityException
-     */
-    public static boolean verifyTrust(X509Certificate[] certificates, Crypto crypto) 
-        throws WSSecurityException {
-        String subjectString = certificates[0].getSubjectX500Principal().getName();
-        //
-        // Use the validation method from the crypto to check whether the subjects' 
-        // certificate was really signed by the issuer stated in the certificate
-        //
-        if (certificates != null && certificates.length > 1
-            && crypto.validateCertPath(certificates)) {
-            if (log.isDebugEnabled()) {
-                log.debug(
-                    "Certificate path has been verified for certificate with subject " 
-                    + subjectString
-                );
-            }
-            return true;
-        }
-        
-        if (log.isDebugEnabled()) {
-            log.debug(
-                "Certificate path could not be verified for certificate with subject " 
-                + subjectString
-            );
-        }
-            
-        return false;
-    }
-    
-    
-    
-    /**
-     * Get the default principal from the KeyStore
-     * @param crypto The Crypto object containing the default alias
-     * @return The default principal
-     * @throws WSSecurityException
-     */
-    private Principal getDefaultPrincipal(
-        Crypto crypto
-    ) throws WSSecurityException {
-        if (crypto == null) {
-            throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
-        }
-        if (crypto.getDefaultX509Alias() != null) {
-            certs = crypto.getCertificates(crypto.getDefaultX509Alias());
-            return certs[0].getSubjectX500Principal();
-        } else {
-            throw new WSSecurityException(
-                WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo"
-            );
-        }
-    }
-    
-    
-    /**
-     * Get the Secret Key from a CallbackHandler for a custom token
-     * @param id The id of the element
-     * @param cb The CallbackHandler object
-     * @return A Secret Key
-     * @throws WSSecurityException
-     */
-    private byte[] getSecretKeyFromCustomToken(
-        String id,
-        CallbackHandler cb
-    ) throws WSSecurityException {
-        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
-            );
-        }
-
-        return pwcb.getKey();
-    }
-    
-    
-    /**
-     * Get the Secret Key from a CallbackHandler for the Encrypted Key SHA1 case.
-     * @param id The id of the element
-     * @param cb The CallbackHandler object
-     * @return A Secret Key
-     * @throws WSSecurityException
-     */
-    private byte[] getSecretKeyFromEncKeySHA1KI(
-        String id,
-        CallbackHandler cb
-    ) throws WSSecurityException {
-        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
-            );
-        }
-        return pwcb.getKey();
-    }
-    
-    
-    /**
      * Get the signature method algorithm URI from the associated signature element.
      * @param signatureElement The signature element
      * @return the signature method URI
@@ -754,77 +387,6 @@ public class SignatureProcessor implemen
     
     
     /**
-     * A method to create a Principal from a SAML KeyInfo
-     * @param samlKeyInfo The SAML KeyInfo object
-     * @return A principal
-     */
-    private static Principal createPrincipalFromSAMLKeyInfo(
-        SAMLKeyInfo samlKeyInfo
-    ) {
-        X509Certificate[] samlCerts = samlKeyInfo.getCerts();
-        Principal principal = null;
-        if (samlCerts != null && samlCerts.length > 0) {
-            principal = samlCerts[0].getSubjectX500Principal();
-        } else {
-            final SAMLAssertion assertion = samlKeyInfo.getAssertion();
-            principal = new CustomTokenPrincipal(assertion.getId());
-            ((CustomTokenPrincipal)principal).setTokenObject(assertion);
-        }
-        return principal;
-    }
-    
-    
-    /**
-     * Get the KeyValue object from the KeyInfo DOM element if it exists
-     */
-    private KeyValue getKeyValue(
-        Element keyInfoElement
-    ) throws MarshalException {
-        XMLStructure keyInfoStructure = new DOMStructure(keyInfoElement);
-        KeyInfo keyInfo = keyInfoFactory.unmarshalKeyInfo(keyInfoStructure);
-        List<?> list = keyInfo.getContent();
-
-        for (int i = 0; i < list.size(); i++) {
-            XMLStructure xmlStructure = (XMLStructure) list.get(i);
-            if (xmlStructure instanceof KeyValue) {
-                return (KeyValue)xmlStructure;
-            }
-        }
-        return null;
-    }
-    
-    /**
-     * Validate a public key via a CallbackHandler
-     * @param cb The CallbackHandler object
-     * @param publicKey The PublicKey to validate
-     * @return A PublicKeyPrincipal object encapsulating the public key after successful 
-     *         validation
-     * @throws WSSecurityException
-     */
-    private static Principal validatePublicKey(
-        CallbackHandler cb,
-        PublicKey publicKey
-    ) throws WSSecurityException {
-        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
-            );
-        }
-        return new PublicKeyPrincipal(publicKey);
-    }
-    
-    
-    /**
      * This method digs into the Signature element to get the elements that
      * this Signature covers. Build the QName of these Elements and return them
      * to caller
@@ -837,9 +399,9 @@ public class SignatureProcessor implemen
     private List<WSDataRef> buildProtectedRefs(
         Document doc,
         SignedInfo signedInfo,
-        WSDocInfo wsDocInfo,
-        List<WSDataRef> protectedRefs
+        WSDocInfo wsDocInfo
     ) throws WSSecurityException {
+        List<WSDataRef> protectedRefs = new java.util.ArrayList<WSDataRef>();
         List<?> referencesList = signedInfo.getReferences();
         for (int i = 0; i < referencesList.size(); i++) {
             Reference siRef = (Reference)referencesList.get(i);
@@ -887,13 +449,10 @@ public class SignatureProcessor implemen
                     throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
                 }
                 
-                signatureMethod = signedInfo.getSignatureMethod().getAlgorithm();
-                c14nMethod = signedInfo.getCanonicalizationMethod().getAlgorithm();
-                
                 WSDataRef ref = new WSDataRef();
                 ref.setWsuId(uri);
                 ref.setProtectedElement(se);
-                ref.setAlgorithm(signatureMethod);
+                ref.setAlgorithm(signedInfo.getSignatureMethod().getAlgorithm());
                 ref.setDigestAlgorithm(siRef.getDigestMethod().getAlgorithm());
                 ref.setXpath(ReferenceListProcessor.getXPath(se));
                 protectedRefs.add(ref);
@@ -903,54 +462,5 @@ public class SignatureProcessor implemen
     }
     
     
-    /**
-     * Extracts the certificate(s) from the Binary Security token reference.
-     *
-     * @param elem The element containing the binary security token. This is
-     *             either X509 certificate(s) or a PKIPath.
-     * @return an array of X509 certificates
-     * @throws WSSecurityException
-     */
-    public static X509Certificate[] getCertificatesTokenReference(Element elem, Crypto crypto)
-        throws WSSecurityException {
-        if (crypto == null) {
-            throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
-        }
-        BinarySecurity token = createSecurityToken(elem);
-        if (token instanceof PKIPathSecurity) {
-            return ((PKIPathSecurity) token).getX509Certificates(crypto);
-        } else {
-            X509Certificate cert = ((X509Security) token).getX509Certificate(crypto);
-            return new X509Certificate[]{cert};
-        }
-    }
-
-
-    /**
-     * Checks the <code>element</code> and creates appropriate binary security object.
-     *
-     * @param element The XML element that contains either a <code>BinarySecurityToken
-     *                </code> or a <code>PKIPath</code> element. Other element types a not
-     *                supported
-     * @return the BinarySecurity object, either a <code>X509Security</code> or a
-     *         <code>PKIPathSecurity</code> object.
-     * @throws WSSecurityException
-     */
-    private static BinarySecurity createSecurityToken(Element element) throws WSSecurityException {
-
-        String type = element.getAttribute("ValueType");
-        if (X509Security.X509_V3_TYPE.equals(type)) {
-            X509Security x509 = new X509Security(element);
-            return (BinarySecurity) x509;
-        } else if (PKIPathSecurity.getType().equals(type)) {
-            PKIPathSecurity pkiPath = new PKIPathSecurity(element);
-            return (BinarySecurity) pkiPath;
-        }
-        throw new WSSecurityException(
-            WSSecurityException.UNSUPPORTED_SECURITY_TOKEN,
-            "unsupportedBinaryTokenType", 
-            new Object[]{type}
-        );
-    }
 
 }

Modified: webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/TimestampProcessor.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/TimestampProcessor.java?rev=1051143&r1=1051142&r2=1051143&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/TimestampProcessor.java (original)
+++ webservices/wss4j/trunk/src/main/java/org/apache/ws/security/processor/TimestampProcessor.java Mon Dec 20 15:22:01 2010
@@ -55,6 +55,7 @@ public class TimestampProcessor implemen
         WSSecurityEngineResult result = 
             new WSSecurityEngineResult(WSConstants.TS, timestamp);
         result.put(WSSecurityEngineResult.TAG_ID, timestamp.getID());
+        wsDocInfo.addTokenElement(elem);
         wsDocInfo.addResult(result);
         return java.util.Collections.singletonList(result);
     }

Added: webservices/wss4j/trunk/src/main/java/org/apache/ws/security/str/DerivedKeyTokenSTRParser.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/src/main/java/org/apache/ws/security/str/DerivedKeyTokenSTRParser.java?rev=1051143&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/main/java/org/apache/ws/security/str/DerivedKeyTokenSTRParser.java (added)
+++ webservices/wss4j/trunk/src/main/java/org/apache/ws/security/str/DerivedKeyTokenSTRParser.java Mon Dec 20 15:22:01 2010
@@ -0,0 +1,250 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.ws.security.str;
+
+import org.apache.ws.security.WSConstants;
+import org.apache.ws.security.WSDocInfo;
+import org.apache.ws.security.WSPasswordCallback;
+import org.apache.ws.security.WSSConfig;
+import org.apache.ws.security.WSSecurityEngineResult;
+import org.apache.ws.security.WSSecurityException;
+import org.apache.ws.security.components.crypto.Crypto;
+import org.apache.ws.security.message.token.Reference;
+import org.apache.ws.security.message.token.SecurityTokenReference;
+import org.apache.ws.security.message.token.UsernameToken;
+import org.apache.ws.security.saml.SAMLKeyInfo;
+import org.apache.ws.security.saml.SAMLUtil;
+import org.w3c.dom.Element;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.security.PublicKey;
+import java.security.cert.X509Certificate;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+
+public class DerivedKeyTokenSTRParser implements STRParser {
+    
+    private byte[] secretKey;
+    
+    public void parseSecurityTokenReference(
+        Element strElement,
+        String algorithm,
+        Crypto crypto,
+        CallbackHandler cb,
+        WSDocInfo wsDocInfo,
+        WSSConfig wssConfig
+    ) throws WSSecurityException {
+        SecurityTokenReference secRef = new SecurityTokenReference(strElement);
+        
+        String uri = null;
+        String keyIdentifierValueType = null;
+        String keyIdentifierValue = null;
+        
+        WSSecurityEngineResult result = null;
+        if (secRef.containsReference()) {
+            Reference ref = secRef.getReference();
+            uri = ref.getURI();
+            if (uri.charAt(0) == '#') {
+                uri = uri.substring(1);
+            }
+            result = wsDocInfo.getResult(uri);
+        } else {
+            // Contains key identifier
+            keyIdentifierValue = secRef.getKeyIdentifierValue();
+            keyIdentifierValueType = secRef.getKeyIdentifierValueType();
+            result = wsDocInfo.getResult(keyIdentifierValue);
+        }
+        
+        if (result != null) {
+            int action = ((Integer)result.get(WSSecurityEngineResult.TAG_ACTION)).intValue();
+            if (WSConstants.UT == action) {
+                UsernameToken usernameToken = 
+                    (UsernameToken)result.get(WSSecurityEngineResult.TAG_USERNAME_TOKEN);
+                secretKey = usernameToken.getDerivedKey();
+            } else if (WSConstants.ENCR == action) {
+                secretKey = (byte[])result.get(WSSecurityEngineResult.TAG_DECRYPTED_KEY);
+            } else if (WSConstants.SCT == action) {
+                secretKey = (byte[])result.get(WSSecurityEngineResult.TAG_SECRET);
+            } else if (WSConstants.ST_UNSIGNED == action) {
+                Element samlElement = wsDocInfo.getTokenElement(uri);
+                SAMLKeyInfo keyInfo = 
+                    SAMLUtil.getSAMLKeyInfo(samlElement, crypto, cb);
+                // TODO Handle malformed SAML tokens where they don't have the 
+                // secret in them
+                secretKey = keyInfo.getSecret();
+            } else {
+                throw new WSSecurityException(
+                    WSSecurityException.FAILED_CHECK, "unsupportedKeyId"
+                );
+            }
+        } else if (result == null && uri != null) {
+            // Now use the callback and get it
+            secretKey = getSecret(cb, uri);
+        } else if (keyIdentifierValue != null && keyIdentifierValueType != null) {
+            X509Certificate[] certs = secRef.getKeyIdentifier(crypto);
+            if (certs == null || certs.length < 1 || certs[0] == null) {
+                secretKey = this.getSecret(cb, keyIdentifierValue, keyIdentifierValueType); 
+            } else {
+                secretKey = this.getSecret(cb, crypto, certs);
+            }
+        } else {
+            throw new WSSecurityException(
+                WSSecurityException.FAILED_CHECK, "unsupportedKeyId"
+            );
+        }
+    }
+    
+    
+    public void validateCredentials() throws WSSecurityException {
+        //
+    }
+    
+    public X509Certificate[] getCertificates() {
+        return null;
+    }
+    
+    public Principal getPrincipal() {
+        return null;
+    }
+    
+    public PublicKey getPublicKey() {
+        return null;
+    }
+    
+    public byte[] getSecretKey() {
+        return secretKey;
+    }
+
+    private byte[] getSecret(CallbackHandler cb, String id) throws WSSecurityException {
+        if (cb == null) {
+            throw new WSSecurityException(WSSecurityException.FAILURE, "noCallback");
+        }
+
+        WSPasswordCallback callback = 
+            new WSPasswordCallback(id, WSPasswordCallback.SECURITY_CONTEXT_TOKEN);
+        try {
+            Callback[] callbacks = new Callback[]{callback};
+            cb.handle(callbacks);
+        } catch (IOException e) {
+            throw new WSSecurityException(
+                WSSecurityException.FAILURE, 
+                "noKey",
+                new Object[] {id}, 
+                e
+            );
+        } catch (UnsupportedCallbackException e) {
+            throw new WSSecurityException(
+                WSSecurityException.FAILURE,
+                "noKey",
+                new Object[] {id}, 
+                e
+            );
+        }
+
+        return callback.getKey();
+    }
+    
+    private byte[] getSecret(
+        CallbackHandler cb, 
+        String keyIdentifierValue, 
+        String keyIdentifierType
+    ) throws WSSecurityException {
+        if (cb == null) {
+            throw new WSSecurityException(WSSecurityException.FAILURE, "noCallback");
+        }
+        
+        WSPasswordCallback pwcb = 
+            new WSPasswordCallback(
+                keyIdentifierValue, null, keyIdentifierType, WSPasswordCallback.ENCRYPTED_KEY_TOKEN
+            );
+        try {
+            Callback[] callbacks = new Callback[]{pwcb};
+            cb.handle(callbacks);
+        } catch (IOException e) {
+            throw new WSSecurityException(
+                WSSecurityException.FAILURE, 
+                "noKey",
+                new Object[] {keyIdentifierValue}, 
+                e
+            );
+        } catch (UnsupportedCallbackException e) {
+            throw new WSSecurityException(
+                WSSecurityException.FAILURE, 
+                "noKey",
+                new Object[] {keyIdentifierValue}, 
+                e
+            );
+        }
+            
+        return pwcb.getKey();
+    }
+    
+    private byte[] getSecret(
+        CallbackHandler cb,
+        Crypto crypto,
+        X509Certificate certs[]
+    ) throws WSSecurityException {
+        if (cb == null) {
+            throw new WSSecurityException(WSSecurityException.FAILURE, "noCallback");
+        }
+
+        String alias = crypto.getAliasForX509Cert(certs[0]);
+
+        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}
+            );
+        }
+
+        java.security.Key privateKey;
+        try {
+            privateKey = crypto.getPrivateKey(alias, password);
+            return privateKey.getEncoded();
+        } catch (Exception e) {
+            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e);
+        }
+    }
+    
+}



Mime
View raw message