1 23 package com.sun.web.security; 24 25 import com.sun.enterprise.ComponentInvocation; 26 import java.net.MalformedURLException ; 27 import java.net.URL ; 28 import java.security.Principal ; 29 import java.security.cert.X509Certificate ; 30 import java.util.ArrayList ; 31 import java.util.HashMap ; 32 import java.util.Map ; 33 import java.util.Iterator ; 34 import java.util.logging.Level ; 35 import java.util.logging.Logger ; 36 import java.util.Set ; 37 import javax.security.auth.Subject ; 38 import javax.servlet.ServletConfig ; 39 40 41 import com.sun.logging.LogDomains; 42 import java.io.IOException ; 43 import com.sun.enterprise.deployment.Application; 44 import com.sun.enterprise.deployment.RunAsIdentityDescriptor; 45 import com.sun.enterprise.deployment.WebBundleDescriptor; 46 import com.sun.enterprise.deployment.WebComponentDescriptor; 47 import com.sun.enterprise.deployment.interfaces.SecurityRoleMapper; 48 import com.sun.enterprise.deployment.web.LoginConfiguration; 49 50 import com.sun.enterprise.deployment.runtime.web.SunWebApp; 51 import com.sun.enterprise.security.SecurityContext; 52 import com.sun.enterprise.security.auth.LoginContextDriver; 53 import com.sun.enterprise.security.auth.realm.certificate.CertificateRealm; 54 import com.sun.enterprise.security.jauth.AuthConfig; 55 import com.sun.enterprise.security.jauth.ServerAuthContext; 56 import com.sun.enterprise.security.jauth.AuthParam; 57 import com.sun.enterprise.security.jauth.HttpServletAuthParam; 58 import com.sun.enterprise.security.jauth.PendingException; 59 import com.sun.enterprise.security.jauth.FailureException; 60 import com.sun.enterprise.security.jauth.AuthException; 61 import com.sun.enterprise.webservice.WSSCallbackHandler; 62 import com.sun.enterprise.webservice.monitoring.WebServiceEngineImpl; 63 import com.sun.enterprise.webservice.monitoring.AuthenticationListener; 64 import javax.servlet.http.HttpServlet ; 65 import javax.servlet.http.HttpServletRequest ; 66 import javax.servlet.http.HttpServletResponse ; 67 import org.apache.catalina.Authenticator; 68 import org.apache.catalina.Container; 69 import org.apache.catalina.Context; 70 import org.apache.catalina.HttpRequest; 71 import org.apache.catalina.HttpResponse; 72 import org.apache.catalina.LifecycleException; 73 import org.apache.catalina.Realm; 74 import org.apache.catalina.authenticator.AuthenticatorBase; 75 import org.apache.catalina.deploy.LoginConfig; 76 import org.apache.catalina.deploy.SecurityConstraint; 77 import org.apache.catalina.realm.Constants; 78 import org.apache.catalina.realm.RealmBase; 79 import org.apache.catalina.util.StringManager; 80 import sun.security.x509.X500Name; 81 82 import com.sun.enterprise.Switch; 83 import com.sun.enterprise.admin.monitor.callflow.Agent; 84 import com.sun.enterprise.admin.monitor.callflow.RequestInfo; 85 import com.sun.enterprise.admin.monitor.callflow.ContainerTypeOrApplicationType; 86 87 95 96 public class RealmAdapter extends RealmBase { 97 private static final String UNCONSTRAINED = "unconstrained"; 98 99 static Logger _logger=LogDomains.getLogger(LogDomains.WEB_LOGGER); 100 101 public static final String SECURITY_CONTEXT = "SecurityContext"; 102 103 public static final String BASIC = "BASIC"; 104 public static final String FORM = "FORM"; 105 private static int MAX_COUNT = 5; 106 private static int SLEEP_TIME = 5000; 108 private static final String SYSTEM_HTTPSERVLET_SECURITY_PROVIDER = 111 "system_httpservlet_security_provider"; 112 113 private SecurityRoleMapper mapper = null; 115 private WebBundleDescriptor webDesc = null; 116 117 private HashMap runAsPrincipals = null; 119 121 private String _realmName = null; 123 126 protected static final String name = "J2EE-RI-RealmAdapter"; 127 130 private String CONTEXT_ID = null; 131 134 protected static StringManager sm = 135 StringManager.getManager(Constants.Package); 136 137 protected static StringManager smRA = 138 StringManager.getManager("com.sun.web.security"); 139 140 143 protected volatile WebSecurityManager webSecurityManager = null; 144 145 148 protected WebSecurityManagerFactory webSecurityManagerFactory = 149 WebSecurityManagerFactory.getInstance(); 150 protected boolean isCurrentURIincluded = false; 151 152 private ArrayList roles = null; 153 154 157 private boolean contextEvaluated = false; 158 private String loginPage = null; 159 private String errorPage = null; 160 161 private static SecurityConstraint[] emptyConstraints = 162 new SecurityConstraint[] {}; 163 164 169 private static String defaultSystemProviderID = 170 getDefaultSystemProviderID(); 171 172 private String appID; 173 private boolean isSystemApp; 174 private String securityProviderID; 175 private ServerAuthContext sAC; 176 177 public RealmAdapter() {} 178 179 183 public RealmAdapter(String realmName) { 184 _realmName = realmName; 185 } 186 187 193 public RealmAdapter(WebBundleDescriptor descriptor, boolean isSystemApp) { 194 this.isSystemApp = isSystemApp; 195 webDesc = descriptor; 196 Application app = descriptor.getApplication(); 197 mapper = app.getRoleMapper(); 198 LoginConfiguration loginConfig = descriptor.getLoginConfiguration(); 199 _realmName = app.getRealm(); 200 if (_realmName == null && loginConfig != null) { 201 _realmName = loginConfig.getRealmName(); 202 } 203 CONTEXT_ID = WebSecurityManager.getContextID(descriptor); 205 runAsPrincipals = new HashMap (); 206 Iterator bundle = webDesc.getWebComponentDescriptorsSet().iterator(); 207 208 while(bundle.hasNext()) { 209 210 WebComponentDescriptor wcd = (WebComponentDescriptor)bundle.next(); 211 RunAsIdentityDescriptor runAsDescriptor = wcd.getRunAsIdentity(); 212 213 if (runAsDescriptor != null) { 214 String principal = runAsDescriptor.getPrincipal(); 215 String servlet = wcd.getCanonicalName(); 216 217 if (principal == null || servlet == null) { 218 _logger.warning("web.realmadapter.norunas"); 219 } else { 220 runAsPrincipals.put(servlet, principal); 221 _logger.fine("Servlet "+servlet+ 222 " will run-as: "+principal); 223 } 224 } 225 } 226 228 this.appID = app.getRegistrationName(); 229 this.securityProviderID = getSecurityProviderID(); 230 this.sAC = getServerAuthContext(); 231 } 232 233 public WebBundleDescriptor getWebDescriptor() { 234 return webDesc; 235 } 236 237 WebSecurityManager getWebSecurityManager(boolean logNull) { 241 if (webSecurityManager == null) { 242 synchronized(this) { 243 webSecurityManager = webSecurityManagerFactory. 244 getWebSecurityManager(CONTEXT_ID); 245 } 246 if (webSecurityManager == null && logNull) { 247 String msg = smRA.getString("realmAdapter.noWebSecMgr", CONTEXT_ID); 248 _logger.warning(msg); 249 } 250 } 251 252 return webSecurityManager; 253 } 254 255 264 public boolean hasRole(HttpRequest request, 267 HttpResponse response, 268 Principal principal, 269 String role) { 270 WebSecurityManager secMgr = getWebSecurityManager(true); 271 if (secMgr == null) { 272 return false; 273 } 274 275 HttpServletRequest hrequest = (HttpServletRequest ) request; 281 String servletName = getResourceName( hrequest.getRequestURI(), 282 hrequest.getContextPath()); 283 285 boolean isGranted = 287 secMgr.hasRoleRefPermission(servletName, role, principal); 288 289 if (!isGranted){ 290 servletName = getCanonicalName(hrequest); 294 295 if (servletName.equalsIgnoreCase(UNCONSTRAINED)){ 298 if(_logger.isLoggable(Level.INFO)){ 299 _logger.log(Level.INFO, 300 "Unable to find a <servlet-name> element which map: " 301 + hrequest.getRequestURI()); 302 } 303 304 313 isGranted = secMgr.hasRoleRefPermission("", role, principal); 314 315 } else { 317 isGranted = secMgr.hasRoleRefPermission(servletName, 318 role, 319 principal); 320 } 321 } 322 323 if(_logger.isLoggable(Level.FINE)) { 324 _logger.fine( "Checking if servlet " + servletName 325 + " with principal " + principal 326 + " has role " + role 327 + " isGranted: " + isGranted); 328 } 329 330 return isGranted; 331 332 } 333 334 public void logout() { 335 setSecurityContext(null); 336 } 337 338 344 public Principal authenticate(String username, byte[] authData) { 345 return authenticate(username, new String (authData)); 346 } 347 348 354 public Principal authenticate(String username, String password) { 355 if (_logger.isLoggable(Level.FINE)){ 356 _logger.fine( "Tomcat callback for authenticate user/password"); 357 _logger.fine( "usename = " + username); 358 } 359 if(authenticate(username, password, null)) { 360 SecurityContext secCtx = SecurityContext.getCurrent(); 361 assert (secCtx != null); return new WebPrincipal(username, password, secCtx); 363 } else { 364 return null; 365 } 366 } 367 368 public Principal authenticate(X509Certificate certs[]) { 369 if(authenticate(null, null, certs)) { 370 SecurityContext secCtx = SecurityContext.getCurrent(); 371 assert (secCtx != null); return new WebPrincipal(certs, secCtx); 373 } else { 374 return null; 375 } 376 } 377 378 383 public boolean authenticate(WebPrincipal prin) { 384 if (prin.isUsingCertificate()) { 385 return authenticate(null, null, prin.getCertificates()); 386 } else { 387 return authenticate(prin.getName(), prin.getPassword(), null); 388 } 389 } 390 391 392 399 protected boolean authenticate(String username, String password, 400 X509Certificate [] certs) { 401 402 SecurityContext.setCurrent(null); 403 String realm_name = null; 404 boolean success = false; 405 try { 406 if (certs != null) { 407 Subject subject = new Subject (); 408 X509Certificate certificate = certs[0]; 409 X500Name x500Name = (X500Name) certificate.getSubjectDN(); 410 Switch.getSwitch().getCallFlowAgent().addRequestInfo( 411 RequestInfo.REMOTE_USER, x500Name.getName()); 412 subject.getPublicCredentials().add(x500Name); 413 LoginContextDriver.login(subject, X500Name.class); 414 realm_name = CertificateRealm.AUTH_TYPE; 415 } else { 416 Switch.getSwitch().getCallFlowAgent().addRequestInfo( 417 RequestInfo.REMOTE_USER, username); 418 realm_name = _realmName; 419 LoginContextDriver.login(username, password, realm_name); 420 } 421 success = true; 422 } catch (Exception le) { 423 success = false; 424 if (_logger.isLoggable(Level.WARNING)) { 425 _logger.warning("Web login failed: " + le.getMessage()); 426 } 427 } 428 if(success){ 429 if (_logger.isLoggable(Level.FINE)) { 430 _logger.log(Level.FINE,"Web login succeeded for: " + username); 431 } 432 } 433 if (webDesc!=null && webDesc.hasWebServices()) { 434 WebPrincipal principal = new WebPrincipal(username, password, null); 435 for (AuthenticationListener listener : WebServiceEngineImpl.getInstance().getAuthListeners()) { 436 if (success) { 437 listener.authSucess(webDesc, null, principal); 438 } else { 439 listener.authFailure(webDesc, null, principal); 440 } 441 } 442 } 443 return success; 444 } 445 463 public void preSetRunAsIdentity (ComponentInvocation inv) { 464 465 String name=this.getServletName(inv); 466 if (name == null) { 467 return; 468 } 469 470 String runAs = (String )runAsPrincipals.get(name); 471 472 if (runAs != null) { 473 SecurityContext old = getSecurityContext(); 477 inv.setOldSecurityContext(old); 478 479 loginForRunAs(runAs); 481 482 if (_logger.isLoggable(Level.FINE)) { 483 _logger.fine("run-as principal for " + name + 484 " set to: "+ runAs); 485 } 486 } 487 } 488 489 490 503 private String getServletName(ComponentInvocation inv) 504 { 505 Object invInstance = inv.getInstance(); 506 507 if (invInstance instanceof HttpServlet ) { 508 509 HttpServlet thisServlet = (HttpServlet )invInstance; 510 ServletConfig svc = thisServlet.getServletConfig(); 511 512 if (svc != null) { 513 return thisServlet.getServletName(); 514 } 515 } 516 return null; 517 } 518 519 520 543 public void postSetRunAsIdentity (ComponentInvocation inv){ 544 545 String name=this.getServletName(inv); 546 if (name == null) { 547 return; 548 } 549 550 String runAs = (String )runAsPrincipals.get(name); 551 if (runAs != null) { 552 setSecurityContext (inv.getOldSecurityContext ()); 554 } 555 } 556 558 private void loginForRunAs (String principal) { 559 LoginContextDriver.loginPrincipal (principal, _realmName); 560 } 561 private SecurityContext getSecurityContext (){ 562 return SecurityContext.getCurrent (); 563 } 564 private void setSecurityContext (SecurityContext sc){ 565 SecurityContext.setCurrent (sc); 566 } 567 568 protected String getPassword(String username) { 569 throw new IllegalStateException ("Should not reach here"); 570 } 571 572 protected Principal getPrincipal(String username) { 573 throw new IllegalStateException ("Should not reach here"); 574 } 575 576 585 public Principal createFailOveredPrincipal(String username){ 586 _logger.log(Level.FINEST,"IN createFailOveredPrincipal ("+username+")"); 587 loginForRunAs(username); 589 SecurityContext secCtx = SecurityContext.getCurrent(); 590 _logger.log(Level.FINE,"Security context is "+secCtx); 591 assert (secCtx != null); 592 Principal principal = new WebPrincipal(username, null, secCtx); 593 _logger.log(Level.INFO,"Principal created for FailOvered user "+principal); 594 return principal; 595 } 596 598 610 public boolean hasResourcePermission(HttpRequest request, 611 HttpResponse response, 612 SecurityConstraint[] constraints, 613 Context context) 614 throws IOException { 615 boolean isGranted = false; 616 try { 617 isGranted = invokeWebSecurityManager( 618 request, response, constraints); 619 } catch(IOException iex) { 620 throw iex; 621 } catch(Throwable ex) { 622 ((HttpServletResponse ) response.getResponse()).sendError 623 (HttpServletResponse.SC_SERVICE_UNAVAILABLE); 624 response.setDetailMessage(sm.getString("realmBase.forbidden")); 625 return isGranted; 626 } 627 628 if ( isGranted ){ 629 return isGranted; 630 } else { 631 ((HttpServletResponse ) response.getResponse()).sendError 632 (HttpServletResponse.SC_FORBIDDEN); 633 response.setDetailMessage(sm.getString("realmBase.forbidden")); 634 return isGranted; 635 } 636 } 637 638 649 private boolean invokeWebSecurityManager(HttpRequest request, 650 HttpResponse response, 651 SecurityConstraint[] constraints) 652 throws IOException { 653 HttpServletRequest hrequest = (HttpServletRequest )request; 654 655 if ( hrequest.getServletPath() == null){ 656 request.setServletPath( getResourceName( hrequest.getRequestURI(), 657 hrequest.getContextPath())); 658 } 659 660 if(_logger.isLoggable(Level.FINE)) 661 _logger.fine("[Web-Security] [ hasResourcePermission ] Principal: " 662 + hrequest.getUserPrincipal() + " ContextPath: " + hrequest.getContextPath()); 663 664 WebSecurityManager secMgr = getWebSecurityManager(true); 665 if (secMgr == null) { 666 return false; 667 } 668 return secMgr.hasResourcePermission(hrequest); 669 } 670 671 683 public boolean hasUserDataPermission(HttpRequest request, 684 HttpResponse response, 685 SecurityConstraint[] constraints) throws IOException { 686 HttpServletRequest hrequest = (HttpServletRequest )request; 687 if ( hrequest.getServletPath() == null){ 688 request.setServletPath( 689 getResourceName( hrequest.getRequestURI(), 690 hrequest.getContextPath())); 691 } 692 693 if(_logger.isLoggable(Level.FINE)){ 694 _logger.fine("[Web-Security][ hasUserDataPermission ] Principal: " 695 + hrequest.getUserPrincipal() 696 + " ContextPath: " 697 + hrequest.getContextPath()); 698 } 699 700 if (request.getRequest().isSecure()) { 701 if(_logger.isLoggable(Level.FINE)) 702 _logger.fine("[Web-Security] request.getRequest().isSecure(): " + request.getRequest().isSecure()); 703 return true; 704 } 705 706 WebSecurityManager secMgr = getWebSecurityManager(true); 707 if (secMgr == null) { 708 return false; 709 } 710 711 int isGranted = 0; 712 try { 713 isGranted = secMgr.hasUserDataPermission(hrequest); 714 } catch (IllegalArgumentException e) { 715 String msg = sm.getString("realmBase.badRequest", e.getMessage()); 718 _logger.warning(msg); 719 if(_logger.isLoggable(Level.FINE)) { 720 _logger.log(Level.FINE, msg, e); 721 } 722 ((HttpServletResponse ) response.getResponse()).sendError 723 (HttpServletResponse.SC_BAD_REQUEST, msg); 724 return false; 725 } 726 727 730 if ( isGranted == -1 ){ 736 if(_logger.isLoggable(Level.FINE)) 737 _logger.fine( "[Web-Security] redirecting using SSL"); 738 return redirect(request, response); 739 } 740 741 if (isGranted == 0){ 742 ((HttpServletResponse ) response.getResponse()).sendError 743 (HttpServletResponse.SC_FORBIDDEN, 744 sm.getString("realmBase.forbidden")); 745 return false; 746 } 747 748 return true; 749 } 750 751 private boolean redirect(HttpRequest request, HttpResponse response) throws IOException { 752 HttpServletRequest hrequest = 754 (HttpServletRequest ) request.getRequest(); 755 HttpServletResponse hresponse = 756 (HttpServletResponse ) response.getResponse(); 757 int redirectPort = request.getConnector().getRedirectPort(); 758 759 if (redirectPort <= 0) { 761 if(_logger.isLoggable(Level.INFO)) 762 _logger.fine("[Web-Security] SSL redirect is disabled"); 763 764 hresponse.sendError 765 (HttpServletResponse.SC_FORBIDDEN, hrequest.getRequestURI()); 766 return (false); 767 } 768 769 String protocol = "https"; 770 String host = hrequest.getServerName(); 771 StringBuffer file = new StringBuffer (hrequest.getRequestURI()); 772 String requestedSessionId = hrequest.getRequestedSessionId(); 773 if ((requestedSessionId != null) && 774 hrequest.isRequestedSessionIdFromURL()) { 775 file.append(";jsessionid="); 776 file.append(requestedSessionId); 777 } 778 String queryString = hrequest.getQueryString(); 779 if (queryString != null) { 780 file.append('?'); 781 file.append(queryString); 782 } 783 URL url = null; 784 try { 785 url = new URL (protocol, host, redirectPort, file.toString()); 786 hresponse.sendRedirect(url.toString()); 787 return (false); 788 } catch (MalformedURLException e) { 789 hresponse.sendError 790 (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 791 hrequest.getRequestURI()); 792 return (false); 793 } 794 } 795 796 private String getCanonicalName(HttpServletRequest currentRequest){ 800 String servletUri = ""; 802 String currentUri = ""; 803 String aliasUri = ""; 804 String currentUriExtension = ""; 805 String aliasUriExtension = ""; 806 boolean isAliasExists = false; 807 for (Iterator itr = webDesc.getWebComponentDescriptorsSet().iterator(); itr.hasNext();) { 808 WebComponentDescriptor webComponentDescriptor = (WebComponentDescriptor)itr.next(); 809 servletUri = webComponentDescriptor.getWebComponentImplementation(); 810 811 currentUri = getResourceName( currentRequest.getRequestURI(), currentRequest.getContextPath()); 812 currentUriExtension = getExtension(currentUri); 813 814 for (Iterator i = webComponentDescriptor.getUrlPatternsSet().iterator(); i.hasNext();) { 816 aliasUri = i.next().toString(); 817 aliasUriExtension = getExtension(aliasUri); 818 819 if (aliasUri.equalsIgnoreCase(currentUri)){ 820 isAliasExists = true; 821 break; 822 } 823 824 if (aliasUriExtension.equalsIgnoreCase(currentUriExtension) 825 && aliasUri.equalsIgnoreCase("*" + aliasUriExtension)){ 826 isAliasExists = true; 827 break; 828 } 829 } 830 831 if (currentUri.equalsIgnoreCase(servletUri) 832 || isAliasExists){ 833 return webComponentDescriptor.getCanonicalName(); 834 } 835 } 836 return UNCONSTRAINED; 837 } 838 839 private String getResourceName(String uri, String contextPath){ 840 try{ 841 return uri.substring(contextPath.length()); 842 } catch (java.lang.Exception ex){ 843 return ""; 844 } 845 } 846 847 private String getExtension(String uri){ 848 try{ 849 return uri.substring(uri.lastIndexOf(".")); 850 } catch (java.lang.Exception ex){ 851 return ""; 853 } 854 } 855 856 857 860 protected String getName() { 861 return (this.name); 862 } 863 864 870 public String getRealmName() { 871 return _realmName; 872 } 873 874 public void setRealmName(String realmName){ 875 } 877 878 887 public SecurityConstraint[] findSecurityConstraints(HttpRequest request, 888 Context context) { 889 WebSecurityManager secMgr = getWebSecurityManager(false); 890 891 if (secMgr != null && secMgr.hasNoConstrainedResources()) { 892 return null; 893 } 894 895 SecurityConstraint[] constraints = RealmAdapter.emptyConstraints; 896 synchronized (this) { 897 if (!contextEvaluated) { 898 LoginConfig config = context.getLoginConfig(); 899 if ((config != null) && 900 (Constants.FORM_METHOD.equals(config.getAuthMethod()))) { 901 loginPage = config.getLoginPage(); 902 errorPage = config.getErrorPage(); 903 contextEvaluated = true; 904 } 905 } 906 } 907 908 if (loginPage != null || errorPage != null) { 911 String requestURI = request.getRequestPathMB().toString(); 912 if(_logger.isLoggable(Level.FINE)) 913 _logger.fine("[Web-Security] requestURI: " + requestURI + 914 " loginPage: " + loginPage); 915 if (loginPage != null && loginPage.equals(requestURI)) { 916 if(_logger.isLoggable(Level.FINE)) 917 _logger.fine(" Allow access to login page " + loginPage); 918 constraints = null; 919 } 920 else if (errorPage != null && errorPage.equals(requestURI)) { 921 if(_logger.isLoggable(Level.FINE)) 922 _logger.fine(" Allow access to error page " + errorPage); 923 constraints = null; 924 } 925 926 else if (requestURI.endsWith(Constants.FORM_ACTION)) { 927 _logger.fine(" Allow access to username/password submission"); 928 constraints = null; 929 } 930 } 931 return constraints; 932 } 933 935 952 public int preAuthenticateCheck(HttpRequest request, 953 HttpResponse response, 954 SecurityConstraint[] constraints, 955 boolean disableProxyCaching, 956 boolean securePagesWithPragma) 957 throws IOException { 958 boolean isGranted = false; 959 try { 960 isGranted = invokeWebSecurityManager( 961 request, response, constraints); 962 } catch(IOException iex) { 963 throw iex; 964 } catch(Throwable ex) { 965 ((HttpServletResponse ) response.getResponse()).sendError 966 (HttpServletResponse.SC_SERVICE_UNAVAILABLE); 967 response.setDetailMessage(sm.getString("realmBase.forbidden")); 968 return Realm.AUTHENTICATED_NOT_AUTHORIZED; 969 } 970 971 if(isGranted) { 972 HashMap sharedState = null; 973 boolean delegateSessionMgmt = false; 974 if (this.sAC != null) { 975 sharedState = new HashMap (); 976 try { 977 delegateSessionMgmt = this.sAC.managesSessions(sharedState); 978 } catch (AuthException ae) { 979 delegateSessionMgmt = false; 980 } 981 } 982 if (delegateSessionMgmt) { 983 if (validate(request,response,null,null,sharedState)){ 984 disableProxyCaching(request, response, disableProxyCaching, 985 securePagesWithPragma); 986 } 987 } else if( ((HttpServletRequest ) request).getUserPrincipal() != null) { 988 disableProxyCaching(request, response, disableProxyCaching, 989 securePagesWithPragma); 990 } 991 return Realm.AUTHENTICATE_NOT_NEEDED; 992 } else if(((HttpServletRequest ) request).getUserPrincipal() != null){ 993 ((HttpServletResponse ) response.getResponse()).sendError 994 (HttpServletResponse.SC_FORBIDDEN); 995 response.setDetailMessage(sm.getString("realmBase.forbidden")); 996 return Realm.AUTHENTICATED_NOT_AUTHORIZED; 997 } else { 998 disableProxyCaching(request, response, disableProxyCaching,securePagesWithPragma); 999 return Realm.AUTHENTICATE_NEEDED; 1000 } 1001 } 1002 1003 1004 1016 public boolean invokeAuthenticateDelegate(HttpRequest request, 1017 HttpResponse response, 1018 Context context, 1019 Authenticator authenticator) 1020 throws IOException { 1021 1022 boolean result = false; 1023 LoginConfig config = context.getLoginConfig(); 1024 if (this.sAC != null) { 1025 HashMap sharedState = new HashMap (); 1027 result = validate(request,response,config,authenticator,sharedState); 1028 } else { 1029 result = ((AuthenticatorBase) authenticator).authenticate( 1031 request, response, config); 1032 } 1033 return result; 1034 } 1035 1036 private ServerAuthContext getServerAuthContext() { 1037 ServerAuthContext rvalue = null; 1038 String providerID = this.securityProviderID; 1039 if (this.isSystemApp && providerID == null) { 1042 providerID = defaultSystemProviderID; 1043 if (providerID == null) { 1044 return null; 1045 } 1046 } 1047 1048 AuthConfig authConfig = AuthConfig.getAuthConfig(); 1049 try { 1050 rvalue = authConfig.getServerAuthContext 1051 ("HttpServlet", 1052 providerID,null,null,WSSCallbackHandler.getInstance()); 1053 } catch (AuthException ae) { 1054 _logger.log(Level.SEVERE, 1055 "Container-auth: fail to get ServerAuthContext for app " + 1056 appID + ", with security provider id " + providerID, ae); 1057 } 1058 return rvalue; 1059 } 1060 1061 private boolean validate(HttpRequest request, 1062 HttpResponse response, 1063 LoginConfig config, 1064 Authenticator authenticator, 1065 Map sharedState) throws IOException { 1066 1067 HttpServletRequest req = (HttpServletRequest )request; 1068 HttpServletResponse res = (HttpServletResponse )response; 1069 1070 Subject subject = new Subject (); 1071 1072 HttpServletAuthParam param = new HttpServletAuthParam(req,res); 1073 1074 boolean rvalue = false; 1075 try{ 1076 this.sAC.validateRequest((AuthParam)param, subject, sharedState); 1077 rvalue = true; 1078 } catch(PendingException pe){ 1079 _logger.log(Level.FINE,"Container-auth: validation incomplete",pe); 1080 } catch(FailureException fe){ 1081 _logger.log(Level.FINE,"Container-auth: Error validating request ",fe); 1082 } catch (AuthException ae) { 1083 _logger.log(Level.FINE,"Container-auth: http msg authentication fail",ae); 1084 } 1085 1086 if (rvalue) { 1087 Set principalSet = subject.getPrincipals(); 1088 if (principalSet != null && !principalSet.isEmpty()) { 1091 Principal p = (Principal )principalSet.iterator().next(); 1092 SecurityContext ctx = new SecurityContext(p.getName(),subject); 1093 WebPrincipal wp = new WebPrincipal(p,ctx); 1094 try { 1095 if (this.sAC.managesSessions(sharedState)) { 1096 request.setAuthType(PROXY_AUTH_TYPE); 1100 request.setUserPrincipal(wp); 1101 } else { 1102 AuthenticatorProxy proxy = 1103 new AuthenticatorProxy(authenticator,wp); 1104 proxy.authenticate(request,response,config); 1105 } 1106 } catch (LifecycleException le) { 1107 _logger.log(Level.SEVERE,"[Web-Security] unable to register session",le); 1108 } catch (AuthException ae) { 1109 _logger.log(Level.SEVERE,"[Web-Security] unable to register session",ae); 1110 } 1111 } else { 1112 rvalue = false; 1113 } 1114 } 1115 return rvalue; 1116 } 1117 1118 1123 private String getSecurityProviderID() { 1124 SunWebApp sunWebApp = webDesc.getSunDescriptor(); 1125 String rvalue = (sunWebApp != null ? sunWebApp.getAttributeValue 1126 (sunWebApp.HTTPSERVLET_SECURITY_PROVIDER) : null); 1127 return rvalue; 1128 } 1129 1130 1136 private static String getDefaultSystemProviderID() { 1137 String p = System.getProperty(SYSTEM_HTTPSERVLET_SECURITY_PROVIDER); 1138 if (p != null) { 1139 p = p.trim(); 1140 if (p.length() == 0) { 1141 p = null; 1142 } 1143 } 1144 return p; 1145 } 1146 1147 private static String PROXY_AUTH_TYPE = "PLUGGABLE_PROVIDER"; 1148 1149 1153 class AuthenticatorProxy extends AuthenticatorBase { 1154 1155 AuthenticatorBase authBase; 1156 Principal principal; 1157 1158 public boolean getCache() { 1159 return authBase.getCache(); 1160 } 1161 1162 public Container getContainer() { 1163 return authBase.getContainer(); 1164 } 1165 1166 AuthenticatorProxy(Authenticator authenticator, Principal p) 1167 throws LifecycleException 1168 { 1169 1170 this.authBase = (AuthenticatorBase) authenticator; 1171 this.principal = p; 1172 1173 setCache(authBase.getCache()); 1174 setContainer(authBase.getContainer()); 1175 start(); } 1177 1178 public boolean 1179 authenticate(HttpRequest request, 1180 HttpResponse response, 1181 LoginConfig config) throws IOException 1182 1183 { 1184 register(request,response,this.principal, 1185 RealmAdapter.PROXY_AUTH_TYPE, 1186 this.principal.getName(),null); 1187 return true; 1188 } 1189 } 1190} 1191 | Popular Tags |