1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements. See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership. The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License. You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied. See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.ws.security.message;
21  
22  import java.util.ArrayList;
23  import java.util.List;
24  
25  import javax.security.auth.callback.CallbackHandler;
26  
27  import org.apache.ws.security.WSConstants;
28  import org.apache.ws.security.WSEncryptionPart;
29  import org.apache.ws.security.WSSConfig;
30  import org.apache.ws.security.WSSecurityEngine;
31  import org.apache.ws.security.WSSecurityEngineResult;
32  import org.apache.ws.security.WSSecurityException;
33  import org.apache.ws.security.cache.MemoryReplayCache;
34  import org.apache.ws.security.common.KeystoreCallbackHandler;
35  import org.apache.ws.security.common.SOAPUtil;
36  import org.apache.ws.security.common.UsernamePasswordCallbackHandler;
37  import org.apache.ws.security.components.crypto.Crypto;
38  import org.apache.ws.security.components.crypto.CryptoFactory;
39  import org.apache.ws.security.handler.RequestData;
40  import org.apache.ws.security.util.WSSecurityUtil;
41  import org.w3c.dom.Document;
42  import org.w3c.dom.Element;
43  
44  /**
45   * Some test-cases for replay attacks.
46   */
47  public class ReplayTest extends org.junit.Assert {
48      private static final org.apache.commons.logging.Log LOG = 
49          org.apache.commons.logging.LogFactory.getLog(ReplayTest.class);
50      
51      private CallbackHandler callbackHandler = new KeystoreCallbackHandler();
52      private Crypto crypto = null;
53      
54      public ReplayTest() throws Exception {
55          crypto = CryptoFactory.getInstance();
56      }
57  
58      @org.junit.Test
59      public void testReplayedTimestamp() throws Exception {
60  
61          Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
62          WSSecHeader secHeader = new WSSecHeader();
63          secHeader.insertSecurityHeader(doc);
64          
65          WSSecTimestamp timestamp = new WSSecTimestamp();
66          timestamp.setTimeToLive(300);
67          Document createdDoc = timestamp.build(doc, secHeader);
68          
69          WSSecSignature builder = new WSSecSignature();
70          builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security");
71          builder.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
72          
73          List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
74          WSEncryptionPart encP =
75              new WSEncryptionPart(
76                  "Timestamp", WSConstants.WSU_NS, "");
77          parts.add(encP);
78          builder.setParts(parts);
79          
80          builder.prepare(createdDoc, crypto, secHeader);
81          
82          List<javax.xml.crypto.dsig.Reference> referenceList = 
83              builder.addReferencesToSign(parts, secHeader);
84  
85          builder.computeSignature(referenceList, false, null);
86  
87          if (LOG.isDebugEnabled()) {
88              String outputString = 
89                  org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(createdDoc);
90              LOG.debug(outputString);
91          }
92          
93          WSSConfig wssConfig = WSSConfig.getNewInstance();
94          RequestData data = new RequestData();
95          data.setWssConfig(wssConfig);
96          data.setCallbackHandler(callbackHandler);
97          data.setTimestampReplayCache(new MemoryReplayCache());
98          
99          // Successfully verify timestamp
100         verify(createdDoc, wssConfig, data);
101         
102         // Now try again - a replay attack should be detected
103         try {
104             verify(createdDoc, wssConfig, data);
105             fail("Expected failure on a replay attack");
106         } catch (WSSecurityException ex) {
107             assertTrue(ex.getErrorCode() == WSSecurityException.INVALID_SECURITY); 
108         }   
109     }
110     
111     @org.junit.Test
112     public void testReplayedTimestampBelowSignature() throws Exception {
113 
114         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
115         WSSecHeader secHeader = new WSSecHeader();
116         secHeader.insertSecurityHeader(doc);
117         
118         WSSecTimestamp timestamp = new WSSecTimestamp();
119         timestamp.setTimeToLive(300);
120         Document createdDoc = timestamp.build(doc, secHeader);
121         
122         WSSecSignature builder = new WSSecSignature();
123         builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security");
124         builder.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
125         
126         List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
127         WSEncryptionPart encP =
128             new WSEncryptionPart(
129                 "Timestamp", WSConstants.WSU_NS, "");
130         parts.add(encP);
131         builder.setParts(parts);
132         
133         builder.build(createdDoc, crypto, secHeader);
134         
135         if (LOG.isDebugEnabled()) {
136             String outputString = 
137                 org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(createdDoc);
138             LOG.debug(outputString);
139         }
140         
141         WSSConfig wssConfig = WSSConfig.getNewInstance();
142         RequestData data = new RequestData();
143         data.setWssConfig(wssConfig);
144         data.setCallbackHandler(callbackHandler);
145         data.setTimestampReplayCache(new MemoryReplayCache());
146         
147         // Successfully verify timestamp
148         verify(createdDoc, wssConfig, data);
149         
150         // Now try again - a replay attack should be detected
151         try {
152             verify(createdDoc, wssConfig, data);
153             fail("Expected failure on a replay attack");
154         } catch (WSSecurityException ex) {
155             assertTrue(ex.getErrorCode() == WSSecurityException.INVALID_SECURITY); 
156         }   
157     }
158     
159     @org.junit.Test
160     public void testReplayedTimestampNoExpires() throws Exception {
161 
162         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
163         WSSecHeader secHeader = new WSSecHeader();
164         secHeader.insertSecurityHeader(doc);
165         
166         WSSecTimestamp timestamp = new WSSecTimestamp();
167         timestamp.setTimeToLive(0);
168         Document createdDoc = timestamp.build(doc, secHeader);
169         
170         WSSecSignature builder = new WSSecSignature();
171         builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security");
172         builder.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
173         
174         List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
175         WSEncryptionPart encP =
176             new WSEncryptionPart(
177                 "Timestamp", WSConstants.WSU_NS, "");
178         parts.add(encP);
179         builder.setParts(parts);
180         
181         builder.prepare(createdDoc, crypto, secHeader);
182         
183         List<javax.xml.crypto.dsig.Reference> referenceList = 
184             builder.addReferencesToSign(parts, secHeader);
185 
186         builder.computeSignature(referenceList, false, null);
187 
188         if (LOG.isDebugEnabled()) {
189             String outputString = 
190                 org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(createdDoc);
191             LOG.debug(outputString);
192         }
193         
194         WSSConfig wssConfig = WSSConfig.getNewInstance();
195         RequestData data = new RequestData();
196         data.setWssConfig(wssConfig);
197         data.setCallbackHandler(callbackHandler);
198         data.setTimestampReplayCache(new MemoryReplayCache());
199         
200         // Successfully verify timestamp
201         verify(createdDoc, wssConfig, data);
202         
203         // Now try again - a replay attack should be detected
204         try {
205             verify(createdDoc, wssConfig, data);
206             fail("Expected failure on a replay attack");
207         } catch (WSSecurityException ex) {
208             assertTrue(ex.getErrorCode() == WSSecurityException.INVALID_SECURITY); 
209         }   
210     }
211     
212     @org.junit.Test
213     public void testReplayedUsernameToken() throws Exception {
214         WSSecUsernameToken builder = new WSSecUsernameToken();
215         builder.setUserInfo("wernerd", "verySecret");
216         
217         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
218         WSSecHeader secHeader = new WSSecHeader();
219         secHeader.insertSecurityHeader(doc);
220         Document signedDoc = builder.build(doc, secHeader);
221 
222         if (LOG.isDebugEnabled()) {
223             String outputString = 
224                 org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc);
225             LOG.debug(outputString);
226         }
227         
228         WSSConfig wssConfig = WSSConfig.getNewInstance();
229         RequestData data = new RequestData();
230         data.setCallbackHandler(new UsernamePasswordCallbackHandler());
231         data.setWssConfig(wssConfig);
232         data.setNonceReplayCache(new MemoryReplayCache());
233         
234         // Successfully verify UsernameToken
235         verify(signedDoc, wssConfig, data);
236         
237         // Now try again - a replay attack should be detected
238         try {
239             verify(signedDoc, wssConfig, data);
240             fail("Expected failure on a replay attack");
241         } catch (WSSecurityException ex) {
242             assertTrue(ex.getErrorCode() == WSSecurityException.INVALID_SECURITY); 
243         }   
244     }
245     
246     /**
247      * Verifies the soap envelope
248      * 
249      * @param env soap envelope
250      * @param wssConfig
251      * @throws java.lang.Exception Thrown when there is a problem in verification
252      */
253     private List<WSSecurityEngineResult> verify(
254         Document doc, WSSConfig wssConfig, RequestData data
255     ) throws Exception {
256         WSSecurityEngine secEngine = new WSSecurityEngine();
257         secEngine.setWssConfig(wssConfig);
258         Element elem = WSSecurityUtil.getSecurityHeader(doc, null);
259         data.setSigCrypto(crypto);
260         return secEngine.processSecurityHeader(elem, data);
261     }
262     
263     
264 }