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.ReferenceListProcessor</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 Security header, not
59   * as child of the EncryptedKey. The EncryptedData elements contain a KeyInfo
60   * that references the EncryptedKey via a STR/Reference structure.
61   *
62   * WSDataRef object must contain the correct QName of the decrypted element.
63   *
64   */
65  public class ReferenceListDataRefTest {
66      private static final org.slf4j.Logger LOG =
67          org.slf4j.LoggerFactory.getLogger(ReferenceListDataRefTest.class);
68      private WSSecurityEngine secEngine = new WSSecurityEngine();
69      private CallbackHandler callbackHandler = new KeystoreCallbackHandler();
70      private Crypto crypto;
71  
72      public ReferenceListDataRefTest() throws Exception {
73          crypto = CryptoFactory.getInstance("wss40.properties");
74          WSSConfig.init();
75      }
76  
77      /**
78       * Test that check for correct WSDataRef object from ReferenceList Processor
79       *
80       *
81       * @throws Exception
82       *             Thrown when there is an error in encryption or decryption
83       */
84      @Test
85      public void testDataRefReferenceListProcessor() 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
116          * Security header. Be sure that the ReferenceList is after the
117          * EncryptedKey element in the Security header (strict layout)
118          */
119         Element refs = builder.encrypt(symmetricKey);
120         builder.addExternalRefElement(refs);
121 
122         /*
123          * now add (prepend) the EncryptedKey element, then a
124          * BinarySecurityToken if one was setup during prepare
125          */
126         builder.prependToHeader();
127 
128         builder.prependBSTElementToHeader();
129 
130         Document encryptedDoc = doc;
131         LOG.info("After Encryption Triple DES....");
132 
133         checkDataRef(encryptedDoc);
134     }
135 
136     /**
137      * Verifies the soap envelope <p/>
138      *
139      * @param doc
140      * @throws Exception
141      *             Thrown when there is a problem in verification
142      */
143     @SuppressWarnings("unchecked")
144     private void checkDataRef(Document doc) throws Exception {
145 
146         // Retrieve the wsResults List
147         WSHandlerResult wsResults =
148             secEngine.processSecurityHeader(doc, null, callbackHandler, crypto);
149         boolean found = false;
150 
151         for (int i = 0; i < wsResults.getResults().size(); i++) {
152             WSSecurityEngineResult wsSecEngineResult = wsResults.getResults().get(i);
153             int action = (Integer)
154                     wsSecEngineResult.get(WSSecurityEngineResult.TAG_ACTION);
155 
156             // We want to filter only encryption results
157             if (action != WSConstants.ENCR) {
158                 continue;
159             }
160             List<WSDataRef> dataRefs =
161                 (List<WSDataRef>)wsSecEngineResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS);
162 
163             //We want check only the DATA_REF_URIS
164             if (dataRefs != null && !dataRefs.isEmpty()) {
165                 for (Object obj : dataRefs) {
166 
167                     // ReferenceList Processor must Return a WSDataRef objects
168                     assertTrue(obj instanceof WSDataRef);
169 
170                     WSDataRef dataRef = (WSDataRef) obj;
171 
172                     // Check whether QName is correctly set
173                     assertEquals("add", dataRef.getName().getLocalPart());
174                     assertEquals(
175                         "http://ws.apache.org/counter/counter_port_type",
176                         dataRef.getName().getNamespaceURI()
177                     );
178 
179                     // Check whether wsu:Id is set
180                     assertNotNull(dataRef.getWsuId());
181 
182                     // Check the encryption algorithm was set
183                     assertEquals(WSConstants.TRIPLE_DES, dataRef.getAlgorithm());
184 
185                     // flag to indicate the element was found in TAG_DATA_REF_URIS
186                     found = true;
187 
188                 }
189             }
190         }
191 
192         // Make sure the element is actually found in the decrypted elements
193         assertTrue(found);
194 
195     }
196 
197 }