Search in sources :

Example 11 with ApplicationType

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

the class AppConfig method loadConfigData.

private void loadConfigData(HttpFilterConfig config) throws Exception {
    Attribute attr = config.getAttribute("applicationName");
    if (attr == null) {
        throw new Exception("Application name not set");
    }
    this.appConfig.applicationName = attr.getValues().get(0);
    ApplicationType app = null;
    for (ApplicationType at : config.getConfigManager().getCfg().getApplications().getApplication()) {
        if (at.getName().equalsIgnoreCase(this.appConfig.applicationName)) {
            app = at;
        }
    }
    if (app == null) {
        logger.warn(this.appConfig.applicationName + " not found");
        return;
    }
    this.appConfig.cookieName = app.getCookieConfig().getSessionCookieName();
    this.appConfig.secretKey = config.getConfigManager().getSecretKey(app.getCookieConfig().getKeyAlias());
    this.appConfig.timeoutSeconds = app.getCookieConfig().getTimeout();
    this.gson = new Gson();
}
Also used : ApplicationType(com.tremolosecurity.config.xml.ApplicationType) Attribute(com.tremolosecurity.saml.Attribute) Gson(com.google.gson.Gson)

Example 12 with ApplicationType

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

the class OpenUnisonUtils method exportIdPMetadata.

private static void exportIdPMetadata(Options options, CommandLine cmd, TremoloType tt, KeyStore ks) throws Exception, KeyStoreException, CertificateEncodingException, NoSuchAlgorithmException, UnrecoverableKeyException, SecurityException, MarshallingException, SignatureException {
    InitializationService.initialize();
    logger.info("Finding IdP...");
    String idpName = loadOption(cmd, "idpName", options);
    ApplicationType idp = null;
    for (ApplicationType app : tt.getApplications().getApplication()) {
        if (app.getName().equalsIgnoreCase(idpName)) {
            idp = app;
        }
    }
    if (idp == null) {
        throw new Exception("IdP '" + idpName + "' not found");
    }
    logger.info("Loading the base URL");
    String baseURL = loadOption(cmd, "urlBase", options);
    String url = baseURL + idp.getUrls().getUrl().get(0).getUri();
    SecureRandom random = new SecureRandom();
    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);
    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();
    EntityDescriptorBuilder edb = new EntityDescriptorBuilder();
    EntityDescriptor ed = edb.buildObject();
    ed.setID(id);
    ed.setEntityID(url);
    IDPSSODescriptorBuilder idpssdb = new IDPSSODescriptorBuilder();
    // ed.getSPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol");
    IDPSSODescriptor sd = idpssdb.buildObject();
    sd.addSupportedProtocol("urn:oasis:names:tc:SAML:2.0:protocol");
    ed.getRoleDescriptors().add(sd);
    HashMap<String, List<String>> params = new HashMap<String, List<String>>();
    for (ParamType pt : idp.getUrls().getUrl().get(0).getIdp().getParams()) {
        List<String> vals = params.get(pt.getName());
        if (vals == null) {
            vals = new ArrayList<String>();
            params.put(pt.getName(), vals);
        }
        vals.add(pt.getValue());
    }
    sd.setWantAuthnRequestsSigned(params.containsKey("requireSignedAuthn") && params.get("requireSignedAuthn").get(0).equalsIgnoreCase("true"));
    KeyDescriptorBuilder kdb = new KeyDescriptorBuilder();
    if (params.get("encKey") != null && !params.get("encKey").isEmpty() && (ks.getCertificate(params.get("encKey").get(0)) != null)) {
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.ENCRYPTION);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();
        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(Base64.encode(ks.getCertificate(params.get("encKey").get(0)).getEncoded()));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sd.getKeyDescriptors().add(kd);
    }
    if (params.get("sigKey") != null && !params.get("sigKey").isEmpty() && (ks.getCertificate(params.get("sigKey").get(0)) != null)) {
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.SIGNING);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();
        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(Base64.encode(ks.getCertificate(params.get("sigKey").get(0)).getEncoded()));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sd.getKeyDescriptors().add(kd);
    }
    HashSet<String> nameids = new HashSet<String>();
    for (TrustType trustType : idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust()) {
        for (ParamType pt : trustType.getParam()) {
            if (pt.getName().equalsIgnoreCase("nameIdMap")) {
                String val = pt.getValue().substring(0, pt.getValue().indexOf('='));
                if (!nameids.contains(val)) {
                    nameids.add(val);
                }
            }
        }
    }
    NameIDFormatBuilder nifb = new NameIDFormatBuilder();
    for (String nidf : nameids) {
        NameIDFormat nif = nifb.buildObject();
        nif.setFormat(nidf);
        sd.getNameIDFormats().add(nif);
    }
    SingleSignOnServiceBuilder ssosb = new SingleSignOnServiceBuilder();
    SingleSignOnService sso = ssosb.buildObject();
    sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    sso.setLocation(url + "/httpPost");
    sd.getSingleSignOnServices().add(sso);
    sso = ssosb.buildObject();
    sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
    sso.setLocation(url + "/httpRedirect");
    sd.getSingleSignOnServices().add(sso);
    String signingKey = loadOptional(cmd, "signMetadataWithKey", options);
    if (signingKey != null && ks.getCertificate(signingKey) != null) {
        BasicX509Credential signingCredential = new BasicX509Credential((X509Certificate) ks.getCertificate(signingKey), (PrivateKey) ks.getKey(signingKey, tt.getKeyStorePassword().toCharArray()));
        Signature signature = OpenSAMLUtils.buildSAMLObject(Signature.class);
        signature.setSigningCredential(signingCredential);
        signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
        signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        ed.setSignature(signature);
        try {
            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(ed).marshall(ed);
        } catch (MarshallingException e) {
            throw new RuntimeException(e);
        }
        Signer.signObject(signature);
    }
    // Get the Subject marshaller
    EntityDescriptorMarshaller marshaller = new EntityDescriptorMarshaller();
    // Marshall the Subject
    Element assertionElement = marshaller.marshall(ed);
    logger.info(net.shibboleth.utilities.java.support.xml.SerializeSupport.nodeToString(assertionElement));
}
Also used : IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) HashMap(java.util.HashMap) KeyInfoBuilder(org.opensaml.xmlsec.signature.impl.KeyInfoBuilder) KeyDescriptor(org.opensaml.saml.saml2.metadata.KeyDescriptor) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) SingleSignOnService(org.opensaml.saml.saml2.metadata.SingleSignOnService) NameIDFormatBuilder(org.opensaml.saml.saml2.metadata.impl.NameIDFormatBuilder) EntityDescriptorMarshaller(org.opensaml.saml.saml2.metadata.impl.EntityDescriptorMarshaller) X509Data(org.opensaml.xmlsec.signature.X509Data) SingleSignOnServiceBuilder(org.opensaml.saml.saml2.metadata.impl.SingleSignOnServiceBuilder) EntityDescriptorBuilder(org.opensaml.saml.saml2.metadata.impl.EntityDescriptorBuilder) X509DataBuilder(org.opensaml.xmlsec.signature.impl.X509DataBuilder) MarshallingException(org.opensaml.core.xml.io.MarshallingException) KeyInfo(org.opensaml.xmlsec.signature.KeyInfo) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) X509CertificateBuilder(org.opensaml.xmlsec.signature.impl.X509CertificateBuilder) SecureRandom(java.security.SecureRandom) TrustType(com.tremolosecurity.config.xml.TrustType) KeyStoreException(java.security.KeyStoreException) SignatureException(org.opensaml.xmlsec.signature.support.SignatureException) SecurityException(org.opensaml.security.SecurityException) UnmarshallingException(org.opensaml.core.xml.io.UnmarshallingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) MarshallingException(org.opensaml.core.xml.io.MarshallingException) IOException(java.io.IOException) Base64DecodingException(org.apache.xml.security.exceptions.Base64DecodingException) ServletException(javax.servlet.ServletException) PropertyException(javax.xml.bind.PropertyException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) AuthMechParamType(com.tremolosecurity.config.xml.AuthMechParamType) ParamType(com.tremolosecurity.config.xml.ParamType) ApplicationType(com.tremolosecurity.config.xml.ApplicationType) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) NameIDFormat(org.opensaml.saml.saml2.metadata.NameIDFormat) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) Signature(org.opensaml.xmlsec.signature.Signature) KeyDescriptorBuilder(org.opensaml.saml.saml2.metadata.impl.KeyDescriptorBuilder) IDPSSODescriptorBuilder(org.opensaml.saml.saml2.metadata.impl.IDPSSODescriptorBuilder)

Example 13 with ApplicationType

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

the class ConfigSys method doConfig.

/* (non-Javadoc)
	 * @see com.tremolosecurity.proxy.ConfigSys#doConfig(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, com.tremolosecurity.proxy.util.NextSys)
	 */
public void doConfig(HttpServletRequest req, HttpServletResponse resp, NextSys nextSys) throws IOException, ServletException {
    UrlHolder holder = null;
    AuthInfo userAuth = null;
    try {
        SessionManager sessionManager = (SessionManager) this.ctx.getAttribute(ProxyConstants.TREMOLO_SESSION_MANAGER);
        boolean setSessionCookie = false;
        boolean checkLogout = false;
        RequestHolder reqHolder = (RequestHolder) req.getAttribute(ProxyConstants.TREMOLO_REQ_HOLDER);
        holder = (UrlHolder) req.getAttribute(ProxyConstants.AUTOIDM_CFG);
        boolean isForcedAuth = req.getAttribute(ProxyConstants.TREMOLO_IS_FORCED_AUTH) != null ? (Boolean) req.getAttribute(ProxyConstants.TREMOLO_IS_FORCED_AUTH) : false;
        checkLogout = true;
        StringBuffer resetsb = new StringBuffer(cfg.getAuthPath()).append("resetChain");
        HttpSession sharedSession = req.getSession();
        if (sharedSession != null) {
            AuthController actl = (AuthController) sharedSession.getAttribute(ProxyConstants.AUTH_CTL);
            if (actl != null && actl.getHolder() != null) {
                RequestHolder presentHolder = actl.getHolder();
                AuthInfo authdata = actl.getAuthInfo();
                userAuth = authdata;
                if (!req.getRequestURI().startsWith(cfg.getAuthPath()) && /*&&  ! presentHolder.getUrlNoQueryString().equalsIgnoreCase(req.getRequestURL().toString())*/
                (authdata == null || !authdata.isAuthComplete())) {
                    // we're going to ignore requests for favicon.ico
                    if (!req.getRequestURI().endsWith("/favicon.ico") && !req.getRequestURI().endsWith("/apple-touch-icon-precomposed.png") && !req.getRequestURI().endsWith("/apple-touch-icon.png")) {
                        sharedSession.removeAttribute(ProxyConstants.AUTH_CTL);
                        this.cfg.createAnonUser(sharedSession);
                    }
                } else if (req.getRequestURI().equalsIgnoreCase(resetsb.toString())) {
                    sharedSession.removeAttribute("TREMOLO_AUTH_URI");
                    for (AuthStep step : actl.getAuthSteps()) {
                        step.setExecuted(false);
                        step.setSuccess(false);
                    }
                    actl.setCurrentStep(actl.getAuthSteps().get(0));
                    String chainName = holder.getUrl().getAuthChain();
                    AuthChainType chain = cfg.getAuthChains().get(chainName);
                    String mech = chain.getAuthMech().get(0).getName();
                    String uri = cfg.getAuthMechs().get(mech).getUri();
                    holder.getConfig().getAuthManager().loadAmtParams(sharedSession, chain.getAuthMech().get(0));
                    String redirectURI = "";
                    if (holder.getConfig().getContextPath().equalsIgnoreCase("/")) {
                        redirectURI = uri;
                    } else {
                        redirectURI = new StringBuffer().append(holder.getConfig().getContextPath()).append(uri).toString();
                    }
                    sharedSession.setAttribute("TREMOLO_AUTH_URI", redirectURI);
                    resp.sendRedirect(redirectURI);
                    return;
                }
            }
            if (isForcedAuth) {
                actl.setHolder(reqHolder);
                String authChain = holder.getUrl().getAuthChain();
                AuthChainType act = cfg.getAuthChains().get(authChain);
                holder.getConfig().getAuthManager().loadAmtParams(sharedSession, act.getAuthMech().get(0));
            }
        }
        if (holder == null) {
            if (req.getRequestURI().startsWith(cfg.getAuthPath())) {
                req.setAttribute(ProxyConstants.AUTOIDM_MYVD, cfg.getMyVD());
                ProxyResponse presp = new ProxyResponse((HttpServletResponse) resp, (HttpServletRequest) req);
                // we still need a holder
                /*AuthController actl = (AuthController) sharedSession.getAttribute(AuthSys.AUTH_CTL);
						if (actl != null) {
							holder = cfg.findURL(actl.getHolder().getUrlNoQueryString());
							req.setAttribute(ConfigSys.AUTOIDM_CFG, holder);
						} else {*/
                AuthMechanism authMech = cfg.getAuthMech(((HttpServletRequest) req).getRequestURI());
                if (authMech != null) {
                    String finalURL = authMech.getFinalURL(req, resp);
                    if (finalURL != null) {
                        holder = cfg.findURL(finalURL);
                    } else {
                    // throw new ServletException("Can not generate holder");
                    }
                } else {
                // throw new ServletException("Can not generate holder");
                }
                // no holder should be needed beyond this point
                // }
                /*
						
						
								String urlChain = holder.getUrl().getAuthChain();
								AuthChainType act = holder.getConfig().getAuthChains().get(urlChain);
								
								HashMap<String,Attribute> params = new HashMap<String,Attribute>();
								ProxyUtil.loadParams(req, params);
								reqHolder = new RequestHolder(HTTPMethod.GET,params,finalURL,true,act.getName());
								
								isForcedAuth = true;
								req.setAttribute(ConfigSys.AUTOIDM_CFG, holder);
								
								String chainName = holder.getUrl().getAuthChain();
								AuthChainType chain = cfg.getAuthChains().get(chainName);
								String mech = chain.getAuthMech().get(0).getName();
								String uri = cfg.getAuthMechs().get(mech).getUri();
								
								AuthSys.loadAmtParams(sharedSession, chain.getAuthMech().get(0));
							}
						} 
							
						
						if (holder == null) {
							resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
							AccessLog.log(AccessEvent.NotFound, null, req, null, "Resource Not Found");
							return;
						}*/
                nextSys.nextSys(req, presp);
                presp.pushHeadersAndCookies(null);
            } else {
                String redirectLocation = cfg.getErrorPages().get(HttpServletResponse.SC_NOT_FOUND);
                if (redirectLocation != null) {
                    resp.sendRedirect(redirectLocation);
                } else {
                    resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
                }
                AccessLog.log(AccessEvent.NotFound, null, req, null, "Resource Not Found");
            }
        } else {
            req.setAttribute(ProxyConstants.AUTOIDM_CFG, holder);
            req.setAttribute(ProxyConstants.AUTOIDM_MYVD, cfg.getMyVD());
            ProxyResponse presp = new ProxyResponse((HttpServletResponse) resp, (HttpServletRequest) req);
            ProxyData pd = null;
            try {
                nextSys.nextSys(req, presp);
                pd = (ProxyData) req.getAttribute(ProxyConstants.TREMOLO_PRXY_DATA);
                if (holder.getApp().getCookieConfig() != null) {
                    String logouturi = holder.getApp().getCookieConfig().getLogoutURI();
                    AuthController actl = (AuthController) sharedSession.getAttribute(ProxyConstants.AUTH_CTL);
                    if (actl != null) {
                        AuthInfo authdata = actl.getAuthInfo();
                        userAuth = authdata;
                        if ((req.getRequestURI().equalsIgnoreCase(logouturi) || (pd != null && pd.isLogout())) && (authdata != null)) {
                            // Execute logout handlers
                            ArrayList<LogoutHandler> logoutHandlers = (ArrayList<LogoutHandler>) sharedSession.getAttribute(LogoutUtil.LOGOUT_HANDLERS);
                            if (logoutHandlers != null) {
                                for (LogoutHandler h : logoutHandlers) {
                                    h.handleLogout(req, presp);
                                }
                            }
                            sessionManager.clearSession(holder, sharedSession, (HttpServletRequest) req, (HttpServletResponse) resp);
                        }
                    }
                }
                presp.pushHeadersAndCookies(holder);
                if (pd != null && pd.getIns() != null) {
                    if (pd.getResponse() == null) {
                        this.procData(pd.getRequest(), resp, holder, pd.isText(), pd.getIns(), sessionManager);
                    } else {
                        this.procData(pd.getRequest(), pd.getResponse(), holder, pd.isText(), pd.getIns(), pd.getPostProc(), sessionManager);
                    }
                }
            } finally {
                if (pd != null && pd.getHttpRequestBase() != null) {
                    pd.getHttpRequestBase().releaseConnection();
                    if (!resp.isCommitted()) {
                        resp.getOutputStream().flush();
                        resp.getOutputStream().close();
                    }
                }
            }
        }
    } catch (Exception e) {
        ApplicationType appType = null;
        if (holder != null) {
            appType = holder.getApp();
        } else {
            appType = new ApplicationType();
            appType.setName("UNKNOWN");
        }
        AccessLog.log(AccessEvent.Error, appType, (HttpServletRequest) req, userAuth, "NONE");
        req.setAttribute("TREMOLO_ERROR_REQUEST_URL", req.getRequestURL().toString());
        req.setAttribute("TREMOLO_ERROR_EXCEPTION", e);
        logger.error("Could not process request", e);
        String redirectLocation = cfg.getErrorPages().get(500);
        if (redirectLocation != null) {
            resp.sendRedirect(redirectLocation);
        } else {
            StringBuffer b = new StringBuffer();
            b.append(cfg.getAuthFormsPath()).append("error.jsp");
            resp.setStatus(500);
            req.getRequestDispatcher(b.toString()).forward(req, resp);
        }
    }
}
Also used : AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) HttpSession(javax.servlet.http.HttpSession) ArrayList(java.util.ArrayList) RequestHolder(com.tremolosecurity.proxy.auth.RequestHolder) AuthStep(com.tremolosecurity.proxy.auth.util.AuthStep) AuthController(com.tremolosecurity.proxy.auth.AuthController) ServletException(javax.servlet.ServletException) SocketException(java.net.SocketException) IOException(java.io.IOException) ConnectionClosedException(org.apache.http.ConnectionClosedException) UrlHolder(com.tremolosecurity.config.util.UrlHolder) HttpServletRequest(javax.servlet.http.HttpServletRequest) ApplicationType(com.tremolosecurity.config.xml.ApplicationType) AuthMechanism(com.tremolosecurity.proxy.auth.AuthMechanism) LogoutHandler(com.tremolosecurity.proxy.logout.LogoutHandler) AuthChainType(com.tremolosecurity.config.xml.AuthChainType)

Example 14 with ApplicationType

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

the class UnisonConfigManagerImpl method initialize.

/* (non-Javadoc)
	 * @see com.tremolosecurity.config.util.ConfigManager#initialize()
	 */
/* (non-Javadoc)
	 * @see com.tremolosecurity.config.util.UnisonConfigManager#initialize()
	 */
@Override
public void initialize(String name) throws JAXBException, Exception, IOException, FileNotFoundException, InstantiationException, IllegalAccessException, ClassNotFoundException, LDAPException, KeyStoreException, NoSuchAlgorithmException, CertificateException, ProvisioningException {
    JAXBContext jc = JAXBContext.newInstance("com.tremolosecurity.config.xml");
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    String path = configXML;
    this.threads = new ArrayList<StopableThread>();
    // path = path.substring(path.lastIndexOf('/') - 1);
    // path = path.substring(path.lastIndexOf('/') - 1);
    path = path.substring(0, path.lastIndexOf('/'));
    JAXBElement<TremoloType> autoidmcfg = this.loadUnisonConfiguration(unmarshaller);
    this.cfg = autoidmcfg.getValue();
    this.byHost = new HashMap<String, ArrayList<UrlHolder>>();
    this.cache = new HashMap<String, UrlHolder>();
    this.upgradeManager = (HttpUpgradeRequestManager) Class.forName(this.cfg.getUpgradeHandler()).newInstance();
    String myVdPath = cfg.getMyvdConfig();
    this.loadKeystore(path, myVdPath);
    this.initSSL();
    this.loadMyVD(path, myVdPath);
    if (cfg.getApplications().getErrorPage() != null) {
        for (ErrorPage ep : cfg.getApplications().getErrorPage()) {
            this.errorPages.put(ep.getCode(), ep.getLocation());
        }
    }
    this.customAzRules = new HashMap<String, CustomAuthorization>();
    if (this.cfg.getCustomAzRules() != null) {
        for (CustomAzRuleType azrule : this.cfg.getCustomAzRules().getAzRule()) {
            createCustomAuthorizationRule(azrule);
        }
    }
    loadApplicationObjects();
    this.authChains = new HashMap<String, AuthChainType>();
    if (cfg.getAuthChains() != null) {
        Iterator<AuthChainType> itac = cfg.getAuthChains().getChain().iterator();
        while (itac.hasNext()) {
            AuthChainType ac = itac.next();
            this.authChains.put(ac.getName(), ac);
        }
    }
    this.authMechs = new HashMap<String, MechanismType>();
    if (cfg.getAuthMechs() != null) {
        Iterator<MechanismType> itmt = cfg.getAuthMechs().getMechanism().iterator();
        while (itmt.hasNext()) {
            MechanismType mt = itmt.next();
            authMechs.put(mt.getName(), mt);
        }
    }
    this.resGroups = new HashMap<String, ResultGroupType>();
    if (cfg.getResultGroups() != null) {
        Iterator<ResultGroupType> itrgt = cfg.getResultGroups().getResultGroup().iterator();
        while (itrgt.hasNext()) {
            ResultGroupType rgt = itrgt.next();
            this.resGroups.put(rgt.getName(), rgt);
        }
    }
    this.apps = new HashMap<String, ApplicationType>();
    Iterator<ApplicationType> itApp = cfg.getApplications().getApplication().iterator();
    while (itApp.hasNext()) {
        ApplicationType app = itApp.next();
        this.apps.put(app.getName(), app);
    }
    this.provEnvgine = new ProvisioningEngineImpl(this);
    this.provEnvgine.initWorkFlows();
    this.provEnvgine.initMessageConsumers();
    this.provEnvgine.initScheduler();
    this.provEnvgine.initListeners();
    this.provEnvgine.initReports();
    try {
        if (this.getCfg().getResultGroups() != null && this.getCfg().getResultGroups().getDynamicResultGroups() != null && this.getCfg().getResultGroups().getDynamicResultGroups().isEnabled()) {
            DynamicPortalUrlsType dynamicResultGroups = this.getCfg().getResultGroups().getDynamicResultGroups();
            String className = dynamicResultGroups.getClassName();
            HashMap<String, Attribute> cfgAttrs = new HashMap<String, Attribute>();
            for (ParamType pt : dynamicResultGroups.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());
            }
            DynamicResultGroups dynResGroups = (DynamicResultGroups) Class.forName(className).newInstance();
            dynResGroups.loadDynamicResultGroups(this, this.getProvisioningEngine(), cfgAttrs);
        }
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
        throw new ProvisioningException("Could not initialize dynamic targets", e);
    }
    try {
        if (this.getCfg().getCustomAzRules() != null && this.getCfg().getCustomAzRules().getDynamicCustomAuthorizations() != null && this.getCfg().getCustomAzRules().getDynamicCustomAuthorizations().isEnabled()) {
            DynamicPortalUrlsType dynamicCustomAuthorization = this.getCfg().getCustomAzRules().getDynamicCustomAuthorizations();
            String className = dynamicCustomAuthorization.getClassName();
            HashMap<String, Attribute> cfgAttrs = new HashMap<String, Attribute>();
            for (ParamType pt : dynamicCustomAuthorization.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());
            }
            DynamicAuthorizations dynCustomAz = (DynamicAuthorizations) Class.forName(className).newInstance();
            dynCustomAz.loadDynamicAuthorizations(this, this.getProvisioningEngine(), cfgAttrs);
        }
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
        throw new ProvisioningException("Could not initialize dynamic targets", e);
    }
    try {
        if (this.getCfg().getAuthChains() != null && this.getCfg().getAuthChains().getDynamicAuthChains() != null && this.getCfg().getAuthChains().getDynamicAuthChains().isEnabled()) {
            DynamicPortalUrlsType dynamicAuthChains = this.getCfg().getAuthChains().getDynamicAuthChains();
            String className = dynamicAuthChains.getClassName();
            HashMap<String, Attribute> cfgAttrs = new HashMap<String, Attribute>();
            for (ParamType pt : dynamicAuthChains.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());
            }
            DynamicAuthChains dynAuthChains = (DynamicAuthChains) Class.forName(className).newInstance();
            dynAuthChains.loadDynamicAuthChains(this, provEnvgine, cfgAttrs);
        }
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
        throw new ProvisioningException("Could not initialize dynamic targets", e);
    }
    try {
        if (this.getCfg().getApplications() != null && this.getCfg().getApplications().getDynamicApplications() != null && this.getCfg().getApplications().getDynamicApplications().isEnabled()) {
            DynamicPortalUrlsType dynamicApps = this.getCfg().getApplications().getDynamicApplications();
            String className = dynamicApps.getClassName();
            HashMap<String, Attribute> cfgAttrs = new HashMap<String, Attribute>();
            for (ParamType pt : dynamicApps.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());
            }
            DynamicApplications dynApps = (DynamicApplications) Class.forName(className).newInstance();
            dynApps.loadDynamicApplications(this, provEnvgine, cfgAttrs);
        }
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
        throw new ProvisioningException("Could not initialize dynamic targets", e);
    }
    this.postInitialize();
}
Also used : ErrorPage(com.tremolosecurity.config.xml.ApplicationsType.ErrorPage) TremoloType(com.tremolosecurity.config.xml.TremoloType) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JAXBContext(javax.xml.bind.JAXBContext) DynamicApplications(com.tremolosecurity.proxy.dynamicloaders.DynamicApplications) ProvisioningEngineImpl(com.tremolosecurity.provisioning.core.ProvisioningEngineImpl) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) StopableThread(com.tremolosecurity.server.StopableThread) CustomAzRuleType(com.tremolosecurity.config.xml.CustomAzRuleType) MechanismType(com.tremolosecurity.config.xml.MechanismType) Unmarshaller(javax.xml.bind.Unmarshaller) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) DynamicAuthChains(com.tremolosecurity.proxy.dynamicloaders.DynamicAuthChains) CustomAuthorization(com.tremolosecurity.proxy.az.CustomAuthorization) AuthMechParamType(com.tremolosecurity.config.xml.AuthMechParamType) ParamType(com.tremolosecurity.config.xml.ParamType) DynamicAuthorizations(com.tremolosecurity.proxy.dynamicloaders.DynamicAuthorizations) ApplicationType(com.tremolosecurity.config.xml.ApplicationType) DynamicResultGroups(com.tremolosecurity.proxy.dynamicloaders.DynamicResultGroups) DynamicPortalUrlsType(com.tremolosecurity.config.xml.DynamicPortalUrlsType) ResultGroupType(com.tremolosecurity.config.xml.ResultGroupType)

Example 15 with ApplicationType

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

the class LoadApplicationsFromK8s method createApplication.

public ApplicationType createApplication(JSONObject item, String name) throws Exception {
    ApplicationType app = new ApplicationType();
    app.setName(name);
    JSONObject spec = (JSONObject) item.get("spec");
    app.setAzTimeoutMillis(getLongValue(spec.get("azTimeoutMillis"), 3000));
    app.setIsApp(getBoolValue(spec.get("isApp"), true));
    JSONArray urls = (JSONArray) spec.get("urls");
    app.setUrls(new UrlsType());
    for (Object o : urls) {
        JSONObject jsonUrl = (JSONObject) o;
        UrlType url = new UrlType();
        if (!app.isIsApp()) {
            createIdpOnUrl(jsonUrl, url);
        }
        JSONArray hosts = (JSONArray) jsonUrl.get("hosts");
        for (Object x : hosts) {
            url.getHost().add((String) x);
        }
        JSONArray filters = (JSONArray) jsonUrl.get("filterChain");
        url.setFilterChain(new FilterChainType());
        if (filters != null) {
            for (Object x : filters) {
                JSONObject jsonFilter = (JSONObject) x;
                FilterConfigType ft = new FilterConfigType();
                ft.setClazz((String) jsonFilter.get("className"));
                JSONObject params = (JSONObject) jsonFilter.get("params");
                if (params != null) {
                    for (Object y : params.keySet()) {
                        String paramName = (String) y;
                        Object z = params.get(paramName);
                        if (z instanceof String) {
                            ParamWithValueType pt = new ParamWithValueType();
                            pt.setName(paramName);
                            pt.setValue((String) z);
                            ft.getParam().add(pt);
                        } else {
                            JSONArray values = (JSONArray) z;
                            for (Object w : values) {
                                ParamWithValueType pt = new ParamWithValueType();
                                pt.setName(paramName);
                                pt.setValue((String) w);
                                ft.getParam().add(pt);
                            }
                        }
                    }
                }
                JSONArray secretParams = (JSONArray) jsonFilter.get("secretParams");
                if (secretParams != null) {
                    HttpCon nonwatchHttp = this.k8sWatch.getK8s().createClient();
                    String token = this.k8sWatch.getK8s().getAuthToken();
                    try {
                        for (Object ox : secretParams) {
                            JSONObject secretParam = (JSONObject) ox;
                            String paramName = (String) secretParam.get("name");
                            String secretName = (String) secretParam.get("secretName");
                            String secretKey = (String) secretParam.get("secretKey");
                            String secretValue = this.k8sWatch.getSecretValue(secretName, secretKey, token, nonwatchHttp);
                            ParamWithValueType pt = new ParamWithValueType();
                            pt.setName(paramName);
                            pt.setValue(secretValue);
                            pt.setValueAttribute(secretValue);
                            ft.getParam().add(pt);
                        }
                    } finally {
                        nonwatchHttp.getHttp().close();
                        nonwatchHttp.getBcm().close();
                    }
                }
                url.getFilterChain().getFilter().add(ft);
            }
        }
        JSONArray jsonAzRules = (JSONArray) jsonUrl.get("azRules");
        AzRulesType art = new AzRulesType();
        if (jsonAzRules != null) {
            for (Object x : jsonAzRules) {
                JSONObject jsonRule = (JSONObject) x;
                AzRuleType artx = new AzRuleType();
                artx.setScope((String) jsonRule.get("scope"));
                artx.setConstraint((String) jsonRule.get("constraint"));
                art.getRule().add(artx);
            }
        }
        url.setAzRules(art);
        url.setProxyTo((String) jsonUrl.get("proxyTo"));
        url.setUri((String) jsonUrl.get("uri"));
        url.setRegex(getBoolValue(jsonUrl.get("regex"), false));
        url.setAuthChain((String) jsonUrl.get("authChain"));
        url.setOverrideHost(getBoolValue(jsonUrl.get("overrideHost"), false));
        url.setOverrideReferer(getBoolValue(jsonUrl.get("overrideReferer"), false));
        JSONObject jsonResults = (JSONObject) jsonUrl.get("results");
        if (jsonResults != null) {
            ResultRefType rt = new ResultRefType();
            rt.setAuSuccess((String) jsonResults.get("auSuccess"));
            rt.setAzSuccess((String) jsonResults.get("azSuccess"));
            rt.setAuFail((String) jsonResults.get("auFail"));
            rt.setAzFail((String) jsonResults.get("azFail"));
            url.setResults(rt);
        }
        app.getUrls().getUrl().add(url);
    }
    JSONObject jsonCookie = (JSONObject) spec.get("cookieConfig");
    if (jsonCookie != null) {
        CookieConfigType cct = new CookieConfigType();
        cct.setSessionCookieName((String) jsonCookie.get("sessionCookieName"));
        cct.setDomain((String) jsonCookie.get("domain"));
        cct.setScope(getIntValue(jsonCookie.get("scope"), -1));
        cct.setLogoutURI((String) jsonCookie.get("logoutURI"));
        cct.setKeyAlias((String) jsonCookie.get("keyAlias"));
        cct.setTimeout(getIntValue(jsonCookie.get("timeout"), 0).intValue());
        cct.setSecure(getBoolValue(jsonCookie.get("secure"), false));
        cct.setHttpOnly(getBoolValue(jsonCookie.get("httpOnly"), false));
        cct.setSameSite((String) jsonCookie.get("sameSite"));
        cct.setCookiesEnabled(getBoolValue(jsonCookie.get("cookiesEnabled"), true));
        app.setCookieConfig(cct);
    }
    return app;
}
Also used : AzRulesType(com.tremolosecurity.config.xml.AzRulesType) JSONArray(org.json.simple.JSONArray) UrlsType(com.tremolosecurity.config.xml.UrlsType) FilterChainType(com.tremolosecurity.config.xml.FilterChainType) ResultRefType(com.tremolosecurity.config.xml.ResultRefType) ApplicationType(com.tremolosecurity.config.xml.ApplicationType) CustomAzRuleType(com.tremolosecurity.config.xml.CustomAzRuleType) AzRuleType(com.tremolosecurity.config.xml.AzRuleType) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) FilterConfigType(com.tremolosecurity.config.xml.FilterConfigType) CookieConfigType(com.tremolosecurity.config.xml.CookieConfigType) JSONObject(org.json.simple.JSONObject) ParamWithValueType(com.tremolosecurity.config.xml.ParamWithValueType) UrlType(com.tremolosecurity.config.xml.UrlType)

Aggregations

ApplicationType (com.tremolosecurity.config.xml.ApplicationType)16 IOException (java.io.IOException)6 ParamType (com.tremolosecurity.config.xml.ParamType)5 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)4 Attribute (com.tremolosecurity.saml.Attribute)4 ServletException (javax.servlet.ServletException)4 AuthMechParamType (com.tremolosecurity.config.xml.AuthMechParamType)3 FilterConfigType (com.tremolosecurity.config.xml.FilterConfigType)3 ParamWithValueType (com.tremolosecurity.config.xml.ParamWithValueType)3 TrustType (com.tremolosecurity.config.xml.TrustType)3 UrlType (com.tremolosecurity.config.xml.UrlType)3 LDAPAttribute (com.novell.ldap.LDAPAttribute)2 LDAPException (com.novell.ldap.LDAPException)2 AuthChainType (com.tremolosecurity.config.xml.AuthChainType)2 CustomAzRuleType (com.tremolosecurity.config.xml.CustomAzRuleType)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 DateTime (org.joda.time.DateTime)2