You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ws.apache.org by gi...@apache.org on 2013/01/16 16:14:24 UTC

svn commit: r1433975 [1/2] - in /webservices/wss4j/trunk: bindings/wsu10-binding/ bindings/wsu10-binding/src/main/java/org/ bindings/wsu10-binding/src/main/java/org/apache/ bindings/wsu10-binding/src/main/java/org/apache/ws/ bindings/wsu10-binding/src/...

Author: giger
Date: Wed Jan 16 15:14:23 2013
New Revision: 1433975

URL: http://svn.apache.org/viewvc?rev=1433975&view=rev
Log:
WSS-363 Support pluggable Validation of received tokens as per DOM code. 

Added:
    webservices/wss4j/trunk/bindings/wsu10-binding/src/main/java/org/
    webservices/wss4j/trunk/bindings/wsu10-binding/src/main/java/org/apache/
    webservices/wss4j/trunk/bindings/wsu10-binding/src/main/java/org/apache/ws/
    webservices/wss4j/trunk/bindings/wsu10-binding/src/main/java/org/apache/ws/security/
    webservices/wss4j/trunk/bindings/wsu10-binding/src/main/java/org/apache/ws/security/binding/
    webservices/wss4j/trunk/bindings/wsu10-binding/src/main/java/org/apache/ws/security/binding/wsu10/
    webservices/wss4j/trunk/bindings/wsu10-binding/src/main/java/org/apache/ws/security/binding/wsu10/AbstractAttributedDateTime.java   (with props)
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/validate/
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/validate/BinarySecurityTokenValidator.java   (with props)
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/validate/BinarySecurityTokenValidatorImpl.java   (with props)
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/validate/SamlTokenValidator.java   (with props)
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/validate/SamlTokenValidatorImpl.java   (with props)
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/validate/SecurityContextTokenValidator.java   (with props)
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/validate/SecurityContextTokenValidatorImpl.java   (with props)
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/validate/SignatureTokenValidator.java   (with props)
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/validate/SignatureTokenValidatorImpl.java   (with props)
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/validate/TimestampValidator.java   (with props)
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/validate/TimestampValidatorImpl.java   (with props)
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/validate/TokenContext.java   (with props)
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/validate/UsernameTokenValidator.java   (with props)
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/validate/UsernameTokenValidatorImpl.java   (with props)
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/validate/Validator.java   (with props)
Modified:
    webservices/wss4j/trunk/bindings/wsu10-binding/pom.xml
    webservices/wss4j/trunk/bindings/wsu10-binding/src/main/resources/wsu10.xjb
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/ext/WSSSecurityProperties.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/BinarySecurityTokenInputHandler.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/SAMLTokenInputHandler.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/SecurityContextTokenInputHandler.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/TimestampInputHandler.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/UsernameTokenInputHandler.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/WSSSignatureInputHandler.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/securityToken/KerberosServiceSecurityToken.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/securityToken/X509SecurityToken.java

Modified: webservices/wss4j/trunk/bindings/wsu10-binding/pom.xml
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/bindings/wsu10-binding/pom.xml?rev=1433975&r1=1433974&r2=1433975&view=diff
==============================================================================
--- webservices/wss4j/trunk/bindings/wsu10-binding/pom.xml (original)
+++ webservices/wss4j/trunk/bindings/wsu10-binding/pom.xml Wed Jan 16 15:14:23 2013
@@ -78,6 +78,16 @@
                             <!-- disable schema validation since the validation code
                             doesn't respect the catalog and will do online lookups :-( -->
                             <strict>false</strict>
+                            <args>
+                                <arg>-Xinheritance</arg>
+                            </args>
+                            <plugins>
+                                <plugin>
+                                    <groupId>org.jvnet.jaxb2_commons</groupId>
+                                    <artifactId>jaxb2-basics</artifactId>
+                                    <version>0.6.3</version>
+                                </plugin>
+                            </plugins>
                         </configuration>
                     </execution>
                 </executions>

Added: webservices/wss4j/trunk/bindings/wsu10-binding/src/main/java/org/apache/ws/security/binding/wsu10/AbstractAttributedDateTime.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/bindings/wsu10-binding/src/main/java/org/apache/ws/security/binding/wsu10/AbstractAttributedDateTime.java?rev=1433975&view=auto
==============================================================================
--- webservices/wss4j/trunk/bindings/wsu10-binding/src/main/java/org/apache/ws/security/binding/wsu10/AbstractAttributedDateTime.java (added)
+++ webservices/wss4j/trunk/bindings/wsu10-binding/src/main/java/org/apache/ws/security/binding/wsu10/AbstractAttributedDateTime.java Wed Jan 16 15:14:23 2013
@@ -0,0 +1,54 @@
+/**
+ * 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.binding.wsu10;
+
+import javax.xml.bind.annotation.XmlTransient;
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeFactory;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+@XmlTransient
+public abstract class AbstractAttributedDateTime {
+
+    private static final DatatypeFactory datatypeFactory;
+
+    static {
+        try {
+            datatypeFactory = DatatypeFactory.newInstance();
+        } catch (DatatypeConfigurationException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @XmlTransient
+    private XMLGregorianCalendar xmlGregorianCalendar;
+
+    public abstract String getValue();
+
+    public XMLGregorianCalendar getAsXMLGregorianCalendar() throws IllegalArgumentException {
+        if (xmlGregorianCalendar == null && getValue() != null) {
+            xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar(getValue());
+        }
+        return xmlGregorianCalendar;
+    }
+}

Propchange: webservices/wss4j/trunk/bindings/wsu10-binding/src/main/java/org/apache/ws/security/binding/wsu10/AbstractAttributedDateTime.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: webservices/wss4j/trunk/bindings/wsu10-binding/src/main/java/org/apache/ws/security/binding/wsu10/AbstractAttributedDateTime.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Modified: webservices/wss4j/trunk/bindings/wsu10-binding/src/main/resources/wsu10.xjb
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/bindings/wsu10-binding/src/main/resources/wsu10.xjb?rev=1433975&r1=1433974&r2=1433975&view=diff
==============================================================================
--- webservices/wss4j/trunk/bindings/wsu10-binding/src/main/resources/wsu10.xjb (original)
+++ webservices/wss4j/trunk/bindings/wsu10-binding/src/main/resources/wsu10.xjb Wed Jan 16 15:14:23 2013
@@ -1,10 +1,16 @@
 <bindings xmlns="http://java.sun.com/xml/ns/jaxb"
+          xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
           xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
+          xmlns:inheritance="http://jaxb2-commons.dev.java.net/basic/inheritance"
+          jaxb:extensionBindingPrefixes="inheritance"
           version="2.1">
     <bindings schemaLocation="schemas/oasis-200401-wss-wssecurity-utility-1.0.xsd" version="1.0">
         <schemaBindings>
             <package name="org.apache.ws.security.binding.wsu10"/>
         </schemaBindings>
+        <bindings node="//xs:complexType[@name='AttributedDateTime']">
+            <inheritance:extends>org.apache.ws.security.binding.wsu10.AbstractAttributedDateTime</inheritance:extends>
+        </bindings>
     </bindings>
 </bindings>

Modified: webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/ext/WSSSecurityProperties.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/ext/WSSSecurityProperties.java?rev=1433975&r1=1433974&r2=1433975&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/ext/WSSSecurityProperties.java (original)
+++ webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/ext/WSSSecurityProperties.java Wed Jan 16 15:14:23 2013
@@ -20,17 +20,17 @@ package org.apache.ws.security.stax.ext;
 
 import java.net.URL;
 import java.security.KeyStore;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
+import java.util.*;
 
 import org.apache.ws.security.common.bsp.BSPRule;
 import org.apache.ws.security.common.crypto.Crypto;
 import org.apache.ws.security.common.crypto.Merlin;
+import org.apache.ws.security.stax.validate.Validator;
 import org.apache.xml.security.stax.config.ConfigurationProperties;
 import org.apache.xml.security.stax.ext.XMLSecurityProperties;
 
 import javax.security.auth.callback.CallbackHandler;
+import javax.xml.namespace.QName;
 
 /**
  * Main configuration class to supply keys etc.
@@ -45,6 +45,7 @@ public class WSSSecurityProperties exten
     private String actor;
     private CallbackHandler callbackHandler;
     private final List<BSPRule> ignoredBSPRules = new LinkedList<BSPRule>();
+    private final Map<QName, Validator> validators = new HashMap<QName, Validator>();
 
     private Integer timestampTTL = 300;
     private boolean strictTimestampCheck = true;
@@ -100,6 +101,7 @@ public class WSSSecurityProperties exten
         this.actor = wssSecurityProperties.actor;
         this.callbackHandler = wssSecurityProperties.callbackHandler;
         this.ignoredBSPRules.addAll(wssSecurityProperties.ignoredBSPRules);
+        this.validators.putAll(wssSecurityProperties.validators);
         this.timestampTTL = wssSecurityProperties.timestampTTL;
         this.strictTimestampCheck = wssSecurityProperties.strictTimestampCheck;
         this.handleCustomPasswordTypes = wssSecurityProperties.handleCustomPasswordTypes;
@@ -265,6 +267,15 @@ public class WSSSecurityProperties exten
         return Collections.unmodifiableList(ignoredBSPRules);
     }
 
+    public void addValidator(QName qName, Validator validator) {
+        validators.put(qName, validator);
+    }
+
+    @SuppressWarnings("unchecked")
+    public <T extends Validator> T getValidator(QName qName) {
+        return (T)validators.get(qName);
+    }
+
     public void setSignatureUser(String signatureUser) {
         this.signatureUser = signatureUser;
     }

Modified: webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/BinarySecurityTokenInputHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/BinarySecurityTokenInputHandler.java?rev=1433975&r1=1433974&r2=1433975&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/BinarySecurityTokenInputHandler.java (original)
+++ webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/BinarySecurityTokenInputHandler.java Wed Jan 16 15:14:23 2013
@@ -18,25 +18,19 @@
  */
 package org.apache.ws.security.stax.impl.processor.input;
 
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
 import org.apache.ws.security.binding.wss10.BinarySecurityTokenType;
 import org.apache.ws.security.common.bsp.BSPRule;
-import org.apache.ws.security.common.crypto.Crypto;
 import org.apache.ws.security.common.ext.WSSecurityException;
-import org.apache.ws.security.stax.ext.WSSConfigurationException;
 import org.apache.ws.security.stax.ext.WSSConstants;
 import org.apache.ws.security.stax.ext.WSSSecurityProperties;
 import org.apache.ws.security.stax.ext.WSSecurityContext;
-import org.apache.ws.security.stax.impl.securityToken.KerberosServiceSecurityToken;
-import org.apache.ws.security.stax.impl.securityToken.X509PKIPathv1SecurityToken;
-import org.apache.ws.security.stax.impl.securityToken.X509_V3SecurityToken;
 import org.apache.ws.security.stax.securityEvent.KerberosTokenSecurityEvent;
+import org.apache.ws.security.stax.validate.BinarySecurityTokenValidator;
+import org.apache.ws.security.stax.validate.BinarySecurityTokenValidatorImpl;
+import org.apache.ws.security.stax.validate.TokenContext;
 import org.apache.xml.security.exceptions.XMLSecurityException;
 import org.apache.xml.security.stax.ext.*;
 import org.apache.xml.security.stax.ext.stax.XMLSecEvent;
-import org.apache.xml.security.stax.impl.securityToken.AbstractInboundSecurityToken;
 import org.apache.xml.security.stax.impl.util.IDGenerator;
 import org.apache.xml.security.stax.securityEvent.TokenSecurityEvent;
 import org.apache.xml.security.stax.securityEvent.X509TokenSecurityEvent;
@@ -54,8 +48,6 @@ import java.util.List;
  */
 public class BinarySecurityTokenInputHandler extends AbstractInputSecurityHeaderHandler {
 
-    private static final transient Log log = LogFactory.getLog(BinarySecurityTokenInputHandler.class);
-
     @Override
     public void handle(final InputProcessorChain inputProcessorChain, final XMLSecurityProperties securityProperties,
                        final Deque<XMLSecEvent> eventQueue, final Integer index) throws XMLSecurityException {
@@ -69,64 +61,34 @@ public class BinarySecurityTokenInputHan
             binarySecurityTokenType.setId(IDGenerator.generateID(null));
         }
 
+        final WSSecurityContext wsSecurityContext = (WSSecurityContext) inputProcessorChain.getSecurityContext();
+        final WSSSecurityProperties wssSecurityProperties = (WSSSecurityProperties) securityProperties;
         final List<QName> elementPath = getElementPath(eventQueue);
-        final XMLSecEvent responsibleXMLSecStartXMLEvent = getResponsibleStartXMLEvent(eventQueue, index);
-        final WSSecurityContext securityContext = (WSSecurityContext) inputProcessorChain.getSecurityContext();
+        final List<XMLSecEvent> xmlSecEvents = getResponsibleXMLSecEvents(eventQueue, index);
 
-        final SecurityTokenProvider securityTokenProvider = new SecurityTokenProvider() {
+        final TokenContext tokenContext = new TokenContext(wssSecurityProperties, wsSecurityContext, xmlSecEvents, elementPath);
 
-            private AbstractInboundSecurityToken securityToken = null;
+        BinarySecurityTokenValidator binarySecurityTokenValidator =
+                wssSecurityProperties.getValidator(WSSConstants.TAG_wsse_BinarySecurityToken);
+        if (binarySecurityTokenValidator == null) {
+            binarySecurityTokenValidator = new BinarySecurityTokenValidatorImpl();
+        }
+        final SecurityToken binarySecurityToken =
+                binarySecurityTokenValidator.validate(binarySecurityTokenType, tokenContext);
 
-            @SuppressWarnings("unchecked")
+        SecurityTokenProvider securityTokenProvider = new SecurityTokenProvider() {
             @Override
             public SecurityToken getSecurityToken() throws XMLSecurityException {
-                if (this.securityToken != null) {
-                    return this.securityToken;
-                }
-
-                //only Base64Encoding is supported
-                if (!WSSConstants.SOAPMESSAGE_NS10_BASE64_ENCODING.equals(binarySecurityTokenType.getEncodingType())) {
-                    throw new WSSecurityException(
-                            WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "badEncoding", binarySecurityTokenType.getEncodingType());
-                }
-
-                byte[] securityTokenData = Base64.decodeBase64(binarySecurityTokenType.getValue());
-
-                if (WSSConstants.NS_X509_V3_TYPE.equals(binarySecurityTokenType.getValueType())) {
-                    Crypto crypto = getCrypto((WSSSecurityProperties) securityProperties);
-                    this.securityToken = new X509_V3SecurityToken(
-                            (WSSecurityContext) securityContext, crypto, ((WSSSecurityProperties)securityProperties).getCallbackHandler(),
-                            securityTokenData, binarySecurityTokenType.getId(), WSSConstants.WSSKeyIdentifierType.SECURITY_TOKEN_DIRECT_REFERENCE
-                    );
-                } else if (WSSConstants.NS_X509PKIPathv1.equals(binarySecurityTokenType.getValueType())) {
-                    Crypto crypto = getCrypto((WSSSecurityProperties) securityProperties);
-                    this.securityToken = new X509PKIPathv1SecurityToken(
-                            (WSSecurityContext) securityContext, crypto, ((WSSSecurityProperties)securityProperties).getCallbackHandler(),
-                            securityTokenData, binarySecurityTokenType.getId(), WSSConstants.WSSKeyIdentifierType.SECURITY_TOKEN_DIRECT_REFERENCE
-                    );
-                } else if (WSSConstants.NS_GSS_Kerberos5_AP_REQ.equals(binarySecurityTokenType.getValueType())) {
-                    this.securityToken = new KerberosServiceSecurityToken(
-                            (WSSecurityContext) securityContext, ((WSSSecurityProperties)securityProperties).getCallbackHandler(),
-                            securityTokenData, binarySecurityTokenType.getValueType(),
-                            binarySecurityTokenType.getId(), WSSConstants.WSSKeyIdentifierType.SECURITY_TOKEN_DIRECT_REFERENCE
-                    );
-                } else {
-                    throw new WSSecurityException(
-                            WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "invalidValueType", binarySecurityTokenType.getValueType());
-                }
-
-                this.securityToken.setElementPath(elementPath);
-                this.securityToken.setXMLSecEvent(responsibleXMLSecStartXMLEvent);
-                return this.securityToken;
+                return binarySecurityToken;
             }
 
             @Override
             public String getId() {
-                return binarySecurityTokenType.getId();
+                return binarySecurityToken.getId();
             }
         };
 
-        securityContext.registerSecurityTokenProvider(binarySecurityTokenType.getId(), securityTokenProvider);
+        wsSecurityContext.registerSecurityTokenProvider(binarySecurityTokenType.getId(), securityTokenProvider);
 
         TokenSecurityEvent tokenSecurityEvent;
         //fire a tokenSecurityEvent
@@ -136,29 +98,17 @@ public class BinarySecurityTokenInputHan
             tokenSecurityEvent = new KerberosTokenSecurityEvent();
         } else {
             throw new WSSecurityException(
-                    WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "invalidValueType", binarySecurityTokenType.getValueType());
+                    WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "invalidValueType",
+                    binarySecurityTokenType.getValueType());
         }
-        tokenSecurityEvent.setSecurityToken((SecurityToken) securityTokenProvider.getSecurityToken());
+        tokenSecurityEvent.setSecurityToken((SecurityToken) binarySecurityToken);
         tokenSecurityEvent.setCorrelationID(binarySecurityTokenType.getId());
-        securityContext.registerSecurityEvent(tokenSecurityEvent);
-    }
-
-    private Crypto getCrypto(WSSSecurityProperties securityProperties) throws WSSConfigurationException {
-        Crypto crypto = null;
-        try {
-            crypto = securityProperties.getSignatureVerificationCrypto();
-        } catch (WSSConfigurationException e) {
-            log.debug(e.getMessage(), e);
-            //ignore
-        }
-        if (crypto == null) {
-            crypto = securityProperties.getDecryptionCrypto();
-        }
-        return crypto;
+        wsSecurityContext.registerSecurityEvent(tokenSecurityEvent);
     }
 
     private void checkBSPCompliance(InputProcessorChain inputProcessorChain, BinarySecurityTokenType binarySecurityTokenType)
             throws WSSecurityException {
+
         final WSSecurityContext securityContext = (WSSecurityContext) inputProcessorChain.getSecurityContext();
         if (binarySecurityTokenType.getEncodingType() == null) {
             securityContext.handleBSPRule(BSPRule.R3029);

Modified: webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/SAMLTokenInputHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/SAMLTokenInputHandler.java?rev=1433975&r1=1433974&r2=1433975&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/SAMLTokenInputHandler.java (original)
+++ webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/SAMLTokenInputHandler.java Wed Jan 16 15:14:23 2013
@@ -19,20 +19,20 @@
 package org.apache.ws.security.stax.impl.processor.input;
 
 import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
 import org.apache.ws.security.binding.wss10.ObjectFactory;
 import org.apache.ws.security.binding.wss10.SecurityTokenReferenceType;
 import org.apache.ws.security.common.ext.WSSecurityException;
-import org.apache.ws.security.common.saml.SamlAssertionWrapper;
 import org.apache.ws.security.common.saml.OpenSAMLUtil;
 import org.apache.ws.security.common.saml.SAMLUtil;
+import org.apache.ws.security.common.saml.SamlAssertionWrapper;
 import org.apache.ws.security.stax.ext.WSSConstants;
 import org.apache.ws.security.stax.ext.WSSSecurityProperties;
 import org.apache.ws.security.stax.ext.WSSUtils;
 import org.apache.ws.security.stax.ext.WSSecurityContext;
-import org.apache.ws.security.stax.impl.securityToken.SAMLSecurityToken;
 import org.apache.ws.security.stax.securityEvent.SamlTokenSecurityEvent;
+import org.apache.ws.security.stax.validate.SamlTokenValidator;
+import org.apache.ws.security.stax.validate.SamlTokenValidatorImpl;
+import org.apache.ws.security.stax.validate.TokenContext;
 import org.apache.xml.security.binding.xmldsig.KeyInfoType;
 import org.apache.xml.security.binding.xmldsig.KeyValueType;
 import org.apache.xml.security.binding.xmldsig.X509DataType;
@@ -51,14 +51,11 @@ import org.apache.xml.security.stax.secu
 import org.apache.xml.security.stax.securityEvent.SecurityEventConstants;
 import org.apache.xml.security.stax.securityEvent.SecurityEventListener;
 import org.apache.xml.security.stax.securityEvent.SignedElementSecurityEvent;
-import org.joda.time.DateTime;
-import org.opensaml.common.SAMLVersion;
 import org.opensaml.security.SAMLSignatureProfileValidator;
 import org.opensaml.xml.security.x509.BasicX509Credential;
 import org.opensaml.xml.signature.Signature;
 import org.opensaml.xml.signature.SignatureValidator;
 import org.opensaml.xml.validation.ValidationException;
-import org.opensaml.xml.validation.ValidatorSuite;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -89,7 +86,6 @@ import java.util.*;
  */
 public class SAMLTokenInputHandler extends AbstractInputSecurityHeaderHandler {
 
-    private static final transient Log log = LogFactory.getLog(SAMLTokenInputHandler.class);
     private static final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
 
     private static final List<QName> saml1TokenPath = new ArrayList<QName>(WSSConstants.WSSE_SECURITY_HEADER_PATH);
@@ -101,19 +97,21 @@ public class SAMLTokenInputHandler exten
         saml2TokenPath.add(WSSConstants.TAG_saml2_Assertion);
     }
 
-    /**
-     * The time in seconds in the future within which the NotBefore time of an incoming
-     * Assertion is valid. The default is 60 seconds.
-     */
-    private int futureTTL = 60;
-
     @Override
     public void handle(final InputProcessorChain inputProcessorChain, final XMLSecurityProperties securityProperties,
                        Deque<XMLSecEvent> eventQueue, Integer index) throws XMLSecurityException {
 
         final Document samlTokenDocument = (Document) parseStructure(eventQueue, index, securityProperties);
 
-        final SamlAssertionWrapper samlAssertionWrapper = new SamlAssertionWrapper(samlTokenDocument.getDocumentElement());
+        final WSSSecurityProperties wssSecurityProperties = (WSSSecurityProperties) securityProperties;
+        final WSSecurityContext wsSecurityContext = (WSSecurityContext) inputProcessorChain.getSecurityContext();
+        final Element samlElement = samlTokenDocument.getDocumentElement();
+        final SamlAssertionWrapper samlAssertionWrapper = new SamlAssertionWrapper(samlElement);
+
+        SamlTokenValidator samlTokenValidator = wssSecurityProperties.getValidator(new QName(samlElement.getNamespaceURI(), samlElement.getLocalName()));
+        if (samlTokenValidator == null) {
+            samlTokenValidator = new SamlTokenValidatorImpl();
+        }
 
         //important: check the signature before we do other processing...
         if (samlAssertionWrapper.isSigned()) {
@@ -139,7 +137,8 @@ public class SAMLTokenInputHandler exten
             if (sigSecurityToken == null) {
                 throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "noKeyInSAMLToken");
             }
-            sigSecurityToken.verify();
+
+            samlTokenValidator.validate(sigSecurityToken, wssSecurityProperties);
 
             BasicX509Credential credential = new BasicX509Credential();
             if (sigSecurityToken.getX509Certificates() != null) {
@@ -161,11 +160,6 @@ public class SAMLTokenInputHandler exten
             }
         }
 
-        // TODO move the following into a Validator eventually
-
-        checkConditions(samlAssertionWrapper);
-        validateAssertion(samlAssertionWrapper);
-
         String confirmMethod = null;
         List<String> methods = samlAssertionWrapper.getConfirmationMethods();
         if (methods != null && methods.size() > 0) {
@@ -176,16 +170,14 @@ public class SAMLTokenInputHandler exten
 
         if (OpenSAMLUtil.isMethodHolderOfKey(confirmMethod)) {
 
-            //todo shouldn't we do a crypto-lookup here first?
-
             // First try to get the credential from a CallbackHandler
             final byte[] subjectSecretKey = SAMLUtil.getSecretKeyFromCallbackHandler(
-                    samlAssertionWrapper.getId(), ((WSSSecurityProperties) securityProperties).getCallbackHandler());
+                    samlAssertionWrapper.getId(), wssSecurityProperties.getCallbackHandler());
 
             if (subjectSecretKey != null && subjectSecretKey.length > 0) {
 
                 subjectSecurityToken = new AbstractInboundSecurityToken(
-                        inputProcessorChain.getSecurityContext(), "",
+                        wsSecurityContext, "",
                         XMLSecurityConstants.XMLKeyIdentifierType.NO_KEY_INFO) {
                     @Override
                     public XMLSecurityConstants.TokenType getTokenType() {
@@ -230,32 +222,19 @@ public class SAMLTokenInputHandler exten
             subjectSecurityToken = null;
         }
 
-        if (log.isDebugEnabled()) {
-            log.debug("SAML Assertion issuer " + samlAssertionWrapper.getIssuerString());
-        }
-
+        final List<XMLSecEvent> xmlSecEvents = getResponsibleXMLSecEvents(eventQueue, index);
         final List<QName> elementPath = getElementPath(eventQueue);
-        final XMLSecEvent responsibleStartXMLEvent = getResponsibleStartXMLEvent(eventQueue, index);
+        final TokenContext tokenContext = new TokenContext(wssSecurityProperties, wsSecurityContext, xmlSecEvents, elementPath);
 
-        SecurityTokenProvider securityTokenProvider = new SecurityTokenProvider() {
+        final SecurityToken securityToken = samlTokenValidator.validate(
+                samlAssertionWrapper, subjectSecurityToken, tokenContext);
 
-            private SAMLSecurityToken securityToken = null;
+        SecurityTokenProvider subjectSecurityTokenProvider = new SecurityTokenProvider() {
 
             @SuppressWarnings("unchecked")
             @Override
             public SecurityToken getSecurityToken() throws XMLSecurityException {
-                if (this.securityToken != null) {
-                    return this.securityToken;
-                }
-
-                this.securityToken = new SAMLSecurityToken(samlAssertionWrapper, subjectSecurityToken,
-                        (WSSecurityContext) inputProcessorChain.getSecurityContext(),
-                        ((WSSSecurityProperties) securityProperties).getSignatureVerificationCrypto(),
-                        samlAssertionWrapper.getId(), null);
-
-                this.securityToken.setElementPath(elementPath);
-                this.securityToken.setXMLSecEvent(responsibleStartXMLEvent);
-                return this.securityToken;
+                return securityToken;
             }
 
             @Override
@@ -263,17 +242,18 @@ public class SAMLTokenInputHandler exten
                 return samlAssertionWrapper.getId();
             }
         };
-        inputProcessorChain.getSecurityContext().registerSecurityTokenProvider(samlAssertionWrapper.getId(), securityTokenProvider);
+
+        wsSecurityContext.registerSecurityTokenProvider(samlAssertionWrapper.getId(), subjectSecurityTokenProvider);
 
         //fire a tokenSecurityEvent
         SamlTokenSecurityEvent samlTokenSecurityEvent = new SamlTokenSecurityEvent();
-        samlTokenSecurityEvent.setSecurityToken((SecurityToken) securityTokenProvider.getSecurityToken());
+        samlTokenSecurityEvent.setSecurityToken((SecurityToken) subjectSecurityTokenProvider.getSecurityToken());
         samlTokenSecurityEvent.setCorrelationID(samlAssertionWrapper.getId());
-        inputProcessorChain.getSecurityContext().registerSecurityEvent(samlTokenSecurityEvent);
+        wsSecurityContext.registerSecurityEvent(samlTokenSecurityEvent);
 
         SAMLTokenVerifierInputProcessor samlTokenVerifierInputProcessor =
-                new SAMLTokenVerifierInputProcessor(securityProperties, samlAssertionWrapper, securityTokenProvider, subjectSecurityToken);
-        inputProcessorChain.getSecurityContext().addSecurityEventListener(samlTokenVerifierInputProcessor);
+                new SAMLTokenVerifierInputProcessor(securityProperties, samlAssertionWrapper, subjectSecurityTokenProvider, subjectSecurityToken);
+        wsSecurityContext.addSecurityEventListener(samlTokenVerifierInputProcessor);
         inputProcessorChain.addProcessor(samlTokenVerifierInputProcessor);
     }
 
@@ -567,70 +547,6 @@ public class SAMLTokenInputHandler exten
     }
 
     /**
-     * Check the Conditions of the Assertion.
-     */
-    protected void checkConditions(SamlAssertionWrapper samlAssertion) throws WSSecurityException {
-        DateTime validFrom = null;
-        DateTime validTill = null;
-        if (samlAssertion.getSamlVersion().equals(SAMLVersion.VERSION_20)
-                && samlAssertion.getSaml2().getConditions() != null) {
-            validFrom = samlAssertion.getSaml2().getConditions().getNotBefore();
-            validTill = samlAssertion.getSaml2().getConditions().getNotOnOrAfter();
-        } else if (samlAssertion.getSamlVersion().equals(SAMLVersion.VERSION_11)
-                && samlAssertion.getSaml1().getConditions() != null) {
-            validFrom = samlAssertion.getSaml1().getConditions().getNotBefore();
-            validTill = samlAssertion.getSaml1().getConditions().getNotOnOrAfter();
-        }
-
-        if (validFrom != null) {
-            DateTime currentTime = new DateTime();
-            currentTime = currentTime.plusSeconds(futureTTL);
-            if (validFrom.isAfter(currentTime)) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE,
-                        "empty", "SAML Token condition (Not Before) not met");
-            }
-        }
-
-        if (validTill != null && validTill.isBeforeNow()) {
-            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE,
-                    "empty", "SAML Token condition (Not On Or After) not met");
-        }
-    }
-
-    /**
-     * Validate the assertion against schemas/profiles
-     */
-    protected void validateAssertion(SamlAssertionWrapper samlAssertion) throws WSSecurityException {
-        if (samlAssertion.getSaml1() != null) {
-            ValidatorSuite schemaValidators =
-                    org.opensaml.Configuration.getValidatorSuite("saml1-schema-validator");
-            ValidatorSuite specValidators =
-                    org.opensaml.Configuration.getValidatorSuite("saml1-spec-validator");
-            try {
-                schemaValidators.validate(samlAssertion.getSaml1());
-                specValidators.validate(samlAssertion.getSaml1());
-            } catch (ValidationException e) {
-                throw new WSSecurityException(
-                        WSSecurityException.ErrorCode.FAILURE, "empty", e, "Saml Validation error: "
-                );
-            }
-        } else if (samlAssertion.getSaml2() != null) {
-            ValidatorSuite schemaValidators =
-                    org.opensaml.Configuration.getValidatorSuite("saml2-core-schema-validator");
-            ValidatorSuite specValidators =
-                    org.opensaml.Configuration.getValidatorSuite("saml2-core-spec-validator");
-            try {
-                schemaValidators.validate(samlAssertion.getSaml2());
-                specValidators.validate(samlAssertion.getSaml2());
-            } catch (ValidationException e) {
-                throw new WSSecurityException(
-                        WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity", e, "Saml Validation error: "
-                );
-            }
-        }
-    }
-
-    /**
      * Processor to check the holder-of-key or sender-vouches requirements against the received assertion
      * which can not be done until the whole soap-header is processed and we now that the whole soap-body
      * is signed.
@@ -656,7 +572,7 @@ public class SAMLTokenInputHandler exten
         @Override
         public void registerSecurityEvent(SecurityEvent securityEvent) throws XMLSecurityException {
             if (securityEvent.getSecurityEventType() == SecurityEventConstants.SignedElement) {
-                SignedElementSecurityEvent signedElementSecurityEvent = (SignedElementSecurityEvent)securityEvent;
+                SignedElementSecurityEvent signedElementSecurityEvent = (SignedElementSecurityEvent) securityEvent;
 
                 List<QName> elementPath = signedElementSecurityEvent.getElementPath();
                 if (elementPath.equals(WSSConstants.SOAP_11_BODY_PATH)) {
@@ -730,10 +646,10 @@ public class SAMLTokenInputHandler exten
                             //compare certificates:
                             if (subjectCertificates != null && subjectCertificates.length > 0
                                     && httpsCertificate.equals(subjectCertificates[0])) {
-                                    return;
+                                return;
                                 //compare public keys:
                             } else if (httpsCertificate.getPublicKey().equals(subjectPublicKey)) {
-                                    return;
+                                return;
                             }
                         } else {
                             for (int j = 0; j < securityTokenProviders.size(); j++) {
@@ -748,22 +664,21 @@ public class SAMLTokenInputHandler exten
                                 if (x509Certificates != null && x509Certificates.length > 0
                                         && subjectCertificates != null && subjectCertificates.length > 0 &&
                                         subjectCertificates[0].equals(x509Certificates[0])) {
-                                        return;
+                                    return;
                                 }
                                 if (publicKey != null && publicKey.equals(subjectPublicKey)) {
                                     return;
                                 }
-                                 Iterator<Map.Entry<String,Key>> iterator = keyMap.entrySet().iterator();
-                                 while(iterator.hasNext()){
-                                     Map.Entry<String,Key> next = iterator.next();
-                                     if (next.getValue().equals(subjectSecretKey)) {
-                                         return;
-                                     }
-                                 }
+                                Iterator<Map.Entry<String, Key>> iterator = keyMap.entrySet().iterator();
+                                while (iterator.hasNext()) {
+                                    Map.Entry<String, Key> next = iterator.next();
+                                    if (next.getValue().equals(subjectSecretKey)) {
+                                        return;
+                                    }
+                                }
                             }
                         }
-                    }
-                    else if (OpenSAMLUtil.isMethodSenderVouches(confirmationMethod)) {
+                    } else if (OpenSAMLUtil.isMethodSenderVouches(confirmationMethod)) {
                         /**
                          * Check the sender-vouches requirements against the received assertion. The SAML
                          * Assertion and the SOAP Body must be signed by the same signature.
@@ -781,7 +696,7 @@ public class SAMLTokenInputHandler exten
                         SignedElementSecurityEvent samlTokenSignedElementSecurityEvent = null;
                         for (int j = 0; j < samlTokenSignedElementSecurityEvents.size(); j++) {
                             SignedElementSecurityEvent signedElementSecurityEvent = samlTokenSignedElementSecurityEvents.get(j);
-                            if (((SecurityToken)securityTokenProvider.getSecurityToken()).getXMLSecEvent() ==
+                            if (((SecurityToken) securityTokenProvider.getSecurityToken()).getXMLSecEvent() ==
                                     signedElementSecurityEvent.getXmlSecEvent()) {
 
                                 samlTokenSignedElementSecurityEvent = signedElementSecurityEvent;

Modified: webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/SecurityContextTokenInputHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/SecurityContextTokenInputHandler.java?rev=1433975&r1=1433974&r2=1433975&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/SecurityContextTokenInputHandler.java (original)
+++ webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/SecurityContextTokenInputHandler.java Wed Jan 16 15:14:23 2013
@@ -19,24 +19,20 @@
 package org.apache.ws.security.stax.impl.processor.input;
 
 import org.apache.ws.security.binding.wssc.AbstractSecurityContextTokenType;
-import org.apache.ws.security.common.ext.WSPasswordCallback;
-import org.apache.ws.security.common.ext.WSSecurityException;
 import org.apache.ws.security.stax.ext.WSSConstants;
 import org.apache.ws.security.stax.ext.WSSSecurityProperties;
-import org.apache.ws.security.stax.ext.WSSUtils;
 import org.apache.ws.security.stax.ext.WSSecurityContext;
 import org.apache.ws.security.stax.securityEvent.SecurityContextTokenSecurityEvent;
+import org.apache.ws.security.stax.validate.SecurityContextTokenValidator;
+import org.apache.ws.security.stax.validate.SecurityContextTokenValidatorImpl;
+import org.apache.ws.security.stax.validate.TokenContext;
 import org.apache.xml.security.exceptions.XMLSecurityException;
-import org.apache.xml.security.stax.config.JCEAlgorithmMapper;
 import org.apache.xml.security.stax.ext.*;
 import org.apache.xml.security.stax.ext.stax.XMLSecEvent;
-import org.apache.xml.security.stax.impl.securityToken.AbstractInboundSecurityToken;
 import org.apache.xml.security.stax.impl.util.IDGenerator;
 
-import javax.crypto.spec.SecretKeySpec;
 import javax.xml.bind.JAXBElement;
 import javax.xml.namespace.QName;
-import java.security.Key;
 import java.util.Deque;
 import java.util.List;
 
@@ -60,51 +56,24 @@ public class SecurityContextTokenInputHa
             securityContextTokenType.setId(IDGenerator.generateID(null));
         }
 
+        final QName elementName = new QName(securityContextTokenTypeJAXBElement.getName().getNamespaceURI(),
+                WSSConstants.TAG_wsc0502_Identifier.getLocalPart());
         final String identifier = (String) XMLSecurityUtils.getQNameType(securityContextTokenType.getAny(),
-                new QName(securityContextTokenTypeJAXBElement.getName().getNamespaceURI(), WSSConstants.TAG_wsc0502_Identifier.getLocalPart()));
+                elementName);
 
+        final WSSecurityContext wsSecurityContext = (WSSecurityContext) inputProcessorChain.getSecurityContext();
+        final WSSSecurityProperties wssSecurityProperties = (WSSSecurityProperties) securityProperties;
+        final List<XMLSecEvent> xmlSecEvents = getResponsibleXMLSecEvents(eventQueue, index);
         final List<QName> elementPath = getElementPath(eventQueue);
-        final XMLSecEvent responsibleXMLSecStartXMLEvent = getResponsibleStartXMLEvent(eventQueue, index);
 
-        final AbstractInboundSecurityToken securityContextToken =
-                new AbstractInboundSecurityToken(
-                        (WSSecurityContext) inputProcessorChain.getSecurityContext(),
-                        securityContextTokenType.getId(), null) {
-
-                    @Override
-                    public boolean isAsymmetric() {
-                        return false;
-                    }
-
-                    @Override
-                    public Key getKey(String algorithmURI, XMLSecurityConstants.KeyUsage keyUsage,
-                                      String correlationID) throws XMLSecurityException {
-
-                        Key key = getSecretKey().get(algorithmURI);
-                        if (key != null) {
-                            return key;
-                        }
-
-                        String algo = JCEAlgorithmMapper.translateURItoJCEID(algorithmURI);
-                        WSPasswordCallback passwordCallback = new WSPasswordCallback(identifier, WSPasswordCallback.Usage.SECURITY_CONTEXT_TOKEN);
-                        WSSUtils.doSecretKeyCallback(((WSSSecurityProperties)securityProperties).getCallbackHandler(), passwordCallback, null);
-                        if (passwordCallback.getKey() == null) {
-                            throw new WSSecurityException(WSSecurityException.ErrorCode.SECURITY_TOKEN_UNAVAILABLE, "noKey", securityContextTokenType.getId());
-                        }
-                        key = new SecretKeySpec(passwordCallback.getKey(), algo);
-                        setSecretKey(algorithmURI, key);
-                        return key;
-                    }
-
-                    @Override
-                    public WSSConstants.TokenType getTokenType() {
-                        //todo and set externalUriRef
-                        return WSSConstants.SecurityContextToken;
-                    }
-                };
+        final TokenContext tokenContext = new TokenContext(wssSecurityProperties, wsSecurityContext, xmlSecEvents, elementPath);
 
-        securityContextToken.setElementPath(elementPath);
-        securityContextToken.setXMLSecEvent(responsibleXMLSecStartXMLEvent);
+        SecurityContextTokenValidator securityContextTokenValidator = wssSecurityProperties.getValidator(elementName);
+        if (securityContextTokenValidator == null) {
+            securityContextTokenValidator = new SecurityContextTokenValidatorImpl();
+        }
+        final SecurityToken securityContextToken =
+                securityContextTokenValidator.validate(securityContextTokenType, identifier, tokenContext);
 
         SecurityTokenProvider securityTokenProvider = new SecurityTokenProvider() {
 
@@ -119,13 +88,7 @@ public class SecurityContextTokenInputHa
                 return securityContextTokenType.getId();
             }
         };
-        inputProcessorChain.getSecurityContext().registerSecurityTokenProvider(securityContextTokenType.getId(), securityTokenProvider);
-
-        //fire a tokenSecurityEvent
-        SecurityContextTokenSecurityEvent securityContextTokenSecurityEvent = new SecurityContextTokenSecurityEvent();
-        securityContextTokenSecurityEvent.setSecurityToken((SecurityToken) securityTokenProvider.getSecurityToken());
-        securityContextTokenSecurityEvent.setCorrelationID(securityContextTokenType.getId());
-        inputProcessorChain.getSecurityContext().registerSecurityEvent(securityContextTokenSecurityEvent);
+        wsSecurityContext.registerSecurityTokenProvider(securityContextTokenType.getId(), securityTokenProvider);
 
         //also register a SecurityProvider with the identifier. @see SecurityContexTest#testSCTKDKTSignAbsolute
         SecurityTokenProvider securityTokenProviderDirectReference = new SecurityTokenProvider() {
@@ -141,6 +104,12 @@ public class SecurityContextTokenInputHa
                 return identifier;
             }
         };
-        inputProcessorChain.getSecurityContext().registerSecurityTokenProvider(identifier, securityTokenProviderDirectReference);
+        wsSecurityContext.registerSecurityTokenProvider(identifier, securityTokenProviderDirectReference);
+
+        //fire a tokenSecurityEvent
+        SecurityContextTokenSecurityEvent securityContextTokenSecurityEvent = new SecurityContextTokenSecurityEvent();
+        securityContextTokenSecurityEvent.setSecurityToken((SecurityToken) securityTokenProvider.getSecurityToken());
+        securityContextTokenSecurityEvent.setCorrelationID(securityContextTokenType.getId());
+        wsSecurityContext.registerSecurityEvent(securityContextTokenSecurityEvent);
     }
 }

Modified: webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/TimestampInputHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/TimestampInputHandler.java?rev=1433975&r1=1433974&r2=1433975&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/TimestampInputHandler.java (original)
+++ webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/TimestampInputHandler.java Wed Jan 16 15:14:23 2013
@@ -18,8 +18,6 @@
  */
 package org.apache.ws.security.stax.impl.processor.input;
 
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
 import org.apache.ws.security.binding.wsu10.TimestampType;
 import org.apache.ws.security.common.bsp.BSPRule;
 import org.apache.ws.security.common.ext.WSSecurityException;
@@ -27,19 +25,24 @@ import org.apache.ws.security.stax.ext.W
 import org.apache.ws.security.stax.ext.WSSSecurityProperties;
 import org.apache.ws.security.stax.ext.WSSecurityContext;
 import org.apache.ws.security.stax.securityEvent.TimestampSecurityEvent;
+import org.apache.ws.security.stax.validate.TimestampValidator;
+import org.apache.ws.security.stax.validate.TimestampValidatorImpl;
+import org.apache.ws.security.stax.validate.TokenContext;
 import org.apache.xml.security.exceptions.XMLSecurityException;
-import org.apache.xml.security.stax.ext.*;
+import org.apache.xml.security.stax.ext.AbstractInputSecurityHeaderHandler;
+import org.apache.xml.security.stax.ext.InputProcessorChain;
+import org.apache.xml.security.stax.ext.XMLSecurityProperties;
+import org.apache.xml.security.stax.ext.XMLSecurityUtils;
 import org.apache.xml.security.stax.ext.stax.XMLSecEvent;
 import org.apache.xml.security.stax.impl.util.IDGenerator;
 
 import javax.xml.bind.JAXBElement;
 import javax.xml.datatype.DatatypeConstants;
 import javax.xml.datatype.XMLGregorianCalendar;
+import javax.xml.namespace.QName;
 import javax.xml.stream.XMLStreamConstants;
-import java.util.Calendar;
 import java.util.Deque;
-import java.util.GregorianCalendar;
-import java.util.Iterator;
+import java.util.List;
 
 /**
  * @author $Author$
@@ -47,141 +50,105 @@ import java.util.Iterator;
  */
 public class TimestampInputHandler extends AbstractInputSecurityHeaderHandler {
 
-    private static final transient Log log = LogFactory.getLog(TimestampInputHandler.class);
-
-    //Chapter 10 Security Timestamps: ...may only be present at most once per header (that is, per SOAP actor/role)
     @Override
     public void handle(final InputProcessorChain inputProcessorChain, final XMLSecurityProperties securityProperties,
                        Deque<XMLSecEvent> eventQueue, Integer index) throws XMLSecurityException {
 
         final WSSSecurityProperties wssSecurityProperties = (WSSSecurityProperties) securityProperties;
+        final WSSecurityContext wssecurityContext = (WSSecurityContext) inputProcessorChain.getSecurityContext();
 
-        Boolean alreadyProcessed = inputProcessorChain.getSecurityContext().<Boolean>get(WSSConstants.TIMESTAMP_PROCESSED);
+        //Chapter 10 Security Timestamps: ...may only be present at most once per header (that is, per SOAP actor/role)
+        Boolean alreadyProcessed = wssecurityContext.<Boolean>get(WSSConstants.TIMESTAMP_PROCESSED);
         if (Boolean.TRUE.equals(alreadyProcessed)) {
             throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY, "invalidTimestamp",
                     "Message contains two or more timestamps");
         }
-        inputProcessorChain.getSecurityContext().put(WSSConstants.TIMESTAMP_PROCESSED, Boolean.TRUE);
+        wssecurityContext.put(WSSConstants.TIMESTAMP_PROCESSED, Boolean.TRUE);
 
         @SuppressWarnings("unchecked")
         final TimestampType timestampType =
                 ((JAXBElement<TimestampType>) parseStructure(eventQueue, index, securityProperties)).getValue();
 
-        checkBSPCompliance(inputProcessorChain, timestampType, eventQueue, index);
+        final List<XMLSecEvent> xmlSecEvents = getResponsibleXMLSecEvents(eventQueue, index);
+        List<QName> elementPath = getElementPath(eventQueue);
+
+        checkBSPCompliance(inputProcessorChain, timestampType, xmlSecEvents);
 
-        if (timestampType.getCreated() == null) {
-            throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY, "missingCreated");
-        }
         if (timestampType.getId() == null) {
             timestampType.setId(IDGenerator.generateID(null));
         }
 
-        try {
-            // Validate whether the security semantics have expired
-            //created and expires is optional per spec. But we enforce the created element in the validation
-            Calendar crea = null;
-            if (timestampType.getCreated() != null) {
-                XMLGregorianCalendar created;
-                try {
-                    created = WSSConstants.datatypeFactory.newXMLGregorianCalendar(timestampType.getCreated().getValue());
-                } catch (IllegalArgumentException e) {
-                    throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY, e);
-                }
-                log.debug("Timestamp created: " + created);
-                crea = created.toGregorianCalendar();
-            }
-
-            Calendar exp = null;
-            if (timestampType.getExpires() != null) {
-                XMLGregorianCalendar expires;
-                try {
-                    expires = WSSConstants.datatypeFactory.newXMLGregorianCalendar(timestampType.getExpires().getValue());
-                } catch (IllegalArgumentException e) {
-                    throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY, e);
-                }
-                log.debug("Timestamp expires: " + expires);
-                exp = expires.toGregorianCalendar();
-            }
-
-            Calendar rightNow = Calendar.getInstance();
-            Calendar ttl = Calendar.getInstance();
-            ttl.add(Calendar.SECOND, -wssSecurityProperties.getTimestampTTL());
-
-            if (exp != null && wssSecurityProperties.isStrictTimestampCheck() && exp.before(rightNow)) {
-                log.debug("Time now: " + WSSConstants.datatypeFactory.newXMLGregorianCalendar(new GregorianCalendar()).toXMLFormat());
-                throw new WSSecurityException(WSSecurityException.ErrorCode.MESSAGE_EXPIRED, "invalidTimestamp",
-                        "The security semantics of the message have expired");
-            }
+        TimestampValidator timestampValidator = wssSecurityProperties.getValidator(WSSConstants.TAG_wsu_Timestamp);
+        if (timestampValidator == null) {
+            timestampValidator = new TimestampValidatorImpl();
+        }
+        TokenContext tokenContext = new TokenContext(wssSecurityProperties, wssecurityContext, xmlSecEvents, elementPath);
+        timestampValidator.validate(timestampType, tokenContext);
 
-            if (crea != null && wssSecurityProperties.isStrictTimestampCheck() && crea.before(ttl)) {
-                log.debug("Time now: " + WSSConstants.datatypeFactory.newXMLGregorianCalendar(new GregorianCalendar()).toXMLFormat());
-                throw new WSSecurityException(WSSecurityException.ErrorCode.MESSAGE_EXPIRED, "invalidTimestamp",
-                        "The security semantics of the message have expired");
+        TimestampSecurityEvent timestampSecurityEvent = new TimestampSecurityEvent();
+        if (timestampType.getCreated() != null) {
+            try {
+                timestampSecurityEvent.setCreated(
+                        timestampType.getCreated().getAsXMLGregorianCalendar().toGregorianCalendar());
+            } catch (IllegalArgumentException e) { //NOPMD
+                //ignore
             }
-
-            if (crea != null && crea.after(rightNow)) {
-                log.debug("Time now: " + WSSConstants.datatypeFactory.newXMLGregorianCalendar(new GregorianCalendar()).toXMLFormat());
-                throw new WSSecurityException(WSSecurityException.ErrorCode.MESSAGE_EXPIRED, "invalidTimestamp",
-                        "The security semantics of the message is invalid");
+        }
+        if (timestampType.getExpires() != null) {
+            try {
+                timestampSecurityEvent.setExpires(
+                        timestampType.getExpires().getAsXMLGregorianCalendar().toGregorianCalendar());
+            } catch (IllegalArgumentException e) { //NOPMD
+                //ignore
             }
-
-            TimestampSecurityEvent timestampSecurityEvent = new TimestampSecurityEvent();
-            timestampSecurityEvent.setCreated(crea);
-            timestampSecurityEvent.setExpires(exp);
-            timestampSecurityEvent.setCorrelationID(timestampType.getId());
-            inputProcessorChain.getSecurityContext().registerSecurityEvent(timestampSecurityEvent);
-            inputProcessorChain.getSecurityContext().put(WSSConstants.PROP_TIMESTAMP_SECURITYEVENT, timestampSecurityEvent);
-
-        } catch (IllegalArgumentException e) {
-            throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY, e);
         }
+        timestampSecurityEvent.setCorrelationID(timestampType.getId());
+        wssecurityContext.registerSecurityEvent(timestampSecurityEvent);
+        wssecurityContext.put(WSSConstants.PROP_TIMESTAMP_SECURITYEVENT, timestampSecurityEvent);
     }
 
     private void checkBSPCompliance(InputProcessorChain inputProcessorChain, TimestampType timestampType,
-                                    Deque<XMLSecEvent> eventDeque, int index) throws WSSecurityException {
+                                    List<XMLSecEvent> xmlSecEvents) throws WSSecurityException {
         final WSSecurityContext securityContext = (WSSecurityContext) inputProcessorChain.getSecurityContext();
         if (timestampType.getCreated() == null) {
             securityContext.handleBSPRule(BSPRule.R3203);
         }
 
-        Iterator<XMLSecEvent> xmlSecEventIterator = eventDeque.descendingIterator();
-        int curIdx = 0;
-        //forward to first timestamp child element
-        while (curIdx++ <= index) {
-            xmlSecEventIterator.next();
-        }
         int createdIndex = -1;
         int expiresIndex = -1;
-        while (xmlSecEventIterator.hasNext()) {
-            XMLSecEvent xmlSecEvent = xmlSecEventIterator.next();
+        for (int i = 0; i < xmlSecEvents.size(); i++) {
+            XMLSecEvent xmlSecEvent = xmlSecEvents.get(i);
             if (xmlSecEvent.getEventType() == XMLStreamConstants.START_ELEMENT) {
-                if (xmlSecEvent.asStartElement().getName().equals(WSSConstants.TAG_wsu_Created)) {
+                QName name = xmlSecEvent.asStartElement().getName();
+
+                if (name.equals(WSSConstants.TAG_wsu_Timestamp)) {
+                    continue;
+                } else if (name.equals(WSSConstants.TAG_wsu_Created)) {
                     if (createdIndex != -1) {
                         securityContext.handleBSPRule(BSPRule.R3203);
                     }
                     if (expiresIndex != -1) {
                         securityContext.handleBSPRule(BSPRule.R3221);
                     }
-                    createdIndex = curIdx;
-                } else if (xmlSecEvent.asStartElement().getName().equals(WSSConstants.TAG_wsu_Expires)) {
+                    createdIndex = i;
+                } else if (name.equals(WSSConstants.TAG_wsu_Expires)) {
                     if (expiresIndex != -1) {
                         securityContext.handleBSPRule(BSPRule.R3224);
                     }
                     if (createdIndex == -1) {
                         securityContext.handleBSPRule(BSPRule.R3221);
                     }
-                    expiresIndex = curIdx;
+                    expiresIndex = i;
                 } else {
                     securityContext.handleBSPRule(BSPRule.R3222);
                 }
             }
-            curIdx++;
         }
 
         if (timestampType.getCreated() != null) {
             XMLGregorianCalendar createdCalendar;
             try {
-                createdCalendar = WSSConstants.datatypeFactory.newXMLGregorianCalendar(timestampType.getCreated().getValue());
+                createdCalendar = timestampType.getCreated().getAsXMLGregorianCalendar();
             } catch (IllegalArgumentException e) {
                 throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY, e);
             }
@@ -205,7 +172,7 @@ public class TimestampInputHandler exten
         if (timestampType.getExpires() != null) {
             XMLGregorianCalendar expiresCalendar;
             try {
-                expiresCalendar = WSSConstants.datatypeFactory.newXMLGregorianCalendar(timestampType.getExpires().getValue());
+                expiresCalendar = timestampType.getExpires().getAsXMLGregorianCalendar();
             } catch (IllegalArgumentException e) {
                 throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY, e);
             }

Modified: webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/UsernameTokenInputHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/UsernameTokenInputHandler.java?rev=1433975&r1=1433974&r2=1433975&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/UsernameTokenInputHandler.java (original)
+++ webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/UsernameTokenInputHandler.java Wed Jan 16 15:14:23 2013
@@ -18,34 +18,31 @@
  */
 package org.apache.ws.security.stax.impl.processor.input;
 
-import org.apache.commons.codec.binary.Base64;
 import org.apache.jcs.JCS;
 import org.apache.jcs.access.exception.CacheException;
 import org.apache.jcs.engine.ElementAttributes;
-import org.apache.ws.security.binding.wss10.AttributedString;
 import org.apache.ws.security.binding.wss10.EncodedString;
 import org.apache.ws.security.binding.wss10.PasswordString;
 import org.apache.ws.security.binding.wss10.UsernameTokenType;
-import org.apache.ws.security.binding.wsu10.AttributedDateTime;
 import org.apache.ws.security.common.bsp.BSPRule;
-import org.apache.ws.security.common.ext.WSPasswordCallback;
 import org.apache.ws.security.common.ext.WSSecurityException;
 import org.apache.ws.security.stax.ext.WSSConstants;
 import org.apache.ws.security.stax.ext.WSSSecurityProperties;
-import org.apache.ws.security.stax.ext.WSSUtils;
 import org.apache.ws.security.stax.ext.WSSecurityContext;
-import org.apache.ws.security.stax.impl.securityToken.UsernameSecurityToken;
 import org.apache.ws.security.stax.securityEvent.UsernameTokenSecurityEvent;
+import org.apache.ws.security.stax.validate.TokenContext;
+import org.apache.ws.security.stax.validate.UsernameTokenValidator;
+import org.apache.ws.security.stax.validate.UsernameTokenValidatorImpl;
 import org.apache.xml.security.exceptions.XMLSecurityException;
 import org.apache.xml.security.stax.ext.*;
 import org.apache.xml.security.stax.ext.stax.XMLSecEvent;
 import org.apache.xml.security.stax.impl.util.IDGenerator;
 
 import javax.xml.bind.JAXBElement;
-import javax.xml.datatype.XMLGregorianCalendar;
 import javax.xml.namespace.QName;
 import javax.xml.stream.XMLStreamConstants;
-import java.util.*;
+import java.util.Deque;
+import java.util.List;
 
 /**
  * Processor for the UsernameToken XML Structure
@@ -74,53 +71,18 @@ public class UsernameTokenInputHandler e
         final UsernameTokenType usernameTokenType =
                 ((JAXBElement<UsernameTokenType>) parseStructure(eventQueue, index, securityProperties)).getValue();
 
-        checkBSPCompliance(inputProcessorChain, usernameTokenType, eventQueue, index);
+        final List<XMLSecEvent> xmlSecEvents = getResponsibleXMLSecEvents(eventQueue, index);
+
+        checkBSPCompliance(inputProcessorChain, usernameTokenType, xmlSecEvents);
 
         if (usernameTokenType.getId() == null) {
             usernameTokenType.setId(IDGenerator.generateID(null));
         }
 
-        // If the UsernameToken is to be used for key derivation, the (1.1)
-        // spec says that it cannot contain a password, and it must contain
-        // an Iteration element
-        final byte[] salt = XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_wsse11_Salt);
-        PasswordString passwordType = XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_wsse_Password);
-        final Long iteration = XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_wsse11_Iteration);
-        if (salt != null && (passwordType != null || iteration == null)) {
-            throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "badTokenType01");
-        }
-
-        boolean handleCustomPasswordTypes = false;
-        handleCustomPasswordTypes = ((WSSSecurityProperties) securityProperties).getHandleCustomPasswordTypes();
-
-        final byte[] nonceVal;
-        final String created;
-
-        WSSConstants.UsernameTokenPasswordType usernameTokenPasswordType = WSSConstants.UsernameTokenPasswordType.PASSWORD_NONE;
-        if (passwordType != null && passwordType.getType() != null) {
-            usernameTokenPasswordType = WSSConstants.UsernameTokenPasswordType.getUsernameTokenPasswordType(passwordType.getType());
-        }
-
-        final AttributedString username = usernameTokenType.getUsername();
-        if (username == null) {
-            throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "badTokenType01");
-        }
-        final EncodedString encodedNonce = XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_wsse_Nonce);
-        final AttributedDateTime attributedDateTimeCreated = XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_wsu_Created);
-
-        // TODO revisit this once we add in Validators
-        if (usernameTokenPasswordType == WSSConstants.UsernameTokenPasswordType.PASSWORD_DIGEST) {
-            if (encodedNonce == null || attributedDateTimeCreated == null) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "badTokenType01");
-            }
-
-            if (!WSSConstants.SOAPMESSAGE_NS10_BASE64_ENCODING.equals(encodedNonce.getEncodingType())) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.UNSUPPORTED_SECURITY_TOKEN, "badTokenType01");
-            }
+        final EncodedString encodedNonce =
+                XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_wsse_Nonce);
+        if (encodedNonce != null) {
             String nonce = encodedNonce.getValue();
-            nonceVal = Base64.decodeBase64(nonce);
-            created = attributedDateTimeCreated.getValue();
-
             /*
                 It is RECOMMENDED that used nonces be cached for a period at least as long as
                 the timestamp freshness limitation period, above, and that UsernameToken with
@@ -132,124 +94,32 @@ public class UsernameTokenInputHandler e
             ElementAttributes elementAttributes = new ElementAttributes();
             elementAttributes.setMaxLifeSeconds(300);
             try {
-                cache.put(nonce, created, elementAttributes);
+                cache.put(nonce, nonce, elementAttributes);
             } catch (CacheException e) {
                 throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY, e);
             }
+        }
 
-            XMLGregorianCalendar xmlGregorianCalendar;
-            try {
-                xmlGregorianCalendar = WSSConstants.datatypeFactory.newXMLGregorianCalendar(created);
-            } catch (IllegalArgumentException e) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
-            }
-            GregorianCalendar createdCal = xmlGregorianCalendar.toGregorianCalendar();
-            GregorianCalendar now = new GregorianCalendar();
-            if (createdCal.after(now)) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
-            }
-            now.add(Calendar.MINUTE, 5);
-            if (createdCal.after(now)) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
-            }
-
-            WSPasswordCallback pwCb = new WSPasswordCallback(username.getValue(),
-                    null,
-                    passwordType.getType(),
-                    WSPasswordCallback.Usage.USERNAME_TOKEN);
-            try {
-                WSSUtils.doPasswordCallback(((WSSSecurityProperties)securityProperties).getCallbackHandler(), pwCb);
-            } catch (WSSecurityException e) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION, e);
-            }
-
-            if (pwCb.getPassword() == null) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
-            }
-
-            String passDigest = WSSUtils.doPasswordDigest(nonceVal, created, pwCb.getPassword());
-            if (!passwordType.getValue().equals(passDigest)) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
-            }
-            passwordType.setValue(pwCb.getPassword());
-        } else if ((usernameTokenPasswordType == WSSConstants.UsernameTokenPasswordType.PASSWORD_TEXT)
-                || (passwordType != null && passwordType.getValue() != null
-                && usernameTokenPasswordType == WSSConstants.UsernameTokenPasswordType.PASSWORD_NONE)) {
-            nonceVal = null;
-            created = null;
-            WSPasswordCallback pwCb = new WSPasswordCallback(username.getValue(),
-                    null,
-                    passwordType.getType(),
-                    WSPasswordCallback.Usage.USERNAME_TOKEN);
-            try {
-                WSSUtils.doPasswordCallback(((WSSSecurityProperties)securityProperties).getCallbackHandler(), pwCb);
-            } catch (WSSecurityException e) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION, e);
-            }
-
-            if (pwCb.getPassword() == null) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
-            }
-
-            if (!passwordType.getValue().equals(pwCb.getPassword())) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
-            }
-            passwordType.setValue(pwCb.getPassword());
-        } else if (passwordType != null && passwordType.getValue() != null && usernameTokenPasswordType == null) {
-            if (!handleCustomPasswordTypes) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
-            }
-            nonceVal = null;
-            created = null;
-            WSPasswordCallback pwCb = new WSPasswordCallback(username.getValue(),
-                    null,
-                    passwordType.getType(),
-                    WSPasswordCallback.Usage.USERNAME_TOKEN);
-            try {
-                WSSUtils.doPasswordCallback(((WSSSecurityProperties)securityProperties).getCallbackHandler(), pwCb);
-            } catch (WSSecurityException e) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION, e);
-            }
-
-            if (pwCb.getPassword() == null) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
-            }
+        final WSSecurityContext wsSecurityContext = (WSSecurityContext) inputProcessorChain.getSecurityContext();
+        final WSSSecurityProperties wssSecurityProperties = (WSSSecurityProperties) securityProperties;
+        final List<QName> elementPath = getElementPath(eventQueue);
 
-            if (!passwordType.getValue().equals(pwCb.getPassword())) {
-                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
-            }
-            passwordType.setValue(pwCb.getPassword());
-        } else {
-            nonceVal = null;
-            created = null;
-        }
+        final TokenContext tokenContext = new TokenContext(wssSecurityProperties, wsSecurityContext, xmlSecEvents, elementPath);
 
-        final String password;
-        if (passwordType != null) {
-            password = passwordType.getValue();
-        } else {
-            password = null;
+        UsernameTokenValidator usernameTokenValidator =
+                wssSecurityProperties.getValidator(WSSConstants.TAG_wsse_UsernameToken);
+        if (usernameTokenValidator == null) {
+            usernameTokenValidator = new UsernameTokenValidatorImpl();
         }
-
-        final List<QName> elementPath = getElementPath(eventQueue);
-        final XMLSecEvent responsibleStartXMLEvent = getResponsibleStartXMLEvent(eventQueue, index);
+        final SecurityToken usernameSecurityToken =
+                usernameTokenValidator.validate(usernameTokenType, tokenContext);
 
         SecurityTokenProvider securityTokenProvider = new SecurityTokenProvider() {
 
-            private UsernameSecurityToken securityToken = null;
-
             @SuppressWarnings("unchecked")
             @Override
             public SecurityToken getSecurityToken() throws XMLSecurityException {
-                if (this.securityToken != null) {
-                    return this.securityToken;
-                }
-                this.securityToken = new UsernameSecurityToken(username.getValue(), password, created, nonceVal, salt, iteration,
-                        (WSSecurityContext) inputProcessorChain.getSecurityContext(), usernameTokenType.getId(),
-                        WSSConstants.WSSKeyIdentifierType.SECURITY_TOKEN_DIRECT_REFERENCE);
-                this.securityToken.setElementPath(elementPath);
-                this.securityToken.setXMLSecEvent(responsibleStartXMLEvent);
-                return this.securityToken;
+                return usernameSecurityToken;
             }
 
             @Override
@@ -259,6 +129,12 @@ public class UsernameTokenInputHandler e
         };
         inputProcessorChain.getSecurityContext().registerSecurityTokenProvider(usernameTokenType.getId(), securityTokenProvider);
 
+        PasswordString passwordType = XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_wsse_Password);
+        WSSConstants.UsernameTokenPasswordType usernameTokenPasswordType = WSSConstants.UsernameTokenPasswordType.PASSWORD_NONE;
+        if (passwordType != null && passwordType.getType() != null) {
+            usernameTokenPasswordType = WSSConstants.UsernameTokenPasswordType.getUsernameTokenPasswordType(passwordType.getType());
+        }
+
         //fire a tokenSecurityEvent
         UsernameTokenSecurityEvent usernameTokenSecurityEvent = new UsernameTokenSecurityEvent();
         usernameTokenSecurityEvent.setUsernameTokenPasswordType(usernameTokenPasswordType);
@@ -269,51 +145,48 @@ public class UsernameTokenInputHandler e
     }
 
     private void checkBSPCompliance(InputProcessorChain inputProcessorChain, UsernameTokenType usernameTokenType,
-                                    Deque<XMLSecEvent> eventDeque, int index) throws WSSecurityException {
+                                    List<XMLSecEvent> xmlSecEvents) throws WSSecurityException {
 
         final WSSecurityContext securityContext = (WSSecurityContext) inputProcessorChain.getSecurityContext();
         if (usernameTokenType.getAny() == null) {
             securityContext.handleBSPRule(BSPRule.R3031);
         }
 
-        Iterator<XMLSecEvent> xmlSecEventIterator = eventDeque.descendingIterator();
-        int curIdx = 0;
-        //forward to first Usernametoken child element
-        while (curIdx++ <= index) {
-            xmlSecEventIterator.next();
-        }
         int passwordIndex = -1;
         int createdIndex = -1;
         int nonceIndex = -1;
-        while (xmlSecEventIterator.hasNext()) {
-            XMLSecEvent xmlSecEvent = xmlSecEventIterator.next();
+        for (int i = 0; i < xmlSecEvents.size(); i++) {
+            XMLSecEvent xmlSecEvent = xmlSecEvents.get(i);
             if (xmlSecEvent.getEventType() == XMLStreamConstants.START_ELEMENT) {
-                if (xmlSecEvent.asStartElement().getName().equals(WSSConstants.TAG_wsse_Password)) {
+                if (xmlSecEvent.asStartElement().getName().equals(WSSConstants.TAG_wsse_UsernameToken)) {
+                    continue;
+                } else if (xmlSecEvent.asStartElement().getName().equals(WSSConstants.TAG_wsse_Password)) {
                     if (passwordIndex != -1) {
                         securityContext.handleBSPRule(BSPRule.R4222);
                     }
-                    passwordIndex = curIdx;
+                    passwordIndex = i;
                 } else if (xmlSecEvent.asStartElement().getName().equals(WSSConstants.TAG_wsu_Created)) {
                     if (createdIndex != -1) {
                         securityContext.handleBSPRule(BSPRule.R4223);
                     }
-                    createdIndex = curIdx;
+                    createdIndex = i;
                 } else if (xmlSecEvent.asStartElement().getName().equals(WSSConstants.TAG_wsse_Nonce)) {
                     if (nonceIndex != -1) {
                         securityContext.handleBSPRule(BSPRule.R4225);
                     }
-                    nonceIndex = curIdx;
+                    nonceIndex = i;
                 }
             }
-            curIdx++;
         }
 
-        PasswordString passwordType = XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_wsse_Password);
+        PasswordString passwordType =
+                XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_wsse_Password);
         if (passwordType != null && passwordType.getType() == null) {
             securityContext.handleBSPRule(BSPRule.R4201);
         }
 
-        EncodedString encodedNonce = XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_wsse_Nonce);
+        EncodedString encodedNonce =
+                XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_wsse_Nonce);
         if (encodedNonce != null) {
             if (encodedNonce.getEncodingType() == null) {
                 securityContext.handleBSPRule(BSPRule.R4220);

Modified: webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/WSSSignatureInputHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/WSSSignatureInputHandler.java?rev=1433975&r1=1433974&r2=1433975&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/WSSSignatureInputHandler.java (original)
+++ webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/WSSSignatureInputHandler.java Wed Jan 16 15:14:23 2013
@@ -21,15 +21,17 @@ package org.apache.ws.security.stax.impl
 import org.apache.ws.security.binding.wss10.SecurityTokenReferenceType;
 import org.apache.ws.security.common.bsp.BSPRule;
 import org.apache.ws.security.common.ext.WSSecurityException;
+import org.apache.ws.security.stax.ext.WSSConstants;
+import org.apache.ws.security.stax.ext.WSSSecurityProperties;
+import org.apache.ws.security.stax.ext.WSSUtils;
+import org.apache.ws.security.stax.ext.WSSecurityContext;
+import org.apache.ws.security.stax.validate.SignatureTokenValidator;
+import org.apache.ws.security.stax.validate.SignatureTokenValidatorImpl;
 import org.apache.xml.security.binding.excc14n.InclusiveNamespaces;
 import org.apache.xml.security.binding.xmldsig.CanonicalizationMethodType;
-import org.apache.xml.security.binding.xmldsig.KeyInfoType;
 import org.apache.xml.security.binding.xmldsig.ManifestType;
 import org.apache.xml.security.binding.xmldsig.ObjectType;
 import org.apache.xml.security.binding.xmldsig.SignatureType;
-import org.apache.ws.security.stax.ext.WSSConstants;
-import org.apache.ws.security.stax.ext.WSSUtils;
-import org.apache.ws.security.stax.ext.WSSecurityContext;
 import org.apache.xml.security.exceptions.XMLSecurityException;
 import org.apache.xml.security.stax.ext.*;
 import org.apache.xml.security.stax.ext.stax.XMLSecEvent;
@@ -85,22 +87,7 @@ public class WSSSignatureInputHandler ex
         algorithmSuiteSecurityEvent.setCorrelationID(signatureType.getId());
         securityContext.registerSecurityEvent(algorithmSuiteSecurityEvent);
 
-        final SignatureVerifier signatureVerifier =
-                new WSSSignatureVerifier(signatureType, inputProcessorChain.getSecurityContext(), securityProperties) {
-
-                    @Override
-                    protected void handleSecurityToken(SecurityToken securityToken) throws XMLSecurityException {
-                        //todo element path?
-                        //we have to emit a TokenSecurityEvent here too since it could be an embedded token
-                        securityToken.addTokenUsage(SecurityToken.TokenUsage.Signature);
-                        TokenSecurityEvent tokenSecurityEvent = WSSUtils.createTokenSecurityEvent(securityToken, signatureType.getId());
-                        securityContext.registerSecurityEvent(tokenSecurityEvent);
-
-                        super.handleSecurityToken(securityToken);
-                    }
-        };
-
-        return signatureVerifier;
+        return new WSSSignatureVerifier(signatureType, inputProcessorChain.getSecurityContext(), securityProperties);
     }
 
     private void checkBSPCompliance(InputProcessorChain inputProcessorChain, SignatureType signatureType) throws WSSecurityException {
@@ -165,21 +152,37 @@ public class WSSSignatureInputHandler ex
             throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, e);
         }
     }
-    
+
     public class WSSSignatureVerifier extends SignatureVerifier {
-        
+
         public WSSSignatureVerifier(SignatureType signatureType, SecurityContext securityContext,
                                     XMLSecurityProperties securityProperties) throws XMLSecurityException {
             super(signatureType, securityContext, securityProperties);
         }
 
         @Override
-        protected SecurityToken retrieveSecurityToken(KeyInfoType keyInfoType,
+        protected SecurityToken retrieveSecurityToken(SignatureType signatureType,
                                                       XMLSecurityProperties securityProperties,
                                                       SecurityContext securityContext) throws XMLSecurityException {
-            return SecurityTokenFactory.getInstance().getSecurityToken(keyInfoType, SecurityToken.KeyInfoUsage.SIGNATURE_VERIFICATION,
-                                                                securityProperties, securityContext);
-            
+
+            SecurityToken securityToken = SecurityTokenFactory.getInstance().getSecurityToken(
+                    signatureType.getKeyInfo(), SecurityToken.KeyInfoUsage.SIGNATURE_VERIFICATION,
+                    securityProperties, securityContext);
+
+            SignatureTokenValidator signatureTokenValidator = ((WSSSecurityProperties) securityProperties).getValidator(WSSConstants.TAG_dsig_Signature);
+            if (signatureTokenValidator == null) {
+                signatureTokenValidator = new SignatureTokenValidatorImpl();
+            }
+            signatureTokenValidator.validate(securityToken, (WSSSecurityProperties) securityProperties);
+
+            //todo element path?
+            //we have to emit a TokenSecurityEvent here too since it could be an embedded token
+            securityToken.addTokenUsage(SecurityToken.TokenUsage.Signature);
+            TokenSecurityEvent tokenSecurityEvent = WSSUtils.createTokenSecurityEvent(securityToken, signatureType.getId());
+            securityContext.registerSecurityEvent(tokenSecurityEvent);
+
+            return securityToken;
+
         }
     }
 }

Modified: webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/securityToken/KerberosServiceSecurityToken.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/securityToken/KerberosServiceSecurityToken.java?rev=1433975&r1=1433974&r2=1433975&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/securityToken/KerberosServiceSecurityToken.java (original)
+++ webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/securityToken/KerberosServiceSecurityToken.java Wed Jan 16 15:14:23 2013
@@ -73,7 +73,7 @@ public class KerberosServiceSecurityToke
         return WSSConstants.KerberosToken;
     }
 
-    private KerberosTokenDecoder getTGT() throws WSSecurityException {
+    protected KerberosTokenDecoder getTGT() throws WSSecurityException {
         try {
             KerberosContextAndServiceNameCallback contextAndServiceNameCallback = new KerberosContextAndServiceNameCallback();
             callbackHandler.handle(new Callback[]{contextAndServiceNameCallback});

Modified: webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/securityToken/X509SecurityToken.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/securityToken/X509SecurityToken.java?rev=1433975&r1=1433974&r2=1433975&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/securityToken/X509SecurityToken.java (original)
+++ webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/securityToken/X509SecurityToken.java Wed Jan 16 15:14:23 2013
@@ -82,6 +82,7 @@ public abstract class X509SecurityToken 
 
     @Override
     public void verify() throws XMLSecurityException {
+        //todo overall call verify on wrapping tokens for non top-level SecurityTokens!?
         try {
             X509Certificate[] x509Certificates = getX509Certificates();
             if (x509Certificates != null && x509Certificates.length > 0) {