View Javadoc
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.wss4j.dom.processor;
21  
22  import java.util.List;
23  
24  import javax.crypto.KeyGenerator;
25  import javax.crypto.SecretKey;
26  import javax.security.auth.callback.CallbackHandler;
27  
28  import org.apache.wss4j.common.util.SOAPUtil;
29  import org.apache.wss4j.dom.WSConstants;
30  import org.apache.wss4j.dom.WSDataRef;
31  import org.apache.wss4j.dom.common.KeystoreCallbackHandler;
32  
33  import org.apache.wss4j.dom.engine.WSSConfig;
34  import org.apache.wss4j.dom.engine.WSSecurityEngine;
35  import org.apache.wss4j.dom.engine.WSSecurityEngineResult;
36  import org.apache.wss4j.dom.handler.WSHandlerResult;
37  import org.apache.wss4j.common.WSEncryptionPart;
38  import org.apache.wss4j.common.crypto.Crypto;
39  import org.apache.wss4j.common.crypto.CryptoFactory;
40  import org.apache.wss4j.common.util.KeyUtils;
41  import org.apache.wss4j.dom.message.WSSecEncrypt;
42  import org.apache.wss4j.dom.message.WSSecHeader;
43  
44  import org.junit.jupiter.api.Test;
45  import org.w3c.dom.Document;
46  import org.w3c.dom.Element;
47  
48  import static org.junit.jupiter.api.Assertions.assertEquals;
49  import static org.junit.jupiter.api.Assertions.assertNotNull;
50  import static org.junit.jupiter.api.Assertions.assertTrue;
51  
52  /**
53   * Test that checks for correct WSDataRef which should be returned by
54   * <code>org.apache.wss4j.dom.processor.EncryptedKeyProcessor</code>
55   *
56   * This test uses the RSA_15 algorithm to transport (wrap) the symmetric key.
57   * The test case creates a ReferenceList element that references EncryptedData
58   * elements. The ReferencesList element is put into the EncryptedKey. The
59   * EncryptedData elements contain a KeyInfo that references the EncryptedKey via
60   * a STR/Reference structure.
61   *
62   * WSDataRef object must contain the correct QName of the decrypted element.
63   *
64   */
65  public class EncryptedKeyDataRefTest {
66      private static final org.slf4j.Logger LOG =
67          org.slf4j.LoggerFactory.getLogger(EncryptedKeyDataRefTest.class);
68      private WSSecurityEngine secEngine = new WSSecurityEngine();
69      private CallbackHandler callbackHandler = new KeystoreCallbackHandler();
70      private Crypto crypto;
71  
72      public EncryptedKeyDataRefTest() throws Exception {
73          crypto = CryptoFactory.getInstance("wss40.properties");
74          WSSConfig.init();
75      }
76  
77      /**
78       * Test that check for correct WSDataRef object from EncryptedKey Processor
79       *
80       *
81       * @throws Exception
82       *             Thrown when there is an error in encryption or decryption
83       */
84      @Test
85      public void testDataRefEncryptedKeyProcessor() throws Exception {
86          Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
87          WSSecHeader secHeader = new WSSecHeader(doc);
88          secHeader.insertSecurityHeader();
89  
90          WSSecEncrypt builder = new WSSecEncrypt(secHeader);
91          builder.setUserInfo("wss40");
92          builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
93          builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
94          LOG.info("Before Encryption Triple DES....");
95  
96          KeyGenerator keyGen = KeyUtils.getKeyGenerator(WSConstants.TRIPLE_DES);
97          SecretKey symmetricKey = keyGen.generateKey();
98  
99          /*
100          * Prepare the Encrypt object with the token, setup data structure
101          */
102         builder.prepare(crypto, symmetricKey);
103 
104         /*
105          * Set up the parts structure to encrypt the body
106          */
107         WSEncryptionPart encP =
108             new WSEncryptionPart(
109                 "add", "http://ws.apache.org/counter/counter_port_type", "Element"
110             );
111         builder.getParts().add(encP);
112 
113         /*
114          * Encrypt the element (testMethod), create EncryptedData elements that reference
115          * the EncryptedKey, and get a ReferenceList that can be put into the EncryptedKey
116          * itself as a child.
117          */
118         Element refs = builder.encrypt(symmetricKey);
119 
120         /*
121          * We use this method because we want the reference list to be inside the
122          * EncryptedKey element
123          */
124         builder.addInternalRefElement(refs);
125 
126         /*
127          * now add (prepend) the EncryptedKey element, then a
128          * BinarySecurityToken if one was setup during prepare
129          */
130         builder.prependToHeader();
131 
132         builder.prependBSTElementToHeader();
133 
134         Document encryptedDoc = doc;
135         LOG.info("After Encryption Triple DES....");
136 
137         checkDataRef(encryptedDoc);
138     }
139 
140     /**
141      * Verifies the soap envelope <p/>
142      *
143      * @param doc
144      * @throws Exception
145      *             Thrown when there is a problem in verification
146      */
147     @SuppressWarnings("unchecked")
148     private void checkDataRef(Document doc) throws Exception {
149 
150         // Retrieve the wsResults List
151         WSHandlerResult wsResults =
152             secEngine.processSecurityHeader(doc, null, callbackHandler, crypto);
153         boolean found = false;
154 
155         for (WSSecurityEngineResult wsSecEngineResult : wsResults.getResults()) {
156             int action = (Integer)
157                     wsSecEngineResult.get(WSSecurityEngineResult.TAG_ACTION);
158 
159             // We want to filter only encryption results
160             if (action != WSConstants.ENCR) {
161                 continue;
162             }
163             List<WSDataRef> dataRefs = (List<WSDataRef>)wsSecEngineResult
164                 .get(WSSecurityEngineResult.TAG_DATA_REF_URIS);
165 
166             //We want check only the DATA_REF_URIS
167             if (dataRefs != null && !dataRefs.isEmpty()) {
168                 for (Object obj : dataRefs) {
169 
170                     // ReferenceList Processor must Return a WSDataRef objects
171                     assertTrue(obj instanceof WSDataRef);
172 
173                     WSDataRef dataRef = (WSDataRef) obj;
174 
175                     // Check whether QName is correctly set
176                     assertEquals("add", dataRef.getName().getLocalPart());
177                     assertEquals(
178                         "http://ws.apache.org/counter/counter_port_type",
179                         dataRef.getName().getNamespaceURI()
180                     );
181 
182                     // Check whether wsu:Id is set
183                     assertNotNull(dataRef.getWsuId());
184 
185                     // Check the encryption algorithm was set
186                     assertEquals(WSConstants.TRIPLE_DES, dataRef.getAlgorithm());
187 
188                     // flag to indicate the element was found in TAG_DATA_REF_URIS
189                     found = true;
190 
191                 }
192             }
193         }
194 
195         // Make sure the element is actually found in the decrypted elements
196         assertTrue(found);
197 
198     }
199 
200 }