use of com.tremolosecurity.proxy.auth.webauthn.WebAuthnUserData in project OpenUnison by TremoloSecurity.
the class WebAuthnRegistration method doFilter.
@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
request.getServletRequest().setAttribute("com.tremolosecurity.unison.proxy.noRedirectOnError", "com.tremolosecurity.unison.proxy.noRedirectOnError");
if (request.getMethod().equalsIgnoreCase("GET")) {
if (request.getRequestURI().endsWith("/credentialCreateOptions")) {
ObjectConverter oc = new ObjectConverter();
String rpId = getRpId(request.getServletRequest());
AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
WebAuthnUserData webAuthnUserData = WebAuthnUtils.lookupWebAuthnUserData(userData, challengeStoreAttribute, encryptionKeyName);
if (webAuthnUserData == null) {
// no data yet, let's create
webAuthnUserData = new WebAuthnUserData(userData.getAttribs().get(this.uidAttributeName).getValues().get(0));
WebAuthnUtils.storeWebAuthnUserData(webAuthnUserData, this.encryptionKeyName, userData, this.workflowName, this.uidAttributeName, this.challengeStoreAttribute);
}
Challenge challenge = new DefaultChallenge();
CborConverter cbor = oc.getCborConverter();
String b64UrlChallenge = Base64UrlUtil.encodeToString(challenge.getValue());
AuthenticatorSelectionCriteria authenticatorSelectionCriteria = new AuthenticatorSelectionCriteria(authenticatorAttachment, requireResisentKey, userVerificationRequirement);
PublicKeyCredentialParameters publicKeyCredentialParameters = new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.ES256);
String b64UrlId = Base64.getUrlEncoder().encodeToString(webAuthnUserData.getId());
ServerProperty serverProperty = new ServerProperty(new Origin(request.getRequestURL().toString()), rpId, challenge, webAuthnUserData.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
}
}
request.getSession().setAttribute("tremolo.io/webauthn/serverProperty", serverProperty);
PublicKeyCredentialUserEntity publicKeyCredentialUserEntity = new PublicKeyCredentialUserEntity(webAuthnUserData.getId(), webAuthnUserData.getDisplayName(), webAuthnUserData.getDisplayName());
AuthenticationExtensionsClientInputs<RegistrationExtensionClientInput> extensions = new AuthenticationExtensionsClientInputs<>();
PublicKeyCredentialCreationOptions credentialCreationOptions = new PublicKeyCredentialCreationOptions(new PublicKeyCredentialRpEntity(rpId, rpId), publicKeyCredentialUserEntity, challenge, Collections.singletonList(publicKeyCredentialParameters), null, Collections.emptyList(), authenticatorSelectionCriteria, AttestationConveyancePreference.NONE, extensions);
ObjectMapper mapper = new ObjectMapper();
// mapper.writeValueAsString(credentialCreationOptions);
String publecCredentialCreationOptionsJson = oc.getJsonConverter().writeValueAsString(credentialCreationOptions);
JSONObject root = (JSONObject) new JSONParser().parse(publecCredentialCreationOptionsJson);
root.put("challenge", b64UrlChallenge);
((JSONObject) root.get("user")).put("id", b64UrlId);
JSONObject publicKeyRoot = new JSONObject();
publicKeyRoot.put("publicKey", root);
publicKeyRoot.put("serverProperty", Base64.getUrlEncoder().encodeToString(yourBytes));
response.getWriter().println(publicKeyRoot.toString());
} else {
StringBuilder createCredentialURL = new StringBuilder(request.getRequestURL().toString());
createCredentialURL.append("/credentialCreateOptions");
request.setAttribute("tremolo.io/webauthn/challengeurl", createCredentialURL.toString());
createCredentialURL = new StringBuilder(request.getRequestURL().toString());
createCredentialURL.append("/finishregistration");
request.setAttribute("tremolo.io/webauthn/finishregistration", createCredentialURL.toString());
request.getRequestDispatcher(this.challengeURI).forward(request.getServletRequest(), response.getServletResponse());
}
} else if (request.getMethod().equalsIgnoreCase("POST")) {
try {
storeCredential(request);
} catch (WebAuthnException e) {
JSONObject resp = new JSONObject();
resp.put("error", e.getMessage());
response.sendError(500);
response.getWriter().println(resp.toString());
} catch (Throwable t) {
JSONObject resp = new JSONObject();
logger.error("Could not store credential", t);
resp.put("error", "There was an error, please contanct your system administrator");
response.sendError(500);
response.getWriter().println(resp.toString());
}
}
}
use of com.tremolosecurity.proxy.auth.webauthn.WebAuthnUserData in project OpenUnison by TremoloSecurity.
the class WebAuthnRegistration method storeCredential.
private void storeCredential(HttpFilterRequest request) throws ParseException, IOException, ClassNotFoundException, ServletException, Exception {
byte[] requestBytes = (byte[]) request.getAttribute(ProxySys.MSG_BODY);
String requestString = new String(requestBytes, StandardCharsets.UTF_8);
JSONObject root = (JSONObject) new JSONParser().parse(requestString);
if (root.get("label") == null || ((String) root.get("label")).isEmpty()) {
throw new WebAuthnException("Label required");
}
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.getUrlDecoder().decode((String) root.get("serverProperty")));
ObjectInputStream ois = new ObjectInputStream(bais);
ServerProperty serverProperty = (ServerProperty) ois.readObject();
byte[] attestationObject = Base64.getUrlDecoder().decode((String) root.get("attestationObject"));
byte[] clientDataJSON = Base64.getUrlDecoder().decode((String) root.get("clientDataJSON"));
String clientExtensionJSON = (String) root.get("clientExtResults");
Set<String> transports = new HashSet<String>();
// expectations
boolean userVerificationRequired = false;
boolean userPresenceRequired = true;
RegistrationRequest registrationRequest = new RegistrationRequest(attestationObject, clientDataJSON, clientExtensionJSON, transports);
RegistrationParameters registrationParameters = new RegistrationParameters(serverProperty, userVerificationRequired, userPresenceRequired);
RegistrationData registrationData;
WebAuthnManager webAuthnManager = WebAuthnManager.createNonStrictWebAuthnManager();
try {
registrationData = webAuthnManager.parse(registrationRequest);
} catch (DataConversionException e) {
// If you would like to handle WebAuthn data structure parse error, please catch DataConversionException
throw e;
}
try {
webAuthnManager.validate(registrationData, registrationParameters);
} catch (ValidationException e) {
// If you would like to handle WebAuthn data validation error, please catch ValidationException
throw e;
}
OpenUnisonAuthenticator authenticator = new OpenUnisonAuthenticator((String) root.get("label"), registrationData.getAttestationObject().getAuthenticatorData().getAttestedCredentialData(), registrationData.getAttestationObject().getAttestationStatement(), registrationData.getAttestationObject().getAuthenticatorData().getSignCount());
AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
WebAuthnUserData webAuthnUserData = WebAuthnUtils.lookupWebAuthnUserData(userData, this.challengeStoreAttribute, this.encryptionKeyName);
if (webAuthnUserData == null) {
throw new Exception("No webauthn user data, should not happen");
}
for (OpenUnisonAuthenticator auth : webAuthnUserData.getAuthenticators()) {
if (auth.getLabel().equals(authenticator.getLabel())) {
throw new WebAuthnException("Label already exists, choose another label");
}
}
webAuthnUserData.getAuthenticators().add(authenticator);
WebAuthnUtils.storeWebAuthnUserData(webAuthnUserData, encryptionKeyName, userData, workflowName, uidAttributeName, challengeStoreAttribute);
}
use of com.tremolosecurity.proxy.auth.webauthn.WebAuthnUserData 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.proxy.auth.webauthn.WebAuthnUserData 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;
}
}
Aggregations