Search in sources :

Example 31 with UrlHolder

use of com.tremolosecurity.config.util.UrlHolder in project OpenUnison by TremoloSecurity.

the class BasicAuth method checkBasicAuth.

public static boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response, ConfigManager cfgMgr, BasicAuthImpl authImpl, AuthStep as) throws IOException, ServletException {
    String basicHdr = request.getHeader("Authorization");
    HttpSession session = ((HttpServletRequest) request).getSession();
    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
    String realmName = authParams.get("realmName").getValues().get(0);
    String uidAttr = "uid";
    if (authParams.get("uidAttr") != null) {
        uidAttr = authParams.get("uidAttr").getValues().get(0);
    }
    if (basicHdr == null) {
        as.setExecuted(false);
        sendFail(response, realmName);
        return false;
    }
    basicHdr = basicHdr.substring(basicHdr.indexOf(' ') + 1);
    String headerVal = new String(Base64.decode(basicHdr));
    String userName = headerVal.substring(0, headerVal.indexOf(':'));
    String password = headerVal.substring(headerVal.indexOf(':') + 1);
    MyVDConnection myvd = cfgMgr.getMyVD();
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(urlChain);
    AuthMechType amt = act.getAuthMech().get(as.getId());
    try {
        authImpl.doAuth(request, session, uidAttr, userName, password, myvd, act, amt, as, cfgMgr);
    } catch (LDAPException e) {
        if (e.getResultCode() != LDAPException.INVALID_CREDENTIALS) {
            logger.error("Could not authenticate user", e);
        }
        as.setExecuted(true);
        as.setSuccess(false);
        sendFail(response, realmName);
        return false;
    /*if (amt.getRequired().equals("required")) {
				session.setAttribute(AuthSys.AUTH_RES, false);
			}*/
    }
    return true;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) UrlHolder(com.tremolosecurity.config.util.UrlHolder) LDAPException(com.novell.ldap.LDAPException) LDAPAttribute(com.novell.ldap.LDAPAttribute) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) MyVDConnection(com.tremolosecurity.proxy.myvd.MyVDConnection)

Example 32 with UrlHolder

use of com.tremolosecurity.config.util.UrlHolder in project OpenUnison by TremoloSecurity.

the class ScaleJSOperator method doFilter.

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
    Gson gson = new Gson();
    request.getServletRequest().setAttribute("com.tremolosecurity.unison.proxy.noRedirectOnError", "com.tremolosecurity.unison.proxy.noRedirectOnError");
    try {
        if (request.getRequestURI().endsWith("/ops/config")) {
            ScaleJSUtils.addCacheHeaders(response);
            response.setContentType("application/json");
            response.getWriter().println(gson.toJson(this.config).trim());
        } else if (request.getRequestURI().endsWith("/ops/search")) {
            runSearch(request, response, gson);
        } else if (request.getRequestURI().endsWith("/ops/user") && request.getMethod().equalsIgnoreCase("GET")) {
            lookupUser(request, response, gson);
        } else if (request.getRequestURI().endsWith("/ops/user") && request.getMethod().equalsIgnoreCase("POST")) {
            AuthInfo loggedIn = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
            String json = new String((byte[]) request.getAttribute(ProxySys.MSG_BODY));
            OpsUpdate updateInput = gson.fromJson(json, OpsUpdate.class);
            if (this.scaleMainConfig == null) {
                UrlHolder holder = GlobalEntries.getGlobalEntries().getConfigManager().findURL(this.scaleMainURL);
                for (HttpFilter filter : holder.getFilterChain()) {
                    if (filter instanceof ScaleMain) {
                        ScaleMain scaleMain = (ScaleMain) filter;
                        this.scaleMainConfig = scaleMain.scaleConfig;
                    }
                }
            }
            String dn = updateInput.getDn();
            LDAPSearchResults res = GlobalEntries.getGlobalEntries().getConfigManager().getMyVD().search(dn, 0, "(objectClass=*)", new ArrayList<String>());
            if (!res.hasMore()) {
                throw new Exception("Could not locate user '" + dn + "'");
            }
            LDAPEntry entry = res.next();
            AuthInfo userData = new AuthInfo();
            userData.setUserDN(entry.getDN());
            LDAPAttributeSet attrs = entry.getAttributeSet();
            for (Object obj : attrs) {
                LDAPAttribute attr = (LDAPAttribute) obj;
                Attribute attrib = new Attribute(attr.getName());
                String[] vals = attr.getStringValueArray();
                for (String val : vals) {
                    attrib.getValues().add(val);
                }
                userData.getAttribs().put(attrib.getName(), attrib);
            }
            ScaleError errors = new ScaleError();
            Set<String> allowedAttrs = null;
            if (this.scaleMainConfig.getUiDecisions() != null) {
                allowedAttrs = this.scaleMainConfig.getUiDecisions().availableAttributes(userData, request.getServletRequest());
            }
            HashMap<String, String> values = new HashMap<String, String>();
            boolean ok = true;
            for (Attribute attr : updateInput.getAttributes()) {
                String attributeName = attr.getName();
                if (allowedAttrs == null || allowedAttrs.contains(attributeName)) {
                    String value = attr.getValues().get(0);
                    if (this.scaleMainConfig.getAttributes().get(attributeName) == null) {
                        errors.getErrors().add("Invalid attribute : '" + attributeName + "'");
                        ok = false;
                    } else if (this.scaleMainConfig.getAttributes().get(attributeName).isReadOnly()) {
                        errors.getErrors().add("Attribute is read only : '" + this.scaleMainConfig.getAttributes().get(attributeName).getDisplayName() + "'");
                        ok = false;
                    } else if (this.scaleMainConfig.getAttributes().get(attributeName).isRequired() && value.length() == 0) {
                        errors.getErrors().add("Attribute is required : '" + this.scaleMainConfig.getAttributes().get(attributeName).getDisplayName() + "'");
                        ok = false;
                    } else if (this.scaleMainConfig.getAttributes().get(attributeName).getMinChars() > 0 && this.scaleMainConfig.getAttributes().get(attributeName).getMinChars() > value.length()) {
                        errors.getErrors().add(this.scaleMainConfig.getAttributes().get(attributeName).getDisplayName() + " must have at least " + this.scaleMainConfig.getAttributes().get(attributeName).getMinChars() + " characters");
                        ok = false;
                    } else if (this.scaleMainConfig.getAttributes().get(attributeName).getMaxChars() > 0 && this.scaleMainConfig.getAttributes().get(attributeName).getMaxChars() < value.length()) {
                        errors.getErrors().add(this.scaleMainConfig.getAttributes().get(attributeName).getDisplayName() + " must have at most " + this.scaleMainConfig.getAttributes().get(attributeName).getMaxChars() + " characters");
                        ok = false;
                    } else if (this.scaleMainConfig.getAttributes().get(attributeName).getPattern() != null) {
                        try {
                            Matcher m = this.scaleMainConfig.getAttributes().get(attributeName).getPattern().matcher(value);
                            if (m == null || !m.matches()) {
                                ok = false;
                            }
                        } catch (Exception e) {
                            ok = false;
                        }
                        if (!ok) {
                            errors.getErrors().add("Attribute value not valid : '" + this.scaleMainConfig.getAttributes().get(attributeName).getDisplayName() + "' - " + this.scaleMainConfig.getAttributes().get(attributeName).getRegExFailedMsg());
                        }
                    }
                    values.put(attributeName, value);
                }
            }
            for (String attrName : this.scaleMainConfig.getAttributes().keySet()) {
                if (this.scaleMainConfig.getAttributes().get(attrName).isRequired() && !values.containsKey(attrName) && (allowedAttrs == null || allowedAttrs.contains(attrName))) {
                    errors.getErrors().add("Attribute is required : '" + this.scaleMainConfig.getAttributes().get(attrName).getDisplayName() + "'");
                    ok = false;
                }
            }
            if (updateInput.getReason() == null || updateInput.getReason().trim().isEmpty()) {
                errors.getErrors().add("Reason For Updates Required");
                ok = false;
            }
            if (ok) {
                ConfigManager cfgMgr = GlobalEntries.getGlobalEntries().getConfigManager();
                WFCall wfCall = new WFCall();
                wfCall.setName(this.scaleMainConfig.getWorkflowName());
                wfCall.setReason(updateInput.getReason());
                wfCall.setUidAttributeName(this.scaleMainConfig.getUidAttributeName());
                wfCall.setRequestor(loggedIn.getAttribs().get(this.scaleMainConfig.getUidAttributeName()).getValues().get(0));
                TremoloUser tu = new TremoloUser();
                tu.setUid(userData.getAttribs().get(this.scaleMainConfig.getUidAttributeName()).getValues().get(0));
                for (String name : values.keySet()) {
                    tu.getAttributes().add(new Attribute(name, values.get(name)));
                }
                tu.getAttributes().add(new Attribute(this.scaleMainConfig.getUidAttributeName(), userData.getAttribs().get(this.scaleMainConfig.getUidAttributeName()).getValues().get(0)));
                wfCall.setUser(tu);
                try {
                    com.tremolosecurity.provisioning.workflow.ExecuteWorkflow exec = new com.tremolosecurity.provisioning.workflow.ExecuteWorkflow();
                    exec.execute(wfCall, GlobalEntries.getGlobalEntries().getConfigManager());
                } catch (Exception e) {
                    logger.error("Could not update user", e);
                    response.setStatus(500);
                    ScaleError error = new ScaleError();
                    error.getErrors().add("Please contact your system administrator");
                    ScaleJSUtils.addCacheHeaders(response);
                    response.getWriter().print(gson.toJson(error).trim());
                    response.getWriter().flush();
                }
            } else {
                response.setStatus(500);
                ScaleJSUtils.addCacheHeaders(response);
                response.getWriter().print(gson.toJson(errors).trim());
                response.getWriter().flush();
            }
        }
    } catch (Throwable t) {
        logger.error("Could not execute request", t);
        response.setStatus(500);
        ScaleError error = new ScaleError();
        error.getErrors().add("Operation not supported");
        ScaleJSUtils.addCacheHeaders(response);
        response.getWriter().print(gson.toJson(error).trim());
        response.getWriter().flush();
    }
}
Also used : LDAPAttributeSet(com.novell.ldap.LDAPAttributeSet) Set(java.util.Set) LDAPAttribute(com.novell.ldap.LDAPAttribute) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) OpsUpdate(com.tremolosecurity.scalejs.operators.data.OpsUpdate) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) UrlHolder(com.tremolosecurity.config.util.UrlHolder) LDAPEntry(com.novell.ldap.LDAPEntry) TremoloUser(com.tremolosecurity.provisioning.service.util.TremoloUser) HttpFilter(com.tremolosecurity.proxy.filter.HttpFilter) LDAPAttribute(com.novell.ldap.LDAPAttribute) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) WFCall(com.tremolosecurity.provisioning.service.util.WFCall) LDAPAttributeSet(com.novell.ldap.LDAPAttributeSet) ScaleError(com.tremolosecurity.scalejs.data.ScaleError) LDAPException(com.novell.ldap.LDAPException) IOException(java.io.IOException) ConfigManager(com.tremolosecurity.config.util.ConfigManager) LDAPSearchResults(com.novell.ldap.LDAPSearchResults) ScaleMain(com.tremolosecurity.scalejs.ws.ScaleMain)

Example 33 with UrlHolder

use of com.tremolosecurity.config.util.UrlHolder in project OpenUnison by TremoloSecurity.

the class SendMessageThread method doPost.

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException {
    // SharedSession.getSharedSession().getSession(req.getSession().getId());
    HttpSession session = ((HttpServletRequest) request).getSession();
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
    AuthMechType amt = act.getAuthMech().get(as.getId());
    String splashRedirect = authParams.get("splashRedirect").getValues().get(0);
    String noUserSplash = authParams.get("noUserSplash").getValues().get(0);
    if (request.getParameter("email") != null) {
        generateResetKey(request, response, splashRedirect, noUserSplash, as, act, this.lookupAttributeName);
        return;
    } else if (request.getParameter("key") != null) {
        String key = request.getParameter("key");
        org.hibernate.Session con = null;
        try {
            con = this.sessionFactory.openSession();
            finishLogin(request, response, session, act, as.getId(), amt, minValidKey, key, con, reqHolder, as);
        } catch (SQLException e) {
            throw new ServletException("Could not complete login", e);
        } finally {
            if (con != null) {
                con.close();
            }
        }
    }
}
Also used : LDAPAttribute(com.novell.ldap.LDAPAttribute) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) HttpSession(javax.servlet.http.HttpSession) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) HttpServletRequest(javax.servlet.http.HttpServletRequest) UrlHolder(com.tremolosecurity.config.util.UrlHolder) ServletException(javax.servlet.ServletException) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) HttpSession(javax.servlet.http.HttpSession) Session(javax.mail.Session)

Example 34 with UrlHolder

use of com.tremolosecurity.config.util.UrlHolder in project OpenUnison by TremoloSecurity.

the class SAML2Auth method doPost.

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp, AuthStep as) throws ServletException, IOException {
    MyVDConnection myvd = cfgMgr.getMyVD();
    // HttpSession session = (HttpSession)
    // req.getAttribute(ConfigFilter.AUTOIDM_SESSION);//((HttpServletRequest)
    // req).getSession();
    // //SharedSession.getSharedSession().getSession(req.getSession().getId());
    // SharedSession.getSharedSession().getSession(req.getSession().getId());
    HttpSession session = ((HttpServletRequest) req).getSession();
    UrlHolder holder = (UrlHolder) req.getAttribute(ProxyConstants.AUTOIDM_CFG);
    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(urlChain);
    AuthInfo userData = ((AuthController) req.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
    if (userData.isAuthComplete() && userData.getAuthLevel() > 0) {
        // Session is already set, just redirect to relay state
        String relayState = this.getFinalURL(req, resp);
        if (relayState == null) {
            throw new ServletException("No RelayState or default RelayState");
        }
        resp.sendRedirect(relayState);
        return;
    }
    if (as == null) {
        // this is a special case - idp initiated means there's no context
        ArrayList<AuthStep> auths = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthSteps();
        int id = 0;
        for (AuthMechType amt : act.getAuthMech()) {
            AuthStep asx = new AuthStep();
            asx.setId(id);
            asx.setExecuted(false);
            asx.setRequired(amt.getRequired().equals("required"));
            asx.setSuccess(false);
            auths.add(asx);
            id++;
        }
        as = auths.get(0);
    }
    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
    String defaultOC = authParams.get("defaultOC").getValues().get(0);
    String spEncKey = null;
    if (authParams.get("spEncKey") != null) {
        spEncKey = authParams.get("spEncKey").getValues().get(0);
    }
    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
    AuthMechType amt = act.getAuthMech().get(as.getId());
    List<String> sigCertNames = authParams.get("idpSigKeyName").getValues();
    List<X509Certificate> sigCerts = new ArrayList<X509Certificate>();
    boolean isMultiIdp = authParams.get("isMultiIdP") != null && authParams.get("isMultiIdP").getValues().get(0).equalsIgnoreCase("true");
    String ldapAttrib = authParams.get("ldapAttribute").getValues().get(0);
    String dnLabel = authParams.get("dnOU").getValues().get(0);
    String samlResp = req.getParameter("SAMLResponse");
    String xml = null;
    xml = new String(Base64.decodeBase64(samlResp), "UTF-8");
    boolean assertionSigned = true;
    if (authParams.get("assertionsSigned") != null) {
        assertionSigned = Boolean.parseBoolean(authParams.get("assertionsSigned").getValues().get(0));
    }
    boolean responseSigned = false;
    if (authParams.get("responsesSigned") != null) {
        responseSigned = Boolean.parseBoolean(authParams.get("responsesSigned").getValues().get(0));
    }
    boolean assertionEncrypted = false;
    if (authParams.get("assertionEncrypted") != null) {
        assertionEncrypted = Boolean.parseBoolean(authParams.get("assertionEncrypted").getValues().get(0));
    }
    if (logger.isDebugEnabled()) {
        logger.debug("=========saml2resp============");
        logger.debug(xml);
        logger.debug("=========saml2resp============");
    }
    xml = xml.replaceAll("<!--.*-->", "");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Element root = builder.parse(new InputSource(new StringReader(xml))).getDocumentElement();
        Response samlResponse = (Response) XMLObjectSupport.getUnmarshaller(root).unmarshall(root);
        if (isMultiIdp) {
            try {
                String dn = authParams.get("idpDir").getValues().get(0);
                LDAPSearchResults res = cfgMgr.getMyVD().search(dn, 2, equal("issuer", samlResponse.getIssuer().getValue()).toString(), new ArrayList<String>());
                if (!res.hasMore()) {
                    throw new ServletException("No IdP found");
                }
                LDAPEntry entry = res.next();
                java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509");
                sigCerts.add((java.security.cert.X509Certificate) cf.generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(entry.getAttribute("idpSig").getStringValue()))));
            } catch (LDAPException e) {
                throw new ServletException("Could not load IdP data", e);
            } catch (CertificateException e) {
                throw new ServletException("Could not load IdP data", e);
            }
        } else {
            for (String sigCertName : sigCertNames) {
                sigCerts.add(cfgMgr.getCertificate(sigCertName));
            }
        }
        if (responseSigned) {
            if (samlResponse.getSignature() != null) {
                boolean foundSigned = false;
                for (X509Certificate sigCert : sigCerts) {
                    if (sigCert != null) {
                        BasicCredential sigCred = new BasicCredential(sigCert.getPublicKey());
                        sigCred.setUsageType(UsageType.SIGNING);
                        try {
                            SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator();
                            profileValidator.validate(samlResponse.getSignature());
                            SignatureValidator.validate(samlResponse.getSignature(), sigCred);
                            foundSigned = true;
                        } catch (org.opensaml.xmlsec.signature.support.SignatureException se) {
                        }
                    }
                }
                if (!foundSigned) {
                    throw new ServletException("could not validate response");
                }
            } else {
                throw new Exception("Response not signed");
            }
        }
        Assertion assertion = null;
        if (samlResponse.getEncryptedAssertions().size() > 0) {
            try {
                EncryptedAssertion encAssertion = samlResponse.getEncryptedAssertions().get(0);
                PrivateKey privKey = this.cfgMgr.getPrivateKey(spEncKey);
                PublicKey pubKey = this.cfgMgr.getCertificate(spEncKey).getPublicKey();
                Credential credential = new BasicCredential(pubKey, privKey);
                StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(credential);
                Decrypter decrypter = new Decrypter(null, resolver, new InlineEncryptedKeyResolver());
                decrypter.setRootInNewDocument(true);
                assertion = decrypter.decrypt(encAssertion);
            } catch (Exception e) {
                throw new ServletException("Error decrypting assertion", e);
            }
        } else {
            if (assertionEncrypted) {
                throw new Exception("Assertion not encrypted");
            }
            if (samlResponse.getAssertions().size() == 0) {
                throw new Exception("No assertions found");
            }
            assertion = (Assertion) samlResponse.getAssertions().get(0);
        }
        if (assertionSigned) {
            if (assertion.getSignature() != null) {
                boolean foundSigned = false;
                for (X509Certificate sigCert : sigCerts) {
                    if (sigCert != null) {
                        BasicCredential sigCred = new BasicCredential(sigCert.getPublicKey());
                        sigCred.setUsageType(UsageType.SIGNING);
                        try {
                            SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator();
                            profileValidator.validate(assertion.getSignature());
                            SignatureValidator.validate(assertion.getSignature(), sigCred);
                            foundSigned = true;
                        } catch (org.opensaml.xmlsec.signature.support.SignatureException se) {
                        }
                    }
                }
                if (!foundSigned) {
                    throw new ServletException("Assertion can not be validated with a trusted certificate");
                }
            } else {
                throw new Exception("No assertion signature");
            }
        }
        // If it made it here, the assertion is valid, lets check the authncontextclassref
        Attribute authnContextClassRef = authParams.get("authCtxRef");
        if (authnContextClassRef != null && authnContextClassRef.getValues().size() > 0 && !authnContextClassRef.getValues().get(0).isEmpty() && !authnContextClassRef.getValues().get(0).equalsIgnoreCase("none") && (assertion.getAuthnStatements() == null || assertion.getAuthnStatements().size() == 0 || assertion.getAuthnStatements().get(0).getAuthnContext() == null || assertion.getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef() == null || assertion.getAuthnStatements().get(0).getAuthnContext() == null || assertion.getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef() == null || assertion.getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef().getURI() == null || !assertion.getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef().getURI().equalsIgnoreCase(authnContextClassRef.getValues().get(0)))) {
            logger.warn("Can not validate the authentication context classref");
            as.setSuccess(false);
            holder.getConfig().getAuthManager().nextAuth(req, resp, session, false);
            return;
        }
        try {
            if (authParams.get("dontLinkToLDAP") == null || authParams.get("dontLinkToLDAP").getValues().get(0).equalsIgnoreCase("false")) {
                StringBuffer filter = new StringBuffer();
                filter.append('(').append(ldapAttrib).append('=').append(assertion.getSubject().getNameID().getValue()).append(')');
                LDAPSearchResults res = myvd.search(AuthUtil.getChainRoot(cfgMgr, act), 2, filter.toString(), new ArrayList<String>());
                if (res.hasMore()) {
                    createUserFromDir(session, act, ldapAttrib, assertion, res);
                } else {
                    createUnlinkedUser(session, act, ldapAttrib, dnLabel, defaultOC, assertion);
                }
            } else {
                createUnlinkedUser(session, act, ldapAttrib, dnLabel, defaultOC, assertion);
            }
        } catch (LDAPException e) {
            if (e.getResultCode() == 32) {
                createUnlinkedUser(session, act, ldapAttrib, dnLabel, defaultOC, assertion);
            } else {
                throw e;
            }
        }
        // logout management
        Attribute logoutURLAttr = authParams.get("idpRedirLogoutURL");
        if (logoutURLAttr != null && logoutURLAttr.getValues().size() > 0 && !logoutURLAttr.getValues().get(0).isEmpty() && authParams.get("spSigKey") != null && authParams.get("spSigKey").getValues().size() > 0) {
            String logoutURL = logoutURLAttr.getValues().get(0);
            String sessionIndex = assertion.getAuthnStatements().get(0).getSessionIndex();
            String nameID = assertion.getSubject().getNameID().getValue();
            String nameIDFormat = assertion.getSubject().getNameID().getFormat();
            Saml2SingleLogout handler = new Saml2SingleLogout(logoutURL, sessionIndex, nameID, nameIDFormat, samlResponse.getDestination(), authParams.get("spSigKey").getValues().get(0), authParams.get("sigAlg").getValues().get(0), authParams.get("entityID").getValues().get(0));
            LogoutUtil.addLogoutHandler(req, handler);
        }
        as.setSuccess(true);
    } catch (Exception e) {
        logger.error("Error Parsing Assertion", e);
        throw new ServletException("error parsing assertion", e);
    }
    holder.getConfig().getAuthManager().nextAuth(req, resp, session, false);
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) PrivateKey(java.security.PrivateKey) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) XSString(org.opensaml.core.xml.schema.XSString) AuthStep(com.tremolosecurity.proxy.auth.util.AuthStep) HttpServletRequest(javax.servlet.http.HttpServletRequest) UrlHolder(com.tremolosecurity.config.util.UrlHolder) ServletException(javax.servlet.ServletException) LDAPEntry(com.novell.ldap.LDAPEntry) SAMLSignatureProfileValidator(org.opensaml.saml.security.impl.SAMLSignatureProfileValidator) PublicKey(java.security.PublicKey) EncryptedAssertion(org.opensaml.saml.saml2.core.EncryptedAssertion) Assertion(org.opensaml.saml.saml2.core.Assertion) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) Decrypter(org.opensaml.saml.saml2.encryption.Decrypter) X509Certificate(java.security.cert.X509Certificate) LDAPException(com.novell.ldap.LDAPException) ByteArrayInputStream(java.io.ByteArrayInputStream) InlineEncryptedKeyResolver(org.opensaml.xmlsec.encryption.support.InlineEncryptedKeyResolver) Attribute(com.tremolosecurity.saml.Attribute) LDAPAttribute(com.novell.ldap.LDAPAttribute) Element(org.w3c.dom.Element) StaticKeyInfoCredentialResolver(org.opensaml.xmlsec.keyinfo.impl.StaticKeyInfoCredentialResolver) StringReader(java.io.StringReader) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) MyVDConnection(com.tremolosecurity.proxy.myvd.MyVDConnection) BasicCredential(org.opensaml.security.credential.BasicCredential) BasicCredential(org.opensaml.security.credential.BasicCredential) Credential(org.opensaml.security.credential.Credential) TremoloHttpSession(com.tremolosecurity.proxy.TremoloHttpSession) HttpSession(javax.servlet.http.HttpSession) Saml2SingleLogout(com.tremolosecurity.proxy.auth.saml2.Saml2SingleLogout) UnmarshallingException(org.opensaml.core.xml.io.UnmarshallingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) LDAPException(com.novell.ldap.LDAPException) MarshallingException(org.opensaml.core.xml.io.MarshallingException) IOException(java.io.IOException) Base64DecodingException(org.apache.xml.security.exceptions.Base64DecodingException) ServletException(javax.servlet.ServletException) SignatureException(java.security.SignatureException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InitializationException(org.opensaml.core.config.InitializationException) MalformedURLException(java.net.MalformedURLException) CertificateException(java.security.cert.CertificateException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) LogoutResponse(org.opensaml.saml.saml2.core.LogoutResponse) Response(org.opensaml.saml.saml2.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) LDAPSearchResults(com.novell.ldap.LDAPSearchResults) DocumentBuilder(javax.xml.parsers.DocumentBuilder) EncryptedAssertion(org.opensaml.saml.saml2.core.EncryptedAssertion)

Example 35 with UrlHolder

use of com.tremolosecurity.config.util.UrlHolder in project OpenUnison by TremoloSecurity.

the class PersistentCookieResult method createResultCookie.

@Override
public void createResultCookie(Cookie cookie, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    ConfigManager mgr = holder.getConfig();
    HashSet<String> mechs = new HashSet<String>();
    for (String mechName : mgr.getAuthMechs().keySet()) {
        MechanismType mech = mgr.getAuthMechs().get(mechName);
        if (mech.getClassName().equalsIgnoreCase("com.tremolosecurity.proxy.auth.persistentCookie.PersistentCookie")) {
            mechs.add(mechName);
        }
    }
    AuthController authCtl = (AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL);
    String chainName = authCtl.getAuthInfo().getAuthChain();
    AuthChainType chain = mgr.getAuthChains().get(chainName);
    chain = AuthManagerImpl.buildACT(chain, mgr);
    int millisToLive = 0;
    String keyAlias = "";
    boolean useSSLSession = false;
    for (AuthMechType amt : chain.getAuthMech()) {
        if (mechs.contains(amt.getName())) {
            for (ParamWithValueType pt : amt.getParams().getParam()) {
                String value = "";
                if (pt.getValue() != null && !pt.getValue().isBlank()) {
                    value = pt.getValue();
                } else {
                    value = pt.getValueAttribute();
                }
                if (pt.getName().equalsIgnoreCase("millisToLive")) {
                    millisToLive = Integer.parseInt(value);
                }
                if (pt.getName().equalsIgnoreCase("useSSLSessionID") && value.equalsIgnoreCase("true")) {
                    useSSLSession = true;
                } else if (pt.getName().equalsIgnoreCase("keyAlias")) {
                    keyAlias = value;
                }
            }
        }
    }
    DateTime now = new DateTime();
    DateTime expires = now.plusMillis(millisToLive);
    com.tremolosecurity.lastmile.LastMile lastmile = null;
    try {
        lastmile = new com.tremolosecurity.lastmile.LastMile("/", now, expires, 0, "NONE");
    } catch (URISyntaxException e) {
    // not possible
    }
    lastmile.getAttributes().add(new Attribute("DN", authCtl.getAuthInfo().getUserDN()));
    lastmile.getAttributes().add(new Attribute("CLIENT_IP", request.getRemoteAddr()));
    if (useSSLSession) {
        Object sessionID = request.getAttribute("javax.servlet.request.ssl_session_id");
        if (sessionID instanceof byte[]) {
            sessionID = new String(Base64.encodeBase64((byte[]) sessionID));
        }
        lastmile.getAttributes().add(new Attribute("SSL_SESSION_ID", (String) sessionID));
    }
    try {
        cookie.setValue(new StringBuilder().append('"').append(lastmile.generateLastMileToken(mgr.getSecretKey(keyAlias))).append('"').toString());
    } catch (Exception e) {
        throw new ServletException("Could not encrypt persistent cookie", e);
    }
    cookie.setMaxAge(millisToLive / 1000);
}
Also used : Attribute(com.tremolosecurity.saml.Attribute) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) URISyntaxException(java.net.URISyntaxException) AuthController(com.tremolosecurity.proxy.auth.AuthController) ConfigManager(com.tremolosecurity.config.util.ConfigManager) DateTime(org.joda.time.DateTime) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) UrlHolder(com.tremolosecurity.config.util.UrlHolder) ServletException(javax.servlet.ServletException) MechanismType(com.tremolosecurity.config.xml.MechanismType) ParamWithValueType(com.tremolosecurity.config.xml.ParamWithValueType) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) HashSet(java.util.HashSet)

Aggregations

UrlHolder (com.tremolosecurity.config.util.UrlHolder)61 ServletException (javax.servlet.ServletException)42 HttpSession (javax.servlet.http.HttpSession)39 HashMap (java.util.HashMap)38 HttpServletRequest (javax.servlet.http.HttpServletRequest)36 AuthChainType (com.tremolosecurity.config.xml.AuthChainType)34 Attribute (com.tremolosecurity.saml.Attribute)31 AuthMechType (com.tremolosecurity.config.xml.AuthMechType)26 AuthController (com.tremolosecurity.proxy.auth.AuthController)26 IOException (java.io.IOException)26 AuthInfo (com.tremolosecurity.proxy.auth.AuthInfo)18 RequestHolder (com.tremolosecurity.proxy.auth.RequestHolder)18 LDAPException (com.novell.ldap.LDAPException)17 LDAPAttribute (com.novell.ldap.LDAPAttribute)16 ConfigManager (com.tremolosecurity.config.util.ConfigManager)12 MyVDConnection (com.tremolosecurity.proxy.myvd.MyVDConnection)10 MalformedURLException (java.net.MalformedURLException)10 ArrayList (java.util.ArrayList)10 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)9 Gson (com.google.gson.Gson)8