Search in sources :

Example 1 with Base64UrlException

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

the class FidoMetadataDownloader method retrieveBlob.

/**
 * @throws Base64UrlException if the metadata BLOB is not a well-formed JWT in compact
 *     serialization.
 * @throws CertPathValidatorException if the downloaded or explicitly configured BLOB fails
 *     certificate path validation.
 * @throws CertificateException if the BLOB signing certificate chain fails to parse.
 * @throws IOException if any of the following fails: downloading the BLOB, reading or writing the
 *     cache file (if any), or parsing the BLOB contents.
 * @throws InvalidAlgorithmParameterException if certificate path validation fails.
 * @throws InvalidKeyException if signature verification fails.
 * @throws UnexpectedLegalHeader if the downloaded BLOB (if any) contains a <code>"legalHeader"
 *     </code> value not configured in {@link
 *     FidoMetadataDownloaderBuilder.Step1#expectLegalHeader(String...)
 *     expectLegalHeader(String...)} but is otherwise valid. The downloaded BLOB will not be
 *     written to cache in this case.
 * @throws NoSuchAlgorithmException if signature verification fails.
 * @throws SignatureException if signature verification fails.
 * @throws FidoMetadataDownloaderException if the explicitly configured BLOB (if any) has a bad
 *     signature.
 */
private MetadataBLOB retrieveBlob(X509Certificate trustRootCertificate) throws Base64UrlException, CertPathValidatorException, CertificateException, IOException, InvalidAlgorithmParameterException, InvalidKeyException, UnexpectedLegalHeader, NoSuchAlgorithmException, SignatureException, FidoMetadataDownloaderException {
    if (blobJwt != null) {
        return parseAndVerifyBlob(new ByteArray(blobJwt.getBytes(StandardCharsets.UTF_8)), trustRootCertificate);
    } else {
        final Optional<ByteArray> cachedContents;
        if (blobCacheFile != null) {
            cachedContents = readCacheFile(blobCacheFile);
        } else {
            cachedContents = blobCacheSupplier.get();
        }
        final MetadataBLOB cachedBlob = cachedContents.map(cached -> {
            try {
                return parseAndVerifyBlob(cached, trustRootCertificate);
            } catch (Exception e) {
                return null;
            }
        }).orElse(null);
        if (cachedBlob != null && cachedBlob.getPayload().getNextUpdate().atStartOfDay().atZone(clock.getZone()).isAfter(clock.instant().atZone(clock.getZone()))) {
            return cachedBlob;
        } else {
            final ByteArray downloaded = download(blobUrl);
            try {
                final MetadataBLOB downloadedBlob = parseAndVerifyBlob(downloaded, trustRootCertificate);
                if (cachedBlob == null || downloadedBlob.getPayload().getNo() > cachedBlob.getPayload().getNo()) {
                    if (expectedLegalHeaders.contains(downloadedBlob.getPayload().getLegalHeader())) {
                        if (blobCacheFile != null) {
                            new FileOutputStream(blobCacheFile).write(downloaded.getBytes());
                        }
                        if (blobCacheConsumer != null) {
                            blobCacheConsumer.accept(downloaded);
                        }
                        return downloadedBlob;
                    } else {
                        throw new UnexpectedLegalHeader(cachedBlob, downloadedBlob);
                    }
                } else {
                    return cachedBlob;
                }
            } catch (FidoMetadataDownloaderException e) {
                if (e.getReason() == FidoMetadataDownloaderException.Reason.BAD_SIGNATURE && cachedBlob != null) {
                    return cachedBlob;
                } else {
                    throw e;
                }
            }
        }
    }
}
Also used : X509Certificate(java.security.cert.X509Certificate) SSLContext(javax.net.ssl.SSLContext) CertificateFactory(java.security.cert.CertificateFactory) URL(java.net.URL) Date(java.util.Date) HexException(com.yubico.webauthn.data.exception.HexException) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Scanner(java.util.Scanner) KeyStoreException(java.security.KeyStoreException) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) CertStoreParameters(java.security.cert.CertStoreParameters) ByteArrayInputStream(java.io.ByteArrayInputStream) DigestException(java.security.DigestException) CertPathValidatorException(java.security.cert.CertPathValidatorException) CRL(java.security.cert.CRL) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) NonNull(lombok.NonNull) SignatureException(java.security.SignatureException) Collection(java.util.Collection) Signature(java.security.Signature) CertPathValidator(java.security.cert.CertPathValidator) Set(java.util.Set) KeyStore(java.security.KeyStore) KeyManagementException(java.security.KeyManagementException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) FileNotFoundException(java.io.FileNotFoundException) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Stream(java.util.stream.Stream) CertificateParser(com.yubico.internal.util.CertificateParser) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Optional(java.util.Optional) InvalidKeyException(java.security.InvalidKeyException) ByteArray(com.yubico.webauthn.data.ByteArray) TrustAnchor(java.security.cert.TrustAnchor) MessageDigest(java.security.MessageDigest) BinaryUtil(com.yubico.internal.util.BinaryUtil) Supplier(java.util.function.Supplier) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) ArrayList(java.util.ArrayList) AccessLevel(lombok.AccessLevel) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) MalformedURLException(java.net.MalformedURLException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) CertPath(java.security.cert.CertPath) CertificateException(java.security.cert.CertificateException) PKIXParameters(java.security.cert.PKIXParameters) File(java.io.File) Reason(com.yubico.fido.metadata.FidoMetadataDownloaderException.Reason) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) Consumer(java.util.function.Consumer) Base64Variants(com.fasterxml.jackson.core.Base64Variants) CertStore(java.security.cert.CertStore) Base64UrlException(com.yubico.webauthn.data.exception.Base64UrlException) Clock(java.time.Clock) AllArgsConstructor(lombok.AllArgsConstructor) Collections(java.util.Collections) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) ByteArray(com.yubico.webauthn.data.ByteArray) HexException(com.yubico.webauthn.data.exception.HexException) KeyStoreException(java.security.KeyStoreException) DigestException(java.security.DigestException) CertPathValidatorException(java.security.cert.CertPathValidatorException) SignatureException(java.security.SignatureException) KeyManagementException(java.security.KeyManagementException) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) Base64UrlException(com.yubico.webauthn.data.exception.Base64UrlException)

Example 2 with Base64UrlException

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

the class WebAuthnRestResource method deregisterCredential.

@Path("action/deregister")
@POST
public Response deregisterCredential(@NonNull @FormParam("sessionToken") String sessionTokenBase64, @NonNull @FormParam("credentialId") String credentialIdBase64) throws MalformedURLException, Base64UrlException {
    logger.trace("deregisterCredential sesion: {}, credentialId: {}", sessionTokenBase64, credentialIdBase64);
    final ByteArray credentialId;
    try {
        credentialId = ByteArray.fromBase64Url(credentialIdBase64);
    } catch (Base64UrlException e) {
        return messagesJson(Response.status(Status.BAD_REQUEST), "Credential ID is not valid Base64Url data: " + credentialIdBase64);
    }
    Either<List<String>, DeregisterCredentialResult> result = server.deregisterCredential(ByteArray.fromBase64Url(sessionTokenBase64), credentialId);
    if (result.isRight()) {
        return finishResponse(result, "Failed to deregister credential; further error message(s) were unfortunately lost to an internal server error.", "deregisterCredential", "");
    } else {
        return messagesJson(Response.status(Status.BAD_REQUEST), result.left().get());
    }
}
Also used : DeregisterCredentialResult(demo.webauthn.WebAuthnServer.DeregisterCredentialResult) Base64UrlException(com.yubico.webauthn.data.exception.Base64UrlException) ByteArray(com.yubico.webauthn.data.ByteArray) List(java.util.List) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Aggregations

ByteArray (com.yubico.webauthn.data.ByteArray)2 Base64UrlException (com.yubico.webauthn.data.exception.Base64UrlException)2 Base64Variants (com.fasterxml.jackson.core.Base64Variants)1 DeserializationFeature (com.fasterxml.jackson.databind.DeserializationFeature)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Reason (com.yubico.fido.metadata.FidoMetadataDownloaderException.Reason)1 BinaryUtil (com.yubico.internal.util.BinaryUtil)1 CertificateParser (com.yubico.internal.util.CertificateParser)1 HexException (com.yubico.webauthn.data.exception.HexException)1 DeregisterCredentialResult (demo.webauthn.WebAuthnServer.DeregisterCredentialResult)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 URLConnection (java.net.URLConnection)1