Search in sources :

Example 11 with RequestHolder

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

the class SecretQuestionAuth method doGet.

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException {
    HttpSession session = ((HttpServletRequest) request).getSession();
    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
    AuthMechType amt = act.getAuthMech().get(as.getId());
    AuthInfo user = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
    if (user == null) {
        throw new ServletException("No user present");
    }
    String questionAttrName = authParams.get("questionAttr").getValues().get(0);
    String loginForm = authParams.get("loginForm").getValues().get(0);
    Attribute qAttr = user.getAttribs().get(questionAttrName);
    if (qAttr == null) {
        throw new ServletException("User " + user.getUserDN() + " does not have secret questions");
    }
    byte[] encBytes = org.bouncycastle.util.encoders.Base64.decode(qAttr.getValues().get(0));
    ByteArrayInputStream bais = new ByteArrayInputStream(encBytes);
    ObjectInputStream ois = new ObjectInputStream(bais);
    ArrayList<SecretQuestion> questions = null;
    try {
        questions = (ArrayList<SecretQuestion>) ois.readObject();
    } catch (ClassNotFoundException e) {
        throw new ServletException("Could not load questions", e);
    }
    request.getSession(true).setAttribute("TREMOLO_SECRET_ANSWERS", questions);
    request.setAttribute("TREMOLO_SECRET_QUESTIONS", questions);
    request.setAttribute("TREMOLO_SECRET_QUESTION_LIST", this.questionList);
    request.getRequestDispatcher(loginForm).forward(request, response);
}
Also used : AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) RequestHolder(com.tremolosecurity.proxy.auth.RequestHolder) AuthController(com.tremolosecurity.proxy.auth.AuthController) HttpServletRequest(javax.servlet.http.HttpServletRequest) UrlHolder(com.tremolosecurity.config.util.UrlHolder) ServletException(javax.servlet.ServletException) ByteArrayInputStream(java.io.ByteArrayInputStream) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) ObjectInputStream(java.io.ObjectInputStream)

Example 12 with RequestHolder

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

the class OAuth2JWT method processToken.

@Override
public void processToken(HttpServletRequest request, HttpServletResponse response, AuthStep as, HttpSession session, HashMap<String, Attribute> authParams, AuthChainType act, String realmName, String scope, ConfigManager cfg, String lmToken) throws ServletException, IOException {
    String issuer = authParams.get("issuer").getValues().get(0);
    HashSet<String> audiences = new HashSet<String>();
    if (authParams.get("audience") == null) {
        logger.warn("No audience configuration, all requests will fail");
    } else {
        audiences.addAll(authParams.get("audience").getValues());
    }
    String fromWellKnown = authParams.get("fromWellKnown") != null ? authParams.get("fromWellKnown").getValues().get(0) : "false";
    boolean useWellKnown = fromWellKnown.equalsIgnoreCase("true");
    PublicKey pk = null;
    if (useWellKnown) {
        pk = keyCache.get(issuer);
        if (pk == null) {
            StringBuilder sb = new StringBuilder();
            sb.append(issuer);
            if (!issuer.endsWith("/")) {
                sb.append("/");
            }
            sb.append(".well-known/openid-configuration");
            String wellKnownURL = sb.toString();
            HttpCon http = null;
            try {
                http = this.createClient();
                HttpGet get = new HttpGet(wellKnownURL);
                CloseableHttpResponse resp = http.getHttp().execute(get);
                String json = EntityUtils.toString(resp.getEntity());
                resp.close();
                JSONParser parser = new JSONParser();
                JSONObject root = (JSONObject) parser.parse(json);
                String jwksUrl = (String) root.get("jwks_uri");
                get = new HttpGet(jwksUrl);
                resp = http.getHttp().execute(get);
                json = EntityUtils.toString(resp.getEntity());
                resp.close();
                JsonWebKey jwk = null;
                JsonWebKeySet jks = new JsonWebKeySet(json);
                if (jks.getJsonWebKeys().size() == 0) {
                    jwk = jks.getJsonWebKeys().get(0);
                } else {
                    for (JsonWebKey j : jks.getJsonWebKeys()) {
                        if (j.getUse().equalsIgnoreCase("sig")) {
                            jwk = j;
                            break;
                        }
                    }
                }
                if (jwk == null) {
                    throw new ServletException("No key found");
                }
                pk = (PublicKey) jwk.getKey();
                keyCache.put(issuer, pk);
            } catch (Exception e) {
                throw new ServletException("Could not get oidc certs", e);
            } finally {
                if (http != null) {
                    http.getHttp().close();
                    http.getBcm().close();
                }
            }
        }
    } else {
        String validationKey = authParams.get("validationKey").getValues().get(0);
        pk = cfg.getCertificate(validationKey).getPublicKey();
    }
    boolean linkToDirectory = Boolean.parseBoolean(authParams.get("linkToDirectory").getValues().get(0));
    String noMatchOU = authParams.get("noMatchOU").getValues().get(0);
    String uidAttr = authParams.get("uidAttr").getValues().get(0);
    String lookupFilter = authParams.get("lookupFilter").getValues().get(0);
    String defaultObjectClass = authParams.get("defaultObjectClass").getValues().get(0);
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
    JsonWebSignature jws = new JsonWebSignature();
    try {
        jws.setCompactSerialization(lmToken);
        jws.setKey(pk);
        if (!jws.verifySignature()) {
            as.setExecuted(true);
            as.setSuccess(false);
            logger.warn("Could not verify signature");
            cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
            super.sendFail(response, realmName, scope, null, null);
            return;
        }
        String json = jws.getPayload();
        JSONObject obj = (JSONObject) new JSONParser().parse(json);
        long exp = ((Long) obj.get("exp")) * 1000L;
        long nbf = ((Long) obj.get("nbf")) * 1000L;
        if (new DateTime(exp).isBeforeNow()) {
            as.setExecuted(true);
            as.setSuccess(false);
            logger.warn("JWT not yet valid");
            cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
            super.sendFail(response, realmName, scope, null, null);
            return;
        }
        if (new DateTime(nbf).isAfterNow()) {
            as.setExecuted(true);
            as.setSuccess(false);
            logger.warn("JWT expired");
            cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
            super.sendFail(response, realmName, scope, null, null);
            return;
        }
        if (!((String) obj.get("iss")).equals(issuer)) {
            as.setExecuted(true);
            as.setSuccess(false);
            logger.warn("JWT invalid issuer");
            cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
            super.sendFail(response, realmName, scope, null, null);
            return;
        }
        Object aud = obj.get("aud");
        if (aud == null) {
            logger.warn("JWT has no aud");
            as.setExecuted(true);
            as.setSuccess(false);
            cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
            super.sendFail(response, realmName, scope, null, null);
            return;
        } else if (aud instanceof JSONArray) {
            JSONArray auds = (JSONArray) aud;
            boolean found = false;
            for (Object audVal : auds) {
                if (audiences.contains((String) audVal)) {
                    found = true;
                }
            }
            if (!found) {
                as.setExecuted(true);
                as.setSuccess(false);
                logger.warn("Invalid audience");
                cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
                super.sendFail(response, realmName, scope, null, null);
                return;
            }
        } else {
            if (!audiences.contains((String) aud)) {
                as.setExecuted(true);
                as.setSuccess(false);
                logger.warn("Invalid audience");
                cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
                super.sendFail(response, realmName, scope, null, null);
                return;
            }
        }
        if (!linkToDirectory) {
            loadUnlinkedUser(session, noMatchOU, uidAttr, act, obj, defaultObjectClass);
            as.setSuccess(true);
        } else {
            lookupUser(as, session, cfg.getMyVD(), noMatchOU, uidAttr, lookupFilter, act, obj, defaultObjectClass);
        }
        String redirectToURL = request.getParameter("target");
        if (redirectToURL != null && !redirectToURL.isEmpty()) {
            reqHolder.setURL(redirectToURL);
        }
        as.setExecuted(true);
        as.setSuccess(true);
        cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
    } catch (JoseException | ParseException e) {
        throw new ServletException("Could not process JWT", e);
    }
}
Also used : JoseException(org.jose4j.lang.JoseException) HttpGet(org.apache.http.client.methods.HttpGet) RequestHolder(com.tremolosecurity.proxy.auth.RequestHolder) DateTime(org.joda.time.DateTime) ServletException(javax.servlet.ServletException) UrlHolder(com.tremolosecurity.config.util.UrlHolder) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HashSet(java.util.HashSet) PublicKey(java.security.PublicKey) JsonWebKey(org.jose4j.jwk.JsonWebKey) JSONArray(org.json.simple.JSONArray) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) AuthController(com.tremolosecurity.proxy.auth.AuthController) LDAPException(com.novell.ldap.LDAPException) ServletException(javax.servlet.ServletException) ParseException(org.json.simple.parser.ParseException) IOException(java.io.IOException) JoseException(org.jose4j.lang.JoseException) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) JsonWebSignature(org.jose4j.jws.JsonWebSignature) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException)

Example 13 with RequestHolder

use of com.tremolosecurity.proxy.auth.RequestHolder 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)

Example 14 with RequestHolder

use of com.tremolosecurity.proxy.auth.RequestHolder 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 15 with RequestHolder

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

the class UnisonServletFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = new LocalSessionRequest((HttpServletRequest) request);
    HttpServletResponse resp = (HttpServletResponse) response;
    ConfigManager cfg = (ConfigManager) ctx.getAttribute(ProxyConstants.TREMOLO_CONFIG);
    SessionManager sessionMgr = (SessionManager) ctx.getAttribute(ProxyConstants.TREMOLO_SESSION_MANAGER);
    ProxyRequest pr = null;
    try {
        pr = new ProxyRequest((HttpServletRequest) req);
    } catch (Exception e1) {
        logger.error("Unable to create request", e1);
        throw new IOException("Could not create request");
    }
    try {
        req.setAttribute(ProxyConstants.TREMOLO_FILTER_CHAIN, chain);
        NextEmbSys embSys = new NextEmbSys(this.cfg.getServletContext(), chain, passOn);
        /*System.err.println("*** Begin Request ****");
			System.err.println("url = '" + ((HttpServletRequest)req).getRequestURL() + "'");
			Cookie[] cookies = ((HttpServletRequest) req).getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					System.err.println("'" + cookie.getName() + "'='" + cookie.getValue() + "'");
				}
			}
			System.err.println("*** End Request ****");*/
        String fwdProto = req.getHeader("X-Forwarded-Proto");
        boolean toSSL = false;
        if (cfg.isForceToSSL()) {
            if (fwdProto != null) {
                toSSL = fwdProto.equalsIgnoreCase("http");
            } else {
                toSSL = !req.getRequestURL().toString().toLowerCase().startsWith("https");
            }
        }
        if (toSSL) {
            StringBuffer redirURL = new StringBuffer();
            URL reqURL = new URL(req.getRequestURL().toString());
            redirURL.append("https://").append(reqURL.getHost());
            if (cfg.getExternalSecurePort() != 443) {
                redirURL.append(":").append(cfg.getSecurePort());
            }
            redirURL.append(reqURL.getPath());
            if (reqURL.getQuery() != null) {
                redirURL.append('?').append(reqURL.getQuery());
            }
            resp.sendRedirect(redirURL.toString());
            return;
        }
        // add hsts
        if (GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getApplications().isHsts()) {
            StringBuffer sb = new StringBuffer();
            sb.append("max-age=").append(GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getApplications().getHstsTTL()).append(" ; includeSubDomains");
            resp.addHeader("Strict-Transport-Security", sb.toString());
        }
        req.setAttribute(ProxyConstants.TREMOLO_CFG_OBJ, cfg);
        HttpServletRequest servReq = (HttpServletRequest) req;
        String URL;
        HttpSession sharedSession = null;
        UrlHolder holder = null;
        URL = servReq.getRequestURL().toString();
        holder = cfg.findURL(URL);
        boolean isForcedAuth = false;
        RequestHolder reqHolder = null;
        String sessionCookieName = req.getParameter("sessionCookie");
        if (sessionCookieName == null) {
            Cookie[] cookies = ((HttpServletRequest) req).getCookies();
            if (cookies != null) {
                for (int i = 0; i < cookies.length; i++) {
                    if (cookies[i].getName().equals("autoIdmSessionCookieName")) {
                        sessionCookieName = cookies[i].getValue();
                    }
                }
            }
        }
        if (sessionCookieName == null) {
        } else {
        }
        if (holder == null) {
            // check the session
            sharedSession = sessionMgr.getSession(sessionCookieName, holder, ((HttpServletRequest) req), ((HttpServletResponse) resp), this.ctx);
            if (sharedSession != null) {
                AuthController actl = (AuthController) sharedSession.getAttribute(ProxyConstants.AUTH_CTL);
                if (actl.getHolder() != null) {
                    URL = ((AuthController) sharedSession.getAttribute(ProxyConstants.AUTH_CTL)).getHolder().getURL();
                    holder = cfg.findURL(URL);
                }
            }
        } else {
            sharedSession = sessionMgr.getSession(holder, ((HttpServletRequest) req), ((HttpServletResponse) resp), this.ctx);
        }
        // LocalSessionRequest lsr = new LocalSessionRequest((HttpServletRequest)req,sharedSession);
        if (sharedSession != null) {
            pr.setSession(sharedSession);
        }
        if ((holder == null || holder.getUrl().getUri().equalsIgnoreCase("/")) && req.getRequestURI().startsWith(cfg.getAuthPath()) && sessionCookieName == null) {
            // if (req.getRequestURI().startsWith("/auth/")) {
            AuthMechanism authMech = cfg.getAuthMech(((HttpServletRequest) req).getRequestURI());
            if (authMech != null) {
                String finalURL = authMech.getFinalURL(pr, resp);
                if (resp.getStatus() == 302) {
                    // redirect sent, stop processing
                    return;
                }
                if (finalURL != null) {
                    holder = cfg.findURL(finalURL);
                    if (holder != null) {
                        String urlChain = holder.getUrl().getAuthChain();
                        AuthChainType act = holder.getConfig().getAuthChains().get(urlChain);
                        HashMap<String, Attribute> params = new HashMap<String, Attribute>();
                        ProxyUtil.loadParams(req, params);
                        if (req instanceof ProxyRequest) {
                            reqHolder = new RequestHolder(HTTPMethod.GET, params, finalURL, true, act.getName(), ((ProxyRequest) req).getQueryStringParams());
                        } else {
                            reqHolder = new RequestHolder(HTTPMethod.GET, params, finalURL, true, act.getName(), ((com.tremolosecurity.embedd.LocalSessionRequest) req).getQueryStringParams());
                        }
                        isForcedAuth = true;
                        sharedSession = sessionMgr.getSession(holder, ((HttpServletRequest) req), ((HttpServletResponse) resp), this.ctx);
                        if (sharedSession != null) {
                            pr.setSession(sharedSession);
                        }
                        Cookie lsessionCookieName = new Cookie("autoIdmSessionCookieName", holder.getApp().getCookieConfig().getSessionCookieName());
                        String domain = ProxyTools.getInstance().getCookieDomain(holder.getApp().getCookieConfig(), req);
                        if (domain != null) {
                            lsessionCookieName.setDomain(domain);
                        }
                        lsessionCookieName.setPath("/");
                        lsessionCookieName.setMaxAge(-1);
                        lsessionCookieName.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, lsessionCookieName, (HttpServletResponse) response);
                        }
                        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) response);
                        }
                    // resp.addCookie(appCookieName);
                    }
                }
            }
        }
        req.setAttribute(ProxyConstants.AUTOIDM_CFG, holder);
        req.setAttribute(ProxyConstants.TREMOLO_IS_FORCED_AUTH, isForcedAuth);
        req.setAttribute(ProxyConstants.TREMOLO_REQ_HOLDER, reqHolder);
        if (!resp.isCommitted()) {
            embSys.nextSys(pr, (HttpServletResponse) resp);
        }
    } catch (Exception e) {
        req.setAttribute("TREMOLO_ERROR_REQUEST_URL", req.getRequestURL().toString());
        req.setAttribute("TREMOLO_ERROR_EXCEPTION", e);
        logger.error("Could not process request", e);
        StringBuffer b = new StringBuffer();
        b.append(cfg.getAuthFormsPath()).append("error.jsp");
        req.getRequestDispatcher(b.toString()).forward(pr, resp);
    }
}
Also used : Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) NextEmbSys(com.tremolosecurity.embedd.NextEmbSys) RequestHolder(com.tremolosecurity.proxy.auth.RequestHolder) URL(java.net.URL) HttpServletRequest(javax.servlet.http.HttpServletRequest) LocalSessionRequest(com.tremolosecurity.embedd.LocalSessionRequest) UrlHolder(com.tremolosecurity.config.util.UrlHolder) AuthMechanism(com.tremolosecurity.proxy.auth.AuthMechanism) ProxyRequest(com.tremolosecurity.proxy.ProxyRequest) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) Cookie(javax.servlet.http.Cookie) SessionManager(com.tremolosecurity.proxy.SessionManager) HttpSession(javax.servlet.http.HttpSession) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) AuthController(com.tremolosecurity.proxy.auth.AuthController) ConfigManager(com.tremolosecurity.config.util.ConfigManager) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Aggregations

RequestHolder (com.tremolosecurity.proxy.auth.RequestHolder)20 UrlHolder (com.tremolosecurity.config.util.UrlHolder)18 AuthController (com.tremolosecurity.proxy.auth.AuthController)17 ServletException (javax.servlet.ServletException)14 AuthChainType (com.tremolosecurity.config.xml.AuthChainType)13 HashMap (java.util.HashMap)12 HttpServletRequest (javax.servlet.http.HttpServletRequest)12 HttpSession (javax.servlet.http.HttpSession)12 Attribute (com.tremolosecurity.saml.Attribute)11 AuthMechType (com.tremolosecurity.config.xml.AuthMechType)10 IOException (java.io.IOException)10 AuthInfo (com.tremolosecurity.proxy.auth.AuthInfo)7 LDAPAttribute (com.novell.ldap.LDAPAttribute)5 LDAPException (com.novell.ldap.LDAPException)5 ConfigManager (com.tremolosecurity.config.util.ConfigManager)5 Gson (com.google.gson.Gson)4 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)4 MyVDConnection (com.tremolosecurity.proxy.myvd.MyVDConnection)4 JSONParser (org.json.simple.parser.JSONParser)4 ParseException (org.json.simple.parser.ParseException)4