Search in sources :

Example 1 with RealmInitializer

use of com.sun.enterprise.security.integration.RealmInitializer in project Payara by payara.

the class DynamicWebServletRegistrationImpl method setSecurityConfig.

public void setSecurityConfig(SecurityConfig config) {
    if (config == null) {
        return;
    }
    this.config = config;
    LoginConfig lc = config.getLoginConfig();
    if (lc != null) {
        LoginConfiguration loginConf = new LoginConfigurationImpl();
        loginConf.setAuthenticationMethod(lc.getAuthMethod().name());
        loginConf.setRealmName(lc.getRealmName());
        FormLoginConfig form = lc.getFormLoginConfig();
        if (form != null) {
            loginConf.setFormErrorPage(form.getFormErrorPage());
            loginConf.setFormLoginPage(form.getFormLoginPage());
        }
        LoginConfigDecorator decorator = new LoginConfigDecorator(loginConf);
        setLoginConfig(decorator);
        getWebBundleDescriptor().setLoginConfiguration(loginConf);
    }
    Set<org.glassfish.embeddable.web.config.SecurityConstraint> securityConstraints = config.getSecurityConstraints();
    for (org.glassfish.embeddable.web.config.SecurityConstraint sc : securityConstraints) {
        com.sun.enterprise.deployment.web.SecurityConstraint securityConstraint = new SecurityConstraintImpl();
        Set<org.glassfish.embeddable.web.config.WebResourceCollection> wrcs = sc.getWebResourceCollection();
        for (org.glassfish.embeddable.web.config.WebResourceCollection wrc : wrcs) {
            WebResourceCollectionImpl webResourceColl = new WebResourceCollectionImpl();
            webResourceColl.setDisplayName(wrc.getName());
            for (String urlPattern : wrc.getUrlPatterns()) {
                webResourceColl.addUrlPattern(urlPattern);
            }
            securityConstraint.addWebResourceCollection(webResourceColl);
            AuthorizationConstraintImpl ac = null;
            if (sc.getAuthConstraint() != null && sc.getAuthConstraint().length > 0) {
                ac = new AuthorizationConstraintImpl();
                for (String roleName : sc.getAuthConstraint()) {
                    Role role = new Role(roleName);
                    getWebBundleDescriptor().addRole(role);
                    ac.addSecurityRole(roleName);
                }
            } else {
                // DENY
                ac = new AuthorizationConstraintImpl();
            }
            securityConstraint.setAuthorizationConstraint(ac);
            UserDataConstraint udc = new UserDataConstraintImpl();
            udc.setTransportGuarantee(((sc.getDataConstraint() == TransportGuarantee.CONFIDENTIAL) ? UserDataConstraint.CONFIDENTIAL_TRANSPORT : UserDataConstraint.NONE_TRANSPORT));
            securityConstraint.setUserDataConstraint(udc);
            if (wrc.getHttpMethods() != null) {
                for (String httpMethod : wrc.getHttpMethods()) {
                    webResourceColl.addHttpMethod(httpMethod);
                }
            }
            if (wrc.getHttpMethodOmissions() != null) {
                for (String httpMethod : wrc.getHttpMethodOmissions()) {
                    webResourceColl.addHttpMethodOmission(httpMethod);
                }
            }
            getWebBundleDescriptor().addSecurityConstraint(securityConstraint);
            TomcatDeploymentConfig.configureSecurityConstraint(this, getWebBundleDescriptor());
        }
    }
    if (pipeline != null) {
        GlassFishValve basic = pipeline.getBasic();
        if ((basic != null) && (basic instanceof java.net.Authenticator)) {
            removeValve(basic);
        }
        GlassFishValve[] valves = pipeline.getValves();
        for (int i = 0; i < valves.length; i++) {
            if (valves[i] instanceof java.net.Authenticator) {
                removeValve(valves[i]);
            }
        }
    }
    if (realm != null && realm instanceof RealmInitializer) {
        ((RealmInitializer) realm).initializeRealm(this.getWebBundleDescriptor(), false, ((VirtualServer) parent).getAuthRealmName());
        ((RealmInitializer) realm).setVirtualServer(getParent());
        ((RealmInitializer) realm).updateWebSecurityManager();
        setRealm(realm);
    }
}
Also used : WebResourceCollection(com.sun.enterprise.deployment.web.WebResourceCollection) RealmInitializer(com.sun.enterprise.security.integration.RealmInitializer) AuthorizationConstraintImpl(org.glassfish.web.deployment.descriptor.AuthorizationConstraintImpl) SecurityConstraint(com.sun.enterprise.deployment.web.SecurityConstraint) LoginConfigurationImpl(org.glassfish.web.deployment.descriptor.LoginConfigurationImpl) FormLoginConfig(org.glassfish.embeddable.web.config.FormLoginConfig) LoginConfig(org.glassfish.embeddable.web.config.LoginConfig) SecurityConstraintImpl(org.glassfish.web.deployment.descriptor.SecurityConstraintImpl) UserDataConstraint(com.sun.enterprise.deployment.web.UserDataConstraint) FormLoginConfig(org.glassfish.embeddable.web.config.FormLoginConfig) UserDataConstraintImpl(org.glassfish.web.deployment.descriptor.UserDataConstraintImpl) LoginConfiguration(com.sun.enterprise.deployment.web.LoginConfiguration) SecurityConstraint(com.sun.enterprise.deployment.web.SecurityConstraint) UserDataConstraint(com.sun.enterprise.deployment.web.UserDataConstraint) SecurityConstraint(com.sun.enterprise.deployment.web.SecurityConstraint) WebServiceEndpoint(com.sun.enterprise.deployment.WebServiceEndpoint) GlassFishValve(org.glassfish.web.valve.GlassFishValve) Role(org.glassfish.security.common.Role) LoginConfigDecorator(com.sun.enterprise.web.deploy.LoginConfigDecorator) WebResourceCollectionImpl(org.glassfish.web.deployment.descriptor.WebResourceCollectionImpl)

Example 2 with RealmInitializer

use of com.sun.enterprise.security.integration.RealmInitializer in project Payara by payara.

the class J2EEInstanceListener method handleAfterEvent.

private void handleAfterEvent(InstanceEvent event, InstanceEvent.EventType eventType) {
    Wrapper wrapper = event.getWrapper();
    Context context = (Context) wrapper.getParent();
    if (!(context instanceof WebModule)) {
        return;
    }
    WebModule wm = (WebModule) context;
    Object instance;
    if (eventType == InstanceEvent.EventType.AFTER_FILTER_EVENT) {
        instance = event.getFilter();
    } else {
        instance = event.getServlet();
    }
    if (instance == null) {
        return;
    }
    // Emit monitoring probe event
    if (instance instanceof Servlet) {
        if (eventType == InstanceEvent.EventType.AFTER_INIT_EVENT) {
            wm.servletInitializedEvent(wrapper.getName());
        } else if (eventType == InstanceEvent.EventType.AFTER_DESTROY_EVENT) {
            wm.servletDestroyedEvent(wrapper.getName());
        }
    }
    // EE invocation context
    try {
        if (eventType == InstanceEvent.EventType.AFTER_DESTROY_EVENT && !DefaultServlet.class.equals(instance.getClass()) && !JspServlet.class.equals(instance.getClass())) {
            injectionMgr.destroyManagedObject(instance, false);
        }
    } catch (InjectionException ie) {
        String msg = _rb.getString(LogFacade.EXCEPTION_DURING_HANDLE_EVENT);
        msg = MessageFormat.format(msg, new Object[] { eventType, wm });
        _logger.log(Level.SEVERE, msg, ie);
    }
    ComponentInvocation inv = new WebComponentInvocation(wm, instance);
    try {
        im.postInvoke(inv);
    } catch (Exception ex) {
        String msg = _rb.getString(LogFacade.EXCEPTION_DURING_HANDLE_EVENT);
        msg = MessageFormat.format(msg, new Object[] { eventType, wm });
        throw new RuntimeException(msg, ex);
    } finally {
        if (eventType == InstanceEvent.EventType.AFTER_DESTROY_EVENT) {
            if (tm != null) {
                tm.componentDestroyed(instance, inv);
            }
        } else if (eventType == InstanceEvent.EventType.AFTER_FILTER_EVENT || eventType == InstanceEvent.EventType.AFTER_SERVICE_EVENT) {
            // Emit monitoring probe event
            if (eventType == InstanceEvent.EventType.AFTER_SERVICE_EVENT) {
                ServletResponse response = event.getResponse();
                int status = -1;
                if (response != null && response instanceof HttpServletResponse) {
                    status = ((HttpServletResponse) response).getStatus();
                }
                wm.afterServiceEvent(wrapper.getName(), status);
            }
            // BEGIN IASRI# 4646060
            if (im.getCurrentInvocation() == null) {
                // END IASRI# 4646060
                try {
                    // clear security context
                    Realm ra = context.getRealm();
                    if (ra != null && (ra instanceof RealmInitializer)) {
                        // cleanup not only securitycontext but also PolicyContext
                        ((RealmInitializer) ra).logout();
                    }
                } catch (Exception ex) {
                    String msg = _rb.getString(LogFacade.EXCEPTION_DURING_HANDLE_EVENT);
                    msg = MessageFormat.format(msg, new Object[] { eventType, wm });
                    _logger.log(Level.SEVERE, msg, ex);
                }
                if (tm != null) {
                    try {
                        if (tm.getTransaction() != null) {
                            tm.rollback();
                        }
                        tm.cleanTxnTimeout();
                    } catch (Exception ex) {
                    }
                }
            }
            if (tm != null) {
                tm.componentDestroyed(instance, inv);
            }
        }
    }
}
Also used : AppServSecurityContext(com.sun.enterprise.security.integration.AppServSecurityContext) ServerContext(org.glassfish.internal.api.ServerContext) ServletRequestWrapper(javax.servlet.ServletRequestWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) ComponentInvocation(org.glassfish.api.invocation.ComponentInvocation) WebComponentInvocation(com.sun.enterprise.web.WebComponentInvocation) RealmInitializer(com.sun.enterprise.security.integration.RealmInitializer) HttpServletResponse(javax.servlet.http.HttpServletResponse) WebModule(com.sun.enterprise.web.WebModule) String(java.lang.String) InjectionException(com.sun.enterprise.container.common.spi.util.InjectionException) InjectionException(com.sun.enterprise.container.common.spi.util.InjectionException) WebComponentInvocation(com.sun.enterprise.web.WebComponentInvocation) JspServlet(org.apache.jasper.servlet.JspServlet) Servlet(javax.servlet.Servlet) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) DefaultServlet(org.apache.catalina.servlets.DefaultServlet)

Example 3 with RealmInitializer

use of com.sun.enterprise.security.integration.RealmInitializer in project Payara by payara.

the class WebContainer method loadWebModule.

/**
 * Creates and configures a web module and adds it to the specified
 * virtual server.
 */
private WebModule loadWebModule(VirtualServer vs, WebModuleConfig wmInfo, String j2eeApplication, Properties deploymentProperties) throws Exception {
    String wmName = wmInfo.getName();
    String wmContextPath = wmInfo.getContextPath();
    if (wmContextPath.indexOf('%') != -1) {
        try {
            RequestUtil.urlDecode(wmContextPath, "UTF-8");
        } catch (Exception e) {
            String msg = rb.getString(LogFacade.INVALID_ENCODED_CONTEXT_ROOT);
            msg = MessageFormat.format(msg, wmName, wmContextPath);
            throw new Exception(msg);
        }
    }
    if (wmContextPath.length() == 0 && vs.getDefaultWebModuleID() != null) {
        String msg = rb.getString(LogFacade.DEFAULT_WEB_MODULE_CONFLICT);
        msg = MessageFormat.format(msg, new Object[] { wmName, vs.getID() });
        throw new Exception(msg);
    }
    wmInfo.setWorkDirBase(_appsWorkRoot);
    // START S1AS 6178005
    wmInfo.setStubBaseDir(appsStubRoot);
    // END S1AS 6178005
    String displayContextPath = null;
    if (wmContextPath.length() == 0)
        displayContextPath = "/";
    else
        displayContextPath = wmContextPath;
    Map<String, AdHocServletInfo> adHocPaths = null;
    Map<String, AdHocServletInfo> adHocSubtrees = null;
    WebModule ctx = (WebModule) vs.findChild(wmContextPath);
    if (ctx != null) {
        if (ctx instanceof AdHocWebModule) {
            /*
                 * Found ad-hoc web module which has been created by web
                 * container in order to store mappings for ad-hoc paths
                 * and subtrees.
                 * All these mappings must be propagated to the context
                 * that is being deployed.
                 */
            if (ctx.hasAdHocPaths()) {
                adHocPaths = ctx.getAdHocPaths();
            }
            if (ctx.hasAdHocSubtrees()) {
                adHocSubtrees = ctx.getAdHocSubtrees();
            }
            vs.removeChild(ctx);
        } else if (Constants.DEFAULT_WEB_MODULE_NAME.equals(ctx.getModuleName())) {
            /*
                 * Dummy context that was created just off of a docroot,
                 * (see
                 * VirtualServer.createSystemDefaultWebModuleIfNecessary()).
                 * Unload it so it can be replaced with the web module to be
                 * loaded
                 */
            unloadWebModule(wmContextPath, ctx.getWebBundleDescriptor().getApplication().getRegistrationName(), vs.getName(), true, null);
        } else if (!ctx.getAvailable()) {
            /*
                 * Context has been marked unavailable by a previous
                 * call to disableWebModule. Mark the context as available and
                 * return
                 */
            ctx.setAvailable(true);
            return ctx;
        } else {
            String msg = rb.getString(LogFacade.DUPLICATE_CONTEXT_ROOT);
            throw new Exception(MessageFormat.format(msg, vs.getID(), ctx.getModuleName(), displayContextPath, wmName));
        }
    }
    if (logger.isLoggable(Level.FINEST)) {
        Object[] params = { wmName, vs.getID(), displayContextPath };
        logger.log(Level.FINEST, LogFacade.WEB_MODULE_LOADING, params);
    }
    File docBase = null;
    if (JWS_APPCLIENT_MODULE_NAME.equals(wmName)) {
        docBase = new File(System.getProperty("com.sun.aas.installRoot"));
    } else {
        docBase = wmInfo.getLocation();
    }
    ctx = (WebModule) _embedded.createContext(wmName, wmContextPath, docBase, vs.getDefaultContextXmlLocation(), vs.getDefaultWebXmlLocation(), useDOLforDeployment, wmInfo);
    // for now disable JNDI
    ctx.setUseNaming(false);
    // Set JSR 77 object name and attributes
    Engine engine = (Engine) vs.getParent();
    if (engine != null) {
        ctx.setEngineName(engine.getName());
        ctx.setJvmRoute(engine.getJvmRoute());
    }
    String j2eeServer = _serverContext.getInstanceName();
    String domain = _serverContext.getDefaultDomainName();
    // String[] javaVMs = J2EEModuleUtil.getjavaVMs();
    ctx.setDomain(domain);
    ctx.setJ2EEServer(j2eeServer);
    ctx.setJ2EEApplication(j2eeApplication);
    // turn on container internal cache by default as in v2
    // ctx.setCachingAllowed(false);
    ctx.setCacheControls(vs.getCacheControls());
    ctx.setBean(wmInfo.getBean());
    if (adHocPaths != null) {
        ctx.addAdHocPaths(adHocPaths);
    }
    if (adHocSubtrees != null) {
        ctx.addAdHocSubtrees(adHocSubtrees);
    }
    // Object containing web.xml information
    WebBundleDescriptor wbd = wmInfo.getDescriptor();
    // Set the context root
    if (wbd != null) {
        ctx.setContextRoot(wbd.getContextRoot());
    } else {
        // Should never happen.
        logger.log(Level.WARNING, LogFacade.UNABLE_TO_SET_CONTEXT_ROOT, wmInfo);
    }
    // 
    // Ensure that the generated directory for JSPs in the document root
    // (i.e. those that are serviced by a system default-web-module)
    // is different for each virtual server.
    String wmInfoWorkDir = wmInfo.getWorkDir();
    if (wmInfoWorkDir != null) {
        StringBuilder workDir = new StringBuilder(wmInfo.getWorkDir());
        if (wmName.equals(Constants.DEFAULT_WEB_MODULE_NAME)) {
            workDir.append("-");
            workDir.append(FileUtils.makeFriendlyFilename(vs.getID()));
        }
        ctx.setWorkDir(workDir.toString());
    }
    ClassLoader parentLoader = wmInfo.getParentLoader();
    if (parentLoader == null) {
        // Use the shared classloader as the parent for all
        // standalone web-modules
        parentLoader = _serverContext.getSharedClassLoader();
    }
    ctx.setParentClassLoader(parentLoader);
    if (wbd != null) {
        // Determine if an alternate DD is set for this web-module in
        // the application
        ctx.configureAlternateDD(wbd);
        ctx.configureWebServices(wbd);
    }
    // Object containing sun-web.xml information
    SunWebAppImpl iasBean = null;
    // The default context is the only case when wbd == null
    if (wbd != null) {
        iasBean = (SunWebAppImpl) wbd.getSunDescriptor();
    }
    // set the sun-web config bean
    ctx.setIasWebAppConfigBean(iasBean);
    // Configure SingleThreadedServletPools, work/tmp directory etc
    ctx.configureMiscSettings(iasBean, vs, displayContextPath);
    // Configure alternate docroots if dummy web module
    if (ctx.getID().startsWith(Constants.DEFAULT_WEB_MODULE_NAME)) {
        ctx.setAlternateDocBases(vs.getProperties());
    }
    // Configure the class loader delegation model, classpath etc
    Loader loader = ctx.configureLoader(iasBean);
    // Set the class loader on the DOL object
    if (wbd != null && wbd.hasWebServices()) {
        wbd.addExtraAttribute("WEBLOADER", loader);
    }
    for (LifecycleListener listener : ctx.findLifecycleListeners()) {
        if (listener instanceof ContextConfig) {
            ((ContextConfig) listener).setClassLoader(wmInfo.getAppClassLoader());
        }
    }
    // Configure the session manager and other related settings
    ctx.configureSessionSettings(wbd, wmInfo);
    // set i18n info from locale-charset-info tag in sun-web.xml
    ctx.setI18nInfo();
    if (wbd != null) {
        String resourceType = wmInfo.getObjectType();
        boolean isSystem = resourceType != null && resourceType.startsWith("system-");
        // security will generate policy for system default web module
        if (!wmName.startsWith(Constants.DEFAULT_WEB_MODULE_NAME)) {
            // TODO : v3 : dochez Need to remove dependency on security
            Realm realm = habitat.getService(Realm.class);
            if ("null".equals(j2eeApplication)) {
                /*
                     * Standalone webapps inherit the realm referenced by
                     * the virtual server on which they are being deployed,
                     * unless they specify their own
                     */
                if (realm != null && realm instanceof RealmInitializer) {
                    ((RealmInitializer) realm).initializeRealm(wbd, isSystem, vs.getAuthRealmName());
                    ctx.setRealm(realm);
                }
            } else {
                if (realm != null && realm instanceof RealmInitializer) {
                    ((RealmInitializer) realm).initializeRealm(wbd, isSystem, null);
                    ctx.setRealm(realm);
                }
            }
        }
        // post processing DOL object for standalone web module
        if (wbd.getApplication() != null && wbd.getApplication().isVirtual()) {
            wbd.visit(new WebValidatorWithoutCL());
        }
    }
    // Add virtual server mime mappings, if present
    addMimeMappings(ctx, vs.getMimeMap());
    String moduleName = Constants.DEFAULT_WEB_MODULE_NAME;
    String monitoringNodeName = moduleName;
    if (wbd != null && wbd.getApplication() != null) {
        // Not a dummy web module
        com.sun.enterprise.deployment.Application app = wbd.getApplication();
        ctx.setStandalone(app.isVirtual());
        // S1AS BEGIN WORKAROUND FOR 6174360
        if (app.isVirtual()) {
            // Standalone web module
            moduleName = app.getRegistrationName();
            monitoringNodeName = wbd.getModuleID();
        } else {
            // Nested (inside EAR) web module
            moduleName = wbd.getModuleDescriptor().getArchiveUri();
            StringBuilder sb = new StringBuilder();
            sb.append(app.getRegistrationName()).append(MONITORING_NODE_SEPARATOR).append(moduleName);
            monitoringNodeName = sb.toString().replaceAll("\\.", "\\\\.").replaceAll("_war", "\\\\.war");
        }
    // S1AS END WORKAROUND FOR 6174360
    }
    ctx.setModuleName(moduleName);
    ctx.setMonitoringNodeName(monitoringNodeName);
    List<String> servletNames = new ArrayList<String>();
    if (wbd != null) {
        for (WebComponentDescriptor webCompDesc : wbd.getWebComponentDescriptors()) {
            if (webCompDesc.isServlet()) {
                servletNames.add(webCompDesc.getCanonicalName());
            }
        }
    }
    webStatsProviderBootstrap.registerApplicationStatsProviders(monitoringNodeName, vs.getName(), servletNames);
    vs.addChild(ctx);
    ctx.loadSessions(deploymentProperties);
    return ctx;
}
Also used : SunWebAppImpl(org.glassfish.web.deployment.runtime.SunWebAppImpl) WebValidatorWithoutCL(org.glassfish.web.deployment.util.WebValidatorWithoutCL) RealmInitializer(com.sun.enterprise.security.integration.RealmInitializer) ArrayList(java.util.ArrayList) WebappClassLoader(org.glassfish.web.loader.WebappClassLoader) Loader(org.apache.catalina.Loader) LifecycleListener(org.apache.catalina.LifecycleListener) ContextConfig(org.apache.catalina.startup.ContextConfig) WebBundleDescriptor(com.sun.enterprise.deployment.WebBundleDescriptor) WebappClassLoader(org.glassfish.web.loader.WebappClassLoader) Realm(org.apache.catalina.Realm) StandardEngine(org.apache.catalina.core.StandardEngine) Engine(org.apache.catalina.Engine) LifecycleException(org.apache.catalina.LifecycleException) NamingException(javax.naming.NamingException) BindException(java.net.BindException) MalformedURLException(java.net.MalformedURLException) WebComponentDescriptor(com.sun.enterprise.deployment.WebComponentDescriptor) Application(com.sun.enterprise.deployment.Application) File(java.io.File)

Example 4 with RealmInitializer

use of com.sun.enterprise.security.integration.RealmInitializer in project Payara by payara.

the class DynamicWebServletRegistrationImpl method setParent.

/**
 * Sets the virtual server parent of this web module, and passes it on to
 * this web module's realm adapter..
 *
 * @param container The virtual server parent
 */
@Override
public void setParent(Container container) {
    super.setParent(container);
    if (container instanceof VirtualServer) {
        vsId = ((VirtualServer) container).getID();
    }
    // The following assumes that the realm has been set on this WebModule
    // before the WebModule is added as a child to the virtual server on
    // which it is being deployed.
    /*RealmAdapter ra = (RealmAdapter) getRealm();
        if (ra != null) {
          1  ra.setVirtualServer(container);
        }*/
    Realm ra = getRealm();
    if (ra != null && ra instanceof RealmInitializer) {
        ((RealmInitializer) ra).setVirtualServer(container);
    }
}
Also used : RealmInitializer(com.sun.enterprise.security.integration.RealmInitializer) Realm(org.apache.catalina.Realm)

Aggregations

RealmInitializer (com.sun.enterprise.security.integration.RealmInitializer)4 Realm (org.apache.catalina.Realm)2 InjectionException (com.sun.enterprise.container.common.spi.util.InjectionException)1 Application (com.sun.enterprise.deployment.Application)1 WebBundleDescriptor (com.sun.enterprise.deployment.WebBundleDescriptor)1 WebComponentDescriptor (com.sun.enterprise.deployment.WebComponentDescriptor)1 WebServiceEndpoint (com.sun.enterprise.deployment.WebServiceEndpoint)1 LoginConfiguration (com.sun.enterprise.deployment.web.LoginConfiguration)1 SecurityConstraint (com.sun.enterprise.deployment.web.SecurityConstraint)1 UserDataConstraint (com.sun.enterprise.deployment.web.UserDataConstraint)1 WebResourceCollection (com.sun.enterprise.deployment.web.WebResourceCollection)1 AppServSecurityContext (com.sun.enterprise.security.integration.AppServSecurityContext)1 WebComponentInvocation (com.sun.enterprise.web.WebComponentInvocation)1 WebModule (com.sun.enterprise.web.WebModule)1 LoginConfigDecorator (com.sun.enterprise.web.deploy.LoginConfigDecorator)1 File (java.io.File)1 String (java.lang.String)1 BindException (java.net.BindException)1 MalformedURLException (java.net.MalformedURLException)1 ArrayList (java.util.ArrayList)1