ws-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From gi...@apache.org
Subject svn commit: r1172285 [18/48] - in /webservices/wss4j/branches/swssf: ./ cxf-integration/ cxf-integration/src/ cxf-integration/src/main/ cxf-integration/src/main/java/ cxf-integration/src/main/java/org/ cxf-integration/src/main/java/org/swssf/ cxf-integ...
Date Sun, 18 Sep 2011 13:51:36 GMT
Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/DerivedKeyTokenInputHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/DerivedKeyTokenInputHandler.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/DerivedKeyTokenInputHandler.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/DerivedKeyTokenInputHandler.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,150 @@
+/**
+ * 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.swssf.impl.processor.input;
+
+import org.oasis_open.docs.ws_sx.ws_secureconversation._200512.DerivedKeyTokenType;
+import org.swssf.config.JCEAlgorithmMapper;
+import org.swssf.crypto.Crypto;
+import org.swssf.ext.*;
+import org.swssf.impl.derivedKey.DerivedKeyUtils;
+import org.swssf.impl.securityToken.AbstractAlgorithmSuiteSecurityEventFiringSecurityToken;
+import org.swssf.impl.securityToken.SAMLSecurityToken;
+import org.swssf.impl.securityToken.SecurityTokenFactory;
+import org.swssf.impl.securityToken.UsernameSecurityToken;
+
+import javax.crypto.spec.SecretKeySpec;
+import javax.xml.stream.events.StartElement;
+import javax.xml.stream.events.XMLEvent;
+import java.security.Key;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+/**
+ * Processor for the SecurityContextToken XML Structure
+ *
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class DerivedKeyTokenInputHandler extends AbstractInputSecurityHeaderHandler {
+
+    public DerivedKeyTokenInputHandler(final InputProcessorChain inputProcessorChain, final SecurityProperties securityProperties, Deque<XMLEvent> eventQueue, Integer index) throws WSSecurityException {
+
+        final DerivedKeyTokenType derivedKeyTokenType = (DerivedKeyTokenType) parseStructure(eventQueue, index);
+        if (derivedKeyTokenType.getId() == null) {
+            derivedKeyTokenType.setId(UUID.randomUUID().toString());
+        }
+        if (derivedKeyTokenType.getSecurityTokenReference() == null) {
+            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, "noReference");
+        }
+
+        SecurityTokenProvider securityTokenProvider = new SecurityTokenProvider() {
+
+            private Map<Crypto, SecurityToken> securityTokens = new HashMap<Crypto, SecurityToken>();
+
+            public SecurityToken getSecurityToken(Crypto crypto) throws WSSecurityException {
+
+                SecurityToken securityToken = securityTokens.get(crypto);
+                if (securityToken != null) {
+                    return securityToken;
+                }
+
+                final SecurityToken referencedSecurityToken = SecurityTokenFactory.newInstance().getSecurityToken(
+                        derivedKeyTokenType.getSecurityTokenReference(),
+                        securityProperties.getDecryptionCrypto(),
+                        securityProperties.getCallbackHandler(),
+                        inputProcessorChain.getSecurityContext(),
+                        null
+                );
+
+                securityToken = new AbstractAlgorithmSuiteSecurityEventFiringSecurityToken(inputProcessorChain.getSecurityContext(), derivedKeyTokenType.getId()) {
+
+                    public boolean isAsymmetric() {
+                        return false;
+                    }
+
+                    public Key getSecretKey(String algorithmURI, Constants.KeyUsage keyUsage) throws WSSecurityException {
+                        super.getSecretKey(algorithmURI, keyUsage);
+                        byte[] secret;
+                        if (referencedSecurityToken != null) {
+                            if (referencedSecurityToken instanceof UsernameSecurityToken) {
+                                UsernameSecurityToken usernameSecurityToken = (UsernameSecurityToken) referencedSecurityToken;
+                                secret = usernameSecurityToken.generateDerivedKey(
+                                        usernameSecurityToken.getPassword(),
+                                        usernameSecurityToken.getSalt(),
+                                        usernameSecurityToken.getIteration()
+                                );
+                            } else if (referencedSecurityToken instanceof SAMLSecurityToken) {
+                                SAMLSecurityToken samlSecurityToken = (SAMLSecurityToken) referencedSecurityToken;
+                                secret = samlSecurityToken.getSamlKeyInfo().getSecret();
+                            } else {
+                                //todo is this the correct algo and KeyUsage?
+                                secret = referencedSecurityToken.getSecretKey(algorithmURI, Constants.KeyUsage.Sig_KD).getEncoded();
+                            }
+                        } else {
+                            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, "unsupportedKeyId");
+                        }
+                        byte[] nonce = derivedKeyTokenType.getNonce();
+                        if (nonce == null || nonce.length == 0) {
+                            throw new WSSecurityException("Missing wsc:Nonce value");
+                        }
+                        byte[] keyBytes = DerivedKeyUtils.deriveKey(
+                                derivedKeyTokenType.getAlgorithm(),
+                                derivedKeyTokenType.getLabel(),
+                                derivedKeyTokenType.getLength(),
+                                secret,
+                                nonce,
+                                derivedKeyTokenType.getOffset()
+                        );
+                        String algo = JCEAlgorithmMapper.translateURItoJCEID(algorithmURI);
+                        return new SecretKeySpec(keyBytes, algo);
+                    }
+
+                    public SecurityToken getKeyWrappingToken() {
+                        //todo?
+                        return null;
+                    }
+
+                    public String getKeyWrappingTokenAlgorithm() {
+                        //todo?
+                        return null;
+                    }
+
+                    public Constants.TokenType getTokenType() {
+                        //todo?
+                        return null;
+                    }
+                };
+                securityTokens.put(crypto, securityToken);
+                return securityToken;
+            }
+
+            public String getId() {
+                return derivedKeyTokenType.getId();
+            }
+        };
+        inputProcessorChain.getSecurityContext().registerSecurityTokenProvider(derivedKeyTokenType.getId(), securityTokenProvider);
+    }
+
+    @Override
+    protected Parseable getParseable(StartElement startElement) {
+        return new DerivedKeyTokenType(startElement);
+    }
+}

Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/DerivedKeyTokenInputHandler.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/EncryptedKeyInputHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/EncryptedKeyInputHandler.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/EncryptedKeyInputHandler.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/EncryptedKeyInputHandler.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,208 @@
+/**
+ * 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.swssf.impl.processor.input;
+
+import org.apache.commons.codec.binary.Base64;
+import org.oasis_open.docs.wss._2004._01.oasis_200401_wss_wssecurity_secext_1_0.ReferenceType;
+import org.oasis_open.docs.wss._2004._01.oasis_200401_wss_wssecurity_secext_1_0.SecurityTokenReferenceType;
+import org.swssf.config.JCEAlgorithmMapper;
+import org.swssf.crypto.Crypto;
+import org.swssf.ext.*;
+import org.swssf.impl.securityToken.AbstractAlgorithmSuiteSecurityEventFiringSecurityToken;
+import org.swssf.impl.securityToken.SecurityTokenFactory;
+import org.swssf.securityEvent.EncryptionTokenSecurityEvent;
+import org.swssf.securityEvent.SecurityEvent;
+import org.w3._2000._09.xmldsig_.KeyInfoType;
+import org.w3._2001._04.xmlenc_.EncryptedKeyType;
+import org.xmlsecurity.ns.configuration.AlgorithmType;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.spec.SecretKeySpec;
+import javax.xml.stream.events.StartElement;
+import javax.xml.stream.events.XMLEvent;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.util.*;
+
+/**
+ * Processor for the EncryptedKey XML Structure
+ *
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class EncryptedKeyInputHandler extends AbstractInputSecurityHeaderHandler {
+
+    public EncryptedKeyInputHandler(final InputProcessorChain inputProcessorChain, final SecurityProperties securityProperties, Deque<XMLEvent> eventQueue, Integer index) throws WSSecurityException {
+
+        final EncryptedKeyType encryptedKeyType = (EncryptedKeyType) parseStructure(eventQueue, index);
+        if (encryptedKeyType.getId() == null) {
+            encryptedKeyType.setId(UUID.randomUUID().toString());
+        }
+
+        SecurityTokenProvider securityTokenProvider = new SecurityTokenProvider() {
+
+            private Map<Crypto, SecurityToken> securityTokens = new HashMap<Crypto, SecurityToken>();
+
+            public SecurityToken getSecurityToken(Crypto crypto) throws WSSecurityException {
+
+                SecurityToken securityToken = securityTokens.get(crypto);
+                if (securityToken != null) {
+                    return securityToken;
+                }
+
+                //decrypt the containing token and register it as a new SecurityToken:
+                String algorithmURI = null;
+                final SecurityToken wrappingSecurityToken;
+                final byte[] secretToken;
+                try {
+                    algorithmURI = encryptedKeyType.getEncryptionMethod().getAlgorithm();
+                    if (algorithmURI == null) {
+                        throw new WSSecurityException(WSSecurityException.ErrorCode.UNSUPPORTED_ALGORITHM, "noEncAlgo");
+                    }
+                    AlgorithmType asyncEncAlgo = JCEAlgorithmMapper.getAlgorithmMapping(algorithmURI);
+                    Cipher cipher = Cipher.getInstance(asyncEncAlgo.getJCEName(), asyncEncAlgo.getJCEProvider());
+
+                    KeyInfoType keyInfoType = encryptedKeyType.getKeyInfo();
+                    wrappingSecurityToken = SecurityTokenFactory.newInstance().getSecurityToken(
+                            keyInfoType,
+                            crypto,
+                            securityProperties.getCallbackHandler(),
+                            inputProcessorChain.getSecurityContext(),
+                            this
+                    );
+                    cipher.init(Cipher.DECRYPT_MODE, wrappingSecurityToken.getSecretKey(algorithmURI, wrappingSecurityToken.isAsymmetric() ? Constants.KeyUsage.Asym_Key_Wrap : Constants.KeyUsage.Sym_Key_Wrap));
+
+                    byte[] encryptedEphemeralKey = Base64.decodeBase64(encryptedKeyType.getCipherData().getCipherValue());
+                    secretToken = cipher.doFinal(encryptedEphemeralKey);
+
+                } catch (NoSuchPaddingException e) {
+                    throw new WSSecurityException(
+                            WSSecurityException.ErrorCode.UNSUPPORTED_ALGORITHM, "unsupportedKeyTransp",
+                            e, "No such padding: " + algorithmURI
+                    );
+                } catch (NoSuchAlgorithmException e) {
+                    throw new WSSecurityException(
+                            WSSecurityException.ErrorCode.UNSUPPORTED_ALGORITHM, "unsupportedKeyTransp",
+                            e, "No such algorithm: " + algorithmURI
+                    );
+                } catch (BadPaddingException e) {
+                    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, e);
+                } catch (IllegalBlockSizeException e) {
+                    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, e);
+                } catch (InvalidKeyException e) {
+                    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, e);
+                } catch (NoSuchProviderException e) {
+                    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noSecProvider", e);
+                }
+
+                final String algorithm = algorithmURI;
+
+                securityToken = new AbstractAlgorithmSuiteSecurityEventFiringSecurityToken(inputProcessorChain.getSecurityContext(), encryptedKeyType.getId()) {
+
+                    private Map<String, Key> keyTable = new Hashtable<String, Key>();
+
+                    public boolean isAsymmetric() {
+                        return false;
+                    }
+
+                    public Key getSecretKey(String algorithmURI, Constants.KeyUsage keyUsage) throws WSSecurityException {
+                        super.getSecretKey(algorithmURI, keyUsage);
+                        if (keyTable.containsKey(algorithmURI)) {
+                            return keyTable.get(algorithmURI);
+                        } else {
+                            String algoFamily = JCEAlgorithmMapper.getJCERequiredKeyFromURI(algorithmURI);
+                            Key key = new SecretKeySpec(secretToken, algoFamily);
+                            keyTable.put(algorithmURI, key);
+                            return key;
+                        }
+                    }
+
+                    public SecurityToken getKeyWrappingToken() {
+                        return wrappingSecurityToken;
+                    }
+
+                    public String getKeyWrappingTokenAlgorithm() {
+                        return algorithm;
+                    }
+
+                    public Constants.TokenType getTokenType() {
+                        return Constants.TokenType.EncryptedKeyToken;
+                    }
+                };
+                securityTokens.put(crypto, securityToken);
+                return securityToken;
+            }
+
+            public String getId() {
+                return encryptedKeyType.getId();
+            }
+        };
+
+        final SecurityToken securityToken = securityTokenProvider.getSecurityToken(securityProperties.getDecryptionCrypto());
+        //fire a RecipientSecurityTokenEvent
+        EncryptionTokenSecurityEvent encryptionTokenSecurityEvent =
+                new EncryptionTokenSecurityEvent(SecurityEvent.Event.EncryptionToken);
+
+        encryptionTokenSecurityEvent.setSecurityToken(securityToken.getKeyWrappingToken());
+        inputProcessorChain.getSecurityContext().registerSecurityEvent(encryptionTokenSecurityEvent);
+
+        //register the key token for decryption:
+        inputProcessorChain.getSecurityContext().registerSecurityTokenProvider(encryptedKeyType.getId(), securityTokenProvider);
+
+        //if this EncryptedKey structure contains a reference list, instantiate a new DecryptInputProcessor
+        //and add it to the chain
+        if (encryptedKeyType.getReferenceList() != null) {
+            KeyInfoType keyInfoType = new KeyInfoType();
+            SecurityTokenReferenceType securityTokenReferenceType = new SecurityTokenReferenceType();
+            ReferenceType referenceType = new ReferenceType();
+            referenceType.setURI("#" + encryptedKeyType.getId());
+            securityTokenReferenceType.setReferenceType(referenceType);
+            keyInfoType.setSecurityTokenReferenceType(securityTokenReferenceType);
+            inputProcessorChain.addProcessor(new DecryptInputProcessor(keyInfoType, encryptedKeyType.getReferenceList(), securityProperties));
+        }
+    }
+
+    @Override
+    protected Parseable getParseable(StartElement startElement) {
+        return new EncryptedKeyType(startElement);
+    }
+
+    /*
+    <xenc:EncryptedKey xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Id="EncKeyId-1483925398">
+        <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
+        <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
+            <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
+                <wsse:KeyIdentifier EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"
+                    ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509SubjectKeyIdentifier">pHoiKNGY2YsLBKxwIV+jURt858M=</wsse:KeyIdentifier>
+                </wsse:SecurityTokenReference>
+        </ds:KeyInfo>
+        <xenc:CipherData>
+            <xenc:CipherValue>Khsa9SN3ALNXOgGDKOqihvfwGsXb9QN/q4Fpi9uuThgz+3D4oRSMkrGSPCqwG13vddvHywGAA/XNbWNT+5Xivz3lURCDCc2H/92YlXXo/crQNJnPlLrLZ81bGOzbNo7lnYQBLp/77K7b1bhldZAeV9ZfEW7DjbOMZ+k1dnDCu3A=</xenc:CipherValue>
+        </xenc:CipherData>
+        <xenc:ReferenceList>
+            <xenc:DataReference URI="#EncDataId-1612925417" />
+        </xenc:ReferenceList>
+    </xenc:EncryptedKey>
+     */
+}

Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/EncryptedKeyInputHandler.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/LogInputProcessor.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/LogInputProcessor.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/LogInputProcessor.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/LogInputProcessor.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,52 @@
+/**
+ * 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.swssf.impl.processor.input;
+
+import org.swssf.ext.*;
+
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.events.XMLEvent;
+import java.io.StringWriter;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class LogInputProcessor extends AbstractInputProcessor {
+
+    public LogInputProcessor(SecurityProperties securityProperties) {
+        super(securityProperties);
+        setPhase(Constants.Phase.POSTPROCESSING);
+        this.getAfterProcessors().add(SecurityHeaderInputProcessor.class.getName());
+    }
+
+    @Override
+    public XMLEvent processNextHeaderEvent(InputProcessorChain inputProcessorChain) throws XMLStreamException, WSSecurityException {
+        return inputProcessorChain.processHeaderEvent();
+    }
+
+    @Override
+    public XMLEvent processNextEvent(InputProcessorChain inputProcessorChain) throws XMLStreamException, WSSecurityException {
+        XMLEvent xmlEvent = inputProcessorChain.processEvent();
+        StringWriter stringWriter = new StringWriter();
+        xmlEvent.writeAsEncodedUnicode(stringWriter);
+        logger.trace(stringWriter.toString());
+        return xmlEvent;
+    }
+}

Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/LogInputProcessor.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/ReferenceListInputHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/ReferenceListInputHandler.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/ReferenceListInputHandler.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/ReferenceListInputHandler.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,48 @@
+/**
+ * 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.swssf.impl.processor.input;
+
+import org.swssf.ext.*;
+import org.w3._2001._04.xmlenc_.ReferenceList;
+
+import javax.xml.stream.events.StartElement;
+import javax.xml.stream.events.XMLEvent;
+import java.util.Deque;
+
+/**
+ * Processor for the ReferenceList XML Structure
+ *
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class ReferenceListInputHandler extends AbstractInputSecurityHeaderHandler {
+
+    public ReferenceListInputHandler(InputProcessorChain inputProcessorChain, final SecurityProperties securityProperties, Deque<XMLEvent> eventQueue, Integer index) throws WSSecurityException {
+
+        final ReferenceList referenceList = (ReferenceList) parseStructure(eventQueue, index);
+
+        //instantiate a new DecryptInputProcessor and add it to the chain
+        inputProcessorChain.addProcessor(new DecryptInputProcessor(referenceList, securityProperties));
+    }
+
+    @Override
+    protected Parseable getParseable(StartElement startElement) {
+        return new ReferenceList(startElement);
+    }
+}

Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/ReferenceListInputHandler.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SAMLTokenInputHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SAMLTokenInputHandler.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SAMLTokenInputHandler.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SAMLTokenInputHandler.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,207 @@
+/**
+ * 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.swssf.impl.processor.input;
+
+import org.swssf.crypto.Crypto;
+import org.swssf.ext.*;
+import org.swssf.impl.saml.SAMLAssertionWrapper;
+import org.swssf.impl.saml.SAMLKeyInfo;
+import org.swssf.impl.securityToken.SecurityTokenFactory;
+import org.swssf.securityEvent.SamlTokenSecurityEvent;
+import org.swssf.securityEvent.SecurityEvent;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.events.*;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * Processor for the SAML Assertion XML Structure
+ *
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class SAMLTokenInputHandler extends AbstractInputSecurityHeaderHandler {
+
+    private static final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
+
+    static {
+        documentBuilderFactory.setNamespaceAware(true);
+    }
+
+    public SAMLTokenInputHandler(final InputProcessorChain inputProcessorChain, final SecurityProperties securityProperties, Deque<XMLEvent> eventQueue, Integer index) throws WSSecurityException {
+
+        final SAMLTokenParseable samlTokenParseable = (SAMLTokenParseable) parseStructure(eventQueue, index);
+
+        final SAMLAssertionWrapper samlAssertionWrapper = new SAMLAssertionWrapper(samlTokenParseable.getDocument().getDocumentElement());
+
+        if (samlAssertionWrapper.isSigned()) {
+            SAMLKeyInfo samlIssuerKeyInfo = samlAssertionWrapper.verifySignature(securityProperties);
+            // Verify trust on the signature
+            samlAssertionWrapper.verifySignedAssertion(samlIssuerKeyInfo, securityProperties);
+        }
+        // Parse the HOK subject if it exists
+        final SAMLKeyInfo samlSubjectKeyInfo = samlAssertionWrapper.parseHOKSubject(securityProperties);
+
+        if (logger.isDebugEnabled()) {
+            logger.debug("SAML Assertion issuer " + samlAssertionWrapper.getIssuerString());
+        }
+
+        SecurityTokenProvider securityTokenProvider = new SecurityTokenProvider() {
+
+            private Map<Crypto, SecurityToken> securityTokens = new HashMap<Crypto, SecurityToken>();
+
+            public SecurityToken getSecurityToken(Crypto crypto) throws WSSecurityException {
+                SecurityToken securityToken = securityTokens.get(crypto);
+                if (securityToken != null) {
+                    return securityToken;
+                }
+
+                securityToken = SecurityTokenFactory.newInstance().getSecurityToken(
+                        samlAssertionWrapper.getSAMLVersion(), samlSubjectKeyInfo,
+                        inputProcessorChain.getSecurityContext(), crypto,
+                        securityProperties.getCallbackHandler(), samlAssertionWrapper.getId(), null);
+                securityTokens.put(crypto, securityToken);
+                return securityToken;
+            }
+
+            public String getId() {
+                return samlAssertionWrapper.getId();
+            }
+        };
+        inputProcessorChain.getSecurityContext().registerSecurityTokenProvider(samlAssertionWrapper.getId(), securityTokenProvider);
+
+        SamlTokenSecurityEvent samlTokenSecurityEvent = new SamlTokenSecurityEvent(SecurityEvent.Event.SamlToken);
+        samlTokenSecurityEvent.setIssuerName(samlAssertionWrapper.getIssuerString());
+        samlTokenSecurityEvent.setSamlVersion(samlAssertionWrapper.getSAMLVersion());
+        samlTokenSecurityEvent.setSecurityToken(securityTokenProvider.getSecurityToken(null));
+        inputProcessorChain.getSecurityContext().registerSecurityEvent(samlTokenSecurityEvent);
+    }
+
+    @Override
+    protected Parseable getParseable(StartElement startElement) {
+        return new SAMLTokenParseable(startElement);
+    }
+
+    class SAMLTokenParseable implements Parseable {
+
+        private Document document;
+        private Node currentNode;
+
+        SAMLTokenParseable(StartElement startElement) {
+            try {
+                currentNode = document = documentBuilderFactory.newDocumentBuilder().newDocument();
+                parseXMLEvent(startElement);
+            } catch (ParserConfigurationException e) {
+                throw new RuntimeException(e);
+            } catch (ParseException e) {
+                throw new RuntimeException(e);
+            }
+        }
+
+        //todo custom SAML unmarshaller directly to XMLObject?
+        public boolean parseXMLEvent(XMLEvent xmlEvent) throws ParseException {
+            switch (xmlEvent.getEventType()) {
+                case XMLEvent.START_ELEMENT:
+                    StartElement startElement = xmlEvent.asStartElement();
+                    Element element = document.createElementNS(startElement.getName().getNamespaceURI(), startElement.getName().getLocalPart());
+                    if (startElement.getName().getPrefix() != null && !"".equals(startElement.getName().getPrefix())) {
+                        element.setPrefix(startElement.getName().getPrefix());
+                    }
+                    currentNode = currentNode.appendChild(element);
+                    @SuppressWarnings("unchecked")
+                    Iterator<Namespace> namespaceIterator = startElement.getNamespaces();
+                    while (namespaceIterator.hasNext()) {
+                        Namespace next = namespaceIterator.next();
+                        parseXMLEvent(next);
+                    }
+                    @SuppressWarnings("unchecked")
+                    Iterator<Attribute> attributesIterator = startElement.getAttributes();
+                    while (attributesIterator.hasNext()) {
+                        Attribute next = attributesIterator.next();
+                        parseXMLEvent(next);
+                    }
+                    break;
+                case XMLEvent.END_ELEMENT:
+                    if (currentNode.getParentNode() != null) {
+                        currentNode = currentNode.getParentNode();
+                    }
+                    break;
+                case XMLEvent.PROCESSING_INSTRUCTION:
+                    Node piNode = document.createProcessingInstruction(((ProcessingInstruction) xmlEvent).getTarget(), ((ProcessingInstruction) xmlEvent).getTarget());
+                    currentNode.appendChild(piNode);
+                    break;
+                case XMLEvent.CHARACTERS:
+                    Node characterNode = document.createTextNode(xmlEvent.asCharacters().getData());
+                    currentNode.appendChild(characterNode);
+                    break;
+                case XMLEvent.COMMENT:
+                    Node commentNode = document.createComment(((Comment) xmlEvent).getText());
+                    currentNode.appendChild(commentNode);
+                    break;
+                case XMLEvent.START_DOCUMENT:
+                    break;
+                case XMLEvent.END_DOCUMENT:
+                    return true;
+                case XMLEvent.ATTRIBUTE:
+                    Attr attributeNode = document.createAttributeNS(((Attribute) xmlEvent).getName().getNamespaceURI(), ((Attribute) xmlEvent).getName().getLocalPart());
+                    attributeNode.setPrefix(((Attribute) xmlEvent).getName().getPrefix());
+                    attributeNode.setValue(((Attribute) xmlEvent).getValue());
+                    ((Element) currentNode).setAttributeNodeNS(attributeNode);
+                    break;
+                case XMLEvent.DTD:
+                    //todo?:
+                    /*
+                    Node dtdNode = document.getDoctype().getEntities()
+                    ((DTD)xmlEvent).getDocumentTypeDeclaration():
+                    ((DTD)xmlEvent).getEntities()
+                    */
+                    break;
+                case XMLEvent.NAMESPACE:
+                    Namespace namespace = (Namespace) xmlEvent;
+                    Attr namespaceNode;
+                    if ("".equals(namespace.getPrefix())) {
+                        namespaceNode = document.createAttributeNS(Constants.NS_XML, "xmlns");
+                    } else {
+                        namespaceNode = document.createAttributeNS(Constants.NS_XML, "xmlns:" + namespace.getPrefix());
+                    }
+                    namespaceNode.setValue(namespace.getNamespaceURI());
+                    ((Element) currentNode).setAttributeNodeNS(namespaceNode);
+                    break;
+                default:
+                    throw new IllegalArgumentException("Illegal XMLEvent received: " + xmlEvent.getEventType());
+            }
+            return false;
+        }
+
+        public void validate() throws ParseException {
+        }
+
+        public Document getDocument() {
+            return document;
+        }
+    }
+}

Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SAMLTokenInputHandler.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SecurityContextTokenInputHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SecurityContextTokenInputHandler.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SecurityContextTokenInputHandler.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SecurityContextTokenInputHandler.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,135 @@
+/**
+ * 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.swssf.impl.processor.input;
+
+import org.oasis_open.docs.ws_sx.ws_secureconversation._200512.SecurityContextTokenType;
+import org.swssf.config.JCEAlgorithmMapper;
+import org.swssf.crypto.Crypto;
+import org.swssf.ext.*;
+import org.swssf.impl.securityToken.AbstractAlgorithmSuiteSecurityEventFiringSecurityToken;
+import org.swssf.securityEvent.SecurityContextTokenSecurityEvent;
+import org.swssf.securityEvent.SecurityEvent;
+
+import javax.crypto.spec.SecretKeySpec;
+import javax.xml.stream.events.StartElement;
+import javax.xml.stream.events.XMLEvent;
+import java.security.Key;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+/**
+ * Processor for the SecurityContextToken XML Structure
+ *
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class SecurityContextTokenInputHandler extends AbstractInputSecurityHeaderHandler {
+
+    public SecurityContextTokenInputHandler(InputProcessorChain inputProcessorChain, final SecurityProperties securityProperties, Deque<XMLEvent> eventQueue, Integer index) throws WSSecurityException {
+
+        final SecurityContextTokenType securityContextTokenType = (SecurityContextTokenType) parseStructure(eventQueue, index);
+        if (securityContextTokenType.getId() == null) {
+            securityContextTokenType.setId(UUID.randomUUID().toString());
+        }
+
+        final SecurityToken securityContextToken = new AbstractAlgorithmSuiteSecurityEventFiringSecurityToken(inputProcessorChain.getSecurityContext(), securityContextTokenType.getId()) {
+
+            public boolean isAsymmetric() {
+                return false;
+            }
+
+            public Key getSecretKey(String algorithmURI, Constants.KeyUsage keyUsage) throws WSSecurityException {
+                super.getSecretKey(algorithmURI, keyUsage);
+                String algo = JCEAlgorithmMapper.translateURItoJCEID(algorithmURI);
+                WSPasswordCallback passwordCallback = new WSPasswordCallback(securityContextTokenType.getIdentifier(), WSPasswordCallback.Usage.SECURITY_CONTEXT_TOKEN);
+                Utils.doSecretKeyCallback(securityProperties.getCallbackHandler(), passwordCallback, null);
+                if (passwordCallback.getKey() == null) {
+                    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noKey", securityContextTokenType.getId());
+                }
+                return new SecretKeySpec(passwordCallback.getKey(), algo);
+            }
+
+            public SecurityToken getKeyWrappingToken() {
+                return null;
+            }
+
+            public String getKeyWrappingTokenAlgorithm() {
+                return null;
+            }
+
+            public Constants.TokenType getTokenType() {
+                //todo and set externalUriRef
+                return null;
+            }
+        };
+
+        SecurityTokenProvider securityTokenProvider = new SecurityTokenProvider() {
+
+            private Map<Crypto, SecurityToken> securityTokens = new HashMap<Crypto, SecurityToken>();
+
+            public SecurityToken getSecurityToken(Crypto crypto) throws WSSecurityException {
+                SecurityToken securityToken = securityTokens.get(crypto);
+                if (securityToken != null) {
+                    return securityToken;
+                }
+                securityTokens.put(crypto, securityContextToken);
+                return securityContextToken;
+            }
+
+            public String getId() {
+                return securityContextTokenType.getId();
+            }
+        };
+        inputProcessorChain.getSecurityContext().registerSecurityTokenProvider(securityContextTokenType.getId(), securityTokenProvider);
+
+        //also register a SecurityProvider with the identifier. @see SecurityContexTest#testSCTKDKTSignAbsolute
+        SecurityTokenProvider securityTokenProviderDirectReference = new SecurityTokenProvider() {
+
+            private Map<Crypto, SecurityToken> securityTokens = new HashMap<Crypto, SecurityToken>();
+
+            public SecurityToken getSecurityToken(Crypto crypto) throws WSSecurityException {
+                SecurityToken securityToken = securityTokens.get(crypto);
+                if (securityToken != null) {
+                    return securityToken;
+                }
+                securityTokens.put(crypto, securityContextToken);
+                return securityContextToken;
+            }
+
+            public String getId() {
+                return securityContextTokenType.getIdentifier();
+            }
+        };
+        inputProcessorChain.getSecurityContext().registerSecurityTokenProvider(securityContextTokenType.getIdentifier(), securityTokenProviderDirectReference);
+
+        SecurityContextTokenSecurityEvent securityContextTokenSecurityEvent = new SecurityContextTokenSecurityEvent(SecurityEvent.Event.SecurityContextToken);
+        securityContextTokenSecurityEvent.setSecurityToken(securityContextToken);
+        //todo how to find the issuer?
+        securityContextTokenSecurityEvent.setIssuerName(securityContextTokenType.getIdentifier());
+        securityContextTokenSecurityEvent.setExternalUriRef(securityContextTokenType.getIdentifier() != null);
+        inputProcessorChain.getSecurityContext().registerSecurityEvent(securityContextTokenSecurityEvent);
+    }
+
+    @Override
+    protected Parseable getParseable(StartElement startElement) {
+        return new SecurityContextTokenType(startElement);
+    }
+}

Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SecurityContextTokenInputHandler.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SecurityHeaderInputProcessor.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SecurityHeaderInputProcessor.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SecurityHeaderInputProcessor.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SecurityHeaderInputProcessor.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,296 @@
+/**
+ * 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.swssf.impl.processor.input;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.swssf.config.SecurityHeaderHandlerMapper;
+import org.swssf.ext.*;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.events.EndElement;
+import javax.xml.stream.events.StartElement;
+import javax.xml.stream.events.XMLEvent;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayDeque;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.Deque;
+
+/**
+ * Processor for the Security-Header XML Structure.
+ * This processor instantiates more processors on demand
+ *
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class SecurityHeaderInputProcessor extends AbstractInputProcessor {
+
+    protected static final transient Log logger = LogFactory.getLog(SecurityHeaderInputProcessor.class);
+
+    private ArrayDeque<XMLEvent> xmlEventList = new ArrayDeque<XMLEvent>();
+    private int eventCount = 0;
+    private int countOfEventsToResponsibleSecurityHeader = 0;
+    private int startIndexForProcessor = 0;
+
+    public SecurityHeaderInputProcessor(SecurityProperties securityProperties) {
+        super(securityProperties);
+        setPhase(Constants.Phase.POSTPROCESSING);
+    }
+
+    @Override
+    public XMLEvent processNextHeaderEvent(InputProcessorChain inputProcessorChain) throws XMLStreamException, WSSecurityException {
+        return null;
+    }
+
+    @Override
+    public XMLEvent processNextEvent(InputProcessorChain inputProcessorChain) throws XMLStreamException, WSSecurityException {
+
+        //buffer all events until the end of the security header
+        InputProcessorChain subInputProcessorChain = inputProcessorChain.createSubChain(this);
+        InternalSecurityHeaderBufferProcessor internalSecurityHeaderBufferProcessor = new InternalSecurityHeaderBufferProcessor(getSecurityProperties());
+        subInputProcessorChain.addProcessor(internalSecurityHeaderBufferProcessor);
+
+        boolean responsibleSecurityHeaderFound = false;
+
+        XMLEvent xmlEvent;
+        do {
+            subInputProcessorChain.reset();
+            xmlEvent = subInputProcessorChain.processHeaderEvent();
+
+            eventCount++;
+
+            if (xmlEvent.isStartElement()) {
+                StartElement startElement = xmlEvent.asStartElement();
+
+                if (subInputProcessorChain.getDocumentContext().getDocumentLevel() == 1) {
+                    if (subInputProcessorChain.getDocumentContext().getSOAPMessageVersionNamespace() == null) {
+                        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "notASOAPMessage");
+                    }
+                } else if (subInputProcessorChain.getDocumentContext().getDocumentLevel() == 3
+                        && subInputProcessorChain.getDocumentContext().isInSOAPHeader()
+                        && startElement.getName().equals(Constants.TAG_wsse_Security)) {
+
+                    if (!Utils.isResponsibleActorOrRole(startElement,
+                            subInputProcessorChain.getDocumentContext().getSOAPMessageVersionNamespace(),
+                            getSecurityProperties().getActor())) {
+                        continue;
+                    }
+
+                    responsibleSecurityHeaderFound = true;
+
+                    subInputProcessorChain.getDocumentContext().setInSecurityHeader(true);
+                    //minus one because the first event will be deqeued when finished security header. @see below
+                    countOfEventsToResponsibleSecurityHeader = eventCount - 1;
+
+                } else if (subInputProcessorChain.getDocumentContext().getDocumentLevel() == 4
+                        && subInputProcessorChain.getDocumentContext().isInSecurityHeader()) {
+                    startIndexForProcessor = eventCount - 1;
+                }
+            } else if (xmlEvent.isEndElement()) {
+                EndElement endElement = xmlEvent.asEndElement();
+                if (responsibleSecurityHeaderFound && subInputProcessorChain.getDocumentContext().getDocumentLevel() == 2
+                        && endElement.getName().equals(Constants.TAG_wsse_Security)) {
+
+                    //subInputProcessorChain.getDocumentContext().setInSecurityHeader(false);
+                    subInputProcessorChain.removeProcessor(internalSecurityHeaderBufferProcessor);
+                    subInputProcessorChain.addProcessor(
+                            new InternalSecurityHeaderReplayProcessor(getSecurityProperties(),
+                                    countOfEventsToResponsibleSecurityHeader,
+                                    //minus one because the first event will be deqeued when finished security header. @see below
+                                    eventCount - 1));
+
+                    //remove this processor from chain now. the next events will go directly to the other processors
+                    subInputProcessorChain.removeProcessor(this);
+                    //since we clone the inputProcessor list we have to add the processors from
+                    //the subChain to the main chain.
+                    inputProcessorChain.getProcessors().clear();
+                    inputProcessorChain.getProcessors().addAll(subInputProcessorChain.getProcessors());
+
+                    countOfEventsToResponsibleSecurityHeader = 0;
+
+                    //return first event now;
+                    return xmlEventList.pollLast();
+                } else if (subInputProcessorChain.getDocumentContext().getDocumentLevel() == 3
+                        && subInputProcessorChain.getDocumentContext().isInSecurityHeader()) {
+                    //we are in the security header and the depth is +1, so every child
+                    //element should have a responsible processor:
+                    engageSecurityHeaderHandler(subInputProcessorChain, getSecurityProperties(), xmlEventList, startIndexForProcessor, endElement.getName());
+                }
+            }
+
+        } while (!(xmlEvent.isStartElement()
+                && xmlEvent.asStartElement().getName().getLocalPart().equals(Constants.TAG_soap_Body_LocalName)
+                && xmlEvent.asStartElement().getName().getNamespaceURI().equals(subInputProcessorChain.getDocumentContext().getSOAPMessageVersionNamespace())
+        ));
+        //if we reach this state we didn't find a security header
+        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "missingSecurityHeader");
+    }
+
+    @SuppressWarnings("unchecked")
+    private static void engageSecurityHeaderHandler(InputProcessorChain inputProcessorChain,
+                                                    SecurityProperties securityProperties,
+                                                    Deque eventQueue,
+                                                    Integer index,
+                                                    QName elementName)
+            throws WSSecurityException, XMLStreamException {
+
+        Class clazz = SecurityHeaderHandlerMapper.getSecurityHeaderHandler(elementName);
+        if (clazz == null) {
+            return;
+        }
+        Constructor[] constructors = clazz.getConstructors();
+        Comparator<Constructor> comparator = new Comparator<Constructor>() {
+            public int compare(Constructor o1, Constructor o2) {
+                if (o1.getParameterTypes().length == o2.getParameterTypes().length) {
+                    return 0;
+                } else if (o1.getParameterTypes().length > o2.getParameterTypes().length) {
+                    return -1;
+                } else {
+                    return 1;
+                }
+            }
+        };
+
+        Arrays.sort(constructors, comparator);
+
+        for (int i = 0; i < constructors.length; i++) {
+            Constructor constructor = constructors[i];
+            Class[] parameterTypes = constructor.getParameterTypes();
+
+            boolean ok = true;
+            Object[] parameterObjects = new Object[parameterTypes.length];
+            for (int j = 0; j < parameterTypes.length; j++) {
+                Class parameterType = parameterTypes[j];
+                if (parameterType.isAssignableFrom(inputProcessorChain.getClass())) {
+                    parameterObjects[j] = inputProcessorChain;
+                } else if (parameterType.isAssignableFrom(securityProperties.getClass())) {
+                    parameterObjects[j] = securityProperties;
+                } else if (parameterType.isAssignableFrom(eventQueue.getClass())) {
+                    parameterObjects[j] = eventQueue;
+                } else if (parameterType.isAssignableFrom(index.getClass())) {
+                    parameterObjects[j] = index;
+                } else if (parameterType.isAssignableFrom(elementName.getClass())) {
+                    parameterObjects[j] = elementName;
+                } else {
+                    ok = false;
+                    break;
+                }
+            }
+            if (ok) {
+                try {
+                    constructor.newInstance(parameterObjects);
+                } catch (InstantiationException e) {
+                    logger.warn(e);
+                } catch (IllegalAccessException e) {
+                    logger.warn(e);
+                } catch (InvocationTargetException e) {
+                    Throwable cause = e.getCause();
+                    if (cause instanceof WSSecurityException) {
+                        throw (WSSecurityException) cause;
+                    } else if (cause instanceof XMLStreamException) {
+                        throw (XMLStreamException) cause;
+                    } else {
+                        throw new RuntimeException(e.getCause());
+                    }
+                }
+                return;
+            }
+            logger.warn("No matching handler found for " + elementName);
+        }
+    }
+
+    /**
+     * Temporary Processor to buffer all events until the end of the security header
+     */
+    public class InternalSecurityHeaderBufferProcessor extends AbstractInputProcessor {
+
+        InternalSecurityHeaderBufferProcessor(SecurityProperties securityProperties) {
+            super(securityProperties);
+            setPhase(Constants.Phase.POSTPROCESSING);
+            getBeforeProcessors().add(SecurityHeaderInputProcessor.class.getName());
+        }
+
+        @Override
+        public XMLEvent processNextHeaderEvent(InputProcessorChain inputProcessorChain) throws XMLStreamException, WSSecurityException {
+            XMLEvent xmlEvent = inputProcessorChain.processHeaderEvent();
+            xmlEventList.push(xmlEvent);
+            return xmlEvent;
+        }
+
+        @Override
+        public XMLEvent processNextEvent(InputProcessorChain inputProcessorChain) throws XMLStreamException, WSSecurityException {
+            //should never be called because we remove this processor before
+            return null;
+        }
+    }
+
+    /**
+     * Temporary processor to replay the buffered events
+     */
+    public class InternalSecurityHeaderReplayProcessor extends AbstractInputProcessor {
+
+        private int countOfEventsToResponsibleSecurityHeader = 0;
+        private int countOfEventsUntilEndOfResponsibleSecurityHeader = 0;
+        private int eventCount = 0;
+
+        public InternalSecurityHeaderReplayProcessor(SecurityProperties securityProperties, int countOfEventsToResponsibleSecurityHeader, int countOfEventsUntilEndOfResponsibleSecurityHeader) {
+            super(securityProperties);
+            setPhase(Constants.Phase.PREPROCESSING);
+            getBeforeProcessors().add(SecurityHeaderInputProcessor.class.getName());
+            getAfterProcessors().add(XMLEventReaderInputProcessor.class.getName());
+            this.countOfEventsToResponsibleSecurityHeader = countOfEventsToResponsibleSecurityHeader;
+            this.countOfEventsUntilEndOfResponsibleSecurityHeader = countOfEventsUntilEndOfResponsibleSecurityHeader;
+        }
+
+        @Override
+        public XMLEvent processNextHeaderEvent(InputProcessorChain inputProcessorChain) throws XMLStreamException, WSSecurityException {
+            return null;
+        }
+
+        @Override
+        public XMLEvent processNextEvent(InputProcessorChain inputProcessorChain) throws XMLStreamException, WSSecurityException {
+
+            if (!xmlEventList.isEmpty()) {
+                eventCount++;
+
+                if (eventCount == countOfEventsToResponsibleSecurityHeader) {
+                    inputProcessorChain.getDocumentContext().setInSecurityHeader(true);
+                }
+                if (eventCount == countOfEventsUntilEndOfResponsibleSecurityHeader) {
+                    inputProcessorChain.getDocumentContext().setInSecurityHeader(false);
+                }
+
+                XMLEvent xmlEvent = xmlEventList.pollLast();
+                if (xmlEvent.isStartElement()) {
+                    inputProcessorChain.getDocumentContext().addPathElement(xmlEvent.asStartElement().getName());
+                } else if (xmlEvent.isEndElement()) {
+                    inputProcessorChain.getDocumentContext().removePathElement();
+                }
+                return xmlEvent;
+
+            } else {
+                inputProcessorChain.removeProcessor(this);
+                return inputProcessorChain.processEvent();
+            }
+        }
+    }
+}

Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SecurityHeaderInputProcessor.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SecurityTokenReferenceInputHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SecurityTokenReferenceInputHandler.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SecurityTokenReferenceInputHandler.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SecurityTokenReferenceInputHandler.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,148 @@
+/**
+ * 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.swssf.impl.processor.input;
+
+import org.oasis_open.docs.wss._2004._01.oasis_200401_wss_wssecurity_secext_1_0.KeyIdentifierType;
+import org.oasis_open.docs.wss._2004._01.oasis_200401_wss_wssecurity_secext_1_0.SecurityTokenReferenceType;
+import org.swssf.crypto.Crypto;
+import org.swssf.ext.*;
+import org.swssf.impl.securityToken.SecurityTokenFactory;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.events.Attribute;
+import javax.xml.stream.events.EndElement;
+import javax.xml.stream.events.StartElement;
+import javax.xml.stream.events.XMLEvent;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Processor for the SecurityTokenReference XML Structure
+ *
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class SecurityTokenReferenceInputHandler extends AbstractInputSecurityHeaderHandler {
+
+    public SecurityTokenReferenceInputHandler(InputProcessorChain inputProcessorChain, final SecurityProperties securityProperties, Deque<XMLEvent> eventQueue, Integer index) throws WSSecurityException {
+
+        final SecurityTokenReferenceType securityTokenReferenceType = (SecurityTokenReferenceType) parseStructure(eventQueue, index);
+
+        if (securityTokenReferenceType.getKeyIdentifierType() != null) {
+            KeyIdentifierType keyIdentifierType = securityTokenReferenceType.getKeyIdentifierType();
+            if (Constants.NS_SAML10_TYPE.equals(keyIdentifierType.getValueType())) {
+                InternalSecurityTokenReferenceInputHandler internalSecurityTokenReferenceInputHandler
+                        = new InternalSecurityTokenReferenceInputHandler(securityTokenReferenceType.getId(), Constants.ATT_NULL_AssertionID, keyIdentifierType.getValue().trim(), securityProperties);
+                inputProcessorChain.addProcessor(internalSecurityTokenReferenceInputHandler);
+            } else if (Constants.NS_SAML20_TYPE.equals(keyIdentifierType.getValueType())) {
+                InternalSecurityTokenReferenceInputHandler internalSecurityTokenReferenceInputHandler
+                        = new InternalSecurityTokenReferenceInputHandler(securityTokenReferenceType.getId(), Constants.ATT_NULL_ID, keyIdentifierType.getValue().trim(), securityProperties);
+                inputProcessorChain.addProcessor(internalSecurityTokenReferenceInputHandler);
+            }
+        }
+    }
+
+    @Override
+    protected Parseable getParseable(StartElement startElement) {
+        return new SecurityTokenReferenceType(startElement);
+    }
+
+    class InternalSecurityTokenReferenceInputHandler extends AbstractInputProcessor {
+
+        private String securityTokenReferenceId;
+        private QName attribute;
+        private String attributeValue;
+        private boolean refFound = false;
+        private boolean end = false;
+        private QName startElementName;
+        private int startElementLevel;
+
+        private ArrayDeque<XMLEvent> xmlEventList = new ArrayDeque<XMLEvent>();
+
+        InternalSecurityTokenReferenceInputHandler(String securityTokenReferenceId, QName attribute, String attributeValue, SecurityProperties securityProperties) {
+            super(securityProperties);
+            this.securityTokenReferenceId = securityTokenReferenceId;
+            this.attribute = attribute;
+            this.attributeValue = attributeValue;
+        }
+
+        @Override
+        public XMLEvent processNextHeaderEvent(InputProcessorChain inputProcessorChain) throws XMLStreamException, WSSecurityException {
+            return inputProcessorChain.processHeaderEvent();
+        }
+
+        @Override
+        public XMLEvent processNextEvent(final InputProcessorChain inputProcessorChain) throws XMLStreamException, WSSecurityException {
+            XMLEvent xmlEvent = inputProcessorChain.processEvent();
+            if (xmlEvent.isStartElement()) {
+                StartElement startElement = xmlEvent.asStartElement();
+                Attribute attribute = startElement.getAttributeByName(this.attribute);
+                if (attribute != null && this.attributeValue.equals(attribute.getValue())) {
+                    if (refFound) {
+                        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, "duplicateId");
+                    }
+                    refFound = true;
+                    startElementName = startElement.getName();
+                    startElementLevel = inputProcessorChain.getDocumentContext().getDocumentLevel();
+                }
+            } else if (xmlEvent.isEndElement()) {
+                EndElement endElement = xmlEvent.asEndElement();
+                if (startElementName != null && endElement.getName().equals(startElementName) && inputProcessorChain.getDocumentContext().getDocumentLevel() == startElementLevel - 1) {
+                    end = true;
+                    xmlEventList.push(xmlEvent);
+
+                    SecurityTokenProvider securityTokenProvider = new SecurityTokenProvider() {
+
+                        private Map<Crypto, SecurityToken> securityTokens = new HashMap<Crypto, SecurityToken>();
+
+                        public SecurityToken getSecurityToken(Crypto crypto) throws WSSecurityException {
+                            SecurityToken securityToken = securityTokens.get(crypto);
+                            if (securityToken != null) {
+                                return securityToken;
+                            }
+                            securityToken = SecurityTokenFactory.newInstance().getSecurityToken(
+                                    attributeValue, xmlEventList, crypto, getSecurityProperties().getCallbackHandler(),
+                                    inputProcessorChain.getSecurityContext(), securityTokenReferenceId, this);
+                            securityTokens.put(crypto, securityToken);
+                            return securityToken;
+                        }
+
+                        public String getId() {
+                            return securityTokenReferenceId;
+                        }
+                    };
+                    inputProcessorChain.getSecurityContext().registerSecurityTokenProvider(securityTokenReferenceId, securityTokenProvider);
+
+                    return xmlEvent;
+                } else if (inputProcessorChain.getDocumentContext().getDocumentLevel() == 1
+                        && inputProcessorChain.getDocumentContext().isInSecurityHeader()) {
+                    //we can now remove this processor from the chain
+                    inputProcessorChain.removeProcessor(this);
+                }
+            }
+            if (refFound && !end) {
+                xmlEventList.push(xmlEvent);
+            }
+            return xmlEvent;
+        }
+    }
+}

Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SecurityTokenReferenceInputHandler.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SignatureConfirmationInputHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SignatureConfirmationInputHandler.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SignatureConfirmationInputHandler.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SignatureConfirmationInputHandler.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,46 @@
+/**
+ * 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.swssf.impl.processor.input;
+
+import org.oasis_open.docs.wss.oasis_wss_wssecurity_secext_1_1.SignatureConfirmationType;
+import org.swssf.ext.*;
+
+import javax.xml.stream.events.StartElement;
+import javax.xml.stream.events.XMLEvent;
+import java.util.Deque;
+
+/**
+ * Processor for the SignatureConfirmation XML Structure
+ *
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class SignatureConfirmationInputHandler extends AbstractInputSecurityHeaderHandler {
+
+    public SignatureConfirmationInputHandler(InputProcessorChain inputProcessorChain, final SecurityProperties securityProperties, Deque<XMLEvent> eventQueue, Integer index) throws WSSecurityException {
+
+        final SignatureConfirmationType signatureConfirmationType = (SignatureConfirmationType) parseStructure(eventQueue, index);
+        inputProcessorChain.getSecurityContext().putAsList(SignatureConfirmationType.class, signatureConfirmationType);
+    }
+
+    @Override
+    protected Parseable getParseable(StartElement startElement) {
+        return new SignatureConfirmationType(startElement);
+    }
+}

Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SignatureConfirmationInputHandler.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SignatureConfirmationInputProcessor.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SignatureConfirmationInputProcessor.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SignatureConfirmationInputProcessor.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SignatureConfirmationInputProcessor.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,94 @@
+/**
+ * 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.swssf.impl.processor.input;
+
+import org.oasis_open.docs.wss.oasis_wss_wssecurity_secext_1_1.SignatureConfirmationType;
+import org.swssf.ext.*;
+import org.swssf.securityEvent.SecurityEvent;
+import org.swssf.securityEvent.SignatureValueSecurityEvent;
+
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.events.EndElement;
+import javax.xml.stream.events.XMLEvent;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class SignatureConfirmationInputProcessor extends AbstractInputProcessor {
+
+    public SignatureConfirmationInputProcessor(SecurityProperties securityProperties) {
+        super(securityProperties);
+    }
+
+    @Override
+    public XMLEvent processNextHeaderEvent(InputProcessorChain inputProcessorChain) throws XMLStreamException, WSSecurityException {
+        XMLEvent xmlEvent = inputProcessorChain.processHeaderEvent();
+        if (xmlEvent.isEndElement()) {
+            EndElement endElement = xmlEvent.asEndElement();
+            if (endElement.getName().equals(Constants.TAG_wsse_Security)) {
+                inputProcessorChain.removeProcessor(this);
+
+                List<SignatureValueSecurityEvent> signatureValueSecurityEventList = inputProcessorChain.getSecurityContext().getAsList(SecurityEvent.class);
+                List<SignatureConfirmationType> signatureConfirmationTypeList = inputProcessorChain.getSecurityContext().getAsList(SignatureConfirmationType.class);
+
+                //when no signature was sent, we expect an empty SignatureConfirmation in the response
+                if (signatureValueSecurityEventList == null || signatureValueSecurityEventList.size() == 0) {
+                    if (signatureConfirmationTypeList == null || signatureConfirmationTypeList.size() != 1) {
+                        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK);
+                    } else if (signatureConfirmationTypeList.get(0).getValue() != null) {
+                        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK);
+                    }
+                }
+
+                if (signatureConfirmationTypeList == null) {
+                    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK);
+                }
+
+                for (int i = 0; i < signatureValueSecurityEventList.size(); i++) {
+                    SignatureValueSecurityEvent signatureValueSecurityEvent = signatureValueSecurityEventList.get(i);
+                    byte[] signatureValue = signatureValueSecurityEvent.getSignatureValue();
+
+                    boolean found = false;
+
+                    for (int j = 0; j < signatureConfirmationTypeList.size(); j++) {
+                        SignatureConfirmationType signatureConfirmationType = signatureConfirmationTypeList.get(j);
+                        byte[] sigConfValue = signatureConfirmationType.getValue();
+                        if (Arrays.equals(signatureValue, sigConfValue)) {
+                            found = true;
+                        }
+                    }
+
+                    if (!found) {
+                        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK);
+                    }
+                }
+            }
+        }
+        return xmlEvent;
+    }
+
+    @Override
+    public XMLEvent processNextEvent(InputProcessorChain inputProcessorChain) throws XMLStreamException, WSSecurityException {
+        //should never be called
+        return null;
+    }
+}

Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SignatureConfirmationInputProcessor.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SignatureInputHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SignatureInputHandler.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SignatureInputHandler.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SignatureInputHandler.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,213 @@
+/**
+ * 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.swssf.impl.processor.input;
+
+import org.swssf.ext.*;
+import org.swssf.impl.algorithms.SignatureAlgorithm;
+import org.swssf.impl.algorithms.SignatureAlgorithmFactory;
+import org.swssf.impl.securityToken.SecurityTokenFactory;
+import org.swssf.impl.util.SignerOutputStream;
+import org.swssf.securityEvent.AlgorithmSuiteSecurityEvent;
+import org.swssf.securityEvent.SecurityEvent;
+import org.swssf.securityEvent.SignatureTokenSecurityEvent;
+import org.w3._2000._09.xmldsig_.KeyInfoType;
+import org.w3._2000._09.xmldsig_.SignatureType;
+
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.events.StartElement;
+import javax.xml.stream.events.XMLEvent;
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.lang.reflect.InvocationTargetException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.cert.CertificateException;
+import java.util.Deque;
+import java.util.Iterator;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class SignatureInputHandler extends AbstractInputSecurityHeaderHandler {
+
+    public SignatureInputHandler(InputProcessorChain inputProcessorChain, SecurityProperties securityProperties, Deque<XMLEvent> eventQueue, Integer index) throws WSSecurityException, XMLStreamException {
+
+        final SignatureType signatureType = (SignatureType) parseStructure(eventQueue, index);
+        verifySignedInfo(inputProcessorChain, securityProperties, signatureType, eventQueue, index);
+    }
+
+    @Override
+    protected Parseable getParseable(StartElement startElement) {
+        return new SignatureType(startElement);
+    }
+
+    private void verifySignedInfo(InputProcessorChain inputProcessorChain, SecurityProperties securityProperties, SignatureType signatureType, Deque<XMLEvent> eventDeque, int index) throws WSSecurityException, XMLStreamException {
+        //todo reparse SignedInfo when custom canonicalization method is used
+        //verify SignedInfo
+        SignatureVerifier signatureVerifier = new SignatureVerifier(signatureType, inputProcessorChain.getSecurityContext(), securityProperties);
+
+        Iterator<XMLEvent> iterator = eventDeque.descendingIterator();
+        //skip to <Signature> Element
+        int i = 0;
+        while (i < index) {
+            iterator.next();
+            i++;
+        }
+
+        boolean verifyElement = false;
+        while (iterator.hasNext()) {
+            XMLEvent xmlEvent = iterator.next();
+            if (xmlEvent.isStartElement() && xmlEvent.asStartElement().getName().equals(Constants.TAG_dsig_SignedInfo)) {
+                verifyElement = true;
+            } else if (xmlEvent.isEndElement() && xmlEvent.asEndElement().getName().equals(Constants.TAG_dsig_SignedInfo)) {
+                signatureVerifier.processEvent(xmlEvent);
+                break;
+            }
+            if (verifyElement) {
+                signatureVerifier.processEvent(xmlEvent);
+            }
+        }
+        signatureVerifier.doFinal();
+
+        //add processors to verify references
+        inputProcessorChain.addProcessor(new SignatureReferenceVerifyInputProcessor(signatureType, securityProperties));
+    }
+
+/*
+    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="Signature-1022834285">
+        <ds:SignedInfo>
+            <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
+            <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
+            <ds:Reference URI="#id-1612925417">
+                <ds:Transforms>
+                    <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
+                </ds:Transforms>
+                <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
+                <ds:DigestValue>cy/khx5N6UobCJ1EbX+qnrGID2U=</ds:DigestValue>
+            </ds:Reference>
+            <ds:Reference URI="#Timestamp-1106985890">
+                <ds:Transforms>
+                    <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
+                </ds:Transforms>
+                <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
+                <ds:DigestValue>+p5YRII6uvUdsJ7XLKkWx1CBewE=</ds:DigestValue>
+            </ds:Reference>
+        </ds:SignedInfo>
+        <ds:SignatureValue>
+            Izg1FlI9oa4gOon2vTXi7V0EpiyCUazECVGYflbXq7/3GF8ThKGDMpush/fo1I2NVjEFTfmT2WP/
+            +ZG5N2jASFptrcGbsqmuLE5JbxUP1TVKb9SigKYcOQJJ8klzmVfPXnSiRZmIU+DUT2UXopWnGNFL
+            TwY0Uxja4ZuI6U8m8Tg=
+        </ds:SignatureValue>
+        <ds:KeyInfo Id="KeyId-1043455692">
+            <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="STRId-1008354042">
+                <wsse:Reference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" URI="#CertId-3458500" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" />
+            </wsse:SecurityTokenReference>
+        </ds:KeyInfo>
+    </ds:Signature>
+     */
+
+    public static class SignatureVerifier {
+
+        private SignatureType signatureType;
+        private SecurityContext securityContext;
+        private SecurityProperties securityProperties;
+
+        private SignerOutputStream signerOutputStream;
+        private OutputStream bufferedSignerOutputStream;
+        private Transformer transformer;
+
+        public SignatureVerifier(SignatureType signatureType, SecurityContext securityContext, SecurityProperties securityProperties) throws WSSecurityException {
+            this.signatureType = signatureType;
+            this.securityContext = securityContext;
+            this.securityProperties = securityProperties;
+
+            try {
+                createSignatureAlgorithm();
+            } catch (Exception e) {
+                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, e);
+            }
+        }
+
+        private void createSignatureAlgorithm() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, CertificateException, WSSecurityException {
+            KeyInfoType keyInfoType = signatureType.getKeyInfo();
+            SecurityToken securityToken = SecurityTokenFactory.newInstance().getSecurityToken(keyInfoType, securityProperties.getSignatureVerificationCrypto(), securityProperties.getCallbackHandler(), securityContext, this);
+            securityToken.verify();
+
+            SignatureTokenSecurityEvent signatureTokenSecurityEvent = new SignatureTokenSecurityEvent(SecurityEvent.Event.SignatureToken);
+            signatureTokenSecurityEvent.setSecurityToken(securityToken);
+            signatureTokenSecurityEvent.setSignatureValue(signatureType.getSignatureValue().getValue());
+            securityContext.registerSecurityEvent(signatureTokenSecurityEvent);
+
+            /*AlgorithmSuiteSecurityEvent algorithmSuiteSecurityEvent = new AlgorithmSuiteSecurityEvent(SecurityEvent.Event.AlgorithmSuite);
+            algorithmSuiteSecurityEvent.setAlgorithmURI(signatureType.getSignedInfo().getSignatureMethod().getAlgorithm());
+            algorithmSuiteSecurityEvent.setKeyUsage();
+            securityContext.registerSecurityEvent(algorithmSuiteSecurityEvent);
+            */
+
+            AlgorithmSuiteSecurityEvent algorithmSuiteSecurityEvent = new AlgorithmSuiteSecurityEvent(SecurityEvent.Event.AlgorithmSuite);
+            algorithmSuiteSecurityEvent.setAlgorithmURI(signatureType.getSignedInfo().getCanonicalizationMethod().getAlgorithm());
+            algorithmSuiteSecurityEvent.setKeyUsage(Constants.KeyUsage.C14n);
+            securityContext.registerSecurityEvent(algorithmSuiteSecurityEvent);
+
+            Key verifyKey;
+            if (securityToken.isAsymmetric()) {
+                verifyKey = securityToken.getPublicKey(Constants.KeyUsage.Asym_Sig);
+            } else {
+                verifyKey = securityToken.getSecretKey(
+                        signatureType.getSignedInfo().getSignatureMethod().getAlgorithm(), Constants.KeyUsage.Sym_Sig);
+            }
+
+            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithmFactory.getInstance().getSignatureAlgorithm(signatureType.getSignedInfo().getSignatureMethod().getAlgorithm());
+            signatureAlgorithm.engineInitVerify(verifyKey);
+            signerOutputStream = new SignerOutputStream(signatureAlgorithm);
+            bufferedSignerOutputStream = new BufferedOutputStream(signerOutputStream);
+
+            try {
+                transformer = Utils.getTransformer(signatureType.getSignedInfo().getCanonicalizationMethod().getInclusiveNamespaces(), this.bufferedSignerOutputStream, signatureType.getSignedInfo().getCanonicalizationMethod().getAlgorithm());
+            } catch (NoSuchMethodException e) {
+                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, e);
+            } catch (InstantiationException e) {
+                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, e);
+            } catch (IllegalAccessException e) {
+                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, e);
+            } catch (InvocationTargetException e) {
+                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, e);
+            }
+        }
+
+        public void processEvent(XMLEvent xmlEvent) throws XMLStreamException {
+            transformer.transform(xmlEvent);
+        }
+
+        public void doFinal() throws WSSecurityException {
+            try {
+                bufferedSignerOutputStream.close();
+                if (!signerOutputStream.verify(signatureType.getSignatureValue().getValue())) {
+                    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK);
+                }
+            } catch (IOException e) {
+                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, e);
+            }
+        }
+    }
+}

Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/main/java/org/swssf/impl/processor/input/SignatureInputHandler.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision



Mime
View raw message