use of com.tremolosecurity.proxy.ProxyResponse in project OpenUnison by TremoloSecurity.
the class UriRequestProcess method postProcess.
@Override
public void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpFilterChain chain) throws Exception {
String proxyTo = holder.getUrl().getProxyTo();
HashMap<String, String> uriParams = (HashMap<String, String>) req.getAttribute("TREMOLO_URI_PARAMS");
Iterator<String> names;
StringBuffer proxyToURL = ProxyTools.getInstance().getGETUrl(req, holder, uriParams);
boolean first = true;
for (NVP p : req.getQueryStringParams()) {
if (first) {
proxyToURL.append('?');
first = false;
} else {
proxyToURL.append('&');
}
proxyToURL.append(p.getName()).append('=').append(URLEncoder.encode(p.getValue(), "UTF-8"));
}
com.tremolosecurity.proxy.HttpUpgradeRequestManager upgradeRequestManager = GlobalEntries.getGlobalEntries().getConfigManager().getUpgradeManager();
if (req.getHeader("Connection") != null && req.getHeader("Connection").getValues().get(0).equalsIgnoreCase("Upgrade")) {
ProxyResponse pr = (ProxyResponse) resp.getServletResponse();
upgradeRequestManager.proxyWebSocket(req, (HttpServletResponse) pr.getResponse(), proxyToURL.toString());
} else {
CloseableHttpClient httpclient = this.getHttp(proxyTo, req.getServletRequest(), holder);
// HttpGet httpget = new HttpGet(proxyToURL.toString());
// this.getHttpMethod(proxyToURL.toString());
HttpRequestBase httpMethod = new UriMethod(req.getMethod(), proxyToURL.toString());
req.setAttribute("TREMOLO_FINAL_URL", proxyToURL.toString());
setHeadersCookies(req, holder, httpMethod, proxyToURL.toString());
HttpContext ctx = (HttpContext) req.getSession().getAttribute(ProxySys.HTTP_CTX);
HttpResponse response = httpclient.execute(httpMethod, ctx);
postProcess(req, resp, holder, response, proxyToURL.toString(), chain, httpMethod);
}
}
use of com.tremolosecurity.proxy.ProxyResponse in project OpenUnison by TremoloSecurity.
the class AuthManagerImpl method finishSuccessfulLogin.
/* (non-Javadoc)
* @see com.tremolosecurity.proxy.auth.sys.AuthManager#finishSuccessfulLogin(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, com.tremolosecurity.config.util.UrlHolder, com.tremolosecurity.config.xml.AuthChainType, com.tremolosecurity.proxy.auth.RequestHolder, com.tremolosecurity.proxy.auth.AuthController, com.tremolosecurity.proxy.util.NextSys)
*/
@Override
public boolean finishSuccessfulLogin(HttpServletRequest req, HttpServletResponse resp, UrlHolder holder, AuthChainType act, RequestHolder reqHolder, AuthController actl, NextSys next) throws IOException, ServletException {
ConfigManager cfg = (ConfigManager) req.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);
AuthInfo ai = actl.getAuthInfo();
ai.setAuthComplete(true);
StringBuffer msg = new StringBuffer();
msg.append(act.getLevel()).append(" / ").append(act.getName());
AccessLog.log(AccessEvent.AuSuccess, holder.getApp(), req, ai, msg.toString());
StringBuffer redirURL;
if (reqHolder == null) {
Cookie sessionCookieName = new Cookie("autoIdmSessionCookieName", "DNE");
String domain = ProxyTools.getInstance().getCookieDomain(holder.getApp().getCookieConfig(), req);
if (domain != null) {
sessionCookieName.setDomain(domain);
}
sessionCookieName.setPath("/");
sessionCookieName.setMaxAge(0);
sessionCookieName.setSecure(false);
// resp.addCookie(sessionCookieName);
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", "DNE");
if (domain != null) {
appCookieName.setDomain(domain);
}
appCookieName.setPath("/");
appCookieName.setMaxAge(0);
appCookieName.setSecure(false);
// resp.addCookie(appCookieName);
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());
}
AuthMgrSys ams = new AuthMgrSys(null);
try {
ams.processAuthResp(req, resp, holder, new Boolean(true));
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
throw new ServletException("Could not initialize custom response", e);
}
return true;
} else {
switch(reqHolder.getMethod()) {
case GET:
redirURL = getGetRedirectURL(reqHolder);
Cookie sessionCookieName = new Cookie("autoIdmSessionCookieName", "DNE");
String domain = ProxyTools.getInstance().getCookieDomain(holder.getApp().getCookieConfig(), req);
if (domain != null) {
sessionCookieName.setDomain(domain);
}
sessionCookieName.setPath("/");
sessionCookieName.setMaxAge(0);
sessionCookieName.setSecure(false);
// resp.addCookie(sessionCookieName);
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", "DNE");
if (domain != null) {
appCookieName.setDomain(domain);
}
appCookieName.setPath("/");
appCookieName.setMaxAge(0);
appCookieName.setSecure(false);
// resp.addCookie(appCookieName);
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());
}
break;
case POST:
redirURL = new StringBuffer(holder.getConfig().getAuthFormsPath()).append("postPreservation.jsp");
break;
default:
redirURL = new StringBuffer(reqHolder.getURL());
}
req.setAttribute(AuthMgrSys.AU_RES, new Boolean(true));
AuthMgrSys ams = new AuthMgrSys(null);
try {
ams.processAuthResp(req, resp, holder, new Boolean(true));
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
throw new ServletException("Could not initialize custom response", e);
}
if (act.getCompliance() != null && act.getCompliance().isEnabled()) {
Attribute uidAttribute = actl.getAuthInfo().getAttribs().get(act.getCompliance().getUidAttributeName());
if (uidAttribute != null) {
String uid = uidAttribute.getValues().get(0);
User updateAttrs = new User(uid);
updateAttrs.getAttribs().put(act.getCompliance().getLastSucceedAttribute(), new Attribute(act.getCompliance().getLastSucceedAttribute(), Long.toString(new DateTime(DateTimeZone.UTC).getMillis())));
updateAttrs.getAttribs().put(act.getCompliance().getNumFailedAttribute(), new Attribute(act.getCompliance().getNumFailedAttribute(), "0"));
updateAttrs.getAttribs().put(act.getCompliance().getUidAttributeName(), new Attribute(act.getCompliance().getUidAttributeName(), uid));
if (GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getUserAttrbiutes() != null) {
for (String attrName : GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getUserAttrbiutes()) {
Attribute fromAuth = ai.getAttribs().get(attrName);
if (fromAuth != null) {
Attribute attrForWF = new Attribute(attrName);
attrForWF.getValues().addAll(fromAuth.getValues());
updateAttrs.getAttribs().put(attrName, attrForWF);
}
}
}
HashMap<String, Object> wfReq = new HashMap<String, Object>();
wfReq.put(ProvisioningParams.UNISON_EXEC_TYPE, ProvisioningParams.UNISON_EXEC_SYNC);
try {
holder.getConfig().getProvisioningEngine().getWorkFlow(act.getCompliance().getUpdateAttributesWorkflow()).executeWorkflow(updateAttrs, wfReq);
} catch (ProvisioningException e) {
throw new ServletException("Could not update successful login attribute", e);
}
}
}
// if
// (redirURL.toString().equalsIgnoreCase(req.getRequestURL().toString())
// || ( actl.getAuthSteps().size() == 1 && !
// req.getRequestURI().startsWith(cfg.getAuthPath()))) {
PostAuthSuccess postAuth = (PostAuthSuccess) req.getAttribute(PostAuthSuccess.POST_AUTH_ACTION);
if (postAuth != null) {
postAuth.runAfterSuccessfulAuthentication(req, resp, holder, act, reqHolder, actl, next);
} else if (!req.getRequestURI().startsWith(cfg.getAuthPath())) {
next.nextSys(req, resp);
} else {
resp.sendRedirect(redirURL.toString());
}
return false;
}
}
use of com.tremolosecurity.proxy.ProxyResponse 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);
*/
}
}
}
use of com.tremolosecurity.proxy.ProxyResponse in project OpenUnison by TremoloSecurity.
the class AuthMgrSys method proccessResponseResult.
private void proccessResponseResult(ServletRequest request, ServletResponse response, ResultGroupType resGrouping, boolean forceError, UrlHolder holder) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, ServletException {
String redir = null;
if (resGrouping == null) {
return;
}
Iterator<ResultType> it = resGrouping.getResult().iterator();
while (it.hasNext()) {
ResultType rt = it.next();
if (rt.getType().equals("redirect")) {
redir = rt.getValue();
} else if (rt.getType().equalsIgnoreCase("cookie")) {
String val = rt.getValue();
String name, value;
boolean isCustom = rt.getSource().equalsIgnoreCase("custom");
// failure cookie, so can not be based on the user
if (rt.getSource().equalsIgnoreCase("static") || isCustom) {
name = val.substring(0, val.indexOf('='));
value = val.substring(val.indexOf('=') + 1);
} else {
name = "";
value = "";
}
Cookie cookie = new Cookie(name, value);
String domain = getCookieDomain(holder, (HttpServletRequest) request);
if (domain != null) {
cookie.setDomain(domain);
}
// cookie.setDomain(((HttpServletRequest) request).getServerName());
cookie.setPath("/");
if (isCustom) {
CustomResult cr = (CustomResult) Class.forName(cookie.getValue()).newInstance();
cr.createResultCookie(cookie, (HttpServletRequest) request, (HttpServletResponse) response);
}
((HttpServletResponse) response).addCookie(cookie);
}
}
if (redir != null) {
((ProxyResponse) response).removeHeader("Location");
((HttpServletResponse) response).sendRedirect(redir);
} else {
if (forceError) {
((HttpServletResponse) response).sendError(401);
}
}
}
Aggregations