Search in sources :

Example 11 with ByteArray

use of com.yubico.webauthn.data.ByteArray in project cas by apereo.

the class WebAuthnServer method startRegistration.

public Either<String, RegistrationRequest> startRegistration(@NonNull final String username, final Optional<String> displayName, final Optional<String> credentialNickname, final ResidentKeyRequirement residentKeyRequirement, final Optional<ByteArray> sessionToken) throws ExecutionException {
    LOGGER.trace("startRegistration username: {}, credentialNickname: {}", username, credentialNickname);
    var registrations = userStorage.getRegistrationsByUsername(username);
    var existingUser = registrations.stream().findAny().map(CredentialRegistration::getUserIdentity);
    val permissionGranted = existingUser.map(userIdentity -> sessions.isSessionForUser(userIdentity.getId(), sessionToken)).orElse(true);
    if (permissionGranted) {
        var registrationUserId = existingUser.orElseGet(() -> UserIdentity.builder().name(username).displayName(displayName.get()).id(generateRandom(32)).build());
        val request = new RegistrationRequest(username, credentialNickname, generateRandom(32), rp.startRegistration(StartRegistrationOptions.builder().user(registrationUserId).authenticatorSelection(AuthenticatorSelectionCriteria.builder().residentKey(residentKeyRequirement).build()).build()), Optional.of(sessions.createSession(registrationUserId.getId())));
        registerRequestStorage.put(request.getRequestId(), request);
        return Either.right(request);
    } else {
        return Either.left("The username \"" + username + "\" is already registered.");
    }
}
Also used : lombok.val(lombok.val) X509Certificate(java.security.cert.X509Certificate) RandomUtils(org.apereo.cas.util.RandomUtils) Arrays(java.util.Arrays) SortedSet(java.util.SortedSet) AuthenticatorData(com.yubico.webauthn.data.AuthenticatorData) CredentialRegistration(com.yubico.data.CredentialRegistration) AuthenticatorSelectionCriteria(com.yubico.webauthn.data.AuthenticatorSelectionCriteria) JacksonCodecs(com.yubico.internal.util.JacksonCodecs) Either(com.yubico.util.Either) FinishRegistrationOptions(com.yubico.webauthn.FinishRegistrationOptions) SecureRandom(java.security.SecureRandom) JsonSerializer(com.fasterxml.jackson.databind.JsonSerializer) JsonNode(com.fasterxml.jackson.databind.JsonNode) StartAssertionOptions(com.yubico.webauthn.StartAssertionOptions) AuthenticatorTransport(com.yubico.webauthn.data.AuthenticatorTransport) AssertionResponse(com.yubico.data.AssertionResponse) RegistrationFailedException(com.yubico.webauthn.exception.RegistrationFailedException) NonNull(lombok.NonNull) Collection(java.util.Collection) RegistrationRequest(com.yubico.data.RegistrationRequest) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) ResidentKeyRequirement(com.yubico.webauthn.data.ResidentKeyRequirement) CertificateParser(com.yubico.internal.util.CertificateParser) AttestationMetadataSource(com.yubico.webauthn.attestation.AttestationMetadataSource) Optional(java.util.Optional) ByteArray(com.yubico.webauthn.data.ByteArray) Setter(lombok.Setter) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) Attestation(com.yubico.webauthn.attestation.Attestation) TreeSet(java.util.TreeSet) Value(lombok.Value) AssertionFailedException(com.yubico.webauthn.exception.AssertionFailedException) StartRegistrationOptions(com.yubico.webauthn.StartRegistrationOptions) FinishAssertionOptions(com.yubico.webauthn.FinishAssertionOptions) JsonSerialize(com.fasterxml.jackson.databind.annotation.JsonSerialize) RelyingParty(com.yubico.webauthn.RelyingParty) UserIdentity(com.yubico.webauthn.data.UserIdentity) SerializerProvider(com.fasterxml.jackson.databind.SerializerProvider) RegistrationResponse(com.yubico.data.RegistrationResponse) RegisteredCredential(com.yubico.webauthn.RegisteredCredential) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) lombok.val(lombok.val) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) Clock(java.time.Clock) RegistrationResult(com.yubico.webauthn.RegistrationResult) Cache(com.google.common.cache.Cache) AllArgsConstructor(lombok.AllArgsConstructor) Collections(java.util.Collections) AssertionRequestWrapper(com.yubico.data.AssertionRequestWrapper) CredentialRegistration(com.yubico.data.CredentialRegistration) RegistrationRequest(com.yubico.data.RegistrationRequest)

Example 12 with ByteArray

use of com.yubico.webauthn.data.ByteArray in project cas by apereo.

the class ExtensionMatcher method matches.

@Override
public boolean matches(X509Certificate attestationCertificate, JsonNode parameters) {
    String matchKey = parameters.get(EXTENSION_KEY).asText();
    JsonNode matchValue = parameters.get(EXTENSION_VALUE);
    byte[] extensionValue = attestationCertificate.getExtensionValue(matchKey);
    if (extensionValue != null) {
        if (matchValue == null) {
            return true;
        } else {
            try {
                final ASN1Primitive value = ASN1Primitive.fromByteArray(extensionValue);
                if (matchValue.isObject()) {
                    if (matchTypedValue(matchKey, matchValue, value)) {
                        return true;
                    }
                } else if (matchValue.isTextual()) {
                    if (matchStringValue(matchKey, matchValue, value))
                        return true;
                }
            } catch (IOException e) {
                LOGGER.error("Failed to parse extension value as ASN1: {}", new ByteArray(extensionValue).getHex(), e);
            }
        }
    }
    return false;
}
Also used : ByteArray(com.yubico.webauthn.data.ByteArray) JsonNode(com.fasterxml.jackson.databind.JsonNode) DEROctetString(org.bouncycastle.asn1.DEROctetString) IOException(java.io.IOException) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive)

Example 13 with ByteArray

use of com.yubico.webauthn.data.ByteArray in project java-webauthn-server by Yubico.

the class FidoMetadataDownloader method verifyHash.

/**
 * @return <code>contents</code> if its SHA-256 hash matches any element of <code>
 *     acceptedCertSha256</code>, otherwise <code>null</code>.
 */
private static ByteArray verifyHash(ByteArray contents, Set<ByteArray> acceptedCertSha256) throws NoSuchAlgorithmException {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    final ByteArray hash = new ByteArray(digest.digest(contents.getBytes()));
    if (acceptedCertSha256.stream().anyMatch(acceptableHash -> acceptableHash.equals(hash))) {
        return contents;
    } else {
        return null;
    }
}
Also used : ByteArray(com.yubico.webauthn.data.ByteArray) MessageDigest(java.security.MessageDigest)

Example 14 with ByteArray

use of com.yubico.webauthn.data.ByteArray in project java-webauthn-server by Yubico.

the class FidoMetadataDownloader method parseAndVerifyBlob.

private MetadataBLOB parseAndVerifyBlob(ByteArray jwt, X509Certificate trustRootCertificate) throws CertPathValidatorException, InvalidAlgorithmParameterException, CertificateException, IOException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, Base64UrlException, FidoMetadataDownloaderException {
    Scanner s = new Scanner(new ByteArrayInputStream(jwt.getBytes())).useDelimiter("\\.");
    final ByteArray header = ByteArray.fromBase64Url(s.next());
    final ByteArray payload = ByteArray.fromBase64Url(s.next());
    final ByteArray signature = ByteArray.fromBase64Url(s.next());
    return verifyBlob(header, payload, signature, trustRootCertificate);
}
Also used : Scanner(java.util.Scanner) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArray(com.yubico.webauthn.data.ByteArray)

Example 15 with ByteArray

use of com.yubico.webauthn.data.ByteArray in project java-webauthn-server by Yubico.

the class FidoMetadataService method findEntries.

/**
 * Look up metadata entries matching a given attestation certificate chain or AAGUID.
 *
 * @param attestationCertificateChain an attestation certificate chain, presumably from a WebAuthn
 *     attestation statement.
 * @param aaguid the AAGUID of the authenticator to look up, if available.
 * @return All metadata entries which satisfy ALL of the following:
 *     <ul>
 *       <li>It satisfies the {@link FidoMetadataServiceBuilder#prefilter(Predicate) prefilter}.
 *       <li>It satisfies AT LEAST ONE of the following:
 *           <ul>
 *             <li><code>aaguid</code> is present and equals the {@link
 *                 MetadataBLOBPayloadEntry#getAaguid() AAGUID} of the metadata entry.
 *             <li><code>aaguid</code> is present and equals the {@link
 *                 MetadataBLOBPayloadEntry#getAaguid() AAGUID} of the {@link
 *                 MetadataBLOBPayloadEntry#getMetadataStatement() metadata statement}, if any, in
 *                 the metadata entry.
 *             <li>The certificate subject key identifier of any certificate in <code>
 *                 attestationCertificateChain</code> matches any element of {@link
 *                 MetadataBLOBPayloadEntry#getAttestationCertificateKeyIdentifiers()
 *                 attestationCertificateKeyIdentifiers} in the metadata entry.
 *             <li>The certificate subject key identifier of any certificate in <code>
 *                 attestationCertificateChain</code> matches any element of {@link
 *                 MetadataStatement#getAttestationCertificateKeyIdentifiers()
 *                 attestationCertificateKeyIdentifiers} in the {@link
 *                 MetadataBLOBPayloadEntry#getMetadataStatement() metadata statement}, if any, in
 *                 the metadata entry.
 *           </ul>
 *       <li>It satisfies the {@link FidoMetadataServiceBuilder#filter(Predicate) filter} together
 *           with <code>attestationCertificateChain</code> and <code>aaguid</code>.
 *     </ul>
 *
 * @see #findEntries(List)
 * @see #findEntries(List, AAGUID)
 */
public Set<MetadataBLOBPayloadEntry> findEntries(@NonNull List<X509Certificate> attestationCertificateChain, @NonNull Optional<AAGUID> aaguid) {
    final Set<String> certSubjectKeyIdentifiers = attestationCertificateChain.stream().map(cert -> {
        try {
            return new ByteArray(CertificateParser.computeSubjectKeyIdentifier(cert)).getHex();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-1 hash algorithm is not available in JCA context.", e);
        }
    }).collect(Collectors.toSet());
    final Optional<AAGUID> nonzeroAaguid = aaguid.filter(a -> !a.isZero());
    log.debug("findEntries(certSubjectKeyIdentifiers = {}, aaguid = {})", certSubjectKeyIdentifiers, aaguid);
    if (!nonzeroAaguid.isPresent()) {
        log.debug("findEntries: ignoring zero AAGUID");
    }
    final Set<MetadataBLOBPayloadEntry> result = Stream.concat(nonzeroAaguid.map(prefilteredEntriesByAaguid::get).map(Collection::stream).orElseGet(Stream::empty), certSubjectKeyIdentifiers.stream().flatMap(cski -> Optional.ofNullable(prefilteredEntriesByCertificateKeyIdentifier.get(cski)).map(Collection::stream).orElseGet(Stream::empty))).filter(metadataBLOBPayloadEntry -> this.filter.test(new AuthenticatorToBeFiltered(attestationCertificateChain, metadataBLOBPayloadEntry, aaguid.orElse(null)))).collect(Collectors.toSet());
    log.debug("findEntries(certSubjectKeyIdentifiers = {}, aaguid = {}) => {} matches", certSubjectKeyIdentifiers, aaguid, result.size());
    return result;
}
Also used : X509Certificate(java.security.cert.X509Certificate) AuthenticatorToBeFiltered(com.yubico.fido.metadata.FidoMetadataService.Filters.AuthenticatorToBeFiltered) Arrays(java.util.Arrays) RequiredArgsConstructor(lombok.RequiredArgsConstructor) HashMap(java.util.HashMap) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) Value(lombok.Value) HashSet(java.util.HashSet) AccessLevel(lombok.AccessLevel) Map(java.util.Map) RelyingParty(com.yubico.webauthn.RelyingParty) DigestException(java.security.DigestException) CertPathValidatorException(java.security.cert.CertPathValidatorException) AttestationTrustSource(com.yubico.webauthn.attestation.AttestationTrustSource) Predicate(java.util.function.Predicate) NonNull(lombok.NonNull) SignatureException(java.security.SignatureException) Collection(java.util.Collection) Set(java.util.Set) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) Collectors(java.util.stream.Collectors) Consumer(java.util.function.Consumer) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Stream(java.util.stream.Stream) CertStore(java.security.cert.CertStore) CertificateParser(com.yubico.internal.util.CertificateParser) Base64UrlException(com.yubico.webauthn.data.exception.Base64UrlException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Optional(java.util.Optional) InvalidKeyException(java.security.InvalidKeyException) RegistrationResult(com.yubico.webauthn.RegistrationResult) ByteArray(com.yubico.webauthn.data.ByteArray) AllArgsConstructor(lombok.AllArgsConstructor) Collections(java.util.Collections) RelyingPartyBuilder(com.yubico.webauthn.RelyingParty.RelyingPartyBuilder) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AuthenticatorToBeFiltered(com.yubico.fido.metadata.FidoMetadataService.Filters.AuthenticatorToBeFiltered) ByteArray(com.yubico.webauthn.data.ByteArray) Collection(java.util.Collection) Stream(java.util.stream.Stream)

Aggregations

ByteArray (com.yubico.webauthn.data.ByteArray)23 IOException (java.io.IOException)10 JsonNode (com.fasterxml.jackson.databind.JsonNode)7 X509Certificate (java.security.cert.X509Certificate)7 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 CertificateException (java.security.cert.CertificateException)6 List (java.util.List)5 Optional (java.util.Optional)5 CertificateParser (com.yubico.internal.util.CertificateParser)4 Base64UrlException (com.yubico.webauthn.data.exception.Base64UrlException)4 Collection (java.util.Collection)4 Collections (java.util.Collections)4 AllArgsConstructor (lombok.AllArgsConstructor)4 NonNull (lombok.NonNull)4 ASN1Primitive (org.bouncycastle.asn1.ASN1Primitive)4 DEROctetString (org.bouncycastle.asn1.DEROctetString)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 DigestException (java.security.DigestException)3 Slf4j (lombok.extern.slf4j.Slf4j)3 CoseException (COSE.CoseException)2