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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
|
/*
* 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.authenticator;
import java.io.IOException;
import java.security.Principal;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import jakarta.security.auth.message.AuthException;
import jakarta.security.auth.message.AuthStatus;
import jakarta.security.auth.message.MessageInfo;
import jakarta.security.auth.message.config.AuthConfigFactory;
import jakarta.security.auth.message.config.AuthConfigProvider;
import jakarta.security.auth.message.config.RegistrationListener;
import jakarta.security.auth.message.config.ServerAuthConfig;
import jakarta.security.auth.message.config.ServerAuthContext;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.Authenticator;
import org.apache.catalina.Contained;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Realm;
import org.apache.catalina.Session;
import org.apache.catalina.TomcatPrincipal;
import org.apache.catalina.Valve;
import org.apache.catalina.authenticator.jaspic.MessageInfoImpl;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.filters.CorsFilter;
import org.apache.catalina.filters.RemoteIpFilter;
import org.apache.catalina.realm.GenericPrincipal;
import org.apache.catalina.util.FilterUtil;
import org.apache.catalina.util.SessionIdGeneratorBase;
import org.apache.catalina.util.StandardSessionIdGenerator;
import org.apache.catalina.valves.RemoteIpValve;
import org.apache.catalina.valves.ValveBase;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.apache.tomcat.util.descriptor.web.LoginConfig;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.apache.tomcat.util.http.FastHttpDateFormat;
import org.apache.tomcat.util.http.RequestUtil;
import org.apache.tomcat.util.res.StringManager;
/**
* Basic implementation of the <b>Valve</b> interface that enforces the <code><security-constraint></code>
* elements in the web application deployment descriptor. This functionality is implemented as a Valve so that it can be
* omitted in environments that do not require these features. Individual implementations of each supported
* authentication method can subclass this base class as required.
* <p>
* <b>USAGE CONSTRAINT</b>: When this class is utilized, the Context to which it is attached (or a parent Container in a
* hierarchy) must have an associated Realm that can be used for authenticating users and enumerating the roles to which
* they have been assigned.
* <p>
* <b>USAGE CONSTRAINT</b>: This Valve is only useful when processing HTTP requests. Requests of any other type will
* simply be passed through.
*
* @author Craig R. McClanahan
*/
public abstract class AuthenticatorBase extends ValveBase implements Authenticator, RegistrationListener {
private final Log log = LogFactory.getLog(AuthenticatorBase.class); // must not be static
/**
* "Expires" header always set to Date(1), so generate once only
*/
private static final String DATE_ONE = FastHttpDateFormat.formatDate(1);
/**
* The string manager for this package.
*/
protected static final StringManager sm = StringManager.getManager(AuthenticatorBase.class);
/**
* Authentication header
*/
protected static final String AUTH_HEADER_NAME = "WWW-Authenticate";
/**
* Default authentication realm name.
*/
protected static final String REALM_NAME = "Authentication required";
protected static String getRealmName(Context context) {
if (context == null) {
// Very unlikely
return REALM_NAME;
}
LoginConfig config = context.getLoginConfig();
if (config == null) {
return REALM_NAME;
}
String result = config.getRealmName();
if (result == null) {
return REALM_NAME;
}
return result;
}
// ------------------------------------------------------ Constructor
public AuthenticatorBase() {
super(true);
}
// ----------------------------------------------------- Instance Variables
/**
* Should a session always be used once a user is authenticated? This may offer some performance benefits since the
* session can then be used to cache the authenticated Principal, hence removing the need to authenticate the user
* via the Realm on every request. This may be of help for combinations such as BASIC authentication used with the
* JNDIRealm or DataSourceRealms. However, there will also be the performance cost of creating and GC'ing the
* session. By default, a session will not be created.
*/
protected boolean alwaysUseSession = false;
/**
* Should we cache authenticated Principals if the request is part of an HTTP session?
*/
protected boolean cache = true;
/**
* Should the session ID, if any, be changed upon a successful authentication to prevent a session fixation attack?
*/
protected boolean changeSessionIdOnAuthentication = true;
/**
* The Context to which this Valve is attached.
*/
protected Context context = null;
/**
* Flag to determine if we disable proxy caching, or leave the issue up to the webapp developer.
*/
protected boolean disableProxyCaching = true;
/**
* Flag to determine if we disable proxy caching with headers incompatible with IE.
*/
protected boolean securePagesWithPragma = false;
/**
* The Java class name of the secure random number generator class to be used when generating SSO session
* identifiers. The random number generator class must be self-seeding and have a zero-argument constructor. If not
* specified, an instance of {@link java.security.SecureRandom} will be generated.
*/
protected String secureRandomClass = null;
/**
* The name of the algorithm to use to create instances of {@link java.security.SecureRandom} which are used to
* generate SSO session IDs. If no algorithm is specified, SHA1PRNG is used. If SHA1PRNG is not available, the
* platform default will be used. To use the platform default (which may be SHA1PRNG), specify the empty string. If
* an invalid algorithm and/or provider is specified the SecureRandom instances will be created using the defaults.
* If that fails, the SecureRandom instances will be created using platform defaults.
*/
protected String secureRandomAlgorithm = SessionIdGeneratorBase.DEFAULT_SECURE_RANDOM_ALGORITHM;
/**
* The name of the provider to use to create instances of {@link java.security.SecureRandom} which are used to
* generate session SSO IDs. If no provider is specified the platform default is used. If an invalid algorithm
* and/or provider is specified the SecureRandom instances will be created using the defaults. If that fails, the
* SecureRandom instances will be created using platform defaults.
*/
protected String secureRandomProvider = null;
/**
* The name of the JASPIC callback handler class. If none is specified the default
* {@link org.apache.catalina.authenticator.jaspic.CallbackHandlerImpl} will be used.
*/
protected String jaspicCallbackHandlerClass = "org.apache.catalina.authenticator.jaspic.CallbackHandlerImpl";
/**
* Should the auth information (remote user and auth type) be returned as response headers for a forwarded/proxied
* request? When the {@link RemoteIpValve} or {@link RemoteIpFilter} mark a forwarded request with the
* {@link Globals#REQUEST_FORWARDED_ATTRIBUTE} this authenticator can return the values of
* {@link HttpServletRequest#getRemoteUser()} and {@link HttpServletRequest#getAuthType()} as response headers
* {@code remote-user} and {@code auth-type} to a reverse proxy. This is useful, e.g., for access log consistency or
* other decisions to make.
*/
protected boolean sendAuthInfoResponseHeaders = false;
protected SessionIdGeneratorBase sessionIdGenerator = null;
/**
* The SingleSignOn implementation in our request processing chain, if there is one.
*/
protected SingleSignOn sso = null;
private AllowCorsPreflight allowCorsPreflight = AllowCorsPreflight.NEVER;
private volatile String jaspicAppContextID = null;
private volatile Optional<AuthConfigProvider> jaspicProvider = null;
private volatile CallbackHandler jaspicCallbackHandler = null;
// ------------------------------------------------------------- Properties
public String getAllowCorsPreflight() {
return allowCorsPreflight.name().toLowerCase(Locale.ENGLISH);
}
public void setAllowCorsPreflight(String allowCorsPreflight) {
this.allowCorsPreflight = AllowCorsPreflight.valueOf(allowCorsPreflight.trim().toUpperCase(Locale.ENGLISH));
}
public boolean getAlwaysUseSession() {
return alwaysUseSession;
}
public void setAlwaysUseSession(boolean alwaysUseSession) {
this.alwaysUseSession = alwaysUseSession;
}
/**
* Return the cache authenticated Principals flag.
*
* @return <code>true</code> if authenticated Principals will be cached, otherwise <code>false</code>
*/
public boolean getCache() {
return this.cache;
}
/**
* Set the cache authenticated Principals flag.
*
* @param cache The new cache flag
*/
public void setCache(boolean cache) {
this.cache = cache;
}
@Override
public Container getContainer() {
return this.context;
}
@Override
public void setContainer(Container container) {
if (container != null && !(container instanceof Context)) {
throw new IllegalArgumentException(sm.getString("authenticator.notContext"));
}
super.setContainer(container);
this.context = (Context) container;
}
/**
* Return the flag that states if we add headers to disable caching by proxies.
*
* @return <code>true</code> if the headers will be added, otherwise <code>false</code>
*/
public boolean getDisableProxyCaching() {
return disableProxyCaching;
}
/**
* Set the value of the flag that states if we add headers to disable caching by proxies.
*
* @param nocache <code>true</code> if we add headers to disable proxy caching, <code>false</code> if we leave the
* headers alone.
*/
public void setDisableProxyCaching(boolean nocache) {
disableProxyCaching = nocache;
}
/**
* Return the flag that states, if proxy caching is disabled, what headers we add to disable the caching.
*
* @return <code>true</code> if a Pragma header should be used, otherwise <code>false</code>
*/
public boolean getSecurePagesWithPragma() {
return securePagesWithPragma;
}
/**
* Set the value of the flag that states what headers we add to disable proxy caching.
*
* @param securePagesWithPragma <code>true</code> if we add headers which are incompatible with downloading office
* documents in IE under SSL but which fix a caching problem in Mozilla.
*/
public void setSecurePagesWithPragma(boolean securePagesWithPragma) {
this.securePagesWithPragma = securePagesWithPragma;
}
/**
* Return the flag that states if we should change the session ID of an existing session upon successful
* authentication.
*
* @return <code>true</code> to change session ID upon successful authentication, <code>false</code> to do not
* perform the change.
*/
public boolean getChangeSessionIdOnAuthentication() {
return changeSessionIdOnAuthentication;
}
/**
* Set the value of the flag that states if we should change the session ID of an existing session upon successful
* authentication.
*
* @param changeSessionIdOnAuthentication <code>true</code> to change session ID upon successful authentication,
* <code>false</code> to do not perform the change.
*/
public void setChangeSessionIdOnAuthentication(boolean changeSessionIdOnAuthentication) {
this.changeSessionIdOnAuthentication = changeSessionIdOnAuthentication;
}
/**
* Return the secure random number generator class name.
*
* @return The fully qualified name of the SecureRandom implementation to use
*/
public String getSecureRandomClass() {
return this.secureRandomClass;
}
/**
* Set the secure random number generator class name.
*
* @param secureRandomClass The new secure random number generator class name
*/
public void setSecureRandomClass(String secureRandomClass) {
this.secureRandomClass = secureRandomClass;
}
/**
* Return the secure random number generator algorithm name.
*
* @return The name of the SecureRandom algorithm used
*/
public String getSecureRandomAlgorithm() {
return secureRandomAlgorithm;
}
/**
* Set the secure random number generator algorithm name.
*
* @param secureRandomAlgorithm The new secure random number generator algorithm name
*/
public void setSecureRandomAlgorithm(String secureRandomAlgorithm) {
this.secureRandomAlgorithm = secureRandomAlgorithm;
}
/**
* Return the secure random number generator provider name.
*
* @return The name of the SecureRandom provider
*/
public String getSecureRandomProvider() {
return secureRandomProvider;
}
/**
* Set the secure random number generator provider name.
*
* @param secureRandomProvider The new secure random number generator provider name
*/
public void setSecureRandomProvider(String secureRandomProvider) {
this.secureRandomProvider = secureRandomProvider;
}
/**
* Return the JASPIC callback handler class name
*
* @return The name of the JASPIC callback handler
*/
public String getJaspicCallbackHandlerClass() {
return jaspicCallbackHandlerClass;
}
/**
* Set the JASPIC callback handler class name
*
* @param jaspicCallbackHandlerClass The new JASPIC callback handler class name
*/
public void setJaspicCallbackHandlerClass(String jaspicCallbackHandlerClass) {
this.jaspicCallbackHandlerClass = jaspicCallbackHandlerClass;
}
/**
* Returns the flag whether authentication information will be sent to a reverse proxy on a forwarded request.
*
* @return {@code true} if response headers shall be sent, {@code false} otherwise
*/
public boolean isSendAuthInfoResponseHeaders() {
return sendAuthInfoResponseHeaders;
}
/**
* Sets the flag whether authentication information will be sent to a reverse proxy on a forwarded request.
*
* @param sendAuthInfoResponseHeaders {@code true} if response headers shall be sent, {@code false} otherwise
*/
public void setSendAuthInfoResponseHeaders(boolean sendAuthInfoResponseHeaders) {
this.sendAuthInfoResponseHeaders = sendAuthInfoResponseHeaders;
}
// --------------------------------------------------------- Public Methods
/**
* Enforce the security restrictions in the web application deployment descriptor of our associated Context.
*
* @param request Request to be processed
* @param response Response to be processed
*
* @exception IOException if an input/output error occurs
* @exception ServletException if thrown by a processing element
*/
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
if (log.isTraceEnabled()) {
log.trace("Security checking request " + request.getMethod() + " " + request.getRequestURI());
}
// Have we got a cached authenticated Principal to record?
if (cache) {
Principal principal = request.getUserPrincipal();
if (principal == null) {
Session session = request.getSessionInternal(false);
if (session != null) {
principal = session.getPrincipal();
if (principal != null) {
if (log.isTraceEnabled()) {
log.trace("We have cached auth type " + session.getAuthType() + " for principal " +
principal);
}
request.setAuthType(session.getAuthType());
request.setUserPrincipal(principal);
}
}
}
}
boolean authRequired = isContinuationRequired(request);
Realm realm = this.context.getRealm();
// Is this request URI subject to a security constraint?
SecurityConstraint[] constraints = realm.findSecurityConstraints(request, this.context);
AuthConfigProvider jaspicProvider = getJaspicProvider();
if (jaspicProvider != null) {
authRequired = true;
}
if (constraints == null && !context.getPreemptiveAuthentication() && !authRequired) {
if (log.isTraceEnabled()) {
log.trace("Not subject to any constraint");
}
getNext().invoke(request, response);
return;
}
// Make sure that constrained resources are not cached by web proxies
// or browsers as caching can provide a security hole
if (constraints != null && disableProxyCaching && !"POST".equalsIgnoreCase(request.getMethod())) {
if (securePagesWithPragma) {
// Note: These can cause problems with downloading files with IE
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", DATE_ONE);
} else {
response.setHeader("Cache-Control", "private");
}
}
if (constraints != null) {
// Enforce any user data constraint for this security constraint
if (log.isTraceEnabled()) {
log.trace("Calling hasUserDataPermission()");
}
if (!realm.hasUserDataPermission(request, response, constraints)) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("authenticator.userDataPermissionFail"));
}
/*
* ASSERT: Authenticator already set the appropriate HTTP status code, so we do not have to do anything
* special
*/
return;
}
}
// Since authenticate modifies the response on failure,
// we have to check for allow-from-all first.
boolean hasAuthConstraint = false;
if (constraints != null) {
hasAuthConstraint = true;
for (int i = 0; i < constraints.length && hasAuthConstraint; i++) {
if (!constraints[i].getAuthConstraint()) {
hasAuthConstraint = false;
} else if (!constraints[i].getAllRoles() && !constraints[i].getAuthenticatedUsers()) {
String[] roles = constraints[i].findAuthRoles();
if (roles == null || roles.length == 0) {
hasAuthConstraint = false;
}
}
}
}
if (!authRequired && hasAuthConstraint) {
authRequired = true;
}
if (!authRequired && context.getPreemptiveAuthentication() && isPreemptiveAuthPossible(request)) {
authRequired = true;
}
JaspicState jaspicState = null;
if ((authRequired || constraints != null) && allowCorsPreflightBypass(request)) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("authenticator.corsBypass"));
}
getNext().invoke(request, response);
return;
}
if (authRequired) {
if (log.isTraceEnabled()) {
log.trace("Calling authenticate()");
}
if (jaspicProvider != null) {
jaspicState = getJaspicState(jaspicProvider, request, response, hasAuthConstraint);
if (jaspicState == null) {
return;
}
}
if (jaspicProvider == null && !doAuthenticate(request, response) ||
jaspicProvider != null && !authenticateJaspic(request, response, jaspicState, false)) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("authenticator.authenticationFail"));
}
/*
* ASSERT: Authenticator already set the appropriate HTTP status code, so we do not have to do anything
* special
*/
return;
}
}
if (constraints != null) {
if (log.isTraceEnabled()) {
log.trace("Calling accessControl()");
}
if (!realm.hasResourcePermission(request, response, constraints, this.context)) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("authenticator.userPermissionFail", request.getUserPrincipal().getName()));
}
/*
* ASSERT: AccessControl method has already set the appropriate HTTP status code, so we do not have to
* do anything special
*/
return;
}
}
// Any and all specified constraints have been satisfied
if (log.isTraceEnabled()) {
log.trace("Successfully passed all security constraints");
}
getNext().invoke(request, response);
if (jaspicProvider != null) {
secureResponseJspic(request, response, jaspicState);
}
}
protected boolean allowCorsPreflightBypass(Request request) {
boolean allowBypass = false;
if (allowCorsPreflight != AllowCorsPreflight.NEVER) {
// First check to see if this is a CORS Preflight request
// This is a subset of the tests in CorsFilter.checkRequestType
if ("OPTIONS".equals(request.getMethod())) {
String originHeader = request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN);
if (originHeader != null && !originHeader.isEmpty() && RequestUtil.isValidOrigin(originHeader) &&
!RequestUtil.isSameOrigin(request, originHeader)) {
String accessControlRequestMethodHeader =
request.getHeader(CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
if (accessControlRequestMethodHeader != null && !accessControlRequestMethodHeader.isEmpty()) {
// This appears to be a CORS Preflight request
if (allowCorsPreflight == AllowCorsPreflight.ALWAYS) {
allowBypass = true;
} else if (allowCorsPreflight == AllowCorsPreflight.FILTER) {
if (DispatcherType.REQUEST == request.getDispatcherType()) {
// Look at Filter configuration for the Context
// Can't cache this unless we add a listener to
// the Context to clear the cache on reload
for (FilterDef filterDef : request.getContext().findFilterDefs()) {
if (CorsFilter.class.getName().equals(filterDef.getFilterClass())) {
for (FilterMap filterMap : context.findFilterMaps()) {
if (filterMap.getFilterName().equals(filterDef.getFilterName())) {
if ((filterMap.getDispatcherMapping() & FilterMap.REQUEST) > 0) {
String requestPath = FilterUtil.getRequestPath(request);
if (FilterUtil.matchFiltersURL(filterMap, requestPath)) {
allowBypass = true;
}
}
// Found mappings for CORS filter.
// No need to look further
break;
}
}
// Found the CORS filter. No need to look further.
break;
}
}
}
} else {
// Unexpected enum type
}
}
}
}
}
return allowBypass;
}
@Override
public boolean authenticate(Request request, HttpServletResponse httpResponse) throws IOException {
AuthConfigProvider jaspicProvider = getJaspicProvider();
if (jaspicProvider == null) {
return doAuthenticate(request, httpResponse);
} else {
Response response = request.getResponse();
JaspicState jaspicState = getJaspicState(jaspicProvider, request, response, true);
if (jaspicState == null) {
return false;
}
boolean result = authenticateJaspic(request, response, jaspicState, true);
secureResponseJspic(request, response, jaspicState);
return result;
}
}
private void secureResponseJspic(Request request, Response response, JaspicState state) {
try {
state.serverAuthContext.secureResponse(state.messageInfo, null);
request.setRequest((HttpServletRequest) state.messageInfo.getRequestMessage());
response.setResponse((HttpServletResponse) state.messageInfo.getResponseMessage());
} catch (AuthException e) {
log.warn(sm.getString("authenticator.jaspicSecureResponseFail"), e);
}
}
private JaspicState getJaspicState(AuthConfigProvider jaspicProvider, Request request, Response response,
boolean authMandatory) throws IOException {
JaspicState jaspicState = new JaspicState();
jaspicState.messageInfo = new MessageInfoImpl(request.getRequest(), response.getResponse(), authMandatory);
try {
CallbackHandler callbackHandler = getCallbackHandler();
ServerAuthConfig serverAuthConfig =
jaspicProvider.getServerAuthConfig("HttpServlet", jaspicAppContextID, callbackHandler);
String authContextID = serverAuthConfig.getAuthContextID(jaspicState.messageInfo);
jaspicState.serverAuthContext = serverAuthConfig.getAuthContext(authContextID, null, null);
} catch (AuthException e) {
log.warn(sm.getString("authenticator.jaspicServerAuthContextFail"), e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return null;
}
return jaspicState;
}
private CallbackHandler getCallbackHandler() {
CallbackHandler handler = jaspicCallbackHandler;
if (handler == null) {
handler = createCallbackHandler();
}
return handler;
}
private CallbackHandler createCallbackHandler() {
CallbackHandler callbackHandler;
Class<?> clazz = null;
try {
clazz = Class.forName(jaspicCallbackHandlerClass, true, Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException e) {
// Proceed with the retry below
}
try {
if (clazz == null) {
clazz = Class.forName(jaspicCallbackHandlerClass);
}
callbackHandler = (CallbackHandler) clazz.getConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new SecurityException(e);
}
if (callbackHandler instanceof Contained) {
((Contained) callbackHandler).setContainer(getContainer());
}
jaspicCallbackHandler = callbackHandler;
return callbackHandler;
}
// ------------------------------------------------------ Protected Methods
/**
* Provided for subclasses to implement their specific authentication mechanism.
*
* @param request The request that triggered the authentication
* @param response The response associated with the request
*
* @return {@code true} if the user was authenticated, otherwise {@code
* false}, in which case an authentication challenge will have been written to the response
*
* @throws IOException If an I/O problem occurred during the authentication process
*/
protected abstract boolean doAuthenticate(Request request, HttpServletResponse response) throws IOException;
/**
* Does this authenticator require that {@link #authenticate(Request, HttpServletResponse)} is called to continue an
* authentication process that started in a previous request?
*
* @param request The request currently being processed
*
* @return {@code true} if authenticate() must be called, otherwise {@code false}
*/
protected boolean isContinuationRequired(Request request) {
return false;
}
/**
* Associate the specified single sign on identifier with the specified Session.
*
* @param ssoId Single sign on identifier
* @param session Session to be associated
*/
protected void associate(String ssoId, Session session) {
if (sso == null) {
return;
}
sso.associate(ssoId, session);
}
private boolean authenticateJaspic(Request request, Response response, JaspicState state,
boolean requirePrincipal) {
boolean cachedAuth = checkForCachedAuthentication(request, response, false);
Subject client = new Subject();
AuthStatus authStatus;
try {
authStatus = state.serverAuthContext.validateRequest(state.messageInfo, client, null);
} catch (AuthException e) {
log.debug(sm.getString("authenticator.loginFail"), e);
// Need to explicitly set the return code as the ServerAuthContext may not have done.
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return false;
}
request.setRequest((HttpServletRequest) state.messageInfo.getRequestMessage());
response.setResponse((HttpServletResponse) state.messageInfo.getResponseMessage());
if (authStatus == AuthStatus.SUCCESS) {
GenericPrincipal principal = getPrincipal(client);
if (log.isTraceEnabled()) {
log.trace("Authenticated user: " + principal);
}
if (principal == null) {
request.setUserPrincipal(null);
request.setAuthType(null);
if (requirePrincipal) {
return false;
}
} else if (!cachedAuth || !principal.getUserPrincipal().equals(request.getUserPrincipal())) {
// Skip registration if authentication credentials were
// cached and the Principal did not change.
// Check to see if any of the JASPIC properties were set
Boolean register = null;
String authType = "JASPIC";
@SuppressWarnings("rawtypes") // JASPIC API uses raw types
Map map = state.messageInfo.getMap();
String registerValue = (String) map.get("jakarta.servlet.http.registerSession");
if (registerValue != null) {
register = Boolean.valueOf(registerValue);
}
String authTypeValue = (String) map.get("jakarta.servlet.http.authType");
if (authTypeValue != null) {
authType = authTypeValue;
}
/*
* Need to handle three cases. See https://bz.apache.org/bugzilla/show_bug.cgi?id=64713 1.
* registerSession TRUE always use session, always cache 2. registerSession NOT SET config for session,
* config for cache 3. registerSession FALSE config for session, never cache
*/
if (register != null) {
register(request, response, principal, authType, null, null,
alwaysUseSession || register.booleanValue(), register.booleanValue());
} else {
register(request, response, principal, authType, null, null);
}
}
request.setNote(Constants.REQ_JASPIC_SUBJECT_NOTE, client);
return true;
}
return false;
}
private GenericPrincipal getPrincipal(Subject subject) {
if (subject == null) {
return null;
}
Set<GenericPrincipal> principals = subject.getPrivateCredentials(GenericPrincipal.class);
if (principals.isEmpty()) {
return null;
}
return principals.iterator().next();
}
/**
* Check to see if the user has already been authenticated earlier in the processing chain or if there is enough
* information available to authenticate the user without requiring further user interaction.
*
* @param request The current request
* @param response The current response
* @param useSSO Should information available from SSO be used to attempt to authenticate the current user?
*
* @return <code>true</code> if the user was authenticated via the cache, otherwise <code>false</code>
*/
protected boolean checkForCachedAuthentication(Request request, HttpServletResponse response, boolean useSSO) {
// Has the user already been authenticated?
Principal principal = request.getUserPrincipal();
String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
if (principal != null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("authenticator.check.found", principal.getName()));
}
// Associate the session with any existing SSO session. Even if
// useSSO is false, this will ensure coordinated session
// invalidation at log out.
if (ssoId != null) {
associate(ssoId, request.getSessionInternal(true));
}
return true;
}
// Is there an SSO session against which we can try to reauthenticate?
if (useSSO && ssoId != null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("authenticator.check.sso", ssoId));
}
/*
* Try to reauthenticate using data cached by SSO. If this fails, either the original SSO logon was of
* DIGEST or SSL (which we can't reauthenticate ourselves because there is no cached username and password),
* or the realm denied the user's reauthentication for some reason. In either case we have to prompt the
* user for a logon
*/
if (reauthenticateFromSSO(ssoId, request)) {
return true;
}
}
// Has the Connector provided a pre-authenticated Principal that now
// needs to be authorized?
if (request.getCoyoteRequest().getRemoteUserNeedsAuthorization()) {
String username = request.getCoyoteRequest().getRemoteUser().toString();
if (username != null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("authenticator.check.authorize", username));
}
Principal authorized = context.getRealm().authenticate(username);
if (authorized == null) {
// Realm doesn't recognise user. Create a user with no roles
// from the authenticated username
if (log.isDebugEnabled()) {
log.debug(sm.getString("authenticator.check.authorizeFail", username));
}
authorized = new GenericPrincipal(username);
}
String authType = request.getAuthType();
if (authType == null || authType.isEmpty()) {
authType = getAuthMethod();
}
register(request, response, authorized, authType, username, null);
return true;
}
}
return false;
}
/**
* Attempts reauthentication to the <code>Realm</code> using the credentials included in argument
* <code>entry</code>.
*
* @param ssoId identifier of SingleSignOn session with which the caller is associated
* @param request the request that needs to be authenticated
*
* @return <code>true</code> if the reauthentication from SSL occurred
*/
protected boolean reauthenticateFromSSO(String ssoId, Request request) {
if (sso == null || ssoId == null) {
return false;
}
boolean reauthenticated = false;
Container parent = getContainer();
if (parent != null) {
Realm realm = parent.getRealm();
if (realm != null) {
reauthenticated = sso.reauthenticate(ssoId, realm, request);
}
}
if (reauthenticated) {
associate(ssoId, request.getSessionInternal(true));
if (log.isDebugEnabled()) {
log.debug(sm.getString("authenticator.reauthentication", request.getUserPrincipal().getName(),
request.getAuthType()));
}
}
return reauthenticated;
}
/**
* Register an authenticated Principal and authentication type in our request, in the current session (if there is
* one), and with our SingleSignOn valve, if there is one. Set the appropriate cookie to be returned.
*
* @param request The servlet request we are processing
* @param response The servlet response we are generating
* @param principal The authenticated Principal to be registered
* @param authType The authentication type to be registered
* @param username Username used to authenticate (if any)
* @param password Password used to authenticate (if any)
*/
public void register(Request request, HttpServletResponse response, Principal principal, String authType,
String username, String password) {
register(request, response, principal, authType, username, password, alwaysUseSession, cache);
}
/**
* Register an authenticated Principal and authentication type in our request, in the current session (if there is
* one), and with our SingleSignOn valve, if there is one. Set the appropriate cookie to be returned.
*
* @param request The servlet request we are processing
* @param response The servlet response we are generating
* @param principal The authenticated Principal to be registered
* @param authType The authentication type to be registered
* @param username Username used to authenticate (if any)
* @param password Password used to authenticate (if any)
* @param alwaysUseSession Should a session always be used once a user is authenticated?
* @param cache Should we cache authenticated Principals if the request is part of an HTTP session?
*/
protected void register(Request request, HttpServletResponse response, Principal principal, String authType,
String username, String password, boolean alwaysUseSession, boolean cache) {
if (log.isDebugEnabled()) {
String name = (principal == null) ? "none" : principal.getName();
log.debug(sm.getString("authenticator.authentication", name, authType));
}
// Cache the authentication information in our request
request.setAuthType(authType);
request.setUserPrincipal(principal);
if (sendAuthInfoResponseHeaders &&
Boolean.TRUE.equals(request.getAttribute(Globals.REQUEST_FORWARDED_ATTRIBUTE))) {
response.setHeader("remote-user", request.getRemoteUser());
response.setHeader("auth-type", request.getAuthType());
}
Session session = request.getSessionInternal(false);
if (session != null) {
// If the principal is null then this is a logout. No need to change
// the session ID. See BZ 59043.
if (getChangeSessionIdOnAuthentication() && principal != null) {
String newSessionId = changeSessionID(request, session);
// If the current session ID is being tracked, update it.
if (session.getNote(Constants.SESSION_ID_NOTE) != null) {
session.setNote(Constants.SESSION_ID_NOTE, newSessionId);
}
}
} else if (alwaysUseSession) {
session = request.getSessionInternal(true);
}
// Cache the authentication information in our session, if any
if (session != null && cache) {
session.setAuthType(authType);
session.setPrincipal(principal);
}
// Construct a cookie to be returned to the client
if (sso == null) {
return;
}
// Only create a new SSO entry if the SSO did not already set a note
// for an existing entry (as it would do with subsequent requests
// for DIGEST and SSL authenticated contexts)
String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
if (ssoId == null) {
// Construct a cookie to be returned to the client
ssoId = sessionIdGenerator.generateSessionId();
Cookie cookie = new Cookie(sso.getCookieName(), ssoId);
cookie.setMaxAge(-1);
cookie.setPath("/");
// Bugzilla 41217
cookie.setSecure(request.isSecure());
// Bugzilla 34724
String ssoDomain = sso.getCookieDomain();
if (ssoDomain != null) {
cookie.setDomain(ssoDomain);
}
// Configure httpOnly on SSO cookie using same rules as session cookies
if (request.getServletContext().getSessionCookieConfig().isHttpOnly() ||
request.getContext().getUseHttpOnly()) {
cookie.setHttpOnly(true);
}
// Configure Partitioned on SSO cookie using same rules as session cookies
cookie.setAttribute(Constants.COOKIE_PARTITIONED_ATTR,
Boolean.toString(request.getContext().getUsePartitioned()));
response.addCookie(cookie);
// Register this principal with our SSO valve
sso.register(ssoId, principal, authType, username, password);
request.setNote(Constants.REQ_SSOID_NOTE, ssoId);
} else {
if (principal == null) {
// Registering a programmatic logout
sso.deregister(ssoId);
request.removeNote(Constants.REQ_SSOID_NOTE);
return;
} else {
// Update the SSO session with the latest authentication data
sso.update(ssoId, principal, authType, username, password);
}
}
// Fix for Bug 10040
// Always associate a session with a new SSO registration.
// SSO entries are only removed from the SSO registry map when
// associated sessions are destroyed; if a new SSO entry is created
// above for this request and the user never revisits the context, the
// SSO entry will never be cleared if we don't associate the session
if (session == null) {
session = request.getSessionInternal(true);
}
sso.associate(ssoId, session);
}
protected String changeSessionID(Request request, Session session) {
String oldId = null;
if (log.isDebugEnabled()) {
oldId = session.getId();
}
String newId = request.changeSessionId();
if (log.isDebugEnabled()) {
log.debug(sm.getString("authenticator.changeSessionId", oldId, newId));
}
return newId;
}
@Override
public void login(String username, String password, Request request) throws ServletException {
Principal principal = doLogin(request, username, password);
register(request, request.getResponse(), principal, getAuthMethod(), username, password);
}
/**
* Return the authentication method, which is vendor-specific and not defined by HttpServletRequest.
*
* @return the authentication method, which is vendor-specific and not defined by HttpServletRequest.
*/
protected abstract String getAuthMethod();
/**
* Process the login request.
*
* @param request Associated request
* @param username The user
* @param password The password
*
* @return The authenticated Principal
*
* @throws ServletException No principal was authenticated with the specified credentials
*/
protected Principal doLogin(Request request, String username, String password) throws ServletException {
Principal p = context.getRealm().authenticate(username, password);
if (p == null) {
throw new ServletException(sm.getString("authenticator.loginFail"));
}
return p;
}
@Override
public void logout(Request request) {
AuthConfigProvider provider = getJaspicProvider();
if (provider != null) {
MessageInfo messageInfo = new MessageInfoImpl(request, request.getResponse(), true);
Subject client = (Subject) request.getNote(Constants.REQ_JASPIC_SUBJECT_NOTE);
if (client != null) {
ServerAuthContext serverAuthContext;
try {
ServerAuthConfig serverAuthConfig =
provider.getServerAuthConfig("HttpServlet", jaspicAppContextID, getCallbackHandler());
String authContextID = serverAuthConfig.getAuthContextID(messageInfo);
serverAuthContext = serverAuthConfig.getAuthContext(authContextID, null, null);
serverAuthContext.cleanSubject(messageInfo, client);
} catch (AuthException e) {
log.debug(sm.getString("authenticator.jaspicCleanSubjectFail"), e);
}
}
}
Principal p = request.getPrincipal();
if (p instanceof TomcatPrincipal) {
try {
((TomcatPrincipal) p).logout();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.debug(sm.getString("authenticator.tomcatPrincipalLogoutFail"), t);
}
}
register(request, request.getResponse(), null, null, null, null);
}
@Override
protected void startInternal() throws LifecycleException {
ServletContext servletContext = context.getServletContext();
jaspicAppContextID = servletContext.getVirtualServerName() + " " + servletContext.getContextPath();
// Look up the SingleSignOn implementation in our request processing
// path, if there is one
Container parent = context.getParent();
while ((sso == null) && (parent != null)) {
Valve[] valves = parent.getPipeline().getValves();
for (Valve valve : valves) {
if (valve instanceof SingleSignOn) {
sso = (SingleSignOn) valve;
break;
}
}
if (sso == null) {
parent = parent.getParent();
}
}
if (log.isDebugEnabled()) {
if (sso != null) {
log.debug(sm.getString("authenticator.sso", sso));
} else {
log.trace("No SingleSignOn Valve is present");
}
}
sessionIdGenerator = new StandardSessionIdGenerator();
sessionIdGenerator.setSecureRandomAlgorithm(getSecureRandomAlgorithm());
sessionIdGenerator.setSecureRandomClass(getSecureRandomClass());
sessionIdGenerator.setSecureRandomProvider(getSecureRandomProvider());
super.startInternal();
}
@Override
protected void stopInternal() throws LifecycleException {
super.stopInternal();
sso = null;
}
/**
* Can the authenticator perform preemptive authentication for the given request?
*
* @param request The request to check for credentials
*
* @return {@code true} if preemptive authentication is possible, otherwise {@code false}
*/
protected boolean isPreemptiveAuthPossible(Request request) {
return false;
}
private AuthConfigProvider getJaspicProvider() {
Optional<AuthConfigProvider> provider = jaspicProvider;
if (provider == null) {
provider = findJaspicProvider();
}
return provider.orElse(null);
}
private Optional<AuthConfigProvider> findJaspicProvider() {
AuthConfigFactory factory = AuthConfigFactory.getFactory();
Optional<AuthConfigProvider> provider;
if (factory == null) {
provider = Optional.empty();
} else {
provider = Optional.ofNullable(factory.getConfigProvider("HttpServlet", jaspicAppContextID, this));
}
jaspicProvider = provider;
return provider;
}
@Override
public void notify(String layer, String appContext) {
findJaspicProvider();
}
private static class JaspicState {
public MessageInfo messageInfo = null;
public ServerAuthContext serverAuthContext = null;
}
protected enum AllowCorsPreflight {
NEVER,
FILTER,
ALWAYS
}
}
|