Search in sources :

Example 11 with ParamType

use of com.tremolosecurity.config.xml.ParamType in project OpenUnison by TremoloSecurity.

the class SendMessageThread method generateTargets.

private void generateTargets(ConfigManager cfgMgr) throws ProvisioningException {
    if (cfgMgr.getCfg().getProvisioning() == null) {
        return;
    }
    this.targetIDs = new HashMap<String, Targets>();
    Iterator<TargetType> it = cfgMgr.getCfg().getProvisioning().getTargets().getTarget().iterator();
    while (it.hasNext()) {
        TargetType targetCfg = it.next();
        addTarget(cfgMgr, targetCfg);
    }
    if (cfgMgr.getCfg().getProvisioning().getTargets().getDynamicTargets() != null && cfgMgr.getCfg().getProvisioning().getTargets().getDynamicTargets().isEnabled()) {
        DynamicPortalUrlsType dynamicTargets = cfgMgr.getCfg().getProvisioning().getTargets().getDynamicTargets();
        String className = dynamicTargets.getClassName();
        HashMap<String, Attribute> cfgAttrs = new HashMap<String, Attribute>();
        for (ParamType pt : dynamicTargets.getParams()) {
            Attribute attr = cfgAttrs.get(pt.getName());
            if (attr == null) {
                attr = new Attribute(pt.getName());
                cfgAttrs.put(pt.getName(), attr);
            }
            attr.getValues().add(pt.getValue());
        }
        try {
            DynamicTargets dynTargets = (DynamicTargets) Class.forName(className).newInstance();
            dynTargets.loadDynamicTargets(cfgMgr, this, cfgAttrs);
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            throw new ProvisioningException("Could not initialize dynamic targets", e);
        }
    }
}
Also used : DynamicTargets(com.tremolosecurity.provisioning.targets.DynamicTargets) Attribute(com.tremolosecurity.saml.Attribute) LDAPAttribute(com.novell.ldap.LDAPAttribute) HashMap(java.util.HashMap) DynamicTargets(com.tremolosecurity.provisioning.targets.DynamicTargets) Targets(com.tremolosecurity.provisioning.objects.Targets) ParamType(com.tremolosecurity.config.xml.ParamType) DynamicPortalUrlsType(com.tremolosecurity.config.xml.DynamicPortalUrlsType) TargetType(com.tremolosecurity.config.xml.TargetType)

Example 12 with ParamType

use of com.tremolosecurity.config.xml.ParamType in project OpenUnison by TremoloSecurity.

the class UnisonConfigManagerImpl method loadAuthMechs.

/* (non-Javadoc)
	 * @see com.tremolosecurity.config.util.ConfigManager#loadAuthMechs()
	 */
/* (non-Javadoc)
	 * @see com.tremolosecurity.config.util.UnisonConfigManager#loadAuthMechs()
	 */
@Override
public void loadAuthMechs() throws ServletException {
    try {
        this.mechs = new HashMap<String, AuthMechanism>();
        // UnisonConfigManagerImpl tremoloCfg = (UnisonConfigManagerImpl) ctx.getAttribute(ConfigFilter.TREMOLO_CONFIG);
        if (getCfg().getAuthMechs() != null) {
            Iterator<MechanismType> mechs = getCfg().getAuthMechs().getMechanism().iterator();
            while (mechs.hasNext()) {
                MechanismType mt = mechs.next();
                initializeAuthenticationMechanism(mt);
            }
        }
    } catch (Exception e) {
        throw new ServletException("Could not initialize Auth Mechanism Filter", e);
    }
    for (String key : this.authChains.keySet()) {
        AuthChainType act = this.authChains.get(key);
        if (act.getLevel() == 0) {
            this.anonAct = act;
            String mechName = act.getAuthMech().get(0).getName();
            this.anonAuthMech = (AnonAuth) this.getAuthMech(this.authMechs.get(mechName).getUri());
        }
    }
    if (this.anonAuthMech == null) {
        this.anonAct = new AuthChainType();
        this.anonAct.setFinishOnRequiredSucess(true);
        this.anonAct.setLevel(0);
        this.anonAct.setName("anon");
        this.anonAuthMech = new AnonAuth();
    }
    if (this.alwaysFailAuth == null) {
        this.alwaysFailAuth = new AlwaysFail();
        String failAuthUri = this.ctxPath + "/fail";
        this.mechs.put(failAuthUri, alwaysFailAuth);
        MechanismType fmt = new MechanismType();
        fmt.setClassName("com.tremolosecurity.proxy.auth.AlwaysFail");
        fmt.setInit(new ConfigType());
        fmt.setParams(new ParamListType());
        fmt.setName("fail");
        fmt.setUri(failAuthUri);
        if (this.cfg.getAuthMechs() == null) {
            this.cfg.setAuthMechs(new AuthMechTypes());
        }
        this.cfg.getAuthMechs().getMechanism().add(fmt);
        this.alwaysFailAuthMech = fmt;
    }
    for (String key : this.authChains.keySet()) {
        AuthChainType act = this.authChains.get(key);
        for (AuthMechType amt : act.getAuthMech()) {
            if (amt.getName().equals(this.alwaysFailAuthMech.getName())) {
                this.authFailChain = act;
                break;
            }
        }
    }
    if (this.authFailChain == null) {
        this.authFailChain = new AuthChainType();
        this.authFailChain.setLevel(0);
        this.authFailChain.setName("alwaysfail");
        AuthMechType amt = new AuthMechType();
        amt.setName(this.alwaysFailAuthMech.getName());
        amt.setRequired("required");
        amt.setParams(new AuthMechParamType());
        this.authFailChain.getAuthMech().add(amt);
    }
    try {
        if (this.getCfg().getAuthMechs() != null && this.getCfg().getAuthMechs().getDynamicAuthMechs() != null && this.getCfg().getAuthMechs().getDynamicAuthMechs().isEnabled()) {
            DynamicPortalUrlsType dynamicAuthMechs = this.getCfg().getAuthMechs().getDynamicAuthMechs();
            String className = dynamicAuthMechs.getClassName();
            HashMap<String, Attribute> cfgAttrs = new HashMap<String, Attribute>();
            for (ParamType pt : dynamicAuthMechs.getParams()) {
                Attribute attr = cfgAttrs.get(pt.getName());
                if (attr == null) {
                    attr = new Attribute(pt.getName());
                    cfgAttrs.put(pt.getName(), attr);
                }
                attr.getValues().add(pt.getValue());
            }
            DynamicAuthMechs dynCustomAuMechs = (DynamicAuthMechs) Class.forName(className).newInstance();
            dynCustomAuMechs.loadDynamicAuthMechs(this, this.getProvisioningEngine(), cfgAttrs);
        }
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | ProvisioningException e) {
        throw new ServletException("Could not initialize authentication mechanisms", e);
    }
}
Also used : AuthMechParamType(com.tremolosecurity.config.xml.AuthMechParamType) AnonAuth(com.tremolosecurity.proxy.auth.AnonAuth) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) ServletException(javax.servlet.ServletException) DynamicAuthMechs(com.tremolosecurity.proxy.dynamicloaders.DynamicAuthMechs) AuthMechanism(com.tremolosecurity.proxy.auth.AuthMechanism) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) MechanismType(com.tremolosecurity.config.xml.MechanismType) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) ConfigType(com.tremolosecurity.config.xml.ConfigType) ParamListType(com.tremolosecurity.config.xml.ParamListType) AuthMechTypes(com.tremolosecurity.config.xml.AuthMechTypes) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) KeyStoreException(java.security.KeyStoreException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) LDAPException(com.novell.ldap.LDAPException) AzException(com.tremolosecurity.proxy.az.AzException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) AuthMechParamType(com.tremolosecurity.config.xml.AuthMechParamType) ParamType(com.tremolosecurity.config.xml.ParamType) AlwaysFail(com.tremolosecurity.proxy.auth.AlwaysFail) DynamicPortalUrlsType(com.tremolosecurity.config.xml.DynamicPortalUrlsType)

Example 13 with ParamType

use of com.tremolosecurity.config.xml.ParamType in project OpenUnison by TremoloSecurity.

the class PreAuthFilter method initFilter.

@Override
public void initFilter(HttpFilterConfig config) throws Exception {
    this.postSAML = config.getAttribute("postSAML") != null && config.getAttribute("postSAML").getValues().get(0).equalsIgnoreCase("true");
    if (postSAML) {
        String idpName = config.getAttribute("idpName").getValues().get(0);
        ApplicationType app = config.getConfigManager().getApp(idpName);
        IdpType idp = app.getUrls().getUrl().get(0).getIdp();
        for (ParamType pt : idp.getParams()) {
            if (pt.getName().equalsIgnoreCase("sigKey")) {
                this.keyAlias = pt.getValue();
            }
        }
        TrustType tt = idp.getTrusts().getTrust().get(0);
        for (ParamType pt : tt.getParam()) {
            if (pt.getName().equalsIgnoreCase("signResponse")) {
                this.signResponse = pt.getValue().equalsIgnoreCase("true");
            } else if (pt.getName().equalsIgnoreCase("signAssertion")) {
                this.signAssertion = pt.getValue().equalsIgnoreCase("true");
            } else if (pt.getName().equalsIgnoreCase("httpPostRespURL")) {
                this.assertionConsumerURL = pt.getValue();
            } else if (pt.getName().equalsIgnoreCase("defaultNameId")) {
                this.nameIDType = pt.getValue();
            } else if (pt.getName().equalsIgnoreCase("nameIdMap")) {
                this.nameIDAttribute = pt.getValue().substring(pt.getValue().indexOf('=') + 1);
            } else if (pt.getName().equalsIgnoreCase("defaultAuthCtx")) {
                this.authnCtxClassRef = pt.getValue();
            }
        }
        String issuerHost = config.getAttribute("issuerHost").getValues().get(0);
        String issuerPort = config.getAttribute("issuerPort").getValues().get(0);
        boolean issuerSSL = config.getAttribute("issuerSSL").getValues().get(0).equalsIgnoreCase("true");
        StringBuffer b = new StringBuffer();
        if (issuerSSL) {
            b.append("https://");
        } else {
            b.append("http://");
        }
        b.append(issuerHost);
        if (!issuerPort.isEmpty()) {
            b.append(':').append(issuerPort);
        }
        b.append("/auth/idp/").append(idpName);
        this.issuer = b.toString();
        // this.issuer = config.getAttribute("issuer").getValues().get(0);
        this.audience = tt.getName();
        this.relayState = config.getAttribute("relayState").getValues().get(0);
        InitializationService.initialize();
        this.url = this.assertionConsumerURL;
    } else {
        this.url = config.getAttribute("url").getValues().get(0);
    }
    URL nurl = new URL(this.url);
    this.uri = nurl.getPath();
    UrlType urlCfg = config.getConfigManager().findURL(this.url).getUrl();
    for (FilterConfigType filterCfg : urlCfg.getFilterChain().getFilter()) {
        if (filterCfg.getClazz().equalsIgnoreCase("com.tremolosecurity.proxy.filters.LastMile")) {
            for (ParamWithValueType pt : filterCfg.getParam()) {
                if (pt.getName().equalsIgnoreCase("encKeyAlias")) {
                    this.lastMileKeyAlias = pt.getValue();
                } else if (pt.getName().equalsIgnoreCase("headerName")) {
                    this.headerName = pt.getValue();
                } else if (pt.getName().equalsIgnoreCase("userAttribute")) {
                    this.loginAttribute = pt.getValue();
                }
            }
            for (ParamWithValueType pt : filterCfg.getParam()) {
                if (pt.getName().equalsIgnoreCase("attribs")) {
                    String param = pt.getValue();
                    String fromUser = param.substring(0, param.indexOf('='));
                    String toApp = param.substring(param.indexOf('=') + 1);
                    if (fromUser.equalsIgnoreCase(this.headerName)) {
                        this.headerName = toApp;
                    }
                }
            }
        }
    }
    logger.info("URL : '" + this.url + "'");
    logger.info("Key Alias : '" + this.lastMileKeyAlias + "'");
    logger.info("Login ID Attribute : '" + this.loginAttribute + "'");
    logger.info("Header Attribute : '" + this.headerName + "'");
    if (this.postSAML) {
        logger.info("Saml : true");
        logger.info("Issuer : " + this.issuer);
    }
}
Also used : ApplicationType(com.tremolosecurity.config.xml.ApplicationType) IdpType(com.tremolosecurity.config.xml.IdpType) FilterConfigType(com.tremolosecurity.config.xml.FilterConfigType) TrustType(com.tremolosecurity.config.xml.TrustType) ParamWithValueType(com.tremolosecurity.config.xml.ParamWithValueType) UrlType(com.tremolosecurity.config.xml.UrlType) ParamType(com.tremolosecurity.config.xml.ParamType) URL(java.net.URL)

Example 14 with ParamType

use of com.tremolosecurity.config.xml.ParamType in project OpenUnison by TremoloSecurity.

the class ScaleMain method loadWorkflows.

private void loadWorkflows(HttpFilterRequest request, HttpFilterResponse response, Gson gson) throws Exception {
    String orgid = request.getRequestURI().substring(request.getRequestURI().lastIndexOf('/') + 1);
    ConfigManager cfgMgr = GlobalEntries.getGlobalEntries().getConfigManager();
    HashSet<String> allowedOrgs = new HashSet<String>();
    AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
    OrgType ot = GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getProvisioning().getOrg();
    AzSys az = new AzSys();
    this.checkOrg(allowedOrgs, ot, az, userData, request.getSession());
    if (!allowedOrgs.contains(orgid)) {
        response.setStatus(401);
        response.setContentType("application/json");
        ScaleError error = new ScaleError();
        error.getErrors().add("Unauthorized");
        ScaleJSUtils.addCacheHeaders(response);
        response.getWriter().print(gson.toJson(error).trim());
        response.getWriter().flush();
    } else {
        List<WorkflowType> wfs = GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getProvisioning().getWorkflows().getWorkflow();
        ArrayList<WFDescription> workflows = new ArrayList<WFDescription>();
        for (WorkflowType wf : wfs) {
            if (wf.isInList() != null && wf.isInList().booleanValue()) {
                if (wf.getOrgid() == null || wf.getOrgid().equalsIgnoreCase(orgid)) {
                    if (wf.getDynamicConfiguration() != null && wf.getDynamicConfiguration().isDynamic()) {
                        HashMap<String, Attribute> params = new HashMap<String, Attribute>();
                        if (wf.getDynamicConfiguration().getParam() != null) {
                            for (ParamType p : wf.getDynamicConfiguration().getParam()) {
                                Attribute attr = params.get(p.getName());
                                if (attr == null) {
                                    attr = new Attribute(p.getName());
                                    params.put(p.getName(), attr);
                                }
                                attr.getValues().add(p.getValue());
                            }
                        }
                        DynamicWorkflow dwf = (DynamicWorkflow) Class.forName(wf.getDynamicConfiguration().getClassName()).newInstance();
                        List<Map<String, String>> wfParams = dwf.generateWorkflows(wf, cfgMgr, params, userData);
                        StringBuffer b = new StringBuffer();
                        b.append('/').append(URLEncoder.encode(wf.getName(), "UTF-8"));
                        String uri = b.toString();
                        for (Map<String, String> wfParamSet : wfParams) {
                            DateTime now = new DateTime();
                            DateTime expires = now.plusHours(1);
                            LastMile lm = new LastMile(uri, now, expires, 0, "");
                            for (String key : wfParamSet.keySet()) {
                                String val = wfParamSet.get(key);
                                Attribute attr = new Attribute(key, val);
                                lm.getAttributes().add(attr);
                            }
                            WFDescription desc = new WFDescription();
                            desc.setUuid(UUID.randomUUID().toString());
                            desc.setName(wf.getName());
                            ST st = new ST(wf.getLabel(), '$', '$');
                            for (String key : wfParamSet.keySet()) {
                                st.add(key.replaceAll("[.]", "_"), wfParamSet.get(key));
                            }
                            desc.setLabel(st.render());
                            st = new ST(wf.getDescription(), '$', '$');
                            for (String key : wfParamSet.keySet()) {
                                st.add(key.replaceAll("[.]", "_"), wfParamSet.get(key));
                            }
                            desc.setDescription(st.render());
                            desc.setEncryptedParams(lm.generateLastMileToken(cfgMgr.getSecretKey(cfgMgr.getCfg().getProvisioning().getApprovalDB().getEncryptionKey())));
                            workflows.add(desc);
                        }
                    } else {
                        WFDescription desc = new WFDescription();
                        desc.setUuid(UUID.randomUUID().toString());
                        desc.setName(wf.getName());
                        desc.setLabel(wf.getLabel());
                        desc.setDescription(wf.getDescription());
                        workflows.add(desc);
                    }
                }
            }
        }
        ScaleJSUtils.addCacheHeaders(response);
        response.setContentType("application/json");
        response.getWriter().println(gson.toJson(workflows).trim());
        response.getWriter().flush();
    }
}
Also used : Attribute(com.tremolosecurity.saml.Attribute) LDAPAttribute(com.novell.ldap.LDAPAttribute) ScaleAttribute(com.tremolosecurity.scalejs.cfg.ScaleAttribute) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) XSSFRichTextString(org.apache.poi.xssf.usermodel.XSSFRichTextString) RichTextString(org.apache.poi.ss.usermodel.RichTextString) DateTime(org.joda.time.DateTime) WFDescription(com.tremolosecurity.provisioning.service.util.WFDescription) DynamicWorkflow(com.tremolosecurity.provisioning.util.DynamicWorkflow) HashSet(java.util.HashSet) ST(org.stringtemplate.v4.ST) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) ScaleError(com.tremolosecurity.scalejs.data.ScaleError) AuthController(com.tremolosecurity.proxy.auth.AuthController) ConfigManager(com.tremolosecurity.config.util.ConfigManager) ParamType(com.tremolosecurity.config.xml.ParamType) LastMile(com.tremolosecurity.lastmile.LastMile) OrgType(com.tremolosecurity.config.xml.OrgType) WorkflowType(com.tremolosecurity.config.xml.WorkflowType) AzSys(com.tremolosecurity.proxy.auth.AzSys) Map(java.util.Map) HashMap(java.util.HashMap)

Example 15 with ParamType

use of com.tremolosecurity.config.xml.ParamType in project OpenUnison by TremoloSecurity.

the class OpenUnisonOnUndertow method main.

public static void main(String[] args) throws Exception {
    OpenUnisonConfig config = null;
    logger.info("Starting OpenUnison on Undertow " + OpenUnisonServletFilter.version);
    if (args.length == 0) {
        logger.error("One argument required, path to yaml or json config");
        System.exit(1);
    } else if (args[0].endsWith(".yaml")) {
        logger.info("Parsing YAML : '" + args[0] + "'");
        Yaml yaml = new Yaml();
        Map<String, Object> map = (Map<String, Object>) yaml.load(new FileInputStream(args[0]));
        JSONObject jsonObject = new JSONObject(map);
        String json = jsonObject.toJSONString();
        config = gson.fromJson(json, OpenUnisonConfig.class);
    } else {
        logger.info("Parsing JSON : '" + args[0] + "'");
        config = gson.fromJson(new InputStreamReader(new FileInputStream(args[0])), OpenUnisonConfig.class);
    }
    final OpenUnisonConfig fconfig = config;
    if (config.getContextRoot() == null) {
        config.setContextRoot("/");
    }
    logger.info("Config Open Port : '" + config.getOpenPort() + "'");
    logger.info("Disable HTTP2 : '" + config.isDisableHttp2() + "'");
    logger.info("Allow unescaped characters : '" + config.isAllowUnEscapedChars() + "'");
    logger.info("Config Open External Port : '" + config.getOpenExternalPort() + "'");
    logger.info("Config Secure Port : '" + config.getSecurePort() + "'");
    logger.info("Config Secure External Port : '" + config.getSecureExternalPort() + "'");
    logger.info("Config Context Root :  '" + config.getContextRoot() + "'");
    logger.info("Force to Secure : '" + config.isForceToSecure() + "'");
    logger.info("ActiveMQ Directory : '" + config.getActivemqDir() + "'");
    logger.info("Quartz Directory : '" + config.getQuartzDir() + "'");
    logger.info("Config TLS Client Auth Mode : '" + config.getClientAuth() + "'");
    logger.info("Config TLS Allowed Client Subjects : '" + config.getAllowedClientNames() + "'");
    logger.info("Config TLS Protocols : '" + config.getAllowedTlsProtocols() + "'");
    logger.info("Config TLS Ciphers : '" + config.getCiphers() + "'");
    logger.info("Config Path to Deployment : '" + config.getPathToDeployment() + "'");
    logger.info("Config Path to Environment File : '" + config.getPathToEnvFile() + "'");
    logger.info("Redirect to contex root : '" + config.isRedirectToContextRoot() + "'");
    logger.info("Support socket shutdown : " + config.isSocketShutdownListener());
    if (config.isSocketShutdownListener()) {
        logger.info("Socket shutdown host : '" + config.getSocketShutdownHost() + "'");
        logger.info("Socket shutdown port : '" + config.getSocketShutdownPort() + "'");
        logger.info("Socket shutdown command : '" + config.getSocketShutdownCommand() + "'");
    }
    logger.info("Override Queue Configuration : '" + config.getQueueConfiguration() != null + "'");
    logger.info("Creating unisonServiceProps");
    File f = File.createTempFile("unisonService", "props");
    logger.info("Temporary unisonServiceProps : '" + f.getAbsolutePath() + "'");
    Properties unisonServiceProps = new Properties();
    unisonServiceProps.put("com.tremolosecurity.openunison.forceToSSL", Boolean.toString(config.isForceToSecure()));
    unisonServiceProps.put("com.tremolosecurity.openunison.openPort", Integer.toString(config.getOpenPort()));
    unisonServiceProps.put("com.tremolosecurity.openunison.securePort", Integer.toString(config.getSecurePort()));
    unisonServiceProps.put("com.tremolosecurity.openunison.externalOpenPort", Integer.toString(config.getOpenExternalPort()));
    unisonServiceProps.put("com.tremolosecurity.openunison.externalSecurePort", Integer.toString(config.getSecureExternalPort()));
    if (config.getActivemqDir() != null) {
        unisonServiceProps.put("com.tremolosecurity.openunison.activemqdir", config.getActivemqDir());
    }
    if (config.getQuartzDir() != null) {
        unisonServiceProps.put("com.tremolosecurity.openunison.quartzdir", config.getQuartzDir());
    }
    unisonServiceProps.store(new FileOutputStream(f), "OpenUnison Configuration");
    System.getProperties().put("com.tremolosecurity.unison.unisonServicePropsPath", f.getAbsolutePath());
    System.getProperties().put("com.tremolosecurity.unison.unisonXML", config.getPathToDeployment() + "/webapp/WEB-INF/unison.xml");
    logger.info("Loading environment file : '" + config.getPathToEnvFile() + "'");
    Properties env = new Properties();
    env.load(new FileInputStream(config.getPathToEnvFile()));
    for (Object name : env.keySet()) {
        logger.info("Adding property : '" + name + "'");
        System.setProperty((String) name, env.getProperty((String) name));
    }
    if (config.getQueueConfiguration() != null) {
        QueueConfigType qc = new QueueConfigType();
        qc.setConnectionFactory(config.getQueueConfiguration().getConnectionFactory());
        qc.setEncryptionKeyName(config.getQueueConfiguration().getEncryptionKeyName());
        qc.setIsUseInternalQueue(config.getQueueConfiguration().isUseInternalQueue());
        qc.setKeepAliveMillis(config.getQueueConfiguration().getKeepAliveMillis());
        qc.setMaxConsumers(((Long) config.getQueueConfiguration().getMaxConsumers()).intValue());
        qc.setMaxProducers(((Long) config.getQueueConfiguration().getMaxProducers()).intValue());
        qc.setMaxSessionsPerConnection(((Long) config.getQueueConfiguration().getMaxSessionsPerConnection()).intValue());
        qc.setMultiTaskQueues(config.getQueueConfiguration().isMultiTaskQueues());
        qc.setNumQueues(((Long) config.getQueueConfiguration().getNumQueues()).intValue());
        qc.setSmtpQueueName(config.getQueueConfiguration().getSmtpQueueName());
        qc.setTaskQueueName(config.getQueueConfiguration().getTaskQueueName());
        for (QueueConfigParam param : config.getQueueConfiguration().getParams()) {
            ParamType pt = new ParamType();
            pt.setName(param.getName());
            if (param.getSourceType().equalsIgnoreCase("static")) {
                pt.setValue(param.getValue());
            } else {
                pt.setValue(System.getProperty(param.getValue()));
            }
            qc.getParam().add(pt);
        }
        GlobalEntries.getGlobalEntries().set("openunison.queueconfig", qc);
    }
    logger.info("Loading keystore for Undertow");
    String unisonXML = config.getPathToDeployment() + "/webapp/WEB-INF/unison.xml";
    logger.info("OpenUnison XML File : '" + unisonXML + "'");
    String unisonXMLContent = OpenUnisonConfigLoader.generateOpenUnisonConfig(unisonXML);
    JAXBContext jc = JAXBContext.newInstance("com.tremolosecurity.config.xml");
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    Object obj = unmarshaller.unmarshal(new ByteArrayInputStream(unisonXMLContent.getBytes("UTF-8")));
    JAXBElement<TremoloType> cfg = (JAXBElement<TremoloType>) obj;
    TremoloType unisonConfiguration = cfg.getValue();
    logger.info("Loading keystore : '" + unisonConfiguration.getKeyStorePath() + "'");
    logger.info("Building Undertow");
    Builder buildUndertow = Undertow.builder();
    buildUndertow.setServerOption(UndertowOptions.NO_REQUEST_TIMEOUT, 60000);
    logger.info("Check if enabling HTTP2 - " + config.isDisableHttp2());
    if (!config.isDisableHttp2()) {
        logger.info("Enabling HTTP2");
        buildUndertow.setServerOption(UndertowOptions.ENABLE_HTTP2, true);
    }
    if (config.getOpenPort() > 0) {
        buildUndertow.addHttpListener(config.getOpenPort(), "0.0.0.0");
        logger.info("Adding open port : '" + config.getOpenPort() + "'");
    }
    if (config.getSecurePort() > 0) {
        setupTlsListener(config, unisonConfiguration, buildUndertow);
    }
    File pathToWebApp = new File(config.getPathToDeployment() + "/webapp");
    logger.info("Path to webapp : '" + pathToWebApp.getAbsolutePath() + "'");
    logger.info("Path directory? : '" + pathToWebApp.isDirectory() + "'");
    logger.info("Path exists : '" + pathToWebApp.exists() + "'");
    DeploymentInfo servletBuilder = Servlets.deployment().setClassLoader(OpenUnisonOnUndertow.class.getClassLoader()).setEagerFilterInit(true).setContextPath(config.getContextRoot()).setDeploymentName("openunison").addFilter(Servlets.filter("openunison", com.tremolosecurity.openunison.OpenUnisonServletFilter.class).addInitParam("mode", "appliance")).addFilterUrlMapping("openunison", "/*", DispatcherType.REQUEST).setResourceManager(new FileResourceManager(pathToWebApp, 1024, true, true)).addServlet(JspServletBuilder.createServlet("Default Jsp Servlet", "*.jsp")).addServlet(Servlets.servlet("identityProvider", com.tremolosecurity.idp.server.IDP.class).addMapping("/auth/idp/*"));
    if (config.getWelcomePages() != null) {
        servletBuilder.addWelcomePages(config.getWelcomePages());
    }
    if (config.getErrorPages() != null) {
        logger.info("Adding error pages");
        ArrayList<ErrorPage> errorPages = new ArrayList<ErrorPage>();
        for (ErrorPageConfig ep : config.getErrorPages()) {
            if (ep.getCode() == 0) {
                logger.info("Adding default page: " + ep.getLocation());
                errorPages.add(new ErrorPage(ep.getLocation()));
            } else {
                logger.info("Adding page for " + ep.getCode() + " : " + ep.getLocation());
                errorPages.add(new ErrorPage(ep.getLocation(), ep.getCode()));
            }
        }
        servletBuilder.addErrorPages(errorPages);
    }
    JspServletBuilder.setupDeployment(servletBuilder, new HashMap<String, JspPropertyGroup>(), new HashMap<String, TagLibraryInfo>(), new HackInstanceManager());
    DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
    manager.deploy();
    PathHandler path = Handlers.path(Handlers.redirect(config.getContextRoot())).addPrefixPath(config.getContextRoot(), manager.start());
    if (config.isForceToLowerCase()) {
        buildUndertow.setHandler(new OpenUnisonPathHandler(path));
    } else {
        buildUndertow.setHandler(path);
    }
    if (!config.getContextRoot().equals("/")) {
        if (!config.isRedirectToContextRoot()) {
            logger.info("Not redirecting to context");
            servletBuilder = Servlets.deployment().setClassLoader(OpenUnisonOnUndertow.class.getClassLoader()).setEagerFilterInit(true).setContextPath("/").setDeploymentName("root");
            manager = Servlets.defaultContainer().addDeployment(servletBuilder);
            manager.deploy();
            path.addPrefixPath("/", manager.start());
        } else {
            logger.info("Redirecting to context");
            path.addPrefixPath("/", new RedirectHandler(config.getContextRoot()));
        }
    }
    if (config.isAllowUnEscapedChars()) {
        buildUndertow.setServerOption(UndertowOptions.ALLOW_UNESCAPED_CHARACTERS_IN_URL, true);
    }
    undertow = buildUndertow.build();
    Runtime.getRuntime().addShutdownHook(new Thread() {

        public void run() {
            logger.info("Shutting down");
            undertow.stop();
            GlobalEntries.getGlobalEntries().getConfigManager().clearThreads();
            if (myvd != null) {
                try {
                    myvd.shutdown();
                } catch (Exception e) {
                    logger.warn("Did not gracefullt stop directory service", e);
                }
            }
        }
    });
    if (config.isSocketShutdownListener()) {
        new Thread() {

            public void run() {
                logger.info("Starting shutdown socket listener");
                try {
                    ServerSocket socket = new ServerSocket(fconfig.getSocketShutdownPort(), 0, InetAddress.getByName(fconfig.getSocketShutdownHost()));
                    while (true) {
                        logger.info("shutdown waiting for input");
                        Socket clientSocket = null;
                        try {
                            clientSocket = socket.accept();
                        } catch (Throwable t) {
                            logger.warn("Could not accept connection", t);
                            continue;
                        }
                        logger.info("request received");
                        // PrintWriter out =
                        // new PrintWriter(clientSocket.getOutputStream(), true);
                        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        logger.info("reading data");
                        String command = in.readLine();
                        logger.info("'" + command + "'");
                        if (command != null) {
                            command.trim();
                        }
                        logger.info("'" + command + "'");
                        if (fconfig.getSocketShutdownCommand().equalsIgnoreCase(command)) {
                            logger.info("Stopping threads");
                            GlobalEntries.getGlobalEntries().getConfigManager().clearThreads();
                            logger.info("Shutting down undertow");
                            undertow.stop();
                            if (myvd != null) {
                                try {
                                    myvd.shutdown();
                                } catch (Exception e) {
                                    logger.warn("Did not gracefullt stop directory service", e);
                                }
                            }
                            logger.info("Closing input stream");
                            try {
                                in.close();
                            } catch (Throwable t) {
                            }
                            /*try {
									out.close();
								} catch (Throwable t) {}*/
                            logger.info("Closing client socket");
                            try {
                                clientSocket.close();
                            } catch (Throwable t) {
                            }
                            logger.info("Closing server socket");
                            try {
                                socket.close();
                            } catch (Throwable t) {
                            }
                            logger.info("Sleeping for 10 seconds");
                            try {
                                Thread.sleep(10000);
                                logger.info("Exiting");
                                System.exit(0);
                                return;
                            } catch (Exception e) {
                            }
                        } else {
                            command = null;
                            logger.info("invalid command");
                            try {
                                in.close();
                            } catch (Throwable t) {
                            }
                            /*try {
									out.close();
								} catch (Throwable t) {}
*/
                            try {
                                clientSocket.close();
                            } catch (Throwable t) {
                            }
                        }
                    }
                } catch (IOException e) {
                    logger.error("Could not start shutdown listener", e);
                }
            }
        }.start();
    }
    undertow.start();
    if (config.getLdapPort() != 0 || config.getLdapsPort() != 0) {
        myvd = (MyVDWrapper) Class.forName("com.tremolosecurity.openunison.myvd.MyVDOnUndertow").newInstance();
        myvd.startMyVD(config, unisonConfiguration);
    }
}
Also used : ErrorPage(io.undertow.servlet.api.ErrorPage) TremoloType(com.tremolosecurity.config.xml.TremoloType) DeploymentManager(io.undertow.servlet.api.DeploymentManager) RedirectHandler(io.undertow.server.handlers.RedirectHandler) JspServletBuilder(io.undertow.jsp.JspServletBuilder) GsonBuilder(com.google.gson.GsonBuilder) Builder(io.undertow.Undertow.Builder) ArrayList(java.util.ArrayList) PathHandler(io.undertow.server.handlers.PathHandler) JAXBContext(javax.xml.bind.JAXBContext) Properties(java.util.Properties) HackInstanceManager(io.undertow.jsp.HackInstanceManager) JspPropertyGroup(org.apache.jasper.deploy.JspPropertyGroup) FileResourceManager(io.undertow.server.handlers.resource.FileResourceManager) Unmarshaller(javax.xml.bind.Unmarshaller) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) TagLibraryInfo(org.apache.jasper.deploy.TagLibraryInfo) InputStreamReader(java.io.InputStreamReader) QueueConfigType(com.tremolosecurity.config.xml.QueueConfigType) ServerSocket(java.net.ServerSocket) JAXBElement(javax.xml.bind.JAXBElement) IOException(java.io.IOException) Yaml(org.yaml.snakeyaml.Yaml) FileInputStream(java.io.FileInputStream) ParamType(com.tremolosecurity.config.xml.ParamType) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) JSONObject(org.json.simple.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) JSONObject(org.json.simple.JSONObject) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket)

Aggregations

ParamType (com.tremolosecurity.config.xml.ParamType)27 HashMap (java.util.HashMap)17 Attribute (com.tremolosecurity.saml.Attribute)14 IOException (java.io.IOException)12 LDAPAttribute (com.novell.ldap.LDAPAttribute)8 AuthMechParamType (com.tremolosecurity.config.xml.AuthMechParamType)7 DynamicPortalUrlsType (com.tremolosecurity.config.xml.DynamicPortalUrlsType)7 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)7 FileNotFoundException (java.io.FileNotFoundException)7 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 JAXBException (javax.xml.bind.JAXBException)7 JSONObject (org.json.simple.JSONObject)7 JSONArray (org.json.simple.JSONArray)6 ApplicationType (com.tremolosecurity.config.xml.ApplicationType)5 TrustType (com.tremolosecurity.config.xml.TrustType)5 ServletException (javax.servlet.ServletException)5 LDAPException (com.novell.ldap.LDAPException)4 HttpCon (com.tremolosecurity.provisioning.util.HttpCon)4 KeyStoreException (java.security.KeyStoreException)4 UnrecoverableKeyException (java.security.UnrecoverableKeyException)4