Search in sources :

Example 1 with AuthStep

use of com.tremolosecurity.proxy.auth.util.AuthStep in project OpenUnison by TremoloSecurity.

the class RemoteBasic method doFilter.

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
    HashMap<String, Attribute> authParams = new HashMap<String, Attribute>();
    authParams.put("realmName", new Attribute("realmName", this.realmName));
    authParams.put("uidAttr", new Attribute("uidAttr", "uid"));
    request.getSession().setAttribute(ProxyConstants.AUTH_MECH_PARAMS, authParams);
    AuthStep as = new AuthStep();
    as.setId(0);
    as.setRequired(true);
    if (com.tremolosecurity.proxy.auth.BasicAuth.checkBasicAuth(request.getServletRequest(), response.getServletResponse(), cfgMgr, new HttpBasicAuth(url, false, host, port), as)) {
        request.removeHeader("Authorization");
        chain.nextFilter(request, response, chain);
    } else {
        chain.setNoProxy(true);
    }
}
Also used : HttpBasicAuth(com.tremolosecurity.proxy.auth.util.HttpBasicAuth) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) AuthStep(com.tremolosecurity.proxy.auth.util.AuthStep)

Example 2 with AuthStep

use of com.tremolosecurity.proxy.auth.util.AuthStep in project OpenUnison by TremoloSecurity.

the class BasicAuth method doFilter.

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
    HashMap<String, Attribute> authParams = new HashMap<String, Attribute>();
    authParams.put("realmName", new Attribute("realmName", this.realmName));
    authParams.put("uidAttr", new Attribute("uidAttr", this.uidAttrName));
    request.getSession().setAttribute(ProxyConstants.AUTH_MECH_PARAMS, authParams);
    AuthStep as = new AuthStep();
    as.setId(0);
    as.setExecuted(true);
    as.setRequired(true);
    if (com.tremolosecurity.proxy.auth.BasicAuth.checkBasicAuth(request.getServletRequest(), response.getServletResponse(), cfgMgr, new LDAPBasicAuth(), as)) {
        request.removeHeader("Authorization");
        chain.nextFilter(request, response, chain);
    } else {
        chain.setNoProxy(true);
    }
}
Also used : LDAPBasicAuth(com.tremolosecurity.proxy.auth.util.LDAPBasicAuth) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) AuthStep(com.tremolosecurity.proxy.auth.util.AuthStep)

Example 3 with AuthStep

use of com.tremolosecurity.proxy.auth.util.AuthStep in project OpenUnison by TremoloSecurity.

the class SendMessageThread method doGet.

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException {
    if (!this.enabled) {
        throw new ServletException("Operation Not Supported");
    }
    // SharedSession.getSharedSession().getSession(req.getSession().getId());
    HttpSession session = ((HttpServletRequest) request).getSession();
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    if (holder == null) {
        String finalURL = this.getFinalURL(request, response);
        try {
            holder = cfgMgr.findURL(finalURL);
            request.setAttribute(ProxyConstants.AUTOIDM_CFG, holder);
        } catch (Exception e) {
            throw new ServletException("Could not run authentication", e);
        }
    }
    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
    if (request.getParameter("email") != null) {
        AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
        String splashRedirect = authParams.get("splashRedirect").getValues().get(0);
        String noUserSplash = authParams.get("noUserSplash").getValues().get(0);
        generateResetKey(request, response, splashRedirect, noUserSplash, as, act, this.lookupAttributeName);
        return;
    } else if (request.getParameter("key") == null) {
        String emailCollectionRedir = authParams.get("emailCollectionRedir").getValues().get(0);
        response.sendRedirect(emailCollectionRedir);
        return;
    } else {
        String key = request.getParameter("key");
        org.hibernate.Session con = null;
        try {
            con = this.sessionFactory.openSession();
            String urlChain = holder.getUrl().getAuthChain();
            AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
            if (as == null || ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthSteps().size() == 0) {
                // like saml2 idp initiated, this is a special use case
                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);
            }
            AuthMechType amt = act.getAuthMech().get(as.getId());
            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) ArrayList(java.util.ArrayList) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) AuthStep(com.tremolosecurity.proxy.auth.util.AuthStep) ServletException(javax.servlet.ServletException) MessagingException(javax.mail.MessagingException) LDAPException(com.novell.ldap.LDAPException) SQLException(java.sql.SQLException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) HttpServletRequest(javax.servlet.http.HttpServletRequest) UrlHolder(com.tremolosecurity.config.util.UrlHolder) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) HttpSession(javax.servlet.http.HttpSession) Session(javax.mail.Session)

Example 4 with AuthStep

use of com.tremolosecurity.proxy.auth.util.AuthStep 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 5 with AuthStep

use of com.tremolosecurity.proxy.auth.util.AuthStep in project OpenUnison by TremoloSecurity.

the class AuthManagerImpl method execAuth.

/* (non-Javadoc)
	 * @see com.tremolosecurity.proxy.auth.sys.AuthManager#execAuth(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.http.HttpSession, boolean, com.tremolosecurity.config.util.UrlHolder, com.tremolosecurity.config.xml.AuthChainType, java.lang.String, com.tremolosecurity.proxy.util.NextSys)
	 */
@Override
public boolean execAuth(HttpServletRequest req, HttpServletResponse resp, HttpSession session, boolean jsRedirect, UrlHolder holder, AuthChainType act, String finalURL, NextSys next) throws IOException, ServletException {
    boolean shortCircut = false;
    ConfigManager cfg = (ConfigManager) req.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);
    // Generate an AuthChainType based on the existing chain+includes
    if (act != cfg.getAuthFailChain()) {
        act = this.buildACT(act, cfg);
    }
    if (act.getLevel() == 0 && (act != cfg.getAuthFailChain())) {
        AuthController actl = (AuthController) session.getAttribute(ProxyConstants.AUTH_CTL);
        // there's no need to go through the process
        String anonMechName = act.getAuthMech().get(0).getName();
        MechanismType mt = holder.getConfig().getAuthMechs().get(anonMechName);
        AnonAuth anonAuth = (AnonAuth) holder.getConfig().getAuthMech(mt.getUri());
        anonAuth.createSession(session, act);
        return finishSuccessfulLogin(req, resp, holder, act, actl.getHolder(), actl, next);
    }
    RequestHolder reqHolder;
    int step = -1;
    AuthController actl = (AuthController) req.getSession().getAttribute(ProxyConstants.AUTH_CTL);
    ArrayList<AuthStep> auths = actl.getAuthSteps();
    if (auths.size() == 0) {
        int id = 0;
        for (AuthMechType amt : act.getAuthMech()) {
            AuthStep as = new AuthStep();
            as.setId(id);
            as.setExecuted(false);
            as.setRequired(amt.getRequired().equals("required"));
            as.setSuccess(false);
            auths.add(as);
            id++;
        }
        boolean anyRequired = false;
        for (AuthStep as : auths) {
            if (as.isRequired()) {
                anyRequired = true;
                break;
            }
        }
        if (!anyRequired) {
            act.setFinishOnRequiredSucess(true);
        }
        step = 0;
        HashMap<String, Attribute> params = new HashMap<String, Attribute>();
        ProxyUtil.loadParams(req, params);
        try {
            reqHolder = new RequestHolder(RequestHolder.getMethod(req.getMethod()), params, finalURL, act.getName(), ((ProxyRequest) req).getQueryStringParams());
            actl.setHolder(reqHolder);
        } catch (Exception e) {
            throw new ServletException("Error creating request holder", e);
        }
    } else {
        reqHolder = actl.getHolder();
        boolean clearAllNotRequired = false;
        // determine the step
        for (AuthStep as : auths) {
            if (as.isSuccess()) {
                // TODO Check to see if the user is locked out
                if (act.getCompliance() != null && act.getCompliance().isEnabled()) {
                    Attribute lastFailed = actl.getAuthInfo().getAttribs().get(act.getCompliance().getLastFailedAttribute());
                    Attribute numFailures = actl.getAuthInfo().getAttribs().get(act.getCompliance().getNumFailedAttribute());
                    if (logger.isDebugEnabled()) {
                        logger.debug("lastFailed Attribute : '" + lastFailed + "'");
                        logger.debug("numFailures Attribute : '" + numFailures + "'");
                    }
                    if (lastFailed != null && numFailures != null) {
                        long lastFailedTS = lastFailed.getValues().size() > 0 ? Long.parseLong(lastFailed.getValues().get(0)) : 0;
                        int numPrevFailures = Integer.parseInt(numFailures.getValues().size() > 0 ? numFailures.getValues().get(0) : "0");
                        long now = new DateTime(DateTimeZone.UTC).getMillis();
                        long lockedUntil = lastFailedTS + act.getCompliance().getMaxLockoutTime();
                        if (logger.isDebugEnabled()) {
                            logger.debug("Num Failed : " + numPrevFailures);
                            logger.debug("Last Failed : '" + lastFailedTS + "'");
                            logger.info("Now : '" + now + "'");
                            logger.info("Locked Until : '" + lockedUntil + "'");
                            logger.info("locked >= now? : '" + (lockedUntil >= now) + "'");
                            logger.info("max fails? : '" + act.getCompliance().getMaxFailedAttempts() + "'");
                            logger.info("too many fails : '" + (numPrevFailures >= act.getCompliance().getMaxFailedAttempts()) + "'");
                        }
                        if (lockedUntil >= now && numPrevFailures >= act.getCompliance().getMaxFailedAttempts()) {
                            try {
                                failAuthentication(req, resp, holder, act);
                            } catch (Exception e) {
                                throw new ServletException("Could not complete authentication failure", e);
                            }
                            return false;
                        }
                    }
                }
                if (act.isFinishOnRequiredSucess()) {
                    step = -1;
                    clearAllNotRequired = true;
                }
            } else {
                if (as.isRequired()) {
                    if (as.isExecuted()) {
                        try {
                            failAuthentication(req, resp, holder, act);
                        } catch (Exception e) {
                            throw new ServletException("Could not complete authentication failure", e);
                        }
                        return false;
                    } else {
                        step = as.getId();
                        break;
                    }
                } else {
                    if (clearAllNotRequired) {
                        as.setExecuted(true);
                        as.setSuccess(true);
                    } else {
                        if (as.isExecuted()) {
                        } else {
                            step = as.getId();
                            break;
                        }
                    }
                }
            }
        }
    }
    if (step != -1) {
        /*if (jsRedirect && step < auths.size()) {
				step++;
			}*/
        AuthStep curStep = auths.get(step);
        actl.setCurrentStep(curStep);
        AuthMechType amt = act.getAuthMech().get(step);
        loadAmtParams(session, amt);
        // req.getRequestDispatcher(authFilterURI).forward(req, resp);
        Cookie sessionCookieName = new Cookie("autoIdmSessionCookieName", holder.getApp().getCookieConfig().getSessionCookieName());
        String domain = ProxyTools.getInstance().getCookieDomain(holder.getApp().getCookieConfig(), req);
        if (domain != null) {
            sessionCookieName.setDomain(domain);
        }
        sessionCookieName.setPath("/");
        sessionCookieName.setMaxAge(-1);
        sessionCookieName.setSecure(false);
        if ((holder.getApp() == null || holder.getApp().getCookieConfig() == null || holder.getApp().getCookieConfig() == null || holder.getApp().getCookieConfig().isCookiesEnabled() == null) || holder.getApp().getCookieConfig().isCookiesEnabled()) {
            ProxyResponse.addCookieToResponse(holder, sessionCookieName, (HttpServletResponse) ((ProxyResponse) resp).getResponse());
        }
        Cookie appCookieName = new Cookie("autoIdmAppName", URLEncoder.encode(holder.getApp().getName(), "UTF-8"));
        if (domain != null) {
            appCookieName.setDomain(domain);
        }
        appCookieName.setPath("/");
        appCookieName.setMaxAge(-1);
        appCookieName.setSecure(false);
        if ((holder.getApp() == null || holder.getApp().getCookieConfig() == null || holder.getApp().getCookieConfig() == null || holder.getApp().getCookieConfig().isCookiesEnabled() == null) || holder.getApp().getCookieConfig().isCookiesEnabled()) {
            ProxyResponse.addCookieToResponse(holder, appCookieName, (HttpServletResponse) ((ProxyResponse) resp).getResponse());
        }
        // resp.addCookie(appCookieName);
        String redirectURI = "";
        MechanismType nextAuthConfiguration = null;
        if (holder.getConfig().getContextPath().equalsIgnoreCase("/")) {
            nextAuthConfiguration = holder.getConfig().getAuthMechs().get(amt.getName());
            if (nextAuthConfiguration == null) {
                StringBuilder sb = new StringBuilder().append("Authentication mechanism '").append(amt.getName()).append("' does not exist, will always fail");
                logger.warn(sb.toString());
                nextAuthConfiguration = holder.getConfig().getAuthFailMechanism();
            }
            redirectURI = nextAuthConfiguration.getUri();
        } else {
            nextAuthConfiguration = holder.getConfig().getAuthMechs().get(amt.getName());
            if (nextAuthConfiguration == null) {
                StringBuilder sb = new StringBuilder().append("Authentication mechanism '").append(amt.getName()).append("' does not exist, will always fail");
                logger.warn(sb.toString());
                nextAuthConfiguration = holder.getConfig().getAuthFailMechanism();
            }
            redirectURI = new StringBuffer().append(holder.getConfig().getContextPath()).append(nextAuthConfiguration.getUri()).toString();
        }
        req.getSession().setAttribute("TREMOLO_AUTH_URI", redirectURI);
        if (jsRedirect) {
            StringBuffer b = new StringBuffer();
            b.append("<html><head></head><body onload=\"window.location='").append(ProxyTools.getInstance().getFqdnUrl(redirectURI, req)).append("';\"></body></html>");
            String respHTML = b.toString();
            ProxyData pd = new ProxyData();
            pd.setHolder(holder);
            pd.setIns(new ByteArrayInputStream(respHTML.getBytes("UTF-8")));
            pd.setPostProc(null);
            pd.setRequest(null);
            pd.setResponse(null);
            pd.setText(true);
            pd.setLogout(false);
            req.setAttribute(ProxyConstants.TREMOLO_PRXY_DATA, pd);
            // req.setAttribute(ProxySys.AUTOIDM_STREAM_WRITER,true);
            // req.setAttribute(ProxySys.TREMOLO_TXT_DATA, new
            // StringBuffer(respHTML));
            resp.sendError(401);
        } else {
            AuthMechanism mech = cfg.getAuthMech(redirectURI);
            if (mech == null) {
                throw new ServletException("Redirect URI '" + redirectURI + "' does not map to an authentication mechanism");
            }
            req.setAttribute(ProxyConstants.AUTH_REDIR_URI, redirectURI);
            if (curStep != null) {
                curStep.setExecuted(true);
            }
            if (req.getMethod().equalsIgnoreCase("get")) {
                mech.doGet(req, resp, curStep);
            } else if (req.getMethod().equalsIgnoreCase("post")) {
                mech.doPost(req, resp, curStep);
            } else if (req.getMethod().equalsIgnoreCase("put") || req.getMethod().equalsIgnoreCase("patch")) {
                mech.doPut(req, resp, curStep);
            } else if (req.getMethod().equalsIgnoreCase("delete")) {
                mech.doDelete(req, resp, curStep);
            } else if (req.getMethod().equalsIgnoreCase("head")) {
                mech.doHead(req, resp, curStep);
            } else if (req.getMethod().equalsIgnoreCase("options")) {
                mech.doOptions(req, resp, curStep);
            }
        }
        return false;
    } else {
        boolean success = true;
        boolean opSuccess = false;
        boolean hasOptional = false;
        for (AuthStep as : auths) {
            if (as.isRequired()) {
                if (!as.isSuccess()) {
                    success = false;
                    break;
                }
            } else {
                hasOptional = true;
                if (as.isSuccess()) {
                    opSuccess = true;
                }
            }
        }
        boolean allSuccess = success && ((hasOptional && opSuccess) || (!hasOptional));
        if (allSuccess) {
            return finishSuccessfulLogin(req, resp, holder, act, reqHolder, actl, next);
        } else {
            throw new ServletException("Unknown state");
        /*
				 * Cookie sessionCookieName = new
				 * Cookie("autoIdmSessionCookieName","DNE");
				 * sessionCookieName.setDomain
				 * (ProxyTools.getInstance().getCookieDomain
				 * (holder.getApp().getCookieConfig(), req));
				 * sessionCookieName.setPath("/");
				 * sessionCookieName.setMaxAge(0);
				 * sessionCookieName.setSecure(false);
				 * //resp.addCookie(sessionCookieName);
				 * 
				 * Cookie appCookieName = new Cookie("autoIdmAppName","DNE");
				 * appCookieName
				 * .setDomain(ProxyTools.getInstance().getCookieDomain
				 * (holder.getApp().getCookieConfig(), req));
				 * appCookieName.setPath("/"); appCookieName.setMaxAge(0);
				 * appCookieName.setSecure(false);
				 * //resp.addCookie(appCookieName);
				 */
        }
    }
}
Also used : AnonAuth(com.tremolosecurity.proxy.auth.AnonAuth) LDAPAttribute(com.novell.ldap.LDAPAttribute) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) RequestHolder(com.tremolosecurity.proxy.auth.RequestHolder) AuthStep(com.tremolosecurity.proxy.auth.util.AuthStep) DateTime(org.joda.time.DateTime) ServletException(javax.servlet.ServletException) AuthMechanism(com.tremolosecurity.proxy.auth.AuthMechanism) ProxyData(com.tremolosecurity.proxy.ProxyData) MechanismType(com.tremolosecurity.config.xml.MechanismType) ProxyRequest(com.tremolosecurity.proxy.ProxyRequest) Cookie(javax.servlet.http.Cookie) ProxyResponse(com.tremolosecurity.proxy.ProxyResponse) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) AuthController(com.tremolosecurity.proxy.auth.AuthController) ConfigManager(com.tremolosecurity.config.util.ConfigManager) ServletException(javax.servlet.ServletException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) LDAPException(com.novell.ldap.LDAPException) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream)

Aggregations

AuthStep (com.tremolosecurity.proxy.auth.util.AuthStep)8 Attribute (com.tremolosecurity.saml.Attribute)5 HashMap (java.util.HashMap)5 IOException (java.io.IOException)4 ServletException (javax.servlet.ServletException)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 LDAPAttribute (com.novell.ldap.LDAPAttribute)3 LDAPException (com.novell.ldap.LDAPException)3 UrlHolder (com.tremolosecurity.config.util.UrlHolder)3 AuthChainType (com.tremolosecurity.config.xml.AuthChainType)3 AuthMechType (com.tremolosecurity.config.xml.AuthMechType)3 AuthController (com.tremolosecurity.proxy.auth.AuthController)3 ArrayList (java.util.ArrayList)3 HttpSession (javax.servlet.http.HttpSession)3 ConfigManager (com.tremolosecurity.config.util.ConfigManager)2 ProxyRequest (com.tremolosecurity.proxy.ProxyRequest)2 AuthMechanism (com.tremolosecurity.proxy.auth.AuthMechanism)2 RequestHolder (com.tremolosecurity.proxy.auth.RequestHolder)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2