use of com.tremolosecurity.proxy.myvd.MyVDConnection in project OpenUnison by TremoloSecurity.
the class IWAAuth method doGet.
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException {
String header = request.getHeader("Authorization");
HttpSession session = ((HttpServletRequest) request).getSession();
HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
if (header == null) {
sendFail(request, response, as);
return;
}
SpnegoPrincipal principal = null;
for (String realm : this.domains.keySet()) {
SpnegoAuthenticator authenticator = this.domains.get(realm);
final SpnegoHttpServletResponse spnegoResponse = new SpnegoHttpServletResponse((HttpServletResponse) response);
try {
principal = authenticator.authenticate(request, spnegoResponse);
break;
} catch (GSSException gsse) {
logger.error("Could not authenticate IWA user", gsse);
} catch (Throwable t) {
logger.error("Could not authenticate IWA user", t);
}
}
if (principal == null) {
sendFail(request, response, as);
return;
}
MyVDConnection myvd = cfgMgr.getMyVD();
UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
// holder.getConfig().getAuthChains().get(urlChain);
AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
AuthMechType amt = act.getAuthMech().get(as.getId());
try {
StringBuffer b = new StringBuffer();
b.append("(userPrincipalName=").append(principal.toString()).append(")");
LDAPSearchResults res = myvd.search(AuthUtil.getChainRoot(cfgMgr, act), 2, equal("userPrincipalName", principal.toString()).toString(), new ArrayList<String>());
if (res.hasMore()) {
logger.info("Loading user attributes");
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);
request.getSession().removeAttribute("TREMOLO_IWA_CHECKED");
} else {
logger.info("user not found, failing");
as.setSuccess(false);
}
} catch (LDAPException e) {
logger.error("Could not authenticate user", e);
as.setSuccess(false);
sendFail(request, response, as);
return;
/*if (amt.getRequired().equals("required")) {
session.setAttribute(AuthSys.AUTH_RES, false);
}*/
}
holder.getConfig().getAuthManager().nextAuth(request, response, session, true);
}
use of com.tremolosecurity.proxy.myvd.MyVDConnection in project OpenUnison by TremoloSecurity.
the class PersistentCookie method doWork.
private void doWork(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException {
as.setExecuted(true);
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) request).getSession();
UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
if (holder == null) {
throw new ServletException("Holder is null");
}
RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
String urlChain = holder.getUrl().getAuthChain();
AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
Attribute attr = authParams.get("cookieName");
if (attr == null) {
throw new ServletException("No cookie name specified");
}
String cookieName = attr.getValues().get(0);
boolean useSSLSessionID;
attr = authParams.get("useSSLSessionID");
if (attr == null) {
useSSLSessionID = false;
} else {
useSSLSessionID = attr.getValues().get(0).equalsIgnoreCase("true");
}
attr = authParams.get("millisToLive");
if (attr == null) {
throw new ServletException("No milliseconds to live specified");
}
long millisToLive = Long.parseLong(attr.getValues().get(0));
attr = authParams.get("keyAlias");
if (attr == null) {
throw new ServletException("No key name specified");
}
String keyAlias = attr.getValues().get(0);
Cookie authCookie = null;
if (request.getCookies() == null) {
as.setSuccess(false);
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
return;
}
for (Cookie cookie : request.getCookies()) {
if (cookie.getName().equalsIgnoreCase(cookieName)) {
authCookie = cookie;
break;
}
}
if (authCookie == null) {
as.setSuccess(false);
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
return;
}
com.tremolosecurity.lastmile.LastMile lastmile = new com.tremolosecurity.lastmile.LastMile();
SecretKey key = this.cfgMgr.getSecretKey(keyAlias);
if (key == null) {
throw new ServletException("Secret key '" + keyAlias + "' does not exist");
}
try {
String cookieVal = authCookie.getValue();
if (cookieVal.startsWith("\"")) {
cookieVal = cookieVal.substring(1, cookieVal.length() - 1);
}
lastmile.loadLastMielToken(cookieVal, key);
} catch (Exception e) {
logger.warn("Could not decrypt cookie", e);
as.setSuccess(false);
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
return;
}
if (!lastmile.isValid()) {
logger.warn("Cookie no longer valid");
as.setSuccess(false);
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
return;
}
boolean found = false;
boolean validip = false;
boolean validSslSessionId = !useSSLSessionID;
String dn = null;
for (Attribute attrib : lastmile.getAttributes()) {
if (attrib.getName().equalsIgnoreCase("CLIENT_IP")) {
validip = attrib.getValues().get(0).equals(request.getRemoteAddr());
} else if (attrib.getName().equalsIgnoreCase("DN")) {
dn = attrib.getValues().get(0);
} else if (attrib.getName().equalsIgnoreCase("SSL_SESSION_ID")) {
Object sessionID = request.getAttribute("javax.servlet.request.ssl_session_id");
if (sessionID instanceof byte[]) {
sessionID = new String(Base64.encodeBase64((byte[]) sessionID));
}
validSslSessionId = attrib.getValues().get(0).equals(sessionID);
}
}
if (dn != null && validip && validSslSessionId) {
try {
LDAPSearchResults res = myvd.search(dn, 0, "(objectClass=*)", 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 ldapattr = it.next();
attr = new Attribute(ldapattr.getName());
String[] vals = ldapattr.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);
}
} catch (LDAPException e) {
if (e.getResultCode() != LDAPException.INVALID_CREDENTIALS) {
logger.error("Could not authenticate user", e);
}
as.setSuccess(false);
}
} else {
as.setSuccess(false);
}
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
}
use of com.tremolosecurity.proxy.myvd.MyVDConnection in project OpenUnison by TremoloSecurity.
the class SecretQuestionAuth method doPost.
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException {
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) request).getSession();
UrlHolder holder = (UrlHolder) request.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 alg = authParams.get("alg").getValues().get(0);
String salt = authParams.get("salt").getValues().get(0);
String urlChain = holder.getUrl().getAuthChain();
AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
AuthMechType amt = act.getAuthMech().get(as.getId());
ArrayList<SecretQuestion> questions = (ArrayList<SecretQuestion>) request.getSession(true).getAttribute("TREMOLO_SECRET_ANSWERS");
if (questions == null) {
this.doGet(request, response, as);
return;
}
int i = 0;
StringBuffer b = new StringBuffer();
for (SecretQuestion sq : questions) {
b.setLength(0);
b.append("answer").append(i);
String answer = request.getParameter(b.toString());
if (!sq.checkAnswer(alg, answer, salt)) {
if (amt.getRequired().equals("required")) {
as.setSuccess(false);
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
return;
}
}
i++;
}
as.setSuccess(true);
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
}
use of com.tremolosecurity.proxy.myvd.MyVDConnection in project OpenUnison by TremoloSecurity.
the class BasicAuth method checkBasicAuth.
public static boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response, ConfigManager cfgMgr, BasicAuthImpl authImpl, AuthStep as) throws IOException, ServletException {
String basicHdr = request.getHeader("Authorization");
HttpSession session = ((HttpServletRequest) request).getSession();
HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
String realmName = authParams.get("realmName").getValues().get(0);
String uidAttr = "uid";
if (authParams.get("uidAttr") != null) {
uidAttr = authParams.get("uidAttr").getValues().get(0);
}
if (basicHdr == null) {
as.setExecuted(false);
sendFail(response, realmName);
return false;
}
basicHdr = basicHdr.substring(basicHdr.indexOf(' ') + 1);
String headerVal = new String(Base64.decode(basicHdr));
String userName = headerVal.substring(0, headerVal.indexOf(':'));
String password = headerVal.substring(headerVal.indexOf(':') + 1);
MyVDConnection myvd = cfgMgr.getMyVD();
UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
String urlChain = holder.getUrl().getAuthChain();
AuthChainType act = holder.getConfig().getAuthChains().get(urlChain);
AuthMechType amt = act.getAuthMech().get(as.getId());
try {
authImpl.doAuth(request, session, uidAttr, userName, password, myvd, act, amt, as, cfgMgr);
} catch (LDAPException e) {
if (e.getResultCode() != LDAPException.INVALID_CREDENTIALS) {
logger.error("Could not authenticate user", e);
}
as.setExecuted(true);
as.setSuccess(false);
sendFail(response, realmName);
return false;
/*if (amt.getRequired().equals("required")) {
session.setAttribute(AuthSys.AUTH_RES, false);
}*/
}
return true;
}
use of com.tremolosecurity.proxy.myvd.MyVDConnection in project OpenUnison by TremoloSecurity.
the class SAML2Auth method doPost.
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp, AuthStep as) throws ServletException, IOException {
MyVDConnection myvd = cfgMgr.getMyVD();
// HttpSession session = (HttpSession)
// req.getAttribute(ConfigFilter.AUTOIDM_SESSION);//((HttpServletRequest)
// req).getSession();
// //SharedSession.getSharedSession().getSession(req.getSession().getId());
// SharedSession.getSharedSession().getSession(req.getSession().getId());
HttpSession session = ((HttpServletRequest) req).getSession();
UrlHolder holder = (UrlHolder) req.getAttribute(ProxyConstants.AUTOIDM_CFG);
String urlChain = holder.getUrl().getAuthChain();
AuthChainType act = holder.getConfig().getAuthChains().get(urlChain);
AuthInfo userData = ((AuthController) req.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
if (userData.isAuthComplete() && userData.getAuthLevel() > 0) {
// Session is already set, just redirect to relay state
String relayState = this.getFinalURL(req, resp);
if (relayState == null) {
throw new ServletException("No RelayState or default RelayState");
}
resp.sendRedirect(relayState);
return;
}
if (as == null) {
// this is a special case - idp initiated means there's no context
ArrayList<AuthStep> auths = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthSteps();
int id = 0;
for (AuthMechType amt : act.getAuthMech()) {
AuthStep asx = new AuthStep();
asx.setId(id);
asx.setExecuted(false);
asx.setRequired(amt.getRequired().equals("required"));
asx.setSuccess(false);
auths.add(asx);
id++;
}
as = auths.get(0);
}
HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
String defaultOC = authParams.get("defaultOC").getValues().get(0);
String spEncKey = null;
if (authParams.get("spEncKey") != null) {
spEncKey = authParams.get("spEncKey").getValues().get(0);
}
RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
AuthMechType amt = act.getAuthMech().get(as.getId());
List<String> sigCertNames = authParams.get("idpSigKeyName").getValues();
List<X509Certificate> sigCerts = new ArrayList<X509Certificate>();
boolean isMultiIdp = authParams.get("isMultiIdP") != null && authParams.get("isMultiIdP").getValues().get(0).equalsIgnoreCase("true");
String ldapAttrib = authParams.get("ldapAttribute").getValues().get(0);
String dnLabel = authParams.get("dnOU").getValues().get(0);
String samlResp = req.getParameter("SAMLResponse");
String xml = null;
xml = new String(Base64.decodeBase64(samlResp), "UTF-8");
boolean assertionSigned = true;
if (authParams.get("assertionsSigned") != null) {
assertionSigned = Boolean.parseBoolean(authParams.get("assertionsSigned").getValues().get(0));
}
boolean responseSigned = false;
if (authParams.get("responsesSigned") != null) {
responseSigned = Boolean.parseBoolean(authParams.get("responsesSigned").getValues().get(0));
}
boolean assertionEncrypted = false;
if (authParams.get("assertionEncrypted") != null) {
assertionEncrypted = Boolean.parseBoolean(authParams.get("assertionEncrypted").getValues().get(0));
}
if (logger.isDebugEnabled()) {
logger.debug("=========saml2resp============");
logger.debug(xml);
logger.debug("=========saml2resp============");
}
xml = xml.replaceAll("<!--.*-->", "");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Element root = builder.parse(new InputSource(new StringReader(xml))).getDocumentElement();
Response samlResponse = (Response) XMLObjectSupport.getUnmarshaller(root).unmarshall(root);
if (isMultiIdp) {
try {
String dn = authParams.get("idpDir").getValues().get(0);
LDAPSearchResults res = cfgMgr.getMyVD().search(dn, 2, equal("issuer", samlResponse.getIssuer().getValue()).toString(), new ArrayList<String>());
if (!res.hasMore()) {
throw new ServletException("No IdP found");
}
LDAPEntry entry = res.next();
java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509");
sigCerts.add((java.security.cert.X509Certificate) cf.generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(entry.getAttribute("idpSig").getStringValue()))));
} catch (LDAPException e) {
throw new ServletException("Could not load IdP data", e);
} catch (CertificateException e) {
throw new ServletException("Could not load IdP data", e);
}
} else {
for (String sigCertName : sigCertNames) {
sigCerts.add(cfgMgr.getCertificate(sigCertName));
}
}
if (responseSigned) {
if (samlResponse.getSignature() != null) {
boolean foundSigned = false;
for (X509Certificate sigCert : sigCerts) {
if (sigCert != null) {
BasicCredential sigCred = new BasicCredential(sigCert.getPublicKey());
sigCred.setUsageType(UsageType.SIGNING);
try {
SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator();
profileValidator.validate(samlResponse.getSignature());
SignatureValidator.validate(samlResponse.getSignature(), sigCred);
foundSigned = true;
} catch (org.opensaml.xmlsec.signature.support.SignatureException se) {
}
}
}
if (!foundSigned) {
throw new ServletException("could not validate response");
}
} else {
throw new Exception("Response not signed");
}
}
Assertion assertion = null;
if (samlResponse.getEncryptedAssertions().size() > 0) {
try {
EncryptedAssertion encAssertion = samlResponse.getEncryptedAssertions().get(0);
PrivateKey privKey = this.cfgMgr.getPrivateKey(spEncKey);
PublicKey pubKey = this.cfgMgr.getCertificate(spEncKey).getPublicKey();
Credential credential = new BasicCredential(pubKey, privKey);
StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(credential);
Decrypter decrypter = new Decrypter(null, resolver, new InlineEncryptedKeyResolver());
decrypter.setRootInNewDocument(true);
assertion = decrypter.decrypt(encAssertion);
} catch (Exception e) {
throw new ServletException("Error decrypting assertion", e);
}
} else {
if (assertionEncrypted) {
throw new Exception("Assertion not encrypted");
}
if (samlResponse.getAssertions().size() == 0) {
throw new Exception("No assertions found");
}
assertion = (Assertion) samlResponse.getAssertions().get(0);
}
if (assertionSigned) {
if (assertion.getSignature() != null) {
boolean foundSigned = false;
for (X509Certificate sigCert : sigCerts) {
if (sigCert != null) {
BasicCredential sigCred = new BasicCredential(sigCert.getPublicKey());
sigCred.setUsageType(UsageType.SIGNING);
try {
SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator();
profileValidator.validate(assertion.getSignature());
SignatureValidator.validate(assertion.getSignature(), sigCred);
foundSigned = true;
} catch (org.opensaml.xmlsec.signature.support.SignatureException se) {
}
}
}
if (!foundSigned) {
throw new ServletException("Assertion can not be validated with a trusted certificate");
}
} else {
throw new Exception("No assertion signature");
}
}
// If it made it here, the assertion is valid, lets check the authncontextclassref
Attribute authnContextClassRef = authParams.get("authCtxRef");
if (authnContextClassRef != null && authnContextClassRef.getValues().size() > 0 && !authnContextClassRef.getValues().get(0).isEmpty() && !authnContextClassRef.getValues().get(0).equalsIgnoreCase("none") && (assertion.getAuthnStatements() == null || assertion.getAuthnStatements().size() == 0 || assertion.getAuthnStatements().get(0).getAuthnContext() == null || assertion.getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef() == null || assertion.getAuthnStatements().get(0).getAuthnContext() == null || assertion.getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef() == null || assertion.getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef().getURI() == null || !assertion.getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef().getURI().equalsIgnoreCase(authnContextClassRef.getValues().get(0)))) {
logger.warn("Can not validate the authentication context classref");
as.setSuccess(false);
holder.getConfig().getAuthManager().nextAuth(req, resp, session, false);
return;
}
try {
if (authParams.get("dontLinkToLDAP") == null || authParams.get("dontLinkToLDAP").getValues().get(0).equalsIgnoreCase("false")) {
StringBuffer filter = new StringBuffer();
filter.append('(').append(ldapAttrib).append('=').append(assertion.getSubject().getNameID().getValue()).append(')');
LDAPSearchResults res = myvd.search(AuthUtil.getChainRoot(cfgMgr, act), 2, filter.toString(), new ArrayList<String>());
if (res.hasMore()) {
createUserFromDir(session, act, ldapAttrib, assertion, res);
} else {
createUnlinkedUser(session, act, ldapAttrib, dnLabel, defaultOC, assertion);
}
} else {
createUnlinkedUser(session, act, ldapAttrib, dnLabel, defaultOC, assertion);
}
} catch (LDAPException e) {
if (e.getResultCode() == 32) {
createUnlinkedUser(session, act, ldapAttrib, dnLabel, defaultOC, assertion);
} else {
throw e;
}
}
// logout management
Attribute logoutURLAttr = authParams.get("idpRedirLogoutURL");
if (logoutURLAttr != null && logoutURLAttr.getValues().size() > 0 && !logoutURLAttr.getValues().get(0).isEmpty() && authParams.get("spSigKey") != null && authParams.get("spSigKey").getValues().size() > 0) {
String logoutURL = logoutURLAttr.getValues().get(0);
String sessionIndex = assertion.getAuthnStatements().get(0).getSessionIndex();
String nameID = assertion.getSubject().getNameID().getValue();
String nameIDFormat = assertion.getSubject().getNameID().getFormat();
Saml2SingleLogout handler = new Saml2SingleLogout(logoutURL, sessionIndex, nameID, nameIDFormat, samlResponse.getDestination(), authParams.get("spSigKey").getValues().get(0), authParams.get("sigAlg").getValues().get(0), authParams.get("entityID").getValues().get(0));
LogoutUtil.addLogoutHandler(req, handler);
}
as.setSuccess(true);
} catch (Exception e) {
logger.error("Error Parsing Assertion", e);
throw new ServletException("error parsing assertion", e);
}
holder.getConfig().getAuthManager().nextAuth(req, resp, session, false);
}
Aggregations