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 org.apache.ws.security.WSConstants;
23  import org.apache.ws.security.WSSConfig;
24  import org.apache.ws.security.WSSecurityEngine;
25  import org.apache.ws.security.WSSecurityEngineResult;
26  import org.apache.ws.security.common.KeystoreCallbackHandler;
27  import org.apache.ws.security.common.SOAPUtil;
28  import org.apache.ws.security.components.crypto.Crypto;
29  import org.apache.ws.security.components.crypto.CryptoFactory;
30  import org.apache.ws.security.components.crypto.CryptoType;
31  import org.apache.ws.security.message.token.SecurityTokenReference;
32  import org.apache.ws.security.util.WSSecurityUtil;
33  import org.w3c.dom.Document;
34  
35  import java.security.cert.X509Certificate;
36  import java.util.List;
37  import javax.security.auth.callback.CallbackHandler;
38  
39  /**
40   * A set of tests for using a derived key for encryption/signature.
41   */
42  public class DerivedKeyTest extends org.junit.Assert {
43      private static final org.apache.commons.logging.Log LOG = 
44          org.apache.commons.logging.LogFactory.getLog(DerivedKeyTest.class);
45      private WSSecurityEngine secEngine = new WSSecurityEngine();
46      private CallbackHandler callbackHandler = new KeystoreCallbackHandler();
47      private Crypto crypto = null;
48      
49      public DerivedKeyTest() throws Exception {
50          crypto = CryptoFactory.getInstance("wss40.properties");
51          WSSConfig.init();
52      }
53  
54      /**
55       * Test encryption using a DerivedKeyToken using TRIPLEDES
56       * @throws Exception Thrown when there is any problem in signing or 
57       * verification
58       */
59      @org.junit.Test
60      public void testEncryptionDecryptionTRIPLEDES() throws Exception {
61          Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
62          WSSecHeader secHeader = new WSSecHeader();
63          secHeader.insertSecurityHeader(doc);
64  
65          //EncryptedKey
66          WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
67          encrKeyBuilder.setUserInfo("wss40");
68          encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
69          encrKeyBuilder.prepare(doc, crypto);
70  
71          //Key information from the EncryptedKey
72          byte[] ek = encrKeyBuilder.getEphemeralKey();
73          String tokenIdentifier = encrKeyBuilder.getId();  
74          
75          //Derived key encryption
76          WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
77          encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
78          encrBuilder.setExternalKey(ek, tokenIdentifier);
79          Document encryptedDoc = encrBuilder.build(doc, secHeader);
80          
81          encrKeyBuilder.prependToHeader(secHeader);
82          encrKeyBuilder.prependBSTElementToHeader(secHeader);
83  
84          if (LOG.isDebugEnabled()) {
85              LOG.debug("Encrypted message: 3DES  + DerivedKeys");
86              String outputString = 
87                  org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
88              LOG.debug(outputString);
89          }
90          verify(doc);
91      }
92  
93      /**
94       * Test encryption using a DerivedKeyToken using AES128 
95       * @throws Exception Thrown when there is any problem in signing or verification
96       */
97      @org.junit.Test
98      public void testEncryptionDecryptionAES128() throws Exception {
99          Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
100         WSSecHeader secHeader = new WSSecHeader();
101         secHeader.insertSecurityHeader(doc);
102 
103         //EncryptedKey
104         WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
105         encrKeyBuilder.setUserInfo("wss40");
106         encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
107         encrKeyBuilder.prepare(doc, crypto);
108 
109         //Key information from the EncryptedKey
110         byte[] ek = encrKeyBuilder.getEphemeralKey();
111         String tokenIdentifier = encrKeyBuilder.getId();  
112 
113         //Derived key encryption
114         WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
115         encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
116         encrBuilder.setExternalKey(ek, tokenIdentifier);
117         Document encryptedDoc = encrBuilder.build(doc, secHeader);
118 
119         encrKeyBuilder.prependToHeader(secHeader);
120         encrKeyBuilder.prependBSTElementToHeader(secHeader);
121 
122         if (LOG.isDebugEnabled()) {
123             LOG.debug("Encrypted message: 3DES  + DerivedKeys");
124             String outputString = 
125                 org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
126             LOG.debug(outputString);
127         }
128         verify(doc);
129      }
130      
131     @org.junit.Test
132     public void testSignature() throws Exception {
133         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
134         WSSecHeader secHeader = new WSSecHeader();
135         secHeader.insertSecurityHeader(doc);
136 
137         //EncryptedKey
138         WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
139         encrKeyBuilder.setUserInfo("wss40");
140         encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
141         encrKeyBuilder.prepare(doc, crypto);
142 
143         //Key information from the EncryptedKey
144         byte[] ek = encrKeyBuilder.getEphemeralKey();
145         String tokenIdentifier = encrKeyBuilder.getId();         
146 
147         //Derived key encryption
148         WSSecDKSign sigBuilder = new WSSecDKSign();
149         sigBuilder.setExternalKey(ek, tokenIdentifier);
150         sigBuilder.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
151         /* Document signedDoc = */ sigBuilder.build(doc, secHeader);
152 
153         encrKeyBuilder.prependToHeader(secHeader);
154         encrKeyBuilder.prependBSTElementToHeader(secHeader);
155 
156         if (LOG.isDebugEnabled()) {
157             LOG.debug("Encrypted message: 3DES  + DerivedKeys");
158             String outputString = 
159                 org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
160             LOG.debug(outputString);
161         }
162         List<WSSecurityEngineResult> results = verify(doc);
163         
164         WSSecurityEngineResult actionResult = 
165             WSSecurityUtil.fetchActionResult(results, WSConstants.SIGN);
166         assertTrue(actionResult != null);
167         assertFalse(actionResult.isEmpty());
168         assertTrue(actionResult.get(WSSecurityEngineResult.TAG_SECRET) != null);
169     }
170 
171 
172     /**
173      * A test for WSS-211 - "WSS4J does not support ThumbprintSHA1 in DerivedKeyTokens".
174      * Here we're signing the SOAP body, where the signature refers to a DerivedKeyToken
175      * which uses a Thumbprint-SHA1 reference to the encoded certificate (which is in the
176      * keystore)
177      */
178     @org.junit.Test
179     public void testSignatureThumbprintSHA1() throws Exception {
180         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
181         WSSecHeader secHeader = new WSSecHeader();
182         secHeader.insertSecurityHeader(doc);
183 
184         SecurityTokenReference secToken = new SecurityTokenReference(doc);
185         CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
186         cryptoType.setAlias("wss40");
187         X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
188         secToken.setKeyIdentifierThumb(certs[0]);
189 
190         WSSecDKSign sigBuilder = new WSSecDKSign();
191         java.security.Key key = crypto.getPrivateKey("wss40", "security");
192         sigBuilder.setExternalKey(key.getEncoded(), secToken.getElement());
193         sigBuilder.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
194         sigBuilder.build(doc, secHeader);
195 
196         sigBuilder.prependDKElementToHeader(secHeader);
197 
198         if (LOG.isDebugEnabled()) {
199             LOG.debug("Encrypted message: ThumbprintSHA1 + DerivedKeys");
200             String outputString = 
201                 org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
202             LOG.debug(outputString);
203         }
204         List<WSSecurityEngineResult> results = verify(doc);
205         
206         WSSecurityEngineResult actionResult = 
207             WSSecurityUtil.fetchActionResult(results, WSConstants.SIGN);
208         assertTrue(actionResult != null);
209         assertFalse(actionResult.isEmpty());
210         assertTrue(actionResult.get(WSSecurityEngineResult.TAG_SECRET) != null);
211     }
212 
213 
214     /**
215      * Here we're signing the SOAP body, where the signature refers to a DerivedKeyToken
216      * which uses an SKI reference to the encoded certificate (which is in the
217      * keystore)
218      */
219     @org.junit.Test
220     public void testSignatureSKI() throws Exception {
221         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
222         WSSecHeader secHeader = new WSSecHeader();
223         secHeader.insertSecurityHeader(doc);
224 
225         SecurityTokenReference secToken = new SecurityTokenReference(doc);
226         CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
227         cryptoType.setAlias("wss40");
228         X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
229         secToken.setKeyIdentifierSKI(certs[0], crypto);
230 
231         WSSecDKSign sigBuilder = new WSSecDKSign();
232         java.security.Key key = crypto.getPrivateKey("wss40", "security");
233         sigBuilder.setExternalKey(key.getEncoded(), secToken.getElement());
234         sigBuilder.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
235         sigBuilder.build(doc, secHeader);
236 
237         sigBuilder.prependDKElementToHeader(secHeader);
238 
239         if (LOG.isDebugEnabled()) {
240             LOG.debug("Encrypted message: SKI + DerivedKeys");
241             String outputString = 
242                 org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
243             LOG.debug(outputString);
244         }
245         List<WSSecurityEngineResult> results = verify(doc);
246         
247         WSSecurityEngineResult actionResult = 
248             WSSecurityUtil.fetchActionResult(results, WSConstants.SIGN);
249         assertTrue(actionResult != null);
250         assertFalse(actionResult.isEmpty());
251         assertTrue(actionResult.get(WSSecurityEngineResult.TAG_SECRET) != null);
252     }
253 
254     @org.junit.Test
255     public void testSignatureEncrypt() throws Exception {
256         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
257         WSSecHeader secHeader = new WSSecHeader();
258         secHeader.insertSecurityHeader(doc);
259 
260         //EncryptedKey
261         WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
262         encrKeyBuilder.setUserInfo("wss40");
263         encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
264         encrKeyBuilder.prepare(doc, crypto);
265 
266         //Key information from the EncryptedKey
267         byte[] ek = encrKeyBuilder.getEphemeralKey();
268         String tokenIdentifier = encrKeyBuilder.getId();
269 
270         //Derived key encryption
271         WSSecDKSign sigBuilder = new WSSecDKSign();
272         sigBuilder.setExternalKey(ek, tokenIdentifier);
273         sigBuilder.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
274         LOG.info("Before HMAC-SHA1 signature");
275         Document signedDoc = sigBuilder.build(doc, secHeader);
276 
277         //Derived key signature
278         WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
279         encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
280         encrBuilder.setExternalKey(ek, tokenIdentifier);
281         Document signedEncryptedDoc = encrBuilder.build(signedDoc, secHeader);
282 
283         encrKeyBuilder.prependToHeader(secHeader);
284         encrKeyBuilder.prependBSTElementToHeader(secHeader);
285 
286         if (LOG.isDebugEnabled()) {
287             LOG.debug("Encrypted message: 3DES  + DerivedKeys");
288             String outputString = 
289                 org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedEncryptedDoc);
290             LOG.debug(outputString);
291         }
292         verify(signedEncryptedDoc);
293     }
294 
295     @org.junit.Test
296     public void testEncryptSignature() throws Exception {
297         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
298         WSSecHeader secHeader = new WSSecHeader();
299         secHeader.insertSecurityHeader(doc);
300 
301         //EncryptedKey
302         WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
303         encrKeyBuilder.setUserInfo("wss40");
304         encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
305         encrKeyBuilder.prepare(doc, crypto);
306 
307         //Key information from the EncryptedKey
308         byte[] ek = encrKeyBuilder.getEphemeralKey();
309         String tokenIdentifier = encrKeyBuilder.getId();
310 
311         //Derived key encryption
312         WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
313         encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
314         encrBuilder.setExternalKey(ek, tokenIdentifier);
315         encrBuilder.build(doc, secHeader);
316 
317         //Derived key signature
318         WSSecDKSign sigBuilder = new WSSecDKSign();
319         sigBuilder.setExternalKey(ek, tokenIdentifier);
320         sigBuilder.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
321         LOG.info("Before HMAC-SHA1 signature");
322         Document encryptedSignedDoc = sigBuilder.build(doc, secHeader);
323 
324         encrKeyBuilder.prependToHeader(secHeader);
325         encrKeyBuilder.prependBSTElementToHeader(secHeader);
326 
327         if (LOG.isDebugEnabled()) {
328             LOG.debug("Encrypted message: 3DES  + DerivedKeys");
329             String outputString = 
330                 org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedSignedDoc);
331             LOG.debug(outputString);
332         }
333 
334         verify(encryptedSignedDoc);
335     }
336 
337     /**
338      * Verifies the soap envelope
339      * <p/>
340      * 
341      * @param envelope 
342      * @throws Exception Thrown when there is a problem in verification
343      */
344     private List<WSSecurityEngineResult> verify(Document doc) throws Exception {
345         List<WSSecurityEngineResult> results = 
346             secEngine.processSecurityHeader(doc, null, callbackHandler, crypto);
347         String outputString = 
348             org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
349         assertTrue(outputString.indexOf("counter_port_type") > 0 ? true : false);
350         
351         return results;
352     }
353 
354 }