You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ws.apache.org by co...@apache.org on 2013/02/27 21:00:34 UTC

svn commit: r1450941 - in /webservices/wss4j/trunk: ws-security-common/src/main/java/org/apache/wss4j/common/util/ ws-security-dom/src/main/java/org/apache/wss4j/dom/ ws-security-dom/src/main/java/org/apache/wss4j/dom/action/ ws-security-dom/src/main/j...

Author: coheigea
Date: Wed Feb 27 20:00:34 2013
New Revision: 1450941

URL: http://svn.apache.org/r1450941
Log:
[WSS-427] - Add support for processing UsernameToken Created Dates
 - For DOM

Added:
    webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/util/DateUtil.java
Modified:
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/WSSConfig.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/action/TimestampAction.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/WSHandler.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/WSHandlerConstants.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/token/Timestamp.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/token/UsernameToken.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/UsernameTokenProcessor.java
    webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/wss4j/dom/message/UsernameTokenTest.java

Added: webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/util/DateUtil.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/util/DateUtil.java?rev=1450941&view=auto
==============================================================================
--- webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/util/DateUtil.java (added)
+++ webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/util/DateUtil.java Wed Feb 27 20:00:34 2013
@@ -0,0 +1,76 @@
+/**
+ * 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.wss4j.common.util;
+
+import java.util.Date;
+
+public final class DateUtil {
+    private static org.apache.commons.logging.Log LOG =
+            org.apache.commons.logging.LogFactory.getLog(DateUtil.class);
+
+    /**
+     * Return true if the "Created" value is before the current time minus the timeToLive
+     * argument, and if the Created value is not "in the future".
+     * 
+     * @param timeToLive the value in seconds for the validity of the Created time
+     * @param futureTimeToLive the value in seconds for the future validity of the Created time
+     * @return true if the Date is before (now-timeToLive), false otherwise
+     */
+    public static boolean verifyCreated(
+        Date createdDate,
+        int timeToLive,
+        int futureTimeToLive
+    ) {
+        if (createdDate == null) {
+            return true;
+        }
+        
+        Date validCreation = new Date();
+        long currentTime = validCreation.getTime();
+        if (futureTimeToLive > 0) {
+            validCreation.setTime(currentTime + ((long)futureTimeToLive * 1000L));
+        }
+        // Check to see if the created time is in the future
+        if (createdDate.after(validCreation)) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Validation of Created: The message was created in the future!");
+            }
+            return false;
+        }
+        
+        // Calculate the time that is allowed for the message to travel
+        currentTime -= ((long)timeToLive * 1000L);
+        validCreation.setTime(currentTime);
+
+        // Validate the time it took the message to travel
+        if (createdDate.before(validCreation)) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Validation of Created: The message was created too long ago");
+            }
+            return false;
+        }
+
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Validation of Created: Everything is ok");
+        }
+        return true;
+    }
+    
+}

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/WSSConfig.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/WSSConfig.java?rev=1450941&r1=1450940&r2=1450941&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/WSSConfig.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/WSSConfig.java Wed Feb 27 20:00:34 2013
@@ -267,6 +267,18 @@ public class WSSConfig {
     protected int timeStampFutureTTL = 60;
     
     /**
+     * The time in seconds between creation and expiry for a UsernameToken Created
+     * element. The default is 300 seconds (5 minutes).
+     */
+    protected int utTTL = 300;
+    
+    /**
+     * The time in seconds in the future within which the Created time of an incoming 
+     * UsernameToken is valid. The default is 60 seconds.
+     */
+    protected int utFutureTTL = 60;
+    
+    /**
      * This variable controls whether types other than PasswordDigest or PasswordText
      * are allowed when processing UsernameTokens. 
      * 
@@ -743,5 +755,21 @@ public class WSSConfig {
     public void setAllowUsernameTokenNoPassword(boolean allowUsernameTokenNoPassword) {
         this.allowUsernameTokenNoPassword = allowUsernameTokenNoPassword;
     }
+
+    public int getUtTTL() {
+        return utTTL;
+    }
+
+    public void setUtTTL(int utTTL) {
+        this.utTTL = utTTL;
+    }
+
+    public int getUtFutureTTL() {
+        return utFutureTTL;
+    }
+
+    public void setUtFutureTTL(int utFutureTTL) {
+        this.utFutureTTL = utFutureTTL;
+    }
     
 }

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/action/TimestampAction.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/action/TimestampAction.java?rev=1450941&r1=1450940&r2=1450941&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/action/TimestampAction.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/action/TimestampAction.java Wed Feb 27 20:00:34 2013
@@ -33,7 +33,7 @@ public class TimestampAction implements 
         // add the Timestamp to the SOAP Envelope
         //
         WSSecTimestamp timeStampBuilder = new WSSecTimestamp(reqData.getWssConfig());
-        timeStampBuilder.setTimeToLive(handler.decodeTimeToLive(reqData));
+        timeStampBuilder.setTimeToLive(handler.decodeTimeToLive(reqData, true));
         timeStampBuilder.build(doc, reqData.getSecHeader());
     }
 }

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/WSHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/WSHandler.java?rev=1450941&r1=1450940&r2=1450941&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/WSHandler.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/WSHandler.java Wed Feb 27 20:00:34 2013
@@ -286,8 +286,11 @@ public abstract class WSHandler {
             String passwordType = decodePasswordType(reqData);
             wssConfig.setRequiredPasswordType(passwordType);
         }
-        wssConfig.setTimeStampTTL(decodeTimeToLive(reqData));
-        wssConfig.setTimeStampFutureTTL(decodeFutureTimeToLive(reqData));
+        wssConfig.setTimeStampTTL(decodeTimeToLive(reqData, true));
+        wssConfig.setTimeStampFutureTTL(decodeFutureTimeToLive(reqData, true));
+        wssConfig.setUtTTL(decodeTimeToLive(reqData, false));
+        wssConfig.setUtFutureTTL(decodeFutureTimeToLive(reqData, false));
+        
         wssConfig.setHandleCustomPasswordTypes(decodeCustomPasswordTypes(reqData));
         wssConfig.setPasswordsAreEncoded(decodeUseEncodedPasswords(reqData));
         wssConfig.setAllowNamespaceQualifiedPasswordTypes(
@@ -645,26 +648,41 @@ public abstract class WSHandler {
         }
     }
 
-    public int decodeTimeToLive(RequestData reqData) {
-        String ttl = 
-            getString(WSHandlerConstants.TTL_TIMESTAMP, reqData.getMsgContext());
-        int ttlI = 0;
+    /**
+     * Decode the TimeToLive parameter for either a Timestamp or a UsernameToken Created element,
+     * depending on the boolean argument
+     */
+    public int decodeTimeToLive(RequestData reqData, boolean timestamp) {
+        String tag = WSHandlerConstants.TTL_TIMESTAMP;
+        if (!timestamp) {
+            tag = WSHandlerConstants.TTL_USERNAMETOKEN;
+        }
+        String ttl = getString(tag, reqData.getMsgContext());
+        int defaultTimeToLive = 300;
         if (ttl != null) {
             try {
-                ttlI = Integer.parseInt(ttl);
+                int ttlI = Integer.parseInt(ttl);
+                if (ttlI < 0) {
+                    return defaultTimeToLive;
+                }
+                return ttlI;
             } catch (NumberFormatException e) {
-                ttlI = reqData.getTimeToLive();
+                return defaultTimeToLive;
             }
         }
-        if (ttlI <= 0) {
-            ttlI = reqData.getTimeToLive();
-        }
-        return ttlI;
+        return defaultTimeToLive;
     }
     
-    protected int decodeFutureTimeToLive(RequestData reqData) {
-        String ttl = 
-            getString(WSHandlerConstants.TTL_FUTURE_TIMESTAMP, reqData.getMsgContext());
+    /**
+     * Decode the FutureTimeToLive parameter for either a Timestamp or a UsernameToken Created 
+     * element, depending on the boolean argument
+     */
+    protected int decodeFutureTimeToLive(RequestData reqData, boolean timestamp) {
+        String tag = WSHandlerConstants.TTL_FUTURE_TIMESTAMP;
+        if (!timestamp) {
+            tag = WSHandlerConstants.TTL_FUTURE_USERNAMETOKEN;
+        }
+        String ttl = getString(tag, reqData.getMsgContext());
         int defaultFutureTimeToLive = 60;
         if (ttl != null) {
             try {

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/WSHandlerConstants.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/WSHandlerConstants.java?rev=1450941&r1=1450940&r2=1450941&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/WSHandlerConstants.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/WSHandlerConstants.java Wed Feb 27 20:00:34 2013
@@ -713,22 +713,22 @@ public final class WSHandlerConstants {
 
     /**
      * Time-To-Live is the time difference between creation and expiry time in
-     * seconds in the WSS Timestamp. After this time the SOAP request is
-     * invalid (at least the security data shall be treated this way).
+     * seconds of the UsernameToken Created value. After this time the SOAP request 
+     * is invalid (at least the security data shall be treated this way).
      * <p/>
      * If this parameter is not defined, contains a value less or equal
      * zero, or an illegal format the handlers use a default TTL of
      * 300 seconds (5 minutes).
      */
-    public static final String TTL_TIMESTAMP = "timeToLive";
+    public static final String TTL_USERNAMETOKEN = "utTimeToLive";
     
     /**
      * This configuration tag specifies the time in seconds in the future within which
-     * the Created time of an incoming Timestamp is valid. The default value is "60",
+     * the Created time of an incoming UsernameToken is valid. The default value is "60",
      * to avoid problems where clocks are slightly askew. To reject all future-created
-     * Timestamps, set this value to "0". 
+     * UsernameTokens, set this value to "0". 
      */
-    public static final String TTL_FUTURE_TIMESTAMP = "futureTimeToLive";
+    public static final String TTL_FUTURE_USERNAMETOKEN = "utFutureTimeToLive";
     
     /**
      * This configuration tag is a comma separated String of regular expressions which
@@ -739,6 +739,25 @@ public final class WSHandlerConstants {
      */
     public static final String SIG_SUBJECT_CERT_CONSTRAINTS = "sigSubjectCertConstraints";
     
+    /**
+     * Time-To-Live is the time difference between creation and expiry time in
+     * seconds in the WSS Timestamp. After this time the SOAP request is
+     * invalid (at least the security data shall be treated this way).
+     * <p/>
+     * If this parameter is not defined, contains a value less or equal
+     * zero, or an illegal format the handlers use a default TTL of
+     * 300 seconds (5 minutes).
+     */
+    public static final String TTL_TIMESTAMP = "timeToLive";
+    
+    /**
+     * This configuration tag specifies the time in seconds in the future within which
+     * the Created time of an incoming Timestamp is valid. The default value is "60",
+     * to avoid problems where clocks are slightly askew. To reject all future-created
+     * Timestamps, set this value to "0". 
+     */
+    public static final String TTL_FUTURE_TIMESTAMP = "futureTimeToLive";
+    
     
     //
     // Internal storage constants

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/token/Timestamp.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/token/Timestamp.java?rev=1450941&r1=1450940&r2=1450941&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/token/Timestamp.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/token/Timestamp.java Wed Feb 27 20:00:34 2013
@@ -32,6 +32,7 @@ import javax.xml.datatype.XMLGregorianCa
 import org.apache.wss4j.common.bsp.BSPRule;
 import org.apache.wss4j.common.ext.WSSecurityException;
 import org.apache.wss4j.common.util.DOM2Writer;
+import org.apache.wss4j.common.util.DateUtil;
 import org.apache.wss4j.dom.WSConstants;
 import org.apache.wss4j.dom.WSSConfig;
 import org.apache.wss4j.dom.bsp.BSPEnforcer;
@@ -50,9 +51,6 @@ import org.w3c.dom.Text;
  */
 public class Timestamp {
     
-    private static final org.apache.commons.logging.Log LOG = 
-        org.apache.commons.logging.LogFactory.getLog(Timestamp.class);
-
     private Element element = null;
     private List<Element> customElements = null;
     private Date createdDate;
@@ -310,35 +308,7 @@ public class Timestamp {
         int timeToLive,
         int futureTimeToLive
     ) {
-        Date validCreation = new Date();
-        long currentTime = validCreation.getTime();
-        if (futureTimeToLive > 0) {
-            validCreation.setTime(currentTime + ((long)futureTimeToLive * 1000L));
-        }
-        // Check to see if the created time is in the future
-        if (createdDate != null && createdDate.after(validCreation)) {
-            if (LOG.isDebugEnabled()) {
-                LOG.debug("Validation of Timestamp: The message was created in the future!");
-            }
-            return false;
-        }
-        
-        // Calculate the time that is allowed for the message to travel
-        currentTime -= ((long)timeToLive * 1000L);
-        validCreation.setTime(currentTime);
-
-        // Validate the time it took the message to travel
-        if (createdDate != null && createdDate.before(validCreation)) {
-            if (LOG.isDebugEnabled()) {
-                LOG.debug("Validation of Timestamp: The message was created too long ago");
-            }
-            return false;
-        }
-
-        if (LOG.isDebugEnabled()) {
-            LOG.debug("Validation of Timestamp: Everything is ok");
-        }
-        return true;
+        return DateUtil.verifyCreated(createdDate, timeToLive, futureTimeToLive);
     }
 
     

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/token/UsernameToken.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/token/UsernameToken.java?rev=1450941&r1=1450940&r2=1450941&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/token/UsernameToken.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/token/UsernameToken.java Wed Feb 27 20:00:34 2013
@@ -24,11 +24,13 @@ import org.apache.wss4j.common.derivedKe
 import org.apache.wss4j.common.derivedKey.ConversationException;
 import org.apache.wss4j.common.derivedKey.DerivationAlgorithm;
 import org.apache.wss4j.dom.WSConstants;
+import org.apache.wss4j.dom.WSSConfig;
 import org.apache.wss4j.dom.WSUsernameTokenPrincipal;
 import org.apache.wss4j.common.bsp.BSPRule;
 import org.apache.wss4j.common.ext.WSPasswordCallback;
 import org.apache.wss4j.common.ext.WSSecurityException;
 import org.apache.wss4j.common.util.DOM2Writer;
+import org.apache.wss4j.common.util.DateUtil;
 import org.apache.wss4j.dom.bsp.BSPEnforcer;
 import org.apache.wss4j.dom.handler.RequestData;
 import org.apache.wss4j.dom.util.WSSecurityUtil;
@@ -42,6 +44,7 @@ import org.w3c.dom.Text;
 
 import javax.security.auth.callback.Callback;
 import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.xml.datatype.XMLGregorianCalendar;
 import javax.xml.namespace.QName;
 
 import java.io.IOException;
@@ -87,6 +90,7 @@ public class UsernameToken {
     private boolean hashed = true;
     private String rawPassword;        // enhancement by Alberto Coletti
     private boolean passwordsAreEncoded = false;
+    private Date createdDate;
     
     /**
      * Constructs a <code>UsernameToken</code> object and parses the
@@ -211,6 +215,24 @@ public class UsernameToken {
                 );
             }
         }
+        
+        if (elementCreated != null) {
+            String createdString = getCreated();
+            if (createdString != null && !"".equals(createdString)) {
+                XMLGregorianCalendar createdCalendar = null;
+                try {
+                    createdCalendar = 
+                        WSSConfig.datatypeFactory.newXMLGregorianCalendar(createdString);
+                } catch (IllegalArgumentException e) {
+                    throw new WSSecurityException(
+                        WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN,
+                        "badUsernameToken",
+                        "Error parsing UsernameToken Created value"
+                    );
+                }
+                createdDate = createdCalendar.toGregorianCalendar().getTime();
+            }
+        }
     }
 
     /**
@@ -396,6 +418,14 @@ public class UsernameToken {
     public String getCreated() {
         return nodeString(elementCreated);
     }
+    
+    /**
+     * Return the Created Element as a Date object
+     * @return the Created Date
+     */
+    public Date getCreatedDate() {
+       return createdDate;
+    }
 
     /**
      * Gets the password string. This is the password as it is in the password
@@ -899,6 +929,21 @@ public class UsernameToken {
     }
     
     /**
+     * Return true if the "Created" value is before the current time minus the timeToLive
+     * argument, and if the Created value is not "in the future".
+     * 
+     * @param timeToLive the value in seconds for the validity of the Created time
+     * @param futureTimeToLive the value in seconds for the future validity of the Created time
+     * @return true if the UsernameToken is before (now-timeToLive), false otherwise
+     */
+    public boolean verifyCreated(
+        int timeToLive,
+        int futureTimeToLive
+    ) {
+        return DateUtil.verifyCreated(createdDate, timeToLive, futureTimeToLive);
+    }
+    
+    /**
      * This static method generates a 128 bit salt value as defined in WSS
      * Username Token Profile.
      * 

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/UsernameTokenProcessor.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/UsernameTokenProcessor.java?rev=1450941&r1=1450940&r2=1450941&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/UsernameTokenProcessor.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/UsernameTokenProcessor.java Wed Feb 27 20:00:34 2013
@@ -19,6 +19,7 @@
 
 package org.apache.wss4j.dom.processor;
 
+import java.util.Date;
 import java.util.List;
 
 import org.apache.wss4j.common.ext.WSSecurityException;
@@ -113,7 +114,7 @@ public class UsernameTokenProcessor impl
      * @return a Credential object corresponding to the (validated) Username Token
      * @throws WSSecurityException
      */
-    public Credential 
+    private Credential 
     handleUsernameToken(
         Element token, 
         Validator validator,
@@ -121,17 +122,20 @@ public class UsernameTokenProcessor impl
     ) throws WSSecurityException {
         boolean allowNamespaceQualifiedPasswordTypes = false;
         WSSConfig wssConfig = data.getWssConfig();
+        int utTTL = 300;
+        int futureTimeToLive = 60;
         if (wssConfig != null) {
             allowNamespaceQualifiedPasswordTypes = 
                 wssConfig.getAllowNamespaceQualifiedPasswordTypes();
+            utTTL = wssConfig.getUtTTL();
+            futureTimeToLive = wssConfig.getUtFutureTTL();
         }
         
         //
         // Parse and validate the UsernameToken element
         //
         UsernameToken ut = 
-            new UsernameToken(token, allowNamespaceQualifiedPasswordTypes, 
-                    data.getBSPEnforcer());
+            new UsernameToken(token, allowNamespaceQualifiedPasswordTypes, data.getBSPEnforcer());
         
         // Test for replay attacks
         ReplayCache replayCache = data.getNonceReplayCache();
@@ -143,7 +147,21 @@ public class UsernameTokenProcessor impl
                     "A replay attack has been detected"
                 );
             }
-            replayCache.add(ut.getNonce());
+            
+            // If no Created, then just cache for the default time
+            // Otherwise, cache for the configured TTL of the UsernameToken Created time, as any
+            // older token will just get rejected anyway
+            Date created = ut.getCreatedDate();
+            if (created == null || utTTL <= 0) {
+                replayCache.add(ut.getNonce());
+            } else {
+                replayCache.add(ut.getNonce(), utTTL + 1L);
+            }
+        }
+        
+        // Validate whether the security semantics have expired
+        if (!ut.verifyCreated(utTTL, futureTimeToLive)) {
+            throw new WSSecurityException(WSSecurityException.ErrorCode.MESSAGE_EXPIRED);
         }
         
         Credential credential = new Credential();

Modified: webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/wss4j/dom/message/UsernameTokenTest.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/wss4j/dom/message/UsernameTokenTest.java?rev=1450941&r1=1450940&r2=1450941&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/wss4j/dom/message/UsernameTokenTest.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/wss4j/dom/message/UsernameTokenTest.java Wed Feb 27 20:00:34 2013
@@ -36,15 +36,19 @@ import org.apache.wss4j.dom.handler.Requ
 import org.apache.wss4j.dom.handler.WSHandlerConstants;
 import org.apache.wss4j.dom.message.token.UsernameToken;
 import org.apache.wss4j.dom.util.WSSecurityUtil;
+import org.apache.wss4j.dom.util.XmlSchemaDateFormat;
 import org.apache.xml.security.utils.Base64;
 import org.w3c.dom.Document;
+import org.w3c.dom.Element;
 
 import javax.security.auth.callback.Callback;
 import javax.security.auth.callback.CallbackHandler;
 import javax.security.auth.callback.UnsupportedCallbackException;
 import java.io.IOException;
 import java.security.MessageDigest;
+import java.text.DateFormat;
 import java.util.Collections;
+import java.util.Date;
 import java.util.List;
 
 /**
@@ -245,7 +249,161 @@ public class UsernameTokenTest extends o
             // expected
         }
     }
+    
+    /**
+     * This is a test for processing an "old" UsernameToken, i.e. one with a "Created" element that is
+     * out of date
+     */
+    @org.junit.Test
+    public void testOldUsernameToken() throws Exception {
+        WSSecUsernameToken builder = new WSSecUsernameToken();
+        builder.setUserInfo("wernerd", "verySecret");
+        Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+        WSSecHeader secHeader = new WSSecHeader();
+        secHeader.insertSecurityHeader(doc);
+        Document signedDoc = builder.build(doc, secHeader);
+
+        if (LOG.isDebugEnabled()) {
+            String outputString = 
+                XMLUtils.PrettyDocumentToString(signedDoc);
+            LOG.debug(outputString);
+        }
+        
+        WSSecurityEngine secEngine = new WSSecurityEngine();
+        WSSConfig config = WSSConfig.getNewInstance();
+        config.setUtTTL(-1);
+        secEngine.setWssConfig(config);
+        
+        try {
+            secEngine.processSecurityHeader(doc, null, callbackHandler, null);
+            fail("The UsernameToken validation should have failed");
+        } catch (WSSecurityException ex) {
+            assertTrue(ex.getErrorCode() == WSSecurityException.ErrorCode.MESSAGE_EXPIRED); 
+        }  
+    }
+
+    /** 
+     * This is a test for processing a UsernameToken where the "Created" element is in the (near)
+     * future. It should be accepted by default when it is created 30 seconds in the future, 
+     * and then rejected once we configure "0 seconds" for future-time-to-live.
+     */
+    @org.junit.Test
+    public void testNearFutureCreated() throws Exception {
+        Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+        WSSecHeader secHeader = new WSSecHeader();
+        secHeader.insertSecurityHeader(doc);
+        
+        Element usernameTokenElement = 
+            doc.createElementNS(
+                WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX + ":" + WSConstants.USERNAME_TOKEN_LN
+            );
+        Element usernameElement = 
+            doc.createElementNS(
+                WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX + ":" + WSConstants.USERNAME_LN
+            );
+        usernameElement.appendChild(doc.createTextNode("wernerd"));
+        usernameTokenElement.appendChild(usernameElement);
+        
+        Element passwordElement = 
+            doc.createElementNS(
+                WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX + ":" + WSConstants.PASSWORD_LN
+            );
+        passwordElement.setAttributeNS(null, "Type", WSConstants.PASSWORD_TEXT);
+        passwordElement.appendChild(doc.createTextNode("verySecret"));
+        usernameTokenElement.appendChild(passwordElement);
+
+        Element elementCreated =
+            doc.createElementNS(
+                WSConstants.WSU_NS, WSConstants.WSU_PREFIX + ":" + WSConstants.CREATED_LN
+            );
+        DateFormat zulu = new XmlSchemaDateFormat();
+        Date createdDate = new Date();
+        long currentTime = createdDate.getTime() + 30000;
+        createdDate.setTime(currentTime);
+        elementCreated.appendChild(doc.createTextNode(zulu.format(createdDate)));
+        usernameTokenElement.appendChild(elementCreated);
+
+        secHeader.getSecurityHeader().appendChild(usernameTokenElement);
+        
+        if (LOG.isDebugEnabled()) {
+            String outputString = 
+                XMLUtils.PrettyDocumentToString(doc);
+            LOG.debug(outputString);
+        }
+        
+        // This should work
+        WSSecurityEngine secEngine = new WSSecurityEngine();
+        secEngine.processSecurityHeader(doc, null, callbackHandler, null);
+        
+        // This should not
+        try {
+            WSSConfig config = WSSConfig.getNewInstance();
+            config.setUtFutureTTL(0);
+            secEngine.setWssConfig(config);
+            secEngine.processSecurityHeader(doc, null, callbackHandler, null);
+            fail("The UsernameToken validation should have failed");
+        } catch (WSSecurityException ex) {
+            assertTrue(ex.getErrorCode() == WSSecurityException.ErrorCode.MESSAGE_EXPIRED); 
+        }  
+    }
+    
+    /** 
+     * This is a test for processing a UsernameToken where the "Created" element is in the future.
+     * A UsernameToken that is 120 seconds in the future should be rejected by default.
+     */
+    @org.junit.Test
+    public void testFutureCreated() throws Exception {
+        Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+        WSSecHeader secHeader = new WSSecHeader();
+        secHeader.insertSecurityHeader(doc);
+        
+        Element usernameTokenElement = 
+            doc.createElementNS(
+                WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX + ":" + WSConstants.USERNAME_TOKEN_LN
+            );
+        Element usernameElement = 
+            doc.createElementNS(
+                WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX + ":" + WSConstants.USERNAME_LN
+            );
+        usernameElement.appendChild(doc.createTextNode("wernerd"));
+        usernameTokenElement.appendChild(usernameElement);
+        
+        Element passwordElement = 
+            doc.createElementNS(
+                WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX + ":" + WSConstants.PASSWORD_LN
+            );
+        passwordElement.setAttributeNS(null, "Type", WSConstants.PASSWORD_TEXT);
+        passwordElement.appendChild(doc.createTextNode("verySecret"));
+        usernameTokenElement.appendChild(passwordElement);
+
+        Element elementCreated =
+            doc.createElementNS(
+                WSConstants.WSU_NS, WSConstants.WSU_PREFIX + ":" + WSConstants.CREATED_LN
+            );
+        DateFormat zulu = new XmlSchemaDateFormat();
+        Date createdDate = new Date();
+        long currentTime = createdDate.getTime() + 120000;
+        createdDate.setTime(currentTime);
+        elementCreated.appendChild(doc.createTextNode(zulu.format(createdDate)));
+        usernameTokenElement.appendChild(elementCreated);
 
+        secHeader.getSecurityHeader().appendChild(usernameTokenElement);
+        
+        if (LOG.isDebugEnabled()) {
+            String outputString = 
+                XMLUtils.PrettyDocumentToString(doc);
+            LOG.debug(outputString);
+        }
+        
+        try {
+            WSSecurityEngine secEngine = new WSSecurityEngine();
+            secEngine.processSecurityHeader(doc, null, callbackHandler, null);
+            fail("The UsernameToken validation should have failed");
+        } catch (WSSecurityException ex) {
+            assertTrue(ex.getErrorCode() == WSSecurityException.ErrorCode.MESSAGE_EXPIRED); 
+        }  
+    }
+    
     /**
      * Test that adds a UserNameToken with password text to a WS-Security envelope
      */