/
AbstractBindingBuilder.java
2203 lines (1983 loc) · 96.3 KB
/
AbstractBindingBuilder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 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.cxf.ws.security.wss4j.policyhandlers;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.callback.CallbackHandler;
import javax.xml.crypto.dsig.Reference;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.apache.cxf.Bus;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.saaj.SAAJUtils;
import org.apache.cxf.common.classloader.ClassLoaderUtils;
import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.common.util.StringUtils;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.helpers.CastUtils;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.helpers.MapNamespaceContext;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.MessageUtils;
import org.apache.cxf.resource.ResourceManager;
import org.apache.cxf.service.model.EndpointInfo;
import org.apache.cxf.ws.policy.AssertionInfo;
import org.apache.cxf.ws.policy.AssertionInfoMap;
import org.apache.cxf.ws.policy.PolicyConstants;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
import org.apache.cxf.ws.security.wss4j.AttachmentCallbackHandler;
import org.apache.cxf.ws.security.wss4j.WSS4JUtils;
import org.apache.cxf.wsdl.WSDLConstants;
import org.apache.neethi.Assertion;
import org.apache.wss4j.common.WSEncryptionPart;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
import org.apache.wss4j.common.crypto.CryptoType;
import org.apache.wss4j.common.crypto.JasyptPasswordEncryptor;
import org.apache.wss4j.common.crypto.PasswordEncryptor;
import org.apache.wss4j.common.derivedKey.ConversationConstants;
import org.apache.wss4j.common.derivedKey.ConversationException;
import org.apache.wss4j.common.ext.WSPasswordCallback;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.principal.UsernameTokenPrincipal;
import org.apache.wss4j.common.saml.SAMLCallback;
import org.apache.wss4j.common.saml.SAMLUtil;
import org.apache.wss4j.common.saml.SamlAssertionWrapper;
import org.apache.wss4j.common.util.Loader;
import org.apache.wss4j.dom.WSConstants;
import org.apache.wss4j.dom.WSSConfig;
import org.apache.wss4j.dom.WSSecurityEngineResult;
import org.apache.wss4j.dom.bsp.BSPEnforcer;
import org.apache.wss4j.dom.handler.WSHandlerConstants;
import org.apache.wss4j.dom.handler.WSHandlerResult;
import org.apache.wss4j.dom.message.WSSecBase;
import org.apache.wss4j.dom.message.WSSecDKSign;
import org.apache.wss4j.dom.message.WSSecEncryptedKey;
import org.apache.wss4j.dom.message.WSSecHeader;
import org.apache.wss4j.dom.message.WSSecSignature;
import org.apache.wss4j.dom.message.WSSecSignatureConfirmation;
import org.apache.wss4j.dom.message.WSSecTimestamp;
import org.apache.wss4j.dom.message.WSSecUsernameToken;
import org.apache.wss4j.dom.message.token.BinarySecurity;
import org.apache.wss4j.dom.message.token.SecurityTokenReference;
import org.apache.wss4j.dom.message.token.X509Security;
import org.apache.wss4j.dom.util.WSSecurityUtil;
import org.apache.wss4j.policy.SPConstants;
import org.apache.wss4j.policy.SPConstants.IncludeTokenType;
import org.apache.wss4j.policy.model.AbstractBinding;
import org.apache.wss4j.policy.model.AbstractSymmetricAsymmetricBinding;
import org.apache.wss4j.policy.model.AbstractToken;
import org.apache.wss4j.policy.model.AbstractToken.DerivedKeys;
import org.apache.wss4j.policy.model.AbstractTokenWrapper;
import org.apache.wss4j.policy.model.AlgorithmSuite.AlgorithmSuiteType;
import org.apache.wss4j.policy.model.AsymmetricBinding;
import org.apache.wss4j.policy.model.Attachments;
import org.apache.wss4j.policy.model.ContentEncryptedElements;
import org.apache.wss4j.policy.model.EncryptedElements;
import org.apache.wss4j.policy.model.EncryptedParts;
import org.apache.wss4j.policy.model.Header;
import org.apache.wss4j.policy.model.IssuedToken;
import org.apache.wss4j.policy.model.KerberosToken;
import org.apache.wss4j.policy.model.KeyValueToken;
import org.apache.wss4j.policy.model.Layout.LayoutType;
import org.apache.wss4j.policy.model.SamlToken;
import org.apache.wss4j.policy.model.SamlToken.SamlTokenType;
import org.apache.wss4j.policy.model.SecureConversationToken;
import org.apache.wss4j.policy.model.SecurityContextToken;
import org.apache.wss4j.policy.model.SignedElements;
import org.apache.wss4j.policy.model.SignedParts;
import org.apache.wss4j.policy.model.SupportingTokens;
import org.apache.wss4j.policy.model.SymmetricBinding;
import org.apache.wss4j.policy.model.UsernameToken;
import org.apache.wss4j.policy.model.Wss10;
import org.apache.wss4j.policy.model.Wss11;
import org.apache.wss4j.policy.model.X509Token;
import org.apache.wss4j.policy.model.X509Token.TokenType;
import org.opensaml.common.SAMLVersion;
/**
*
*/
public abstract class AbstractBindingBuilder extends AbstractCommonBindingHandler {
public static final String CRYPTO_CACHE = "ws-security.crypto.cache";
protected static final Logger LOG = LogUtils.getL7dLogger(AbstractBindingBuilder.class);
protected AbstractSymmetricAsymmetricBinding.ProtectionOrder protectionOrder =
AbstractSymmetricAsymmetricBinding.ProtectionOrder.SignBeforeEncrypting;
protected final WSSConfig wssConfig;
protected SOAPMessage saaj;
protected WSSecHeader secHeader;
protected AssertionInfoMap aim;
protected AbstractBinding binding;
protected WSSecTimestamp timestampEl;
protected String mainSigId;
protected List<WSEncryptionPart> sigConfList;
protected Set<WSEncryptionPart> encryptedTokensList = new HashSet<WSEncryptionPart>();
protected List<SupportingToken> endEncSuppTokList;
protected List<SupportingToken> endSuppTokList;
protected List<SupportingToken> sgndEndEncSuppTokList;
protected List<SupportingToken> sgndEndSuppTokList;
protected List<byte[]> signatures = new ArrayList<byte[]>();
protected Element bottomUpElement;
protected Element topDownElement;
protected Element bstElement;
protected Element lastEncryptedKeyElement;
private Element lastSupportingTokenElement;
private Element lastDerivedKeyElement;
public AbstractBindingBuilder(
WSSConfig config,
AbstractBinding binding,
SOAPMessage saaj,
WSSecHeader secHeader,
AssertionInfoMap aim,
SoapMessage message) {
super(message);
this.wssConfig = config;
this.binding = binding;
this.aim = aim;
this.secHeader = secHeader;
this.saaj = saaj;
message.getExchange().put(WSHandlerConstants.SEND_SIGV, signatures);
}
protected void insertAfter(Element child, Element sib) {
if (sib.getNextSibling() == null) {
secHeader.getSecurityHeader().appendChild(child);
} else {
secHeader.getSecurityHeader().insertBefore(child, sib.getNextSibling());
}
}
protected void addDerivedKeyElement(Element el) {
if (lastDerivedKeyElement != null) {
insertAfter(el, lastDerivedKeyElement);
} else if (lastEncryptedKeyElement != null) {
insertAfter(el, lastEncryptedKeyElement);
} else if (topDownElement != null) {
insertAfter(el, topDownElement);
} else if (secHeader.getSecurityHeader().getFirstChild() != null) {
secHeader.getSecurityHeader().insertBefore(
el, secHeader.getSecurityHeader().getFirstChild()
);
} else {
secHeader.getSecurityHeader().appendChild(el);
}
lastEncryptedKeyElement = el;
}
protected void addEncryptedKeyElement(Element el) {
if (lastEncryptedKeyElement != null) {
insertAfter(el, lastEncryptedKeyElement);
} else if (lastDerivedKeyElement != null) {
secHeader.getSecurityHeader().insertBefore(el, lastDerivedKeyElement);
} else if (topDownElement != null) {
insertAfter(el, topDownElement);
} else if (secHeader.getSecurityHeader().getFirstChild() != null) {
secHeader.getSecurityHeader().insertBefore(
el, secHeader.getSecurityHeader().getFirstChild()
);
} else {
secHeader.getSecurityHeader().appendChild(el);
}
lastEncryptedKeyElement = el;
}
protected void addSupportingElement(Element el) {
if (lastSupportingTokenElement != null) {
insertAfter(el, lastSupportingTokenElement);
} else if (lastDerivedKeyElement != null) {
insertAfter(el, lastDerivedKeyElement);
} else if (lastEncryptedKeyElement != null) {
insertAfter(el, lastEncryptedKeyElement);
} else if (topDownElement != null) {
insertAfter(el, topDownElement);
} else if (bottomUpElement != null) {
secHeader.getSecurityHeader().insertBefore(el, bottomUpElement);
} else {
secHeader.getSecurityHeader().appendChild(el);
}
lastSupportingTokenElement = el;
}
protected void insertBeforeBottomUp(Element el) {
if (bottomUpElement == null) {
secHeader.getSecurityHeader().appendChild(el);
} else {
secHeader.getSecurityHeader().insertBefore(el, bottomUpElement);
}
bottomUpElement = el;
}
protected void addTopDownElement(Element el) {
if (topDownElement == null) {
if (secHeader.getSecurityHeader().getFirstChild() == null) {
secHeader.getSecurityHeader().appendChild(el);
} else {
secHeader.getSecurityHeader().insertBefore(
el, secHeader.getSecurityHeader().getFirstChild()
);
}
} else {
insertAfter(el, topDownElement);
}
topDownElement = el;
}
protected final Map<Object, Crypto> getCryptoCache() {
EndpointInfo info = message.getExchange().get(Endpoint.class).getEndpointInfo();
synchronized (info) {
Map<Object, Crypto> o =
CastUtils.cast((Map<?, ?>)message.getContextualProperty(CRYPTO_CACHE));
if (o == null) {
o = new ConcurrentHashMap<Object, Crypto>();
info.setProperty(CRYPTO_CACHE, o);
}
return o;
}
}
protected final TokenStore getTokenStore() {
return WSS4JUtils.getTokenStore(message);
}
protected WSSecTimestamp createTimestamp() {
if (binding.isIncludeTimestamp()) {
Object o = message.getContextualProperty(SecurityConstants.TIMESTAMP_TTL);
int ttl = 300; //default is 300 seconds
if (o instanceof Number) {
ttl = ((Number)o).intValue();
} else if (o instanceof String) {
ttl = Integer.parseInt((String)o);
}
if (ttl <= 0) {
ttl = 300;
}
timestampEl = new WSSecTimestamp(wssConfig);
timestampEl.setTimeToLive(ttl);
timestampEl.prepare(saaj.getSOAPPart());
Collection<AssertionInfo> ais = getAllAssertionsByLocalname(SPConstants.INCLUDE_TIMESTAMP);
for (AssertionInfo ai : ais) {
ai.setAsserted(true);
}
}
return timestampEl;
}
protected WSSecTimestamp handleLayout(WSSecTimestamp timestamp) {
if (binding.getLayout() != null) {
Collection<AssertionInfo> ais = getAllAssertionsByLocalname(SPConstants.LAYOUT);
AssertionInfo ai = null;
for (AssertionInfo layoutAi : ais) {
layoutAi.setAsserted(true);
ai = layoutAi;
}
if (binding.getLayout().getLayoutType() == LayoutType.LaxTsLast) {
if (timestamp == null) {
ai.setNotAsserted(SPConstants.LAYOUT_LAX_TIMESTAMP_LAST + " requires a timestamp");
} else {
ai.setAsserted(true);
assertPolicy(
new QName(binding.getLayout().getName().getNamespaceURI(),
SPConstants.LAYOUT_LAX_TIMESTAMP_LAST));
Element el = timestamp.getElement();
secHeader.getSecurityHeader().appendChild(el);
if (bottomUpElement == null) {
bottomUpElement = el;
}
}
} else if (binding.getLayout().getLayoutType() == LayoutType.LaxTsFirst) {
if (timestamp == null) {
ai.setNotAsserted(SPConstants.LAYOUT_LAX_TIMESTAMP_FIRST + " requires a timestamp");
} else {
addTopDownElement(timestampEl.getElement());
assertPolicy(
new QName(binding.getLayout().getName().getNamespaceURI(),
SPConstants.LAYOUT_LAX_TIMESTAMP_FIRST));
}
} else if (timestampEl != null) {
addTopDownElement(timestampEl.getElement());
}
assertPolicy(
new QName(binding.getLayout().getName().getNamespaceURI(), SPConstants.LAYOUT_LAX));
assertPolicy(
new QName(binding.getLayout().getName().getNamespaceURI(), SPConstants.LAYOUT_STRICT));
} else if (timestampEl != null) {
addTopDownElement(timestampEl.getElement());
}
return timestamp;
}
protected void reshuffleTimestamp() {
// Make sure that the Timestamp is in first place, if that is what the policy requires
if (binding.getLayout() != null && timestampEl != null) {
if (binding.getLayout().getLayoutType() == LayoutType.LaxTsFirst
&& secHeader.getSecurityHeader().getFirstChild() != timestampEl.getElement()) {
Node firstChild = secHeader.getSecurityHeader().getFirstChild();
while (firstChild != null && firstChild.getNodeType() != Node.ELEMENT_NODE) {
firstChild = firstChild.getNextSibling();
}
if (firstChild != null && firstChild != timestampEl.getElement()) {
secHeader.getSecurityHeader().insertBefore(timestampEl.getElement(), firstChild);
}
} else if (binding.getLayout().getLayoutType() == LayoutType.LaxTsLast
&& secHeader.getSecurityHeader().getLastChild() != timestampEl.getElement()) {
secHeader.getSecurityHeader().appendChild(timestampEl.getElement());
}
}
}
private List<SupportingToken> handleSupportingTokens(
Collection<AssertionInfo> tokensInfos,
boolean endorse
) throws WSSecurityException {
List<SupportingToken> ret = new ArrayList<SupportingToken>();
if (tokensInfos != null) {
for (AssertionInfo assertionInfo : tokensInfos) {
if (assertionInfo.getAssertion() instanceof SupportingTokens) {
handleSupportingTokens((SupportingTokens)assertionInfo.getAssertion(), endorse, ret);
}
}
}
return ret;
}
protected List<SupportingToken> handleSupportingTokens(
SupportingTokens suppTokens,
boolean endorse,
List<SupportingToken> ret
) throws WSSecurityException {
if (suppTokens == null) {
return ret;
}
for (AbstractToken token : suppTokens.getTokens()) {
assertToken(token);
if (!isTokenRequired(token.getIncludeTokenType())) {
continue;
}
if (token instanceof UsernameToken) {
handleUsernameTokenSupportingToken(
(UsernameToken)token, endorse, suppTokens.isEncryptedToken(), ret
);
} else if (token instanceof IssuedToken
|| token instanceof SecureConversationToken
|| token instanceof SecurityContextToken
|| token instanceof KerberosToken) {
//ws-trust/ws-sc stuff.......
SecurityToken secToken = getSecurityToken();
if (secToken == null) {
policyNotAsserted(token, "Could not find IssuedToken");
}
Element clone = cloneElement(secToken.getToken());
secToken.setToken(clone);
addSupportingElement(clone);
String id = secToken.getId();
if (id != null && id.charAt(0) == '#') {
id = id.substring(1);
}
if (suppTokens.isEncryptedToken()) {
WSEncryptionPart part = new WSEncryptionPart(id, "Element");
part.setElement(clone);
encryptedTokensList.add(part);
}
if (secToken.getX509Certificate() == null) {
ret.add(
new SupportingToken(token, new WSSecurityTokenHolder(wssConfig, secToken))
);
} else {
WSSecSignature sig = new WSSecSignature(wssConfig);
sig.setX509Certificate(secToken.getX509Certificate());
sig.setCustomTokenId(id);
sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
String tokenType = secToken.getTokenType();
if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
|| WSConstants.SAML_NS.equals(tokenType)) {
sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
} else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
|| WSConstants.SAML2_NS.equals(tokenType)) {
sig.setCustomTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE);
} else if (tokenType != null) {
sig.setCustomTokenValueType(tokenType);
} else {
sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
}
sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getAsymmetricSignature());
sig.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue());
Crypto crypto = secToken.getCrypto();
String uname = null;
try {
uname = crypto.getX509Identifier(secToken.getX509Certificate());
} catch (WSSecurityException e1) {
LOG.log(Level.FINE, e1.getMessage(), e1);
throw new Fault(e1);
}
String password = getPassword(uname, token, WSPasswordCallback.SIGNATURE);
sig.setUserInfo(uname, password);
try {
sig.prepare(saaj.getSOAPPart(), secToken.getCrypto(), secHeader);
} catch (WSSecurityException e) {
LOG.log(Level.FINE, e.getMessage(), e);
throw new Fault(e);
}
ret.add(new SupportingToken(token, sig));
}
} else if (token instanceof X509Token) {
//We have to use a cert. Prepare X509 signature
WSSecSignature sig = getSignatureBuilder(suppTokens, token, endorse);
Element bstElem = sig.getBinarySecurityTokenElement();
if (bstElem != null) {
if (lastEncryptedKeyElement != null) {
if (lastEncryptedKeyElement.getNextSibling() != null) {
secHeader.getSecurityHeader().insertBefore(bstElem,
lastEncryptedKeyElement.getNextSibling());
} else {
secHeader.getSecurityHeader().appendChild(bstElem);
}
} else {
sig.prependBSTElementToHeader(secHeader);
}
if (suppTokens.isEncryptedToken()) {
WSEncryptionPart part = new WSEncryptionPart(sig.getBSTTokenId(), "Element");
part.setElement(bstElem);
encryptedTokensList.add(part);
}
}
ret.add(new SupportingToken(token, sig));
} else if (token instanceof KeyValueToken) {
WSSecSignature sig = getSignatureBuilder(suppTokens, token, endorse);
if (suppTokens.isEncryptedToken()) {
WSEncryptionPart part = new WSEncryptionPart(sig.getBSTTokenId(), "Element");
encryptedTokensList.add(part);
}
ret.add(new SupportingToken(token, sig));
} else if (token instanceof SamlToken) {
SamlAssertionWrapper assertionWrapper = addSamlToken((SamlToken)token);
if (assertionWrapper != null) {
Element assertionElement = assertionWrapper.toDOM(saaj.getSOAPPart());
addSupportingElement(assertionElement);
ret.add(new SupportingToken(token, assertionWrapper));
if (suppTokens.isEncryptedToken()) {
WSEncryptionPart part = new WSEncryptionPart(assertionWrapper.getId(), "Element");
part.setElement(assertionElement);
encryptedTokensList.add(part);
}
}
}
}
return ret;
}
protected void handleUsernameTokenSupportingToken(
UsernameToken token, boolean endorse, boolean encryptedToken, List<SupportingToken> ret
) throws WSSecurityException {
if (endorse) {
WSSecUsernameToken utBuilder = addDKUsernameToken(token, true);
if (utBuilder != null) {
utBuilder.prepare(saaj.getSOAPPart());
addSupportingElement(utBuilder.getUsernameTokenElement());
ret.add(new SupportingToken(token, utBuilder));
if (encryptedToken) {
WSEncryptionPart part = new WSEncryptionPart(utBuilder.getId(), "Element");
part.setElement(utBuilder.getUsernameTokenElement());
encryptedTokensList.add(part);
}
}
} else {
WSSecUsernameToken utBuilder = addUsernameToken(token);
if (utBuilder != null) {
utBuilder.prepare(saaj.getSOAPPart());
addSupportingElement(utBuilder.getUsernameTokenElement());
ret.add(new SupportingToken(token, utBuilder));
//WebLogic and WCF always encrypt these
//See: http://e-docs.bea.com/wls/docs103/webserv_intro/interop.html
//encryptedTokensIdList.add(utBuilder.getId());
if (encryptedToken
|| MessageUtils.getContextualBoolean(message,
SecurityConstants.ALWAYS_ENCRYPT_UT,
true)) {
WSEncryptionPart part = new WSEncryptionPart(utBuilder.getId(), "Element");
part.setElement(utBuilder.getUsernameTokenElement());
encryptedTokensList.add(part);
}
}
}
}
protected Element cloneElement(Element el) {
return (Element)secHeader.getSecurityHeader().getOwnerDocument().importNode(el, true);
}
protected void addSignatureParts(List<SupportingToken> tokenList,
List<WSEncryptionPart> sigParts) {
for (SupportingToken supportingToken : tokenList) {
Object tempTok = supportingToken.getTokenImplementation();
WSEncryptionPart part = null;
if (tempTok instanceof WSSecSignature) {
WSSecSignature tempSig = (WSSecSignature) tempTok;
SecurityTokenReference secRef = tempSig.getSecurityTokenReference();
if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())
|| WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
Element secRefElement = cloneElement(secRef.getElement());
addSupportingElement(secRefElement);
part = new WSEncryptionPart("STRTransform", null, "Element");
part.setId(tempSig.getSecurityTokenReferenceURI());
part.setElement(secRefElement);
} else {
if (tempSig.getBSTTokenId() != null) {
part = new WSEncryptionPart(tempSig.getBSTTokenId());
part.setElement(tempSig.getBinarySecurityTokenElement());
}
}
} else if (tempTok instanceof WSSecUsernameToken) {
WSSecUsernameToken unt = (WSSecUsernameToken)tempTok;
part = new WSEncryptionPart(unt.getId());
part.setElement(unt.getUsernameTokenElement());
} else if (tempTok instanceof BinarySecurity) {
BinarySecurity bst = (BinarySecurity)tempTok;
part = new WSEncryptionPart(bst.getID());
part.setElement(bst.getElement());
} else if (tempTok instanceof SamlAssertionWrapper) {
SamlAssertionWrapper assertionWrapper = (SamlAssertionWrapper)tempTok;
Document doc = assertionWrapper.getElement().getOwnerDocument();
boolean saml1 = assertionWrapper.getSaml1() != null;
// TODO We only support using a KeyIdentifier for the moment
SecurityTokenReference secRef =
createSTRForSamlAssertion(doc, assertionWrapper.getId(), saml1, false);
Element clone = cloneElement(secRef.getElement());
addSupportingElement(clone);
part = new WSEncryptionPart("STRTransform", null, "Element");
part.setId(secRef.getID());
part.setElement(clone);
} else if (tempTok instanceof WSSecurityTokenHolder) {
SecurityToken token = ((WSSecurityTokenHolder)tempTok).getToken();
String tokenType = token.getTokenType();
if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
|| WSConstants.SAML_NS.equals(tokenType)
|| WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
|| WSConstants.SAML2_NS.equals(tokenType)) {
Document doc = token.getToken().getOwnerDocument();
boolean saml1 = WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
|| WSConstants.SAML_NS.equals(tokenType);
String id = null;
if (saml1) {
id = token.getToken().getAttributeNS(null, "AssertionID");
} else {
id = token.getToken().getAttributeNS(null, "ID");
}
SecurityTokenReference secRef =
createSTRForSamlAssertion(doc, id, saml1, false);
Element clone = cloneElement(secRef.getElement());
addSupportingElement(clone);
part = new WSEncryptionPart("STRTransform", null, "Element");
part.setId(secRef.getID());
part.setElement(clone);
} else {
String id = token.getId();
if (id != null && id.charAt(0) == '#') {
id = id.substring(1);
}
part = new WSEncryptionPart(id);
part.setElement(token.getToken());
}
} else {
policyNotAsserted(supportingToken.getToken(),
"UnsupportedTokenInSupportingToken: " + tempTok);
}
if (part != null) {
sigParts.add(part);
}
}
}
/**
* Create a SecurityTokenReference to point to a SAML Assertion
* @param doc The owner Document instance
* @param id The Assertion ID
* @param saml1 Whether the Assertion is a SAML1 or SAML2 Assertion
* @param useDirectReferenceToAssertion whether to refer directly to the assertion or not
* @return a SecurityTokenReference to a SAML Assertion
*/
private SecurityTokenReference createSTRForSamlAssertion(
Document doc,
String id,
boolean saml1,
boolean useDirectReferenceToAssertion
) {
SecurityTokenReference secRefSaml = new SecurityTokenReference(doc);
String secRefID = wssConfig.getIdAllocator().createSecureId("STR-", secRefSaml);
secRefSaml.setID(secRefID);
if (useDirectReferenceToAssertion) {
org.apache.wss4j.dom.message.token.Reference ref =
new org.apache.wss4j.dom.message.token.Reference(doc);
ref.setURI("#" + id);
if (saml1) {
ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
} else {
secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
}
secRefSaml.setReference(ref);
} else {
Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier");
String valueType = null;
if (saml1) {
valueType = WSConstants.WSS_SAML_KI_VALUE_TYPE;
secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
} else {
valueType = WSConstants.WSS_SAML2_KI_VALUE_TYPE;
secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
}
keyId.setAttributeNS(
null, "ValueType", valueType
);
keyId.appendChild(doc.createTextNode(id));
Element elem = secRefSaml.getElement();
elem.appendChild(keyId);
}
return secRefSaml;
}
protected WSSecUsernameToken addUsernameToken(UsernameToken token) {
assertToken(token);
if (!isTokenRequired(token.getIncludeTokenType())) {
return null;
}
String userName = (String)message.getContextualProperty(SecurityConstants.USERNAME);
if (!StringUtils.isEmpty(userName)) {
WSSecUsernameToken utBuilder = new WSSecUsernameToken(wssConfig);
// If NoPassword property is set we don't need to set the password
if (token.getPasswordType() == UsernameToken.PasswordType.NoPassword) {
utBuilder.setUserInfo(userName, null);
utBuilder.setPasswordType(null);
} else {
String password = (String)message.getContextualProperty(SecurityConstants.PASSWORD);
if (StringUtils.isEmpty(password)) {
password = getPassword(userName, token, WSPasswordCallback.USERNAME_TOKEN);
}
if (!StringUtils.isEmpty(password)) {
// If the password is available then build the token
if (token.getPasswordType() == UsernameToken.PasswordType.HashPassword) {
utBuilder.setPasswordType(WSConstants.PASSWORD_DIGEST);
} else {
utBuilder.setPasswordType(WSConstants.PASSWORD_TEXT);
}
utBuilder.setUserInfo(userName, password);
} else {
policyNotAsserted(token, "No password available");
return null;
}
}
if (token.isCreated() && token.getPasswordType() != UsernameToken.PasswordType.HashPassword) {
utBuilder.addCreated();
}
if (token.isNonce() && token.getPasswordType() != UsernameToken.PasswordType.HashPassword) {
utBuilder.addNonce();
}
return utBuilder;
} else {
policyNotAsserted(token, "No username available");
return null;
}
}
protected WSSecUsernameToken addDKUsernameToken(UsernameToken token, boolean useMac) {
assertToken(token);
if (!isTokenRequired(token.getIncludeTokenType())) {
return null;
}
String userName = (String)message.getContextualProperty(SecurityConstants.USERNAME);
if (!StringUtils.isEmpty(userName)) {
WSSecUsernameToken utBuilder = new WSSecUsernameToken(wssConfig);
String password = (String)message.getContextualProperty(SecurityConstants.PASSWORD);
if (StringUtils.isEmpty(password)) {
password = getPassword(userName, token, WSPasswordCallback.USERNAME_TOKEN);
}
if (!StringUtils.isEmpty(password)) {
// If the password is available then build the token
utBuilder.setUserInfo(userName, password);
utBuilder.addDerivedKey(useMac, null, 1000);
utBuilder.prepare(saaj.getSOAPPart());
} else {
policyNotAsserted(token, "No password available");
return null;
}
return utBuilder;
} else {
policyNotAsserted(token, "No username available");
return null;
}
}
protected SamlAssertionWrapper addSamlToken(SamlToken token) throws WSSecurityException {
assertToken(token);
if (!isTokenRequired(token.getIncludeTokenType())) {
return null;
}
//
// Get the SAML CallbackHandler
//
Object o = message.getContextualProperty(SecurityConstants.SAML_CALLBACK_HANDLER);
if (o == null && message.getContextualProperty(SecurityConstants.TOKEN) != null) {
SecurityToken securityToken = (SecurityToken)message.getContextualProperty(SecurityConstants.TOKEN);
Element tokenElement = (Element)securityToken.getToken();
String namespace = tokenElement.getNamespaceURI();
String localname = tokenElement.getLocalName();
SamlTokenType tokenType = token.getSamlTokenType();
if ((tokenType == SamlTokenType.WssSamlV11Token10 || tokenType == SamlTokenType.WssSamlV11Token11)
&& WSConstants.SAML_NS.equals(namespace) && "Assertion".equals(localname)) {
return new SamlAssertionWrapper(tokenElement);
} else if (tokenType == SamlTokenType.WssSamlV20Token11
&& WSConstants.SAML2_NS.equals(namespace) && "Assertion".equals(localname)) {
return new SamlAssertionWrapper(tokenElement);
}
}
CallbackHandler handler = null;
if (o instanceof CallbackHandler) {
handler = (CallbackHandler)o;
} else if (o instanceof String) {
try {
handler = (CallbackHandler)ClassLoaderUtils
.loadClass((String)o, this.getClass()).newInstance();
} catch (Exception e) {
handler = null;
}
}
if (handler == null) {
policyNotAsserted(token, "No SAML CallbackHandler available");
return null;
}
SAMLCallback samlCallback = new SAMLCallback();
SamlTokenType tokenType = token.getSamlTokenType();
if (tokenType == SamlTokenType.WssSamlV11Token10 || tokenType == SamlTokenType.WssSamlV11Token11) {
samlCallback.setSamlVersion(SAMLVersion.VERSION_11);
} else if (tokenType == SamlTokenType.WssSamlV20Token11) {
samlCallback.setSamlVersion(SAMLVersion.VERSION_20);
}
SAMLUtil.doSAMLCallback(handler, samlCallback);
SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
if (samlCallback.isSignAssertion()) {
String issuerName = samlCallback.getIssuerKeyName();
if (issuerName == null) {
String userNameKey = SecurityConstants.SIGNATURE_USERNAME;
issuerName = (String)message.getContextualProperty(userNameKey);
}
String password = samlCallback.getIssuerKeyPassword();
if (password == null) {
password = getPassword(issuerName, token, WSPasswordCallback.SIGNATURE);
}
Crypto crypto = samlCallback.getIssuerCrypto();
if (crypto == null) {
crypto = getSignatureCrypto(null);
}
assertion.signAssertion(
issuerName,
password,
crypto,
samlCallback.isSendKeyValue(),
samlCallback.getCanonicalizationAlgorithm(),
samlCallback.getSignatureAlgorithm()
);
}
return assertion;
}
/**
* Store a SAML Assertion as a SecurityToken
*/
protected void storeAssertionAsSecurityToken(SamlAssertionWrapper assertion) {
String id = findIDFromSamlToken(assertion.getElement());
if (id == null) {
return;
}
SecurityToken secToken = new SecurityToken(id);
if (assertion.getSaml2() != null) {
secToken.setTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
} else {
secToken.setTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
}
secToken.setToken(assertion.getElement());
getTokenStore().add(secToken);
message.setContextualProperty(SecurityConstants.TOKEN_ID, secToken.getId());
}
protected String findIDFromSamlToken(Element samlToken) {
String id = null;
if (samlToken != null) {
QName elName = DOMUtils.getElementQName(samlToken);
if (elName.equals(new QName(WSConstants.SAML_NS, "Assertion"))
&& samlToken.hasAttributeNS(null, "AssertionID")) {
id = samlToken.getAttributeNS(null, "AssertionID");
} else if (elName.equals(new QName(WSConstants.SAML2_NS, "Assertion"))
&& samlToken.hasAttributeNS(null, "ID")) {
id = samlToken.getAttributeNS(null, "ID");
}
if (id == null) {
id = samlToken.getAttributeNS(WSConstants.WSU_NS, "Id");
}
}
return id;
}
public String getPassword(String userName, Assertion info, int usage) {
//Then try to get the password from the given callback handler
CallbackHandler handler = getCallbackHandler();
if (handler == null) {
policyNotAsserted(info, "No callback handler and no password available");
return null;
}
WSPasswordCallback[] cb = {new WSPasswordCallback(userName, usage)};
try {
handler.handle(cb);
} catch (Exception e) {
policyNotAsserted(info, e);
}
//get the password
return cb[0].getPassword();
}
protected CallbackHandler getCallbackHandler() {
Object o = message.getContextualProperty(SecurityConstants.CALLBACK_HANDLER);
CallbackHandler handler = null;
if (o instanceof CallbackHandler) {
handler = (CallbackHandler)o;
} else if (o instanceof String) {
try {
handler = (CallbackHandler)ClassLoaderUtils
.loadClass((String)o, this.getClass()).newInstance();
message.setContextualProperty(SecurityConstants.CALLBACK_HANDLER, handler);
} catch (Exception e) {
handler = null;
}
}
return handler;
}
/**
* Generates a wsu:Id attribute for the provided {@code Element} and returns the attribute value
* or finds and returns the value of the attribute if it already exists.
*
* @param element the {@code Element} to check/create the attribute on
*
* @return the generated or discovered wsu:Id attribute value
*/
public String addWsuIdToElement(Element elem) {
String id;
//first try to get the Id attr
Attr idAttr = elem.getAttributeNodeNS(null, "Id");
if (idAttr == null) {
//then try the wsu:Id value
idAttr = elem.getAttributeNodeNS(PolicyConstants.WSU_NAMESPACE_URI, "Id");
}
if (idAttr != null) {
id = idAttr.getValue();
} else {
//Add an id
id = wssConfig.getIdAllocator().createId("_", elem);
String pfx = null;
try {
pfx = elem.lookupPrefix(PolicyConstants.WSU_NAMESPACE_URI);
} catch (Throwable t) {
pfx = DOMUtils.getPrefixRecursive(elem, PolicyConstants.WSU_NAMESPACE_URI);
}
boolean found = !StringUtils.isEmpty(pfx);
int cnt = 0;
while (StringUtils.isEmpty(pfx)) {
pfx = "wsu" + (cnt == 0 ? "" : cnt);
String ns;
try {
ns = elem.lookupNamespaceURI(pfx);
} catch (Throwable t) {
ns = DOMUtils.getNamespace(elem, pfx);
}
if (!StringUtils.isEmpty(ns)) {
pfx = null;
cnt++;
}
}
if (!found) {
idAttr = elem.getOwnerDocument().createAttributeNS(WSDLConstants.NS_XMLNS, "xmlns:" + pfx);
idAttr.setValue(PolicyConstants.WSU_NAMESPACE_URI);
elem.setAttributeNodeNS(idAttr);
}
idAttr = elem.getOwnerDocument().createAttributeNS(PolicyConstants.WSU_NAMESPACE_URI,
pfx + ":Id");
idAttr.setValue(id);
elem.setAttributeNodeNS(idAttr);
}