Search in sources :

Example 1 with PublicKeyCredentialRpEntity

use of com.webauthn4j.data.PublicKeyCredentialRpEntity 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 2 with PublicKeyCredentialRpEntity

use of com.webauthn4j.data.PublicKeyCredentialRpEntity in project webauthn4j by webauthn4j.

the class WebAuthnModelAuthenticator method makeCredential.

public MakeCredentialResponse makeCredential(MakeCredentialRequest makeCredentialRequest, RegistrationEmulationOption registrationEmulationOption) {
    PublicKeyCredentialRpEntity rpEntity = makeCredentialRequest.getRpEntity();
    // Check if all the supplied parameters are syntactically well-formed and of the correct length.
    // If not, return an error code equivalent to "UnknownError" and terminate the operation.
    // TODO
    // Check if at least one of the specified combinations of PublicKeyCredentialType and cryptographic parameters
    // in credTypesAndPubKeyAlgs is supported. If not, return an error code equivalent to "NotSupportedError"
    // and terminate the operation.
    Optional<PublicKeyCredentialParameters> optionalPublicKeyCredentialParameters = makeCredentialRequest.getCredTypesAndPublicKeyAlgs().stream().filter(this::isCapableOfHandling).findFirst();
    PublicKeyCredentialParameters publicKeyCredentialParameters;
    if (optionalPublicKeyCredentialParameters.isPresent()) {
        publicKeyCredentialParameters = optionalPublicKeyCredentialParameters.get();
    } else {
        throw new NotSupportedException("Specified PublicKeyCredentialParameters are not supported");
    }
    // For each descriptor of excludeCredentialDescriptorList:
    List<PublicKeyCredentialDescriptor> descriptors = makeCredentialRequest.getExcludeCredentialDescriptorList();
    if (descriptors == null) {
        descriptors = Collections.emptyList();
    }
    for (PublicKeyCredentialDescriptor descriptor : descriptors) {
        PublicKeyCredentialSource publicKeyCredentialSource = lookup(descriptor.getId());
        // The method of obtaining user consent MUST include a test of user presence.
        if (publicKeyCredentialSource != null) {
            if (publicKeyCredentialSource.getRpId().equals(rpEntity.getId()) && publicKeyCredentialSource.getType().equals(descriptor.getType())) {
                boolean userConsent = true;
                // confirms consent to create a new credential
                if (userConsent) {
                    throw new InvalidStateException("");
                } else // does not consent to create a new credential
                {
                    throw new NotAllowedException("User consent is required");
                }
            }
        }
    }
    // return an error code equivalent to "ConstraintError" and terminate the operation.
    if (makeCredentialRequest.isRequireResidentKey() && !isCapableOfStoringClientSideResidentCredential()) {
        throw new ConstraintException("Authenticator isn't capable of storing client-side resident credential");
    }
    // return an error code equivalent to "ConstraintError" and terminate the operation.
    if (makeCredentialRequest.isRequireUserVerification() && !isCapableOfUserVerification()) {
        throw new ConstraintException("Authenticator isn't capable of user verification");
    }
    // Obtain user consent for creating a new credential.
    // The prompt for obtaining this consent is shown by the authenticator if it has its own output capability,
    // or by the user agent otherwise. The prompt SHOULD display rpEntity.id, rpEntity.name, userEntity.name
    // and userEntity.displayName, if possible.
    boolean userVerification = true;
    boolean userConsent = true;
    // "NotAllowedError" and terminate the operation.
    if (makeCredentialRequest.isRequireUserVerification() && !userVerification) {
        throw new NotAllowedException("User is not verified.");
    }
    if (makeCredentialRequest.isRequireUserPresence() && !userConsent) {
        throw new NotAllowedException("User doesn't resolve consent.");
    }
    // Once user consent has been obtained, generate a new credential object:
    byte[] credentialId;
    // Let (publicKey, privateKey) be a new pair of cryptographic keys using the combination of
    // PublicKeyCredentialType and cryptographic parameters represented by the first item in
    // credTypesAndPubKeyAlgs that is supported by this authenticator.
    KeyPair credentialKeyPair;
    COSEKey cosePublicKey;
    COSEKey cosePrivateKey;
    try {
        credentialKeyPair = ECUtil.createKeyPair();
        ECPublicKey publicKey = (ECPublicKey) credentialKeyPair.getPublic();
        ECPrivateKey privateKey = (ECPrivateKey) credentialKeyPair.getPrivate();
        cosePublicKey = TestDataUtil.createEC2COSEPublicKey(publicKey);
        cosePrivateKey = TestDataUtil.createEC2COSEPrivateKey(publicKey, privateKey);
        // Let userHandle be userEntity.id.
        byte[] userHandle = makeCredentialRequest.getUserEntity().getId();
        // Let credentialSource be a new public key credential source with the fields:
        PublicKeyCredentialSource credentialSource = new PublicKeyCredentialSource();
        credentialSource.setType(PublicKeyCredentialType.PUBLIC_KEY);
        credentialSource.setPrivateKey(cosePrivateKey);
        credentialSource.setRpId(rpEntity.getId());
        credentialSource.setUserHandle(userHandle);
        credentialSource.setOtherUI(null);
        // Credential Private Key:
        if (makeCredentialRequest.isRequireResidentKey()) {
            // Let credentialId be a new credential id.
            credentialId = new byte[32];
            secureRandom.nextBytes(credentialId);
            // Set credentialSource.id to credentialId.
            credentialSource.setId(credentialId);
            // Let credentials be this authenticator’s credentials map.
            // noinspection UnnecessaryLocalVariable
            Map<CredentialMapKey, PublicKeyCredentialSource> credentials = credentialMap;
            credentials.put(new CredentialMapKey(rpEntity.getId(), userHandle), credentialSource);
        } else // Otherwise:
        {
            // Let credentialId be the result of serializing and encrypting credentialSource
            // so that only this authenticator can decrypt it.
            byte[] data = cborConverter.writeValueAsBytes(credentialSource);
            credentialId = CipherUtil.encrypt(data, credentialEncryptionKey);
        }
    }// return an error code equivalent to "UnknownError" and terminate the operation.
     catch (RuntimeException e) {
        throw new WebAuthnModelException(e);
    }
    // Let processedExtensions be the result of authenticator extension processing for each
    // supported extension identifier -> authenticator extension input in extensions.
    AuthenticationExtensionsAuthenticatorOutputs<RegistrationExtensionAuthenticatorOutput> registrationExtensionAuthenticatorOutputs = processRegistrationExtensions(makeCredentialRequest);
    // If the authenticator supports:
    // a per-RP ID signature counter
    // allocate the counter, associate it with the RP ID, and initialize the counter value as zero.
    // a global signature counter
    // Use the global signature counter's actual value when generating authenticator data.
    // a per credential signature counter
    // allocate the counter, associate it with the new credential, and initialize the counter value as zero.
    // TODO: counter mode
    countUp();
    // Let attestedCredentialData be the attested credential data byte array including the credentialId and publicKey.
    byte[] rpIdHash = MessageDigestUtil.createSHA256().digest(rpEntity.getId().getBytes(StandardCharsets.UTF_8));
    byte flag = BIT_AT;
    if (userConsent)
        flag |= BIT_UP;
    if (userVerification)
        flag |= BIT_UV;
    if (!registrationExtensionAuthenticatorOutputs.getKeys().isEmpty())
        flag |= BIT_ED;
    AttestedCredentialData attestedCredentialData = new AttestedCredentialData(aaguid, credentialId, cosePublicKey);
    // Let authenticatorData be the byte array specified in §6.1 Authenticator data,
    // including attestedCredentialData as the attestedCredentialData and processedExtensions, if any, as the extensions.
    AuthenticatorData<RegistrationExtensionAuthenticatorOutput> authenticatorData = new AuthenticatorData<>(rpIdHash, flag, counter, attestedCredentialData, registrationExtensionAuthenticatorOutputs);
    byte[] authenticatorDataBytes = authenticatorDataConverter.convert(authenticatorData);
    byte[] signedData = getSignedData(authenticatorDataBytes, makeCredentialRequest.getHash());
    byte[] clientDataHash = makeCredentialRequest.getHash();
    AttestationStatementRequest attestationStatementRequest = new AttestationStatementRequest(signedData, credentialKeyPair, clientDataHash);
    AttestationStatement attestationStatement = createAttestationStatement(attestationStatementRequest, registrationEmulationOption);
    // Return the attestation object for the new credential created by the procedure specified in
    // §6.3.4 Generating an Attestation Object using an authenticator-chosen attestation statement format,
    // authenticatorData, and hash. For more details on attestation, see §6.3 Attestation.
    AttestationObject attestationObject = new AttestationObject(authenticatorData, attestationStatement);
    // On successful completion of this operation, the authenticator returns the attestation object to the client.
    MakeCredentialResponse makeCredentialResponse = new MakeCredentialResponse();
    makeCredentialResponse.setAttestationObject(attestationObject);
    return makeCredentialResponse;
}
Also used : COSEKey(com.webauthn4j.data.attestation.authenticator.COSEKey) RegistrationExtensionAuthenticatorOutput(com.webauthn4j.data.extension.authenticator.RegistrationExtensionAuthenticatorOutput) AttestedCredentialData(com.webauthn4j.data.attestation.authenticator.AttestedCredentialData) AuthenticatorData(com.webauthn4j.data.attestation.authenticator.AuthenticatorData) AttestationStatement(com.webauthn4j.data.attestation.statement.AttestationStatement) ECPrivateKey(java.security.interfaces.ECPrivateKey) KeyPair(java.security.KeyPair) PublicKeyCredentialRpEntity(com.webauthn4j.data.PublicKeyCredentialRpEntity) PublicKeyCredentialDescriptor(com.webauthn4j.data.PublicKeyCredentialDescriptor) ECPublicKey(java.security.interfaces.ECPublicKey) PublicKeyCredentialParameters(com.webauthn4j.data.PublicKeyCredentialParameters) AttestationObject(com.webauthn4j.data.attestation.AttestationObject)

Aggregations

PublicKeyCredentialParameters (com.webauthn4j.data.PublicKeyCredentialParameters)2 PublicKeyCredentialRpEntity (com.webauthn4j.data.PublicKeyCredentialRpEntity)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 AuthController (com.tremolosecurity.proxy.auth.AuthController)1 AuthInfo (com.tremolosecurity.proxy.auth.AuthInfo)1 WebAuthnUserData (com.tremolosecurity.proxy.auth.webauthn.WebAuthnUserData)1 CborConverter (com.webauthn4j.converter.util.CborConverter)1 ObjectConverter (com.webauthn4j.converter.util.ObjectConverter)1 AuthenticatorSelectionCriteria (com.webauthn4j.data.AuthenticatorSelectionCriteria)1 PublicKeyCredentialCreationOptions (com.webauthn4j.data.PublicKeyCredentialCreationOptions)1 PublicKeyCredentialDescriptor (com.webauthn4j.data.PublicKeyCredentialDescriptor)1 PublicKeyCredentialUserEntity (com.webauthn4j.data.PublicKeyCredentialUserEntity)1 AttestationObject (com.webauthn4j.data.attestation.AttestationObject)1 AttestedCredentialData (com.webauthn4j.data.attestation.authenticator.AttestedCredentialData)1 AuthenticatorData (com.webauthn4j.data.attestation.authenticator.AuthenticatorData)1 COSEKey (com.webauthn4j.data.attestation.authenticator.COSEKey)1 AttestationStatement (com.webauthn4j.data.attestation.statement.AttestationStatement)1 Origin (com.webauthn4j.data.client.Origin)1 Challenge (com.webauthn4j.data.client.challenge.Challenge)1 DefaultChallenge (com.webauthn4j.data.client.challenge.DefaultChallenge)1