-
Notifications
You must be signed in to change notification settings - Fork 8
/
MessageSecurityContext.java
executable file
·946 lines (829 loc) · 33.9 KB
/
MessageSecurityContext.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
/*
* GovWay - A customizable API Gateway
* https://govway.org
*
* Copyright (c) 2005-2024 Link.it srl (https://link.it).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3, as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openspcoop2.security.message;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPPart;
import org.apache.wss4j.common.ConfigurationConstants;
import org.apache.wss4j.common.ext.WSPasswordCallback;
import org.openspcoop2.core.id.IDServizio;
import org.openspcoop2.core.id.IDSoggetto;
import org.openspcoop2.core.mvc.properties.utils.DBPropertiesUtils;
import org.openspcoop2.core.mvc.properties.utils.MultiPropertiesUtilities;
import org.openspcoop2.core.transazioni.utils.TempiElaborazione;
import org.openspcoop2.message.MessageUtils;
import org.openspcoop2.message.OpenSPCoop2Message;
import org.openspcoop2.message.OpenSPCoop2MessageFactory;
import org.openspcoop2.message.OpenSPCoop2SoapMessage;
import org.openspcoop2.message.constants.MessageRole;
import org.openspcoop2.message.constants.MessageType;
import org.openspcoop2.message.constants.ServiceBinding;
import org.openspcoop2.message.soap.SoapUtils;
import org.openspcoop2.message.soap.reference.Reference;
import org.openspcoop2.message.xml.XPathExpressionEngine;
import org.openspcoop2.protocol.sdk.Busta;
import org.openspcoop2.protocol.sdk.constants.CodiceErroreCooperazione;
import org.openspcoop2.security.SecurityException;
import org.openspcoop2.security.message.constants.SecurityConstants;
import org.openspcoop2.security.message.saml.SAMLConstants;
import org.openspcoop2.security.message.utils.EncryptionBean;
import org.openspcoop2.security.message.utils.SignatureBean;
import org.openspcoop2.utils.LoggerWrapperFactory;
import org.openspcoop2.utils.digest.IDigestReader;
import org.openspcoop2.utils.properties.PropertiesUtilities;
import org.openspcoop2.utils.resources.ClassLoaderUtilities;
import org.openspcoop2.utils.xml.AbstractXPathExpressionEngine;
import org.openspcoop2.utils.xml.DynamicNamespaceContext;
import org.openspcoop2.utils.xml.XPathNotFoundException;
import org.openspcoop2.utils.xml.XPathReturnType;
import org.slf4j.Logger;
/**
* Classe di base per la gestione della sicurezza
*
* @author Spadafora Marcello (Ma.Spadafora@finsiel.it)
* @author $Author$
* @version $Rev$, $Date$
*/
public abstract class MessageSecurityContext{
protected Map<String,Object> incomingProperties = new HashMap<>();
protected Map<String,Object> outgoingProperties = new HashMap<>();
protected boolean useActorDefaultIfNotDefined = true;
protected String actorDefault = null;
protected String actor;
protected String msgErrore;
protected CodiceErroreCooperazione codiceErrore;
/** Eventuale subCodici di errore */
protected List<SubErrorCodeSecurity> listaSubCodiceErrore = new ArrayList<>();
protected boolean functionAsClient = true;
protected String prefixWsuId;
protected boolean removeAllWsuIdRef;
protected String securityEngine;
protected IMessageSecurityContext messageSecurityContext;
protected IMessageSecuritySender messageSecuritySender;
protected IMessageSecurityReceiver messageSecurityReceiver;
protected IMessageSecurityDigest messageSecurityDigest;
protected Logger log;
public Logger getLog() {
return this.log;
}
private IDSoggetto idFruitore;
private String pddFruitore;
private IDServizio idServizio;
private String pddErogatore;
public IDSoggetto getIdFruitore() {
return this.idFruitore;
}
public IDServizio getIdServizio() {
return this.idServizio;
}
public String getPddFruitore() {
return this.pddFruitore;
}
public String getPddErogatore() {
return this.pddErogatore;
}
private List<Reference> references;
public List<Reference> getReferences() {
return this.references;
}
public void setReferences(List<Reference> references) {
this.references = references;
}
// I due encrypt part servono per un utilizzo manuale delle classi di sicurezza
private String manualAttachmentsEncryptPart = null;
private String manualAttachmentsSignaturePart = null;
public String getManualAttachmentsEncryptPart() {
return this.manualAttachmentsEncryptPart;
}
public void setManualAttachmentsEncryptPart(String manualAttachmentsEncryptPart) {
this.manualAttachmentsEncryptPart = manualAttachmentsEncryptPart;
}
public String getManualAttachmentsSignaturePart() {
return this.manualAttachmentsSignaturePart;
}
public void setManualAttachmentsSignaturePart(String manualAttachmentsSignaturePart) {
this.manualAttachmentsSignaturePart = manualAttachmentsSignaturePart;
}
// I due bean signatureBean e encryptionBean servono per un utilizzo manuale delle classi di sicurezza.
private SignatureBean signatureBean;
private EncryptionBean encryptionBean;
public SignatureBean getSignatureBean() {
return this.signatureBean;
}
public void setSignatureBean(SignatureBean signatureBean) {
this.signatureBean = signatureBean;
}
public EncryptionBean getEncryptionBean() {
return this.encryptionBean;
}
public void setEncryptionBean(EncryptionBean encryptionBean) {
this.encryptionBean = encryptionBean;
}
/**
* Costruttore.
*
* @param messageSecurityContextParameters contextParameters
*/
protected MessageSecurityContext(MessageSecurityContextParameters messageSecurityContextParameters){
this.useActorDefaultIfNotDefined = messageSecurityContextParameters.isUseActorDefaultIfNotDefined();
this.actorDefault = messageSecurityContextParameters.getActorDefault();
if(messageSecurityContextParameters.getLog()!=null)
this.log = messageSecurityContextParameters.getLog();
else
this.log = LoggerWrapperFactory.getLogger(MessageSecurityContext.class);
this.functionAsClient = messageSecurityContextParameters.isFunctionAsClient();
this.prefixWsuId = messageSecurityContextParameters.getPrefixWsuId();
this.removeAllWsuIdRef = messageSecurityContextParameters.isRemoveAllWsuIdRef();
this.idFruitore = messageSecurityContextParameters.getIdFruitore();
this.idServizio = messageSecurityContextParameters.getIdServizio();
this.pddFruitore = messageSecurityContextParameters.getPddFruitore();
this.pddErogatore = messageSecurityContextParameters.getPddErogatore();
}
/** Process */
// incoming
protected abstract boolean processIncoming(OpenSPCoop2Message message, Busta busta, org.openspcoop2.utils.Map<Object> ctx);
public boolean processIncoming(OpenSPCoop2Message message, Busta busta, org.openspcoop2.utils.Map<Object> ctx, TempiElaborazione tempiElaborazione) {
MessageRole messageRole = message.getMessageRole();
if(MessageRole.REQUEST.equals(messageRole)) {
if(tempiElaborazione!=null) {
tempiElaborazione.startSicurezzaMessaggioRichiesta();
}
}
else {
if(tempiElaborazione!=null) {
tempiElaborazione.startSicurezzaMessaggioRisposta();
}
}
try {
return this.processIncoming(message, busta, ctx);
}
finally {
if(MessageRole.REQUEST.equals(messageRole)) {
if(tempiElaborazione!=null) {
tempiElaborazione.endSicurezzaMessaggioRichiesta();
}
}
else {
if(tempiElaborazione!=null) {
tempiElaborazione.endSicurezzaMessaggioRisposta();
}
}
}
}
// outcoming
protected abstract boolean processOutgoing(OpenSPCoop2Message message, org.openspcoop2.utils.Map<Object> ctx);
public boolean processOutgoing(OpenSPCoop2Message message, org.openspcoop2.utils.Map<Object> ctx, TempiElaborazione tempiElaborazione) {
MessageRole messageRole = message.getMessageRole();
if(MessageRole.REQUEST.equals(messageRole)) {
if(tempiElaborazione!=null) {
tempiElaborazione.startSicurezzaMessaggioRichiesta();
}
}
else {
if(tempiElaborazione!=null) {
tempiElaborazione.startSicurezzaMessaggioRisposta();
}
}
try {
return this.processOutgoing(message, ctx);
}
finally {
if(MessageRole.REQUEST.equals(messageRole)) {
if(tempiElaborazione!=null) {
tempiElaborazione.endSicurezzaMessaggioRichiesta();
}
}
else {
if(tempiElaborazione!=null) {
tempiElaborazione.endSicurezzaMessaggioRisposta();
}
}
}
}
/** Function As Client */
public void setFunctionAsClient(boolean functionAsClient) {
this.functionAsClient = functionAsClient;
}
public boolean isFunctionAsClient() {
return this.functionAsClient;
}
/** Prefix WSUID */
public String getPrefixWsuId() {
return this.prefixWsuId;
}
/** indicazione se rimuovere tutti gli attributi WsuId negli elementi 'toccati' dalla sicurezza */
public boolean isRemoveAllWsuIdRef() {
return this.removeAllWsuIdRef;
}
/** GetValues ottenuti dopo il processamento */
public abstract String getSubject();
public String getMsgErrore() { return this.msgErrore; }
public CodiceErroreCooperazione getCodiceErrore() { return this.codiceErrore; }
public List<SubErrorCodeSecurity> getListaSubCodiceErrore() {
return this.listaSubCodiceErrore;
}
/** Actor utilizzato nell'header di sicurezza */
/**
* Set/get dell'Actor
*/
public String getActor() {
return this.actor;
}
private void setActor(boolean incoming) {
boolean actorDefinito = false;
boolean mustUnderstandTrue=false;
Map<String,Object> securityProperties = null;
if(incoming){
securityProperties = this.incomingProperties;
}else{
securityProperties = this.outgoingProperties;
}
if (securityProperties != null && securityProperties.size() > 0) {
for (String key : securityProperties.keySet()) {
String value = null;
Object oValue = securityProperties.get(key);
if(oValue instanceof String) {
value = (String) oValue;
}
/**System.out.println(key + " -> " + value );*/
// check actor
if(ConfigurationConstants.ACTOR.equals(key)){
this.actor = value;
}
// Check Fix Bug#18 Test-1
if(ConfigurationConstants.MUST_UNDERSTAND.equals(key)){
if("true".equals(value)){
mustUnderstandTrue = true;
}
}else if("actor".equals(key)){
actorDefinito = true;
}
}
}
if(mustUnderstandTrue && actorDefinito==false && this.useActorDefaultIfNotDefined ){
// Aggiungo actor 'govway'
this.actor = this.actorDefault;
}
}
/** Security Message Properties */
/**
* Set/get proprieta' che verranno usate per i messaggi in ingresso dal MessageSecurity
* @param secProperties
*/
public void setIncomingProperties(Map<String,Object> secProperties) throws SecurityException{
this.setIncomingProperties(secProperties, true, false);
}
public void setIncomingProperties(Map<String,Object> secProperties, boolean convertSecProperties) throws SecurityException{
this.setIncomingProperties(secProperties, convertSecProperties, false);
}
public void setIncomingProperties(Map<String,Object> secProperties, boolean convertSecProperties, boolean preserveNotStringProperty) throws SecurityException{
if(secProperties!=null && secProperties.size()>0 && convertSecProperties) {
this.incomingProperties = convertSecProperties(secProperties, preserveNotStringProperty);
}
else {
this.incomingProperties = secProperties;
}
this.setActor(true);
this.readMessageSecurityEngine(true);
this.resolvePWCallback(true);
}
public Map<String,Object> getIncomingProperties() {
return this.incomingProperties;
}
/**
* Set/get proprieta' che verranno usate per i messaggi in uscita dal MessageSecurity
* @param secProperties
*/
public void setOutgoingProperties(Map<String,Object> secProperties) throws SecurityException{
this.setOutgoingProperties(secProperties, true, false);
}
public void setOutgoingProperties(Map<String,Object> secProperties, boolean convertSecProperties) throws SecurityException{
this.setOutgoingProperties(secProperties, convertSecProperties, false);
}
public void setOutgoingProperties(Map<String,Object> secProperties, boolean convertSecProperties, boolean preserveNotStringProperty) throws SecurityException{
if(secProperties!=null && secProperties.size()>0 && convertSecProperties) {
this.outgoingProperties = convertSecProperties(secProperties, preserveNotStringProperty);
}
else {
this.outgoingProperties = secProperties;
}
this.setActor(false);
this.readMessageSecurityEngine(false);
this.resolvePWCallback(false);
}
public Map<String,Object> getOutgoingProperties() {
return this.outgoingProperties;
}
private Map<String,Object> convertSecProperties(Map<String,Object> secProperties, boolean preserveNotStringProperty) throws SecurityException{
try {
Map<String, Object> mapNoStringProperty = new HashMap<>();
Map<String, String> map = new HashMap<>();
if (secProperties != null && secProperties.size() > 0) {
for (String key : secProperties.keySet()) {
Object value = secProperties.get(key);
String v = null;
if(value instanceof String) {
v = (String) value;
}
map.put(key, v);
if(preserveNotStringProperty &&
value!=null && !(value instanceof String)) {
mapNoStringProperty.put(key, value);
}
}
}
Map<String, Properties> multiMap = DBPropertiesUtils.toMultiMap(map);
Map<String, Object> table = new HashMap<>();
Properties defaultProperties = MultiPropertiesUtilities.removeDefaultProperties(multiMap);
if(defaultProperties!=null && defaultProperties.size()>0) {
Iterator<?> it = defaultProperties.keySet().iterator();
while (it.hasNext()) {
Object oKey = it.next();
if(oKey instanceof String) {
String key = (String) oKey;
String value = null;
Object oValue = defaultProperties.get(key);
if(oValue instanceof String) {
value = (String) oValue;
}
table.put(key, value);
}
}
}
if(multiMap.size()>0) { // ho rimosso la mappa di default
if(preserveNotStringProperty && mapNoStringProperty.size()>0) {
List<String> keysMultiMap = new ArrayList<>();
keysMultiMap.addAll(multiMap.keySet());
Iterator<String> it = mapNoStringProperty.keySet().iterator();
while (it.hasNext()) {
String keyWithPrefix = it.next();
Object object = mapNoStringProperty.get(keyWithPrefix);
String prefix = DBPropertiesUtils.startsWith(keysMultiMap, keyWithPrefix);
if(prefix==null) {
table.put(keyWithPrefix, object);
}
else {
String keyWithoutPrefix = DBPropertiesUtils.normalizePropertyName(prefix, keyWithPrefix);
multiMap.get(prefix).put(keyWithoutPrefix, object);
}
}
}
table.putAll(multiMap);
}
else {
if(preserveNotStringProperty && mapNoStringProperty.size()>0) {
table.putAll(mapNoStringProperty);
}
}
return table;
}catch(Exception e) {
throw new SecurityException(e.getMessage(),e);
}
}
/** Message Security Engine */
public String getSecurityEngine() {
return this.securityEngine;
}
public IMessageSecurityContext getMessageSecurityContext() {
return this.messageSecurityContext;
}
public IMessageSecuritySender getMessageSecuritySender() {
return this.messageSecuritySender;
}
public IMessageSecurityReceiver getMessageSecurityReceiver() {
return this.messageSecurityReceiver;
}
public IMessageSecurityDigest getMessageSecurityDigest() {
return this.messageSecurityDigest;
}
public IDigestReader getDigestReader(OpenSPCoop2MessageFactory messageFactory) throws SecurityException{
if(this.messageSecurityDigest!=null){
return this.getMessageSecurityDigest().getDigestReader(messageFactory, this);
}
return null;
}
private void readMessageSecurityEngine(boolean incoming) throws SecurityException{
try{
this.securityEngine = SecurityConstants.SECURITY_ENGINE_WSS4J;
String engineProperty = null;
if(incoming){
engineProperty = (String) this.incomingProperties.get(SecurityConstants.SECURITY_ENGINE);
}else{
engineProperty = (String) this.outgoingProperties.get(SecurityConstants.SECURITY_ENGINE);
}
if(engineProperty!=null){
engineProperty = engineProperty.trim();
if(SecurityConstants.SECURITY_ENGINE_WSS4J.equals(engineProperty)){
// DEFAULT: this.securityEngine = SecurityConstants.SECURITY_ENGINE_WSS4J;
}
else if(SecurityConstants.SECURITY_ENGINE_SOAPBOX.equals(engineProperty)){
this.securityEngine = SecurityConstants.SECURITY_ENGINE_SOAPBOX;
}
else if(SecurityConstants.SECURITY_ENGINE_JOSE.equals(engineProperty)){
this.securityEngine = SecurityConstants.SECURITY_ENGINE_JOSE;
}
else if(SecurityConstants.SECURITY_ENGINE_XML.equals(engineProperty)){
this.securityEngine = SecurityConstants.SECURITY_ENGINE_XML;
}
else{
throw new SecurityException("Security engine impostato ["+engineProperty+"] non supportato");
}
}
if(SecurityConstants.SECURITY_ENGINE_WSS4J.equals(this.securityEngine)){
this.messageSecurityContext = (IMessageSecurityContext) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.wss4j.MessageSecurityContext_wss4j");
this.messageSecuritySender = (IMessageSecuritySender) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.wss4j.MessageSecuritySender_wss4j");
this.messageSecurityReceiver = (IMessageSecurityReceiver) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.wss4j.MessageSecurityReceiver_wss4j");
this.messageSecurityDigest = (IMessageSecurityDigest) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.wss4j.MessageSecurityDigest_wss4j");
}else if(SecurityConstants.SECURITY_ENGINE_SOAPBOX.equals(this.securityEngine)){
this.messageSecurityContext = (IMessageSecurityContext) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.soapbox.MessageSecurityContext_soapbox");
this.messageSecuritySender = (IMessageSecuritySender) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.soapbox.MessageSecuritySender_soapbox");
this.messageSecurityReceiver = (IMessageSecurityReceiver) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.soapbox.MessageSecurityReceiver_soapbox");
this.messageSecurityDigest = (IMessageSecurityDigest) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.soapbox.MessageSecurityDigest_soapbox");
}else if(SecurityConstants.SECURITY_ENGINE_JOSE.equals(this.securityEngine)){
this.messageSecurityContext = (IMessageSecurityContext) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.jose.MessageSecurityContext_jose");
this.messageSecuritySender = (IMessageSecuritySender) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.jose.MessageSecuritySender_jose");
this.messageSecurityReceiver = (IMessageSecurityReceiver) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.jose.MessageSecurityReceiver_jose");
this.messageSecurityDigest = (IMessageSecurityDigest) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.jose.MessageSecurityDigest_jose");
}else if(SecurityConstants.SECURITY_ENGINE_XML.equals(this.securityEngine)){
this.messageSecurityContext = (IMessageSecurityContext) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.xml.MessageSecurityContext_xml");
this.messageSecuritySender = (IMessageSecuritySender) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.xml.MessageSecuritySender_xml");
this.messageSecurityReceiver = (IMessageSecurityReceiver) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.xml.MessageSecurityReceiver_xml");
this.messageSecurityDigest = (IMessageSecurityDigest) ClassLoaderUtilities.newInstance("org.openspcoop2.security.message.xml.MessageSecurityDigest_xml");
}
this.messageSecurityContext.init(this);
}catch(Exception e){
throw new SecurityException(e.getMessage(),e);
}
}
/** resolvePWCallback */
private void resolvePWCallback(boolean incoming) throws SecurityException{
try{
Map<String, Object> props = null;
if(incoming) {
props = this.incomingProperties;
}else {
props = this.outgoingProperties;
}
boolean pwCallback = props.containsKey(SecurityConstants.PASSWORD_CALLBACK_REF); // non controllo il valore, mi basta la presenza
props.remove(SecurityConstants.PASSWORD_CALLBACK_REF);
if(pwCallback) {
String aliasGenerico = null;
if(props.containsKey(SecurityConstants.USER)) {
aliasGenerico = (String) props.get(SecurityConstants.USER);
}
HashMap<String, String> mapAliasToPassword = new HashMap<>();
if(props.containsKey(SecurityConstants.SIGNATURE_PASSWORD)) {
String password = (String) props.get(SecurityConstants.SIGNATURE_PASSWORD);
String alias = null;
if(props.containsKey(SecurityConstants.SIGNATURE_USER)) {
alias = (String) props.get(SecurityConstants.SIGNATURE_USER);
}
else {
alias = aliasGenerico;
}
if(alias!=null){
mapAliasToPassword.put(alias, password);
}
}
if(props.containsKey(SecurityConstants.ENCRYPTION_PASSWORD)) {
String password = (String) props.get(SecurityConstants.ENCRYPTION_PASSWORD);
String alias = null;
if(props.containsKey(SecurityConstants.ENCRYPTION_USER)) {
alias = (String) props.get(SecurityConstants.ENCRYPTION_USER);
}
else {
alias = aliasGenerico;
}
if(alias!=null){
mapAliasToPassword.put(alias, password);
}
}
if(props.containsKey(SecurityConstants.DECRYPTION_PASSWORD)) {
String password = (String) props.get(SecurityConstants.DECRYPTION_PASSWORD);
String alias = null;
if(props.containsKey(SecurityConstants.DECRYPTION_USER)) {
alias = (String) props.get(SecurityConstants.DECRYPTION_USER);
}
else {
alias = aliasGenerico;
}
if(alias!=null){
mapAliasToPassword.put(alias, password);
}
}
if(props.containsKey(SecurityConstants.USERNAME_TOKEN_PW)) {
String password = (String) props.get(SecurityConstants.USERNAME_TOKEN_PW);
String alias = aliasGenerico;
if(alias!=null){
mapAliasToPassword.put(alias, password);
}
}
if(props.containsKey(SecurityConstants.USERNAME_TOKEN_PW_MAP)) {
String mapUserPassword = (String) props.get(SecurityConstants.USERNAME_TOKEN_PW_MAP);
if(mapUserPassword!=null && !"".equals(mapUserPassword)) {
Properties convertTextToProperties = PropertiesUtilities.convertTextToProperties(mapUserPassword);
if(convertTextToProperties!=null && !convertTextToProperties.isEmpty()) {
for (Map.Entry<Object,Object> entry : convertTextToProperties.entrySet()) {
if((entry.getKey() instanceof String) && (entry.getValue() instanceof String)) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
mapAliasToPassword.put(key, value);
}
}
}
}
}
if(mapAliasToPassword.size()>0) {
CallbackHandler pwCallbackHandler = newCallbackHandler(mapAliasToPassword);
props.put(SecurityConstants.PASSWORD_CALLBACK_REF, pwCallbackHandler);
}
}
}catch(Exception e){
throw new SecurityException(e.getMessage(),e);
}
}
public static CallbackHandler newCallbackHandler(Map<String, String> mapAliasToPassword) {
return new CallbackHandler() {
private Map<String, String> mapAliasToPasswordParam = mapAliasToPassword;
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof WSPasswordCallback) {
WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
if(this.mapAliasToPasswordParam.containsKey(pc.getIdentifier())) {
pc.setPassword(this.mapAliasToPasswordParam.get(pc.getIdentifier()));
}
} else {
throw new UnsupportedCallbackException(callbacks[i],
"Unrecognized Callback");
}
}
}
};
}
/** Utility per verificare l'esistenza di un header di sicurezza */
public boolean existsSecurityHeader(OpenSPCoop2Message msg,String actor){
SOAPHeader header = null;
try{
if(msg==null){
return false;
}
if(ServiceBinding.SOAP.equals(msg.getServiceBinding())){
OpenSPCoop2SoapMessage soapMsg = msg.castAsSoap();
header = soapMsg.getSOAPHeader();
}
else{
return true;
}
}catch(Exception e){
if(this.log!=null)
this.log.error("existsHeaderMessageSecurity error con actor["+actor+"]",e);
return false;
}
return existsSecurityHeader(msg.getFactory(), msg.getMessageType(),
header, actor);
}
public boolean existsSecurityHeader(OpenSPCoop2Message msg,String actor,
boolean bufferMessage_readOnly, String idTransazione){
SOAPEnvelope soapEnvelope = null;
try{
if(msg==null){
return false;
}
if(ServiceBinding.SOAP.equals(msg.getServiceBinding())){
OpenSPCoop2SoapMessage soapMsg = msg.castAsSoap();
SOAPPart soapPart = MessageUtils.getSOAPPart(soapMsg, bufferMessage_readOnly, idTransazione);
if(soapPart!=null) {
soapEnvelope = soapPart.getEnvelope();
}
}
else{
return true;
}
}catch(Exception e){
if(this.log!=null)
this.log.error("existsHeaderMessageSecurity error con actor["+actor+"]",e);
return false;
}
return existsSecurityHeader(msg.getFactory(), msg.getMessageType(),
soapEnvelope, actor);
}
public boolean existsSecurityHeader(OpenSPCoop2MessageFactory messageFactory, MessageType messageType,
SOAPEnvelope soapEnvelope,String actor){
SOAPHeader header = null;
try{
header = soapEnvelope.getHeader();
}catch(Exception e){
if(this.log!=null)
this.log.error("existsHeaderMessageSecurity error con actor["+actor+"]",e);
return false;
}
return existsSecurityHeader(messageFactory, messageType,
header, actor);
}
public boolean existsSecurityHeader(OpenSPCoop2MessageFactory messageFactory, MessageType messageType,
SOAPHeader header,String actor){
try{
if(header==null || (SoapUtils.getNotEmptyChildNodes(messageFactory, header).isEmpty()) ){
return false;
}
java.util.Iterator<?> it = header.examineAllHeaderElements();
while( it.hasNext() ){
// Test Header Element
SOAPHeaderElement headerElement = (SOAPHeaderElement) it.next();
if( SecurityConstants.WSS_HEADER_ELEMENT.equals(headerElement.getLocalName()) &&
SecurityConstants.WSS_HEADER_ELEMENT_NAMESPACE.equals(headerElement.getNamespaceURI()) ){
// potenziale header, verifico l'actor
String actorCheck = SoapUtils.getSoapActor(headerElement, messageType);
if(actor==null){
if(actorCheck==null) {
return true;
}
}else{
if(actor.equals(actorCheck)) {
return true;
}
}
}
}
return false;
}catch(Exception e){
if(this.log!=null)
this.log.error("existsHeaderMessageSecurity error con actor["+actor+"]",e);
return false;
}
}
public SOAPHeaderElement getSecurityHeader(OpenSPCoop2Message msg,String actor){
SOAPHeader header = null;
try{
if(msg==null){
return null;
}
if(ServiceBinding.SOAP.equals(msg.getServiceBinding())){
OpenSPCoop2SoapMessage soapMsg = msg.castAsSoap();
header = soapMsg.getSOAPHeader();
}
else{
return null;
}
}catch(Exception e){
if(this.log!=null)
this.log.error("getHeaderMessageSecurity error con actor["+actor+"]",e);
return null;
}
return getSecurityHeader(msg.getFactory(), msg.getMessageType(),
header, actor);
}
public SOAPHeaderElement getSecurityHeader(OpenSPCoop2Message msg,String actor,
boolean bufferMessageReadOnly, String idTransazione){
SOAPEnvelope soapEnvelope = null;
try{
if(msg==null){
return null;
}
if(ServiceBinding.SOAP.equals(msg.getServiceBinding())){
OpenSPCoop2SoapMessage soapMsg = msg.castAsSoap();
SOAPPart soapPart = MessageUtils.getSOAPPart(soapMsg, bufferMessageReadOnly, idTransazione);
if(soapPart!=null) {
soapEnvelope = soapPart.getEnvelope();
}
}
else{
return null;
}
}catch(Exception e){
if(this.log!=null)
this.log.error("getHeaderMessageSecurity error con actor["+actor+"]",e);
return null;
}
return getSecurityHeader(msg.getFactory(), msg.getMessageType(),
soapEnvelope, actor);
}
public SOAPHeaderElement getSecurityHeader(OpenSPCoop2MessageFactory messageFactory, MessageType messageType,
SOAPEnvelope soapEnvelope,String actor){
SOAPHeader header = null;
try{
header = soapEnvelope.getHeader();
}catch(Exception e){
if(this.log!=null)
this.log.error("getHeaderMessageSecurity error con actor["+actor+"]",e);
return null;
}
return getSecurityHeader(messageFactory, messageType,
header, actor);
}
public SOAPHeaderElement getSecurityHeader(OpenSPCoop2MessageFactory messageFactory, MessageType messageType,
SOAPHeader header,String actor){
try{
if(header==null || (SoapUtils.getNotEmptyChildNodes(messageFactory, header).isEmpty()) ){
return null;
}
java.util.Iterator<?> it = header.examineAllHeaderElements();
while( it.hasNext() ){
// Test Header Element
SOAPHeaderElement headerElement = (SOAPHeaderElement) it.next();
if( SecurityConstants.WSS_HEADER_ELEMENT.equals(headerElement.getLocalName()) &&
SecurityConstants.WSS_HEADER_ELEMENT_NAMESPACE.equals(headerElement.getNamespaceURI()) ){
// potenziale header, verifico l'actor
String actorCheck = SoapUtils.getSoapActor(headerElement, messageType);
if(actor==null){
if(actorCheck==null) {
return headerElement;
}
}else{
if(actor.equals(actorCheck)) {
return headerElement;
}
}
}
}
return null;
}catch(Exception e){
if(this.log!=null)
this.log.error("getHeaderMessageSecurity error con actor["+actor+"]",e);
return null;
}
}
/** Utility per verificare l'esistenza di un header di sicurezza */
public SOAPElement getSAMLTokenInSecurityHeader(OpenSPCoop2MessageFactory messageFactory, SOAPHeaderElement securityHeader,String samlVersion){
try{
SOAPElement samlElement = null;
DynamicNamespaceContext dnc = new DynamicNamespaceContext();
dnc.findPrefixNamespace(securityHeader);
AbstractXPathExpressionEngine xpathExpressionEngine = new XPathExpressionEngine(messageFactory);
String xpath =null;
if(SecurityConstants.SAML_VERSION_XMLCONFIG_ID_VALUE_20.equals(samlVersion)) {
xpath = SAMLConstants.XPATH_SAML_20_ASSERTION;
}
else {
xpath = SAMLConstants.XPATH_SAML_11_ASSERTION;
}
try {
Object o = xpathExpressionEngine.getMatchPattern(securityHeader, dnc, xpath, XPathReturnType.NODE);
samlElement = (SOAPElement) o;
} catch(XPathNotFoundException e) {
// ignore
}
return samlElement;
}catch(Exception e){
if(this.log!=null)
this.log.error("getSAMLTokenInSecurityHeader error, saml version: ["+samlVersion+"]",e);
return null;
}
}
public String getSAMLTokenSubjectConfirmationMethodInSecurityHeader(OpenSPCoop2MessageFactory messageFactory, SOAPElement samlToken,String samlVersion){
try{
DynamicNamespaceContext dnc = new DynamicNamespaceContext();
dnc.findPrefixNamespace(samlToken);
AbstractXPathExpressionEngine xpathExpressionEngine = new XPathExpressionEngine(messageFactory);
String xpath =null;
if(SecurityConstants.SAML_VERSION_XMLCONFIG_ID_VALUE_20.equals(samlVersion)) {
xpath = SAMLConstants.XPATH_SAML_20_ASSERTION_SUBJECT_CONFIRMATION_METHOD;
}
else {
xpath = SAMLConstants.XPATH_SAML_11_ASSERTION_SUBJECT_CONFIRMATION_METHOD;
}
String method = null;
try {
Object o = xpathExpressionEngine.getMatchPattern(samlToken, dnc, xpath, XPathReturnType.STRING);
method = (String) o;
} catch(XPathNotFoundException e) {
// ignore
}
return method;
}catch(Exception e){
if(this.log!=null)
this.log.error("getSAMLTokenSubjectConfirmationMethodInSecurityHeader error, saml version: ["+samlVersion+"]",e);
return null;
}
}
}