use of com.tremolosecurity.proxy.auth.AuthInfo in project OpenUnison by TremoloSecurity.
the class ScaleJSOperator method doFilter.
@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
Gson gson = new Gson();
request.getServletRequest().setAttribute("com.tremolosecurity.unison.proxy.noRedirectOnError", "com.tremolosecurity.unison.proxy.noRedirectOnError");
try {
if (request.getRequestURI().endsWith("/ops/config")) {
ScaleJSUtils.addCacheHeaders(response);
response.setContentType("application/json");
response.getWriter().println(gson.toJson(this.config).trim());
} else if (request.getRequestURI().endsWith("/ops/search")) {
runSearch(request, response, gson);
} else if (request.getRequestURI().endsWith("/ops/user") && request.getMethod().equalsIgnoreCase("GET")) {
lookupUser(request, response, gson);
} else if (request.getRequestURI().endsWith("/ops/user") && request.getMethod().equalsIgnoreCase("POST")) {
AuthInfo loggedIn = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
String json = new String((byte[]) request.getAttribute(ProxySys.MSG_BODY));
OpsUpdate updateInput = gson.fromJson(json, OpsUpdate.class);
if (this.scaleMainConfig == null) {
UrlHolder holder = GlobalEntries.getGlobalEntries().getConfigManager().findURL(this.scaleMainURL);
for (HttpFilter filter : holder.getFilterChain()) {
if (filter instanceof ScaleMain) {
ScaleMain scaleMain = (ScaleMain) filter;
this.scaleMainConfig = scaleMain.scaleConfig;
}
}
}
String dn = updateInput.getDn();
LDAPSearchResults res = GlobalEntries.getGlobalEntries().getConfigManager().getMyVD().search(dn, 0, "(objectClass=*)", new ArrayList<String>());
if (!res.hasMore()) {
throw new Exception("Could not locate user '" + dn + "'");
}
LDAPEntry entry = res.next();
AuthInfo userData = new AuthInfo();
userData.setUserDN(entry.getDN());
LDAPAttributeSet attrs = entry.getAttributeSet();
for (Object obj : attrs) {
LDAPAttribute attr = (LDAPAttribute) obj;
Attribute attrib = new Attribute(attr.getName());
String[] vals = attr.getStringValueArray();
for (String val : vals) {
attrib.getValues().add(val);
}
userData.getAttribs().put(attrib.getName(), attrib);
}
ScaleError errors = new ScaleError();
Set<String> allowedAttrs = null;
if (this.scaleMainConfig.getUiDecisions() != null) {
allowedAttrs = this.scaleMainConfig.getUiDecisions().availableAttributes(userData, request.getServletRequest());
}
HashMap<String, String> values = new HashMap<String, String>();
boolean ok = true;
for (Attribute attr : updateInput.getAttributes()) {
String attributeName = attr.getName();
if (allowedAttrs == null || allowedAttrs.contains(attributeName)) {
String value = attr.getValues().get(0);
if (this.scaleMainConfig.getAttributes().get(attributeName) == null) {
errors.getErrors().add("Invalid attribute : '" + attributeName + "'");
ok = false;
} else if (this.scaleMainConfig.getAttributes().get(attributeName).isReadOnly()) {
errors.getErrors().add("Attribute is read only : '" + this.scaleMainConfig.getAttributes().get(attributeName).getDisplayName() + "'");
ok = false;
} else if (this.scaleMainConfig.getAttributes().get(attributeName).isRequired() && value.length() == 0) {
errors.getErrors().add("Attribute is required : '" + this.scaleMainConfig.getAttributes().get(attributeName).getDisplayName() + "'");
ok = false;
} else if (this.scaleMainConfig.getAttributes().get(attributeName).getMinChars() > 0 && this.scaleMainConfig.getAttributes().get(attributeName).getMinChars() > value.length()) {
errors.getErrors().add(this.scaleMainConfig.getAttributes().get(attributeName).getDisplayName() + " must have at least " + this.scaleMainConfig.getAttributes().get(attributeName).getMinChars() + " characters");
ok = false;
} else if (this.scaleMainConfig.getAttributes().get(attributeName).getMaxChars() > 0 && this.scaleMainConfig.getAttributes().get(attributeName).getMaxChars() < value.length()) {
errors.getErrors().add(this.scaleMainConfig.getAttributes().get(attributeName).getDisplayName() + " must have at most " + this.scaleMainConfig.getAttributes().get(attributeName).getMaxChars() + " characters");
ok = false;
} else if (this.scaleMainConfig.getAttributes().get(attributeName).getPattern() != null) {
try {
Matcher m = this.scaleMainConfig.getAttributes().get(attributeName).getPattern().matcher(value);
if (m == null || !m.matches()) {
ok = false;
}
} catch (Exception e) {
ok = false;
}
if (!ok) {
errors.getErrors().add("Attribute value not valid : '" + this.scaleMainConfig.getAttributes().get(attributeName).getDisplayName() + "' - " + this.scaleMainConfig.getAttributes().get(attributeName).getRegExFailedMsg());
}
}
values.put(attributeName, value);
}
}
for (String attrName : this.scaleMainConfig.getAttributes().keySet()) {
if (this.scaleMainConfig.getAttributes().get(attrName).isRequired() && !values.containsKey(attrName) && (allowedAttrs == null || allowedAttrs.contains(attrName))) {
errors.getErrors().add("Attribute is required : '" + this.scaleMainConfig.getAttributes().get(attrName).getDisplayName() + "'");
ok = false;
}
}
if (updateInput.getReason() == null || updateInput.getReason().trim().isEmpty()) {
errors.getErrors().add("Reason For Updates Required");
ok = false;
}
if (ok) {
ConfigManager cfgMgr = GlobalEntries.getGlobalEntries().getConfigManager();
WFCall wfCall = new WFCall();
wfCall.setName(this.scaleMainConfig.getWorkflowName());
wfCall.setReason(updateInput.getReason());
wfCall.setUidAttributeName(this.scaleMainConfig.getUidAttributeName());
wfCall.setRequestor(loggedIn.getAttribs().get(this.scaleMainConfig.getUidAttributeName()).getValues().get(0));
TremoloUser tu = new TremoloUser();
tu.setUid(userData.getAttribs().get(this.scaleMainConfig.getUidAttributeName()).getValues().get(0));
for (String name : values.keySet()) {
tu.getAttributes().add(new Attribute(name, values.get(name)));
}
tu.getAttributes().add(new Attribute(this.scaleMainConfig.getUidAttributeName(), userData.getAttribs().get(this.scaleMainConfig.getUidAttributeName()).getValues().get(0)));
wfCall.setUser(tu);
try {
com.tremolosecurity.provisioning.workflow.ExecuteWorkflow exec = new com.tremolosecurity.provisioning.workflow.ExecuteWorkflow();
exec.execute(wfCall, GlobalEntries.getGlobalEntries().getConfigManager());
} catch (Exception e) {
logger.error("Could not update user", e);
response.setStatus(500);
ScaleError error = new ScaleError();
error.getErrors().add("Please contact your system administrator");
ScaleJSUtils.addCacheHeaders(response);
response.getWriter().print(gson.toJson(error).trim());
response.getWriter().flush();
}
} else {
response.setStatus(500);
ScaleJSUtils.addCacheHeaders(response);
response.getWriter().print(gson.toJson(errors).trim());
response.getWriter().flush();
}
}
} catch (Throwable t) {
logger.error("Could not execute request", t);
response.setStatus(500);
ScaleError error = new ScaleError();
error.getErrors().add("Operation not supported");
ScaleJSUtils.addCacheHeaders(response);
response.getWriter().print(gson.toJson(error).trim());
response.getWriter().flush();
}
}
use of com.tremolosecurity.proxy.auth.AuthInfo 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);
}
use of com.tremolosecurity.proxy.auth.AuthInfo in project OpenUnison by TremoloSecurity.
the class PreAuthFilter method doFilter.
@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);
List<Cookie> cookies = null;
if (userData.getAuthLevel() > 0 && userData.isAuthComplete()) {
UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
HttpSession session = request.getSession();
String uid = (String) session.getAttribute("TREMOLO_PRE_AUTH");
if (uid == null || !uid.equals(userData.getUserDN())) {
session.setAttribute("TREMOLO_PRE_AUTH", userData.getUserDN());
HashMap<String, String> uriParams = new HashMap<String, String>();
uriParams.put("fullURI", this.uri);
UrlHolder remHolder = cfg.findURL(this.url);
org.apache.http.client.methods.HttpRequestBase method = null;
if (this.postSAML) {
PrivateKey pk = holder.getConfig().getPrivateKey(this.keyAlias);
java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(this.keyAlias);
Saml2Assertion assertion = new Saml2Assertion(userData.getAttribs().get(this.nameIDAttribute).getValues().get(0), pk, cert, null, this.issuer, this.assertionConsumerURL, this.audience, this.signAssertion, this.signResponse, false, this.nameIDType, this.authnCtxClassRef);
String respXML = "";
try {
respXML = assertion.generateSaml2Response();
} catch (Exception e) {
throw new ServletException("Could not generate SAMLResponse", e);
}
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
String base64 = Base64.encodeBase64String(respXML.getBytes("UTF-8"));
formparams.add(new BasicNameValuePair("SAMLResponse", base64));
if (this.relayState != null && !this.relayState.isEmpty()) {
formparams.add(new BasicNameValuePair("RelayState", this.relayState));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost post = new HttpPost(this.assertionConsumerURL);
post.setEntity(entity);
method = post;
} else {
HttpGet get = new HttpGet(remHolder.getProxyURL(uriParams));
method = get;
}
LastMileUtil.addLastMile(cfg, userData.getAttribs().get(loginAttribute).getValues().get(0), this.loginAttribute, method, lastMileKeyAlias, true);
BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(cfg.getHttpClientSocketRegistry());
try {
CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(cfg.getGlobalHttpClientConfig()).build();
HttpResponse resp = httpclient.execute(method);
if (resp.getStatusLine().getStatusCode() == 500) {
BufferedReader in = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
StringBuffer error = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
error.append(line).append('\n');
}
logger.warn("Pre-Auth Failed : " + error);
}
org.apache.http.Header[] headers = resp.getAllHeaders();
StringBuffer stmp = new StringBuffer();
cookies = new ArrayList<Cookie>();
for (org.apache.http.Header header : headers) {
if (header.getName().equalsIgnoreCase("set-cookie") || header.getName().equalsIgnoreCase("set-cookie2")) {
// System.out.println(header.getValue());
String cookieVal = header.getValue();
/*if (cookieVal.endsWith("HttpOnly")) {
cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly"));
}
//System.out.println(cookieVal);*/
List<HttpCookie> cookiesx = HttpCookie.parse(cookieVal);
for (HttpCookie cookie : cookiesx) {
String cookieFinalName = cookie.getName();
if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) {
stmp.setLength(0);
stmp.append("JSESSIONID").append('-').append(holder.getApp().getName().replaceAll(" ", "|"));
cookieFinalName = stmp.toString();
}
// logger.info("Adding cookie name '" + cookieFinalName + "'='" + cookie.getValue() + "'");
Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue());
respcookie.setComment(cookie.getComment());
if (cookie.getDomain() != null) {
// respcookie.setDomain(cookie.getDomain());
}
respcookie.setMaxAge((int) cookie.getMaxAge());
respcookie.setPath(cookie.getPath());
respcookie.setSecure(cookie.getSecure());
respcookie.setVersion(cookie.getVersion());
cookies.add(respcookie);
if (request.getCookieNames().contains(respcookie.getName())) {
request.removeCookie(cookieFinalName);
}
request.addCookie(new Cookie(cookie.getName(), cookie.getValue()));
}
}
}
} finally {
bhcm.shutdown();
}
}
}
chain.nextFilter(request, response, chain);
if (cookies != null) {
for (Cookie cookie : cookies) {
response.addCookie(cookie);
}
}
}
use of com.tremolosecurity.proxy.auth.AuthInfo in project OpenUnison by TremoloSecurity.
the class OAuth2JWT method loadUnlinkedUser.
public static void loadUnlinkedUser(HttpSession session, String noMatchOU, String uidAttr, AuthChainType act, Map jwtNVP, String defaultObjectClass) {
String uid = (String) jwtNVP.get(uidAttr);
StringBuffer dn = new StringBuffer();
dn.append(uidAttr).append('=').append(uid).append(",ou=").append(noMatchOU).append(",").append(GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getLdapRoot());
AuthInfo authInfo = new AuthInfo(dn.toString(), (String) session.getAttribute(ProxyConstants.AUTH_MECH_NAME), act.getName(), act.getLevel());
((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).setAuthInfo(authInfo);
for (Object o : jwtNVP.keySet()) {
String s = (String) o;
Attribute attr;
Object oAttr = jwtNVP.get(s);
if (logger.isDebugEnabled()) {
logger.debug(s + " type - '" + oAttr.getClass().getName() + "'");
}
if (oAttr instanceof JSONArray) {
attr = new Attribute(s);
for (Object ox : ((JSONArray) oAttr)) {
attr.getValues().add((String) ox);
}
} else {
attr = new Attribute(s, oAttr.toString());
}
authInfo.getAttribs().put(attr.getName(), attr);
}
authInfo.getAttribs().put("objectClass", new Attribute("objectClass", defaultObjectClass));
}
use of com.tremolosecurity.proxy.auth.AuthInfo in project OpenUnison by TremoloSecurity.
the class CallWorkflow method doFilter.
@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
request.setAttribute("com.tremolosecurity.unison.proxy.noRedirectOnError", "com.tremolosecurity.unison.proxy.noRedirectOnError");
if (request.getServletRequest().getMethod().equalsIgnoreCase("POST")) {
AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
response.setContentType("application/json");
String json = new String((byte[]) request.getAttribute(ProxySys.MSG_BODY));
Gson gson = new Gson();
WFCall wfCall = gson.fromJson(json.toString(), WFCall.class);
if (!allowedWorkflows.contains(wfCall.getName())) {
logger.warn(wfCall.getName() + " not authorized");
response.getServletResponse().sendError(403);
} else {
try {
com.tremolosecurity.provisioning.workflow.ExecuteWorkflow exec = new com.tremolosecurity.provisioning.workflow.ExecuteWorkflow();
exec.execute(wfCall, GlobalEntries.getGlobalEntries().getConfigManager());
} catch (Throwable t) {
logger.error("Error executing workflow", t);
response.getServletResponse().sendError(500);
}
}
} else {
logger.warn("Invalid HTTPS Method : '" + request.getServletRequest().getMethod() + "'");
response.getServletResponse().sendError(500);
}
}
Aggregations