-
Notifications
You must be signed in to change notification settings - Fork 138
/
LoginContextDriver.java
991 lines (884 loc) · 39.4 KB
/
LoginContextDriver.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
/*
* Copyright (c) 2023 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2021 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.security.auth.login;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.security.auth.x500.X500Principal;
import org.glassfish.internal.api.Globals;
import org.glassfish.security.common.Group;
import org.glassfish.security.common.UserNameAndPassword;
import org.glassfish.security.common.UserPrincipal;
import com.sun.enterprise.common.iiop.security.AnonCredential;
import com.sun.enterprise.common.iiop.security.GSSUPName;
import com.sun.enterprise.security.SecurityContext;
import com.sun.enterprise.security.SecurityLoggerInfo;
import com.sun.enterprise.security.SecurityServicesUtil;
import com.sun.enterprise.security.audit.AuditManager;
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.ServerLoginCallbackHandler;
import com.sun.enterprise.security.auth.login.common.X509CertificateCredential;
import com.sun.enterprise.security.auth.realm.Realm;
import com.sun.enterprise.security.auth.realm.certificate.CertificateRealm;
import com.sun.enterprise.security.auth.realm.exceptions.InvalidOperationException;
import com.sun.enterprise.security.auth.realm.exceptions.NoSuchRealmException;
import com.sun.enterprise.security.auth.realm.exceptions.NoSuchUserException;
import com.sun.enterprise.security.common.AppservAccessController;
import com.sun.enterprise.security.common.ClientSecurityContext;
import com.sun.enterprise.security.common.SecurityConstants;
/**
*
* This class is invoked implicitly by the server to log in the user information that was sent on the wire by the client. Clients
* will use the <i>doClientLogin</i> method to simulate authentication to the server.
*
* @author Harpreet Singh (hsingh@eng.sun.com)
* @author Jyri Virkki
*
*/
public class LoginContextDriver {
private static final Logger _logger = SecurityLoggerInfo.getLogger();
private static final ServerLoginCallbackHandler dummyCallback = new ServerLoginCallbackHandler();
// moved to SecurityConstants.
// private static final String CLIENT_JAAS_PASSWORD = "default";
// private static final String CLIENT_JAAS_CERTIFICATE = "certificate";
public static final String CERT_REALMNAME = "certificate";
private static volatile AuditManager AUDIT_MANAGER = null;
/**
* This class cannot be instantiated
*
*/
private LoginContextDriver() {
}
private static AuditManager getAuditManager() {
if (AUDIT_MANAGER != null) {
return AUDIT_MANAGER;
}
return _getAuditManager();
}
private static synchronized AuditManager _getAuditManager() {
if (AUDIT_MANAGER == null) {
SecurityServicesUtil secServUtil = Globals.get(SecurityServicesUtil.class);
AUDIT_MANAGER = secServUtil.getAuditManager();
}
return AUDIT_MANAGER;
}
/**
* This method is just a convenience wrapper for <i>login(Subject, Class)</i> method. It will construct a PasswordCredential
* class.
*
* @param String username
* @param String password
* @param String realmName the name of the realm to login into, if realmName is null, we login into the default realm
*/
public static void login(String username, char[] password, String realmName) {
if (realmName == null || !(Realm.isValidRealm(realmName))) {
realmName = Realm.getDefaultRealm();
}
final Subject fs = new Subject();
final PasswordCredential pc = new PasswordCredential(username, password, realmName);
AppservAccessController.doPrivileged(new PrivilegedAction() {
@Override
public java.lang.Object run() {
fs.getPrivateCredentials().add(pc);
return fs;
}
});
LoginContextDriver.login(fs, PasswordCredential.class);
}
public static void login(AssertedCredentials asrtCred) throws javax.security.auth.login.LoginException {
Subject subject = new Subject();
subject.getPrivateCredentials().add(asrtCred);
String jaasCtx = null;
try {
jaasCtx = Realm.getInstance(asrtCred.getRealmName()).getJAASContext();
} catch (Exception ex) {
if (ex instanceof LoginException) {
throw (LoginException) ex;
} else {
throw (LoginException) new LoginException(ex.toString()).initCause(ex);
}
}
try {
// A dummyCallback is used to satisfy JAAS but it is never used.
// name/pwd info is already contained in Subject's Credential
LoginContext lg = new LoginContext(jaasCtx, subject, dummyCallback);
lg.login();
} catch (Exception e) {
if (_logger.isLoggable(Level.INFO)) {
_logger.log(Level.INFO, SecurityLoggerInfo.auditAtnRefusedError, asrtCred.getUserName());
}
if (_logger.isLoggable(Level.FINEST)) {
_logger.log(Level.FINEST, "doPasswordLogin fails", e);
}
if (AUDIT_MANAGER.isAuditOn()) {
AUDIT_MANAGER.authentication(asrtCred.getUserName(), asrtCred.getRealmName(), false);
}
if (e instanceof LoginException) {
throw (LoginException) e;
} else {
throw (LoginException) new LoginException("Login failed: " + e.getMessage()).initCause(e);
}
}
setSecurityContext(asrtCred.getUserName(), subject, asrtCred.getRealmName());
}
/**
* This method performs the login on the server side.
*
* <P>
* This method is the main login method for S1AS. It is called with a Subject and the type (class) of credential which should be
* checked. The Subject must contain a credential of the specified type or login will fail.
*
* <P>
* While the implementation has been cleaned up, the login process still consists of a number of special cases which are treated
* separately at the realm level. In the future tighter JAAS integration could clean some of this up.
*
* <P>
* The following credential types are recognized at this time:
* <ul>
* <li>PasswordCredential - This is the general case for all login methods which rely on the client providing a name and
* password. It can be used with any realms/JAAS login modules which expect such data (e.g. file realm, LDAP realm, UNIX realm)
* <LI>X509CertificateCredential - Special case for SSL client auth. Here authentication has already been done by the SSL
* subsystem so this login only creates a security context based on the certificate data.
* <LI>AnonCredential - Unauthenticated session, set anonymous security context.
* <LI>GSSUPName - Retrieve user and realm and set security context.
* <LI>X500Principal - Retrieve user and realm and set security context.
* </ul>
*
* @param Subject the subject of the client
* @param Class the class of the credential packaged in the subject.
*
*/
public static void login(Subject subject, Class cls) throws LoginException {
if (_logger.isLoggable(Level.FINEST)) {
_logger.log(Level.FINEST, "Processing login with credentials of type: " + cls.toString());
}
if (cls.equals(PasswordCredential.class)) {
doPasswordLogin(subject);
} else if (cls.equals(X509CertificateCredential.class)) {
doCertificateLogin(subject);
} else if (cls.equals(AnonCredential.class)) {
doAnonLogin();
} else if (cls.equals(GSSUPName.class)) {
doGSSUPLogin(subject);
} else if (cls.equals(X500Principal.class)) {
doX500Login(subject, null);
} else {
_logger.log(Level.INFO, SecurityLoggerInfo.unknownCredentialError, cls.toString());
throw new LoginException("Unknown credential type, cannot login.");
}
}
/**
* This method is used for logging in a run As principal. It creates a JAAS subject whose credential is to type GSSUPName. This
* is used primarily for runas
*
*/
public static void loginPrincipal(String username, String realmName) throws LoginException {
// no realm provided, assuming default
if (realmName == null || realmName.isEmpty()) {
realmName = Realm.getDefaultRealm();
}
final Subject s = new Subject();
final UserPrincipal p = new UserNameAndPassword(username);
final GSSUPName name = new GSSUPName(username, realmName);
AppservAccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
s.getPrincipals().add(p);
s.getPublicCredentials().add(name);
return null;
}
});
try {
Realm realm = Realm.getInstance(realmName);
Enumeration<String> en = realm.getGroupNames(username);
Set<Principal> principalSet = s.getPrincipals();
while (en.hasMoreElements()) {
principalSet.add(new Group(en.nextElement()));
}
} catch (InvalidOperationException ex) {
_logger.log(Level.WARNING, SecurityLoggerInfo.invalidOperationForRealmError,
new Object[] { username, realmName, ex.toString() });
} catch (NoSuchUserException ex) {
_logger.log(Level.WARNING, SecurityLoggerInfo.noSuchUserInRealmError, new Object[] { username, realmName, ex.toString() });
} catch (NoSuchRealmException ex) {
LoginException lex = new LoginException(ex.toString());
lex.initCause(ex);
throw lex;
}
setSecurityContext(username, s, realmName);
}
/**
* This method logs out the user by clearing the security context.
*
*/
public static void logout() throws LoginException {
unsetSecurityContext();
}
/**
* Log in subject with PasswordCredential. This is a generic login which applies to all login mechanisms which process
* PasswordCredential. In other words, any mechanism which receives an actual username, realm and password set from the client.
*
* <P>
* The realm contained in the credential is checked, and a JAAS LoginContext is created using a context name obtained from the
* appropriate Realm instance. The applicable JAAS LoginModule is initialized (based on the jaas login configuration) and login()
* is invoked on it.
*
* <P>
* RI code makes several assumptions which are retained here:
* <ul>
* <li>The PasswordCredential is stored as a private credential of the subject.
* <li>There is only one such credential present (actually, only the first one is relevant if more are present). </ui>
*
* @param s Subject to be authenticated.
* @throws LoginException Thrown if the login fails.
*
*/
private static void doPasswordLogin(Subject subject) throws LoginException {
final Subject s = subject;
Object obj = getPrivateCredentials(s, PasswordCredential.class);
assert obj != null;
PasswordCredential p = (PasswordCredential) obj;
String user = p.getUser();
char[] pwd = p.getPassword();
String realm = p.getRealm();
String jaasCtx = null;
try {
jaasCtx = Realm.getInstance(realm).getJAASContext();
} catch (Exception ex) {
if (ex instanceof LoginException) {
throw (LoginException) ex;
} else {
throw (LoginException) new LoginException(ex.toString()).initCause(ex);
}
}
assert user != null;
assert pwd != null;
assert realm != null;
assert jaasCtx != null;
if (_logger.isLoggable(Level.FINE)) {
_logger.fine("Logging in user [" + user + "] into realm: " + realm + " using JAAS module: " + jaasCtx);
}
try {
// A dummyCallback is used to satisfy JAAS but it is never used.
// name/pwd info is already contained in Subject's Credential
LoginContext lg = new LoginContext(jaasCtx, s, dummyCallback);
lg.login();
} catch (Exception e) {
if (_logger.isLoggable(Level.FINEST)) {
_logger.log(Level.FINEST, "doPasswordLogin fails", e);
}
if (getAuditManager() != null && getAuditManager().isAuditOn()) {
getAuditManager().authentication(user, realm, false);
}
if (e instanceof LoginException) {
throw (LoginException) e;
} else {
throw (LoginException) new LoginException("Login failed: " + e.getMessage()).initCause(e);
}
}
if (getAuditManager() != null && getAuditManager().isAuditOn()) {
getAuditManager().authentication(user, realm, true);
}
if (_logger.isLoggable(Level.FINE)) {
_logger.fine("Password login succeeded for : " + user);
}
setSecurityContext(user, s, realm);
if (_logger.isLoggable(Level.FINE)) {
_logger.log(Level.FINE, "Set security context as user: " + user);
}
}
public static void jmacLogin(Subject subject, Principal callerPrincipal, String realmName) throws LoginException {
if (CertificateRealm.AUTH_TYPE.equals(realmName)) {
if (callerPrincipal instanceof X500Principal) {
LoginContextDriver.jmacLogin(subject, (X500Principal) callerPrincipal);
}
} else if (!callerPrincipal.equals(SecurityContext.getDefaultCallerPrincipal())) {
LoginContextDriver.jmacLogin(subject, callerPrincipal.getName(), realmName);
}
}
/**
* Performs login for JMAC security. The difference between this method and others is that it just verifies whether the login
* will succeed in the given realm. It does not set the result of the authentication in the appserver runtime environment A
* silent return from this method means that the given user succeeding in authenticating with the given password in the given
* realm
*
* @param subject
* @param username
* @param password
* @param realmName the realm to authenticate under
* @returns Subject on successful authentication
* @throws LoginException
*/
public static Subject jmacLogin(Subject subject, String username, char[] password, String realmName) throws LoginException {
if (realmName == null || !(Realm.isValidRealm(realmName))) {
realmName = Realm.getDefaultRealm();
}
if (subject == null) {
subject = new Subject();
}
final Subject fs = subject;
final PasswordCredential pc = new PasswordCredential(username, password, realmName);
AppservAccessController.doPrivileged(new PrivilegedAction() {
@Override
public java.lang.Object run() {
fs.getPrivateCredentials().add(pc);
return fs;
}
});
String jaasCtx = null;
try {
jaasCtx = Realm.getInstance(realmName).getJAASContext();
} catch (Exception ex) {
if (ex instanceof LoginException) {
throw (LoginException) ex;
} else {
throw (LoginException) new LoginException(ex.toString()).initCause(ex);
}
}
if (_logger.isLoggable(Level.FINE)) {
_logger.fine("jmac login user [" + username + "] into realm: " + realmName + " using JAAS module: " + jaasCtx);
}
try {
// A dummyCallback is used to satisfy JAAS but it is never used.
// name/pwd info is already contained in Subject's Credential
LoginContext lg = new LoginContext(jaasCtx, fs, dummyCallback);
lg.login();
} catch (Exception e) {
if (_logger.isLoggable(Level.INFO)) {
_logger.log(Level.INFO, SecurityLoggerInfo.auditAtnRefusedError, username);
}
if (getAuditManager().isAuditOn()) {
getAuditManager().authentication(username, realmName, false);
}
if (e instanceof LoginException) {
throw (LoginException) e;
} else {
throw (LoginException) new LoginException("Login failed: " + e.getMessage()).initCause(e);
}
}
if (getAuditManager().isAuditOn()) {
getAuditManager().authentication(username, realmName, true);
}
if (_logger.isLoggable(Level.FINE)) {
_logger.fine("jmac Password login succeeded for : " + username);
}
return subject;
// do not set the security Context
}
public static Subject jmacLogin(Subject subject, X500Principal x500Principal) throws LoginException {
if (subject == null) {
subject = new Subject();
}
final Subject fs = subject;
String userName = "";
try {
userName = x500Principal.getName();
AppservAccessController.doPrivileged(new PrivilegedAction() {
@Override
public java.lang.Object run() {
fs.getPublicCredentials().add(x500Principal);
return fs;
}
});
Realm realm = Realm.getInstance(CertificateRealm.AUTH_TYPE);
CertificateRealm certRealm = (CertificateRealm) realm;
String jaasCtx = certRealm.getJAASContext();
if (jaasCtx != null) {
// The subject has the Cretificate Credential.
LoginContext lg = new LoginContext(jaasCtx, fs, dummyCallback);
lg.login();
}
certRealm.authenticate(fs, x500Principal);
} catch (Exception ex) {
if (_logger.isLoggable(Level.INFO)) {
_logger.log(Level.INFO, SecurityLoggerInfo.auditAtnRefusedError, userName);
}
if (getAuditManager().isAuditOn()) {
getAuditManager().authentication(userName, CertificateRealm.AUTH_TYPE, false);
}
if (ex instanceof LoginException) {
throw (LoginException) ex;
} else {
throw (LoginException) new LoginException(ex.toString()).initCause(ex);
}
}
if (_logger.isLoggable(Level.FINE)) {
_logger.fine("jmac cert login succeeded for: " + userName);
}
if (getAuditManager().isAuditOn()) {
getAuditManager().authentication(userName, CertificateRealm.AUTH_TYPE, true);
}
// do not set the security Context
return subject;
}
public static Subject jmacLogin(Subject subject, String identityAssertion, String realm) throws LoginException {
if (subject == null) {
subject = new Subject();
}
final Subject fs = subject;
String userName = identityAssertion;
try {
if (realm == null || "".equals(realm)) {
realm = Realm.getDefaultRealm();
}
Realm realmInst = Realm.getInstance(realm);
final Enumeration groups = realmInst.getGroupNames(userName);
if (groups != null && groups.hasMoreElements()) {
AppservAccessController.doPrivileged(new PrivilegedAction() {
@Override
public java.lang.Object run() {
while (groups.hasMoreElements()) {
String grp = (String) groups.nextElement();
fs.getPrincipals().add(new Group(grp));
}
return fs;
}
});
}
} catch (Exception ex) {
if (_logger.isLoggable(Level.FINE)) {
_logger.log(Level.FINE, "Exception when trying to populate groups for CallerPrincipal " + identityAssertion, ex);
}
}
return subject;
}
/**
* A special case login for handling X509CertificateCredential. This does not get triggered based on current RI code. See
* X500Login.
*
*/
private static void doCertificateLogin(Subject s) throws LoginException {
if (_logger.isLoggable(Level.FINE)) {
_logger.log(Level.FINE, "Processing X509 certificate login.");
}
String realm = CertificateRealm.AUTH_TYPE;
String user = null;
try {
Object obj = getPublicCredentials(s, X509CertificateCredential.class);
X509CertificateCredential xp = (X509CertificateCredential) obj;
user = xp.getAlias();
if (_logger.isLoggable(Level.FINE)) {
_logger.log(Level.FINE, "Set security context as user: " + user);
}
setSecurityContext(user, s, realm);
if (getAuditManager().isAuditOn()) {
getAuditManager().authentication(user, realm, true);
}
} catch (LoginException le) {
if (getAuditManager().isAuditOn()) {
getAuditManager().authentication(user, realm, false);
}
throw le;
}
}
/**
* A special case login for anonymous credentials (no login info).
*
*/
private static void doAnonLogin() throws LoginException {
// instance of anononymous credential login with guest
SecurityContext.setUnauthenticatedContext();
if (_logger.isLoggable(Level.FINE)) {
_logger.log(Level.FINE, "Set anonymous security context.");
}
}
/**
* A special case login for GSSUPName credentials.
*
*/
private static void doGSSUPLogin(Subject s) throws LoginException {
if (_logger.isLoggable(Level.FINE)) {
_logger.fine("Processing GSSUP login.");
}
String user = null;
String realm = Realm.getDefaultRealm();
try {
Object obj = getPublicCredentials(s, GSSUPName.class);
user = ((GSSUPName) obj).getUser();
setSecurityContext(user, s, realm);
if (getAuditManager().isAuditOn()) {
getAuditManager().authentication(user, realm, true);
}
if (_logger.isLoggable(Level.FINE)) {
_logger.fine("GSSUP login succeeded for : " + user);
}
} catch (LoginException le) {
if (getAuditManager().isAuditOn()) {
getAuditManager().authentication(user, realm, false);
}
throw le;
}
}
/**
* A special case login for X500Principal credentials. This is invoked for certificate login because the containers extract the
* X.500 name from the X.509 certificate before calling into this class.
*
*/
public static void doX500Login(Subject s, String appModuleID) throws LoginException {
if (_logger.isLoggable(Level.FINE)) {
_logger.fine("Processing X.500 name login.");
}
String user = null;
String realm_name = null;
try {
X500Principal x500Principal = (X500Principal) getPublicCredentials(s, X500Principal.class);
user = x500Principal.getName();
// In the RI-inherited implementation this directly creates
// some credentials and sets the security context. This means
// that the certificate realm does not get an opportunity to
// process the request. While the realm will not do any
// authentication (already done by this point) it can choose
// to adjust the groups or principal name or other variables
// of the security context. Of course, bug 4646134 needs to be
// kept in mind at all times.
Realm realm = Realm.getInstance(CertificateRealm.AUTH_TYPE);
if (realm instanceof CertificateRealm) { // should always be true
CertificateRealm certRealm = (CertificateRealm) realm;
String jaasCtx = certRealm.getJAASContext();
if (jaasCtx != null) {
// The subject has the Cretificate Credential.
LoginContext lg = new LoginContext(jaasCtx, s, new ServerLoginCallbackHandler(user, null, appModuleID));
lg.login();
}
certRealm.authenticate(s, x500Principal);
realm_name = CertificateRealm.AUTH_TYPE;
if (getAuditManager().isAuditOn()) {
getAuditManager().authentication(user, realm_name, true);
}
} else {
_logger.warning(SecurityLoggerInfo.certLoginBadRealmError);
realm_name = realm.getName();
setSecurityContext(user, s, realm_name);
}
if (_logger.isLoggable(Level.FINE)) {
_logger.fine("X.500 name login succeeded for : " + user);
}
} catch (LoginException le) {
if (getAuditManager().isAuditOn()) {
getAuditManager().authentication(user, realm_name, false);
}
throw le;
} catch (Exception ex) {
throw (LoginException) new LoginException(ex.toString()).initCause(ex);
}
}
/**
* Retrieve a public credential of the given type (java class) from the subject.
*
* <P>
* This method retains the RI assumption that only the first credential of the given type is used.
*
*/
private static Object getPublicCredentials(Subject s, Class<?> cls) throws LoginException {
Set credset = s.getPublicCredentials(cls);
final Iterator iter = credset.iterator();
if (!iter.hasNext()) {
String credmsg = cls.toString();
if (_logger.isLoggable(Level.FINER)) {
_logger.finer("Expected public credentials of type : " + credmsg + " but none found.");
}
throw new LoginException("Expected public credential of type: " + credmsg + " but none found.");
}
Object obj = null;
try {
obj = AppservAccessController.doPrivileged(new PrivilegedAction() {
@Override
public java.lang.Object run() {
return iter.next();
}
});
} catch (Exception e) {
// should never come here
if (e instanceof LoginException) {
throw (LoginException) e;
} else {
throw (LoginException) new LoginException("Failed to retrieve public credential: " + e.getMessage()).initCause(e);
}
}
return obj;
}
/**
* Retrieve a private credential of the given type (java class) from the subject.
*
* <P>
* This method retains the RI assumption that only the first credential of the given type is used.
*
*/
private static Object getPrivateCredentials(Subject subject, Class<?> cls) throws LoginException {
final Subject s = subject;
final Class<?> cl = cls;
final Set credset = (Set) AppservAccessController.doPrivileged(new PrivilegedAction() {
@Override
public java.lang.Object run() {
return s.getPrivateCredentials(cl);
}
});
final Iterator iter = credset.iterator();
if (!iter.hasNext()) {
String credmsg = cls.toString();
if (_logger.isLoggable(Level.FINER)) {
_logger.finer("Expected private credential of type: " + credmsg + " but none found.");
}
throw new LoginException("Expected private credential of type: " + credmsg + " but none found.");
}
// retrieve only first credential of give type
Object obj = null;
try {
obj = AppservAccessController.doPrivileged(new PrivilegedAction() {
@Override
public java.lang.Object run() {
return iter.next();
}
});
} catch (Exception e) {
// should never come here
if (e instanceof LoginException) {
throw (LoginException) e;
} else {
throw (LoginException) new LoginException("Failed to retrieve private credential: " + e.getMessage()).initCause(e);
}
}
return obj;
}
/**
* This method sets the security context on the current Thread Local Storage
*
* @param String username is the user who authenticated
* @param Subject is the subject representation of the user
* @param Credentials the credentials that the server associated with it
*/
private static void setSecurityContext(String userName, Subject subject, String realm) {
SecurityContext securityContext = new SecurityContext(userName, subject, realm);
SecurityContext.setCurrent(securityContext);
}
/**
* Set the current security context on the Thread Local Storage to null.
*
*/
private static void unsetSecurityContext() {
SecurityContext.setCurrent((SecurityContext) null);
}
/**
* Perform login on the client side. It just simulates the login on the client side. The method uses the callback handlers and
* generates correct credential information that will be later sent to the server
*
* @param int type whether it is <i> username_password</i> or <i> certificate </i> based login.
* @param CallbackHandler the callback handler to gather user information.
* @exception LoginException the exception thrown by the callback handler.
*/
public static Subject doClientLogin(int type, javax.security.auth.callback.CallbackHandler jaasHandler) throws LoginException {
final javax.security.auth.callback.CallbackHandler handler = jaasHandler;
// the subject will actually be filled in with a PasswordCredential
// required by the csiv2 layer in the LoginModule.
// we create the dummy credential here and call the
// set security context. Thus, we have 2 credentials, one each for
// the csiv2 layer and the other for the RI.
final Subject subject = new Subject();
if (type == SecurityConstants.USERNAME_PASSWORD) {
AppservAccessController.doPrivileged(new PrivilegedAction() {
@Override
public java.lang.Object run() {
try {
LoginContext lg = new LoginContext(SecurityConstants.CLIENT_JAAS_PASSWORD, subject, handler);
lg.login();
} catch (javax.security.auth.login.LoginException e) {
throw (LoginException) new LoginException(e.toString()).initCause(e);
}
return null;
}
});
postClientAuth(subject, PasswordCredential.class);
return subject;
} else if (type == SecurityConstants.CERTIFICATE) {
AppservAccessController.doPrivileged(new PrivilegedAction() {
@Override
public java.lang.Object run() {
try {
LoginContext lg = new LoginContext(SecurityConstants.CLIENT_JAAS_CERTIFICATE, subject, handler);
lg.login();
} catch (javax.security.auth.login.LoginException e) {
throw (LoginException) new LoginException(e.toString()).initCause(e);
}
return null;
}
});
postClientAuth(subject, X509CertificateCredential.class);
return subject;
} else if (type == SecurityConstants.ALL) {
AppservAccessController.doPrivileged(new PrivilegedAction() {
@Override
public java.lang.Object run() {
try {
LoginContext lgup = new LoginContext(SecurityConstants.CLIENT_JAAS_PASSWORD, subject, handler);
LoginContext lgc = new LoginContext(SecurityConstants.CLIENT_JAAS_CERTIFICATE, subject, handler);
lgup.login();
postClientAuth(subject, PasswordCredential.class);
lgc.login();
postClientAuth(subject, X509CertificateCredential.class);
} catch (javax.security.auth.login.LoginException e) {
throw (LoginException) new LoginException(e.toString()).initCause(e);
}
return null;
}
});
return subject;
} else {
AppservAccessController.doPrivileged(new PrivilegedAction() {
@Override
public java.lang.Object run() {
try {
LoginContext lg = new LoginContext(SecurityConstants.CLIENT_JAAS_PASSWORD, subject, handler);
lg.login();
postClientAuth(subject, PasswordCredential.class);
} catch (javax.security.auth.login.LoginException e) {
throw (LoginException) new LoginException(e.toString()).initCause(e);
}
return null;
}
});
return subject;
}
}
/**
* Perform logout on the client side.
*
* @exception LoginException
*/
public static void doClientLogout() throws LoginException {
unsetClientSecurityContext();
}
/**
* Performs Digest authentication based on RFC 2617. It
*
* @param digestCred DigestCredentials
*/
public static void login(DigestCredentials digestCred) throws javax.security.auth.login.LoginException {
Subject subject = new Subject();
subject.getPrivateCredentials().add(digestCred);
String jaasCtx = null;
try {
jaasCtx = Realm.getInstance(digestCred.getRealmName()).getJAASContext();
} catch (Exception ex) {
if (ex instanceof LoginException) {
throw (LoginException) ex;
} else {
throw (LoginException) new LoginException(ex.toString()).initCause(ex);
}
}
try {
// A dummyCallback is used to satisfy JAAS but it is never used.
// name/pwd info is already contained in Subject's Credential
LoginContext lg = new LoginContext(jaasCtx, subject, dummyCallback);
lg.login();
} catch (Exception e) {
if (_logger.isLoggable(Level.INFO)) {
_logger.log(Level.INFO, SecurityLoggerInfo.auditAtnRefusedError, digestCred.getUserName());
}
if (_logger.isLoggable(Level.FINEST)) {
_logger.log(Level.FINEST, "doPasswordLogin fails", e);
}
if (getAuditManager().isAuditOn()) {
getAuditManager().authentication(digestCred.getUserName(), digestCred.getRealmName(), false);
}
if (e instanceof LoginException) {
throw (LoginException) e;
} else {
throw (LoginException) new LoginException("Login failed: " + e.getMessage()).initCause(e);
}
}
setSecurityContext(digestCred.getUserName(), subject, digestCred.getRealmName());
}
/**
* Extract the relevant username and realm information from the subject and sets the correct state in the security context. The
* relevant information is set into the Thread Local Storage from which then is extracted to send over the wire.
*
* @param Subject the subject returned by the JAAS login.
* @param Class the class of the credential object stored in the subject
*
*/
private static void postClientAuth(Subject subject, Class<?> clazz) {
final Class<?> clas = clazz;
final Subject fs = subject;
Set credset = (Set) AppservAccessController.doPrivileged(new PrivilegedAction() {
@Override
public java.lang.Object run() {
if (_logger.isLoggable(Level.FINEST)) {
_logger.log(Level.FINEST, "LCD post login subject :" + fs);
}
return fs.getPrivateCredentials(clas);
}
});
final Iterator iter = credset.iterator();
while (iter.hasNext()) {
Object obj = null;
try {
obj = AppservAccessController.doPrivileged(new PrivilegedAction() {
@Override
public java.lang.Object run() {
return iter.next();
}
});
} catch (Exception e) {
// should never come here
_logger.log(Level.SEVERE, SecurityLoggerInfo.securityAccessControllerActionError, e);
}
if (obj instanceof PasswordCredential) {
PasswordCredential p = (PasswordCredential) obj;
String user = p.getUser();
if (_logger.isLoggable(Level.FINEST)) {
String realm = p.getRealm();
_logger.log(Level.FINEST, "In LCD user-pass login:" + user + " realm :" + realm);
}
setClientSecurityContext(user, fs);
return;
} else if (obj instanceof X509CertificateCredential) {
X509CertificateCredential p = (X509CertificateCredential) obj;
String user = p.getAlias();
if (_logger.isLoggable(Level.FINEST)) {
String realm = p.getRealm();
_logger.log(Level.FINEST, "In LCD cert-login::" + user + " realm :" + realm);
}
setClientSecurityContext(user, fs);
return;
}
}
}
/**
* Sets the security context on the appclient side. It sets the relevant information into the TLS
*
* @param String username is the user who authenticated
* @param Subject is the subject representation of the user
* @param Credentials the credentials that the server associated with it
*/
private static void setClientSecurityContext(String username, Subject subject) {
ClientSecurityContext securityContext = new ClientSecurityContext(username, subject);
ClientSecurityContext.setCurrent(securityContext);
}
/**
* Unsets the current appclient security context on the Thread Local Storage
*/
private static void unsetClientSecurityContext() {
ClientSecurityContext.setCurrent(null);
}
}