/
RealmBase.java
1558 lines (1316 loc) · 53.4 KB
/
RealmBase.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.realm;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.servlet.annotation.ServletSecurity.TransportGuarantee;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.CredentialHandler;
import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.Realm;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.Wrapper;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.util.LifecycleMBeanBase;
import org.apache.catalina.util.SessionConfig;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.buf.B2CConverter;
import org.apache.tomcat.util.buf.HexUtils;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.util.security.ConcurrentMessageDigest;
import org.apache.tomcat.util.security.MD5Encoder;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSName;
/**
* Simple implementation of <b>Realm</b> that reads an XML file to configure
* the valid users, passwords, and roles. The file format (and default file
* location) are identical to those currently supported by Tomcat 3.X.
*
* @author Craig R. McClanahan
*/
public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
private static final Log log = LogFactory.getLog(RealmBase.class);
private static final List<Class<? extends DigestCredentialHandlerBase>> credentialHandlerClasses =
new ArrayList<>();
static {
// Order is important since it determines the search order for a
// matching handler if only an algorithm is specified when calling
// main()
credentialHandlerClasses.add(MessageDigestCredentialHandler.class);
credentialHandlerClasses.add(SecretKeyCredentialHandler.class);
}
// ----------------------------------------------------- Instance Variables
/**
* The Container with which this Realm is associated.
*/
protected Container container = null;
/**
* Container log
*/
protected Log containerLog = null;
private CredentialHandler credentialHandler;
/**
* The string manager for this package.
*/
protected static final StringManager sm = StringManager.getManager(RealmBase.class);
/**
* The property change support for this component.
*/
protected final PropertyChangeSupport support = new PropertyChangeSupport(this);
/**
* Should we validate client certificate chains when they are presented?
*/
protected boolean validate = true;
/**
* The name of the class to use for retrieving user names from X509
* certificates.
*/
protected String x509UsernameRetrieverClassName;
/**
* The object that will extract user names from X509 client certificates.
*/
protected X509UsernameRetriever x509UsernameRetriever;
/**
* The all role mode.
*/
protected AllRolesMode allRolesMode = AllRolesMode.STRICT_MODE;
/**
* When processing users authenticated via the GSS-API, should any
* "@..." be stripped from the end of the user name?
*/
protected boolean stripRealmForGss = true;
private int transportGuaranteeRedirectStatus = HttpServletResponse.SC_FOUND;
// ------------------------------------------------------------- Properties
/**
* @return The HTTP status code used when the container needs to issue an
* HTTP redirect to meet the requirements of a configured transport
* guarantee.
*/
public int getTransportGuaranteeRedirectStatus() {
return transportGuaranteeRedirectStatus;
}
/**
* Set the HTTP status code used when the container needs to issue an HTTP
* redirect to meet the requirements of a configured transport guarantee.
*
* @param transportGuaranteeRedirectStatus The status to use. This value is
* not validated
*/
public void setTransportGuaranteeRedirectStatus(int transportGuaranteeRedirectStatus) {
this.transportGuaranteeRedirectStatus = transportGuaranteeRedirectStatus;
}
@Override
public CredentialHandler getCredentialHandler() {
return credentialHandler;
}
@Override
public void setCredentialHandler(CredentialHandler credentialHandler) {
this.credentialHandler = credentialHandler;
}
/**
* Return the Container with which this Realm has been associated.
*/
@Override
public Container getContainer() {
return (container);
}
/**
* Set the Container with which this Realm has been associated.
*
* @param container The associated Container
*/
@Override
public void setContainer(Container container) {
Container oldContainer = this.container;
this.container = container;
support.firePropertyChange("container", oldContainer, this.container);
}
/**
* Return the all roles mode.
* @return A string representation of the current all roles mode
*/
public String getAllRolesMode() {
return allRolesMode.toString();
}
/**
* Set the all roles mode.
* @param allRolesMode A string representation of the new all roles mode
*/
public void setAllRolesMode(String allRolesMode) {
this.allRolesMode = AllRolesMode.toMode(allRolesMode);
}
/**
* Return the "validate certificate chains" flag.
* @return The value of the validate certificate chains flag
*/
public boolean getValidate() {
return validate;
}
/**
* Set the "validate certificate chains" flag.
*
* @param validate The new validate certificate chains flag
*/
public void setValidate(boolean validate) {
this.validate = validate;
}
/**
* Gets the name of the class that will be used to extract user names
* from X509 client certificates.
* @return The name of the class that will be used to extract user names
* from X509 client certificates.
*/
public String getX509UsernameRetrieverClassName() {
return x509UsernameRetrieverClassName;
}
/**
* Sets the name of the class that will be used to extract user names
* from X509 client certificates. The class must implement
* X509UsernameRetriever.
*
* @param className The name of the class that will be used to extract user names
* from X509 client certificates.
* @see X509UsernameRetriever
*/
public void setX509UsernameRetrieverClassName(String className) {
this.x509UsernameRetrieverClassName = className;
}
public boolean isStripRealmForGss() {
return stripRealmForGss;
}
public void setStripRealmForGss(boolean stripRealmForGss) {
this.stripRealmForGss = stripRealmForGss;
}
// --------------------------------------------------------- Public Methods
/**
* Add a property change listener to this component.
*
* @param listener The listener to add
*/
@Override
public void addPropertyChangeListener(PropertyChangeListener listener) {
support.addPropertyChangeListener(listener);
}
/**
* Return the Principal associated with the specified username, if there
* is one; otherwise return <code>null</code>.
*
* @param username Username of the Principal to look up
*/
@Override
public Principal authenticate(String username) {
if (username == null) {
return null;
}
if (containerLog.isTraceEnabled()) {
containerLog.trace(sm.getString("realmBase.authenticateSuccess", username));
}
return getPrincipal(username);
}
/**
* Return the Principal associated with the specified username and
* credentials, if there is one; otherwise return <code>null</code>.
*
* @param username Username of the Principal to look up
* @param credentials Password or other credentials to use in
* authenticating this username
* @return the associated principal, or <code>null</code> if there is none.
*/
@Override
public Principal authenticate(String username, String credentials) {
// No user or no credentials
// Can't possibly authenticate, don't bother doing anything.
if(username == null || credentials == null) {
if (containerLog.isTraceEnabled()) {
containerLog.trace(sm.getString("realmBase.authenticateFailure",
username));
}
return null;
}
// Look up the user's credentials
String serverCredentials = getPassword(username);
if (serverCredentials == null) {
// User was not found
// Waste a bit of time as not to reveal that the user does not exist.
getCredentialHandler().mutate(credentials);
if (containerLog.isTraceEnabled()) {
containerLog.trace(sm.getString("realmBase.authenticateFailure",
username));
}
return null;
}
boolean validated = getCredentialHandler().matches(credentials, serverCredentials);
if (validated) {
if (containerLog.isTraceEnabled()) {
containerLog.trace(sm.getString("realmBase.authenticateSuccess",
username));
}
return getPrincipal(username);
} else {
if (containerLog.isTraceEnabled()) {
containerLog.trace(sm.getString("realmBase.authenticateFailure",
username));
}
return null;
}
}
/**
* Try to authenticate with the specified username, which
* matches the digest calculated using the given parameters using the
* method described in RFC 2617 (which is a superset of RFC 2069).
*
* @param username Username of the Principal to look up
* @param clientDigest Digest which has been submitted by the client
* @param nonce Unique (or supposedly unique) token which has been used
* for this request
* @param nc the nonce counter
* @param cnonce the client chosen nonce
* @param qop the "quality of protection" (<code>nc</code> and <code>cnonce</code>
* will only be used, if <code>qop</code> is not <code>null</code>).
* @param realm Realm name
* @param md5a2 Second MD5 digest used to calculate the digest :
* MD5(Method + ":" + uri)
* @return the associated principal, or <code>null</code> if there is none.
*/
@Override
public Principal authenticate(String username, String clientDigest,
String nonce, String nc, String cnonce,
String qop, String realm,
String md5a2) {
// In digest auth, digests are always lower case
String md5a1 = getDigest(username, realm);
if (md5a1 == null)
return null;
md5a1 = md5a1.toLowerCase(Locale.ENGLISH);
String serverDigestValue;
if (qop == null) {
serverDigestValue = md5a1 + ":" + nonce + ":" + md5a2;
} else {
serverDigestValue = md5a1 + ":" + nonce + ":" + nc + ":" +
cnonce + ":" + qop + ":" + md5a2;
}
byte[] valueBytes = null;
try {
valueBytes = serverDigestValue.getBytes(getDigestCharset());
} catch (UnsupportedEncodingException uee) {
log.error("Illegal digestEncoding: " + getDigestEncoding(), uee);
throw new IllegalArgumentException(uee.getMessage());
}
String serverDigest = MD5Encoder.encode(ConcurrentMessageDigest.digestMD5(valueBytes));
if (log.isDebugEnabled()) {
log.debug("Digest : " + clientDigest + " Username:" + username
+ " ClientSigest:" + clientDigest + " nonce:" + nonce
+ " nc:" + nc + " cnonce:" + cnonce + " qop:" + qop
+ " realm:" + realm + "md5a2:" + md5a2
+ " Server digest:" + serverDigest);
}
if (serverDigest.equals(clientDigest)) {
return getPrincipal(username);
}
return null;
}
/**
* Return the Principal associated with the specified chain of X509
* client certificates. If there is none, return <code>null</code>.
*
* @param certs Array of client certificates, with the first one in
* the array being the certificate of the client itself.
*/
@Override
public Principal authenticate(X509Certificate certs[]) {
if ((certs == null) || (certs.length < 1))
return (null);
// Check the validity of each certificate in the chain
if (log.isDebugEnabled())
log.debug("Authenticating client certificate chain");
if (validate) {
for (int i = 0; i < certs.length; i++) {
if (log.isDebugEnabled())
log.debug(" Checking validity for '" +
certs[i].getSubjectDN().getName() + "'");
try {
certs[i].checkValidity();
} catch (Exception e) {
if (log.isDebugEnabled())
log.debug(" Validity exception", e);
return (null);
}
}
}
// Check the existence of the client Principal in our database
return (getPrincipal(certs[0]));
}
/**
* {@inheritDoc}
*/
@Override
public Principal authenticate(GSSContext gssContext, boolean storeCred) {
if (gssContext.isEstablished()) {
GSSName gssName = null;
try {
gssName = gssContext.getSrcName();
} catch (GSSException e) {
log.warn(sm.getString("realmBase.gssNameFail"), e);
}
if (gssName!= null) {
String name = gssName.toString();
if (isStripRealmForGss()) {
int i = name.indexOf('@');
if (i > 0) {
// Zero so we don;t leave a zero length name
name = name.substring(0, i);
}
}
GSSCredential gssCredential = null;
if (storeCred && gssContext.getCredDelegState()) {
try {
gssCredential = gssContext.getDelegCred();
} catch (GSSException e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString(
"realmBase.delegatedCredentialFail", name),
e);
}
}
}
return getPrincipal(name, gssCredential);
}
}
// Fail in all other cases
return null;
}
/**
* Execute a periodic task, such as reloading, etc. This method will be
* invoked inside the classloading context of this container. Unexpected
* throwables will be caught and logged.
*/
@Override
public void backgroundProcess() {
// NOOP in base class
}
/**
* Return the SecurityConstraints configured to guard the request URI for
* this request, or <code>null</code> if there is no such constraint.
*
* @param request Request we are processing
* @param context Context the Request is mapped to
*/
@Override
public SecurityConstraint [] findSecurityConstraints(Request request,
Context context) {
ArrayList<SecurityConstraint> results = null;
// Are there any defined security constraints?
SecurityConstraint constraints[] = context.findConstraints();
if ((constraints == null) || (constraints.length == 0)) {
if (log.isDebugEnabled())
log.debug(" No applicable constraints defined");
return (null);
}
// Check each defined security constraint
String uri = request.getRequestPathMB().toString();
// Bug47080 - in rare cases this may be null
// Mapper treats as '/' do the same to prevent NPE
if (uri == null) {
uri = "/";
}
String method = request.getMethod();
int i;
boolean found = false;
for (i = 0; i < constraints.length; i++) {
SecurityCollection [] collection = constraints[i].findCollections();
// If collection is null, continue to avoid an NPE
// See Bugzilla 30624
if ( collection == null) {
continue;
}
if (log.isDebugEnabled()) {
log.debug(" Checking constraint '" + constraints[i] +
"' against " + method + " " + uri + " --> " +
constraints[i].included(uri, method));
}
for(int j=0; j < collection.length; j++){
String [] patterns = collection[j].findPatterns();
// If patterns is null, continue to avoid an NPE
// See Bugzilla 30624
if ( patterns == null) {
continue;
}
for(int k=0; k < patterns.length; k++) {
if(uri.equals(patterns[k])) {
found = true;
if(collection[j].findMethod(method)) {
if(results == null) {
results = new ArrayList<>();
}
results.add(constraints[i]);
}
}
}
}
}
if(found) {
return resultsToArray(results);
}
int longest = -1;
for (i = 0; i < constraints.length; i++) {
SecurityCollection [] collection = constraints[i].findCollections();
// If collection is null, continue to avoid an NPE
// See Bugzilla 30624
if ( collection == null) {
continue;
}
if (log.isDebugEnabled()) {
log.debug(" Checking constraint '" + constraints[i] +
"' against " + method + " " + uri + " --> " +
constraints[i].included(uri, method));
}
for(int j=0; j < collection.length; j++){
String [] patterns = collection[j].findPatterns();
// If patterns is null, continue to avoid an NPE
// See Bugzilla 30624
if ( patterns == null) {
continue;
}
boolean matched = false;
int length = -1;
for(int k=0; k < patterns.length; k++) {
String pattern = patterns[k];
if(pattern.startsWith("/") && pattern.endsWith("/*") &&
pattern.length() >= longest) {
if(pattern.length() == 2) {
matched = true;
length = pattern.length();
} else if(pattern.regionMatches(0,uri,0,
pattern.length()-1) ||
(pattern.length()-2 == uri.length() &&
pattern.regionMatches(0,uri,0,
pattern.length()-2))) {
matched = true;
length = pattern.length();
}
}
}
if(matched) {
if(length > longest) {
found = false;
if(results != null) {
results.clear();
}
longest = length;
}
if(collection[j].findMethod(method)) {
found = true;
if(results == null) {
results = new ArrayList<>();
}
results.add(constraints[i]);
}
}
}
}
if(found) {
return resultsToArray(results);
}
for (i = 0; i < constraints.length; i++) {
SecurityCollection [] collection = constraints[i].findCollections();
// If collection is null, continue to avoid an NPE
// See Bugzilla 30624
if ( collection == null) {
continue;
}
if (log.isDebugEnabled()) {
log.debug(" Checking constraint '" + constraints[i] +
"' against " + method + " " + uri + " --> " +
constraints[i].included(uri, method));
}
boolean matched = false;
int pos = -1;
for(int j=0; j < collection.length; j++){
String [] patterns = collection[j].findPatterns();
// If patterns is null, continue to avoid an NPE
// See Bugzilla 30624
if ( patterns == null) {
continue;
}
for(int k=0; k < patterns.length && !matched; k++) {
String pattern = patterns[k];
if(pattern.startsWith("*.")){
int slash = uri.lastIndexOf('/');
int dot = uri.lastIndexOf('.');
if(slash >= 0 && dot > slash &&
dot != uri.length()-1 &&
uri.length()-dot == pattern.length()-1) {
if(pattern.regionMatches(1,uri,dot,uri.length()-dot)) {
matched = true;
pos = j;
}
}
}
}
}
if(matched) {
found = true;
if(collection[pos].findMethod(method)) {
if(results == null) {
results = new ArrayList<>();
}
results.add(constraints[i]);
}
}
}
if(found) {
return resultsToArray(results);
}
for (i = 0; i < constraints.length; i++) {
SecurityCollection [] collection = constraints[i].findCollections();
// If collection is null, continue to avoid an NPE
// See Bugzilla 30624
if ( collection == null) {
continue;
}
if (log.isDebugEnabled()) {
log.debug(" Checking constraint '" + constraints[i] +
"' against " + method + " " + uri + " --> " +
constraints[i].included(uri, method));
}
for(int j=0; j < collection.length; j++){
String [] patterns = collection[j].findPatterns();
// If patterns is null, continue to avoid an NPE
// See Bugzilla 30624
if ( patterns == null) {
continue;
}
boolean matched = false;
for(int k=0; k < patterns.length && !matched; k++) {
String pattern = patterns[k];
if(pattern.equals("/")){
matched = true;
}
}
if(matched) {
if(results == null) {
results = new ArrayList<>();
}
results.add(constraints[i]);
}
}
}
if(results == null) {
// No applicable security constraint was found
if (log.isDebugEnabled())
log.debug(" No applicable constraint located");
}
return resultsToArray(results);
}
/**
* Convert an ArrayList to a SecurityContraint [].
*/
private SecurityConstraint [] resultsToArray(
ArrayList<SecurityConstraint> results) {
if(results == null || results.size() == 0) {
return null;
}
SecurityConstraint [] array = new SecurityConstraint[results.size()];
results.toArray(array);
return array;
}
/**
* Perform access control based on the specified authorization constraint.
* Return <code>true</code> if this constraint is satisfied and processing
* should continue, or <code>false</code> otherwise.
*
* @param request Request we are processing
* @param response Response we are creating
* @param constraints Security constraint we are enforcing
* @param context The Context to which client of this class is attached.
*
* @exception IOException if an input/output error occurs
*/
@Override
public boolean hasResourcePermission(Request request,
Response response,
SecurityConstraint []constraints,
Context context)
throws IOException {
if (constraints == null || constraints.length == 0)
return true;
// Which user principal have we already authenticated?
Principal principal = request.getPrincipal();
boolean status = false;
boolean denyfromall = false;
for(int i=0; i < constraints.length; i++) {
SecurityConstraint constraint = constraints[i];
String roles[];
if (constraint.getAllRoles()) {
// * means all roles defined in web.xml
roles = request.getContext().findSecurityRoles();
} else {
roles = constraint.findAuthRoles();
}
if (roles == null)
roles = new String[0];
if (log.isDebugEnabled())
log.debug(" Checking roles " + principal);
if (constraint.getAuthenticatedUsers() && principal != null) {
if (log.isDebugEnabled()) {
log.debug("Passing all authenticated users");
}
status = true;
} else if (roles.length == 0 && !constraint.getAllRoles() &&
!constraint.getAuthenticatedUsers()) {
if(constraint.getAuthConstraint()) {
if( log.isDebugEnabled() )
log.debug("No roles");
status = false; // No listed roles means no access at all
denyfromall = true;
break;
}
if(log.isDebugEnabled())
log.debug("Passing all access");
status = true;
} else if (principal == null) {
if (log.isDebugEnabled())
log.debug(" No user authenticated, cannot grant access");
} else {
for (int j = 0; j < roles.length; j++) {
if (hasRole(null, principal, roles[j])) {
status = true;
if( log.isDebugEnabled() )
log.debug( "Role found: " + roles[j]);
}
else if( log.isDebugEnabled() )
log.debug( "No role found: " + roles[j]);
}
}
}
if (!denyfromall && allRolesMode != AllRolesMode.STRICT_MODE &&
!status && principal != null) {
if (log.isDebugEnabled()) {
log.debug("Checking for all roles mode: " + allRolesMode);
}
// Check for an all roles(role-name="*")
for (int i = 0; i < constraints.length; i++) {
SecurityConstraint constraint = constraints[i];
String roles[];
// If the all roles mode exists, sets
if (constraint.getAllRoles()) {
if (allRolesMode == AllRolesMode.AUTH_ONLY_MODE) {
if (log.isDebugEnabled()) {
log.debug("Granting access for role-name=*, auth-only");
}
status = true;
break;
}
// For AllRolesMode.STRICT_AUTH_ONLY_MODE there must be zero roles
roles = request.getContext().findSecurityRoles();
if (roles.length == 0 && allRolesMode == AllRolesMode.STRICT_AUTH_ONLY_MODE) {
if (log.isDebugEnabled()) {
log.debug("Granting access for role-name=*, strict auth-only");
}
status = true;
break;
}
}
}
}
// Return a "Forbidden" message denying access to this resource
if(!status) {
response.sendError
(HttpServletResponse.SC_FORBIDDEN,
sm.getString("realmBase.forbidden"));
}
return status;
}
/**
* Return <code>true</code> if the specified Principal has the specified
* security role, within the context of this Realm; otherwise return
* <code>false</code>. This method can be overridden by Realm
* implementations, but the default is adequate when an instance of
* <code>GenericPrincipal</code> is used to represent authenticated
* Principals from this Realm.
*
* @param principal Principal for whom the role is to be checked
* @param role Security role to be checked
*/
@Override
public boolean hasRole(Wrapper wrapper, Principal principal, String role) {
// Check for a role alias defined in a <security-role-ref> element
if (wrapper != null) {
String realRole = wrapper.findSecurityReference(role);
if (realRole != null)
role = realRole;
}
// Should be overridden in JAASRealm - to avoid pretty inefficient conversions
if ((principal == null) || (role == null) ||
!(principal instanceof GenericPrincipal))
return false;
GenericPrincipal gp = (GenericPrincipal) principal;
boolean result = gp.hasRole(role);
if (log.isDebugEnabled()) {
String name = principal.getName();
if (result)
log.debug(sm.getString("realmBase.hasRoleSuccess", name, role));
else
log.debug(sm.getString("realmBase.hasRoleFailure", name, role));
}
return (result);
}
/**
* Enforce any user data constraint required by the security constraint
* guarding this request URI. Return <code>true</code> if this constraint
* was not violated and processing should continue, or <code>false</code>
* if we have created a response already.
*
* @param request Request we are processing
* @param response Response we are creating
* @param constraints Security constraint being checked
*
* @exception IOException if an input/output error occurs
*/
@Override
public boolean hasUserDataPermission(Request request,
Response response,
SecurityConstraint []constraints)
throws IOException {
// Is there a relevant user data constraint?
if (constraints == null || constraints.length == 0) {
if (log.isDebugEnabled())
log.debug(" No applicable security constraint defined");
return true;
}
for(int i=0; i < constraints.length; i++) {
SecurityConstraint constraint = constraints[i];
String userConstraint = constraint.getUserConstraint();
if (userConstraint == null) {
if (log.isDebugEnabled())
log.debug(" No applicable user data constraint defined");
return true;
}
if (userConstraint.equals(TransportGuarantee.NONE.name())) {
if (log.isDebugEnabled())
log.debug(" User data constraint has no restrictions");
return true;
}
}
// Validate the request against the user data constraint
if (request.getRequest().isSecure()) {
if (log.isDebugEnabled())
log.debug(" User data constraint already satisfied");
return true;
}
// Initialize variables we need to determine the appropriate action
int redirectPort = request.getConnector().getRedirectPort();
// Is redirecting disabled?
if (redirectPort <= 0) {
if (log.isDebugEnabled())
log.debug(" SSL redirect is disabled");