/
SecurityMechanismSelector.java
1483 lines (1322 loc) · 62.6 KB
/
SecurityMechanismSelector.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
/*
* Copyright (c) 2023 Contributors to the Eclipse Foundation
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.enterprise.iiop.security;
import com.sun.corba.ee.org.omg.CSI.ITTAnonymous;
import com.sun.corba.ee.org.omg.CSI.ITTDistinguishedName;
import com.sun.corba.ee.org.omg.CSI.ITTPrincipalName;
import com.sun.corba.ee.org.omg.CSI.ITTX509CertChain;
import com.sun.corba.ee.org.omg.CSIIOP.AS_ContextSec;
import com.sun.corba.ee.org.omg.CSIIOP.CompoundSecMech;
import com.sun.corba.ee.org.omg.CSIIOP.Confidentiality;
import com.sun.corba.ee.org.omg.CSIIOP.DelegationByClient;
import com.sun.corba.ee.org.omg.CSIIOP.EstablishTrustInClient;
import com.sun.corba.ee.org.omg.CSIIOP.EstablishTrustInTarget;
import com.sun.corba.ee.org.omg.CSIIOP.IdentityAssertion;
import com.sun.corba.ee.org.omg.CSIIOP.Integrity;
import com.sun.corba.ee.org.omg.CSIIOP.SAS_ContextSec;
import com.sun.corba.ee.org.omg.CSIIOP.TLS_SEC_TRANS;
import com.sun.corba.ee.org.omg.CSIIOP.TransportAddress;
import com.sun.corba.ee.spi.ior.IOR;
import com.sun.corba.ee.spi.ior.iiop.IIOPAddress;
import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate;
import com.sun.corba.ee.spi.transport.SocketInfo;
import com.sun.enterprise.common.iiop.security.AnonCredential;
import com.sun.enterprise.common.iiop.security.GSSUPName;
import com.sun.enterprise.common.iiop.security.SecurityContext;
import com.sun.enterprise.deployment.EjbDescriptor;
import com.sun.enterprise.deployment.EjbIORConfigurationDescriptor;
import com.sun.enterprise.security.SecurityServicesUtil;
import com.sun.enterprise.security.auth.login.LoginContextDriver;
import com.sun.enterprise.security.auth.login.common.LoginException;
import com.sun.enterprise.security.auth.login.common.PasswordCredential;
import com.sun.enterprise.security.auth.login.common.X509CertificateCredential;
import com.sun.enterprise.security.auth.realm.Realm;
import com.sun.enterprise.security.common.ClientSecurityContext;
import com.sun.enterprise.security.common.SecurityConstants;
import com.sun.enterprise.security.ssl.SSLUtils;
import com.sun.enterprise.util.LocalStringManagerImpl;
import com.sun.enterprise.util.Utility;
import com.sun.logging.LogDomains;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import java.net.Socket;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.security.auth.Subject;
import javax.security.auth.x500.X500Principal;
import org.glassfish.api.admin.ProcessEnvironment;
import org.glassfish.api.admin.ProcessEnvironment.ProcessType;
import org.glassfish.api.invocation.ComponentInvocation;
import org.glassfish.api.invocation.InvocationManager;
import org.glassfish.enterprise.iiop.api.GlassFishORBHelper;
import org.glassfish.enterprise.iiop.api.ProtocolManager;
import org.glassfish.hk2.api.PostConstruct;
import org.glassfish.internal.api.ORBLocator;
import org.ietf.jgss.Oid;
import org.jvnet.hk2.annotations.Service;
import org.omg.CORBA.ORB;
import static com.sun.logging.LogDomains.SECURITY_LOGGER;
/**
* This class is responsible for making various decisions for selecting security information to be sent in the IIOP
* message based on target configuration and client policies. Note: This class can be called concurrently by multiple
* client threads. However, none of its methods need to be synchronized because the methods either do not modify state
* or are idempotent.
*
* @author Nithya Subramanian
*
*/
@Service
@Singleton
public final class SecurityMechanismSelector implements PostConstruct {
private static final Logger LOG = LogDomains.getLogger(SecurityMechanismSelector.class, SECURITY_LOGGER, false);
public static final String CLIENT_CONNECTION_CONTEXT = "ClientConnContext";
// public static final String SERVER_CONNECTION_CONTEXT = "ServerConnContext";
private Set<EjbIORConfigurationDescriptor> corbaIORDescSet;
private boolean sslRequired;
// List of hosts trusted by the client for sending passwords to.
// Also, list of hosts trusted by the server for accepting propagated
// identities.
// private static String[] serverTrustedHosts = null;
/**
* A reference to POAProtocolMgr will be obtained dynamically
* and set if not null. So set it to null here.
*/
private ProtocolManager protocolMgr;
@Inject
private SSLUtils sslUtils;
private GlassFishORBHelper orbHelper;
// private CompoundSecMech mechanism = null;
private ORB orb;
private CSIV2TaggedComponentInfo ctc;
@Inject
private InvocationManager invMgr;
@Inject
private ProcessEnvironment processEnv;
/**
* Read the client and server preferences from the config files.
*/
public SecurityMechanismSelector() {
}
@Override
public void postConstruct() {
try {
orbHelper = Lookups.getGlassFishORBHelper();
// Initialize client security config
String s = (orbHelper.getCSIv2Props()).getProperty(ORBLocator.ORB_SSL_CLIENT_REQUIRED);
if (s != null && s.equals("true")) {
sslRequired = true;
}
// initialize corbaIORDescSet with security config for CORBA objects
corbaIORDescSet = new HashSet<>();
EjbIORConfigurationDescriptor iorDesc = new EjbIORConfigurationDescriptor();
EjbIORConfigurationDescriptor iorDesc2 = new EjbIORConfigurationDescriptor();
String serverSslReqd = (orbHelper.getCSIv2Props()).getProperty(ORBLocator.ORB_SSL_SERVER_REQUIRED);
if (serverSslReqd != null && serverSslReqd.equals("true")) {
iorDesc.setIntegrity(EjbIORConfigurationDescriptor.REQUIRED);
iorDesc.setConfidentiality(EjbIORConfigurationDescriptor.REQUIRED);
iorDesc2.setIntegrity(EjbIORConfigurationDescriptor.REQUIRED);
iorDesc2.setConfidentiality(EjbIORConfigurationDescriptor.REQUIRED);
}
String clientAuthReq = (orbHelper.getCSIv2Props()).getProperty(ORBLocator.ORB_CLIENT_AUTH_REQUIRED);
if (clientAuthReq != null && clientAuthReq.equals("true")) {
// Need auth either by SSL or username-password.
// This sets SSL clientauth to required.
iorDesc.setEstablishTrustInClient(EjbIORConfigurationDescriptor.REQUIRED);
// This sets username-password auth to required.
iorDesc2.setAuthMethodRequired(true);
getCorbaIORDescSet().add(iorDesc2);
}
getCorbaIORDescSet().add(iorDesc);
} catch (Exception e) {
LOG.log(Level.SEVERE, "IIOP1005: An exception has occured in the ejb security initialization.", e);
}
}
public ConnectionContext getClientConnectionContext() {
Hashtable h = ConnectionExecutionContext.getContext();
ConnectionContext scc = (ConnectionContext) h.get(CLIENT_CONNECTION_CONTEXT);
return scc;
}
public void setClientConnectionContext(ConnectionContext scc) {
Hashtable h = ConnectionExecutionContext.getContext();
h.put(CLIENT_CONNECTION_CONTEXT, scc);
}
/**
* This method determines if SSL should be used to connect to the target based on client and target policies. It will
* return null if SSL should not be used or an SocketInfo containing the SSL port if SSL should be used.
*/
public SocketInfo getSSLPort(IOR ior, ConnectionContext ctx) {
SocketInfo info = null;
CompoundSecMech mechanism = null;
try {
mechanism = selectSecurityMechanism(ior);
} catch (SecurityMechanismException sme) {
throw new RuntimeException(sme.getMessage());
}
ctx.setIOR(ior);
ctx.setMechanism(mechanism);
TLS_SEC_TRANS ssl = null;
if (mechanism != null) {
ssl = getCtc().getSSLInformation(mechanism);
}
if (ssl == null) {
if (isSslRequired()) {
// Attempt to create SSL connection to host, ORBInitialPort
IIOPProfileTemplate templ = (IIOPProfileTemplate) ior.getProfile().getTaggedProfileTemplate();
IIOPAddress addr = templ.getPrimaryAddress();
info = IORToSocketInfoImpl.createSocketInfo("SecurityMechanismSelector1", "SSL", addr.getHost(), orbHelper.getORBPort(orbHelper.getORB()));
return info;
} else {
return null;
}
}
int targetRequires = ssl.target_requires;
int targetSupports = ssl.target_supports;
/*
* If target requires any of Integrity, Confidentiality or EstablishTrustInClient, then SSL is used.
*/
if (isSet(targetRequires, Integrity.value) || isSet(targetRequires, Confidentiality.value) || isSet(targetRequires, EstablishTrustInClient.value)) {
LOG.log(Level.FINE, "Target requires SSL");
ctx.setSSLUsed(true);
String type = "SSL";
if (isSet(targetRequires, EstablishTrustInClient.value)) {
type = "SSL_MUTUALAUTH";
ctx.setSSLClientAuthenticationOccurred(true);
}
short sslport = ssl.addresses[0].port;
int ssl_port = Utility.shortToInt(sslport);
String host_name = ssl.addresses[0].host_name;
info = IORToSocketInfoImpl.createSocketInfo("SecurityMechanismSelector2", type, host_name, ssl_port);
return info;
} else if (isSet(targetSupports, Integrity.value) || isSet(targetSupports, Confidentiality.value)
|| isSet(targetSupports, EstablishTrustInClient.value)) {
LOG.log(Level.FINE, "Target supports SSL");
if (!isSslRequired()) {
return null;
}
LOG.log(Level.FINE, "Client is configured to require SSL for the target");
ctx.setSSLUsed(true);
short sslport = ssl.addresses[0].port;
String host_name = ssl.addresses[0].host_name;
int ssl_port = Utility.shortToInt(sslport);
info = IORToSocketInfoImpl.createSocketInfo("SecurityMechanismSelector3", "SSL", host_name, ssl_port);
return info;
} else if (isSslRequired()) {
throw new RuntimeException("SSL required by client but not supported by server.");
} else {
return null;
}
}
/*
* public String[] getServerTrustedHosts() { return serverTrustedHosts; }
*
* public void setServerTrustedHosts(String[] val) { this.serverTrustedHosts = val; }
*/
public ORB getOrb() {
return orb;
}
public void setOrb(ORB val) {
this.orb = val;
}
public synchronized CSIV2TaggedComponentInfo getCtc() {
if (ctc == null) {
this.ctc = new CSIV2TaggedComponentInfo(orbHelper.getORB());
}
return ctc;
}
public java.util.List<SocketInfo> getSSLPorts(IOR ior, ConnectionContext ctx) {
CompoundSecMech mechanism = null;
try {
mechanism = selectSecurityMechanism(ior);
} catch (SecurityMechanismException sme) {
throw new RuntimeException(sme.getMessage());
}
ctx.setIOR(ior);
ctx.setMechanism(mechanism);
TLS_SEC_TRANS ssl = null;
if (mechanism != null) {
ssl = getCtc().getSSLInformation(mechanism);
}
if (ssl == null) {
if (isSslRequired()) {
// Attempt to create SSL connection to host, ORBInitialPort
IIOPProfileTemplate templ = (IIOPProfileTemplate) ior.getProfile().getTaggedProfileTemplate();
IIOPAddress addr = templ.getPrimaryAddress();
SocketInfo info = IORToSocketInfoImpl.createSocketInfo("SecurityMechanismSelector1", "SSL", addr.getHost(),
orbHelper.getORBPort(orbHelper.getORB()));
// SocketInfo[] sInfos = new SocketInfo[]{info};
List<SocketInfo> sInfos = new ArrayList<>();
sInfos.add(info);
return sInfos;
} else {
return null;
}
}
int targetRequires = ssl.target_requires;
int targetSupports = ssl.target_supports;
/*
* If target requires any of Integrity, Confidentiality or EstablishTrustInClient, then SSL is used.
*/
if (isSet(targetRequires, Integrity.value) || isSet(targetRequires, Confidentiality.value) || isSet(targetRequires, EstablishTrustInClient.value)) {
LOG.log(Level.FINE, "Target requires SSL");
ctx.setSSLUsed(true);
String type = "SSL";
if (isSet(targetRequires, EstablishTrustInClient.value)) {
type = "SSL_MUTUALAUTH";
ctx.setSSLClientAuthenticationOccurred(true);
}
// SocketInfo[] socketInfos = new SocketInfo[ssl.addresses.size];
List<SocketInfo> socketInfos = new ArrayList<>();
for (TransportAddress element : ssl.addresses) {
short sslport = element.port;
int ssl_port = Utility.shortToInt(sslport);
String host_name = element.host_name;
SocketInfo sInfo = IORToSocketInfoImpl.createSocketInfo("SecurityMechanismSelector2", type, host_name, ssl_port);
socketInfos.add(sInfo);
}
return socketInfos;
} else if (isSet(targetSupports, Integrity.value) || isSet(targetSupports, Confidentiality.value)
|| isSet(targetSupports, EstablishTrustInClient.value)) {
LOG.log(Level.FINE, "Target supports SSL");
if (!isSslRequired()) {
return null;
}
LOG.log(Level.FINE, "Client is configured to require SSL for the target");
ctx.setSSLUsed(true);
// SocketInfo[] socketInfos = new SocketInfo[ssl.addresses.size];
List<SocketInfo> socketInfos = new ArrayList<>();
for (TransportAddress element : ssl.addresses) {
short sslport = element.port;
int ssl_port = Utility.shortToInt(sslport);
String host_name = element.host_name;
SocketInfo sInfo = IORToSocketInfoImpl.createSocketInfo("SecurityMechanismSelector3", "SSL", host_name, ssl_port);
socketInfos.add(sInfo);
}
return socketInfos;
} else if (isSslRequired()) {
throw new RuntimeException("SSL required by client but not supported by server.");
} else {
return null;
}
}
/**
* Select the security context to be used by the CSIV2 layer based on whether the current component is an application
* client or a web/EJB component.
*/
public SecurityContext selectSecurityContext(IOR ior) throws InvalidIdentityTokenException, InvalidMechanismException, SecurityMechanismException {
SecurityContext context = null;
ConnectionContext cc = new ConnectionContext();
// print CSIv2 mechanism definition in IOR
if (traceIORs()) {
LOG.info("\nCSIv2 Mechanism List: " + getSecurityMechanismString(ctc, ior));
}
getSSLPort(ior, cc);
setClientConnectionContext(cc);
CompoundSecMech mechanism = cc.getMechanism();
if (mechanism == null) {
return null;
}
boolean sslUsed = cc.getSSLUsed();
boolean clientAuthOccurred = cc.getSSLClientAuthenticationOccurred();
// Standalone client
if (isNotServerOrACC()) {
context = getSecurityContextForAppClient(null, sslUsed, clientAuthOccurred, mechanism);
return context;
}
LOG.log(Level.FINE, "SSL used: {0}, SSL Mutual auth: {1}", new Object[] {sslUsed, clientAuthOccurred});
ComponentInvocation ci = null;
/*
* // BEGIN IASRI# 4646060 ci = invMgr.getCurrentInvocation(); if (ci == null) { // END IASRI# 4646060 return null; }
* Object obj = ci.getContainerContext();
*/
if (isACC()) {
context = getSecurityContextForAppClient(ci, sslUsed, clientAuthOccurred, mechanism);
} else {
context = getSecurityContextForWebOrEJB(ci, sslUsed, clientAuthOccurred, mechanism);
}
return context;
}
/**
* Create the security context to be used by the CSIV2 layer to marshal in the service context of the IIOP message from
* an appclient or standalone client.
*
* @return the security context.
*/
public SecurityContext getSecurityContextForAppClient(ComponentInvocation ci, boolean sslUsed, boolean clientAuthOccurred, CompoundSecMech mechanism)
throws InvalidMechanismException, InvalidIdentityTokenException, SecurityMechanismException {
return sendUsernameAndPassword(ci, sslUsed, clientAuthOccurred, mechanism);
}
/**
* Create the security context to be used by the CSIV2 layer to marshal in the service context of the IIOP message from
* an web component or EJB invoking another EJB.
*
* @return the security context.
*/
public SecurityContext getSecurityContextForWebOrEJB(ComponentInvocation ci, boolean sslUsed, boolean clientAuthOccurred, CompoundSecMech mechanism)
throws InvalidMechanismException, InvalidIdentityTokenException, SecurityMechanismException {
SecurityContext ctx = null;
if (!sslUsed) {
ctx = propagateIdentity(false, ci, mechanism);
} else {
ctx = propagateIdentity(clientAuthOccurred, ci, mechanism);
}
return ctx;
}
Object getSSLSocketInfo(Object ior) {
ConnectionContext ctx = new ConnectionContext();
List<SocketInfo> socketInfo = getSSLPorts((com.sun.corba.ee.spi.ior.IOR) ior, ctx);
setClientConnectionContext(ctx);
return socketInfo;
}
private boolean isMechanismSupported(SAS_ContextSec sas) {
byte[][] mechanisms = sas.supported_naming_mechanisms;
byte[] mechSupported = GSSUtils.getMechanism();
if (mechanisms == null) {
return false;
}
for (byte[] mechanism : mechanisms) {
if (Arrays.equals(mechSupported, mechanism)) {
return true;
}
}
return false;
}
public boolean isIdentityTypeSupported(SAS_ContextSec sas) {
int ident_token = sas.supported_identity_types;
// the identity token matches atleast one of the types we support
int value = ident_token & CSIV2TaggedComponentInfo.SUPPORTED_IDENTITY_TOKEN_TYPES;
if (value != 0) {
return true;
} else {
return false;
}
}
/**
* Get the security context to send username and password in the service context.
*
* @param whether username/password will be sent over plain IIOP or over IIOP/SSL.
* @return the security context.
* @exception SecurityMechanismException if there was an error.
*/
private SecurityContext sendUsernameAndPassword(ComponentInvocation ci, boolean sslUsed, boolean clientAuthOccurred, CompoundSecMech mechanism)
throws SecurityMechanismException {
SecurityContext ctx = null;
if (mechanism == null) {
return null;
}
AS_ContextSec asContext = mechanism.as_context_mech;
if (isSet(asContext.target_requires, EstablishTrustInClient.value)
|| (isSet(mechanism.target_requires, EstablishTrustInClient.value) && !clientAuthOccurred)) {
ctx = getUsernameAndPassword(ci, mechanism);
LOG.log(Level.FINE, "Sending Username/Password");
} else {
return null;
}
return ctx;
}
/**
* Get the security context to propagate principal/distinguished name in the service context.
*
* @param clientAuth whether SSL client authentication has happened.
* @return the security context.
* @exception SecurityMechanismException if there was an error.
*/
private SecurityContext propagateIdentity(boolean clientAuth, ComponentInvocation ci, CompoundSecMech mechanism)
throws InvalidIdentityTokenException, InvalidMechanismException, SecurityMechanismException {
SecurityContext ctx = null;
if (mechanism == null) {
return null;
}
AS_ContextSec asContext = mechanism.as_context_mech;
SAS_ContextSec sasContext = mechanism.sas_context_mech;
LOG.log(Level.FINE, "SAS CONTEXT's target_requires={0}", sasContext.target_requires);
LOG.log(Level.FINE, "SAS CONTEXT's target_supports={1}", sasContext.target_supports);
if (isSet(asContext.target_requires, EstablishTrustInClient.value)) {
ctx = getUsernameAndPassword(ci, mechanism);
if (ctx.authcls == null) {
// run as mode cannot send password
throw new SecurityMechanismException(
"Cannot propagate username/password required by target when using run as identity");
}
} else if (isSet(sasContext.target_supports, IdentityAssertion.value) || isSet(sasContext.target_requires, IdentityAssertion.value)) {
// called from the client side. thus before getting the identity. check the
// mechanisms and the identity token supported
if (!isIdentityTypeSupported(sasContext)) {
throw new InvalidIdentityTokenException("The given identity token is unsupported.");
}
if (sasContext.target_supports == IdentityAssertion.value) {
if (!isMechanismSupported(sasContext)) {
throw new InvalidMechanismException("The given mechanism type is unsupported.");
}
}
// propagate principal/certificate/distinguished name
ctx = getIdentity();
} else if (isSet(asContext.target_supports, EstablishTrustInClient.value)) {
if (clientAuth) { // client auth done we can send password
ctx = getUsernameAndPassword(ci, mechanism);
if (ctx.authcls == null) {
return null; // runas mode dont have username/password
// dont really need to send it too
}
} else { // not sending anything for unauthenticated client
return null;
}
} else {
return null; // will never come here
}
return ctx;
}
/**
* Return whether the server is trusted or not based on configuration information.
*
* @return true if the server is trusted.
*/
/*
* private boolean isServerTrusted() { String star = "*"; // first check if "*" in trusted - then why bother // doing
* all the processing . We trust everything // System.out.println (" In server trusted ??"); for (int i = 0; i <
* serverTrustedHosts.length; i++){ if (serverTrustedHosts[i].length () == 1) { if (serverTrustedHosts[i].equals (star))
* return true; } } ConnectionContext scc = getClientConnectionContext (); if (scc != null){ Socket skt = scc.getSocket
* (); InetAddress adr = skt.getInetAddress (); // System.out.println (" Calling isServerTrusted"); //
* System.out.println (" addres "+ adr.toString ()); return isDomainInTrustedList (adr, serverTrustedHosts); } return
* false;
*
* }
*/
/**
* Checks if a given domain is trusted. e.g. domain = 123.203.1.1 is an IP address trusted list = *.com, *.eng should
* say that the given domain is trusted.
*
* @param the InetAddress of the domain to be checked for
* @param the array of trusted domains
* @return true - if the given domain is trusted
*/
/*
* private boolean isDomainInTrustedList (InetAddress inetAddress, String[] trusted) throws SecurityException { boolean
* isTrusted = false; String domain = null; String star = "*"; String dot = "."; // lookup and get domain name try{
* domain = inetAddress.getHostName (); } catch (Exception e){
* _logger.log(Level.SEVERE,"iiop.domain_lookup_failed",inetAddress.getHostAddress ()); return false; } if
* (_logger.isLoggable(Level.FINE)) { _logger.log(Level.FINE, " Verifying if domain address ="+ inetAddress.toString ()
* + " is in the Trusted list "); _logger.log(Level.FINE, " the domain name is = "+ domain); }
*
* String[] domainTok = TypeUtil.stringToArray (domain, dot); // now lets go through the list of trusted domains // one
* at a time for (int i=0; i< trusted.length; i++){ // String to compare with String[] toksList = TypeUtil.stringToArray
* (trusted[i], dot); // cannot compare *.eng to *.eng.sun if (toksList.length != domainTok.length){ isTrusted = false;
* continue; } else{ for (int j=toksList.length-1; j>=0 ; j--){ // compare com in *.eng.com and abc.eng.com // compare
* in the reverse order if (toksList[j].equals (domainTok[j])){ isTrusted = true; } else { // compare * in abc.*.com and
* abc.eng.com if (toksList[j].equals (star)){ isTrusted = true; } else { // get out and try the next domain isTrusted =
* false; break; } } } // We went through one domain and found a match // no need to compare further if (isTrusted)
* return isTrusted; } } return isTrusted; }
*/
/**
* Get the username and password either from the JAAS subject or from thread local storage. For appclients if login
* has'nt happened this method would trigger login and popup a user interface to gather authentication information.
*
* @return the security context.
*/
private SecurityContext getUsernameAndPassword(ComponentInvocation ci, CompoundSecMech mechanism) throws SecurityMechanismException {
try {
Subject s = null;
// if(ci == null) {
if (isNotServerOrACC()) {
// Standalone client ... Changed the security context
// from which to fetch the subject
ClientSecurityContext sc = ClientSecurityContext.getCurrent();
if (sc == null) {
return null;
}
s = sc.getSubject();
LOG.log(Level.FINE, "SUBJECT: {0}", s);
} else {
// Object obj = ci.getContainerContext();
// if(obj instanceof AppContainer) {
if (isACC()) {
// get the subject
ClientSecurityContext sc = ClientSecurityContext.getCurrent();
if (sc == null) {
s = LoginContextDriver.doClientLogin(SecurityConstants.USERNAME_PASSWORD, SecurityServicesUtil.getInstance().getCallbackHandler());
} else {
s = sc.getSubject();
}
} else {
// web/ejb
s = getSubjectFromSecurityCurrent();
// TODO check if username/password is available
// if not throw exception
}
}
SecurityContext ctx = new SecurityContext();
final Subject sub = s;
ctx.subject = s;
// determining if run-as has been used
PrivilegedAction<Set<PasswordCredential>> action = () -> sub.getPrivateCredentials(PasswordCredential.class);
Set<PasswordCredential> privateCredSet = AccessController.doPrivileged(action);
// this is runas case dont set
if (privateCredSet.isEmpty()) {
LOG.log(Level.FINE, "No private credential run as mode");
// the auth class
ctx.authcls = null;
ctx.identcls = GSSUPName.class;
} else {
/**
* lookup the realm name that is required by the server and set it up in the PasswordCredential class.
*/
AS_ContextSec asContext = mechanism.as_context_mech;
final byte[] target_name = asContext.target_name;
byte[] _realm = null;
if (target_name == null || target_name.length == 0) {
_realm = Realm.getDefaultRealm().getBytes();
} else {
_realm = GSSUtils.importName(GSSUtils.GSSUP_MECH_OID, target_name);
}
final String realm_name = new String(_realm);
final Iterator<PasswordCredential> it = privateCredSet.iterator();
for (; it.hasNext();) {
PrivilegedAction<Void> action2 = () -> {
PasswordCredential pc = it.next();
pc.setRealm(realm_name);
return null;
};
AccessController.doPrivileged(action2);
}
ctx.authcls = PasswordCredential.class;
}
return ctx;
} catch (LoginException le) {
throw le;
} catch (Exception e) {
LOG.log(Level.SEVERE, "IIOP1001: Exception getting username and password", e);
return null;
}
}
/**
* Get the principal/distinguished name from thread local storage.
*
* @return the security context.
*/
private SecurityContext getIdentity() throws SecurityMechanismException {
LOG.log(Level.FINE, "Getting PRINCIPAL/DN from TLS");
SecurityContext ctx = new SecurityContext();
final SecurityContext sCtx = ctx;
// get stuff from the SecurityContext class
com.sun.enterprise.security.SecurityContext scontext = com.sun.enterprise.security.SecurityContext.getCurrent();
if ((scontext == null) || scontext.didServerGenerateCredentials()) {
// a default guest/guest123 was created
sCtx.identcls = AnonCredential.class;
PrivilegedAction<Void> action = () -> {
// remove all the public and private credentials
Subject sub = new Subject();
sCtx.subject = sub;
sCtx.subject.getPublicCredentials().add(new AnonCredential());
return null;
};
AccessController.doPrivileged(action);
return sCtx;
}
Subject s = getSubjectFromSecurityCurrent();
ctx.subject = s;
// Figure out the credential class
final Subject sub = s;
PrivilegedAction<Set<PasswordCredential>> action = () -> sub.getPrivateCredentials(PasswordCredential.class);
Set<PasswordCredential> credSet = AccessController.doPrivileged(action);
if (credSet.size() == 1) {
ctx.identcls = GSSUPName.class;
final Set<PasswordCredential> cs = credSet;
PrivilegedAction<Subject> action2 = () -> {
Subject ss = new Subject();
Iterator<PasswordCredential> iter = cs.iterator();
PasswordCredential pc = iter.next();
GSSUPName gssname = new GSSUPName(pc.getUser(), pc.getRealm());
ss.getPublicCredentials().add(gssname);
return ss;
};
Subject subj = AccessController.doPrivileged(action2);
ctx.subject = subj;
return ctx;
}
Set<?> pubCredSet = s.getPublicCredentials();
if (pubCredSet.size() != 1) {
LOG.log(Level.SEVERE, "IIOP1002: Principal propagation: Cannot find principal information in subject");
return null;
}
Iterator<?> credIter = pubCredSet.iterator();
if (credIter.hasNext()) {
Object o = credIter.next();
if (o instanceof GSSUPName) {
ctx.identcls = GSSUPName.class;
} else if (o instanceof X500Principal) {
ctx.identcls = X500Principal.class;
} else {
ctx.identcls = X509CertificateCredential.class;
}
} else {
LOG.log(Level.SEVERE, "IIOP1003: Principal propagation: Cannot find credential information in subject.");
return null;
}
return ctx;
}
private Subject getSubjectFromSecurityCurrent() throws SecurityMechanismException {
com.sun.enterprise.security.SecurityContext sc = null;
sc = com.sun.enterprise.security.SecurityContext.getCurrent();
if (sc == null) {
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, " SETTING GUEST ---");
}
sc = com.sun.enterprise.security.SecurityContext.init();
}
if (sc == null) {
throw new SecurityMechanismException("Could not find " + " security information");
}
Subject s = sc.getSubject();
if (s == null) {
throw new SecurityMechanismException("Could not find " + " subject information in the security context.");
}
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "Subject in security current:" + s);
}
return s;
}
public CompoundSecMech selectSecurityMechanism(IOR ior) throws SecurityMechanismException {
CompoundSecMech[] mechList = getCtc().getSecurityMechanisms(ior);
CompoundSecMech mech = selectSecurityMechanism(mechList);
return mech;
}
/**
* Select the security mechanism from the list of compound security mechanisms.
*/
private CompoundSecMech selectSecurityMechanism(CompoundSecMech[] mechList) throws SecurityMechanismException {
// We should choose from list of compound security mechanisms
// which are in decreasing preference order. Right now we select
// the first one.
if (mechList == null || mechList.length == 0) {
return null;
}
CompoundSecMech mech = null;
for (CompoundSecMech element : mechList) {
mech = element;
boolean useMech = useMechanism(mech);
if (useMech) {
return mech;
}
}
throw new SecurityMechanismException("Cannot use any of the " + " target's supported mechanisms");
}
private boolean useMechanism(CompoundSecMech mech) {
boolean val = true;
TLS_SEC_TRANS tls = getCtc().getSSLInformation(mech);
if (mech.sas_context_mech.supported_naming_mechanisms.length > 0 && !isMechanismSupported(mech.sas_context_mech)) {
return false;
} else if (mech.as_context_mech.client_authentication_mech.length > 0 && !isMechanismSupportedAS(mech.as_context_mech)) {
return false;
}
if (tls == null) {
return true;
}
int targetRequires = tls.target_requires;
if (isSet(targetRequires, EstablishTrustInClient.value)) {
if (!sslUtils.isKeyAvailable()) {
val = false;
}
}
return val;
}
private boolean isMechanismSupportedAS(AS_ContextSec as) {
byte[] mechanism = as.client_authentication_mech;
byte[] mechSupported = GSSUtils.getMechanism();
if (mechanism == null) {
return false;
}
if (Arrays.equals(mechanism, mechSupported)) {
return true;
}
return false;
}
// Returns the target_name from PasswordCredential in Subject subj
// subj must contain a single instance of PasswordCredential.
private byte[] getTargetName(Subject subj) {
byte[] tgt_name = {};
final Subject sub = subj;
final Set<PasswordCredential> credset = AccessController.doPrivileged(new PrivilegedAction<Set>() {
@Override
public Set run() {
return sub.getPrivateCredentials(PasswordCredential.class);
}
});
if (credset.size() == 1) {
tgt_name = AccessController.doPrivileged(new PrivilegedAction<byte[]>() {
@Override
public byte[] run() {
Iterator<PasswordCredential> iter = credset.iterator();
PasswordCredential pc = iter.next();
return pc.getTargetName();
}
});
}
return tgt_name;
}
private boolean evaluate_client_conformance_ssl(EjbIORConfigurationDescriptor iordesc, boolean ssl_used, X509Certificate[] certchain) {
try {
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "SecurityMechanismSelector.evaluate_client_conformance_ssl->:");
}
boolean ssl_required = false;
boolean ssl_supported = false;
int ssl_target_requires = 0;
int ssl_target_supports = 0;
/*************************************************************************
* Conformance Matrix:
*
* |---------------|---------------------|---------------------|------------| | SSLClientAuth | targetrequires.ETIC |
* targetSupports.ETIC | Conformant | |---------------|---------------------|---------------------|------------| | Yes |
* 0 | 1 | Yes | | Yes | 0 | 0 | No | | Yes | 1 | X | Yes | | No | 0 | X | Yes | | No | 1 | X | No |
* |---------------|---------------------|---------------------|------------|
*
*************************************************************************/
// gather the configured SSL security policies.
ssl_target_requires = this.getCtc().getTargetRequires(iordesc);
ssl_target_supports = this.getCtc().getTargetSupports(iordesc);
if (isSet(ssl_target_requires, Integrity.value) || isSet(ssl_target_requires, Confidentiality.value)
|| isSet(ssl_target_requires, EstablishTrustInClient.value)) {
ssl_required = true;
} else {
ssl_required = false;
}
if (ssl_target_supports != 0) {
ssl_supported = true;
} else {
ssl_supported = false;
}
/*
* Check for conformance for using SSL usage.
*
* a. if SSL was used, then either the target must require or support SSL. In the latter case, SSL is used because of
* client policy.
*
* b. if SSL was not used, then the target must not require it either. The target may or may not support SSL (it is
* irrelevant).
*/
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE,
"SecurityMechanismSelector.evaluate_client_conformance_ssl:" + " " + isSet(ssl_target_requires, Integrity.value) + " "
+ isSet(ssl_target_requires, Confidentiality.value) + " " + isSet(ssl_target_requires, EstablishTrustInClient.value) + " "
+ ssl_required + " " + ssl_supported + " " + ssl_used);
}
if (ssl_used) {
if (!(ssl_required || ssl_supported))
{
return false; // security mechanism did not match
}
} else {
if (ssl_required)
{
return false; // security mechanism did not match
}
}
/*
* Check for conformance for SSL client authentication.
*
* a. if client performed SSL client authentication, then the target must either require or support SSL client
* authentication. If the target only supports, SSL client authentication is used because of client security policy.
*
* b. if SSL client authentication was not used, then the target must not require SSL client authentcation either. The
* target may or may not support SSL client authentication (it is irrelevant).
*/
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "SecurityMechanismSelector.evaluate_client_conformance_ssl:" + " "
+ isSet(ssl_target_requires, EstablishTrustInClient.value) + " " + isSet(ssl_target_supports, EstablishTrustInClient.value));
}
if (certchain != null) {
if (!(isSet(ssl_target_requires, EstablishTrustInClient.value) || isSet(ssl_target_supports, EstablishTrustInClient.value)))
{
return false; // security mechanism did not match
}
} else {
if (isSet(ssl_target_requires, EstablishTrustInClient.value))
{
return false; // security mechanism did not match
}
}
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "SecurityMechanismSelector.evaluate_client_conformance_ssl: true");
}
return true; // mechanism matched
} finally {
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "SecurityMechanismSelector.evaluate_client_conformance_ssl<-:");
}
}
}
/*
* Evaluates a client's conformance to a security policies at the client authentication layer.
*
* returns true if conformant ; else returns false
*/
private boolean evaluate_client_conformance_ascontext(SecurityContext ctx, EjbIORConfigurationDescriptor iordesc, String realmName) {
boolean client_authenticated = false;
// get requirements and supports at the client authentication layer
AS_ContextSec ascontext = null;
try {
ascontext = this.getCtc().createASContextSec(iordesc, realmName);
} catch (Exception e) {
LOG.log(Level.SEVERE, "IIOP1000: Exception creating ASContext", e);
return false;
}
/*************************************************************************
* Conformance Matrix:
*
* |------------|---------------------|---------------------|------------| | ClientAuth | targetrequires.ETIC |