Search in sources :

Example 11 with AuthInfo

use of com.tremolosecurity.proxy.auth.AuthInfo 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());
        }
    }
}
Also used : Origin(com.webauthn4j.data.client.Origin) PublicKeyCredentialCreationOptions(com.webauthn4j.data.PublicKeyCredentialCreationOptions) ObjectConverter(com.webauthn4j.converter.util.ObjectConverter) ObjectOutputStream(java.io.ObjectOutputStream) PublicKeyCredentialUserEntity(com.webauthn4j.data.PublicKeyCredentialUserEntity) Challenge(com.webauthn4j.data.client.challenge.Challenge) DefaultChallenge(com.webauthn4j.data.client.challenge.DefaultChallenge) DefaultChallenge(com.webauthn4j.data.client.challenge.DefaultChallenge) WebAuthnException(com.webauthn4j.util.exception.WebAuthnException) CborConverter(com.webauthn4j.converter.util.CborConverter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) ServerProperty(com.webauthn4j.server.ServerProperty) PublicKeyCredentialRpEntity(com.webauthn4j.data.PublicKeyCredentialRpEntity) WebAuthnUserData(com.tremolosecurity.proxy.auth.webauthn.WebAuthnUserData) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) AuthController(com.tremolosecurity.proxy.auth.AuthController) JSONObject(org.json.simple.JSONObject) PublicKeyCredentialParameters(com.webauthn4j.data.PublicKeyCredentialParameters) AuthenticationExtensionsClientInputs(com.webauthn4j.data.extension.client.AuthenticationExtensionsClientInputs) RegistrationExtensionClientInput(com.webauthn4j.data.extension.client.RegistrationExtensionClientInput) AuthenticatorSelectionCriteria(com.webauthn4j.data.AuthenticatorSelectionCriteria) JSONParser(org.json.simple.parser.JSONParser)

Example 12 with AuthInfo

use of com.tremolosecurity.proxy.auth.AuthInfo 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);
}
Also used : RegistrationData(com.webauthn4j.data.RegistrationData) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) ServerProperty(com.webauthn4j.server.ServerProperty) ValidationException(com.webauthn4j.validator.exception.ValidationException) OpenUnisonAuthenticator(com.tremolosecurity.proxy.auth.webauthn.OpenUnisonAuthenticator) WebAuthnUserData(com.tremolosecurity.proxy.auth.webauthn.WebAuthnUserData) WebAuthnManager(com.webauthn4j.WebAuthnManager) RegistrationRequest(com.webauthn4j.data.RegistrationRequest) AuthController(com.tremolosecurity.proxy.auth.AuthController) ValidationException(com.webauthn4j.validator.exception.ValidationException) ServletException(javax.servlet.ServletException) WebAuthnException(com.webauthn4j.util.exception.WebAuthnException) DataConversionException(com.webauthn4j.converter.exception.DataConversionException) ParseException(org.json.simple.parser.ParseException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) WebAuthnException(com.webauthn4j.util.exception.WebAuthnException) JSONObject(org.json.simple.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) JSONParser(org.json.simple.parser.JSONParser) RegistrationParameters(com.webauthn4j.data.RegistrationParameters) DataConversionException(com.webauthn4j.converter.exception.DataConversionException) ObjectInputStream(java.io.ObjectInputStream) HashSet(java.util.HashSet)

Example 13 with AuthInfo

use of com.tremolosecurity.proxy.auth.AuthInfo in project OpenUnison by TremoloSecurity.

the class UserToJSON method doFilter.

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
    HttpSession session = request.getSession();
    AuthController actl = (AuthController) session.getAttribute(ProxyConstants.AUTH_CTL);
    if (actl == null) {
        throw new Exception("No authentication");
    }
    if (actl.getAuthInfo() != null) {
        AuthInfo authInfo = actl.getAuthInfo();
        if (authInfo.getAttribs().containsKey("UserJSON")) {
            authInfo.getAttribs().remove("UserJSON");
        }
        Gson gson = new Gson();
        String ret = gson.toJson(authInfo);
        if (doProxy) {
            chain.setNoProxy(false);
            authInfo.getAttribs().put("UserJSON", new Attribute("UserJSON", ret));
            chain.nextFilter(request, response, chain);
        } else {
            response.addHeader("UserJSON", ret);
            chain.setNoProxy(true);
        }
    }
}
Also used : AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) Attribute(com.tremolosecurity.saml.Attribute) HttpSession(javax.servlet.http.HttpSession) Gson(com.google.gson.Gson) AuthController(com.tremolosecurity.proxy.auth.AuthController)

Example 14 with AuthInfo

use of com.tremolosecurity.proxy.auth.AuthInfo in project OpenUnison by TremoloSecurity.

the class LastMile method doFilter.

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
    DateTime notBefore = new DateTime();
    notBefore = notBefore.minusSeconds(timeScew);
    DateTime notAfter = new DateTime();
    notAfter = notAfter.plusSeconds(timeScew);
    AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
    com.tremolosecurity.lastmile.LastMile lastmile = new com.tremolosecurity.lastmile.LastMile(request.getRequestURI(), notBefore, notAfter, userData.getAuthLevel(), userData.getAuthChain());
    Iterator<String> it = this.headers.keySet().iterator();
    while (it.hasNext()) {
        String fromUser = it.next();
        String toApp = this.headers.get(fromUser);
        Attribute attrib = userData.getAttribs().get(fromUser);
        request.removeHeader(toApp);
        if (logger.isDebugEnabled()) {
            logger.debug("Header to add : " + fromUser);
        }
        if (attrib != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Attribute " + fromUser + "='" + attrib.getValues() + "' for " + userData.getUserDN());
            }
            Attribute toAppAttrib = new Attribute(toApp);
            toAppAttrib.getValues().addAll(attrib.getValues());
            lastmile.getAttributes().add(toAppAttrib);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Attribute " + fromUser + " is not available for " + userData.getUserDN());
            }
        }
    }
    String encryptedXML = lastmile.generateLastMileToken(encKey);
    if (this.headerPrefix != null && !this.headerPrefix.isEmpty()) {
        StringBuffer b = new StringBuffer();
        b.append(this.headerPrefix).append(' ').append(encryptedXML);
        encryptedXML = b.toString();
    }
    request.addHeader(new Attribute(this.headerName, encryptedXML));
    // response.addHeader(this.headerName, requestKey.getEncrypted());
    chain.nextFilter(request, response, chain);
}
Also used : AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) Attribute(com.tremolosecurity.saml.Attribute) AuthController(com.tremolosecurity.proxy.auth.AuthController) DateTime(org.joda.time.DateTime)

Example 15 with AuthInfo

use of com.tremolosecurity.proxy.auth.AuthInfo in project OpenUnison by TremoloSecurity.

the class AnonAz method doFilter.

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
    // SharedSession.getSharedSession().getSession(req.getSession().getId());
    HttpSession session = request.getSession();
    AuthController actl = (AuthController) session.getAttribute(ProxyConstants.AUTH_CTL);
    if (actl == null) {
        actl = new AuthController();
        session.setAttribute(ProxyConstants.AUTH_CTL, actl);
    }
    if (actl.getAuthInfo() == null) {
        AuthInfo authInfo = new AuthInfo(this.rdn, (String) session.getAttribute(ProxyConstants.AUTH_MECH_NAME), "anonymous", 0);
        ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).setAuthInfo(authInfo);
        authInfo.getAttribs().put(this.uidAttr, new Attribute(this.uidAttr, this.uidVal));
        authInfo.getAttribs().put("objectClass", new Attribute("objectClass", GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getUserObjectClass()));
        actl.setAuthInfo(authInfo);
    }
    chain.nextFilter(request, response, chain);
}
Also used : AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) Attribute(com.tremolosecurity.saml.Attribute) HttpSession(javax.servlet.http.HttpSession) AuthController(com.tremolosecurity.proxy.auth.AuthController)

Aggregations

AuthInfo (com.tremolosecurity.proxy.auth.AuthInfo)71 AuthController (com.tremolosecurity.proxy.auth.AuthController)59 Attribute (com.tremolosecurity.saml.Attribute)46 LDAPAttribute (com.novell.ldap.LDAPAttribute)27 IOException (java.io.IOException)25 ServletException (javax.servlet.ServletException)24 HttpSession (javax.servlet.http.HttpSession)23 Gson (com.google.gson.Gson)22 LDAPException (com.novell.ldap.LDAPException)22 LDAPSearchResults (com.novell.ldap.LDAPSearchResults)22 LDAPEntry (com.novell.ldap.LDAPEntry)19 HashMap (java.util.HashMap)19 UrlHolder (com.tremolosecurity.config.util.UrlHolder)18 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)18 MalformedURLException (java.net.MalformedURLException)15 AuthChainType (com.tremolosecurity.config.xml.AuthChainType)14 ArrayList (java.util.ArrayList)14 AzSys (com.tremolosecurity.proxy.auth.AzSys)12 UnsupportedEncodingException (java.io.UnsupportedEncodingException)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)11