use of com.tremolosecurity.config.xml.AuthMechType in project OpenUnison by TremoloSecurity.
the class WebAuthn method doGet.
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException {
if (request.getParameter("requestOptions") != null && request.getParameter("requestOptions").equalsIgnoreCase("true")) {
AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
// SharedSession.getSharedSession().getSession(req.getSession().getId());
HttpSession session = ((HttpServletRequest) request).getSession();
UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
RequestHolder reqHolder = ((AuthController) request.getSession().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());
HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
String attributeName = authParams.get("attribute").getValues().get(0);
String encryptionKeyName = authParams.get("encryptionKeyName").getValues().get(0);
if (userData.getAttribs().get(attributeName) == null) {
StringBuilder sb = new StringBuilder();
sb.append("User '").append(userData.getUserDN()).append("' does not have attribute '").append(attributeName).append("'");
logger.warn(sb.toString());
as.setExecuted(true);
as.setSuccess(false);
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
return;
}
WebAuthnUserData webauthnUser = WebAuthnUtils.lookupWebAuthnUserData(userData, attributeName, encryptionKeyName);
if (webauthnUser == null) {
throw new ServletException("No webauthn user data, can not happen");
}
try {
Challenge challenge = new DefaultChallenge();
JSONObject resp = new JSONObject();
JSONObject publicKey = new JSONObject();
resp.put("publicKey", publicKey);
JSONArray allowedCredentials = new JSONArray();
publicKey.put("allowedCredentials", allowedCredentials);
for (Authenticator auth : webauthnUser.getAuthenticators()) {
byte[] credentialId = auth.getAttestedCredentialData().getCredentialId();
JSONObject credential = new JSONObject();
allowedCredentials.add(credential);
credential.put("type", "public-key");
credential.put("id", Base64UrlUtil.encodeToString(credentialId));
}
publicKey.put("challenge", Base64UrlUtil.encodeToString(challenge.getValue()));
publicKey.put("rpId", WebAuthnRegistration.getRpId(request));
publicKey.put("timeout", 30000);
publicKey.put("userVerification", authParams.get("userVerificationRequirement").getValues().get(0));
ServerProperty serverProperty = new ServerProperty(new Origin(request.getRequestURL().toString()), WebAuthnRegistration.getRpId(request), challenge, webauthnUser.getId());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = null;
byte[] yourBytes = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(serverProperty);
out.flush();
yourBytes = bos.toByteArray();
} finally {
try {
bos.close();
} catch (IOException ex) {
// ignore close exception
}
}
resp.put("serverProperty", java.util.Base64.getUrlEncoder().encodeToString(yourBytes));
response.getWriter().println(resp.toString());
} catch (Exception e) {
throw new ServletException(e);
}
} else {
AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
// SharedSession.getSharedSession().getSession(req.getSession().getId());
HttpSession session = ((HttpServletRequest) request).getSession();
UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
RequestHolder reqHolder = ((AuthController) request.getSession().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());
HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
String formURI = authParams.get("formURI").getValues().get(0);
request.getRequestDispatcher(formURI).forward(request, response);
}
}
use of com.tremolosecurity.config.xml.AuthMechType in project OpenUnison by TremoloSecurity.
the class WebAuthn method doPost.
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException {
if (request.getParameter("webauthnResponse") != null) {
AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
// SharedSession.getSharedSession().getSession(req.getSession().getId());
HttpSession session = ((HttpServletRequest) request).getSession();
UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
RequestHolder reqHolder = ((AuthController) request.getSession().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());
HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
ByteArrayInputStream bais = new ByteArrayInputStream(Base64UrlUtil.decode((String) request.getParameter("serverProperty")));
ObjectInputStream ois = new ObjectInputStream(bais);
ServerProperty serverProperty = null;
try {
serverProperty = (ServerProperty) ois.readObject();
} catch (ClassNotFoundException | IOException e) {
throw new ServletException(e);
}
String attributeName = authParams.get("attribute").getValues().get(0);
String encryptionKeyName = authParams.get("encryptionKeyName").getValues().get(0);
Authenticator auth = null;
if (userData.getAttribs().get(attributeName) == null) {
StringBuilder sb = new StringBuilder();
sb.append("User '").append(userData.getUserDN()).append("' does not have attribute '").append(attributeName).append("'");
logger.warn(sb.toString());
as.setExecuted(true);
as.setSuccess(false);
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
return;
}
WebAuthnUserData webauthnUser = WebAuthnUtils.lookupWebAuthnUserData(userData, attributeName, encryptionKeyName);
if (webauthnUser == null) {
throw new ServletException("No webauthn user data, can not happen");
}
JSONObject webauthnResp = null;
try {
webauthnResp = (JSONObject) new JSONParser().parse(request.getParameter("webauthnResponse"));
} catch (ParseException e) {
throw new ServletException("could not parse webauthn response", e);
}
byte[] credentialId = java.util.Base64.getUrlDecoder().decode((String) webauthnResp.get("credential_id"));
byte[] userHandle = java.util.Base64.getUrlDecoder().decode((String) webauthnResp.get("userHandle"));
;
byte[] authenticatorData = java.util.Base64.getUrlDecoder().decode((String) webauthnResp.get("authenticatorData"));
byte[] clientDataJSON = java.util.Base64.getUrlDecoder().decode((String) webauthnResp.get("clientDataJSON"));
String clientExtensionJSON = (String) webauthnResp.get("clientExtResults");
byte[] signature = java.util.Base64.getUrlDecoder().decode((String) webauthnResp.get("signature"));
if (!Arrays.equals(userHandle, webauthnUser.getId())) {
StringBuilder sb = new StringBuilder();
sb.append("User '").append(userData.getUserDN()).append("' credential not owned by the client");
logger.warn(sb.toString());
as.setExecuted(true);
as.setSuccess(false);
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
return;
}
auth = null;
for (Authenticator checkUser : webauthnUser.getAuthenticators()) {
if (Arrays.equals(checkUser.getAttestedCredentialData().getCredentialId(), credentialId)) {
auth = checkUser;
}
}
if (auth == null) {
StringBuilder sb = new StringBuilder();
sb.append("User '").append(userData.getUserDN()).append("' does not have a credential associated with '").append((String) webauthnResp.get("credential_id")).append("'");
logger.warn(sb.toString());
as.setExecuted(true);
as.setSuccess(false);
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
return;
}
AuthenticationRequest authenticationRequest = new AuthenticationRequest(credentialId, userHandle, authenticatorData, clientDataJSON, clientExtensionJSON, signature);
AuthenticationParameters authenticationParameters = new AuthenticationParameters(serverProperty, auth, null, false, true);
WebAuthnManager webAuthnManager = WebAuthnManager.createNonStrictWebAuthnManager();
AuthenticationData authenticationData;
try {
authenticationData = webAuthnManager.parse(authenticationRequest);
} catch (DataConversionException e) {
StringBuilder sb = new StringBuilder();
sb.append("User '").append(userData.getUserDN()).append("' could not parse authentication data with credential '").append((String) webauthnResp.get("credential_id")).append("'");
logger.warn(sb.toString(), e);
as.setExecuted(true);
as.setSuccess(false);
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
return;
}
try {
webAuthnManager.validate(authenticationData, authenticationParameters);
} catch (ValidationException e) {
StringBuilder sb = new StringBuilder();
sb.append("User '").append(userData.getUserDN()).append("' could not validate authentication data with credential '").append((String) webauthnResp.get("credential_id")).append("'");
logger.warn(sb.toString(), e);
as.setExecuted(true);
as.setSuccess(false);
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
return;
}
as.setExecuted(true);
as.setSuccess(true);
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
} else {
// redirect the user to the correct URL
AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
// SharedSession.getSharedSession().getSession(req.getSession().getId());
HttpSession session = ((HttpServletRequest) request).getSession();
UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
RequestHolder reqHolder = ((AuthController) request.getSession().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());
response.sendRedirect(holder.getConfig().getAuthMechs().get(amt.getName()).getUri());
return;
}
}
use of com.tremolosecurity.config.xml.AuthMechType in project OpenUnison by TremoloSecurity.
the class OTPAuth method doPost.
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException {
if (request.getParameter("code") == null) {
this.doGet(request, response, as);
return;
}
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) request.getSession().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());
Attribute attr = authParams.get("keyName");
if (attr == null) {
throw new ServletException("keyName not present");
}
SecretKey key = this.cfgMgr.getSecretKey(attr.getValues().get(0));
if (key == null) {
throw new ServletException("Key '" + attr.getValues().get(0) + "' does not exist");
}
int windowSize = 3;
attr = authParams.get("windowSize");
if (attr == null) {
logger.warn("No windowSize set");
} else {
windowSize = Integer.parseInt(attr.getValues().get(0));
}
attr = authParams.get("attributeName");
if (attr == null) {
throw new ServletException("attributeName not present");
}
String attributeName = attr.getValues().get(0);
AuthController ac = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL));
attr = ac.getAuthInfo().getAttribs().get(attributeName);
if (attr == null) {
if (logger.isDebugEnabled()) {
logger.info("Attribute '" + attributeName + "' not present");
}
as.setSuccess(false);
} else {
try {
String keyjson = attr.getValues().get(0);
if (logger.isDebugEnabled()) {
logger.debug("token json : '" + keyjson + "'");
}
Gson gson = new Gson();
Token token = gson.fromJson(new String(Base64.decode(keyjson)), Token.class);
byte[] iv = org.bouncycastle.util.encoders.Base64.decode(token.getIv());
IvParameterSpec spec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, spec);
byte[] encBytes = org.bouncycastle.util.encoders.Base64.decode(token.getEncryptedRequest());
String totpJson = new String(cipher.doFinal(encBytes));
TOTPKey totp = gson.fromJson(totpJson, TOTPKey.class);
GoogleAuthenticatorConfigBuilder b = new GoogleAuthenticatorConfigBuilder();
b.setWindowSize(windowSize);
GoogleAuthenticatorConfig cfg = b.build();
GoogleAuthenticator ga = new GoogleAuthenticator(cfg);
String code = request.getParameter("code");
if (code == null) {
as.setSuccess(false);
} else {
as.setSuccess(ga.authorize(totp.getSecretKey(), Integer.parseInt(code)));
}
String redirectToURL = request.getParameter("target");
if (redirectToURL != null && !redirectToURL.isEmpty()) {
reqHolder.setURL(redirectToURL);
}
} catch (Exception e) {
as.setSuccess(false);
logger.error("Could not decrypt key", e);
}
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
}
}
use of com.tremolosecurity.config.xml.AuthMechType in project OpenUnison by TremoloSecurity.
the class AuthManagerImpl method buildMechList.
private static List<AuthMechType> buildMechList(List<AuthMechType> origMechs, ConfigManager cfg) {
List<AuthMechType> newList = new ArrayList<AuthMechType>();
for (AuthMechType amt : origMechs) {
MechanismType mt = cfg.getAuthMechs().get(amt.getName());
if (mt != null && mt.getClassName().trim().equalsIgnoreCase("com.tremolosecurity.proxy.auth.IncludeChain")) {
ParamWithValueType pt = amt.getParams().getParam().get(0);
String chainName = "";
if (pt.getValue() != null && !pt.getValue().isBlank()) {
chainName = pt.getValue();
} else {
chainName = pt.getValueAttribute();
}
AuthChainType toInclude = cfg.getAuthChains().get(chainName);
if (toInclude == null) {
logger.warn(new StringBuilder().append("Could not load chain '").append(chainName).append("', forcing to fail").toString());
toInclude = cfg.getAuthFailChain();
}
newList.addAll(buildMechList(toInclude.getAuthMech(), cfg));
} else {
newList.add(amt);
}
}
return newList;
}
use of com.tremolosecurity.config.xml.AuthMechType in project OpenUnison by TremoloSecurity.
the class CrlChecker method doGet.
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException {
// SharedSession.getSharedSession().getSession(req.getSession().getId());
HttpSession session = ((HttpServletRequest) request).getSession();
UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
RequestHolder reqHolder = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
Attribute issuersParam = authParams.get("issuer");
HashSet<X500Principal> issuers = new HashSet<X500Principal>();
for (String dn : issuersParam.getValues()) {
issuers.add(new X500Principal(dn));
}
String urlChain = holder.getUrl().getAuthChain();
AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
AuthMechType amt = act.getAuthMech().get(as.getId());
X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
if (certs == null) {
if (amt.getRequired().equals("required")) {
as.setSuccess(false);
}
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
return;
}
X509Certificate cert = certs[0];
DN dn = new DN(cert.getSubjectX500Principal().getName());
Vector<RDN> rdns = dn.getRDNs();
HashMap<String, String> subject = new HashMap<String, String>();
for (RDN rdn : rdns) {
subject.put(rdn.getType(), rdn.getValue());
}
// Load SANS
try {
if (cert.getSubjectAlternativeNames() != null) {
java.util.Collection altNames = cert.getSubjectAlternativeNames();
Iterator iter = altNames.iterator();
while (iter.hasNext()) {
java.util.List item = (java.util.List) iter.next();
Integer type = (Integer) item.get(0);
subject.put(SAN_NAMES[type.intValue()], item.get(1).toString());
}
}
} catch (CertificateParsingException e1) {
throw new ServletException("Could not parse certificate", e1);
}
for (CertificateExtractSubjectAttribute cesa : this.extracts) {
cesa.addSubjects(subject, certs);
}
MyVDConnection myvd = cfgMgr.getMyVD();
// HttpSession session = (HttpSession) req.getAttribute(ConfigFilter.AUTOIDM_SESSION);//((HttpServletRequest) req).getSession(); //SharedSession.getSharedSession().getSession(req.getSession().getId());
boolean OK = false;
boolean certOK = true;
int i = 0;
for (X509Certificate certx : certs) {
if (issuers.contains(certx.getIssuerX500Principal())) {
OK = true;
}
if (certOK) {
for (CRLManager crlM : this.crls) {
X509Certificate issuer = null;
if (i + 1 < certs.length) {
issuer = certs[i + 1];
} else {
try {
Enumeration<String> enumer = cfgMgr.getKeyStore().aliases();
while (enumer.hasMoreElements()) {
String alias = enumer.nextElement();
X509Certificate lissuer = (X509Certificate) cfgMgr.getKeyStore().getCertificate(alias);
if (lissuer != null && lissuer.getSubjectX500Principal().equals(certs[i].getIssuerX500Principal())) {
try {
certs[i].verify(lissuer.getPublicKey());
issuer = lissuer;
} catch (Exception e) {
logger.warn("Issuer with wrong public key", e);
}
}
}
} catch (KeyStoreException e) {
throw new ServletException("Could not process CRLs", e);
}
}
if (issuer != null) {
if (!crlM.isValid(certx, issuer)) {
certOK = false;
break;
}
} else {
logger.warn("No issuer! not performing CRL check");
}
}
}
}
if (!OK || !certOK) {
as.setSuccess(false);
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
return;
}
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 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(subject.get(reqName));
index = uidAttr.indexOf('$', index + 1);
}
b.append(uidAttr.substring(lastIndex));
filter = b.toString();
} else {
StringBuffer b = new StringBuffer();
if (subject.get(uidAttr) == null) {
filter = "(!(objectClass=*))";
} else {
filter = equal(uidAttr, subject.get(uidAttr)).toString();
}
}
String rdnAttr = authParams.get("rdnAttribute").getValues().get(0);
ArrayList<String> rdnAttrs = new ArrayList<String>();
StringTokenizer toker = new StringTokenizer(rdnAttr, ",", false);
while (toker.hasMoreTokens()) {
rdnAttrs.add(toker.nextToken());
}
String defaultOC = authParams.get("defaultOC").getValues().get(0);
String dnLabel = authParams.get("dnLabel").getValues().get(0);
as.setSuccess(true);
try {
LDAPSearchResults res = myvd.search(AuthUtil.getChainRoot(cfgMgr, act), 2, filter, new ArrayList<String>());
if (res.hasMore()) {
createUserFromDir(session, act, res);
} else {
createUnlinkedUser(session, act, rdnAttrs, dnLabel, defaultOC, subject);
}
} catch (LDAPException e) {
if (e.getResultCode() == 32) {
createUnlinkedUser(session, act, rdnAttrs, dnLabel, defaultOC, subject);
} else {
throw new ServletException("Could not search for user", e);
}
}
holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
/*try {
for (String oid : cert.getCriticalExtensionOIDs()) {
byte[] derEncoded = cert.getExtensionValue(oid);
//System.out.println("critical : " + oid);
}
for (String oid : cert.getNonCriticalExtensionOIDs()) {
byte[] derEncoded = cert.getExtensionValue(oid);
//System.out.println("noncritical : " + oid);
ASN1InputStream ain = new ASN1InputStream(new ByteArrayInputStream(derEncoded));
DEREncodable obj = ain.readObject();
do {
DEROctetString deros = (DEROctetString) obj;
//System.out.println(deros.toString());
X509Extension extension = new X509Extension(false,deros);
//System.out.println(extension.toString());
obj = ain.readObject();
} while (obj != null);
}
} catch (Exception e) {
throw new ServletException("Error parsing certificate",e);
}*/
}
Aggregations