use of com.tremolosecurity.config.util.UrlHolder in project OpenUnison by TremoloSecurity.
the class Saml2SingleLogout method handleLogout.
@Override
public void handleLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException {
if (request == null || response == null) {
// do nothing
return;
}
String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(digSigAlg);
if (xmlAlg == null) {
throw new ServletException("Unknown Signiture algorithm : '" + digSigAlg + "'");
}
String javaAlg = SAML2Auth.javaDigSigAlgs.get(digSigAlg);
UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
ConfigManager cfgMgr = holder.getConfig();
XMLObject xmlObj = null;
byte[] idBytes = new byte[20];
String respToKey = request.getParameter("logoutreq");
if (respToKey != null) {
LogoutResponseBuilder lrb = new LogoutResponseBuilder();
LogoutResponse lr = lrb.buildObject();
lr.setIssueInstant(Instant.now());
lr.setInResponseTo(respToKey);
lr.setDestination(logoutURL);
random.nextBytes(idBytes);
String id = "f" + Hex.encodeHexString(idBytes);
lr.setID(id);
IssuerBuilder ib = new IssuerBuilder();
Issuer issuer = ib.buildObject();
issuer.setValue(assertionConsumerServiceURL);
lr.setIssuer(issuer);
StatusCodeBuilder scb = new StatusCodeBuilder();
StatusCode statusCode = scb.buildObject();
statusCode.setValue("urn:oasis:names:tc:SAML:2.0:status:Success");
StatusBuilder sb = new StatusBuilder();
Status status = sb.buildObject();
status.setStatusCode(statusCode);
lr.setStatus(status);
xmlObj = lr;
} else {
LogoutRequestBuilder lrb = new LogoutRequestBuilder();
LogoutRequest lr = lrb.buildObject();
lr.setIssueInstant(Instant.now());
lr.setDestination(logoutURL);
random.nextBytes(idBytes);
String id = "f" + Hex.encodeHexString(idBytes);
lr.setID(id);
IssuerBuilder ib = new IssuerBuilder();
Issuer issuer = ib.buildObject();
issuer.setValue(assertionConsumerServiceURL);
lr.setIssuer(issuer);
NameIDBuilder nidbpb = new NameIDBuilder();
NameID nid = nidbpb.buildObject();
// nidp.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
nid.setFormat(nameIDFormat);
// nid.setSPNameQualifier(assertionConsumerServiceURL);
nid.setValue(nameID);
lr.setNameID(nid);
SessionIndexBuilder sib = new SessionIndexBuilder();
SessionIndex si = sib.buildObject();
si.setValue(sessionIndex);
lr.getSessionIndexes().add(si);
xmlObj = lr;
}
try {
String xml = OpenSAMLUtils.xml2str(xmlObj);
xml = xml.substring(xml.indexOf("?>") + 2);
if (logger.isDebugEnabled()) {
logger.debug("=======AuthnRequest============");
logger.debug(xml);
logger.debug("=======AuthnRequest============");
}
byte[] bxml = xml.getBytes("UTF-8");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DeflaterOutputStream compressor = new DeflaterOutputStream(baos, new Deflater(Deflater.BEST_COMPRESSION, true));
compressor.write(bxml);
compressor.flush();
compressor.close();
String b64 = new String(Base64.encodeBase64(baos.toByteArray()));
StringBuffer redirURL = new StringBuffer();
StringBuffer query = new StringBuffer();
idBytes = new byte[20];
random.nextBytes(idBytes);
if (respToKey != null) {
query.append("SAMLResponse=");
} else {
query.append("SAMLRequest=");
}
query.append(URLEncoder.encode(b64, "UTF-8")).append("&RelayState=").append(URLEncoder.encode(Hex.encodeHexString(idBytes), "UTF-8"));
query.append("&SigAlg=").append(URLEncoder.encode(xmlAlg, "UTF-8"));
// http://www.w3.org/2000/09/xmldsig#rsa-sha1
java.security.Signature signer = java.security.Signature.getInstance(javaAlg);
PrivateKey sigKey = cfgMgr.getPrivateKey(signingKeyAlias);
if (sigKey == null) {
throw new ServletException("Signing Key : '" + signingKeyAlias + "' not found");
}
signer.initSign(sigKey);
signer.update(query.toString().getBytes("UTF-8"));
String base64Sig = new String(Base64.encodeBase64(signer.sign()));
query.append("&Signature=").append(URLEncoder.encode(base64Sig, "UTF-8"));
redirURL.append(logoutURL).append("?").append(query.toString());
if (logger.isDebugEnabled()) {
logger.debug("Logout URL : '" + redirURL.toString() + "'");
}
// ((ProxyResponse) response).removeHeader("Location");
response.sendRedirect(redirURL.toString());
} catch (Exception e) {
throw new ServletException("Could not generate logout request", e);
}
}
use of com.tremolosecurity.config.util.UrlHolder 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.config.util.UrlHolder in project OpenUnison by TremoloSecurity.
the class HideCookie method doFilter.
@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
String proxyTo = holder.getUrl().getProxyTo();
HashMap<String, String> uriParams = new HashMap<String, String>();
uriParams.put("fullURI", request.getRequestURI());
Iterator<String> names;
StringBuffer proxyToURL = ProxyTools.getInstance().getGETUrl(request, holder, uriParams);
if (!holder.isOverrideHost()) {
String surl = proxyToURL.toString();
String proto = surl.substring(0, surl.indexOf("://") + 3);
String url = surl.substring(surl.indexOf('/', 9));
proxyToURL.setLength(0);
proxyToURL.append(proto);
Attribute host = request.getHeader("Host");
if (host == null) {
host = request.getHeader("host");
}
proxyToURL.append(host.getValues().get(0));
proxyToURL.append(url);
}
URL url = new URL(proxyToURL.toString());
CookieManager cookieJar = (CookieManager) request.getSession().getAttribute(TREMOLO_HIDE_COOKIE_JAR);
if (cookieJar == null) {
cookieJar = new CookieManager();
request.getSession().setAttribute(TREMOLO_HIDE_COOKIE_JAR, cookieJar);
}
Map<String, List<String>> cookies = cookieJar.get(url.toURI(), new HashMap<String, List<String>>());
for (String headerName : cookies.keySet()) {
for (String val : cookies.get(headerName)) {
if (headerName.equalsIgnoreCase("cookie")) {
String name = val.substring(0, val.indexOf('='));
String value = val.substring(val.indexOf('=') + 1);
request.addCookie(new Cookie(name, value));
}
}
}
chain.nextFilter(request, response, chain);
StringBuffer b = new StringBuffer();
ArrayList<String> cookieHeaders = new ArrayList<String>();
for (Cookie cookie : response.getCookies()) {
HttpCookie httpCookie = new HttpCookie(cookie.getName(), cookie.getValue());
if (cookie.getSecure()) {
httpCookie.setSecure(true);
}
if (cookie.getComment() != null) {
httpCookie.setComment(cookie.getComment());
}
if (cookie.getMaxAge() >= 0) {
httpCookie.setMaxAge(cookie.getMaxAge());
}
if (cookie.getPath() != null) {
httpCookie.setPath(cookie.getPath());
}
httpCookie.setVersion(cookie.getVersion());
cookieHeaders.add(httpCookie.toString());
}
Map<String, List<String>> respHeaders = new HashMap<String, List<String>>();
respHeaders.put("Set-Cookie", cookieHeaders);
cookieJar.put(url.toURI(), respHeaders);
response.getCookies().clear();
}
use of com.tremolosecurity.config.util.UrlHolder 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.config.util.UrlHolder in project OpenUnison by TremoloSecurity.
the class UserOnlyAuthMech 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);
RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
String uidAttr = "uid";
if (authParams.get("uidAttr") != null) {
uidAttr = authParams.get("uidAttr").getValues().get(0);
}
boolean uidIsFilter = false;
if (authParams.get("uidIsFilter") != null) {
uidIsFilter = authParams.get("uidIsFilter").getValues().get(0).equalsIgnoreCase("true");
}
String noUserJSP = authParams.get("noUserJSP").getValues().get(0);
String filter = "";
if (uidIsFilter) {
StringBuffer b = new StringBuffer();
int lastIndex = 0;
int index = uidAttr.indexOf('$');
while (index >= 0) {
b.append(uidAttr.substring(lastIndex, index));
lastIndex = uidAttr.indexOf('}', index) + 1;
String reqName = uidAttr.substring(index + 2, lastIndex - 1);
b.append(req.getParameter(reqName));
index = uidAttr.indexOf('$', index + 1);
}
b.append(uidAttr.substring(lastIndex));
filter = b.toString();
} else {
StringBuffer b = new StringBuffer();
b.append("(").append(uidAttr).append("=").append(req.getParameter("user")).append(")");
filter = b.toString();
}
String urlChain = holder.getUrl().getAuthChain();
AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
AuthMechType amt = act.getAuthMech().get(as.getId());
try {
LDAPSearchResults res = myvd.search(AuthUtil.getChainRoot(cfgMgr, act), 2, filter, new ArrayList<String>());
if (res.hasMore()) {
LDAPEntry entry = res.next();
Iterator<LDAPAttribute> it = entry.getAttributeSet().iterator();
AuthInfo authInfo = new AuthInfo(entry.getDN(), (String) session.getAttribute(ProxyConstants.AUTH_MECH_NAME), act.getName(), act.getLevel());
((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).setAuthInfo(authInfo);
while (it.hasNext()) {
LDAPAttribute attrib = it.next();
Attribute attr = new Attribute(attrib.getName());
String[] vals = attrib.getStringValueArray();
for (int i = 0; i < vals.length; i++) {
attr.getValues().add(vals[i]);
}
authInfo.getAttribs().put(attr.getName(), attr);
}
as.setSuccess(true);
} else {
as.setSuccess(false);
resp.sendRedirect(noUserJSP);
return;
}
} catch (LDAPException e) {
logger.error("Could not find user", e);
as.setSuccess(false);
resp.sendRedirect(noUserJSP);
return;
}
String redirectToURL = req.getParameter("target");
if (redirectToURL != null && !redirectToURL.isEmpty()) {
reqHolder.setURL(redirectToURL);
}
holder.getConfig().getAuthManager().nextAuth(req, resp, session, false);
}
Aggregations