From 0e6bd42183537e125d28a868b74587f202b24bcf Mon Sep 17 00:00:00 2001 From: mosuem <27859082+mosuem@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:40:24 +0000 Subject: [PATCH] Update BoringSSL to 289645a4 --- CHANGELOG.md | 1 + lib/src/bindings/boringssl.g.dart | 710 ++++--- lib/src/bindings/record_use_mapping.g.dart | 38 +- .../gen/bcm/aesni-gcm-x86_64-win.asm | 2 +- .../boringssl/gen/bcm/aesni-x86_64-win.asm | 6 +- .../gen/bcm/ghash-ssse3-x86_64-win.asm | 2 +- .../boringssl/gen/bcm/ghash-x86_64-win.asm | 2 +- .../boringssl/gen/bcm/p256-x86_64-asm-win.asm | 2 +- .../boringssl/gen/bcm/rsaz-avx2-win.asm | 2 +- .../boringssl/gen/bcm/sha1-x86_64-win.asm | 2 +- .../boringssl/gen/bcm/sha256-x86_64-win.asm | 2 +- .../boringssl/gen/bcm/sha512-x86_64-win.asm | 2 +- .../boringssl/gen/bcm/vpaes-x86_64-win.asm | 2 +- .../boringssl/gen/bcm/x86_64-mont5-win.asm | 2 +- .../gen/crypto/chacha-x86_64-win.asm | 2 +- third_party/boringssl/sources.cmake | 3 + .../src/crypto/armv8_feature_parsing.h | 19 +- .../boringssl/src/crypto/asn1/a_strex.cc | 34 +- .../boringssl/src/crypto/asn1/a_strnid.cc | 78 +- .../boringssl/src/crypto/asn1/a_type.cc | 34 +- .../boringssl/src/crypto/asn1/asn1_lib.cc | 27 +- .../boringssl/src/crypto/asn1/asn1_par.cc | 2 +- .../boringssl/src/crypto/asn1/internal.h | 83 +- .../boringssl/src/crypto/asn1/tasn_dec.cc | 5 +- third_party/boringssl/src/crypto/bio/bio.cc | 17 +- .../boringssl/src/crypto/blake2/blake2.cc | 15 +- .../boringssl/src/crypto/bytestring/cbb.cc | 14 +- .../boringssl/src/crypto/bytestring/cbs.cc | 36 + .../src/crypto/bytestring/internal.h | 5 + third_party/boringssl/src/crypto/cms/cms.cc | 9 +- .../boringssl/src/crypto/cpu_aarch64_apple.cc | 6 + .../boringssl/src/crypto/cpu_aarch64_linux.cc | 8 + .../src/crypto/cpu_aarch64_openbsd.cc | 14 + .../src/crypto/cpu_aarch64_sysreg.cc | 5 +- third_party/boringssl/src/crypto/crypto.cc | 68 + .../boringssl/src/crypto/curve25519/cpace.cc | 227 +++ .../src/crypto/curve25519/curve25519.cc | 200 +- .../src/crypto/curve25519/curve25519_tables.h | 496 ++--- .../src/crypto/curve25519/internal.h | 30 +- .../src/crypto/curve25519/spake25519.cc | 32 +- .../src/crypto/digest/digest_extra.cc | 180 +- .../boringssl/src/crypto/digest/p_keccak.cc | 147 ++ third_party/boringssl/src/crypto/dsa/dsa.cc | 10 +- third_party/boringssl/src/crypto/evp/evp.cc | 5 +- .../boringssl/src/crypto/evp/evp_asn1.cc | 9 +- .../boringssl/src/crypto/evp/evp_ctx.cc | 23 +- .../boringssl/src/crypto/evp/evp_kem.cc | 9 +- .../boringssl/src/crypto/evp/internal.h | 15 +- third_party/boringssl/src/crypto/evp/p_dh.cc | 42 +- third_party/boringssl/src/crypto/evp/p_dsa.cc | 46 +- third_party/boringssl/src/crypto/evp/p_ec.cc | 99 +- .../boringssl/src/crypto/evp/p_ed25519.cc | 58 +- .../boringssl/src/crypto/evp/p_hkdf.cc | 10 +- .../boringssl/src/crypto/evp/p_mlkem.cc | 12 +- third_party/boringssl/src/crypto/evp/p_rsa.cc | 106 +- .../boringssl/src/crypto/evp/p_slhdsa.cc | 537 +++++ .../boringssl/src/crypto/evp/p_x25519.cc | 54 +- .../boringssl/src/crypto/evp/p_xwing.cc | 51 +- third_party/boringssl/src/crypto/evp/sign.cc | 10 +- .../src/crypto/fipsmodule/aes/gcm.cc.inc | 11 +- .../src/crypto/fipsmodule/aes/internal.h | 122 +- .../fipsmodule/bn/exponentiation.cc.inc | 66 +- .../src/crypto/fipsmodule/cipher/e_aes.cc.inc | 40 +- .../src/crypto/fipsmodule/cmac/cmac.cc.inc | 4 +- .../src/crypto/fipsmodule/dh/dh.cc.inc | 7 + .../crypto/fipsmodule/digest/digest.cc.inc | 16 +- .../crypto/fipsmodule/digest/digests.cc.inc | 6 +- .../src/crypto/fipsmodule/digest/internal.h | 4 + .../fipsmodule/digestsign/digestsign.cc.inc | 9 +- .../src/crypto/fipsmodule/ec/ec_key.cc.inc | 8 +- .../src/crypto/fipsmodule/ec/p256-nistz.h | 157 +- .../crypto/fipsmodule/entropy/jitter.cc.inc | 42 +- .../src/crypto/fipsmodule/keccak/internal.h | 12 + .../crypto/fipsmodule/keccak/keccak.cc.inc | 10 +- .../src/crypto/fipsmodule/mldsa/mldsa.cc.inc | 109 +- .../src/crypto/fipsmodule/mlkem/mlkem.cc.inc | 144 +- .../src/crypto/fipsmodule/rand/rand.cc.inc | 4 +- .../src/crypto/fipsmodule/rsa/rsa.cc.inc | 8 +- .../fipsmodule/service_indicator/internal.h | 4 + .../service_indicator.cc.inc | 15 +- .../src/crypto/fipsmodule/slhdsa/fors.cc.inc | 35 +- .../src/crypto/fipsmodule/slhdsa/fors.h | 9 +- .../crypto/fipsmodule/slhdsa/merkle.cc.inc | 43 +- .../src/crypto/fipsmodule/slhdsa/merkle.h | 17 +- .../crypto/fipsmodule/slhdsa/slhdsa.cc.inc | 49 +- .../src/crypto/fipsmodule/slhdsa/thash.cc.inc | 114 +- .../src/crypto/fipsmodule/slhdsa/thash.h | 30 +- .../src/crypto/fipsmodule/slhdsa/wots.cc.inc | 48 +- .../src/crypto/fipsmodule/slhdsa/wots.h | 7 +- third_party/boringssl/src/crypto/hpke/hpke.cc | 1562 +++++++-------- third_party/boringssl/src/crypto/internal.h | 169 +- third_party/boringssl/src/crypto/md5/md5.cc | 42 + .../boringssl/src/crypto/mem_internal.h | 7 + .../boringssl/src/crypto/obj/obj_dat.h | 150 +- .../boringssl/src/crypto/pem/pem_all.cc | 24 +- .../boringssl/src/crypto/pem/pem_info.cc | 30 +- .../boringssl/src/crypto/pem/pem_lib.cc | 81 +- .../boringssl/src/crypto/pem/pem_pk8.cc | 101 +- .../boringssl/src/crypto/pkcs7/internal.h | 5 +- .../boringssl/src/crypto/pkcs7/pkcs7.cc | 10 +- .../boringssl/src/crypto/pkcs7/pkcs7_x509.cc | 42 +- .../boringssl/src/crypto/pkcs8/p5_pbev2.cc | 41 +- .../boringssl/src/crypto/pkcs8/pkcs8.cc | 31 +- .../boringssl/src/crypto/pkcs8/pkcs8_x509.cc | 54 +- .../boringssl/src/crypto/poly1305/poly1305.cc | 16 +- .../src/crypto/poly1305/poly1305_arm.cc | 16 +- .../src/crypto/poly1305/poly1305_vec.cc | 8 +- third_party/boringssl/src/crypto/pool/pool.cc | 10 + .../src/crypto/rand/deterministic.cc | 10 +- .../boringssl/src/crypto/rand/fork_detect.cc | 32 +- .../boringssl/src/crypto/rand/forkunsafe.cc | 6 +- third_party/boringssl/src/crypto/rand/rand.cc | 4 + .../boringssl/src/crypto/rand/urandom.cc | 14 +- .../boringssl/src/crypto/rand/windows.cc | 10 +- .../boringssl/src/crypto/rsa/rsa_asn1.cc | 74 +- .../boringssl/src/crypto/rsa/rsa_crypt.cc | 29 +- .../boringssl/src/crypto/rsa/rsa_print.cc | 3 +- third_party/boringssl/src/crypto/sha/sha1.cc | 9 - .../boringssl/src/crypto/sha/sha256.cc | 20 - .../boringssl/src/crypto/sha/sha512.cc | 30 - .../src/crypto/trust_token/trust_token.cc | 12 +- .../boringssl/src/crypto/x509/a_sign.cc | 2 +- .../boringssl/src/crypto/x509/a_verify.cc | 7 +- .../boringssl/src/crypto/x509/algorithm.cc | 8 +- .../boringssl/src/crypto/x509/asn1_gen.cc | 105 +- .../boringssl/src/crypto/x509/by_dir.cc | 79 +- .../boringssl/src/crypto/x509/by_file.cc | 26 +- .../boringssl/src/crypto/x509/internal.h | 99 +- .../boringssl/src/crypto/x509/name_print.cc | 11 +- .../boringssl/src/crypto/x509/policy.cc | 65 +- .../boringssl/src/crypto/x509/rsa_pss.cc | 31 +- .../boringssl/src/crypto/x509/v3_akey.cc | 53 +- .../boringssl/src/crypto/x509/v3_alt.cc | 752 ++++--- .../boringssl/src/crypto/x509/v3_bcons.cc | 55 +- .../boringssl/src/crypto/x509/v3_bitst.cc | 40 +- .../boringssl/src/crypto/x509/v3_conf.cc | 190 +- .../boringssl/src/crypto/x509/v3_cpols.cc | 375 ++-- .../boringssl/src/crypto/x509/v3_crld.cc | 239 +-- .../boringssl/src/crypto/x509/v3_enum.cc | 9 +- .../boringssl/src/crypto/x509/v3_extku.cc | 55 +- .../boringssl/src/crypto/x509/v3_genn.cc | 47 +- .../boringssl/src/crypto/x509/v3_ia5.cc | 10 +- .../boringssl/src/crypto/x509/v3_info.cc | 89 +- .../boringssl/src/crypto/x509/v3_int.cc | 10 +- .../boringssl/src/crypto/x509/v3_lib.cc | 6 +- .../boringssl/src/crypto/x509/v3_ocsp.cc | 56 +- .../boringssl/src/crypto/x509/v3_pcons.cc | 54 +- .../boringssl/src/crypto/x509/v3_pmaps.cc | 55 +- .../boringssl/src/crypto/x509/v3_prn.cc | 61 +- .../boringssl/src/crypto/x509/v3_purp.cc | 319 ++- .../boringssl/src/crypto/x509/v3_skey.cc | 71 +- .../boringssl/src/crypto/x509/v3_utl.cc | 1748 ++++++++--------- .../boringssl/src/crypto/x509/x509_cmp.cc | 6 +- .../boringssl/src/crypto/x509/x509_ext.cc | 24 +- .../boringssl/src/crypto/x509/x509_lu.cc | 387 ++-- .../boringssl/src/crypto/x509/x509_mtc.cc | 159 +- .../boringssl/src/crypto/x509/x509_req.cc | 28 +- .../boringssl/src/crypto/x509/x509_set.cc | 2 +- .../boringssl/src/crypto/x509/x509_trs.cc | 99 +- .../boringssl/src/crypto/x509/x509_vfy.cc | 1339 ++++++------- .../boringssl/src/crypto/x509/x509_vpm.cc | 221 ++- .../boringssl/src/crypto/x509/x509cset.cc | 9 + .../boringssl/src/crypto/x509/x509rset.cc | 4 +- .../boringssl/src/crypto/x509/x509spki.cc | 4 +- .../boringssl/src/crypto/x509/x_algor.cc | 11 +- .../boringssl/src/crypto/x509/x_all.cc | 34 +- .../boringssl/src/crypto/x509/x_crl.cc | 200 +- .../boringssl/src/crypto/x509/x_name.cc | 228 +-- .../boringssl/src/crypto/x509/x_pubkey.cc | 26 +- .../boringssl/src/crypto/x509/x_req.cc | 9 +- .../boringssl/src/crypto/x509/x_x509.cc | 140 +- .../boringssl/src/crypto/x509/x_x509a.cc | 6 +- .../boringssl/src/gen/crypto/err_data.cc | 550 +++--- .../boringssl/src/include/openssl/asn1.h | 76 +- .../boringssl/src/include/openssl/base.h | 22 +- .../boringssl/src/include/openssl/base64.h | 3 +- .../boringssl/src/include/openssl/bio.h | 25 +- .../boringssl/src/include/openssl/bn.h | 6 +- .../src/include/openssl/bytestring.h | 7 + .../boringssl/src/include/openssl/cms.h | 10 +- .../src/include/openssl/curve25519.h | 82 +- .../boringssl/src/include/openssl/dh.h | 9 +- .../boringssl/src/include/openssl/digest.h | 52 +- .../boringssl/src/include/openssl/dsa.h | 9 +- .../boringssl/src/include/openssl/ec_key.h | 7 +- .../boringssl/src/include/openssl/ecdh.h | 4 +- .../boringssl/src/include/openssl/evp.h | 64 +- .../boringssl/src/include/openssl/hpke.h | 35 +- .../boringssl/src/include/openssl/md5.h | 20 + .../boringssl/src/include/openssl/nid.h | 55 +- .../boringssl/src/include/openssl/pkcs7.h | 14 +- .../boringssl/src/include/openssl/pkcs8.h | 2 +- .../boringssl/src/include/openssl/pool.h | 10 +- .../src/include/openssl/prefix_symbols.h | 94 +- .../boringssl/src/include/openssl/rsa.h | 11 +- .../boringssl/src/include/openssl/sha.h | 58 +- .../boringssl/src/include/openssl/sha2.h | 172 +- .../boringssl/src/include/openssl/span.h | 2 +- .../src/include/openssl/trust_token.h | 14 +- .../boringssl/src/include/openssl/x509.h | 196 +- tool/REVISION | 2 +- 201 files changed, 9475 insertions(+), 7268 deletions(-) create mode 100644 third_party/boringssl/src/crypto/curve25519/cpace.cc create mode 100644 third_party/boringssl/src/crypto/digest/p_keccak.cc create mode 100644 third_party/boringssl/src/crypto/evp/p_slhdsa.cc diff --git a/CHANGELOG.md b/CHANGELOG.md index d5f5c40..1687bb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ ## 0.4.2-wip - Update BoringSSL to e98a6564. +- Update BoringSSL to 289645a4. ## 0.4.1 diff --git a/lib/src/bindings/boringssl.g.dart b/lib/src/bindings/boringssl.g.dart index 32916f6..e5c76db 100644 --- a/lib/src/bindings/boringssl.g.dart +++ b/lib/src/bindings/boringssl.g.dart @@ -1008,7 +1008,7 @@ external int ASN1_STRING_copy( /// representation that does not always correspond to the DER encoding of the /// type. See the documentation for `ASN1_STRING` for details. /// -/// Prefer `ASN1_STRING_get0_data`. +/// Prefer `ASN1_STRING_get0_data`. See crbug.com/574019297. @meta.RecordUse() @ffi.Native Function(ffi.Pointer)>( symbol: 'bssl_dart_ASN1_STRING_data', @@ -1057,7 +1057,21 @@ external ffi.Pointer ASN1_STRING_get0_data( ) external int ASN1_STRING_get_default_mask(); -/// ASN1_STRING_length returns the length of `str`, in bytes. +/// ASN1_STRING_get_length returns the length of `str`, in bytes. +/// +/// The contents of an `ASN1_STRING` encode the value in some type-specific +/// representation that does not always correspond to the DER encoding of the +/// type. See the documentation for `ASN1_STRING` for details. +@meta.RecordUse() +@ffi.Native)>( + symbol: 'bssl_dart_ASN1_STRING_get_length', +) +external int ASN1_STRING_get_length( + ffi.Pointer str, +); + +/// ASN1_STRING_length returns the length of `str`, in bytes. Prefer +/// `ASN1_STRING_get_length`. /// /// The contents of an `ASN1_STRING` encode the value in some type-specific /// representation that does not always correspond to the DER encoding of the @@ -1125,14 +1139,8 @@ external int ASN1_STRING_print_ex_fp( int flags, ); -/// ASN1_STRING_set sets the contents of `str` to a copy of `len` bytes from -/// `data`. It returns one on success and zero on error. If `data` is NULL, it -/// updates the length and allocates the buffer as needed, but does not -/// initialize the contents. -/// -/// If `str` is a BIT STRING, this function sets the number of unused bits to -/// zero. `ASN1_BIT_STRING_set1` may be used to set a BIT STRING that is not a -/// whole number of bytes. +/// ASN1_STRING_set behaves like `ASN1_STRING_set1_data` except that, if `len` is +/// negative, it implicitly calls `strlen` on data to determine the length. @meta.RecordUse() @ffi.Native< ffi.Int Function( @@ -1164,6 +1172,21 @@ external void ASN1_STRING_set0( int len, ); +/// ASN1_STRING_set1_data sets the contents of `str` to `len` bytes from `data`. +/// +/// If `str` is a BIT STRING, this function sets the number of unused bits to +/// zero. `ASN1_BIT_STRING_set1` may be used to set a BIT STRING that is not a +/// whole number of bytes. +@meta.RecordUse() +@ffi.Native< + ffi.Int Function(ffi.Pointer, ffi.Pointer, ffi.Size) +>(symbol: 'bssl_dart_ASN1_STRING_set1_data') +external int ASN1_STRING_set1_data( + ffi.Pointer str, + ffi.Pointer data, + int len, +); + /// ASN1_STRING_set_by_NID behaves like `ASN1_mbstring_ncopy`, but determines /// `mask`, `minsize`, and `maxsize` based on `nid`. When `nid` is a recognized /// X.509 attribute type, it will pick a suitable ASN.1 string type and bounds. @@ -1470,9 +1493,11 @@ external int ASN1_TIME_to_time_t( ffi.Pointer out, ); -/// ASN1_TYPE_cmp returns zero if `a` and `b` are equal and some non-zero value -/// otherwise. Note this function can only be used for equality checks, not an -/// ordering. +/// ASN1_TYPE_cmp compares `a` and `b`. It returns zero if they are equal, and a +/// negative or positive value if `a` sorts before or after `b`, respectively. +/// NULL sorts before any non-NULL value. Otherwise, values are ordered first by +/// type, then by contents. The order is arbitrary but suitable for sorting. +/// Callers should not rely on the exact order. @meta.RecordUse() @ffi.Native, ffi.Pointer)>( symbol: 'bssl_dart_ASN1_TYPE_cmp', @@ -2381,6 +2406,16 @@ external int BIO_do_connect( ffi.Pointer bio, ); +/// BIO_dup_ref increments the reference count of `bio` and returns the same +/// handle. +@meta.RecordUse() +@ffi.Native Function(ffi.Pointer)>( + symbol: 'bssl_dart_BIO_dup_ref', +) +external ffi.Pointer BIO_dup_ref( + ffi.Pointer bio, +); + /// BIO_eof returns non-zero when `bio` has reached end-of-file. The precise /// meaning of which depends on the concrete type of `bio`. Note that in the /// case of BIO_pair this always returns non-zero. @@ -4204,7 +4239,8 @@ external int BN_bn2cbb_padded( /// BN_bn2dec returns an allocated string that contains a NUL-terminated, /// decimal representation of `bn`. If `bn` is negative, the first char in the -/// resulting string will be '-'. Returns NULL on allocation failure. +/// resulting string will be '-'. Returns NULL on allocation failure. The +/// resulting string must be freed with `OPENSSL_free`. /// /// Converting an arbitrarily large integer to decimal is quadratic in the bit /// length of `a`. This function assumes the caller has capped the input within @@ -4219,7 +4255,8 @@ external ffi.Pointer BN_bn2dec( /// BN_bn2hex returns an allocated string that contains a NUL-terminated, hex /// representation of `bn`. If `bn` is negative, the first char in the resulting -/// string will be '-'. Returns NULL on allocation failure. +/// string will be '-'. Returns NULL on allocation failure. The resulting string +/// must be freed with `OPENSSL_free`. @meta.RecordUse() @ffi.Native Function(ffi.Pointer)>( symbol: 'bssl_dart_BN_bn2hex', @@ -7175,6 +7212,18 @@ external int CBS_is_valid_asn1_relative_oid( ffi.Pointer cbs, ); +/// CBS_is_valid_asn1_set_of returns one if `cbs` is an ASN.1 SET OF contents +/// (not including the element framing) with members sorted in nondescending +/// order according to DER rules, and zero otherwise. This function does not +/// parse the members and does not check that they are of any particular type. +@meta.RecordUse() +@ffi.Native)>( + symbol: 'bssl_dart_CBS_is_valid_asn1_set_of', +) +external int CBS_is_valid_asn1_set_of( + ffi.Pointer cbs, +); + /// CBS_mem_equal compares the current contents of `cbs` with the `len` bytes /// starting at `data`. If they're equal, it returns one, otherwise zero. If the /// lengths match, it uses a constant-time comparison. @@ -7338,6 +7387,106 @@ external void CONF_modules_unload( int all, ); +/// CPACE_CTX_free frees `ctx` and all the resources that it has allocated. +@meta.RecordUse() +@ffi.Native)>( + symbol: 'bssl_dart_CPACE_CTX_free', +) +external void CPACE_CTX_free( + ffi.Pointer ctx, +); + +/// CPACE_CTX_new returns a newly-allocated `CPACE_CTX` object that implements +/// one side of the CPace protocol, or nullptr on error. This function implements +/// CPACE-X25519-SHA512 in initiator-responder mode, acting as `role` and with +/// `password` as the password-related string (PRS). +/// +/// `channel_id` and `session_id` are the channel identifier (CI) and session +/// identifier (sid) values, respectively. Both values must match for the +/// exchange to proceed. `assoc_data` is the cleartext associated data (ADa or +/// ADb) to be sent to the peer. These values may be empty if not used. See +/// Section 4.1 of draft-irtf-cfrg-cpace-21 for details. +/// +/// The application-level identities of each party in the protocol should be +/// incorporated into either `channel_id` or each party's respective `assoc_data` +/// values. See Section 10.1 of draft-irtf-cfrg-cpace-21. +/// +/// Once a `CPACE_CTX` is successfully created, the caller should call +/// `CPACE_generate_msg` to generate the message to send to the peer. +@meta.RecordUse() +@ffi.Native< + ffi.Pointer Function( + ffi.UnsignedInt, + ffi.Pointer, + ffi.Size, + ffi.Pointer, + ffi.Size, + ffi.Pointer, + ffi.Size, + ffi.Pointer, + ffi.Size, + ) +>(symbol: 'bssl_dart_CPACE_CTX_new') +external ffi.Pointer CPACE_CTX_new( + int role, + ffi.Pointer password, + int password_len, + ffi.Pointer channel_id, + int channel_id_len, + ffi.Pointer assoc_data, + int assoc_data_len, + ffi.Pointer session_id, + int session_id_len, +); + +/// CPACE_generate_msg generates the message to be sent to the peer. On success, +/// it writes the message to `out_msg` and returns one. Otherwise, it returns +/// zero. `ctx` must have been allocated by `CPACE_CTX_new`, with no subsequent +/// functions called on it. +/// +/// `out_msg` only contains the Ya or Yb value. It does not include ADa or ADb. +/// On success, the caller should separately send `out_msg` and their +/// `assoc_data` value to the peer. It is the caller's responsibility to send +/// `assoc_data` together with `out_msg`. After receiving the peer's reply, the +/// caller should call `CPACE_process_msg` to complete the protocol. +@meta.RecordUse() +@ffi.Native, ffi.Pointer)>( + symbol: 'bssl_dart_CPACE_generate_msg', +) +external int CPACE_generate_msg( + ffi.Pointer ctx, + ffi.Pointer out_msg, +); + +/// CPACE_process_msg processes `msg` and `peer_assoc_data` from the peer and +/// computes the shared secret, or intermediate session key (ISK). On success, it +/// writes the secret to `out_shared_secret` and returns one; it also writes a +/// derived session ID if `out_sid` is not NULL. Otherwise, it returns zero. +/// `ctx` must have successfully been passed to `CPACE_generate_msg`, with no +/// subsequent functions called on it. +/// +/// `msg` should contain the peer's Ya or Yb value, and `peer_assoc_data` the +/// peer's ADa or ADb value. +@meta.RecordUse() +@ffi.Native< + ffi.Int Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Size, + ffi.Pointer, + ffi.Pointer, + ) +>(symbol: 'bssl_dart_CPACE_process_msg') +external int CPACE_process_msg( + ffi.Pointer ctx, + ffi.Pointer in_msg, + ffi.Pointer peer_assoc_data, + int peer_assoc_data_len, + ffi.Pointer shared_secret, + ffi.Pointer sid_out, +); + /// CRL_DIST_POINTS_free releases memory associated with `crldp`. @meta.RecordUse() @ffi.Native)>( @@ -7355,6 +7504,17 @@ external void CRL_DIST_POINTS_free( ) external ffi.Pointer CRL_DIST_POINTS_new(); +/// CRYPTO_BUFFER_POOL_dup_ref increments the reference count of `pool` and +/// returns the same handle. It does not mutate `pool` for thread-safety purposes +/// and may be used concurrently. +@meta.RecordUse() +@ffi.Native< + ffi.Pointer Function(ffi.Pointer) +>(symbol: 'bssl_dart_CRYPTO_BUFFER_POOL_dup_ref') +external ffi.Pointer CRYPTO_BUFFER_POOL_dup_ref( + ffi.Pointer pool, +); + /// CRYPTO_BUFFER_POOL_free decrements the reference count of `pool` and frees it /// if the reference count drops to zero. @meta.RecordUse() @@ -8094,6 +8254,17 @@ external int DH_compute_key_padded( ffi.Pointer dh, ); +/// DH_dup_ref increments the reference count of `dh` and returns the same +/// handle. It does not mutate `dh` for thread-safety purposes and may be used +/// concurrently. +@meta.RecordUse() +@ffi.Native Function(ffi.Pointer)>( + symbol: 'bssl_dart_DH_dup_ref', +) +external ffi.Pointer DH_dup_ref( + ffi.Pointer dh, +); + /// DH_free decrements the reference count of `dh` and frees it if the reference /// count drops to zero. @meta.RecordUse() @@ -8569,6 +8740,17 @@ external ffi.Pointer DSA_dup_DH( ffi.Pointer dsa, ); +/// DSA_dup_ref increments the reference count of `dsa` and returns the same +/// handle. It does not mutate `dsa` for thread-safety purposes and may be used +/// concurrently. +@meta.RecordUse() +@ffi.Native Function(ffi.Pointer)>( + symbol: 'bssl_dart_DSA_dup_ref', +) +external ffi.Pointer DSA_dup_ref( + ffi.Pointer dsa, +); + /// DSA_free decrements the reference count of `dsa` and frees it if the /// reference count drops to zero. @meta.RecordUse() @@ -8986,7 +9168,7 @@ external int ECDH_compute_key( /// ECDH_compute_key_fips calculates the shared key between `pub_key` and /// `priv_key` and hashes it with the appropriate SHA function for `out_len`. The -/// only value values for `out_len` are thus 24 (SHA-224), 32 (SHA-256), 48 +/// only valid values for `out_len` are thus 28 (SHA-224), 32 (SHA-256), 48 /// (SHA-384), and 64 (SHA-512). It returns one on success and zero on error. /// /// Note that the return value is different to `ECDH_compute_key`: it returns an @@ -9664,6 +9846,17 @@ external ffi.Pointer EC_KEY_dup( ffi.Pointer src, ); +/// EC_KEY_dup_ref increases the reference count of `key` and returns the same +/// handle. It does not mutate `key` for thread-safety purposes and may be used +/// concurrently. +@meta.RecordUse() +@ffi.Native Function(ffi.Pointer)>( + symbol: 'bssl_dart_EC_KEY_dup_ref', +) +external ffi.Pointer EC_KEY_dup_ref( + ffi.Pointer key, +); + /// EC_KEY_free frees all the data owned by `key` and `key` itself. @meta.RecordUse() @ffi.Native)>( @@ -12496,8 +12689,7 @@ external int EVP_DecodeBase64( /// `dst`. It returns the number of bytes written or -1 on error. /// /// WARNING: EVP_DecodeBlock's return value does not take padding into -/// account. It also strips leading whitespace and trailing -/// whitespace and minuses. +/// account. It also strips leading spaces and tabs, and trailing whitespace. @meta.RecordUse() @ffi.Native< ffi.Int Function(ffi.Pointer, ffi.Pointer, ffi.Size) @@ -12788,8 +12980,9 @@ external int EVP_DigestFinal( ffi.Pointer out_size, ); -/// EVP_DigestFinalXOF returns zero and adds an error to the error queue. -/// BoringSSL does not support any XOF digests. +/// EVP_DigestFinalXOF behaves like `EVP_DigestSqueeze` but calls +/// `EVP_MD_CTX_cleanup` after being called, so it is not possible to call it +/// multiple times. @meta.RecordUse() @ffi.Native< ffi.Int Function(ffi.Pointer, ffi.Pointer, ffi.Size) @@ -12923,9 +13116,6 @@ external int EVP_DigestSignFinal( /// Ed25519, `type` should be NULL. The `EVP_MD_CTX` itself is unused but is /// present so the API is uniform. See `EVP_DigestSign`. /// -/// This function does not mutate `pkey` for thread-safety purposes and may be -/// used concurrently with other non-mutating functions on `pkey`. -/// /// It returns one on success, or zero on error. @meta.RecordUse() @ffi.Native< @@ -12961,6 +13151,26 @@ external int EVP_DigestSignUpdate( int len, ); +/// EVP_DigestSqueeze writes len bytes of output from `ctx` to `out` and returns +/// one. This operation is only implemented if `ctx` was initialized with an +/// extendable-output function, which can return arbitrarily long outputs. If +/// not, this function returns zero. This function may be repeated to split its +/// output over multiple calls. Doing so will give the same output as +/// concatenating the calls into a single call. +@meta.RecordUse() +@ffi.Native< + ffi.Int Function( + ffi.Pointer, + ffi.Pointer, + ffi.Size, + ) +>(symbol: 'bssl_dart_EVP_DigestSqueeze') +external int EVP_DigestSqueeze( + ffi.Pointer ctx, + ffi.Pointer out, + int len, +); + /// EVP_DigestUpdate hashes `len` bytes from `data` into the hashing operation /// in `ctx`. It returns one. @meta.RecordUse() @@ -13020,9 +13230,6 @@ external int EVP_DigestVerifyFinal( /// Ed25519, `type` should be NULL. The `EVP_MD_CTX` itself is unused but is /// present so the API is uniform. See `EVP_DigestVerify`. /// -/// This function does not mutate `pkey` for thread-safety purposes and may be -/// used concurrently with other non-mutating functions on `pkey`. -/// /// It returns one on success, or zero on error. @meta.RecordUse() @ffi.Native< @@ -15535,11 +15742,6 @@ external ffi.Pointer EVP_RSA_gen( /// actual size of the signature is written to `*out_sig_len`. /// /// It returns one on success and zero otherwise. -/// -/// It does not modify `ctx`, thus it's possible to continue to use `ctx` in -/// order to sign a longer message. It also does not mutate `pkey` for -/// thread-safety purposes and may be used concurrently with other non-mutating -/// functions on `pkey`. @meta.RecordUse() @ffi.Native< ffi.Int Function( @@ -15605,11 +15807,6 @@ external int EVP_SignUpdate( /// calls to `EVP_VerifyUpdate`. /// /// It returns one on success and zero otherwise. -/// -/// It does not modify `ctx`, thus it's possible to continue to use `ctx` in -/// order to verify a longer message. It also does not mutate `pkey` for -/// thread-safety purposes and may be used concurrently with other non-mutating -/// functions on `pkey`. @meta.RecordUse() @ffi.Native< ffi.Int Function( @@ -16256,6 +16453,20 @@ external int EVP_marshal_public_key( ffi.Pointer key, ); +/// EVP_marshal_public_key_with_ec_point_format marshals key as a DER-encoded +/// `SubjectPublicKeyInfo` structure (RFC 5280) and appends the result to `cbb`. +/// `key` must be an EC key, and the EC point will be serialized in the format +/// specified by `format`. It returns one on success and zero on error. +@meta.RecordUse() +@ffi.Native< + ffi.Int Function(ffi.Pointer, ffi.Pointer, ffi.UnsignedInt) +>(symbol: 'bssl_dart_EVP_marshal_public_key_with_ec_point_format') +external int EVP_marshal_public_key_with_ec_point_format( + ffi.Pointer cbb, + ffi.Pointer key, + int format, +); + /// Hash algorithms. /// /// The following functions return `EVP_MD` objects that implement the named hash @@ -16538,6 +16749,26 @@ external ffi.Pointer EVP_pkey_rsa_pss_sha384(); ) external ffi.Pointer EVP_pkey_rsa_pss_sha512(); +/// EVP_pkey_slh_dsa_* implement SLH-DSA and HashSLH-DSA keys, encoded as in +/// RFC 9909. The `EVP_PKEY_id` values are `EVP_PKEY_SLH_DSA_*`. +@meta.RecordUse() +@ffi.Native Function()>( + symbol: 'bssl_dart_EVP_pkey_slh_dsa_sha2_128s', +) +external ffi.Pointer EVP_pkey_slh_dsa_sha2_128s(); + +@meta.RecordUse() +@ffi.Native Function()>( + symbol: 'bssl_dart_EVP_pkey_slh_dsa_sha2_128s_with_sha256', +) +external ffi.Pointer EVP_pkey_slh_dsa_sha2_128s_with_sha256(); + +@meta.RecordUse() +@ffi.Native Function()>( + symbol: 'bssl_dart_EVP_pkey_slh_dsa_shake_256f', +) +external ffi.Pointer EVP_pkey_slh_dsa_shake_256f(); + /// EVP_pkey_x25519 implements X25519 keys (RFC 7748), encoded as in RFC 8410. /// The `EVP_PKEY_id` value is `EVP_PKEY_X25519`. @meta.RecordUse() @@ -16595,6 +16826,23 @@ external ffi.Pointer EVP_sha256(); @ffi.Native Function()>(symbol: 'bssl_dart_EVP_sha384') external ffi.Pointer EVP_sha384(); +/// SHA-3 family of digest functions. +/// +/// WARNING: Prefer to use SHA-2 (e.g. `EVP_sha256`) over SHA-3. Despite being a +/// newer hash function, SHA-3 performs poorly and should only be used when +/// necessary for interoperability with existing systems. +@meta.RecordUse() +@ffi.Native Function()>(symbol: 'bssl_dart_EVP_sha3_256') +external ffi.Pointer EVP_sha3_256(); + +@meta.RecordUse() +@ffi.Native Function()>(symbol: 'bssl_dart_EVP_sha3_384') +external ffi.Pointer EVP_sha3_384(); + +@meta.RecordUse() +@ffi.Native Function()>(symbol: 'bssl_dart_EVP_sha3_512') +external ffi.Pointer EVP_sha3_512(); + @meta.RecordUse() @ffi.Native Function()>(symbol: 'bssl_dart_EVP_sha512') external ffi.Pointer EVP_sha512(); @@ -16603,6 +16851,32 @@ external ffi.Pointer EVP_sha512(); @ffi.Native Function()>(symbol: 'bssl_dart_EVP_sha512_256') external ffi.Pointer EVP_sha512_256(); +/// EVP_shake* implement SHAKE128 and SHAKE256 extendable-output function. +/// +/// WARNING: SHAKE is slow. Prefer SHA-2, or TurboSHAKE (`EVP_turboshake*`) if +/// an XOF is needed. +@meta.RecordUse() +@ffi.Native Function()>(symbol: 'bssl_dart_EVP_shake128') +external ffi.Pointer EVP_shake128(); + +@meta.RecordUse() +@ffi.Native Function()>(symbol: 'bssl_dart_EVP_shake256') +external ffi.Pointer EVP_shake256(); + +/// EVP_turboshake* implement TurboSHAKE (RFC 9861). TurboSHAKE is similar to +/// SHAKE, but is faster due to it using a more practical round count. +@meta.RecordUse() +@ffi.Native Function()>( + symbol: 'bssl_dart_EVP_turboshake128', +) +external ffi.Pointer EVP_turboshake128(); + +@meta.RecordUse() +@ffi.Native Function()>( + symbol: 'bssl_dart_EVP_turboshake256', +) +external ffi.Pointer EVP_turboshake256(); + /// EXTENDED_KEY_USAGE_free releases memory associated with `eku`. @meta.RecordUse() @ffi.Native)>( @@ -17340,8 +17614,7 @@ external ffi.Pointer NETSCAPE_SPKI_get_pubkey( external ffi.Pointer NETSCAPE_SPKI_new(); /// NETSCAPE_SPKI_set_pubkey sets `spki`'s public key to `pkey`. It returns one -/// on success or zero on error. This function does not take ownership of `pkey`, -/// so the caller may continue to manage its lifetime independently of `spki`. +/// on success or zero on error. @meta.RecordUse() @ffi.Native< ffi.Int Function(ffi.Pointer, ffi.Pointer) @@ -20533,6 +20806,17 @@ external int RSA_decrypt( int padding, ); +/// RSA_dup_ref increments the reference count of `rsa` and returns the same +/// handle. It does not mutate `rsa` for thread-safety purposes and may be used +/// concurrently. +@meta.RecordUse() +@ffi.Native Function(ffi.Pointer)>( + symbol: 'bssl_dart_RSA_dup_ref', +) +external ffi.Pointer RSA_dup_ref( + ffi.Pointer rsa, +); + /// RSA_encrypt encrypts `in_len` bytes from `in` to the public key from `rsa` /// and writes, at most, `max_out` bytes of encrypted data to `out`. The /// `max_out` argument must be, at least, `RSA_size` in order to ensure success. @@ -20609,7 +20893,7 @@ external int RSA_generate_key_ex( /// RSA_generate_key_fips behaves like `RSA_generate_key_ex` but performs /// additional checks for FIPS compliance. The public exponent is always 65537 -/// and `bits` must be either 2048 or 3072. +/// and `bits` must be one of 2048, 3072 and 4096. @meta.RecordUse() @ffi.Native, ffi.Int, ffi.Pointer)>( symbol: 'bssl_dart_RSA_generate_key_fips', @@ -21631,23 +21915,6 @@ external int RSA_verify_raw( int padding, ); -/// SHA1 writes the digest of `len` bytes from `data` to `out` and returns -/// `out`. There must be at least `SHA_DIGEST_LENGTH` bytes of space in -/// `out`. -@meta.RecordUse() -@ffi.Native< - ffi.Pointer Function( - ffi.Pointer, - ffi.Size, - ffi.Pointer, - ) ->(symbol: 'bssl_dart_SHA1') -external ffi.Pointer SHA1( - ffi.Pointer data, - int len, - ffi.Pointer out, -); - /// SHA1_Final adds the final padding to `sha` and writes the resulting digest to /// `out`, which must have at least `SHA_DIGEST_LENGTH` bytes of space. It /// returns one. @@ -21692,26 +21959,11 @@ external int SHA1_Update( int len, ); -/// SHA224 writes the digest of `len` bytes from `data` to `out` and returns -/// `out`. There must be at least `SHA224_DIGEST_LENGTH` bytes of space in -/// `out`. -@meta.RecordUse() -@ffi.Native< - ffi.Pointer Function( - ffi.Pointer, - ffi.Size, - ffi.Pointer, - ) ->(symbol: 'bssl_dart_SHA224') -external ffi.Pointer SHA224( - ffi.Pointer data, - int len, - ffi.Pointer out, -); - /// SHA224_Final adds the final padding to `sha` and writes the resulting digest /// to `out`, which must have at least `SHA224_DIGEST_LENGTH` bytes of space. It /// returns 1. +/// +/// `sha` must have been initialised for SHA-224. @meta.RecordUse() @ffi.Native, ffi.Pointer)>( symbol: 'bssl_dart_SHA224_Final', @@ -21721,7 +21973,7 @@ external int SHA224_Final( ffi.Pointer sha, ); -/// SHA224_Init initialises `sha` and returns 1. +/// SHA224_Init initialises `sha` for SHA-224 and returns 1. @meta.RecordUse() @ffi.Native)>( symbol: 'bssl_dart_SHA224_Init', @@ -21731,6 +21983,8 @@ external int SHA224_Init( ); /// SHA224_Update adds `len` bytes from `data` to `sha` and returns 1. +/// +/// `sha` must have been initialised for SHA-224. @meta.RecordUse() @ffi.Native< ffi.Int Function(ffi.Pointer, ffi.Pointer, ffi.Size) @@ -21741,26 +21995,11 @@ external int SHA224_Update( int len, ); -/// SHA256 writes the digest of `len` bytes from `data` to `out` and returns -/// `out`. There must be at least `SHA256_DIGEST_LENGTH` bytes of space in -/// `out`. -@meta.RecordUse() -@ffi.Native< - ffi.Pointer Function( - ffi.Pointer, - ffi.Size, - ffi.Pointer, - ) ->(symbol: 'bssl_dart_SHA256') -external ffi.Pointer SHA256( - ffi.Pointer data, - int len, - ffi.Pointer out, -); - /// SHA256_Final adds the final padding to `sha` and writes the resulting digest /// to `out`, which must have at least `SHA256_DIGEST_LENGTH` bytes of space. It /// returns one on success and zero on programmer error. +/// +/// `sha` must have been initialised for SHA-256. @meta.RecordUse() @ffi.Native, ffi.Pointer)>( symbol: 'bssl_dart_SHA256_Final', @@ -21770,7 +22009,7 @@ external int SHA256_Final( ffi.Pointer sha, ); -/// SHA256_Init initialises `sha` and returns 1. +/// SHA256_Init initialises `sha` for SHA-256 and returns 1. @meta.RecordUse() @ffi.Native)>( symbol: 'bssl_dart_SHA256_Init', @@ -21806,6 +22045,8 @@ external void SHA256_TransformBlocks( ); /// SHA256_Update adds `len` bytes from `data` to `sha` and returns 1. +/// +/// `sha` must have been initialised for SHA-256. @meta.RecordUse() @ffi.Native< ffi.Int Function(ffi.Pointer, ffi.Pointer, ffi.Size) @@ -21816,26 +22057,11 @@ external int SHA256_Update( int len, ); -/// SHA384 writes the digest of `len` bytes from `data` to `out` and returns -/// `out`. There must be at least `SHA384_DIGEST_LENGTH` bytes of space in -/// `out`. -@meta.RecordUse() -@ffi.Native< - ffi.Pointer Function( - ffi.Pointer, - ffi.Size, - ffi.Pointer, - ) ->(symbol: 'bssl_dart_SHA384') -external ffi.Pointer SHA384( - ffi.Pointer data, - int len, - ffi.Pointer out, -); - /// SHA384_Final adds the final padding to `sha` and writes the resulting digest /// to `out`, which must have at least `SHA384_DIGEST_LENGTH` bytes of space. It /// returns one on success and zero on programmer error. +/// +/// `sha` must have been initialised for SHA-384. @meta.RecordUse() @ffi.Native, ffi.Pointer)>( symbol: 'bssl_dart_SHA384_Final', @@ -21845,7 +22071,7 @@ external int SHA384_Final( ffi.Pointer sha, ); -/// SHA384_Init initialises `sha` and returns 1. +/// SHA384_Init initialises `sha` for SHA-384 and returns 1. @meta.RecordUse() @ffi.Native)>( symbol: 'bssl_dart_SHA384_Init', @@ -21855,6 +22081,8 @@ external int SHA384_Init( ); /// SHA384_Update adds `len` bytes from `data` to `sha` and returns 1. +/// +/// `sha` must have been initialised for SHA-384. @meta.RecordUse() @ffi.Native< ffi.Int Function(ffi.Pointer, ffi.Pointer, ffi.Size) @@ -21865,43 +22093,11 @@ external int SHA384_Update( int len, ); -/// SHA512 writes the digest of `len` bytes from `data` to `out` and returns -/// `out`. There must be at least `SHA512_DIGEST_LENGTH` bytes of space in -/// `out`. -@meta.RecordUse() -@ffi.Native< - ffi.Pointer Function( - ffi.Pointer, - ffi.Size, - ffi.Pointer, - ) ->(symbol: 'bssl_dart_SHA512') -external ffi.Pointer SHA512( - ffi.Pointer data, - int len, - ffi.Pointer out, -); - -/// SHA512_256 writes the digest of `len` bytes from `data` to `out` and returns -/// `out`. There must be at least `SHA512_256_DIGEST_LENGTH` bytes of space in -/// `out`. -@meta.RecordUse() -@ffi.Native< - ffi.Pointer Function( - ffi.Pointer, - ffi.Size, - ffi.Pointer, - ) ->(symbol: 'bssl_dart_SHA512_256') -external ffi.Pointer SHA512_256( - ffi.Pointer data, - int len, - ffi.Pointer out, -); - /// SHA512_256_Final adds the final padding to `sha` and writes the resulting /// digest to `out`, which must have at least `SHA512_256_DIGEST_LENGTH` bytes of /// space. It returns one on success and zero on programmer error. +/// +/// `sha` must have been initialised for SHA-512/256. @meta.RecordUse() @ffi.Native, ffi.Pointer)>( symbol: 'bssl_dart_SHA512_256_Final', @@ -21911,7 +22107,7 @@ external int SHA512_256_Final( ffi.Pointer sha, ); -/// SHA512_256_Init initialises `sha` and returns 1. +/// SHA512_256_Init initialises `sha` for SHA-512/256 and returns 1. @meta.RecordUse() @ffi.Native)>( symbol: 'bssl_dart_SHA512_256_Init', @@ -21921,6 +22117,8 @@ external int SHA512_256_Init( ); /// SHA512_256_Update adds `len` bytes from `data` to `sha` and returns 1. +/// +/// `sha` must have been initialised for SHA-512/256. @meta.RecordUse() @ffi.Native< ffi.Int Function(ffi.Pointer, ffi.Pointer, ffi.Size) @@ -21934,6 +22132,8 @@ external int SHA512_256_Update( /// SHA512_Final adds the final padding to `sha` and writes the resulting digest /// to `out`, which must have at least `SHA512_DIGEST_LENGTH` bytes of space. It /// returns one on success and zero on programmer error. +/// +/// `sha` must have been initialised for SHA-512. @meta.RecordUse() @ffi.Native, ffi.Pointer)>( symbol: 'bssl_dart_SHA512_Final', @@ -21965,6 +22165,8 @@ external void SHA512_Transform( ); /// SHA512_Update adds `len` bytes from `data` to `sha` and returns 1. +/// +/// `sha` must have been initialised for SHA-512. @meta.RecordUse() @ffi.Native< ffi.Int Function(ffi.Pointer, ffi.Pointer, ffi.Size) @@ -22593,9 +22795,11 @@ external void X509V3_set_nconf( ffi.Pointer conf, ); -/// X509_ALGOR_cmp returns zero if `a` and `b` are equal, and some non-zero value -/// otherwise. Note this function can only be used for equality checks, not an -/// ordering. +/// X509_ALGOR_cmp compares `a` and `b`. It returns zero if they are equal, and a +/// negative or positive value if `a` sorts before or after `b`, respectively. +/// Values are ordered first by algorithm, then by parameter, with an absent +/// parameter sorting before a present one. The order is arbitrary but suitable +/// for sorting. Callers should not rely on the exact order. @meta.RecordUse() @ffi.Native, ffi.Pointer)>( symbol: 'bssl_dart_X509_ALGOR_cmp', @@ -23066,6 +23270,16 @@ external ffi.Pointer X509_CRL_dup( ffi.Pointer crl, ); +/// X509_CRL_dup_ref adds one to the reference count of `crl` and returns the +/// same. +@meta.RecordUse() +@ffi.Native Function(ffi.Pointer)>( + symbol: 'bssl_dart_X509_CRL_dup_ref', +) +external ffi.Pointer X509_CRL_dup_ref( + ffi.Pointer crl, +); + /// X509_CRL_free decrements `crl`'s reference count and, if zero, releases /// memory associated with `crl`. @meta.RecordUse() @@ -25004,8 +25218,7 @@ external int X509_REQ_set1_signature_value( ); /// X509_REQ_set_pubkey sets `req`'s public key to `pkey`. It returns one on -/// success and zero on error. This function does not take ownership of `pkey` -/// and internally copies and updates reference counts as needed. +/// success and zero on error. @meta.RecordUse() @ffi.Native, ffi.Pointer)>( symbol: 'bssl_dart_X509_REQ_set_pubkey', @@ -25399,16 +25612,6 @@ external ffi.Pointer X509_STORE_CTX_get0_chain( ffi.Pointer ctx, ); -/// X509_STORE_CTX_get0_current_crl returns the CRL which caused the error -/// returned by `X509_STORE_CTX_get_error`. -@meta.RecordUse() -@ffi.Native Function(ffi.Pointer)>( - symbol: 'bssl_dart_X509_STORE_CTX_get0_current_crl', -) -external ffi.Pointer X509_STORE_CTX_get0_current_crl( - ffi.Pointer ctx, -); - /// X509_STORE_CTX_get0_param returns `ctx`'s verification parameters. This /// object is mutable and may be modified by the caller. @meta.RecordUse() @@ -25924,8 +26127,9 @@ external void X509_STORE_CTX_trusted_stack( /// returns one on success and zero on error. This function internally increments /// `x509`'s reference count, so the caller retains ownership of `x509`. /// -/// Certificates configured by this function are still subject to the checks -/// described in `X509_VERIFY_PARAM_set_trust`. +/// Certificates configured by this function are potential trust anchors, but +/// whether they are trust anchors for any given verification depends on the +/// checks described in `X509_VERIFY_PARAM_set_trust`. /// /// Although `store` is not const, this function's use of `store` is thread-safe. /// However, if this function is called concurrently with `X509_verify_cert`, it @@ -25986,6 +26190,16 @@ external ffi.Pointer X509_STORE_add_lookup( ffi.Pointer method, ); +/// X509_STORE_dup_ref adds one to the reference count of `store` and returns +/// the same handle. +@meta.RecordUse() +@ffi.Native Function(ffi.Pointer)>( + symbol: 'bssl_dart_X509_STORE_dup_ref', +) +external ffi.Pointer X509_STORE_dup_ref( + ffi.Pointer store, +); + /// X509_STORE_free releases memory associated with `store`. @meta.RecordUse() @ffi.Native)>( @@ -26828,6 +27042,10 @@ external int X509_check_purpose( /// was distrusted, and `X509_TRUST_UNTRUSTED` otherwise. `id` should be one of /// the `X509_TRUST_*` constants, or zero to indicate the default behavior. /// `flags` should be zero and is ignored. +/// +/// WARNING: This function assumes `x509` is a trusted certificate, installed in +/// an `X509_STORE`. If passed an arbitrary certificate from an untrusted source, +/// it may return `X509_TRUST_TRUSTED`. @meta.RecordUse() @ffi.Native, ffi.Int, ffi.Int)>( symbol: 'bssl_dart_X509_check_trust', @@ -27931,8 +28149,7 @@ external int X509_set_notBefore( ); /// X509_set_pubkey sets `x509`'s public key to `pkey`. It returns one on success -/// and zero on error. This function does not take ownership of `pkey` and -/// internally copies and updates reference counts as needed. +/// and zero on error. @meta.RecordUse() @ffi.Native, ffi.Pointer)>( symbol: 'bssl_dart_X509_set_pubkey', @@ -27964,6 +28181,20 @@ external int X509_set_subject_name( ffi.Pointer name, ); +/// X509_set_unsigned fills in the placeholder fields in `x509` to make an +/// unsigned certificate (RFC 9925) and returns one on success or zero on error. +/// It sets the signature algorithm to id-alg-unsigned and the signature value to +/// the empty string. If the issuer is empty, it additionally sets the issuer to +/// the id-rdna-unsigned placeholder value. Otherwise, it retains the existing +/// issuer value. +@meta.RecordUse() +@ffi.Native)>( + symbol: 'bssl_dart_X509_set_unsigned', +) +external int X509_set_unsigned( + ffi.Pointer x509, +); + /// X509_set_version sets `x509`'s version to `version`, which should be one of /// the `X509V_VERSION_*` constants. It returns one on success and zero on error. /// @@ -28633,9 +28864,6 @@ external ffi.Pointer d2i_ASN1_T61STRING( /// d2i_ASN1_TIME parses up to `len` bytes from `*inp` as a DER-encoded X.509 /// Time (RFC 5280), as described in `d2i_SAMPLE`. -/// -/// TODO(https://crbug.com/boringssl/354): This function currently also accepts -/// BER, but this will be removed in the future. @meta.RecordUse() @ffi.Native< ffi.Pointer Function( @@ -28688,9 +28916,6 @@ external ffi.Pointer d2i_ASN1_UNIVERSALSTRING( /// d2i_ASN1_UTCTIME parses up to `len` bytes from `*inp` as a DER-encoded /// ASN.1 UTCTime, as described in `d2i_SAMPLE`. -/// -/// TODO(https://crbug.com/boringssl/354): This function currently also accepts -/// BER, but this will be removed in the future. @meta.RecordUse() @ffi.Native< ffi.Pointer Function( @@ -31827,6 +32052,9 @@ extension SymbolAddresses on _SymbolAddresses { ffi.Pointer> get CONF_modules_free => ffi.Native.addressOf(self.CONF_modules_free); @meta.RecordUse() + ffi.Pointer)>> + get CPACE_CTX_free => ffi.Native.addressOf(self.CPACE_CTX_free); + @meta.RecordUse() ffi.Pointer< ffi.NativeFunction)> > @@ -32309,6 +32537,8 @@ const int CBS_ASN1_PRINTABLESTRING = 19; const int CBS_ASN1_PRIVATE = 3221225472; +const int CBS_ASN1_RELATIVE_OID = 13; + const int CBS_ASN1_SEQUENCE = 536870928; const int CBS_ASN1_SET = 536870929; @@ -32348,6 +32578,7 @@ final class CMS_SignerInfo_st extends ffi.Opaque {} typedef CONF = conf_st; typedef CONF_VALUE = conf_value_st; +typedef CPACE_CTX = cpace_ctx_st; typedef CRL_DIST_POINTS = stack_st_DIST_POINT; typedef CRYPTO_BUFFER = crypto_buffer_st; typedef CRYPTO_BUFFER_POOL = crypto_buffer_pool_st; @@ -32447,9 +32678,6 @@ final class DIST_POINT_NAME_st extends ffi.Struct { external int type; external UnnamedUnion$4 name; - - /// If relativename then this contains the full distribution point name - external ffi.Pointer dpname; } /// A DIST_POINT_st, aka `DIST_POINT`, represents a DistributionPoint structure @@ -32813,9 +33041,9 @@ const int EVP_MAX_IV_LENGTH = 16; const int EVP_MAX_KEY_LENGTH = 64; -const int EVP_MAX_MD_BLOCK_SIZE = 128; +const int EVP_MAX_MD_BLOCK_SIZE = 168; -const int EVP_MAX_MD_DATA_SIZE = 208; +const int EVP_MAX_MD_DATA_SIZE = 240; const int EVP_MAX_MD_SIZE = 64; @@ -32862,6 +33090,12 @@ const int EVP_PKEY_RSA2 = 19; const int EVP_PKEY_RSA_PSS = 912; +const int EVP_PKEY_SLH_DSA_SHA2_128S = 973; + +const int EVP_PKEY_SLH_DSA_SHA2_128S_WITH_SHA256 = 975; + +const int EVP_PKEY_SLH_DSA_SHAKE_256F = 974; + const int EVP_PKEY_X25519 = 948; const int EVP_PKEY_X448 = 961; @@ -33114,11 +33348,11 @@ const int NID_OCSP_sign = 180; const int NID_Private = 385; -const int NID_SLH_DSA_SHA2_128s = 979; +const int NID_SLH_DSA_SHA2_128s = 973; -const int NID_SLH_DSA_SHA2_128s_WITH_SHA256 = 981; +const int NID_SLH_DSA_SHA2_128s_WITH_SHA256 = 975; -const int NID_SLH_DSA_SHAKE_256f = 980; +const int NID_SLH_DSA_SHAKE_256f = 974; const int NID_SMIME = 188; @@ -33300,7 +33534,9 @@ const int NID_aes_256_ofb128 = 428; const int NID_aes_256_xts = 914; -const int NID_alg_mtcProof_draft = 976; +const int NID_alg_mtcProof = 976; + +const int NID_alg_unsigned = 979; const int NID_algorithm = 376; @@ -34370,7 +34606,7 @@ const int NID_pbes2 = 161; const int NID_pbmac1 = 162; -const int NID_pe_mtcCertificationAuthority_draft = 978; +const int NID_pe_mtcCertificationAuthority_SHA256 = 978; const int NID_personalSignature = 499; @@ -34500,7 +34736,9 @@ const int NID_rc5_ecb = 121; const int NID_rc5_ofb64 = 123; -const int NID_rdna_trustAnchorID_draft = 977; +const int NID_rdna_trustAnchorID = 977; + +const int NID_rdna_unsigned = 980; const int NID_registeredAddress = 870; @@ -35602,7 +35840,7 @@ final class UnnamedUnion$1 extends ffi.Union { /// md_data contains the hash-specific context. final class UnnamedUnion$2 extends ffi.Union { - @ffi.Array.multi([208]) + @ffi.Array.multi([240]) external ffi.Array md_data; @ffi.Uint64() @@ -35725,6 +35963,8 @@ const int V_ASN1_PRIVATE = 192; const int V_ASN1_REAL = 9; +const int V_ASN1_RELATIVE_OID = 13; + const int V_ASN1_SEQUENCE = 16; const int V_ASN1_SET = 17; @@ -36199,11 +36439,13 @@ const int X509_V_ERR_UNSUPPORTED_NAME_SYNTAX = 53; const int X509_V_FLAG_ALLOW_PROXY_CERTS = 64; +const int X509_V_FLAG_ALLOW_SHA1 = 33554432; + const int X509_V_FLAG_ALLOW_TIMEZONE_OFFSET = 16777216; const int X509_V_FLAG_CB_ISSUER_CHECK = 1; -const int X509_V_FLAG_CHECK_SS_SIGNATURE = 16384; +const int X509_V_FLAG_CHECK_SS_SIGNATURE = 0; const int X509_V_FLAG_CRL_CHECK = 4; @@ -36235,8 +36477,6 @@ const int X509_V_FLAG_USE_CHECK_TIME = 2; const int X509_V_FLAG_USE_DELTAS = 8192; -const int X509_V_FLAG_USE_MTC_DRAFT_PLANTS_05 = 4194304; - const int X509_V_FLAG_X509_STRICT = 0; const int X509_V_OK = 0; @@ -36306,76 +36546,7 @@ final class _G_fpos_t extends ffi.Struct { external __mbstate_t __state; } -final class _IO_FILE extends ffi.Struct { - @ffi.Int() - external int _flags; - - external ffi.Pointer _IO_read_ptr; - - external ffi.Pointer _IO_read_end; - - external ffi.Pointer _IO_read_base; - - external ffi.Pointer _IO_write_base; - - external ffi.Pointer _IO_write_ptr; - - external ffi.Pointer _IO_write_end; - - external ffi.Pointer _IO_buf_base; - - external ffi.Pointer _IO_buf_end; - - external ffi.Pointer _IO_save_base; - - external ffi.Pointer _IO_backup_base; - - external ffi.Pointer _IO_save_end; - - external ffi.Pointer<_IO_marker> _markers; - - external ffi.Pointer<_IO_FILE> _chain; - - @ffi.Int() - external int _fileno; - - @ffi.Int() - external int _flags2; - - @__off_t() - external int _old_offset; - - @ffi.UnsignedShort() - external int _cur_column; - - @ffi.SignedChar() - external int _vtable_offset; - - @ffi.Array.multi([1]) - external ffi.Array _shortbuf; - - external ffi.Pointer<_IO_lock_t> _lock; - - @__off64_t() - external int _offset; - - external ffi.Pointer<_IO_codecvt> _codecvt; - - external ffi.Pointer<_IO_wide_data> _wide_data; - - external ffi.Pointer<_IO_FILE> _freeres_list; - - external ffi.Pointer _freeres_buf; - - @ffi.Size() - external int __pad5; - - @ffi.Int() - external int _mode; - - @ffi.Array.multi([20]) - external ffi.Array _unused2; -} +final class _IO_FILE extends ffi.Opaque {} final class _IO_codecvt extends ffi.Opaque {} @@ -36530,9 +36701,6 @@ final class __pthread_cond_s extends ffi.Struct { external __atomic_wide_counter __g1_start; - @ffi.Array.multi([2]) - external ffi.Array __g_refs; - @ffi.Array.multi([2]) external ffi.Array __g_size; @@ -36544,6 +36712,12 @@ final class __pthread_cond_s extends ffi.Struct { @ffi.Array.multi([2]) external ffi.Array __g_signals; + + @ffi.UnsignedInt() + external int __unused_initialized_1; + + @ffi.UnsignedInt() + external int __unused_initialized_2; } final class __pthread_internal_list extends ffi.Struct { @@ -36578,7 +36752,7 @@ final class __pthread_mutex_s extends ffi.Struct { external int __spins; @ffi.Short() - external int __elision; + external int __unused; external __pthread_list_t __list; } @@ -36608,11 +36782,8 @@ final class __pthread_rwlock_arch_t extends ffi.Struct { @ffi.Int() external int __shared; - @ffi.SignedChar() - external int __rwelision; - - @ffi.Array.multi([7]) - external ffi.Array __pad1; + @ffi.UnsignedLong() + external int __pad1; @ffi.UnsignedLong() external int __pad2; @@ -37131,6 +37302,17 @@ typedef cookie_write_function_t = ) >; +final class cpace_ctx_st extends ffi.Opaque {} + +/// The role that a party plays in the CPACE key agreement protocol. +sealed class cpace_role_t { + /// This role corresponds to the party A in the specification. + static const cpace_role_initiator = 0; + + /// This role corresponds to the party B in the specification. + static const cpace_role_responder = 1; +} + final class crypto_buffer_pool_st extends ffi.Opaque {} final class crypto_buffer_st extends ffi.Opaque {} diff --git a/lib/src/bindings/record_use_mapping.g.dart b/lib/src/bindings/record_use_mapping.g.dart index e680561..27c79f4 100644 --- a/lib/src/bindings/record_use_mapping.g.dart +++ b/lib/src/bindings/record_use_mapping.g.dart @@ -93,6 +93,7 @@ const recordUseMapping = { 'ASN1_STRING_free': 'bssl_dart_ASN1_STRING_free', 'ASN1_STRING_get0_data': 'bssl_dart_ASN1_STRING_get0_data', 'ASN1_STRING_get_default_mask': 'bssl_dart_ASN1_STRING_get_default_mask', + 'ASN1_STRING_get_length': 'bssl_dart_ASN1_STRING_get_length', 'ASN1_STRING_length': 'bssl_dart_ASN1_STRING_length', 'ASN1_STRING_new': 'bssl_dart_ASN1_STRING_new', 'ASN1_STRING_print': 'bssl_dart_ASN1_STRING_print', @@ -100,6 +101,7 @@ const recordUseMapping = { 'ASN1_STRING_print_ex_fp': 'bssl_dart_ASN1_STRING_print_ex_fp', 'ASN1_STRING_set': 'bssl_dart_ASN1_STRING_set', 'ASN1_STRING_set0': 'bssl_dart_ASN1_STRING_set0', + 'ASN1_STRING_set1_data': 'bssl_dart_ASN1_STRING_set1_data', 'ASN1_STRING_set_by_NID': 'bssl_dart_ASN1_STRING_set_by_NID', 'ASN1_STRING_set_default_mask': 'bssl_dart_ASN1_STRING_set_default_mask', 'ASN1_STRING_set_default_mask_asc': @@ -182,6 +184,7 @@ const recordUseMapping = { 'BIO_ctrl_get_write_guarantee': 'bssl_dart_BIO_ctrl_get_write_guarantee', 'BIO_ctrl_pending': 'bssl_dart_BIO_ctrl_pending', 'BIO_do_connect': 'bssl_dart_BIO_do_connect', + 'BIO_dup_ref': 'bssl_dart_BIO_dup_ref', 'BIO_eof': 'bssl_dart_BIO_eof', 'BIO_find_type': 'bssl_dart_BIO_find_type', 'BIO_flush': 'bssl_dart_BIO_flush', @@ -530,6 +533,7 @@ const recordUseMapping = { 'CBS_is_valid_asn1_integer': 'bssl_dart_CBS_is_valid_asn1_integer', 'CBS_is_valid_asn1_oid': 'bssl_dart_CBS_is_valid_asn1_oid', 'CBS_is_valid_asn1_relative_oid': 'bssl_dart_CBS_is_valid_asn1_relative_oid', + 'CBS_is_valid_asn1_set_of': 'bssl_dart_CBS_is_valid_asn1_set_of', 'CBS_mem_equal': 'bssl_dart_CBS_mem_equal', 'CBS_parse_generalized_time': 'bssl_dart_CBS_parse_generalized_time', 'CBS_parse_utc_time': 'bssl_dart_CBS_parse_utc_time', @@ -543,8 +547,13 @@ const recordUseMapping = { 'CONF_modules_free': 'bssl_dart_CONF_modules_free', 'CONF_modules_load_file': 'bssl_dart_CONF_modules_load_file', 'CONF_modules_unload': 'bssl_dart_CONF_modules_unload', + 'CPACE_CTX_free': 'bssl_dart_CPACE_CTX_free', + 'CPACE_CTX_new': 'bssl_dart_CPACE_CTX_new', + 'CPACE_generate_msg': 'bssl_dart_CPACE_generate_msg', + 'CPACE_process_msg': 'bssl_dart_CPACE_process_msg', 'CRL_DIST_POINTS_free': 'bssl_dart_CRL_DIST_POINTS_free', 'CRL_DIST_POINTS_new': 'bssl_dart_CRL_DIST_POINTS_new', + 'CRYPTO_BUFFER_POOL_dup_ref': 'bssl_dart_CRYPTO_BUFFER_POOL_dup_ref', 'CRYPTO_BUFFER_POOL_free': 'bssl_dart_CRYPTO_BUFFER_POOL_free', 'CRYPTO_BUFFER_POOL_new': 'bssl_dart_CRYPTO_BUFFER_POOL_new', 'CRYPTO_BUFFER_POOL_up_ref': 'bssl_dart_CRYPTO_BUFFER_POOL_up_ref', @@ -602,6 +611,7 @@ const recordUseMapping = { 'DH_compute_key': 'bssl_dart_DH_compute_key', 'DH_compute_key_hashed': 'bssl_dart_DH_compute_key_hashed', 'DH_compute_key_padded': 'bssl_dart_DH_compute_key_padded', + 'DH_dup_ref': 'bssl_dart_DH_dup_ref', 'DH_free': 'bssl_dart_DH_free', 'DH_generate_key': 'bssl_dart_DH_generate_key', 'DH_generate_parameters_ex': 'bssl_dart_DH_generate_parameters_ex', @@ -642,6 +652,7 @@ const recordUseMapping = { 'DSA_do_sign': 'bssl_dart_DSA_do_sign', 'DSA_do_verify': 'bssl_dart_DSA_do_verify', 'DSA_dup_DH': 'bssl_dart_DSA_dup_DH', + 'DSA_dup_ref': 'bssl_dart_DSA_dup_ref', 'DSA_free': 'bssl_dart_DSA_free', 'DSA_generate_key': 'bssl_dart_DSA_generate_key', 'DSA_generate_parameters_ex': 'bssl_dart_DSA_generate_parameters_ex', @@ -715,6 +726,7 @@ const recordUseMapping = { 'EC_KEY_check_key': 'bssl_dart_EC_KEY_check_key', 'EC_KEY_derive_from_secret': 'bssl_dart_EC_KEY_derive_from_secret', 'EC_KEY_dup': 'bssl_dart_EC_KEY_dup', + 'EC_KEY_dup_ref': 'bssl_dart_EC_KEY_dup_ref', 'EC_KEY_free': 'bssl_dart_EC_KEY_free', 'EC_KEY_generate_key': 'bssl_dart_EC_KEY_generate_key', 'EC_KEY_generate_key_fips': 'bssl_dart_EC_KEY_generate_key_fips', @@ -928,6 +940,7 @@ const recordUseMapping = { 'EVP_DigestSignFinal': 'bssl_dart_EVP_DigestSignFinal', 'EVP_DigestSignInit': 'bssl_dart_EVP_DigestSignInit', 'EVP_DigestSignUpdate': 'bssl_dart_EVP_DigestSignUpdate', + 'EVP_DigestSqueeze': 'bssl_dart_EVP_DigestSqueeze', 'EVP_DigestUpdate': 'bssl_dart_EVP_DigestUpdate', 'EVP_DigestVerify': 'bssl_dart_EVP_DigestVerify', 'EVP_DigestVerifyFinal': 'bssl_dart_EVP_DigestVerifyFinal', @@ -1210,6 +1223,8 @@ const recordUseMapping = { 'bssl_dart_EVP_marshal_digest_algorithm_no_params', 'EVP_marshal_private_key': 'bssl_dart_EVP_marshal_private_key', 'EVP_marshal_public_key': 'bssl_dart_EVP_marshal_public_key', + 'EVP_marshal_public_key_with_ec_point_format': + 'bssl_dart_EVP_marshal_public_key_with_ec_point_format', 'EVP_md4': 'bssl_dart_EVP_md4', 'EVP_md5': 'bssl_dart_EVP_md5', 'EVP_md5_sha1': 'bssl_dart_EVP_md5_sha1', @@ -1232,6 +1247,10 @@ const recordUseMapping = { 'EVP_pkey_rsa_pss_sha256': 'bssl_dart_EVP_pkey_rsa_pss_sha256', 'EVP_pkey_rsa_pss_sha384': 'bssl_dart_EVP_pkey_rsa_pss_sha384', 'EVP_pkey_rsa_pss_sha512': 'bssl_dart_EVP_pkey_rsa_pss_sha512', + 'EVP_pkey_slh_dsa_sha2_128s': 'bssl_dart_EVP_pkey_slh_dsa_sha2_128s', + 'EVP_pkey_slh_dsa_sha2_128s_with_sha256': + 'bssl_dart_EVP_pkey_slh_dsa_sha2_128s_with_sha256', + 'EVP_pkey_slh_dsa_shake_256f': 'bssl_dart_EVP_pkey_slh_dsa_shake_256f', 'EVP_pkey_x25519': 'bssl_dart_EVP_pkey_x25519', 'EVP_pkey_xwing': 'bssl_dart_EVP_pkey_xwing', 'EVP_rc2_40_cbc': 'bssl_dart_EVP_rc2_40_cbc', @@ -1241,8 +1260,15 @@ const recordUseMapping = { 'EVP_sha224': 'bssl_dart_EVP_sha224', 'EVP_sha256': 'bssl_dart_EVP_sha256', 'EVP_sha384': 'bssl_dart_EVP_sha384', + 'EVP_sha3_256': 'bssl_dart_EVP_sha3_256', + 'EVP_sha3_384': 'bssl_dart_EVP_sha3_384', + 'EVP_sha3_512': 'bssl_dart_EVP_sha3_512', 'EVP_sha512': 'bssl_dart_EVP_sha512', 'EVP_sha512_256': 'bssl_dart_EVP_sha512_256', + 'EVP_shake128': 'bssl_dart_EVP_shake128', + 'EVP_shake256': 'bssl_dart_EVP_shake256', + 'EVP_turboshake128': 'bssl_dart_EVP_turboshake128', + 'EVP_turboshake256': 'bssl_dart_EVP_turboshake256', 'EXTENDED_KEY_USAGE_free': 'bssl_dart_EXTENDED_KEY_USAGE_free', 'EXTENDED_KEY_USAGE_new': 'bssl_dart_EXTENDED_KEY_USAGE_new', 'FIPS_mode': 'bssl_dart_FIPS_mode', @@ -1545,6 +1571,7 @@ const recordUseMapping = { 'RSA_check_fips': 'bssl_dart_RSA_check_fips', 'RSA_check_key': 'bssl_dart_RSA_check_key', 'RSA_decrypt': 'bssl_dart_RSA_decrypt', + 'RSA_dup_ref': 'bssl_dart_RSA_dup_ref', 'RSA_encrypt': 'bssl_dart_RSA_encrypt', 'RSA_flags': 'bssl_dart_RSA_flags', 'RSA_free': 'bssl_dart_RSA_free', @@ -1604,27 +1631,21 @@ const recordUseMapping = { 'RSA_verify_PKCS1_PSS_mgf1': 'bssl_dart_RSA_verify_PKCS1_PSS_mgf1', 'RSA_verify_pss_mgf1': 'bssl_dart_RSA_verify_pss_mgf1', 'RSA_verify_raw': 'bssl_dart_RSA_verify_raw', - 'SHA1': 'bssl_dart_SHA1', 'SHA1_Final': 'bssl_dart_SHA1_Final', 'SHA1_Init': 'bssl_dart_SHA1_Init', 'SHA1_Transform': 'bssl_dart_SHA1_Transform', 'SHA1_Update': 'bssl_dart_SHA1_Update', - 'SHA224': 'bssl_dart_SHA224', 'SHA224_Final': 'bssl_dart_SHA224_Final', 'SHA224_Init': 'bssl_dart_SHA224_Init', 'SHA224_Update': 'bssl_dart_SHA224_Update', - 'SHA256': 'bssl_dart_SHA256', 'SHA256_Final': 'bssl_dart_SHA256_Final', 'SHA256_Init': 'bssl_dart_SHA256_Init', 'SHA256_Transform': 'bssl_dart_SHA256_Transform', 'SHA256_TransformBlocks': 'bssl_dart_SHA256_TransformBlocks', 'SHA256_Update': 'bssl_dart_SHA256_Update', - 'SHA384': 'bssl_dart_SHA384', 'SHA384_Final': 'bssl_dart_SHA384_Final', 'SHA384_Init': 'bssl_dart_SHA384_Init', 'SHA384_Update': 'bssl_dart_SHA384_Update', - 'SHA512': 'bssl_dart_SHA512', - 'SHA512_256': 'bssl_dart_SHA512_256', 'SHA512_256_Final': 'bssl_dart_SHA512_256_Final', 'SHA512_256_Init': 'bssl_dart_SHA512_256_Init', 'SHA512_256_Update': 'bssl_dart_SHA512_256_Update', @@ -1693,6 +1714,7 @@ const recordUseMapping = { 'X509_CRL_delete_ext': 'bssl_dart_X509_CRL_delete_ext', 'X509_CRL_digest': 'bssl_dart_X509_CRL_digest', 'X509_CRL_dup': 'bssl_dart_X509_CRL_dup', + 'X509_CRL_dup_ref': 'bssl_dart_X509_CRL_dup_ref', 'X509_CRL_free': 'bssl_dart_X509_CRL_free', 'X509_CRL_get0_by_cert': 'bssl_dart_X509_CRL_get0_by_cert', 'X509_CRL_get0_by_serial': 'bssl_dart_X509_CRL_get0_by_serial', @@ -1860,8 +1882,6 @@ const recordUseMapping = { 'X509_STORE_CTX_free': 'bssl_dart_X509_STORE_CTX_free', 'X509_STORE_CTX_get0_cert': 'bssl_dart_X509_STORE_CTX_get0_cert', 'X509_STORE_CTX_get0_chain': 'bssl_dart_X509_STORE_CTX_get0_chain', - 'X509_STORE_CTX_get0_current_crl': - 'bssl_dart_X509_STORE_CTX_get0_current_crl', 'X509_STORE_CTX_get0_param': 'bssl_dart_X509_STORE_CTX_get0_param', 'X509_STORE_CTX_get0_parent_ctx': 'bssl_dart_X509_STORE_CTX_get0_parent_ctx', 'X509_STORE_CTX_get0_store': 'bssl_dart_X509_STORE_CTX_get0_store', @@ -1900,6 +1920,7 @@ const recordUseMapping = { 'X509_STORE_add_cert': 'bssl_dart_X509_STORE_add_cert', 'X509_STORE_add_crl': 'bssl_dart_X509_STORE_add_crl', 'X509_STORE_add_lookup': 'bssl_dart_X509_STORE_add_lookup', + 'X509_STORE_dup_ref': 'bssl_dart_X509_STORE_dup_ref', 'X509_STORE_free': 'bssl_dart_X509_STORE_free', 'X509_STORE_get0_objects': 'bssl_dart_X509_STORE_get0_objects', 'X509_STORE_get0_param': 'bssl_dart_X509_STORE_get0_param', @@ -2041,6 +2062,7 @@ const recordUseMapping = { 'X509_set_pubkey': 'bssl_dart_X509_set_pubkey', 'X509_set_serialNumber': 'bssl_dart_X509_set_serialNumber', 'X509_set_subject_name': 'bssl_dart_X509_set_subject_name', + 'X509_set_unsigned': 'bssl_dart_X509_set_unsigned', 'X509_set_version': 'bssl_dart_X509_set_version', 'X509_sign': 'bssl_dart_X509_sign', 'X509_sign_ctx': 'bssl_dart_X509_sign_ctx', diff --git a/third_party/boringssl/gen/bcm/aesni-gcm-x86_64-win.asm b/third_party/boringssl/gen/bcm/aesni-gcm-x86_64-win.asm index a17d4f4..258862e 100644 --- a/third_party/boringssl/gen/bcm/aesni-gcm-x86_64-win.asm +++ b/third_party/boringssl/gen/bcm/aesni-gcm-x86_64-win.asm @@ -967,7 +967,7 @@ $L$one_lsb: DB 89,80,84,79,71,65,77,83,32,98,121,32,60,97,112,112 DB 114,111,64,111,112,101,110,115,115,108,46,111,114,103,62,0 ALIGN 64 -section .text +section .text code align=64 section .pdata rdata align=4 ALIGN 4 diff --git a/third_party/boringssl/gen/bcm/aesni-x86_64-win.asm b/third_party/boringssl/gen/bcm/aesni-x86_64-win.asm index 7f55ea4..9a79ff0 100644 --- a/third_party/boringssl/gen/bcm/aesni-x86_64-win.asm +++ b/third_party/boringssl/gen/bcm/aesni-x86_64-win.asm @@ -2499,7 +2499,7 @@ $L$key_rcon1b: DB 32,98,121,32,60,97,112,112,114,111,64,111,112,101,110,115 DB 115,108,46,111,114,103,62,0 ALIGN 64 -section .text +section .text code align=64 EXTERN __imp_RtlVirtualUnwind @@ -2695,7 +2695,7 @@ $L$SEH_info_ctr32: $L$SEH_info_cbc: DB 9,0,0,0 DD cbc_se_handler wrt ..imagebase -section .pdata +section .pdata rdata align=4 ALIGN 4 DD $L$SEH_begin_aes_hw_set_encrypt_key_base_1 wrt ..imagebase DD $L$SEH_end_aes_hw_set_encrypt_key_base_4 wrt ..imagebase @@ -2706,7 +2706,7 @@ ALIGN 4 DD $L$SEH_info_aes_hw_set_encrypt_key_alt_0 wrt ..imagebase -section .xdata +section .xdata rdata align=8 ALIGN 4 $L$SEH_info_aes_hw_set_encrypt_key_base_0: DB 1 ; version 1, no flags diff --git a/third_party/boringssl/gen/bcm/ghash-ssse3-x86_64-win.asm b/third_party/boringssl/gen/bcm/ghash-ssse3-x86_64-win.asm index 4794beb..64faab6 100644 --- a/third_party/boringssl/gen/bcm/ghash-ssse3-x86_64-win.asm +++ b/third_party/boringssl/gen/bcm/ghash-ssse3-x86_64-win.asm @@ -450,7 +450,7 @@ $L$reverse_bytes: ; .Llow4_mask is an XMM mask which selects the low four bits of each byte. $L$low4_mask: DQ 0x0f0f0f0f0f0f0f0f,0x0f0f0f0f0f0f0f0f -section .text +section .text code align=64 section .pdata rdata align=4 ALIGN 4 diff --git a/third_party/boringssl/gen/bcm/ghash-x86_64-win.asm b/third_party/boringssl/gen/bcm/ghash-x86_64-win.asm index eacd900..abdbb70 100644 --- a/third_party/boringssl/gen/bcm/ghash-x86_64-win.asm +++ b/third_party/boringssl/gen/bcm/ghash-x86_64-win.asm @@ -1214,7 +1214,7 @@ ALIGN 64 DB 60,97,112,112,114,111,64,111,112,101,110,115,115,108,46,111 DB 114,103,62,0 ALIGN 64 -section .text +section .text code align=64 section .pdata rdata align=4 ALIGN 4 diff --git a/third_party/boringssl/gen/bcm/p256-x86_64-asm-win.asm b/third_party/boringssl/gen/bcm/p256-x86_64-asm-win.asm index 9976ab3..c82ea79 100644 --- a/third_party/boringssl/gen/bcm/p256-x86_64-asm-win.asm +++ b/third_party/boringssl/gen/bcm/p256-x86_64-asm-win.asm @@ -35,7 +35,7 @@ $L$ord: DQ 0xf3b9cac2fc632551,0xbce6faada7179e84,0xffffffffffffffff,0xffffffff00000000 $L$ordK: DQ 0xccd1c8aaee00bc4f -section .text +section .text code align=64 ; ############################################################################### diff --git a/third_party/boringssl/gen/bcm/rsaz-avx2-win.asm b/third_party/boringssl/gen/bcm/rsaz-avx2-win.asm index a142c27..4272093 100644 --- a/third_party/boringssl/gen/bcm/rsaz-avx2-win.asm +++ b/third_party/boringssl/gen/bcm/rsaz-avx2-win.asm @@ -1846,7 +1846,7 @@ $L$inc: DD 2,2,2,2,3,3,3,3 DD 4,4,4,4,4,4,4,4 ALIGN 64 -section .text +section .text code align=64 EXTERN __imp_RtlVirtualUnwind diff --git a/third_party/boringssl/gen/bcm/sha1-x86_64-win.asm b/third_party/boringssl/gen/bcm/sha1-x86_64-win.asm index b59fb5d..b3a9225 100644 --- a/third_party/boringssl/gen/bcm/sha1-x86_64-win.asm +++ b/third_party/boringssl/gen/bcm/sha1-x86_64-win.asm @@ -5560,7 +5560,7 @@ K_XX_XX: DB 97,112,112,114,111,64,111,112,101,110,115,115,108,46,111,114 DB 103,62,0 ALIGN 64 -section .text +section .text code align=64 EXTERN __imp_RtlVirtualUnwind diff --git a/third_party/boringssl/gen/bcm/sha256-x86_64-win.asm b/third_party/boringssl/gen/bcm/sha256-x86_64-win.asm index 339f23a..7f3a21b 100644 --- a/third_party/boringssl/gen/bcm/sha256-x86_64-win.asm +++ b/third_party/boringssl/gen/bcm/sha256-x86_64-win.asm @@ -1785,7 +1785,7 @@ K256: DB 52,44,32,67,82,89,80,84,79,71,65,77,83,32,98,121 DB 32,60,97,112,112,114,111,64,111,112,101,110,115,115,108,46 DB 111,114,103,62,0 -section .text +section .text code align=64 global sha256_block_data_order_hw diff --git a/third_party/boringssl/gen/bcm/sha512-x86_64-win.asm b/third_party/boringssl/gen/bcm/sha512-x86_64-win.asm index 2e6760c..9f79afb 100644 --- a/third_party/boringssl/gen/bcm/sha512-x86_64-win.asm +++ b/third_party/boringssl/gen/bcm/sha512-x86_64-win.asm @@ -1829,7 +1829,7 @@ K512: DB 52,44,32,67,82,89,80,84,79,71,65,77,83,32,98,121 DB 32,60,97,112,112,114,111,64,111,112,101,110,115,115,108,46 DB 111,114,103,62,0 -section .text +section .text code align=64 global sha512_block_data_order_avx diff --git a/third_party/boringssl/gen/bcm/vpaes-x86_64-win.asm b/third_party/boringssl/gen/bcm/vpaes-x86_64-win.asm index 001618c..cea2195 100644 --- a/third_party/boringssl/gen/bcm/vpaes-x86_64-win.asm +++ b/third_party/boringssl/gen/bcm/vpaes-x86_64-win.asm @@ -1348,7 +1348,7 @@ $L$ctr_add_two: DB 85,110,105,118,101,114,115,105,116,121,41,0 ALIGN 64 -section .text +section .text code align=64 EXTERN __imp_RtlVirtualUnwind diff --git a/third_party/boringssl/gen/bcm/x86_64-mont5-win.asm b/third_party/boringssl/gen/bcm/x86_64-mont5-win.asm index 05e9759..4b73b80 100644 --- a/third_party/boringssl/gen/bcm/x86_64-mont5-win.asm +++ b/third_party/boringssl/gen/bcm/x86_64-mont5-win.asm @@ -3698,7 +3698,7 @@ $L$inc: DB 114,32,120,56,54,95,54,52,44,32,67,82,89,80,84,79 DB 71,65,77,83,32,98,121,32,60,97,112,112,114,111,64,111 DB 112,101,110,115,115,108,46,111,114,103,62,0 -section .text +section .text code align=64 EXTERN __imp_RtlVirtualUnwind diff --git a/third_party/boringssl/gen/crypto/chacha-x86_64-win.asm b/third_party/boringssl/gen/crypto/chacha-x86_64-win.asm index e37e31f..9cd683b 100644 --- a/third_party/boringssl/gen/crypto/chacha-x86_64-win.asm +++ b/third_party/boringssl/gen/crypto/chacha-x86_64-win.asm @@ -50,7 +50,7 @@ $L$sixteen: DB 95,54,52,44,32,67,82,89,80,84,79,71,65,77,83,32 DB 98,121,32,60,97,112,112,114,111,64,111,112,101,110,115,115 DB 108,46,111,114,103,62,0 -section .text +section .text code align=64 global ChaCha20_ctr32_nohw diff --git a/third_party/boringssl/sources.cmake b/third_party/boringssl/sources.cmake index c6318ca..8c66884 100644 --- a/third_party/boringssl/sources.cmake +++ b/third_party/boringssl/sources.cmake @@ -95,6 +95,7 @@ set(crypto_sources ${BORINGSSL_ROOT}src/crypto/cpu_arm_linux.cc ${BORINGSSL_ROOT}src/crypto/cpu_intel.cc ${BORINGSSL_ROOT}src/crypto/crypto.cc + ${BORINGSSL_ROOT}src/crypto/curve25519/cpace.cc ${BORINGSSL_ROOT}src/crypto/curve25519/curve25519.cc ${BORINGSSL_ROOT}src/crypto/curve25519/curve25519_64_adx.cc ${BORINGSSL_ROOT}src/crypto/curve25519/spake25519.cc @@ -102,6 +103,7 @@ set(crypto_sources ${BORINGSSL_ROOT}src/crypto/dh/dh_asn1.cc ${BORINGSSL_ROOT}src/crypto/dh/params.cc ${BORINGSSL_ROOT}src/crypto/digest/digest_extra.cc + ${BORINGSSL_ROOT}src/crypto/digest/p_keccak.cc ${BORINGSSL_ROOT}src/crypto/dsa/dsa.cc ${BORINGSSL_ROOT}src/crypto/dsa/dsa_asn1.cc ${BORINGSSL_ROOT}src/crypto/ec/ec_asn1.cc @@ -124,6 +126,7 @@ set(crypto_sources ${BORINGSSL_ROOT}src/crypto/evp/p_mldsa.cc ${BORINGSSL_ROOT}src/crypto/evp/p_mlkem.cc ${BORINGSSL_ROOT}src/crypto/evp/p_rsa.cc + ${BORINGSSL_ROOT}src/crypto/evp/p_slhdsa.cc ${BORINGSSL_ROOT}src/crypto/evp/p_x25519.cc ${BORINGSSL_ROOT}src/crypto/evp/p_xwing.cc ${BORINGSSL_ROOT}src/crypto/evp/pbkdf.cc diff --git a/third_party/boringssl/src/crypto/armv8_feature_parsing.h b/third_party/boringssl/src/crypto/armv8_feature_parsing.h index 5ebb876..a8fa8d8 100644 --- a/third_party/boringssl/src/crypto/armv8_feature_parsing.h +++ b/third_party/boringssl/src/crypto/armv8_feature_parsing.h @@ -1,9 +1,10 @@ #ifndef OPENSSL_CRYPTO_CPU_ARMV8_FEATURE_PARSING_H #define OPENSSL_CRYPTO_CPU_ARMV8_FEATURE_PARSING_H -#include #include +#include + #include "internal.h" #if defined(OPENSSL_AARCH64) @@ -18,6 +19,8 @@ namespace armcap { #define ID_AA64ISAR0_SHA1_FIELD_IDX 2 // Bits [11:8] #define ID_AA64ISAR0_SHA2_FIELD_IDX 3 // Bits [15:12] #define ID_AA64ISAR0_SHA3_FIELD_IDX 8 // Bits [35:32] +#define ID_AA64ISAR1_SB_FIELD_IDX 9 // Bits [39:36] +#define ID_AA64PFR0_DIT_FIELD_IDX 12 // Bits [51:48] #define NBITS_ID_FIELD 4 // Helper function to extract a 4-bit field based on its index. @@ -59,6 +62,20 @@ inline uint32_t ParseISAR0Flags(uint64_t isar0) { return armcap; } +inline uint32_t ParseISAR1Flags(uint64_t isar1) { + return GetIDField(isar1, ID_AA64ISAR1_SB_FIELD_IDX) != 0 ? ARMV8_SB : 0; +} + +inline uint32_t ParsePFR0Flags(uint64_t pfr0) { + uint32_t armcap = 0; + // DIT check + unsigned dit = GetIDField(pfr0, ID_AA64PFR0_DIT_FIELD_IDX); + if (dit != 0) { + armcap |= ARMV8_DIT; + } + return armcap; +} + } // namespace armcap BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/crypto/asn1/a_strex.cc b/third_party/boringssl/src/crypto/asn1/a_strex.cc index e57fde1..933818e 100644 --- a/third_party/boringssl/src/crypto/asn1/a_strex.cc +++ b/third_party/boringssl/src/crypto/asn1/a_strex.cc @@ -15,7 +15,6 @@ #include #include -#include #include #include #include @@ -27,7 +26,6 @@ #include #include "../bytestring/internal.h" -#include "../internal.h" #include "internal.h" @@ -37,15 +35,17 @@ using namespace bssl; (ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_QUOTE | ASN1_STRFLGS_ESC_CTRL | \ ASN1_STRFLGS_ESC_MSB) -static int maybe_write(BIO *out, const void *buf, int len) { +namespace { + +int maybe_write(BIO *out, const void *buf, int len) { // If `out` is NULL, ignore the output but report the length. return out == nullptr || BIO_write(out, buf, len) == len; } -static int is_control_character(unsigned char c) { return c < 32 || c == 127; } +int is_control_character(unsigned char c) { return c < 32 || c == 127; } -static int do_esc_char(uint32_t c, unsigned long flags, char *do_quotes, - BIO *out, int is_first, int is_last) { +int do_esc_char(uint32_t c, unsigned long flags, char *do_quotes, BIO *out, + int is_first, int is_last) { // `c` is a `uint32_t` because, depending on `ASN1_STRFLGS_UTF8_CONVERT`, // we may be escaping bytes or Unicode codepoints. char buf[16]; // Large enough for "\\W01234567". @@ -93,8 +93,8 @@ static int do_esc_char(uint32_t c, unsigned long flags, char *do_quotes, // interprets the content formats and converts to or from UTF8 as // appropriate. -static int do_buf(const unsigned char *buf, int buflen, int encoding, - unsigned long flags, char *quotes, BIO *out) { +int do_buf(const unsigned char *buf, int buflen, int encoding, + unsigned long flags, char *quotes, BIO *out) { int (*get_char)(CBS *cbs, uint32_t *out); int get_char_error; switch (encoding) { @@ -158,7 +158,7 @@ static int do_buf(const unsigned char *buf, int buflen, int encoding, return outlen; } -static int do_hex_dump(BIO *out, Span in) { +int do_hex_dump(BIO *out, Span in) { if (in.size() > INT_MAX / 2) { return -1; } @@ -180,7 +180,7 @@ static int do_hex_dump(BIO *out, Span in) { // request it. We can either dump the content octets or the entire DER // encoding. This uses the RFC 2253 #01234 format. -static int do_dump(unsigned long flags, BIO *out, const ASN1_STRING *str) { +int do_dump(unsigned long flags, BIO *out, const ASN1_STRING *str) { if (!maybe_write(out, "#", 1)) { return -1; } @@ -211,7 +211,7 @@ static int do_dump(unsigned long flags, BIO *out, const ASN1_STRING *str) { // string_type_to_encoding returns the `MBSTRING_*` constant for the encoding // used by the `ASN1_STRING` type `type`, or -1 if `tag` is not a string // type. -static int string_type_to_encoding(int type) { +int string_type_to_encoding(int type) { // This function is sometimes passed ASN.1 universal types and sometimes // passed `ASN1_STRING` type values switch (type) { @@ -234,6 +234,11 @@ static int string_type_to_encoding(int type) { return -1; } +const char *const kMon[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; + +} // namespace + // This is the main function, print out an ASN1_STRING taking note of various // escape and display options. Returns number of characters written or -1 if // an error occurred. @@ -379,9 +384,6 @@ int ASN1_TIME_print(BIO *bp, const ASN1_TIME *tm) { return 0; } -static const char *const mon[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; - int ASN1_GENERALIZEDTIME_print(BIO *bp, const ASN1_GENERALIZEDTIME *tm) { CBS cbs; CBS_init(&cbs, tm->data, tm->length); @@ -391,7 +393,7 @@ int ASN1_GENERALIZEDTIME_print(BIO *bp, const ASN1_GENERALIZEDTIME *tm) { return 0; } - return BIO_printf(bp, "%s %2d %02d:%02d:%02d %d GMT", mon[utc.tm_mon], + return BIO_printf(bp, "%s %2d %02d:%02d:%02d %d GMT", kMon[utc.tm_mon], utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec, utc.tm_year + 1900) > 0; } @@ -405,7 +407,7 @@ int ASN1_UTCTIME_print(BIO *bp, const ASN1_UTCTIME *tm) { return 0; } - return BIO_printf(bp, "%s %2d %02d:%02d:%02d %d GMT", mon[utc.tm_mon], + return BIO_printf(bp, "%s %2d %02d:%02d:%02d %d GMT", kMon[utc.tm_mon], utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec, utc.tm_year + 1900) > 0; } diff --git a/third_party/boringssl/src/crypto/asn1/a_strnid.cc b/third_party/boringssl/src/crypto/asn1/a_strnid.cc index 65a3226..db50d51 100644 --- a/third_party/boringssl/src/crypto/asn1/a_strnid.cc +++ b/third_party/boringssl/src/crypto/asn1/a_strnid.cc @@ -38,45 +38,12 @@ DEFINE_LHASH_OF(ASN1_STRING_TABLE) BSSL_NAMESPACE_END -static LHASH_OF(ASN1_STRING_TABLE) *string_tables = nullptr; -static StaticMutex string_tables_lock; - void ASN1_STRING_set_default_mask(unsigned long mask) {} unsigned long ASN1_STRING_get_default_mask() { return B_ASN1_UTF8STRING; } int ASN1_STRING_set_default_mask_asc(const char *p) { return 1; } -static const ASN1_STRING_TABLE *asn1_string_table_get(int nid); - -// The following function generates an ASN1_STRING based on limits in a -// table. Frequently the types and length of an ASN1_STRING are restricted by -// a corresponding OID. For example certificates and certificate requests. - -ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, const unsigned char *in, - ossl_ssize_t len, int inform, int nid) { - ASN1_STRING *str = nullptr; - int ret; - if (!out) { - out = &str; - } - const ASN1_STRING_TABLE *tbl = asn1_string_table_get(nid); - if (tbl != nullptr) { - unsigned long mask = tbl->mask; - if (!(tbl->flags & STABLE_NO_MASK)) { - mask &= B_ASN1_UTF8STRING; - } - ret = ASN1_mbstring_ncopy(out, in, len, inform, mask, tbl->minsize, - tbl->maxsize); - } else { - ret = ASN1_mbstring_copy(out, in, len, inform, B_ASN1_UTF8STRING); - } - if (ret <= 0) { - return nullptr; - } - return *out; -} - // Now the tables and helper functions for the string table: // See RFC 5280. @@ -89,9 +56,14 @@ ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, const unsigned char *in, #define ub_email_address 128 #define ub_serial_number 64 +namespace { + +LHASH_OF(ASN1_STRING_TABLE) *string_tables = nullptr; +StaticMutex string_tables_lock; + // This table must be kept in NID order -static const ASN1_STRING_TABLE tbl_standard[] = { +const ASN1_STRING_TABLE tbl_standard[] = { {NID_commonName, 1, ub_common_name, DIRSTRING_TYPE, 0}, {NID_countryName, 2, 2, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, {NID_localityName, 1, ub_locality_name, DIRSTRING_TYPE, 0}, @@ -115,7 +87,7 @@ static const ASN1_STRING_TABLE tbl_standard[] = { {NID_domainComponent, 1, -1, B_ASN1_IA5STRING, STABLE_NO_MASK}, {NID_ms_csp_name, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK}}; -static int table_cmp(const ASN1_STRING_TABLE *a, const ASN1_STRING_TABLE *b) { +int table_cmp(const ASN1_STRING_TABLE *a, const ASN1_STRING_TABLE *b) { if (a->nid < b->nid) { return -1; } @@ -125,16 +97,16 @@ static int table_cmp(const ASN1_STRING_TABLE *a, const ASN1_STRING_TABLE *b) { return 0; } -static int table_cmp_void(const void *a, const void *b) { +int table_cmp_void(const void *a, const void *b) { return table_cmp(reinterpret_cast(a), reinterpret_cast(b)); } -static uint32_t table_hash(const ASN1_STRING_TABLE *tbl) { +uint32_t table_hash(const ASN1_STRING_TABLE *tbl) { return OPENSSL_hash32(&tbl->nid, sizeof(tbl->nid)); } -static const ASN1_STRING_TABLE *asn1_string_table_get(int nid) { +const ASN1_STRING_TABLE *asn1_string_table_get(int nid) { ASN1_STRING_TABLE key; key.nid = nid; const ASN1_STRING_TABLE *tbl = reinterpret_cast( @@ -155,6 +127,36 @@ static const ASN1_STRING_TABLE *asn1_string_table_get(int nid) { return tbl; } +} // namespace + +// The following function generates an ASN1_STRING based on limits in a +// table. Frequently the types and length of an ASN1_STRING are restricted by +// a corresponding OID. For example certificates and certificate requests. + +ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, const unsigned char *in, + ossl_ssize_t len, int inform, int nid) { + ASN1_STRING *str = nullptr; + int ret; + if (!out) { + out = &str; + } + const ASN1_STRING_TABLE *tbl = asn1_string_table_get(nid); + if (tbl != nullptr) { + unsigned long mask = tbl->mask; + if (!(tbl->flags & STABLE_NO_MASK)) { + mask &= B_ASN1_UTF8STRING; + } + ret = ASN1_mbstring_ncopy(out, in, len, inform, mask, tbl->minsize, + tbl->maxsize); + } else { + ret = ASN1_mbstring_copy(out, in, len, inform, B_ASN1_UTF8STRING); + } + if (ret <= 0) { + return nullptr; + } + return *out; +} + int ASN1_STRING_TABLE_add(int nid, long minsize, long maxsize, unsigned long mask, unsigned long flags) { // Existing entries cannot be overwritten. diff --git a/third_party/boringssl/src/crypto/asn1/a_type.cc b/third_party/boringssl/src/crypto/asn1/a_type.cc index 4aac69a..eb5a914 100644 --- a/third_party/boringssl/src/crypto/asn1/a_type.cc +++ b/third_party/boringssl/src/crypto/asn1/a_type.cc @@ -147,24 +147,23 @@ int ASN1_TYPE_set1(ASN1_TYPE *a, int type, const void *value) { return 1; } -// Returns 0 if they are equal, != 0 otherwise. int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b) { - int result = -1; + if (a == nullptr || b == nullptr) { + // NULL sorts before any non-NULL value. Two NULLs are equal. + return (a != nullptr) - (b != nullptr); + } - if (!a || !b || a->type != b->type) { - return -1; + if (a->type != b->type) { + return a->type < b->type ? -1 : 1; } switch (a->type) { case V_ASN1_OBJECT: - result = OBJ_cmp(a->value.object, b->value.object); - break; + return OBJ_cmp(a->value.object, b->value.object); case V_ASN1_NULL: - result = 0; // They do not have content. - break; + return 0; // They do not have content. case V_ASN1_BOOLEAN: - result = a->value.boolean - b->value.boolean; - break; + return a->value.boolean - b->value.boolean; case V_ASN1_INTEGER: case V_ASN1_ENUMERATED: case V_ASN1_BIT_STRING: @@ -186,11 +185,8 @@ int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b) { case V_ASN1_UTF8STRING: case V_ASN1_OTHER: default: - result = ASN1_STRING_cmp(a->value.asn1_string, b->value.asn1_string); - break; + return ASN1_STRING_cmp(a->value.asn1_string, b->value.asn1_string); } - - return result; } int bssl::asn1_parse_any(CBS *cbs, ASN1_TYPE *out) { @@ -292,6 +288,12 @@ int bssl::asn1_parse_any_as_string(CBS *cbs, ASN1_STRING *out) { return 0; } break; + case CBS_ASN1_RELATIVE_OID: + if (!CBS_is_valid_asn1_relative_oid(&body)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_OBJECT_ENCODING); + return 0; + } + break; case CBS_ASN1_NULL: if (CBS_len(&body) != 0) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_NULL_IS_WRONG_LENGTH); @@ -326,9 +328,7 @@ int bssl::asn1_parse_any_as_string(CBS *cbs, ASN1_STRING *out) { case CBS_ASN1_UTF8STRING: return asn1_parse_utf8_string(&elem, out, tag); case CBS_ASN1_UTCTIME: - // TODO(crbug.com/42290221): Reject timezone offsets here. We have no - // known cases where UTCTime inside ANY needs accept invalid timezones. - return asn1_parse_utc_time(&elem, out, tag, /*allow_timezone_offset=*/1); + return asn1_parse_utc_time(&elem, out, tag, /*allow_timezone_offset=*/0); case CBS_ASN1_GENERALIZEDTIME: return asn1_parse_generalized_time(&elem, out, tag); case CBS_ASN1_OCTETSTRING: diff --git a/third_party/boringssl/src/crypto/asn1/asn1_lib.cc b/third_party/boringssl/src/crypto/asn1/asn1_lib.cc index e41e43e..416fc71 100644 --- a/third_party/boringssl/src/crypto/asn1/asn1_lib.cc +++ b/third_party/boringssl/src/crypto/asn1/asn1_lib.cc @@ -235,6 +235,8 @@ ASN1_STRING *ASN1_STRING_dup(const ASN1_STRING *str) { return ret; } +static_assert(ASN1_STRING_MAX < INT_MAX, "len will not overflow int"); + int ASN1_STRING_set(ASN1_STRING *str, const void *_data, ossl_ssize_t len_s) { const char *data = reinterpret_cast(_data); size_t len; @@ -247,7 +249,6 @@ int ASN1_STRING_set(ASN1_STRING *str, const void *_data, ossl_ssize_t len_s) { len = (size_t)len_s; } - static_assert(ASN1_STRING_MAX < INT_MAX, "len will not overflow int"); if (len > ASN1_STRING_MAX) { OPENSSL_PUT_ERROR(ASN1, ERR_R_OVERFLOW); return 0; @@ -274,18 +275,40 @@ int ASN1_STRING_set(ASN1_STRING *str, const void *_data, ossl_ssize_t len_s) { // `ASN1_STRING`s, in case anyone accidentally passed `str->data` into a // function expecting a C string. We retain this behavior for compatibility, // but code must not rely on this. See CVE-2021-3712. + // TODO(crbug.com/476131577): Make this function a wrapper around + // `ASN1_STRING_set1_data`, after dropping the null-termination here. str->data[len] = '\0'; } return 1; } void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len) { + BSSL_CHECK(len >= 0); OPENSSL_free(str->data); str->data = reinterpret_cast(data); str->length = len; str->flags &= ~0x07; // Clear unused bits if this is a BIT STRING. } +int ASN1_STRING_set1_data(ASN1_STRING *str, const uint8_t *data, size_t len) { + if (len > ASN1_STRING_MAX) { + OPENSSL_PUT_ERROR(ASN1, ERR_R_OVERFLOW); + return 0; + } + uint8_t *new_data = nullptr; + if (len != 0) { + new_data = reinterpret_cast(OPENSSL_memdup(data, len)); + if (new_data == nullptr) { + return 0; + } + } + OPENSSL_free(str->data); + str->data = new_data; + str->length = len; + str->flags &= ~0x07; // Clear unused bits if this is a BIT STRING. + return 1; +} + ASN1_STRING *ASN1_STRING_new() { return (ASN1_STRING_type_new(V_ASN1_OCTET_STRING)); } @@ -361,6 +384,8 @@ int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b) { int ASN1_STRING_length(const ASN1_STRING *str) { return str->length; } +size_t ASN1_STRING_get_length(const ASN1_STRING *str) { return str->length; } + int ASN1_STRING_type(const ASN1_STRING *str) { return str->type; } unsigned char *ASN1_STRING_data(ASN1_STRING *str) { return str->data; } diff --git a/third_party/boringssl/src/crypto/asn1/asn1_par.cc b/third_party/boringssl/src/crypto/asn1/asn1_par.cc index 7767cca..54921d5 100644 --- a/third_party/boringssl/src/crypto/asn1/asn1_par.cc +++ b/third_party/boringssl/src/crypto/asn1/asn1_par.cc @@ -30,7 +30,7 @@ const char *ASN1_tag2str(int tag) { "ENUMERATED", "", "UTF8STRING", - "", + "RELATIVE-OID", "", "", "SEQUENCE", diff --git a/third_party/boringssl/src/crypto/asn1/internal.h b/third_party/boringssl/src/crypto/asn1/internal.h index f3dd9db..382a1ee 100644 --- a/third_party/boringssl/src/crypto/asn1/internal.h +++ b/third_party/boringssl/src/crypto/asn1/internal.h @@ -356,45 +356,45 @@ typedef struct ASN1_EXTERN_FUNCS_st { // IMPLEMENT_EXTERN_ASN1_PARSE_NEW implements an `ASN1_ITEM` for a type whose // parse function returns a new object. -#define IMPLEMENT_EXTERN_ASN1_PARSE_NEW(name, new_func, free_func, tag, \ - parse_func, marshal_func) \ - static int name##_new_cb(ASN1_VALUE **pval, const ASN1_ITEM *it) { \ - name *obj = new_func(); \ - if (obj == nullptr) { \ - return 0; \ - } \ - asn1_store_ptr(pval, obj); \ - return 1; \ - } \ - \ - static void name##_free_cb(ASN1_VALUE **pval, const ASN1_ITEM *it) { \ - free_func(asn1_load_ptr_as(pval)); \ - asn1_store_ptr(pval, nullptr); \ - } \ - \ - static int name##_parse_cb(ASN1_VALUE **pval, CBS *cbs, const ASN1_ITEM *it, \ - int opt) { \ - if (opt && !CBS_peek_asn1_tag(cbs, (tag))) { \ - return 1; \ - } \ - \ - bssl::UniquePtr ret = parse_func(cbs); \ - if (ret == nullptr) { \ - return 0; \ - } \ - name##_free_cb(pval, it); \ - asn1_store_ptr(pval, ret.release()); \ - return 1; \ - } \ - \ - static int name##_marshal_cb(CBB *cbb, ASN1_VALUE **pval, \ - const ASN1_ITEM *it) { \ - return marshal_func(cbb, asn1_load_ptr_as(pval)); \ - } \ - \ - static const ASN1_EXTERN_FUNCS name##_extern_funcs = { \ - name##_new_cb, name##_free_cb, name##_parse_cb, name##_marshal_cb}; \ - \ +#define IMPLEMENT_EXTERN_ASN1_PARSE_NEW(name, new_func, free_func, tag, \ + parse_func, marshal_func) \ + namespace { \ + int name##_new_cb(ASN1_VALUE **pval, const ASN1_ITEM *it) { \ + name *obj = new_func(); \ + if (obj == nullptr) { \ + return 0; \ + } \ + asn1_store_ptr(pval, obj); \ + return 1; \ + } \ + \ + void name##_free_cb(ASN1_VALUE **pval, const ASN1_ITEM *it) { \ + free_func(asn1_load_ptr_as(pval)); \ + asn1_store_ptr(pval, nullptr); \ + } \ + \ + int name##_parse_cb(ASN1_VALUE **pval, CBS *cbs, const ASN1_ITEM *it, \ + int opt) { \ + if (opt && !CBS_peek_asn1_tag(cbs, (tag))) { \ + return 1; \ + } \ + \ + bssl::UniquePtr ret = parse_func(cbs); \ + if (ret == nullptr) { \ + return 0; \ + } \ + name##_free_cb(pval, it); \ + asn1_store_ptr(pval, ret.release()); \ + return 1; \ + } \ + \ + int name##_marshal_cb(CBB *cbb, ASN1_VALUE **pval, const ASN1_ITEM *it) { \ + return marshal_func(cbb, asn1_load_ptr_as(pval)); \ + } \ + \ + const ASN1_EXTERN_FUNCS name##_extern_funcs = { \ + name##_new_cb, name##_free_cb, name##_parse_cb, name##_marshal_cb}; \ + } \ IMPLEMENT_EXTERN_ASN1(name, name##_extern_funcs) // IMPLEMENT_EXTERN_ASN1_PARSE_INTO implements an `ASN1_ITEM` for a type whose @@ -402,14 +402,15 @@ typedef struct ASN1_EXTERN_FUNCS_st { #define IMPLEMENT_EXTERN_ASN1_PARSE_INTO(name, new_func, free_func, tag, \ parse_func, marshal_func) \ \ - static bssl::UniquePtr name##_parse_new(CBS *cbs) { \ + namespace { \ + bssl::UniquePtr name##_parse_new(CBS *cbs) { \ bssl::UniquePtr ret(new_func()); \ if (ret == nullptr || !parse_func(cbs, ret.get())) { \ return 0; \ } \ return ret; \ } \ - \ + } \ IMPLEMENT_EXTERN_ASN1_PARSE_NEW(name, new_func, free_func, tag, \ name##_parse_new, marshal_func) diff --git a/third_party/boringssl/src/crypto/asn1/tasn_dec.cc b/third_party/boringssl/src/crypto/asn1/tasn_dec.cc index 57ce776..85d44e7 100644 --- a/third_party/boringssl/src/crypto/asn1/tasn_dec.cc +++ b/third_party/boringssl/src/crypto/asn1/tasn_dec.cc @@ -574,10 +574,7 @@ static int asn1_parse_item_primitive(ASN1_VALUE **pval, CBS *cbs, case V_ASN1_UTF8STRING: return asn1_parse_utf8_string(cbs, str, tag); case V_ASN1_UTCTIME: - // TODO(crbug.com/42290221): Reject timezone offsets. We need to parse - // invalid timestamps in `X509` objects, but that parser no longer uses - // this code. - return asn1_parse_utc_time(cbs, str, tag, /*allow_timezone_offset=*/1); + return asn1_parse_utc_time(cbs, str, tag, /*allow_timezone_offset=*/0); case V_ASN1_GENERALIZEDTIME: return asn1_parse_generalized_time(cbs, str, tag); case V_ASN1_OCTET_STRING: diff --git a/third_party/boringssl/src/crypto/bio/bio.cc b/third_party/boringssl/src/crypto/bio/bio.cc index aabf06d..7db3793 100644 --- a/third_party/boringssl/src/crypto/bio/bio.cc +++ b/third_party/boringssl/src/crypto/bio/bio.cc @@ -15,7 +15,6 @@ #include #include -#include #include #include @@ -47,6 +46,8 @@ BIO *BIO_new(const BIO_METHOD *method) { } if (method->create != nullptr && !method->create(ret.get())) { + // Matching OpenSSL, don't call `destroy` if `create` fails. + ret->method = nullptr; return nullptr; } @@ -55,7 +56,8 @@ BIO *BIO_new(const BIO_METHOD *method) { Bio::~Bio() { BIO *next = BIO_pop(this); - if (method->destroy != nullptr) { + // `method` may be null if `create` failed. + if (method != nullptr && method->destroy != nullptr) { method->destroy(this); } CRYPTO_free_ex_data(&g_ex_data_class, &ex_data); @@ -74,6 +76,13 @@ int BIO_up_ref(BIO *bio) { return 1; } +BIO *BIO_dup_ref(const BIO *bio) { + if (bio == nullptr) { + return nullptr; + } + return FromOpaque(bio)->DupRefInternal(); +} + void BIO_vfree(BIO *bio) { BIO_free(bio); } void BIO_free_all(BIO *bio) { BIO_free(bio); } @@ -291,9 +300,7 @@ void BIO_clear_retry_flags(BIO *bio) { impl->retry_reason = 0; } -int BIO_method_type(const BIO *bio) { - return FromOpaque(bio)->method->type; -} +int BIO_method_type(const BIO *bio) { return FromOpaque(bio)->method->type; } void BIO_copy_next_retry(BIO *bio) { auto *impl = FromOpaque(bio); diff --git a/third_party/boringssl/src/crypto/blake2/blake2.cc b/third_party/boringssl/src/crypto/blake2/blake2.cc index a14cb8e..684b35e 100644 --- a/third_party/boringssl/src/crypto/blake2/blake2.cc +++ b/third_party/boringssl/src/crypto/blake2/blake2.cc @@ -22,6 +22,8 @@ using namespace bssl; +namespace { + // https://tools.ietf.org/html/rfc7693#section-2.6 static const uint64_t kIV[8] = { UINT64_C(0x6a09e667f3bcc908), UINT64_C(0xbb67ae8584caa73b), @@ -47,8 +49,8 @@ static const uint8_t kSigma[10 * 16] = { }; // https://tools.ietf.org/html/rfc7693#section-3.1 -static void blake2b_mix(uint64_t v[16], int a, int b, int c, int d, uint64_t x, - uint64_t y) { +void blake2b_mix(uint64_t v[16], int a, int b, int c, int d, uint64_t x, + uint64_t y) { v[a] = v[a] + v[b] + x; v[d] = CRYPTO_rotr_u64(v[d] ^ v[a], 32); v[c] = v[c] + v[d]; @@ -59,13 +61,12 @@ static void blake2b_mix(uint64_t v[16], int a, int b, int c, int d, uint64_t x, v[b] = CRYPTO_rotr_u64(v[b] ^ v[c], 63); } -static uint64_t blake2b_load(const uint8_t block[BLAKE2B_CBLOCK], size_t i) { +uint64_t blake2b_load(const uint8_t block[BLAKE2B_CBLOCK], size_t i) { return CRYPTO_load_u64_le(block + 8 * i); } -static void blake2b_transform(BLAKE2B_CTX *b2b, - const uint8_t block[BLAKE2B_CBLOCK], - size_t num_bytes, int is_final_block) { +void blake2b_transform(BLAKE2B_CTX *b2b, const uint8_t block[BLAKE2B_CBLOCK], + size_t num_bytes, int is_final_block) { // https://tools.ietf.org/html/rfc7693#section-3.2 uint64_t v[16]; static_assert(sizeof(v) == sizeof(b2b->h) + sizeof(kIV)); @@ -109,6 +110,8 @@ static void blake2b_transform(BLAKE2B_CTX *b2b, } } +} // namespace + void BLAKE2B256_Init(BLAKE2B_CTX *b2b) { OPENSSL_memset(b2b, 0, sizeof(BLAKE2B_CTX)); diff --git a/third_party/boringssl/src/crypto/bytestring/cbb.cc b/third_party/boringssl/src/crypto/bytestring/cbb.cc index ab1b4be..8e46486 100644 --- a/third_party/boringssl/src/crypto/bytestring/cbb.cc +++ b/third_party/boringssl/src/crypto/bytestring/cbb.cc @@ -750,19 +750,7 @@ int CBB_flush_asn1_set_of(CBB *cbb) { return 0; } } - std::sort(children.begin(), children.end(), [](CBS a, CBS b) -> bool { - // See X.690, section 11.6 for the ordering. They are sorted in ascending - // order by their DER encoding. First compare the common prefix. - size_t a_len = CBS_len(&a), b_len = CBS_len(&b); - int cmp = - OPENSSL_memcmp(CBS_data(&a), CBS_data(&b), std::min(a_len, b_len)); - if (cmp != 0) { - return cmp < 0; - } - // If one is a prefix of the other, the shorter one sorts first. (They're - // actually always equal length. DER encodings are prefix-free.) - return a_len < b_len; - }); + std::sort(children.begin(), children.end(), bssl::cbs_asn1_set_of_less); // Write the contents back in the new order. uint8_t *out = const_cast(CBB_data(cbb)); diff --git a/third_party/boringssl/src/crypto/bytestring/cbs.cc b/third_party/boringssl/src/crypto/bytestring/cbs.cc index b0a0b8f..e0f7346 100644 --- a/third_party/boringssl/src/crypto/bytestring/cbs.cc +++ b/third_party/boringssl/src/crypto/bytestring/cbs.cc @@ -20,6 +20,8 @@ #include #include +#include + #include "../asn1/internal.h" #include "../internal.h" #include "internal.h" @@ -729,6 +731,40 @@ int CBS_is_unsigned_asn1_integer(const CBS *cbs) { return CBS_is_valid_asn1_integer(cbs, &is_negative) && !is_negative; } +bool bssl::cbs_asn1_set_of_less(CBS a, CBS b) { + // See X.690, section 11.6 for the ordering. They are sorted in ascending + // order by their DER encoding. First compare the common prefix. + size_t a_len = CBS_len(&a), b_len = CBS_len(&b); + int cmp = OPENSSL_memcmp(CBS_data(&a), CBS_data(&b), std::min(a_len, b_len)); + if (cmp != 0) { + return cmp < 0; + } + // If one is a prefix of the other, the shorter one sorts first. (They're + // actually always equal length. DER encodings are prefix-free.) + return a_len < b_len; +} + +int CBS_is_valid_asn1_set_of(const CBS *cbs) { + CBS copy = *cbs; + if (CBS_len(©) == 0) { + return 1; + } + CBS prev, cur; + if (!CBS_get_any_asn1_element(©, &prev, nullptr, nullptr)) { + return 0; + } + while (CBS_len(©) != 0) { + if (!CBS_get_any_asn1_element(©, &cur, nullptr, nullptr) || + // Allow duplicate entries; only reject if the current member should go + // strictly before the previous. + cbs_asn1_set_of_less(cur, prev)) { + return 0; + } + prev = cur; + } + return 1; +} + int CBS_is_valid_asn1_oid(const CBS *cbs) { if (CBS_len(cbs) == 0) { return 0; // OID encodings cannot be empty. diff --git a/third_party/boringssl/src/crypto/bytestring/internal.h b/third_party/boringssl/src/crypto/bytestring/internal.h index 6bea4a7..de2fcd2 100644 --- a/third_party/boringssl/src/crypto/bytestring/internal.h +++ b/third_party/boringssl/src/crypto/bytestring/internal.h @@ -129,6 +129,11 @@ inline int I2DFromCBB(size_t initial_capacity, uint8_t **outp, CBBFunc func) { // returns one on success and zero on error. int cbb_add_decimal_ascii(CBB *out, uint64_t v); +// cbs_asn1_set_of_less returns true iff `a` should be sorted before `b` +// according to the DER rules for encoding an ASN.1 SET OF, of which `a` and `b` +// are members. +bool cbs_asn1_set_of_less(CBS a, CBS b); + BSSL_NAMESPACE_END #endif // OPENSSL_HEADER_CRYPTO_BYTESTRING_INTERNAL_H diff --git a/third_party/boringssl/src/crypto/cms/cms.cc b/third_party/boringssl/src/crypto/cms/cms.cc index e8ba962..ddd9d60 100644 --- a/third_party/boringssl/src/crypto/cms/cms.cc +++ b/third_party/boringssl/src/crypto/cms/cms.cc @@ -56,8 +56,9 @@ class CMSContentInfo : public CMS_ContentInfo_st { BSSL_NAMESPACE_END -CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, - BIO *data, uint32_t flags) { +CMS_ContentInfo *CMS_sign(const X509 *signcert, const EVP_PKEY *pkey, + const STACK_OF(X509) *certs, BIO *data, + uint32_t flags) { // We only support external signatures and do not support embedding // certificates in SignedData. if ((flags & CMS_DETACHED) == 0 || sk_X509_num(certs) != 0) { @@ -88,8 +89,8 @@ CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, void CMS_ContentInfo_free(CMS_ContentInfo *cms) { Delete(FromOpaque(cms)); } -CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, X509 *signcert, - EVP_PKEY *pkey, const EVP_MD *md, +CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, const X509 *signcert, + const EVP_PKEY *pkey, const EVP_MD *md, uint32_t flags) { auto *impl = FromOpaque(cms); if ( // Already finalized. diff --git a/third_party/boringssl/src/crypto/cpu_aarch64_apple.cc b/third_party/boringssl/src/crypto/cpu_aarch64_apple.cc index c25b5ac..84a8206 100644 --- a/third_party/boringssl/src/crypto/cpu_aarch64_apple.cc +++ b/third_party/boringssl/src/crypto/cpu_aarch64_apple.cc @@ -71,6 +71,12 @@ void bssl::OPENSSL_cpuid_setup() { has_hw_feature("hw.optional.armv8_2_sha3")) { OPENSSL_armcap_P |= ARMV8_SHA3; } + if (has_hw_feature("hw.optional.arm.FEAT_DIT")) { + OPENSSL_armcap_P |= ARMV8_DIT; + } + if (has_hw_feature("hw.optional.arm.FEAT_SB")) { + OPENSSL_armcap_P |= ARMV8_SB; + } } #endif // OPENSSL_AARCH64 && OPENSSL_APPLE && !OPENSSL_STATIC_ARMCAP diff --git a/third_party/boringssl/src/crypto/cpu_aarch64_linux.cc b/third_party/boringssl/src/crypto/cpu_aarch64_linux.cc index 527c7f0..032c55a 100644 --- a/third_party/boringssl/src/crypto/cpu_aarch64_linux.cc +++ b/third_party/boringssl/src/crypto/cpu_aarch64_linux.cc @@ -34,6 +34,8 @@ void bssl::OPENSSL_cpuid_setup() { static const unsigned long kSHA256 = 1 << 6; static const unsigned long kSHA3 = 1 << 17; static const unsigned long kSHA512 = 1 << 21; + static const unsigned long kDIT = 1 << 24; + static const unsigned long kSB = 1 << 29; if ((hwcap & kNEON) == 0) { // Matching OpenSSL, if NEON is missing, don't report other features @@ -61,6 +63,12 @@ void bssl::OPENSSL_cpuid_setup() { if (hwcap & kSHA3) { OPENSSL_armcap_P |= ARMV8_SHA3; } + if (hwcap & kDIT) { + OPENSSL_armcap_P |= ARMV8_DIT; + } + if (hwcap & kSB) { + OPENSSL_armcap_P |= ARMV8_SB; + } } #endif // OPENSSL_AARCH64 && OPENSSL_LINUX && !OPENSSL_STATIC_ARMCAP diff --git a/third_party/boringssl/src/crypto/cpu_aarch64_openbsd.cc b/third_party/boringssl/src/crypto/cpu_aarch64_openbsd.cc index 235c14a..dbc116c 100644 --- a/third_party/boringssl/src/crypto/cpu_aarch64_openbsd.cc +++ b/third_party/boringssl/src/crypto/cpu_aarch64_openbsd.cc @@ -40,6 +40,20 @@ void bssl::OPENSSL_cpuid_setup() { // Use the common parsing function to check other features. OPENSSL_armcap_P |= armcap::ParseISAR0Flags(cpu_id); + + int isar1_mib[] = {CTL_MACHDEP, CPU_ID_AA64ISAR1}; + cpu_id = 0; + len = sizeof(cpu_id); + if (sysctl(isar1_mib, 2, &cpu_id, &len, nullptr, 0) == 0) { + OPENSSL_armcap_P |= armcap::ParseISAR1Flags(cpu_id); + } + + int pfr0_mib[] = {CTL_MACHDEP, CPU_ID_AA64PFR0}; + cpu_id = 0; + len = sizeof(cpu_id); + if (sysctl(pfr0_mib, 2, &cpu_id, &len, nullptr, 0) == 0) { + OPENSSL_armcap_P |= armcap::ParsePFR0Flags(cpu_id); + } } #endif // OPENSSL_AARCH64 && OPENSSL_OPENBSD && !OPENSSL_STATIC_ARMCAP diff --git a/third_party/boringssl/src/crypto/cpu_aarch64_sysreg.cc b/third_party/boringssl/src/crypto/cpu_aarch64_sysreg.cc index 770be1a..14c1534 100644 --- a/third_party/boringssl/src/crypto/cpu_aarch64_sysreg.cc +++ b/third_party/boringssl/src/crypto/cpu_aarch64_sysreg.cc @@ -57,7 +57,10 @@ void OPENSSL_cpuid_setup() { // Use the common parsing function to check all cryptographic features. uint64_t id_aa64isar0_el1 = READ_SYSREG("id_aa64isar0_el1"); - OPENSSL_armcap_P |= ARMV7_NEON | armcap::ParseISAR0Flags(id_aa64isar0_el1); + uint64_t id_aa64isar1_el1 = READ_SYSREG("id_aa64isar1_el1"); + OPENSSL_armcap_P |= ARMV7_NEON | armcap::ParseISAR0Flags(id_aa64isar0_el1) | + armcap::ParseISAR1Flags(id_aa64isar1_el1) | + armcap::ParsePFR0Flags(id_aa64pfr0_el1); } BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/crypto/crypto.cc b/third_party/boringssl/src/crypto/crypto.cc index 28b5f54..e9f1704 100644 --- a/third_party/boringssl/src/crypto/crypto.cc +++ b/third_party/boringssl/src/crypto/crypto.cc @@ -150,3 +150,71 @@ int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings) { void OPENSSL_cleanup() {} FILE *bssl::CRYPTO_get_stderr() { return stderr; } + +#if defined(OPENSSL_ARM_DIT) +// ARMv8.4 Data-Independent Timing + +namespace { + +// We had an option to encode the system register directly as "dit" but older +// compilers do not recognize it, so we adopt the direct encoding. +uint64_t ReadDit() { + uint64_t previous; + __asm__ __volatile__("mrs %0, S3_3_C4_C2_5" : "=r"(previous) : : "memory"); + return previous; +} +void SwitchOnDit() { + uint64_t on = 1ULL << 24; + __asm__ __volatile__("msr S3_3_C4_C2_5, %0" ::"r"(on) : "memory"); +} +void SwitchOffDit() { + __asm__ __volatile__("msr S3_3_C4_C2_5, xzr" ::: "memory"); +} + +#if defined(OPENSSL_APPLE) +SB_FEATURE void SpeculationBarrier() { + __asm__ __volatile__("sb" ::: "memory"); +} +void FullSynchronizationBarrier() { + __asm__ __volatile__("dsb nsh" ::: "memory"); + __asm__ __volatile__("isb sy" ::: "memory"); +} +#endif // OPENSSL_APPLE + +} // namespace + +ConstTimeGuard::ConstTimeGuard() { + if (CRYPTO_is_ARMv8_DIT_capable()) { + uint64_t previous = ReadDit(); + // DIT is located on Bit 24. + // See + // https://support.arm.com/documentation/102670/0301/AArch64-registers/AArch64-register-descriptions/AArch64-Generic-System-control-register-description/DIT--Data-Independent-Timing + previous_dit_ = (previous & (1ULL << 24)) != 0; + if (!previous_dit_) { + SwitchOnDit(); + // Arm documents that barriers are not necessary when writing to, or + // reading from, PSTATE fields. However, Apple documentation indicates + // that barriers should be used, in particular when setting the PSTATE.DIT + // field. Barriers aren't cheap, so only use them on Apple silicon for + // now. + // + // See go.dev/issue/77776. +#if defined(OPENSSL_APPLE) + if (CRYPTO_is_ARMv8_SB_capable()) { + SpeculationBarrier(); + } else { + FullSynchronizationBarrier(); + } +#endif // OPENSSL_APPLE + } + } else { + previous_dit_ = true; + } +} + +ConstTimeGuard::~ConstTimeGuard() { + if (!previous_dit_) { + SwitchOffDit(); + } +} +#endif // OPENSSL_ARM_DIT diff --git a/third_party/boringssl/src/crypto/curve25519/cpace.cc b/third_party/boringssl/src/crypto/curve25519/cpace.cc new file mode 100644 index 0000000..99529a7 --- /dev/null +++ b/third_party/boringssl/src/crypto/curve25519/cpace.cc @@ -0,0 +1,227 @@ +// Copyright 2026 The BoringSSL Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../internal.h" +#include "../mem_internal.h" +#include "./internal.h" + + +CPACE_CTX *CPACE_CTX_new(enum cpace_role_t role, const uint8_t *password, + size_t password_len, const uint8_t *channel_id, + size_t channel_id_len, const uint8_t *assoc_data, + size_t assoc_data_len, const uint8_t *session_id, + size_t session_id_len) { + bssl::UniquePtr ctx = bssl::MakeUnique(); + if (ctx == nullptr) { + return nullptr; + } + + ctx->our_role = role; + if (!ctx->our_password.CopyFrom(bssl::Span(password, password_len)) || + !ctx->channel_id.CopyFrom(bssl::Span(channel_id, channel_id_len)) || + !ctx->our_aad.CopyFrom(bssl::Span(assoc_data, assoc_data_len)) || + !ctx->session_id.CopyFrom(bssl::Span(session_id, session_id_len))) { + return nullptr; + } + + return ctx.release(); +} + +void CPACE_CTX_free(CPACE_CTX *ctx) { Delete(bssl::FromOpaque(ctx)); } + +namespace { +constexpr uint64_t leb128_len(uint64_t len) { + if (len < 128) { + return 1; + } + return (bssl::CRYPTO_bit_width(len) + 6) / 7; +} + +static constexpr size_t kMaxLenTagSize = leb128_len(UINT64_MAX); +static constexpr std::string_view kDSI = "CPace255"; + +constexpr size_t leb128_tag(uint64_t len, uint8_t tag[kMaxLenTagSize]) { + size_t tag_len = leb128_len(len); + for (size_t i = 0; i < tag_len; ++i) { + if (len < 128) { + tag[i] = len; + } else { + tag[i] = (len & 0x7f) | 0x80; + len >>= 7; + } + } + return tag_len; +} + +void push_lv_to_hasher(SHA512_CTX &hasher, bssl::Span data) { + uint8_t lv_tag[kMaxLenTagSize]; + size_t lv_tag_len = leb128_tag(data.size(), lv_tag); + SHA512_Update(&hasher, lv_tag, lv_tag_len); + SHA512_Update(&hasher, data.data(), data.size()); +} +} // namespace + + +// This implements the first two steps of G.calculate_generator in Section 8.2 +// of draft-irtf-cfrg-cpace-21. +void bssl::CpaceCtx::ComputeGeneratorStrHash( + uint8_t out_gen_str_hash[32]) const { + // len_zpad = max(0,s_in_bytes - 1 - len(prepend_len(PRS)) - + // len(prepend_len(DSI))) + size_t digest_len = leb128_len(our_password.size()) + our_password.size() // + + leb128_len(kDSI.length()) + kDSI.length(); + size_t len_zpad = 0; + if (digest_len < SHA512_CBLOCK - 1) { + len_zpad = SHA512_CBLOCK - 1 - digest_len; + } + + constexpr uint8_t kZeros[SHA512_CBLOCK] = {}; + // gen_str = generator_string(G.DSI, PRS, CI, sid, H.s_in_bytes) + SHA512_CTX hasher; + SHA512_Init(&hasher); + push_lv_to_hasher(hasher, StringAsBytes(kDSI)); + push_lv_to_hasher(hasher, our_password); + push_lv_to_hasher(hasher, Span(kZeros, len_zpad)); + push_lv_to_hasher(hasher, channel_id); + push_lv_to_hasher(hasher, session_id); + uint8_t out[SHA512_DIGEST_LENGTH]; + // gen_str_hash = H.hash(gen_str, G.field_size_bytes). + SHA512_Final(out, &hasher); + OPENSSL_memcpy(out_gen_str_hash, out, 32); +} + +bool bssl::CpaceCtx::ComputeMessage(uint8_t msg[CPACE_MSG_LEN]) { + if (state != cpace_state_init) { + OPENSSL_PUT_ERROR(CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return false; + } + + uint8_t gen_str_hash[32]; + // We now compute the first two steps of G.calculate_generator(H, PRS, sid, + // CI). + ComputeGeneratorStrHash(gen_str_hash); + // This result is then considered as a field coordinate using the u = + // decodeUCoordinate(gen_str_hash, G.field_size_bits) function from RFC7748. + uint8_t g[32], v[32]; + map_to_curve_curve25519_elligator2(g, v, gen_str_hash); + // sample_scalar() = sample_random_bytes(G.field_size_bytes) + RAND_bytes(our_private_key, 32); + auto rc = X25519(our_public_key, our_private_key, g); + OPENSSL_memcpy(msg, our_public_key, 32); + if (!rc) { + // This will happen with negligible probability. + OPENSSL_PUT_ERROR(CRYPTO, ERR_R_INTERNAL_ERROR); + return false; + } + state = cpace_state_msg_generated; + return true; +} + +int CPACE_generate_msg(CPACE_CTX *ctx, uint8_t out_msg[CPACE_MSG_LEN]) { + auto *impl = bssl::FromOpaque(ctx); + return impl->ComputeMessage(out_msg); +} + +bool bssl::CpaceCtx::ComputeISK( + const uint8_t peer_msg[CPACE_MSG_LEN], Span peer_assoc_data, + uint8_t out_shared_secret[CPACE_SHARED_SECRET_LEN], + uint8_t out_sid[SHA512_DIGEST_LENGTH]) { + if (state != cpace_state_msg_generated) { + OPENSSL_PUT_ERROR(CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return false; + } + + state = cpace_state_key_generated; + + uint8_t k[32]; + if (X25519(k, our_private_key, peer_msg) != 1) { + // TODO(crbug.com/42290066): This is another instance where unifying the + // reason code and library code into one error code makes most sense. + OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR); + return false; + } + // ISK = H.hash(lv_cat(G.DSI || b"_ISK", sid, K)||transcript(Ya,ADa,Yb,ADb)) + static constexpr std::string_view kDsiIsk = "CPace255_ISK"; + static constexpr std::string_view kDsiSidOut = "CPaceSidOutput"; + SHA512_CTX hasher, sid_hasher; + SHA512_Init(&hasher); + const bool compute_sid = out_sid != nullptr; + if (compute_sid) { + SHA512_Init(&sid_hasher); + SHA512_Update(&sid_hasher, kDsiSidOut.data(), kDsiSidOut.size()); + } + push_lv_to_hasher(hasher, StringAsBytes(kDsiIsk)); + push_lv_to_hasher(hasher, session_id); + push_lv_to_hasher(hasher, Span(k, 32)); + Span peer_public_key(peer_msg, 32); + auto push_our_transcript = [&] { + push_lv_to_hasher(hasher, our_public_key); + push_lv_to_hasher(hasher, our_aad); + if (compute_sid) { + push_lv_to_hasher(sid_hasher, our_public_key); + push_lv_to_hasher(sid_hasher, our_aad); + } + }; + auto push_peer_transcript = [&] { + push_lv_to_hasher(hasher, peer_public_key); + push_lv_to_hasher(hasher, peer_assoc_data); + if (compute_sid) { + push_lv_to_hasher(sid_hasher, peer_public_key); + push_lv_to_hasher(sid_hasher, peer_assoc_data); + } + }; + + switch (our_role) { + case cpace_role_initiator: { + push_our_transcript(); + push_peer_transcript(); + break; + } + case cpace_role_responder: { + push_peer_transcript(); + push_our_transcript(); + break; + } + } + if (compute_sid) { + SHA512_Final(out_sid, &sid_hasher); + } + return SHA512_Final(out_shared_secret, &hasher); +} + +// CPACE_process_msg processes a received message and finalize +int CPACE_process_msg(CPACE_CTX *ctx, const uint8_t msg[CPACE_MSG_LEN], + const uint8_t *peer_assoc_data, + size_t peer_assoc_data_len, + uint8_t out_shared_secret[CPACE_SHARED_SECRET_LEN], + uint8_t out_sid[SHA512_DIGEST_LENGTH]) { + auto *impl = bssl::FromOpaque(ctx); + return impl->ComputeISK(msg, bssl::Span(peer_assoc_data, peer_assoc_data_len), + out_shared_secret, out_sid); +} diff --git a/third_party/boringssl/src/crypto/curve25519/curve25519.cc b/third_party/boringssl/src/crypto/curve25519/curve25519.cc index a3cd507..2ddfca6 100644 --- a/third_party/boringssl/src/crypto/curve25519/curve25519.cc +++ b/third_party/boringssl/src/crypto/curve25519/curve25519.cc @@ -44,9 +44,11 @@ using namespace bssl; +namespace { + // Low-level intrinsic operations -static uint64_t load_3(const uint8_t *in) { +uint64_t load_3(const uint8_t *in) { uint64_t result; result = (uint64_t)in[0]; result |= ((uint64_t)in[1]) << 8; @@ -54,7 +56,7 @@ static uint64_t load_3(const uint8_t *in) { return result; } -static uint64_t load_4(const uint8_t *in) { +uint64_t load_4(const uint8_t *in) { uint64_t result; result = (uint64_t)in[0]; result |= ((uint64_t)in[1]) << 8; @@ -151,7 +153,7 @@ typedef uint32_t fe_limb_t; static_assert(sizeof(fe) == sizeof(fe_limb_t) * FE_NUM_LIMBS, "fe_limb_t[FE_NUM_LIMBS] is inconsistent with fe"); -static void fe_frombytes_strict(fe *h, const uint8_t s[32]) { +void fe_frombytes_strict(fe *h, const uint8_t s[32]) { // `fiat_25519_from_bytes` requires the top-most bit be clear. declassify_assert((s[31] & 0x80) == 0); fiat_25519_from_bytes(h->v, s); @@ -160,37 +162,37 @@ static void fe_frombytes_strict(fe *h, const uint8_t s[32]) { // fe_frombytes takes in a little-endian 255-bit number and decodes it into an // `fe`. -static void fe_frombytes(fe *h, const uint8_t s[32]) { +void fe_frombytes(fe *h, const uint8_t s[32]) { uint8_t s_copy[32]; OPENSSL_memcpy(s_copy, s, 32); s_copy[31] &= 0x7f; fe_frombytes_strict(h, s_copy); } -static void fe_tobytes(uint8_t s[32], const fe *f) { +void fe_tobytes(uint8_t s[32], const fe *f) { assert_fe(f->v); fiat_25519_to_bytes(s, f->v); } // h = 0 -static void fe_0(fe *h) { OPENSSL_memset(h, 0, sizeof(fe)); } +void fe_0(fe *h) { OPENSSL_memset(h, 0, sizeof(fe)); } -static void fe_loose_0(fe_loose *h) { OPENSSL_memset(h, 0, sizeof(fe_loose)); } +void fe_loose_0(fe_loose *h) { OPENSSL_memset(h, 0, sizeof(fe_loose)); } // h = 1 -static void fe_1(fe *h) { +void fe_1(fe *h) { OPENSSL_memset(h, 0, sizeof(fe)); h->v[0] = 1; } -static void fe_loose_1(fe_loose *h) { +void fe_loose_1(fe_loose *h) { OPENSSL_memset(h, 0, sizeof(fe_loose)); h->v[0] = 1; } // h = f + g // Can overlap h with f or g. -static void fe_add(fe_loose *h, const fe *f, const fe *g) { +void fe_add(fe_loose *h, const fe *f, const fe *g) { assert_fe(f->v); assert_fe(g->v); fiat_25519_add(h->v, f->v, g->v); @@ -199,59 +201,58 @@ static void fe_add(fe_loose *h, const fe *f, const fe *g) { // h = f - g // Can overlap h with f or g. -static void fe_sub(fe_loose *h, const fe *f, const fe *g) { +void fe_sub(fe_loose *h, const fe *f, const fe *g) { assert_fe(f->v); assert_fe(g->v); fiat_25519_sub(h->v, f->v, g->v); assert_fe_loose(h->v); } -static void fe_carry(fe *h, const fe_loose *f) { +void fe_carry(fe *h, const fe_loose *f) { assert_fe_loose(f->v); fiat_25519_carry(h->v, f->v); assert_fe(h->v); } -static void fe_mul_impl(fe_limb_t out[FE_NUM_LIMBS], - const fe_limb_t in1[FE_NUM_LIMBS], - const fe_limb_t in2[FE_NUM_LIMBS]) { +void fe_mul_impl(fe_limb_t out[FE_NUM_LIMBS], const fe_limb_t in1[FE_NUM_LIMBS], + const fe_limb_t in2[FE_NUM_LIMBS]) { assert_fe_loose(in1); assert_fe_loose(in2); fiat_25519_carry_mul(out, in1, in2); assert_fe(out); } -static void fe_mul_ltt(fe_loose *h, const fe *f, const fe *g) { +void fe_mul_ltt(fe_loose *h, const fe *f, const fe *g) { fe_mul_impl(h->v, f->v, g->v); } -static void fe_mul_llt(fe_loose *h, const fe_loose *f, const fe *g) { +void fe_mul_llt(fe_loose *h, const fe_loose *f, const fe *g) { fe_mul_impl(h->v, f->v, g->v); } -static void fe_mul_ttt(fe *h, const fe *f, const fe *g) { +void fe_mul_ttt(fe *h, const fe *f, const fe *g) { fe_mul_impl(h->v, f->v, g->v); } -static void fe_mul_tlt(fe *h, const fe_loose *f, const fe *g) { +void fe_mul_tlt(fe *h, const fe_loose *f, const fe *g) { fe_mul_impl(h->v, f->v, g->v); } -static void fe_mul_ttl(fe *h, const fe *f, const fe_loose *g) { +void fe_mul_ttl(fe *h, const fe *f, const fe_loose *g) { fe_mul_impl(h->v, f->v, g->v); } -static void fe_mul_tll(fe *h, const fe_loose *f, const fe_loose *g) { +void fe_mul_tll(fe *h, const fe_loose *f, const fe_loose *g) { fe_mul_impl(h->v, f->v, g->v); } -static void fe_sq_tl(fe *h, const fe_loose *f) { +void fe_sq_tl(fe *h, const fe_loose *f) { assert_fe_loose(f->v); fiat_25519_carry_square(h->v, f->v); assert_fe(h->v); } -static void fe_sq_tt(fe *h, const fe *f) { +void fe_sq_tt(fe *h, const fe *f) { assert_fe_loose(f->v); fiat_25519_carry_square(h->v, f->v); assert_fe(h->v); @@ -261,7 +262,7 @@ static void fe_sq_tt(fe *h, const fe *f) { // replace (f,g) with (f,g) if b == 0. // // Preconditions: b in {0,1}. -static void fe_cswap(fe *f, fe *g, fe_limb_t b) { +void fe_cswap(fe *f, fe *g, fe_limb_t b) { b = 0 - b; for (unsigned i = 0; i < FE_NUM_LIMBS; i++) { fe_limb_t x = f->v[i] ^ g->v[i]; @@ -271,14 +272,14 @@ static void fe_cswap(fe *f, fe *g, fe_limb_t b) { } } -static void fe_mul121666(fe *h, const fe_loose *f) { +void fe_mul121666(fe *h, const fe_loose *f) { assert_fe_loose(f->v); fiat_25519_carry_scmul_121666(h->v, f->v); assert_fe(h->v); } // h = -f -static void fe_neg(fe_loose *h, const fe *f) { +void fe_neg(fe_loose *h, const fe *f) { assert_fe(f->v); fiat_25519_opp(h->v, f->v); assert_fe_loose(h->v); @@ -288,7 +289,7 @@ static void fe_neg(fe_loose *h, const fe *f) { // replace (f,g) with (f,g) if b == 0. // // Preconditions: b in {0,1}. -static void fe_cmov(fe_loose *f, const fe_loose *g, fe_limb_t b) { +void fe_cmov(fe_loose *f, const fe_loose *g, fe_limb_t b) { // Silence an unused function warning. `fiat_25519_selectznz` isn't quite the // calling convention the rest of this code wants, so implement it by hand. // @@ -307,7 +308,7 @@ static void fe_cmov(fe_loose *f, const fe_loose *g, fe_limb_t b) { // replace (f,g) with (f,g) if b == 0. // // Preconditions: b in {0,1}. -static void fe_cmov(fe *f, const fe *g, fe_limb_t b) { +void fe_cmov(fe *f, const fe *g, fe_limb_t b) { b = 0 - b; for (unsigned i = 0; i < FE_NUM_LIMBS; i++) { fe_limb_t x = f->v[i] ^ g->v[i]; @@ -317,14 +318,14 @@ static void fe_cmov(fe *f, const fe *g, fe_limb_t b) { } // h = f -static void fe_copy(fe *h, const fe *f) { OPENSSL_memmove(h, f, sizeof(fe)); } +void fe_copy(fe *h, const fe *f) { OPENSSL_memmove(h, f, sizeof(fe)); } -static void fe_copy_lt(fe_loose *h, const fe *f) { +void fe_copy_lt(fe_loose *h, const fe *f) { static_assert(sizeof(fe_loose) == sizeof(fe), "fe and fe_loose mismatch"); OPENSSL_memmove(h, f, sizeof(fe)); } -static void fe_loose_invert(fe *out, const fe_loose *z) { +void fe_loose_invert(fe *out, const fe_loose *z) { fe t0; fe t1; fe t2; @@ -382,7 +383,7 @@ static void fe_loose_invert(fe *out, const fe_loose *z) { fe_mul_ttt(out, &t1, &t0); } -static void fe_invert(fe *out, const fe *z) { +void fe_invert(fe *out, const fe *z) { fe_loose l; fe_copy_lt(&l, z); fe_loose_invert(out, &l); @@ -390,7 +391,7 @@ static void fe_invert(fe *out, const fe *z) { // return 0 if f == 0 // return 1 if f != 0 -static int fe_isnonzero(const fe *f) { +int fe_isnonzero(const fe *f) { uint8_t s[32]; fe_tobytes(s, f); @@ -400,7 +401,7 @@ static int fe_isnonzero(const fe *f) { // return 0 if f == 0 // return 1 if f != 0 -static int fe_isnonzero(const fe_loose *f) { +int fe_isnonzero(const fe_loose *f) { fe tight; fe_carry(&tight, f); return fe_isnonzero(&tight); @@ -408,13 +409,13 @@ static int fe_isnonzero(const fe_loose *f) { // return 1 if f is in {1,3,5,...,q-2} // return 0 if f is in {0,2,4,...,q-1} -static int fe_isnegative(const fe *f) { +int fe_isnegative(const fe *f) { uint8_t s[32]; fe_tobytes(s, f); return s[0] & 1; } -static void fe_sq2_tt(fe *h, const fe *f) { +void fe_sq2_tt(fe *h, const fe *f) { // h = f² fe_sq_tt(h, f); @@ -424,7 +425,7 @@ static void fe_sq2_tt(fe *h, const fe *f) { fe_carry(h, &tmp); } -static void fe_pow22523(fe *out, const fe *z) { +void fe_pow22523(fe *out, const fe *z) { fe t0; fe t1; fe t2; @@ -481,6 +482,7 @@ static void fe_pow22523(fe *out, const fe *z) { fe_mul_ttt(out, &t0, z); } +} // namespace // Group operations. @@ -496,7 +498,9 @@ void bssl::x25519_ge_tobytes(uint8_t s[32], const ge_p2 *h) { s[31] ^= fe_isnegative(&x) << 7; } -static void ge_p3_tobytes(uint8_t s[32], const ge_p3 *h) { +namespace { + +void ge_p3_tobytes(uint8_t s[32], const ge_p3 *h) { fe recip; fe x; fe y; @@ -508,6 +512,8 @@ static void ge_p3_tobytes(uint8_t s[32], const ge_p3 *h) { s[31] ^= fe_isnegative(&x) << 7; } +} // namespace + int bssl::x25519_ge_frombytes_vartime(ge_p3 *h, const uint8_t s[32]) { fe u; fe_loose v; @@ -548,39 +554,43 @@ int bssl::x25519_ge_frombytes_vartime(ge_p3 *h, const uint8_t s[32]) { return 1; } -static void ge_p2_0(ge_p2 *h) { +namespace { + +void ge_p2_0(ge_p2 *h) { fe_0(&h->X); fe_1(&h->Y); fe_1(&h->Z); } -static void ge_p3_0(ge_p3 *h) { +void ge_p3_0(ge_p3 *h) { fe_0(&h->X); fe_1(&h->Y); fe_1(&h->Z); fe_0(&h->T); } -static void ge_cached_0(ge_cached *h) { +void ge_cached_0(ge_cached *h) { fe_loose_1(&h->YplusX); fe_loose_1(&h->YminusX); fe_loose_1(&h->Z); fe_loose_0(&h->T2d); } -static void ge_precomp_0(ge_precomp *h) { +void ge_precomp_0(ge_precomp *h) { fe_loose_1(&h->yplusx); fe_loose_1(&h->yminusx); fe_loose_0(&h->xy2d); } // r = p -static void ge_p3_to_p2(ge_p2 *r, const ge_p3 *p) { +void ge_p3_to_p2(ge_p2 *r, const ge_p3 *p) { fe_copy(&r->X, &p->X); fe_copy(&r->Y, &p->Y); fe_copy(&r->Z, &p->Z); } +} // namespace + // r = p void bssl::x25519_ge_p3_to_cached(ge_cached *r, const ge_p3 *p) { fe_add(&r->YplusX, &p->Y, &p->X); @@ -604,15 +614,17 @@ void bssl::x25519_ge_p1p1_to_p3(ge_p3 *r, const ge_p1p1 *p) { fe_mul_tll(&r->T, &p->X, &p->Y); } +namespace { + // r = p -static void ge_p1p1_to_cached(ge_cached *r, const ge_p1p1 *p) { +void ge_p1p1_to_cached(ge_cached *r, const ge_p1p1 *p) { ge_p3 t; x25519_ge_p1p1_to_p3(&t, p); x25519_ge_p3_to_cached(r, &t); } // r = 2 * p -static void ge_p2_dbl(ge_p1p1 *r, const ge_p2 *p) { +void ge_p2_dbl(ge_p1p1 *r, const ge_p2 *p) { fe trX, trZ, trT; fe t0; @@ -631,14 +643,14 @@ static void ge_p2_dbl(ge_p1p1 *r, const ge_p2 *p) { } // r = 2 * p -static void ge_p3_dbl(ge_p1p1 *r, const ge_p3 *p) { +void ge_p3_dbl(ge_p1p1 *r, const ge_p3 *p) { ge_p2 q; ge_p3_to_p2(&q, p); ge_p2_dbl(r, &q); } // r = p + q -static void ge_madd(ge_p1p1 *r, const ge_p3 *p, const ge_precomp *q) { +void ge_madd(ge_p1p1 *r, const ge_p3 *p, const ge_precomp *q) { fe trY, trZ, trT; fe_add(&r->X, &p->Y, &p->X); @@ -655,7 +667,7 @@ static void ge_madd(ge_p1p1 *r, const ge_p3 *p, const ge_precomp *q) { } // r = p - q -static void ge_msub(ge_p1p1 *r, const ge_p3 *p, const ge_precomp *q) { +void ge_msub(ge_p1p1 *r, const ge_p3 *p, const ge_precomp *q) { fe trY, trZ, trT; fe_add(&r->X, &p->Y, &p->X); @@ -671,6 +683,8 @@ static void ge_msub(ge_p1p1 *r, const ge_p3 *p, const ge_precomp *q) { fe_add(&r->T, &trZ, &trT); } +} // namespace + // r = p + q void bssl::x25519_ge_add(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) { fe trX, trY, trZ, trT; @@ -707,12 +721,16 @@ void bssl::x25519_ge_sub(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) { fe_add(&r->T, &trZ, &trT); } -static void cmov(ge_precomp *t, const ge_precomp *u, uint8_t b) { +namespace { + +void cmov(ge_precomp *t, const ge_precomp *u, uint8_t b) { fe_cmov(&t->yplusx, &u->yplusx, b); fe_cmov(&t->yminusx, &u->yminusx, b); fe_cmov(&t->xy2d, &u->xy2d, b); } +} // namespace + void bssl::x25519_ge_scalarmult_small_precomp( ge_p3 *h, const uint8_t a[32], const uint8_t precomp_table[15 * 2 * 32]) { // precomp_table is first expanded into matching `ge_precomp` @@ -775,7 +793,9 @@ void bssl::x25519_ge_scalarmult_base(ge_p3 *h, const uint8_t a[32]) { #else -static void table_select(ge_precomp *t, const int pos, const signed char b) { +namespace { + +void table_select(ge_precomp *t, const int pos, const signed char b) { uint8_t bnegative = constant_time_msb_w(b); uint8_t babs = b - ((bnegative & b) << 1); @@ -809,6 +829,8 @@ static void table_select(ge_precomp *t, const int pos, const signed char b) { cmov(t, &minust, bnegative >> 7); } +} // namespace + // h = a * B // where a = a[0]+256*a[1]+...+256^31 a[31] // B is the Ed25519 base point (x,4/5) with x positive. @@ -877,13 +899,17 @@ void bssl::x25519_ge_scalarmult_base(ge_p3 *h, const uint8_t a[32]) { #endif -static void cmov_cached(ge_cached *t, ge_cached *u, uint8_t b) { +namespace { + +void cmov_cached(ge_cached *t, ge_cached *u, uint8_t b) { fe_cmov(&t->YplusX, &u->YplusX, b); fe_cmov(&t->YminusX, &u->YminusX, b); fe_cmov(&t->Z, &u->Z, b); fe_cmov(&t->T2d, &u->T2d, b); } +} // namespace + // r = scalar * A. // where a = a[0]+256*a[1]+...+256^31 a[31]. void bssl::x25519_ge_scalarmult(ge_p2 *r, const uint8_t *scalar, @@ -939,7 +965,9 @@ void bssl::x25519_ge_scalarmult(ge_p2 *r, const uint8_t *scalar, } } -static void slide(signed char *r, const uint8_t *a) { +namespace { + +void slide(signed char *r, const uint8_t *a) { int i; int b; int k; @@ -977,8 +1005,8 @@ static void slide(signed char *r, const uint8_t *a) { // where a = a[0]+256*a[1]+...+256^31 a[31]. // and b = b[0]+256*b[1]+...+256^31 b[31]. // B is the Ed25519 base point (x,4/5) with x positive. -static void ge_double_scalarmult_vartime(ge_p2 *r, const uint8_t *a, - const ge_p3 *A, const uint8_t *b) { +void ge_double_scalarmult_vartime(ge_p2 *r, const uint8_t *a, const ge_p3 *A, + const uint8_t *b) { signed char aslide[256]; signed char bslide[256]; ge_cached Ai[8]; // A,3A,5A,7A,9A,11A,13A,15A @@ -1048,9 +1076,9 @@ static void ge_double_scalarmult_vartime(ge_p2 *r, const uint8_t *a, // int64_lshift21 returns `a << 21` but is defined when shifting bits into the // sign bit. This works around a language flaw in C. -static int64_t int64_lshift21(int64_t a) { - return (int64_t)((uint64_t)a << 21); -} +int64_t int64_lshift21(int64_t a) { return (int64_t)((uint64_t)a << 21); } + +} // namespace // The set of scalars is \Z/l // where l = 2^252 + 27742317777372353535851937790883648493. @@ -1403,8 +1431,10 @@ void bssl::x25519_sc_reduce(uint8_t s[64]) { // Output: // s[0]+256*s[1]+...+256^31*s[31] = (ab+c) mod l // where l = 2^252 + 27742317777372353535851937790883648493. -static void sc_muladd(uint8_t *s, const uint8_t *a, const uint8_t *b, - const uint8_t *c) { +namespace { + +void sc_muladd(uint8_t *s, const uint8_t *a, const uint8_t *b, + const uint8_t *c) { int64_t a0 = 2097151 & load_3(a); int64_t a1 = 2097151 & (load_4(a + 2) >> 5); int64_t a2 = 2097151 & (load_3(a + 5) >> 2); @@ -1884,15 +1914,19 @@ static void sc_muladd(uint8_t *s, const uint8_t *a, const uint8_t *b, s[31] = s11 >> 17; } +} // namespace + void ED25519_keypair(uint8_t out_public_key[32], uint8_t out_private_key[64]) { uint8_t seed[32]; RAND_bytes(seed, 32); ED25519_keypair_from_seed(out_public_key, out_private_key, seed); } -static int ed25519_sign(uint8_t out_sig[64], const uint8_t *hash_prefix, - size_t hash_prefix_len, const uint8_t *message, - size_t message_len, const uint8_t private_key[64]) { +namespace { + +int ed25519_sign(uint8_t out_sig[64], const uint8_t *hash_prefix, + size_t hash_prefix_len, const uint8_t *message, + size_t message_len, const uint8_t private_key[64]) { uint8_t az[SHA512_DIGEST_LENGTH]; SHA512(private_key, 32, az); @@ -1929,10 +1963,9 @@ static int ed25519_sign(uint8_t out_sig[64], const uint8_t *hash_prefix, return 1; } -static int ed25519_verify(const uint8_t *hash_prefix, size_t hash_prefix_len, - const uint8_t *message, size_t message_len, - const uint8_t signature[64], - const uint8_t public_key[32]) { +int ed25519_verify(const uint8_t *hash_prefix, size_t hash_prefix_len, + const uint8_t *message, size_t message_len, + const uint8_t signature[64], const uint8_t public_key[32]) { ge_p3 A; if ((signature[63] & 224) != 0 || !x25519_ge_frombytes_vartime(&A, public_key)) { @@ -1993,6 +2026,8 @@ static int ed25519_verify(const uint8_t *hash_prefix, size_t hash_prefix_len, return CRYPTO_memcmp(rcheck, rcopy, sizeof(rcheck)) == 0; } +} // namespace + int ED25519_sign(uint8_t out_sig[64], const uint8_t *message, size_t message_len, const uint8_t private_key[64]) { // NOTE: The documentation on this function says that it returns zero on @@ -2013,11 +2048,13 @@ int ED25519_verify(const uint8_t *message, size_t message_len, #define ED25519_MAX_CONTEXT 255 #define ED25519_MAX_HASH_PREFIX (32 + 1 + 1 + ED25519_MAX_CONTEXT) +namespace { + // ed25519_build_hash_prefix implements the `dom2` function from // https://datatracker.ietf.org/doc/html/rfc8032#section-2 -static int ed25519_build_hash_prefix( - uint8_t out_hash_prefix[ED25519_MAX_HASH_PREFIX], - size_t *out_hash_prefix_len, const uint8_t *context, size_t context_len) { +int ed25519_build_hash_prefix(uint8_t out_hash_prefix[ED25519_MAX_HASH_PREFIX], + size_t *out_hash_prefix_len, + const uint8_t *context, size_t context_len) { if (context_len > ED25519_MAX_CONTEXT) { return 0; } @@ -2030,6 +2067,8 @@ static int ed25519_build_hash_prefix( return 1; } +} // namespace + int ED25519_sign_prehashed(uint8_t out_sig[64], const uint8_t *context, size_t context_len, const uint8_t sha512_digest[SHA512_DIGEST_LENGTH], @@ -2086,9 +2125,10 @@ void ED25519_keypair_from_seed(uint8_t out_public_key[32], } -static void x25519_scalar_mult_generic(uint8_t out[32], - const uint8_t scalar[32], - const uint8_t point[32]) { +namespace { + +void x25519_scalar_mult_generic(uint8_t out[32], const uint8_t scalar[32], + const uint8_t point[32]) { fe x1, x2, z2, x3, z3, tmp0, tmp1; fe_loose x2l, z2l, x3l, tmp0l, tmp1l; @@ -2170,8 +2210,8 @@ static void x25519_scalar_mult_generic(uint8_t out[32], fe_tobytes(out, &x2); } -static void x25519_scalar_mult(uint8_t out[32], const uint8_t scalar[32], - const uint8_t point[32]) { +void x25519_scalar_mult(uint8_t out[32], const uint8_t scalar[32], + const uint8_t point[32]) { #if defined(BORINGSSL_X25519_NEON) if (CRYPTO_is_NEON_capable()) { x25519_NEON(out, scalar, point); @@ -2188,6 +2228,8 @@ static void x25519_scalar_mult(uint8_t out[32], const uint8_t scalar[32], x25519_scalar_mult_generic(out, scalar, point); } +} // namespace + void X25519_keypair(uint8_t out_public_value[32], uint8_t out_private_key[32]) { RAND_bytes(out_private_key, 32); @@ -2251,7 +2293,9 @@ void X25519_public_from_private(uint8_t out_public_value[32], CONSTTIME_DECLASSIFY(out_public_value, 32); } -static void fe_from_limb(fe *h, fe_limb_t val) { +namespace { + +void fe_from_limb(fe *h, fe_limb_t val) { fe_0(h); h->v[0] = val; assert_fe(h->v); @@ -2262,8 +2306,8 @@ static void fe_from_limb(fe *h, fe_limb_t val) { // // It maps a field element u to a Montgomery point (xn / xd, y / 1) on the curve // t^2 = s^3 + 486662*s^2 + s. -static void map_to_curve_elligator2(fe *out_xMn, fe *out_xMd, fe *out_yMn, - const fe *u) { +void map_to_curve_elligator2(fe *out_xMn, fe *out_xMd, fe *out_yMn, + const fe *u) { fe one, J_fe, c2_fe; fe_1(&one); fe_from_limb(&J_fe, 486662); @@ -2419,6 +2463,8 @@ static void map_to_curve_elligator2(fe *out_xMn, fe *out_xMd, fe *out_yMn, fe_copy(out_yMn, &y); } +} // namespace + void bssl::map_to_curve_curve25519_elligator2(uint8_t out_qx[32], uint8_t out_qy[32], const uint8_t u[32]) { diff --git a/third_party/boringssl/src/crypto/curve25519/curve25519_tables.h b/third_party/boringssl/src/crypto/curve25519/curve25519_tables.h index 0869238..723a417 100644 --- a/third_party/boringssl/src/crypto/curve25519/curve25519_tables.h +++ b/third_party/boringssl/src/crypto/curve25519/curve25519_tables.h @@ -16,7 +16,9 @@ // ./make_curve25519_tables.py > curve25519_tables.h -static const bssl::fe d = {{ +namespace { + +const bssl::fe d = {{ #if defined(OPENSSL_64_BIT) 929955233495203, 466365720129213, 1662059464998953, 2033849074728123, 1442794654840575 @@ -26,7 +28,7 @@ static const bssl::fe d = {{ #endif }}; -static const bssl::fe sqrtm1 = {{ +const bssl::fe sqrtm1 = {{ #if defined(OPENSSL_64_BIT) 1718705420411056, 234908883556509, 2233514472574048, 2117202627021982, 765476049583133 @@ -36,7 +38,7 @@ static const bssl::fe sqrtm1 = {{ #endif }}; -static const bssl::fe d2 = {{ +const bssl::fe d2 = {{ #if defined(OPENSSL_64_BIT) 1859910466990425, 932731440258426, 1072319116312658, 1815898335770999, 633789495995903 @@ -46,17 +48,257 @@ static const bssl::fe d2 = {{ #endif }}; +// Bi[i] = (2*i+1)*B +const bssl::ge_precomp Bi[8] = { + { + {{ +#if defined(OPENSSL_64_BIT) + 1288382639258501, 245678601348599, 269427782077623, + 1462984067271730, 137412439391563 +#else + 25967493, 19198397, 29566455, 3660896, 54414519, 4014786, 27544626, + 21800161, 61029707, 2047604 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 62697248952638, 204681361388450, 631292143396476, 338455783676468, + 1213667448819585 +#else + 54563134, 934261, 64385954, 3049989, 66381436, 9406985, 12720692, + 5043384, 19500929, 18085054 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 301289933810280, 1259582250014073, 1422107436869536, + 796239922652654, 1953934009299142 +#else + 58370664, 4489569, 9688441, 18769238, 10184608, 21191052, 29287918, + 11864899, 42594502, 29115885 +#endif + }}, + }, + { + {{ +#if defined(OPENSSL_64_BIT) + 1601611775252272, 1720807796594148, 1132070835939856, + 1260455018889551, 2147779492816911 +#else + 15636272, 23865875, 24204772, 25642034, 616976, 16869170, 27787599, + 18782243, 28944399, 32004408 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 316559037616741, 2177824224946892, 1459442586438991, + 1461528397712656, 751590696113597 +#else + 16568933, 4717097, 55552716, 32452109, 15682895, 21747389, 16354576, + 21778470, 7689661, 11199574 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 1850748884277385, 1200145853858453, 1068094770532492, + 672251375690438, 1586055907191707 +#else + 30464137, 27578307, 55329429, 17883566, 23220364, 15915852, 7512774, + 10017326, 49359771, 23634074 +#endif + }}, + }, + { + {{ +#if defined(OPENSSL_64_BIT) + 769950342298419, 132954430919746, 844085933195555, 974092374476333, + 726076285546016 +#else + 10861363, 11473154, 27284546, 1981175, 37044515, 12577860, 32867885, + 14515107, 51670560, 10819379 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 425251763115706, 608463272472562, 442562545713235, 837766094556764, + 374555092627893 +#else + 4708026, 6336745, 20377586, 9066809, 55836755, 6594695, 41455196, + 12483687, 54440373, 5581305 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 1086255230780037, 274979815921559, 1960002765731872, + 929474102396301, 1190409889297339 +#else + 19563141, 16186464, 37722007, 4097518, 10237984, 29206317, 28542349, + 13850243, 43430843, 17738489 +#endif + }}, + }, + { + {{ +#if defined(OPENSSL_64_BIT) + 665000864555967, 2065379846933859, 370231110385876, 350988370788628, + 1233371373142985 +#else + 5153727, 9909285, 1723747, 30776558, 30523604, 5516873, 19480852, + 5230134, 43156425, 18378665 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 2019367628972465, 676711900706637, 110710997811333, + 1108646842542025, 517791959672113 +#else + 36839857, 30090922, 7665485, 10083793, 28475525, 1649722, 20654025, + 16520125, 30598449, 7715701 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 965130719900578, 247011430587952, 526356006571389, 91986625355052, + 2157223321444601 +#else + 28881826, 14381568, 9657904, 3680757, 46927229, 7843315, 35708204, + 1370707, 29794553, 32145132 +#endif + }}, + }, + { + {{ +#if defined(OPENSSL_64_BIT) + 1802695059465007, 1664899123557221, 593559490740857, + 2160434469266659, 927570450755031 +#else + 44589871, 26862249, 14201701, 24808930, 43598457, 8844725, 18474211, + 32192982, 54046167, 13821876 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 1725674970513508, 1933645953859181, 1542344539275782, + 1767788773573747, 1297447965928905 +#else + 60653668, 25714560, 3374701, 28813570, 40010246, 22982724, 31655027, + 26342105, 18853321, 19333481 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 1381809363726107, 1430341051343062, 2061843536018959, + 1551778050872521, 2036394857967624 +#else + 4566811, 20590564, 38133974, 21313742, 59506191, 30723862, 58594505, + 23123294, 2207752, 30344648 +#endif + }}, + }, + { + {{ +#if defined(OPENSSL_64_BIT) + 1970894096313054, 528066325833207, 1619374932191227, + 2207306624415883, 1169170329061080 +#else + 41954014, 29368610, 29681143, 7868801, 60254203, 24130566, 54671499, + 32891431, 35997400, 17421995 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 2070390218572616, 1458919061857835, 624171843017421, + 1055332792707765, 433987520732508 +#else + 25576264, 30851218, 7349803, 21739588, 16472781, 9300885, 3844789, + 15725684, 171356, 6466918 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 893653801273833, 1168026499324677, 1242553501121234, + 1306366254304474, 1086752658510815 +#else + 23103977, 13316479, 9739013, 17404951, 817874, 18515490, 8965338, + 19466374, 36393951, 16193876 +#endif + }}, + }, + { + {{ +#if defined(OPENSSL_64_BIT) + 213454002618221, 939771523987438, 1159882208056014, 317388369627517, + 621213314200687 +#else + 33587053, 3180712, 64714734, 14003686, 50205390, 17283591, 17238397, + 4729455, 49034351, 9256799 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 1971678598905747, 338026507889165, 762398079972271, 655096486107477, + 42299032696322 +#else + 41926547, 29380300, 32336397, 5036987, 45872047, 11360616, 22616405, + 9761698, 47281666, 630304 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 177130678690680, 1754759263300204, 1864311296286618, + 1180675631479880, 1292726903152791 +#else + 53388152, 2639452, 42871404, 26147950, 9494426, 27780403, 60554312, + 17593437, 64659607, 19263131 +#endif + }}, + }, + { + {{ +#if defined(OPENSSL_64_BIT) + 1913163449625248, 460779200291993, 2193883288642314, + 1008900146920800, 1721983679009502 +#else + 63957664, 28508356, 9282713, 6866145, 35201802, 32691408, 48168288, + 15033783, 25105118, 25659556 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 1070401523076875, 1272492007800961, 1910153608563310, + 2075579521696771, 1191169788841221 +#else + 42782475, 15950225, 35307649, 18961608, 55446126, 28463506, 1573891, + 30928545, 2198789, 17749813 +#endif + }}, + {{ +#if defined(OPENSSL_64_BIT) + 692896803108118, 500174642072499, 2068223309439677, + 1162190621851337, 1426986007309901 +#else + 64009494, 10324966, 64867251, 7453182, 61661885, 30818928, 53296841, + 17317989, 34647629, 21263748 +#endif + }}, + }, +}; + +} // namespace + #if defined(OPENSSL_SMALL) +namespace { + // This block of code replaces the standard base-point table with a much smaller // one. The standard table is 30,720 bytes while this one is just 960. // // This table contains 15 pairs of group elements, (x, y), where each field // element is serialised with `fe_tobytes`. If `i` is the index of the group -// element then consider i+1 as a four-bit number: (i₀, i₁, i₂, i₃) (where i₀ -// is the most significant bit). The value of the group element is then: +// element then consider i+1 as a four-bit number: (i₀, i₁, i₂, i₃) where i₀ +// is the most significant bit. The value of the group element is then: // (i₀×2^192 + i₁×2^128 + i₂×2^64 + i₃)G, where G is the generator. -static const uint8_t k25519SmallPrecomp[15 * 2 * 32] = { +const uint8_t k25519SmallPrecomp[15 * 2 * 32] = { 0x1a, 0xd5, 0x25, 0x8f, 0x60, 0x2d, 0x56, 0xc9, 0xb2, 0xa7, 0x25, 0x95, 0x60, 0xc7, 0x2c, 0x69, 0x5c, 0xdc, 0xd6, 0xfd, 0x31, 0xe2, 0xa4, 0xc0, 0xfe, 0x53, 0x6e, 0xcd, 0xd3, 0x36, 0x69, 0x21, 0x58, 0x66, 0x66, 0x66, @@ -139,7 +381,9 @@ static const uint8_t k25519SmallPrecomp[15 * 2 * 32] = { 0x45, 0xc9, 0x8b, 0x17, 0x79, 0xe7, 0xc7, 0x90, 0x99, 0x3a, 0x18, 0x25, }; -#else +} // namespace + +#else // !OPENSSL_SMALL // k25519Precomp[i][j] = (j+1)*256^i*B const uint8_t bssl::k25519Precomp[32][8][3][32] = { @@ -3025,240 +3269,4 @@ const uint8_t bssl::k25519Precomp[32][8][3][32] = { }, }; -#endif // OPENSSL_SMALL - -// Bi[i] = (2*i+1)*B -static const bssl::ge_precomp Bi[8] = { - { - {{ -#if defined(OPENSSL_64_BIT) - 1288382639258501, 245678601348599, 269427782077623, - 1462984067271730, 137412439391563 -#else - 25967493, 19198397, 29566455, 3660896, 54414519, 4014786, 27544626, - 21800161, 61029707, 2047604 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 62697248952638, 204681361388450, 631292143396476, 338455783676468, - 1213667448819585 -#else - 54563134, 934261, 64385954, 3049989, 66381436, 9406985, 12720692, - 5043384, 19500929, 18085054 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 301289933810280, 1259582250014073, 1422107436869536, - 796239922652654, 1953934009299142 -#else - 58370664, 4489569, 9688441, 18769238, 10184608, 21191052, 29287918, - 11864899, 42594502, 29115885 -#endif - }}, - }, - { - {{ -#if defined(OPENSSL_64_BIT) - 1601611775252272, 1720807796594148, 1132070835939856, - 1260455018889551, 2147779492816911 -#else - 15636272, 23865875, 24204772, 25642034, 616976, 16869170, 27787599, - 18782243, 28944399, 32004408 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 316559037616741, 2177824224946892, 1459442586438991, - 1461528397712656, 751590696113597 -#else - 16568933, 4717097, 55552716, 32452109, 15682895, 21747389, 16354576, - 21778470, 7689661, 11199574 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 1850748884277385, 1200145853858453, 1068094770532492, - 672251375690438, 1586055907191707 -#else - 30464137, 27578307, 55329429, 17883566, 23220364, 15915852, 7512774, - 10017326, 49359771, 23634074 -#endif - }}, - }, - { - {{ -#if defined(OPENSSL_64_BIT) - 769950342298419, 132954430919746, 844085933195555, 974092374476333, - 726076285546016 -#else - 10861363, 11473154, 27284546, 1981175, 37044515, 12577860, 32867885, - 14515107, 51670560, 10819379 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 425251763115706, 608463272472562, 442562545713235, 837766094556764, - 374555092627893 -#else - 4708026, 6336745, 20377586, 9066809, 55836755, 6594695, 41455196, - 12483687, 54440373, 5581305 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 1086255230780037, 274979815921559, 1960002765731872, - 929474102396301, 1190409889297339 -#else - 19563141, 16186464, 37722007, 4097518, 10237984, 29206317, 28542349, - 13850243, 43430843, 17738489 -#endif - }}, - }, - { - {{ -#if defined(OPENSSL_64_BIT) - 665000864555967, 2065379846933859, 370231110385876, 350988370788628, - 1233371373142985 -#else - 5153727, 9909285, 1723747, 30776558, 30523604, 5516873, 19480852, - 5230134, 43156425, 18378665 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 2019367628972465, 676711900706637, 110710997811333, - 1108646842542025, 517791959672113 -#else - 36839857, 30090922, 7665485, 10083793, 28475525, 1649722, 20654025, - 16520125, 30598449, 7715701 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 965130719900578, 247011430587952, 526356006571389, 91986625355052, - 2157223321444601 -#else - 28881826, 14381568, 9657904, 3680757, 46927229, 7843315, 35708204, - 1370707, 29794553, 32145132 -#endif - }}, - }, - { - {{ -#if defined(OPENSSL_64_BIT) - 1802695059465007, 1664899123557221, 593559490740857, - 2160434469266659, 927570450755031 -#else - 44589871, 26862249, 14201701, 24808930, 43598457, 8844725, 18474211, - 32192982, 54046167, 13821876 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 1725674970513508, 1933645953859181, 1542344539275782, - 1767788773573747, 1297447965928905 -#else - 60653668, 25714560, 3374701, 28813570, 40010246, 22982724, 31655027, - 26342105, 18853321, 19333481 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 1381809363726107, 1430341051343062, 2061843536018959, - 1551778050872521, 2036394857967624 -#else - 4566811, 20590564, 38133974, 21313742, 59506191, 30723862, 58594505, - 23123294, 2207752, 30344648 -#endif - }}, - }, - { - {{ -#if defined(OPENSSL_64_BIT) - 1970894096313054, 528066325833207, 1619374932191227, - 2207306624415883, 1169170329061080 -#else - 41954014, 29368610, 29681143, 7868801, 60254203, 24130566, 54671499, - 32891431, 35997400, 17421995 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 2070390218572616, 1458919061857835, 624171843017421, - 1055332792707765, 433987520732508 -#else - 25576264, 30851218, 7349803, 21739588, 16472781, 9300885, 3844789, - 15725684, 171356, 6466918 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 893653801273833, 1168026499324677, 1242553501121234, - 1306366254304474, 1086752658510815 -#else - 23103977, 13316479, 9739013, 17404951, 817874, 18515490, 8965338, - 19466374, 36393951, 16193876 -#endif - }}, - }, - { - {{ -#if defined(OPENSSL_64_BIT) - 213454002618221, 939771523987438, 1159882208056014, 317388369627517, - 621213314200687 -#else - 33587053, 3180712, 64714734, 14003686, 50205390, 17283591, 17238397, - 4729455, 49034351, 9256799 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 1971678598905747, 338026507889165, 762398079972271, 655096486107477, - 42299032696322 -#else - 41926547, 29380300, 32336397, 5036987, 45872047, 11360616, 22616405, - 9761698, 47281666, 630304 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 177130678690680, 1754759263300204, 1864311296286618, - 1180675631479880, 1292726903152791 -#else - 53388152, 2639452, 42871404, 26147950, 9494426, 27780403, 60554312, - 17593437, 64659607, 19263131 -#endif - }}, - }, - { - {{ -#if defined(OPENSSL_64_BIT) - 1913163449625248, 460779200291993, 2193883288642314, - 1008900146920800, 1721983679009502 -#else - 63957664, 28508356, 9282713, 6866145, 35201802, 32691408, 48168288, - 15033783, 25105118, 25659556 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 1070401523076875, 1272492007800961, 1910153608563310, - 2075579521696771, 1191169788841221 -#else - 42782475, 15950225, 35307649, 18961608, 55446126, 28463506, 1573891, - 30928545, 2198789, 17749813 -#endif - }}, - {{ -#if defined(OPENSSL_64_BIT) - 692896803108118, 500174642072499, 2068223309439677, - 1162190621851337, 1426986007309901 -#else - 64009494, 10324966, 64867251, 7453182, 61661885, 30818928, 53296841, - 17317989, 34647629, 21263748 -#endif - }}, - }, -}; +#endif // !OPENSSL_SMALL diff --git a/third_party/boringssl/src/crypto/curve25519/internal.h b/third_party/boringssl/src/crypto/curve25519/internal.h index 7912bb3..d5f9033 100644 --- a/third_party/boringssl/src/crypto/curve25519/internal.h +++ b/third_party/boringssl/src/crypto/curve25519/internal.h @@ -15,9 +15,11 @@ #ifndef OPENSSL_HEADER_CRYPTO_CURVE25519_INTERNAL_H #define OPENSSL_HEADER_CRYPTO_CURVE25519_INTERNAL_H +#include #include -#include "../internal.h" +#include "../mem_internal.h" + BSSL_NAMESPACE_BEGIN @@ -165,8 +167,34 @@ struct spake2_ctx_st { char disable_password_scalar_hack; }; +DECLARE_OPAQUE_STRUCT(cpace_ctx_st, CpaceCtx) + BSSL_NAMESPACE_BEGIN +class CpaceCtx : public cpace_ctx_st { + public: + enum cpace_role_t our_role; + enum cpace_state_t { + cpace_state_init = 0, + cpace_state_msg_generated, + cpace_state_key_generated, + } state = cpace_state_init; + Array our_aad; + Array our_password; + Array channel_id; + Array session_id; + uint8_t our_public_key[32]; + uint8_t our_private_key[32]; + + static constexpr bool kAllowUniquePtr = true; + + void ComputeGeneratorStrHash(uint8_t out_gen_str_hash[32]) const; + bool ComputeMessage(uint8_t msg[32]); + bool ComputeISK(const uint8_t msg[32], Span peer_assoc_data, + uint8_t shared_secret[64], + uint8_t out_sid[SHA512_DIGEST_LENGTH]); +}; + extern const uint8_t k25519Precomp[32][8][3][32]; BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/crypto/curve25519/spake25519.cc b/third_party/boringssl/src/crypto/curve25519/spake25519.cc index ee5cd7c..fc56561 100644 --- a/third_party/boringssl/src/crypto/curve25519/spake25519.cc +++ b/third_party/boringssl/src/crypto/curve25519/spake25519.cc @@ -112,7 +112,9 @@ if __name__ == "__main__": printtable(Mtable, "kSpakeMSmallPrecomp") */ -static const uint8_t kSpakeNSmallPrecomp[15 * 2 * 32] = { +namespace { + +const uint8_t kSpakeNSmallPrecomp[15 * 2 * 32] = { 0x20, 0x1b, 0xc5, 0xb3, 0x43, 0x17, 0x71, 0x10, 0x44, 0x1e, 0x73, 0xb3, 0xae, 0x3f, 0xbf, 0x9f, 0xf5, 0x44, 0xc8, 0x13, 0x8f, 0xd1, 0x01, 0xc2, 0x8a, 0x1a, 0x6d, 0xea, 0x4d, 0x00, 0x5d, 0x6e, 0x10, 0xe3, 0xdf, 0x0a, @@ -195,7 +197,7 @@ static const uint8_t kSpakeNSmallPrecomp[15 * 2 * 32] = { 0x72, 0x46, 0x04, 0x07, 0xf2, 0x5b, 0xf4, 0x07, 0xd1, 0xf4, 0x59, 0x71, }; -static const uint8_t kSpakeMSmallPrecomp[15 * 2 * 32] = { +const uint8_t kSpakeMSmallPrecomp[15 * 2 * 32] = { 0xc8, 0xa6, 0x63, 0xc5, 0x97, 0xf1, 0xee, 0x40, 0xab, 0x62, 0x42, 0xee, 0x25, 0x6f, 0x32, 0x6c, 0x75, 0x2c, 0xa7, 0xd3, 0xbd, 0x32, 0x3b, 0x1e, 0x11, 0x9c, 0xbd, 0x04, 0xa9, 0x78, 0x6f, 0x45, 0x5a, 0xda, 0x7e, 0x4b, @@ -278,6 +280,8 @@ static const uint8_t kSpakeMSmallPrecomp[15 * 2 * 32] = { 0xa6, 0x76, 0x81, 0x28, 0xb2, 0x65, 0xe8, 0x47, 0x14, 0xc6, 0x39, 0x06, }; +} // namespace + SPAKE2_CTX *SPAKE2_CTX_new(enum spake2_role_t my_role, const uint8_t *my_name, size_t my_name_len, const uint8_t *their_name, size_t their_name_len) { @@ -310,9 +314,11 @@ void SPAKE2_CTX_free(SPAKE2_CTX *ctx) { Delete(ctx); } +namespace { + // left_shift_3 sets `n` to `n`*8, where `n` is represented in little-endian // order. -static void left_shift_3(uint8_t n[32]) { +void left_shift_3(uint8_t n[32]) { uint8_t carry = 0; unsigned i; @@ -323,33 +329,33 @@ static void left_shift_3(uint8_t n[32]) { } } -namespace { typedef struct { BN_ULONG words[32 / sizeof(BN_ULONG)]; } scalar; -} // namespace // kOrder is the order of the prime-order subgroup of curve25519. -static const scalar kOrder = { +const scalar kOrder = { {TOBN(0x5812631a, 0x5cf5d3ed), TOBN(0x14def9de, 0xa2f79cd6), TOBN(0x00000000, 0x00000000), TOBN(0x10000000, 0x00000000)}}; // scalar_cmov copies `src` to `dest` if `mask` is all ones. -static void scalar_cmov(scalar *dest, const scalar *src, crypto_word_t mask) { +void scalar_cmov(scalar *dest, const scalar *src, crypto_word_t mask) { bn_select_words(dest->words, mask, src->words, dest->words, std::size(dest->words)); } // scalar_double sets `s` to `2×s`. -static void scalar_double(scalar *s) { +void scalar_double(scalar *s) { bn_add_words(s->words, s->words, s->words, std::size(s->words)); } // scalar_add sets `dest` to `dest` plus `src`. -static void scalar_add(scalar *dest, const scalar *src) { +void scalar_add(scalar *dest, const scalar *src) { bn_add_words(dest->words, dest->words, src->words, std::size(dest->words)); } +} // namespace + int SPAKE2_generate_msg(SPAKE2_CTX *ctx, uint8_t *out, size_t *out_len, size_t max_out_len, const uint8_t *password, size_t password_len) { @@ -451,8 +457,10 @@ int SPAKE2_generate_msg(SPAKE2_CTX *ctx, uint8_t *out, size_t *out_len, return 1; } -static void update_with_length_prefix(SHA512_CTX *sha, const uint8_t *data, - const size_t len) { +namespace { + +void update_with_length_prefix(SHA512_CTX *sha, const uint8_t *data, + const size_t len) { uint8_t len_le[8]; size_t l = len; unsigned i; @@ -466,6 +474,8 @@ static void update_with_length_prefix(SHA512_CTX *sha, const uint8_t *data, SHA512_Update(sha, data, len); } +} // namespace + int SPAKE2_process_msg(SPAKE2_CTX *ctx, uint8_t *out_key, size_t *out_key_len, size_t max_out_key_len, const uint8_t *their_msg, size_t their_msg_len) { diff --git a/third_party/boringssl/src/crypto/digest/digest_extra.cc b/third_party/boringssl/src/crypto/digest/digest_extra.cc index 070ab36..4080076 100644 --- a/third_party/boringssl/src/crypto/digest/digest_extra.cc +++ b/third_party/boringssl/src/crypto/digest/digest_extra.cc @@ -26,11 +26,16 @@ #include #include +// IWYU pragma: begin_keep #include "../asn1/internal.h" #include "../fipsmodule/digest/internal.h" -#include "../internal.h" +// IWYU pragma: end_keep +using namespace bssl; + +namespace { + struct nid_to_digest { int nid; const EVP_MD *(*md_func)(); @@ -38,7 +43,7 @@ struct nid_to_digest { const char *long_name; }; -static const struct nid_to_digest nid_to_digest_mapping[] = { +const nid_to_digest nid_to_digest_mapping[] = { {NID_md4, EVP_md4, SN_md4, LN_md4}, {NID_md5, EVP_md5, SN_md5, LN_md5}, {NID_sha1, EVP_sha1, SN_sha1, LN_sha1}, @@ -68,22 +73,7 @@ static const struct nid_to_digest nid_to_digest_mapping[] = { LN_sha512WithRSAEncryption}, }; -const EVP_MD *EVP_get_digestbynid(int nid) { - if (nid == NID_undef) { - // Skip the `NID_undef` entries in `nid_to_digest_mapping`. - return nullptr; - } - - for (const auto &mapping : nid_to_digest_mapping) { - if (mapping.nid == nid) { - return mapping.md_func(); - } - } - - return nullptr; -} - -static const struct { +const struct { uint8_t oid[9]; uint8_t oid_len; int nid; @@ -104,16 +94,32 @@ static const struct { {{0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04}, 9, NID_sha224}, }; -static int cbs_to_digest_nid(const CBS *cbs) { +int cbs_to_digest_nid(const CBS *cbs) { for (const auto &md : kMDOIDs) { - if (bssl::Span(*cbs) == - bssl::Span(md.oid).first(md.oid_len)) { + if (Span(*cbs) == Span(md.oid).first(md.oid_len)) { return md.nid; } } return NID_undef; } +} // namespace + +const EVP_MD *EVP_get_digestbynid(int nid) { + if (nid == NID_undef) { + // Skip the `NID_undef` entries in `nid_to_digest_mapping`. + return nullptr; + } + + for (const auto &mapping : nid_to_digest_mapping) { + if (mapping.nid == nid) { + return mapping.md_func(); + } + } + + return nullptr; +} + const EVP_MD *EVP_get_digestbyobj(const ASN1_OBJECT *obj) { int nid = obj->nid; if (nid == NID_undef) { @@ -166,8 +172,9 @@ const EVP_MD *EVP_parse_digest_algorithm(CBS *cbs) { return EVP_get_digestbynid(nid); } -static int marshal_digest_algorithm(CBB *cbb, const EVP_MD *md, - bool with_null) { +namespace { + +int marshal_digest_algorithm(CBB *cbb, const EVP_MD *md, bool with_null) { CBB algorithm, oid, null; if (!CBB_add_asn1(cbb, &algorithm, CBS_ASN1_SEQUENCE) || !CBB_add_asn1(&algorithm, &oid, CBS_ASN1_OBJECT)) { @@ -199,6 +206,8 @@ static int marshal_digest_algorithm(CBB *cbb, const EVP_MD *md, return 1; } +} // namespace + int EVP_marshal_digest_algorithm(CBB *cbb, const EVP_MD *md) { return marshal_digest_algorithm(cbb, md, /*with_null=*/true); } @@ -247,115 +256,132 @@ int EVP_Q_digest(OSSL_LIB_CTX *libctx, const char *name, const char *propq, return 1; } -static void blake2b256_init(EVP_MD_CTX *ctx) { +namespace { + +void blake2b256_init(EVP_MD_CTX *ctx) { BLAKE2B256_Init(reinterpret_cast(ctx->md_data)); } -static void blake2b256_update(EVP_MD_CTX *ctx, const void *data, size_t len) { +void blake2b256_update(EVP_MD_CTX *ctx, const void *data, size_t len) { BLAKE2B256_Update(reinterpret_cast(ctx->md_data), data, len); } -static void blake2b256_final(EVP_MD_CTX *ctx, uint8_t *md) { +void blake2b256_final(EVP_MD_CTX *ctx, uint8_t *md) { BLAKE2B256_Final(md, reinterpret_cast(ctx->md_data)); } -static const EVP_MD evp_md_blake2b256 = { - NID_undef, BLAKE2B256_DIGEST_LENGTH, 0, - blake2b256_init, blake2b256_update, blake2b256_final, - BLAKE2B_CBLOCK, sizeof(BLAKE2B_CTX), +const EVP_MD evp_md_blake2b256 = { + /*type=*/NID_undef, + /*md_size=*/BLAKE2B256_DIGEST_LENGTH, + /*flags=*/0, + /*init=*/blake2b256_init, + /*update=*/blake2b256_update, + /*final=*/blake2b256_final, + /*squeeze=*/nullptr, + /*block_size=*/BLAKE2B_CBLOCK, + /*ctx_size=*/sizeof(BLAKE2B_CTX), }; -const EVP_MD *EVP_blake2b256() { return &evp_md_blake2b256; } - -static_assert(sizeof(BLAKE2B_CTX) <= EVP_MAX_MD_DATA_SIZE); - - -static void md4_init(EVP_MD_CTX *ctx) { +void md4_init(EVP_MD_CTX *ctx) { BSSL_CHECK(MD4_Init(reinterpret_cast(ctx->md_data))); } -static void md4_update(EVP_MD_CTX *ctx, const void *data, size_t count) { +void md4_update(EVP_MD_CTX *ctx, const void *data, size_t count) { BSSL_CHECK( MD4_Update(reinterpret_cast(ctx->md_data), data, count)); } -static void md4_final(EVP_MD_CTX *ctx, uint8_t *out) { +void md4_final(EVP_MD_CTX *ctx, uint8_t *out) { BSSL_CHECK(MD4_Final(out, reinterpret_cast(ctx->md_data))); } -static const EVP_MD evp_md_md4 = { - NID_md4, // - MD4_DIGEST_LENGTH, // - 0, - md4_init, - md4_update, - md4_final, - 64, - sizeof(MD4_CTX), +const EVP_MD evp_md_md4 = { + /*type=*/NID_md4, + /*md_size=*/MD4_DIGEST_LENGTH, + /*flags=*/0, + /*init=*/md4_init, + /*update=*/md4_update, + /*final=*/md4_final, + /*squeeze=*/nullptr, + /*block_size=*/64, + /*ctx_size=*/sizeof(MD4_CTX), }; -const EVP_MD *EVP_md4() { return &evp_md_md4; } - -static_assert(sizeof(MD4_CTX) <= EVP_MAX_MD_DATA_SIZE); - - -static void md5_init(EVP_MD_CTX *ctx) { +void md5_init(EVP_MD_CTX *ctx) { BSSL_CHECK(MD5_Init(reinterpret_cast(ctx->md_data))); } -static void md5_update(EVP_MD_CTX *ctx, const void *data, size_t count) { +void md5_update(EVP_MD_CTX *ctx, const void *data, size_t count) { BSSL_CHECK( MD5_Update(reinterpret_cast(ctx->md_data), data, count)); } -static void md5_final(EVP_MD_CTX *ctx, uint8_t *out) { +void md5_final(EVP_MD_CTX *ctx, uint8_t *out) { BSSL_CHECK(MD5_Final(out, reinterpret_cast(ctx->md_data))); } -static const EVP_MD evp_md_md5 = { - NID_md5, MD5_DIGEST_LENGTH, 0, md5_init, - md5_update, md5_final, 64, sizeof(MD5_CTX), +const EVP_MD evp_md_md5 = { + /*type=*/NID_md5, + /*md_size=*/MD5_DIGEST_LENGTH, + /*flags=*/0, + /*init=*/md5_init, + /*update=*/md5_update, + /*final=*/md5_final, + /*squeeze=*/nullptr, + /*block_size=*/64, + /*ctx_size=*/sizeof(MD5_CTX), }; -const EVP_MD *EVP_md5() { return &evp_md_md5; } - -static_assert(sizeof(MD5_CTX) <= EVP_MAX_MD_DATA_SIZE); - - -typedef struct { +struct MD5_SHA1_CTX { MD5_CTX md5; SHA_CTX sha1; -} MD5_SHA1_CTX; +}; -static void md5_sha1_init(EVP_MD_CTX *md_ctx) { +void md5_sha1_init(EVP_MD_CTX *md_ctx) { MD5_SHA1_CTX *ctx = reinterpret_cast(md_ctx->md_data); BSSL_CHECK(MD5_Init(&ctx->md5) && SHA1_Init(&ctx->sha1)); } -static void md5_sha1_update(EVP_MD_CTX *md_ctx, const void *data, - size_t count) { +void md5_sha1_update(EVP_MD_CTX *md_ctx, const void *data, size_t count) { MD5_SHA1_CTX *ctx = reinterpret_cast(md_ctx->md_data); BSSL_CHECK(MD5_Update(&ctx->md5, data, count) && SHA1_Update(&ctx->sha1, data, count)); } -static void md5_sha1_final(EVP_MD_CTX *md_ctx, uint8_t *out) { +void md5_sha1_final(EVP_MD_CTX *md_ctx, uint8_t *out) { MD5_SHA1_CTX *ctx = reinterpret_cast(md_ctx->md_data); BSSL_CHECK(MD5_Final(out, &ctx->md5) && SHA1_Final(out + MD5_DIGEST_LENGTH, &ctx->sha1)); } const EVP_MD evp_md_md5_sha1 = { - NID_md5_sha1, - MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, - 0, - md5_sha1_init, - md5_sha1_update, - md5_sha1_final, - 64, - sizeof(MD5_SHA1_CTX), + /*type=*/NID_md5_sha1, + /*md_size=*/MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, + /*flags=*/0, + /*init=*/md5_sha1_init, + /*update=*/md5_sha1_update, + /*final=*/md5_sha1_final, + /*squeeze=*/nullptr, + /*block_size=*/64, + /*ctx_size=*/sizeof(MD5_SHA1_CTX), }; +} // namespace + +const EVP_MD *EVP_blake2b256() { return &evp_md_blake2b256; } + +static_assert(sizeof(BLAKE2B_CTX) <= EVP_MAX_MD_DATA_SIZE); + +const EVP_MD *EVP_md4() { return &evp_md_md4; } + +static_assert(sizeof(MD4_CTX) <= EVP_MAX_MD_DATA_SIZE); + + +const EVP_MD *EVP_md5() { return &evp_md_md5; } + +static_assert(sizeof(MD5_CTX) <= EVP_MAX_MD_DATA_SIZE); + + const EVP_MD *EVP_md5_sha1() { return &evp_md_md5_sha1; } static_assert(sizeof(MD5_SHA1_CTX) <= EVP_MAX_MD_DATA_SIZE); diff --git a/third_party/boringssl/src/crypto/digest/p_keccak.cc b/third_party/boringssl/src/crypto/digest/p_keccak.cc new file mode 100644 index 0000000..ed8f5a4 --- /dev/null +++ b/third_party/boringssl/src/crypto/digest/p_keccak.cc @@ -0,0 +1,147 @@ +// Copyright 2026 The BoringSSL Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +#include + +#include + +#include "../fipsmodule/digest/internal.h" // IWYU pragma: keep +#include "../fipsmodule/keccak/internal.h" + + +BSSL_NAMESPACE_BEGIN +namespace { +template +void keccak_init(EVP_MD_CTX *ctx) { + BORINGSSL_keccak_init(reinterpret_cast(ctx->md_data), + Config); +} + +void keccak_update(EVP_MD_CTX *ctx, const void *data, size_t count) { + BORINGSSL_keccak_absorb(reinterpret_cast(ctx->md_data), + static_cast(data), count); +} + +template +void keccak_final(EVP_MD_CTX *ctx, uint8_t *out) { + BORINGSSL_keccak_squeeze( + reinterpret_cast(ctx->md_data), + static_cast(out), Size); +} + +void keccak_squeeze(EVP_MD_CTX *ctx, uint8_t *out, size_t len) { + BORINGSSL_keccak_squeeze( + reinterpret_cast(ctx->md_data), + static_cast(out), len); +} + +constexpr EVP_MD evp_md_sha3_256 = { + /*type=*/NID_undef, + /*md_size=*/SHA3_256_DIGEST_LENGTH, + /*flags=*/0, + /*init=*/keccak_init, + /*update=*/keccak_update, + /*final=*/keccak_final, + /*squeeze=*/nullptr, + /*block_size=*/SHA3_256_CBLOCK, + /*ctx_size=*/sizeof(BORINGSSL_keccak_st), +}; + +constexpr EVP_MD evp_md_sha3_384 = { + /*type=*/NID_undef, + /*md_size=*/SHA3_384_DIGEST_LENGTH, + /*flags=*/0, + /*init=*/keccak_init, + /*update=*/keccak_update, + /*final=*/keccak_final, + /*squeeze=*/nullptr, + /*block_size=*/SHA3_384_CBLOCK, + /*ctx_size=*/sizeof(BORINGSSL_keccak_st), +}; + +constexpr EVP_MD evp_md_sha3_512 = { + /*type=*/NID_undef, + /*md_size=*/SHA3_512_DIGEST_LENGTH, + /*flags=*/0, + /*init=*/keccak_init, + /*update=*/keccak_update, + /*final=*/keccak_final, + /*squeeze=*/nullptr, + /*block_size=*/SHA3_512_CBLOCK, + /*ctx_size=*/sizeof(BORINGSSL_keccak_st), +}; + +constexpr EVP_MD evp_md_shake128 = { + /*type=*/NID_undef, + /*md_size=*/16, + /*flags=*/0, + /*init=*/keccak_init, + /*update=*/keccak_update, + /*final=*/keccak_final<16>, + /*squeeze=*/keccak_squeeze, + /*block_size=*/SHAKE128_CBLOCK, + /*ctx_size=*/sizeof(BORINGSSL_keccak_st), +}; + +constexpr EVP_MD evp_md_shake256 = { + /*type=*/NID_undef, + /*md_size=*/32, + /*flags=*/0, + /*init=*/keccak_init, + /*update=*/keccak_update, + /*final=*/keccak_final<32>, + /*squeeze=*/keccak_squeeze, + /*block_size=*/SHAKE256_CBLOCK, + /*ctx_size=*/sizeof(BORINGSSL_keccak_st), +}; + +constexpr EVP_MD evp_md_turboshake128 = { + /*type=*/NID_undef, + /*md_size=*/16, + /*flags=*/0, + /*init=*/keccak_init, + /*update=*/keccak_update, + /*final=*/keccak_final<16>, + /*squeeze=*/keccak_squeeze, + /*block_size=*/SHAKE128_CBLOCK, + /*ctx_size=*/sizeof(BORINGSSL_keccak_st), +}; + +constexpr EVP_MD evp_md_turboshake256 = { + /*type=*/NID_undef, + /*md_size=*/32, + /*flags=*/0, + /*init=*/keccak_init, + /*update=*/keccak_update, + /*final=*/keccak_final<32>, + /*squeeze=*/keccak_squeeze, + /*block_size=*/SHAKE256_CBLOCK, + /*ctx_size=*/sizeof(BORINGSSL_keccak_st), +}; + +static_assert(sizeof(BORINGSSL_keccak_st) <= EVP_MAX_MD_DATA_SIZE); +static_assert(SHA3_256_CBLOCK <= EVP_MAX_MD_BLOCK_SIZE); +static_assert(SHAKE128_CBLOCK <= EVP_MAX_MD_BLOCK_SIZE); +static_assert(SHAKE256_CBLOCK <= EVP_MAX_MD_BLOCK_SIZE); +} // namespace +BSSL_NAMESPACE_END + +const EVP_MD *EVP_sha3_256() { return &bssl::evp_md_sha3_256; } +const EVP_MD *EVP_sha3_384() { return &bssl::evp_md_sha3_384; } +const EVP_MD *EVP_sha3_512() { return &bssl::evp_md_sha3_512; } +const EVP_MD *EVP_shake128() { return &bssl::evp_md_shake128; } +const EVP_MD *EVP_shake256() { return &bssl::evp_md_shake256; } +const EVP_MD *EVP_turboshake128() { return &bssl::evp_md_turboshake128; } +const EVP_MD *EVP_turboshake256() { return &bssl::evp_md_turboshake256; } diff --git a/third_party/boringssl/src/crypto/dsa/dsa.cc b/third_party/boringssl/src/crypto/dsa/dsa.cc index 5592fa6..9bb2df1 100644 --- a/third_party/boringssl/src/crypto/dsa/dsa.cc +++ b/third_party/boringssl/src/crypto/dsa/dsa.cc @@ -72,6 +72,13 @@ int DSA_up_ref(DSA *dsa) { return 1; } +DSA *DSA_dup_ref(const DSA *dsa) { + if (dsa == nullptr) { + return nullptr; + } + return FromOpaque(dsa)->DupRefInternal(); +} + unsigned DSA_bits(const DSA *dsa) { return BN_num_bits(FromOpaque(dsa)->p.get()); } @@ -845,7 +852,8 @@ static int dsa_sign_setup(const DSAImpl *dsa, BN_CTX *ctx, BIGNUM **out_kinv, if (!BN_mod(r, r, dsa->q.get(), ctx) || // Compute part of 's = inv(k) (m + xr) mod q' using Fermat's Little // Theorem. - !bn_mod_inverse_prime(kinv, &k, dsa->q.get(), ctx, dsa->method_mont_q.get())) { + !bn_mod_inverse_prime(kinv, &k, dsa->q.get(), ctx, + dsa->method_mont_q.get())) { OPENSSL_PUT_ERROR(DSA, ERR_R_BN_LIB); goto err; } diff --git a/third_party/boringssl/src/crypto/evp/evp.cc b/third_party/boringssl/src/crypto/evp/evp.cc index f99ee15..f52a967 100644 --- a/third_party/boringssl/src/crypto/evp/evp.cc +++ b/third_party/boringssl/src/crypto/evp/evp.cc @@ -63,10 +63,7 @@ EVP_PKEY *EVP_PKEY_dup_ref(const EVP_PKEY *pkey) { if (pkey == nullptr) { return nullptr; } - auto pkey_ref = const_cast(pkey); - // We know that this call always returns one. - EVP_PKEY_up_ref(pkey_ref); - return pkey_ref; + return FromOpaque(pkey)->DupRefInternal(); } int EVP_PKEY_is_opaque(const EVP_PKEY *pkey) { diff --git a/third_party/boringssl/src/crypto/evp/evp_asn1.cc b/third_party/boringssl/src/crypto/evp/evp_asn1.cc index a0b8c32..31a8775 100644 --- a/third_party/boringssl/src/crypto/evp/evp_asn1.cc +++ b/third_party/boringssl/src/crypto/evp/evp_asn1.cc @@ -380,8 +380,7 @@ int i2d_RSA_PUBKEY(const RSA *rsa, uint8_t **outp) { } UniquePtr pkey(EVP_PKEY_new()); - if (pkey == nullptr || - !EVP_PKEY_set1_RSA(pkey.get(), const_cast(rsa))) { + if (pkey == nullptr || !EVP_PKEY_set1_RSA(pkey.get(), rsa)) { return -1; } @@ -404,8 +403,7 @@ int i2d_DSA_PUBKEY(const DSA *dsa, uint8_t **outp) { } UniquePtr pkey(EVP_PKEY_new()); - if (pkey == nullptr || - !EVP_PKEY_set1_DSA(pkey.get(), const_cast(dsa))) { + if (pkey == nullptr || !EVP_PKEY_set1_DSA(pkey.get(), dsa)) { return -1; } @@ -430,8 +428,7 @@ int i2d_EC_PUBKEY(const EC_KEY *ec_key, uint8_t **outp) { } UniquePtr pkey(EVP_PKEY_new()); - if (pkey == nullptr || - !EVP_PKEY_set1_EC_KEY(pkey.get(), const_cast(ec_key))) { + if (pkey == nullptr || !EVP_PKEY_set1_EC_KEY(pkey.get(), ec_key)) { return -1; } diff --git a/third_party/boringssl/src/crypto/evp/evp_ctx.cc b/third_party/boringssl/src/crypto/evp/evp_ctx.cc index a0d7810..9fb4912 100644 --- a/third_party/boringssl/src/crypto/evp/evp_ctx.cc +++ b/third_party/boringssl/src/crypto/evp/evp_ctx.cc @@ -30,7 +30,8 @@ using namespace bssl; static UniquePtr evp_pkey_ctx_new( - EvpPkey *pkey, const EVP_PKEY_ALG *alg, const EVP_PKEY_CTX_METHOD *pmeth) { + const EvpPkey *pkey, const EVP_PKEY_ALG *alg, + const EVP_PKEY_CTX_METHOD *pmeth) { assert(pkey != nullptr || alg != nullptr); UniquePtr ret = MakeUnique(); if (!ret) { @@ -49,7 +50,7 @@ static UniquePtr evp_pkey_ctx_new( return ret; } -EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e) { +EVP_PKEY_CTX *EVP_PKEY_CTX_new(const EVP_PKEY *pkey, ENGINE *e) { auto *pkey_impl = FromOpaque(pkey); if (pkey_impl == nullptr || pkey_impl->ameth == nullptr) { OPENSSL_PUT_ERROR(EVP, ERR_R_PASSED_NULL_PARAMETER); @@ -106,6 +107,15 @@ EVP_PKEY_CTX *EVP_PKEY_CTX_new_id(int id, ENGINE *e) { case EVP_PKEY_ML_KEM_1024: alg = EVP_pkey_ml_kem_1024(); break; + case EVP_PKEY_SLH_DSA_SHA2_128S: + alg = EVP_pkey_slh_dsa_sha2_128s(); + break; + case EVP_PKEY_SLH_DSA_SHA2_128S_WITH_SHA256: + alg = EVP_pkey_slh_dsa_sha2_128s_with_sha256(); + break; + case EVP_PKEY_SLH_DSA_SHAKE_256F: + alg = EVP_pkey_slh_dsa_shake_256f(); + break; } if (alg == nullptr || alg->pkey_method == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); @@ -151,7 +161,7 @@ EVP_PKEY_CTX *EVP_PKEY_CTX_dup(EVP_PKEY_CTX *ctx) { return ret.release(); } -EVP_PKEY *EVP_PKEY_CTX_get0_pkey(EVP_PKEY_CTX *ctx) { +EVP_PKEY *EVP_PKEY_CTX_get0_pkey(const EVP_PKEY_CTX *ctx) { auto *impl = FromOpaque(ctx); return impl->pkey.get(); } @@ -315,7 +325,7 @@ int EVP_PKEY_derive_init(EVP_PKEY_CTX *ctx) { return 1; } -int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer) { +int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, const EVP_PKEY *peer) { auto *impl = FromOpaque(ctx); if (!impl || !impl->pmeth || !(impl->pmeth->derive || impl->pmeth->encrypt || impl->pmeth->decrypt) || @@ -330,7 +340,8 @@ int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer) { return 0; } - int ret = impl->pmeth->ctrl(impl, EVP_PKEY_CTRL_PEER_KEY, 0, peer); + int ret = impl->pmeth->ctrl(impl, EVP_PKEY_CTRL_PEER_KEY, 0, + const_cast(peer)); if (ret <= 0) { return 0; @@ -357,7 +368,7 @@ int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer) { } impl->peerkey = UpRef(FromOpaque(peer)); - ret = impl->pmeth->ctrl(impl, EVP_PKEY_CTRL_PEER_KEY, 1, peer); + ret = impl->pmeth->ctrl(impl, EVP_PKEY_CTRL_PEER_KEY, 1, impl->peerkey.get()); if (ret <= 0) { impl->peerkey = nullptr; return 0; diff --git a/third_party/boringssl/src/crypto/evp/evp_kem.cc b/third_party/boringssl/src/crypto/evp/evp_kem.cc index e07ea3e..e718caf 100644 --- a/third_party/boringssl/src/crypto/evp/evp_kem.cc +++ b/third_party/boringssl/src/crypto/evp/evp_kem.cc @@ -36,7 +36,8 @@ static bool check_kem_invocation(const EVP_KEM *kem, OPENSSL_PUT_ERROR(EVP, ERR_R_PASSED_NULL_PARAMETER); return false; } - if (kem->pkey_id != EVP_PKEY_id(pkey_impl)) { + if (kem->pkey_id != EVP_PKEY_id(pkey_impl) || + (kem->check_key != nullptr && !kem->check_key(kem, pkey_impl))) { OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); return false; } @@ -68,7 +69,7 @@ int EVP_KEM_encap(const EVP_KEM *kem, uint8_t *out_ciphertext, if (!check_kem_invocation(kem, &ciphertext_len, secret_len, pkey_impl)) { return 0; } - return kem->encap(Span(out_ciphertext, ciphertext_len), + return kem->encap(kem, Span(out_ciphertext, ciphertext_len), Span(out_secret, secret_len), pkey_impl); } @@ -84,7 +85,7 @@ int EVP_KEM_encap_external_entropy_for_testing( OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_ENTROPY_LENGTH); return 0; } - return kem->encap_external_entropy(Span(out_ciphertext, ciphertext_len), + return kem->encap_external_entropy(kem, Span(out_ciphertext, ciphertext_len), Span(out_secret, secret_len), pkey_impl, Span(entropy, entropy_len)); } @@ -96,6 +97,6 @@ int EVP_KEM_decap(const EVP_KEM *kem, uint8_t *out_secret, size_t secret_len, if (!check_kem_invocation(kem, nullptr, secret_len, pkey_impl)) { return 0; } - return kem->decap(Span(out_secret, secret_len), + return kem->decap(kem, Span(out_secret, secret_len), Span(ciphertext, ciphertext_len), pkey_impl); } diff --git a/third_party/boringssl/src/crypto/evp/internal.h b/third_party/boringssl/src/crypto/evp/internal.h index 2c83190..d4e57dc 100644 --- a/third_party/boringssl/src/crypto/evp/internal.h +++ b/third_party/boringssl/src/crypto/evp/internal.h @@ -317,13 +317,18 @@ struct evp_kem_st { // Fixed length of external entropy for testing. size_t entropy_len; - int (*encap)(bssl::Span out_ciphertext, + // check_key, if non-null, returns whether `key`, whose type matches + // `pkey_id`, is usable with this KEM. + bool (*check_key)(const EVP_KEM *kem, const EVP_PKEY *key); + + int (*encap)(const EVP_KEM *kem, bssl::Span out_ciphertext, bssl::Span out_secret, const EVP_PKEY *peer_key); - int (*encap_external_entropy)(bssl::Span out_ciphertext, + int (*encap_external_entropy)(const EVP_KEM *kem, + bssl::Span out_ciphertext, bssl::Span out_secret, const EVP_PKEY *peer_key, bssl::Span entropy); - int (*decap)(bssl::Span out_secret, + int (*decap)(const EVP_KEM *kem, bssl::Span out_secret, bssl::Span ciphertext, const EVP_PKEY *key); } /* EVP_KEM */; @@ -353,7 +358,7 @@ struct KemAdapter { OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); return 0; } - if (KEM.encap(Span(out_ciphertext, KEM.ciphertext_len), + if (KEM.encap(&KEM, Span(out_ciphertext, KEM.ciphertext_len), Span(out_secret, KEM.secret_len), ctx->pkey.get())) { *out_ciphertext_len = KEM.ciphertext_len; *out_secret_len = KEM.secret_len; @@ -373,7 +378,7 @@ struct KemAdapter { OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); return 0; } - if (KEM.decap(Span(out_secret, KEM.secret_len), + if (KEM.decap(&KEM, Span(out_secret, KEM.secret_len), Span(ciphertext, ciphertext_len), ctx->pkey.get())) { *out_secret_len = KEM.secret_len; return 1; diff --git a/third_party/boringssl/src/crypto/evp/p_dh.cc b/third_party/boringssl/src/crypto/evp/p_dh.cc index c3d8f7f..aa1db9f 100644 --- a/third_party/boringssl/src/crypto/evp/p_dh.cc +++ b/third_party/boringssl/src/crypto/evp/p_dh.cc @@ -34,25 +34,25 @@ namespace { extern const EVP_PKEY_CTX_METHOD dh_pkey_meth; -static void dh_free(EvpPkey *pkey) { +void dh_free(EvpPkey *pkey) { DH_free(reinterpret_cast(pkey->pkey)); pkey->pkey = nullptr; } -static int dh_size(const EvpPkey *pkey) { +int dh_size(const EvpPkey *pkey) { return DH_size(reinterpret_cast(pkey->pkey)); } -static int dh_bits(const EvpPkey *pkey) { +int dh_bits(const EvpPkey *pkey) { return DH_bits(reinterpret_cast(pkey->pkey)); } -static int dh_param_missing(const EvpPkey *pkey) { +int dh_param_missing(const EvpPkey *pkey) { const DH *dh = reinterpret_cast(pkey->pkey); return dh == nullptr || DH_get0_p(dh) == nullptr || DH_get0_g(dh) == nullptr; } -static int dh_param_copy(EvpPkey *to, const EvpPkey *from) { +int dh_param_copy(EvpPkey *to, const EvpPkey *from) { if (dh_param_missing(from)) { OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PARAMETERS); return 0; @@ -81,7 +81,7 @@ static int dh_param_copy(EvpPkey *to, const EvpPkey *from) { return 1; } -static bool dh_param_equal(const EvpPkey *a, const EvpPkey *b) { +bool dh_param_equal(const EvpPkey *a, const EvpPkey *b) { if (dh_param_missing(a) || dh_param_missing(b)) { return false; } @@ -94,7 +94,7 @@ static bool dh_param_equal(const EvpPkey *a, const EvpPkey *b) { BN_cmp(DH_get0_g(a_dh), DH_get0_g(b_dh)) == 0; } -static bool dh_pub_equal(const EvpPkey *a, const EvpPkey *b) { +bool dh_pub_equal(const EvpPkey *a, const EvpPkey *b) { if (!dh_param_equal(a, b)) { return false; } @@ -104,12 +104,12 @@ static bool dh_pub_equal(const EvpPkey *a, const EvpPkey *b) { return BN_cmp(DH_get0_pub_key(a_dh), DH_get0_pub_key(b_dh)) == 0; } -static bool dh_has_pub(const EvpPkey *pk) { +bool dh_has_pub(const EvpPkey *pk) { const DH *pk_dh = reinterpret_cast(pk->pkey); return DH_get0_pub_key(pk_dh) != nullptr; } -static bool dh_pub_copy(EvpPkey *out, const EvpPkey *pk) { +bool dh_pub_copy(EvpPkey *out, const EvpPkey *pk) { const DH *pk_dh = reinterpret_cast(pk->pkey); const BIGNUM *public_key = DH_get0_pub_key(pk_dh); if (public_key == nullptr) { @@ -128,12 +128,12 @@ static bool dh_pub_copy(EvpPkey *out, const EvpPkey *pk) { return true; } -static bool dh_has_priv(const EvpPkey *pk) { +bool dh_has_priv(const EvpPkey *pk) { const DH *pk_dh = reinterpret_cast(pk->pkey); return DH_get0_priv_key(pk_dh) != nullptr; } -static const EVP_PKEY_ASN1_METHOD dh_asn1_meth = { +const EVP_PKEY_ASN1_METHOD dh_asn1_meth = { /*pkey_id=*/EVP_PKEY_DH, /*oid=*/{0}, /*oid_len=*/0, @@ -167,7 +167,7 @@ struct DH_PKEY_CTX { bool pad = false; }; -static int pkey_dh_init(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *) { +int pkey_dh_init(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *) { DH_PKEY_CTX *dctx = New(); if (dctx == nullptr) { return 0; @@ -177,7 +177,7 @@ static int pkey_dh_init(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *) { return 1; } -static int pkey_dh_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { +int pkey_dh_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { if (!pkey_dh_init(dst, nullptr)) { return 0; } @@ -188,11 +188,11 @@ static int pkey_dh_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { return 1; } -static void pkey_dh_cleanup(EvpPkeyCtx *ctx) { +void pkey_dh_cleanup(EvpPkeyCtx *ctx) { Delete(reinterpret_cast(ctx->data)); } -static int pkey_dh_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { +int pkey_dh_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { DH *dh = DH_new(); if (dh == nullptr || !EVP_PKEY_assign_DH(pkey, dh)) { DH_free(dh); @@ -207,7 +207,7 @@ static int pkey_dh_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { return DH_generate_key(dh); } -static int pkey_dh_derive(EvpPkeyCtx *ctx, uint8_t *out, size_t *out_len) { +int pkey_dh_derive(EvpPkeyCtx *ctx, uint8_t *out, size_t *out_len) { DH_PKEY_CTX *dctx = reinterpret_cast(ctx->data); if (ctx->pkey == nullptr || ctx->peerkey == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_KEYS_NOT_SET); @@ -248,7 +248,7 @@ static int pkey_dh_derive(EvpPkeyCtx *ctx, uint8_t *out, size_t *out_len) { return 1; } -static int pkey_dh_ctrl(EvpPkeyCtx *ctx, int type, int p1, void *p2) { +int pkey_dh_ctrl(EvpPkeyCtx *ctx, int type, int p1, void *p2) { DH_PKEY_CTX *dctx = reinterpret_cast(ctx->data); switch (type) { case EVP_PKEY_CTRL_PEER_KEY: @@ -288,12 +288,8 @@ const EVP_PKEY_CTX_METHOD dh_pkey_meth = { } // namespace -int EVP_PKEY_set1_DH(EVP_PKEY *pkey, DH *key) { - if (EVP_PKEY_assign_DH(pkey, key)) { - DH_up_ref(key); - return 1; - } - return 0; +int EVP_PKEY_set1_DH(EVP_PKEY *pkey, const DH *key) { + return EVP_PKEY_assign_DH(pkey, DH_dup_ref(key)); } int EVP_PKEY_assign_DH(EVP_PKEY *pkey, DH *key) { diff --git a/third_party/boringssl/src/crypto/evp/p_dsa.cc b/third_party/boringssl/src/crypto/evp/p_dsa.cc index df02f1f..f8ffde4 100644 --- a/third_party/boringssl/src/crypto/evp/p_dsa.cc +++ b/third_party/boringssl/src/crypto/evp/p_dsa.cc @@ -31,9 +31,9 @@ namespace { extern const EVP_PKEY_ASN1_METHOD dsa_asn1_meth; -static bssl::evp_decode_result_t dsa_pub_decode(const EVP_PKEY_ALG *alg, - EvpPkey *out, CBS *params, - CBS *key) { +bssl::evp_decode_result_t dsa_pub_decode(const EVP_PKEY_ALG *alg, + EvpPkey *out, CBS *params, + CBS *key) { // See RFC 3279, section 2.3.2. // Decode parameters. RFC 3279 permits DSA parameters to be omitted, in which @@ -59,7 +59,7 @@ static bssl::evp_decode_result_t dsa_pub_decode(const EVP_PKEY_ALG *alg, return evp_decode_ok; } -static int dsa_pub_encode(CBB *out, const EvpPkey *key) { +int dsa_pub_encode(CBB *out, const EvpPkey *key) { const DSAImpl *dsa = reinterpret_cast(key->pkey); const int has_params = dsa->p != nullptr && dsa->q != nullptr && dsa->g != nullptr; @@ -81,9 +81,9 @@ static int dsa_pub_encode(CBB *out, const EvpPkey *key) { return 1; } -static bssl::evp_decode_result_t dsa_priv_decode(const EVP_PKEY_ALG *alg, - EvpPkey *out, CBS *params, - CBS *key) { +bssl::evp_decode_result_t dsa_priv_decode(const EVP_PKEY_ALG *alg, + EvpPkey *out, CBS *params, + CBS *key) { // See PKCS#11, v2.40, section 2.5. // Decode parameters. @@ -124,7 +124,7 @@ static bssl::evp_decode_result_t dsa_priv_decode(const EVP_PKEY_ALG *alg, return evp_decode_ok; } -static int dsa_priv_encode(CBB *out, const EvpPkey *key) { +int dsa_priv_encode(CBB *out, const EvpPkey *key) { const DSAImpl *dsa = reinterpret_cast(key->pkey); if (dsa == nullptr || dsa->priv_key == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PARAMETERS); @@ -148,17 +148,17 @@ static int dsa_priv_encode(CBB *out, const EvpPkey *key) { return 1; } -static int int_dsa_size(const EvpPkey *pkey) { +int int_dsa_size(const EvpPkey *pkey) { const DSAImpl *dsa = reinterpret_cast(pkey->pkey); return DSA_size(dsa); } -static int dsa_bits(const EvpPkey *pkey) { +int dsa_bits(const EvpPkey *pkey) { const DSAImpl *dsa = reinterpret_cast(pkey->pkey); return BN_num_bits(DSA_get0_p(dsa)); } -static int dsa_missing_parameters(const EvpPkey *pkey) { +int dsa_missing_parameters(const EvpPkey *pkey) { const DSAImpl *dsa = reinterpret_cast(pkey->pkey); if (DSA_get0_p(dsa) == nullptr || DSA_get0_q(dsa) == nullptr || DSA_get0_g(dsa) == nullptr) { @@ -167,7 +167,7 @@ static int dsa_missing_parameters(const EvpPkey *pkey) { return 0; } -static int dup_bn_into(UniquePtr *out, const BIGNUM *src) { +int dup_bn_into(UniquePtr *out, const BIGNUM *src) { UniquePtr copy(BN_dup(src)); if (copy == nullptr) { return 0; @@ -176,7 +176,7 @@ static int dup_bn_into(UniquePtr *out, const BIGNUM *src) { return 1; } -static int dsa_copy_parameters(EvpPkey *to, const EvpPkey *from) { +int dsa_copy_parameters(EvpPkey *to, const EvpPkey *from) { if (to->pkey == nullptr) { to->pkey = DSA_new(); if (to->pkey == nullptr) { @@ -194,7 +194,7 @@ static int dsa_copy_parameters(EvpPkey *to, const EvpPkey *from) { return 1; } -static bool dsa_equal_parameters(const EvpPkey *a, const EvpPkey *b) { +bool dsa_equal_parameters(const EvpPkey *a, const EvpPkey *b) { const DSAImpl *a_dsa = reinterpret_cast(a->pkey); const DSAImpl *b_dsa = reinterpret_cast(b->pkey); return BN_cmp(DSA_get0_p(a_dsa), DSA_get0_p(b_dsa)) == 0 && @@ -202,18 +202,18 @@ static bool dsa_equal_parameters(const EvpPkey *a, const EvpPkey *b) { BN_cmp(DSA_get0_g(a_dsa), DSA_get0_g(b_dsa)) == 0; } -static bool dsa_pub_equal(const EvpPkey *a, const EvpPkey *b) { +bool dsa_pub_equal(const EvpPkey *a, const EvpPkey *b) { const DSAImpl *a_dsa = reinterpret_cast(a->pkey); const DSAImpl *b_dsa = reinterpret_cast(b->pkey); return BN_cmp(DSA_get0_pub_key(b_dsa), DSA_get0_pub_key(a_dsa)) == 0; } -static bool dsa_pub_present(const EvpPkey *pk) { +bool dsa_pub_present(const EvpPkey *pk) { const DSA *pk_dsa = reinterpret_cast(pk->pkey); return DSA_get0_pub_key(pk_dsa) != nullptr; } -static bool dsa_pub_copy(EvpPkey *out, const EvpPkey *pk) { +bool dsa_pub_copy(EvpPkey *out, const EvpPkey *pk) { const DSA *pk_dsa = reinterpret_cast(pk->pkey); const BIGNUM *public_key = DSA_get0_pub_key(pk_dsa); if (public_key == nullptr) { @@ -232,12 +232,12 @@ static bool dsa_pub_copy(EvpPkey *out, const EvpPkey *pk) { return true; } -static bool dsa_priv_present(const EvpPkey *pk) { +bool dsa_priv_present(const EvpPkey *pk) { const DSA *pk_dsa = reinterpret_cast(pk->pkey); return DSA_get0_priv_key(pk_dsa) != nullptr; } -static void int_dsa_free(EvpPkey *pkey) { +void int_dsa_free(EvpPkey *pkey) { DSA_free(reinterpret_cast(pkey->pkey)); pkey->pkey = nullptr; } @@ -300,12 +300,8 @@ int EVP_PKEY_CTX_set_dsa_paramgen_q_bits(EVP_PKEY_CTX *ctx, int qbits) { return 0; } -int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, DSA *key) { - if (EVP_PKEY_assign_DSA(pkey, key)) { - DSA_up_ref(key); - return 1; - } - return 0; +int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, const DSA *key) { + return EVP_PKEY_assign_DSA(pkey, DSA_dup_ref(key)); } int EVP_PKEY_assign_DSA(EVP_PKEY *pkey, DSA *key) { diff --git a/third_party/boringssl/src/crypto/evp/p_ec.cc b/third_party/boringssl/src/crypto/evp/p_ec.cc index 3e72432..89ce572 100644 --- a/third_party/boringssl/src/crypto/evp/p_ec.cc +++ b/third_party/boringssl/src/crypto/evp/p_ec.cc @@ -47,8 +47,8 @@ struct EVP_PKEY_ALG_EC : public EVP_PKEY_ALG { extern const EVP_PKEY_ASN1_METHOD ec_asn1_meth; extern const EVP_PKEY_CTX_METHOD ec_pkey_meth; -static int eckey_pub_encode(CBB *out, const EvpPkey *key) { - const EC_KEY *ec_key = reinterpret_cast(key->pkey); +int eckey_pub_encode_with_point_conv_form(CBB *out, const EC_KEY *ec_key, + point_conversion_form_t form) { const EC_GROUP *group = EC_KEY_get0_group(ec_key); const EC_POINT *public_key = EC_KEY_get0_public_key(ec_key); @@ -61,8 +61,7 @@ static int eckey_pub_encode(CBB *out, const EvpPkey *key) { !EC_KEY_marshal_curve_name(&algorithm, group) || !CBB_add_asn1(&spki, &key_bitstring, CBS_ASN1_BITSTRING) || !CBB_add_u8(&key_bitstring, 0 /* padding */) || - !EC_POINT_point2cbb(&key_bitstring, group, public_key, - POINT_CONVERSION_UNCOMPRESSED, nullptr) || + !EC_POINT_point2cbb(&key_bitstring, group, public_key, form, nullptr) || !CBB_flush(out)) { OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); return 0; @@ -71,9 +70,15 @@ static int eckey_pub_encode(CBB *out, const EvpPkey *key) { return 1; } -static bssl::evp_decode_result_t eckey_pub_decode(const EVP_PKEY_ALG *alg, - EvpPkey *out, CBS *params, - CBS *key) { +int eckey_pub_encode(CBB *out, const EvpPkey *key) { + const EC_KEY *ec_key = reinterpret_cast(key->pkey); + return eckey_pub_encode_with_point_conv_form(out, ec_key, + POINT_CONVERSION_UNCOMPRESSED); +} + +bssl::evp_decode_result_t eckey_pub_decode(const EVP_PKEY_ALG *alg, + EvpPkey *out, CBS *params, + CBS *key) { const auto *ec_alg = static_cast(alg); if (ec_alg->ec_group == nullptr) { return evp_decode_unsupported; @@ -107,7 +112,7 @@ static bssl::evp_decode_result_t eckey_pub_decode(const EVP_PKEY_ALG *alg, return evp_decode_ok; } -static bool eckey_pub_equal(const EvpPkey *a, const EvpPkey *b) { +bool eckey_pub_equal(const EvpPkey *a, const EvpPkey *b) { const EC_KEY *a_ec = reinterpret_cast(a->pkey); const EC_KEY *b_ec = reinterpret_cast(b->pkey); const EC_GROUP *group = EC_KEY_get0_group(b_ec); @@ -116,9 +121,9 @@ static bool eckey_pub_equal(const EvpPkey *a, const EvpPkey *b) { return EC_POINT_cmp(group, pa, pb, nullptr) == 0; } -static bssl::evp_decode_result_t eckey_priv_decode(const EVP_PKEY_ALG *alg, - EvpPkey *out, CBS *params, - CBS *key) { +bssl::evp_decode_result_t eckey_priv_decode(const EVP_PKEY_ALG *alg, + EvpPkey *out, CBS *params, + CBS *key) { const auto *ec_alg = static_cast(alg); if (ec_alg->ec_group == nullptr) { return evp_decode_unsupported; @@ -149,7 +154,7 @@ static bssl::evp_decode_result_t eckey_priv_decode(const EVP_PKEY_ALG *alg, return evp_decode_ok; } -static int eckey_priv_encode(CBB *out, const EvpPkey *key) { +int eckey_priv_encode(CBB *out, const EvpPkey *key) { const EC_KEY *ec_key = reinterpret_cast(key->pkey); // Omit the redundant copy of the curve name. This contradicts RFC 5915 but @@ -176,8 +181,7 @@ static int eckey_priv_encode(CBB *out, const EvpPkey *key) { return 1; } -static int eckey_set1_tls_encodedpoint(EvpPkey *pkey, const uint8_t *in, - size_t len) { +int eckey_set1_tls_encodedpoint(EvpPkey *pkey, const uint8_t *in, size_t len) { EC_KEY *ec_key = reinterpret_cast(pkey->pkey); if (ec_key == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); @@ -187,8 +191,7 @@ static int eckey_set1_tls_encodedpoint(EvpPkey *pkey, const uint8_t *in, return EC_KEY_oct2key(ec_key, in, len, nullptr); } -static size_t eckey_get1_tls_encodedpoint(const EvpPkey *pkey, - uint8_t **out_ptr) { +size_t eckey_get1_tls_encodedpoint(const EvpPkey *pkey, uint8_t **out_ptr) { const EC_KEY *ec_key = reinterpret_cast(pkey->pkey); if (ec_key == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); @@ -199,12 +202,12 @@ static size_t eckey_get1_tls_encodedpoint(const EvpPkey *pkey, nullptr); } -static int int_ec_size(const EvpPkey *pkey) { +int int_ec_size(const EvpPkey *pkey) { const EC_KEY *ec_key = reinterpret_cast(pkey->pkey); return ECDSA_size(ec_key); } -static int ec_bits(const EvpPkey *pkey) { +int ec_bits(const EvpPkey *pkey) { const EC_KEY *ec_key = reinterpret_cast(pkey->pkey); const EC_GROUP *group = EC_KEY_get0_group(ec_key); if (group == nullptr) { @@ -214,12 +217,12 @@ static int ec_bits(const EvpPkey *pkey) { return EC_GROUP_order_bits(group); } -static int ec_missing_parameters(const EvpPkey *pkey) { +int ec_missing_parameters(const EvpPkey *pkey) { const EC_KEY *ec_key = reinterpret_cast(pkey->pkey); return ec_key == nullptr || EC_KEY_get0_group(ec_key) == nullptr; } -static int ec_copy_parameters(EvpPkey *to, const EvpPkey *from) { +int ec_copy_parameters(EvpPkey *to, const EvpPkey *from) { const EC_KEY *from_key = reinterpret_cast(from->pkey); if (from_key == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); @@ -239,7 +242,7 @@ static int ec_copy_parameters(EvpPkey *to, const EvpPkey *from) { return EC_KEY_set_group(reinterpret_cast(to->pkey), group); } -static bool ec_equal_parameters(const EvpPkey *a, const EvpPkey *b) { +bool ec_equal_parameters(const EvpPkey *a, const EvpPkey *b) { const EC_KEY *a_ec = reinterpret_cast(a->pkey); const EC_KEY *b_ec = reinterpret_cast(b->pkey); if (a_ec == nullptr || b_ec == nullptr) { @@ -254,22 +257,22 @@ static bool ec_equal_parameters(const EvpPkey *a, const EvpPkey *b) { return EC_GROUP_cmp(group_a, group_b, nullptr) == 0; } -static void int_ec_free(EvpPkey *pkey) { +void int_ec_free(EvpPkey *pkey) { EC_KEY_free(reinterpret_cast(pkey->pkey)); pkey->pkey = nullptr; } -static int eckey_opaque(const EvpPkey *pkey) { +int eckey_opaque(const EvpPkey *pkey) { const EC_KEY *ec_key = reinterpret_cast(pkey->pkey); return EC_KEY_is_opaque(ec_key); } -static bool eckey_pub_present(const EvpPkey *pkey) { +bool eckey_pub_present(const EvpPkey *pkey) { const EC_KEY *ec_key = reinterpret_cast(pkey->pkey); return EC_KEY_get0_public_key(ec_key) != nullptr; } -static bool eckey_pub_copy(EvpPkey *out, const EvpPkey *pkey) { +bool eckey_pub_copy(EvpPkey *out, const EvpPkey *pkey) { const EC_KEY *ec_key = reinterpret_cast(pkey->pkey); const EC_POINT *public_key = EC_KEY_get0_public_key(ec_key); if (public_key == nullptr) { @@ -287,7 +290,7 @@ static bool eckey_pub_copy(EvpPkey *out, const EvpPkey *pkey) { return true; } -static bool eckey_priv_present(const EvpPkey *pkey) { +bool eckey_priv_present(const EvpPkey *pkey) { const EC_KEY *ec_key = reinterpret_cast(pkey->pkey); return EC_KEY_get0_private_key(ec_key) != nullptr; } @@ -337,7 +340,7 @@ struct EC_PKEY_CTX { const EC_GROUP *gen_group = nullptr; }; -static int pkey_ec_init(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *alg) { +int pkey_ec_init(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *alg) { EC_PKEY_CTX *dctx = New(); if (!dctx) { return 0; @@ -352,7 +355,7 @@ static int pkey_ec_init(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *alg) { return 1; } -static int pkey_ec_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { +int pkey_ec_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { if (!pkey_ec_init(dst, nullptr)) { return 0; } @@ -364,12 +367,12 @@ static int pkey_ec_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { return 1; } -static void pkey_ec_cleanup(EvpPkeyCtx *ctx) { +void pkey_ec_cleanup(EvpPkeyCtx *ctx) { Delete(reinterpret_cast(ctx->data)); } -static int pkey_ec_sign(EvpPkeyCtx *ctx, uint8_t *sig, size_t *siglen, - const uint8_t *tbs, size_t tbslen) { +int pkey_ec_sign(EvpPkeyCtx *ctx, uint8_t *sig, size_t *siglen, + const uint8_t *tbs, size_t tbslen) { const EC_KEY *ec = reinterpret_cast(ctx->pkey->pkey); if (!sig) { *siglen = ECDSA_size(ec); @@ -387,13 +390,13 @@ static int pkey_ec_sign(EvpPkeyCtx *ctx, uint8_t *sig, size_t *siglen, return 1; } -static int pkey_ec_verify(EvpPkeyCtx *ctx, const uint8_t *sig, size_t siglen, - const uint8_t *tbs, size_t tbslen) { +int pkey_ec_verify(EvpPkeyCtx *ctx, const uint8_t *sig, size_t siglen, + const uint8_t *tbs, size_t tbslen) { const EC_KEY *ec_key = reinterpret_cast(ctx->pkey->pkey); return ECDSA_verify(0, tbs, tbslen, sig, siglen, ec_key); } -static int pkey_ec_derive(EvpPkeyCtx *ctx, uint8_t *key, size_t *keylen) { +int pkey_ec_derive(EvpPkeyCtx *ctx, uint8_t *key, size_t *keylen) { if (!ctx->pkey || !ctx->peerkey) { OPENSSL_PUT_ERROR(EVP, EVP_R_KEYS_NOT_SET); return 0; @@ -421,7 +424,7 @@ static int pkey_ec_derive(EvpPkeyCtx *ctx, uint8_t *key, size_t *keylen) { return 1; } -static int pkey_ec_ctrl(EvpPkeyCtx *ctx, int type, int p1, void *p2) { +int pkey_ec_ctrl(EvpPkeyCtx *ctx, int type, int p1, void *p2) { EC_PKEY_CTX *dctx = reinterpret_cast(ctx->data); switch (type) { @@ -457,7 +460,7 @@ static int pkey_ec_ctrl(EvpPkeyCtx *ctx, int type, int p1, void *p2) { } } -static int pkey_ec_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { +int pkey_ec_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { EC_PKEY_CTX *dctx = reinterpret_cast(ctx->data); const EC_GROUP *group = dctx->gen_group; if (group == nullptr) { @@ -477,7 +480,7 @@ static int pkey_ec_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { return 1; } -static int pkey_ec_paramgen(EvpPkeyCtx *ctx, EvpPkey *pkey) { +int pkey_ec_paramgen(EvpPkeyCtx *ctx, EvpPkey *pkey) { EC_PKEY_CTX *dctx = reinterpret_cast(ctx->data); if (dctx->gen_group == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_NO_PARAMETERS_SET); @@ -543,12 +546,8 @@ const EVP_PKEY_ALG *bssl::evp_pkey_ec_no_curve() { return &kAlg; } -int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, EC_KEY *key) { - if (EVP_PKEY_assign_EC_KEY(pkey, key)) { - EC_KEY_up_ref(key); - return 1; - } - return 0; +int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, const EC_KEY *key) { + return EVP_PKEY_assign_EC_KEY(pkey, EC_KEY_dup_ref(key)); } int EVP_PKEY_assign_EC_KEY(EVP_PKEY *pkey, EC_KEY *key) { @@ -601,8 +600,8 @@ static EVP_PKEY *pkey_from_ec_point(const EC_GROUP *group, const uint8_t *in, return pkey.release(); } -EVP_PKEY *EVP_PKEY_from_ec_uncompressed_point( - const EVP_PKEY_ALG *alg, const uint8_t *in, size_t len) { +EVP_PKEY *EVP_PKEY_from_ec_uncompressed_point(const EVP_PKEY_ALG *alg, + const uint8_t *in, size_t len) { const EC_GROUP *group = alg_to_group(alg); if (group == nullptr) { return nullptr; @@ -652,6 +651,16 @@ int EVP_PKEY_marshal_ec_compressed_point(CBB *cbb, const EVP_PKEY *key) { return marshal_ec_point(cbb, key, POINT_CONVERSION_COMPRESSED); } +int EVP_marshal_public_key_with_ec_point_format( + CBB *cbb, const EVP_PKEY *key, point_conversion_form_t format) { + const EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(key); + if (ec_key == nullptr) { + // Error is set by `EVP_PKEY_get0_EC_KEY` already. + return 0; + } + return eckey_pub_encode_with_point_conv_form(cbb, ec_key, format); +} + EVP_PKEY *EVP_PKEY_from_ec_private_scalar(const EVP_PKEY_ALG *alg, const uint8_t *in, size_t len) { const EC_GROUP *group = alg_to_group(alg); diff --git a/third_party/boringssl/src/crypto/evp/p_ed25519.cc b/third_party/boringssl/src/crypto/evp/p_ed25519.cc index 868c9f0..3cdbc1d 100644 --- a/third_party/boringssl/src/crypto/evp/p_ed25519.cc +++ b/third_party/boringssl/src/crypto/evp/p_ed25519.cc @@ -41,13 +41,13 @@ extern const EVP_PKEY_CTX_METHOD ed25519_pkey_meth; #define ED25519_PUBLIC_KEY_OFFSET 32 -static void ed25519_free(EvpPkey *pkey) { +void ed25519_free(EvpPkey *pkey) { ED25519_KEY *key = reinterpret_cast(pkey->pkey); Delete(key); pkey->pkey = nullptr; } -static int ed25519_set_priv_raw(EvpPkey *pkey, const uint8_t *in, size_t len) { +int ed25519_set_priv_raw(EvpPkey *pkey, const uint8_t *in, size_t len) { if (len != 32) { OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); return 0; @@ -67,7 +67,7 @@ static int ed25519_set_priv_raw(EvpPkey *pkey, const uint8_t *in, size_t len) { return 1; } -static int ed25519_set_pub_raw(EvpPkey *pkey, const uint8_t *in, size_t len) { +int ed25519_set_pub_raw(EvpPkey *pkey, const uint8_t *in, size_t len) { if (len != 32) { OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); return 0; @@ -84,8 +84,8 @@ static int ed25519_set_pub_raw(EvpPkey *pkey, const uint8_t *in, size_t len) { return 1; } -static int ed25519_get_priv_raw(const EvpPkey *pkey, uint8_t *out, - size_t *out_len) { +int ed25519_get_priv_raw(const EvpPkey *pkey, uint8_t *out, + size_t *out_len) { const ED25519_KEY *key = reinterpret_cast(pkey->pkey); if (!key->has_private) { OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); @@ -108,8 +108,8 @@ static int ed25519_get_priv_raw(const EvpPkey *pkey, uint8_t *out, return 1; } -static int ed25519_get_pub_raw(const EvpPkey *pkey, uint8_t *out, - size_t *out_len) { +int ed25519_get_pub_raw(const EvpPkey *pkey, uint8_t *out, + size_t *out_len) { const ED25519_KEY *key = reinterpret_cast(pkey->pkey); if (out == nullptr) { *out_len = 32; @@ -126,9 +126,9 @@ static int ed25519_get_pub_raw(const EvpPkey *pkey, uint8_t *out, return 1; } -static bssl::evp_decode_result_t ed25519_pub_decode(const EVP_PKEY_ALG *alg, - EvpPkey *out, CBS *params, - CBS *key) { +bssl::evp_decode_result_t ed25519_pub_decode(const EVP_PKEY_ALG *alg, + EvpPkey *out, CBS *params, + CBS *key) { // See RFC 8410, section 4. // The parameters must be omitted. Public keys have length 32. @@ -142,7 +142,7 @@ static bssl::evp_decode_result_t ed25519_pub_decode(const EVP_PKEY_ALG *alg, : evp_decode_error; } -static int ed25519_pub_encode(CBB *out, const EvpPkey *pkey) { +int ed25519_pub_encode(CBB *out, const EvpPkey *pkey) { const ED25519_KEY *key = reinterpret_cast(pkey->pkey); // See RFC 8410, section 4. @@ -163,16 +163,16 @@ static int ed25519_pub_encode(CBB *out, const EvpPkey *pkey) { return 1; } -static bool ed25519_pub_equal(const EvpPkey *a, const EvpPkey *b) { +bool ed25519_pub_equal(const EvpPkey *a, const EvpPkey *b) { const ED25519_KEY *a_key = reinterpret_cast(a->pkey); const ED25519_KEY *b_key = reinterpret_cast(b->pkey); return OPENSSL_memcmp(a_key->key + ED25519_PUBLIC_KEY_OFFSET, b_key->key + ED25519_PUBLIC_KEY_OFFSET, 32) == 0; } -static bssl::evp_decode_result_t ed25519_priv_decode(const EVP_PKEY_ALG *alg, - EvpPkey *out, CBS *params, - CBS *key) { +bssl::evp_decode_result_t ed25519_priv_decode(const EVP_PKEY_ALG *alg, + EvpPkey *out, CBS *params, + CBS *key) { // See RFC 8410, section 7. // Parameters must be empty. The key is a 32-byte value wrapped in an extra @@ -189,7 +189,7 @@ static bssl::evp_decode_result_t ed25519_priv_decode(const EVP_PKEY_ALG *alg, : evp_decode_error; } -static int ed25519_priv_encode(CBB *out, const EvpPkey *pkey) { +int ed25519_priv_encode(CBB *out, const EvpPkey *pkey) { const ED25519_KEY *key = reinterpret_cast(pkey->pkey); if (!key->has_private) { OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); @@ -216,9 +216,9 @@ static int ed25519_priv_encode(CBB *out, const EvpPkey *pkey) { return 1; } -static bool ed25519_pub_present(const EvpPkey *) { return true; } +bool ed25519_pub_present(const EvpPkey *) { return true; } -static bool ed25519_pub_copy(EvpPkey *out, const EvpPkey *pkey) { +bool ed25519_pub_copy(EvpPkey *out, const EvpPkey *pkey) { const ED25519_KEY *pkey_ed25519 = reinterpret_cast(pkey->pkey); ED25519_KEY *public_copy = New(); @@ -233,14 +233,14 @@ static bool ed25519_pub_copy(EvpPkey *out, const EvpPkey *pkey) { return true; } -static bool ed25519_priv_present(const EvpPkey *pkey) { +bool ed25519_priv_present(const EvpPkey *pkey) { const ED25519_KEY *key = reinterpret_cast(pkey->pkey); return key->has_private; } -static int ed25519_size(const EvpPkey *pkey) { return 64; } +int ed25519_size(const EvpPkey *pkey) { return 64; } -static int ed25519_bits(const EvpPkey *pkey) { return 253; } +int ed25519_bits(const EvpPkey *pkey) { return 253; } const EVP_PKEY_ASN1_METHOD ed25519_asn1_meth = { EVP_PKEY_ED25519, @@ -273,9 +273,9 @@ const EVP_PKEY_ASN1_METHOD ed25519_asn1_meth = { }; // Ed25519 has no parameters to copy. -static int pkey_ed25519_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { return 1; } +int pkey_ed25519_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { return 1; } -static int pkey_ed25519_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { +int pkey_ed25519_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { ED25519_KEY *key = New(); if (key == nullptr) { return 0; @@ -289,9 +289,9 @@ static int pkey_ed25519_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { return 1; } -static int pkey_ed25519_sign_message(EvpPkeyCtx *ctx, uint8_t *sig, - size_t *siglen, const uint8_t *tbs, - size_t tbslen) { +int pkey_ed25519_sign_message(EvpPkeyCtx *ctx, uint8_t *sig, + size_t *siglen, const uint8_t *tbs, + size_t tbslen) { const ED25519_KEY *key = reinterpret_cast(ctx->pkey->pkey); if (!key->has_private) { @@ -317,9 +317,9 @@ static int pkey_ed25519_sign_message(EvpPkeyCtx *ctx, uint8_t *sig, return 1; } -static int pkey_ed25519_verify_message(EvpPkeyCtx *ctx, const uint8_t *sig, - size_t siglen, const uint8_t *tbs, - size_t tbslen) { +int pkey_ed25519_verify_message(EvpPkeyCtx *ctx, const uint8_t *sig, + size_t siglen, const uint8_t *tbs, + size_t tbslen) { const ED25519_KEY *key = reinterpret_cast(ctx->pkey->pkey); if (siglen != 64 || diff --git a/third_party/boringssl/src/crypto/evp/p_hkdf.cc b/third_party/boringssl/src/crypto/evp/p_hkdf.cc index a45bd6c..3494d5e 100644 --- a/third_party/boringssl/src/crypto/evp/p_hkdf.cc +++ b/third_party/boringssl/src/crypto/evp/p_hkdf.cc @@ -37,12 +37,12 @@ struct HKDF_PKEY_CTX { Vector info; }; -static int pkey_hkdf_init(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *) { +int pkey_hkdf_init(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *) { ctx->data = New(); return 1; } -static int pkey_hkdf_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { +int pkey_hkdf_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { if (!pkey_hkdf_init(dst, nullptr)) { return 0; } @@ -62,11 +62,11 @@ static int pkey_hkdf_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { return 1; } -static void pkey_hkdf_cleanup(EvpPkeyCtx *ctx) { +void pkey_hkdf_cleanup(EvpPkeyCtx *ctx) { Delete(reinterpret_cast(ctx->data)); } -static int pkey_hkdf_derive(EvpPkeyCtx *ctx, uint8_t *out, size_t *out_len) { +int pkey_hkdf_derive(EvpPkeyCtx *ctx, uint8_t *out, size_t *out_len) { HKDF_PKEY_CTX *hctx = reinterpret_cast(ctx->data); if (hctx->md == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PARAMETERS); @@ -110,7 +110,7 @@ static int pkey_hkdf_derive(EvpPkeyCtx *ctx, uint8_t *out, size_t *out_len) { return 0; } -static int pkey_hkdf_ctrl(EvpPkeyCtx *ctx, int type, int p1, void *p2) { +int pkey_hkdf_ctrl(EvpPkeyCtx *ctx, int type, int p1, void *p2) { HKDF_PKEY_CTX *hctx = reinterpret_cast(ctx->data); switch (type) { case EVP_PKEY_CTRL_HKDF_MODE: diff --git a/third_party/boringssl/src/crypto/evp/p_mlkem.cc b/third_party/boringssl/src/crypto/evp/p_mlkem.cc index c62c35e..dd8710c 100644 --- a/third_party/boringssl/src/crypto/evp/p_mlkem.cc +++ b/third_party/boringssl/src/crypto/evp/p_mlkem.cc @@ -356,8 +356,8 @@ struct MLKEMImplementation { return 1; } - static int KemEncap(Span out_ciphertext, Span out_secret, - const EVP_PKEY *peer_key) { + static int KemEncap(const EVP_KEM *kem, Span out_ciphertext, + Span out_secret, const EVP_PKEY *peer_key) { const auto *peer_pubkey = GetKeyData(FromOpaque(peer_key))->GetPublicKey(); if (out_ciphertext.size() != Traits::kCiphertextBytes) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_CIPHERTEXT_LENGTH); @@ -371,7 +371,8 @@ struct MLKEMImplementation { return 1; } - static int KemEncapExternalEntropy(Span out_ciphertext, + static int KemEncapExternalEntropy(const EVP_KEM *kem, + Span out_ciphertext, Span out_secret, const EVP_PKEY *peer_key, Span entropy) { @@ -393,8 +394,8 @@ struct MLKEMImplementation { return 1; } - static int KemDecap(Span out_secret, Span ciphertext, - const EVP_PKEY *key) { + static int KemDecap(const EVP_KEM *kem, Span out_secret, + Span ciphertext, const EVP_PKEY *key) { const auto *priv = GetKeyData(FromOpaque(key))->AsPrivateKeyData(); if (priv == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); @@ -413,6 +414,7 @@ struct MLKEMImplementation { /*ciphertext_len=*/Traits::kCiphertextBytes, /*secret_len=*/MLKEM_SHARED_SECRET_BYTES, /*entropy_len=*/BCM_MLKEM_ENCAP_ENTROPY, + /*check_key=*/nullptr, &KemEncap, &KemEncapExternalEntropy, &KemDecap, diff --git a/third_party/boringssl/src/crypto/evp/p_rsa.cc b/third_party/boringssl/src/crypto/evp/p_rsa.cc index 41470be..9097b7a 100644 --- a/third_party/boringssl/src/crypto/evp/p_rsa.cc +++ b/third_party/boringssl/src/crypto/evp/p_rsa.cc @@ -46,7 +46,7 @@ extern const EVP_PKEY_ASN1_METHOD rsa_pss_asn1_meth; extern const EVP_PKEY_CTX_METHOD rsa_pkey_meth; extern const EVP_PKEY_CTX_METHOD rsa_pss_pkey_meth; -static int rsa_pub_encode(CBB *out, const EvpPkey *key) { +int rsa_pub_encode(CBB *out, const EvpPkey *key) { // See RFC 3279, section 2.3.1. const RSA *rsa = reinterpret_cast(key->pkey); CBB spki, algorithm, null, key_bitstring; @@ -66,9 +66,9 @@ static int rsa_pub_encode(CBB *out, const EvpPkey *key) { return 1; } -static bssl::evp_decode_result_t rsa_pub_decode(const EVP_PKEY_ALG *alg, - EvpPkey *out, CBS *params, - CBS *key) { +bssl::evp_decode_result_t rsa_pub_decode(const EVP_PKEY_ALG *alg, + EvpPkey *out, CBS *params, + CBS *key) { // See RFC 3279, section 2.3.1. // The parameters must be NULL. @@ -89,7 +89,7 @@ static bssl::evp_decode_result_t rsa_pub_decode(const EVP_PKEY_ALG *alg, return evp_decode_ok; } -static bool rsa_pub_equal(const EvpPkey *a, const EvpPkey *b) { +bool rsa_pub_equal(const EvpPkey *a, const EvpPkey *b) { // We currently assume that all `EVP_PKEY_RSA_PSS` keys have the same // parameters, so this vacuously compares parameters. If we ever support // multiple PSS parameter sets, we probably should compare them too. Note, @@ -100,7 +100,7 @@ static bool rsa_pub_equal(const EvpPkey *a, const EvpPkey *b) { BN_cmp(RSA_get0_e(b_rsa), RSA_get0_e(a_rsa)) == 0; } -static bool rsa_pub_present(const EvpPkey *pk) { +bool rsa_pub_present(const EvpPkey *pk) { const RSA *pk_rsa = reinterpret_cast(pk->pkey); // An RSA public key should always have n and e. It's possible for a (private) // key to have n and d, but not e, so we must explicitly check for the @@ -108,7 +108,7 @@ static bool rsa_pub_present(const EvpPkey *pk) { return RSA_get0_n(pk_rsa) != nullptr && RSA_get0_e(pk_rsa) != nullptr; } -static bool rsa_pub_copy(EvpPkey *out, const EvpPkey *pkey) { +bool rsa_pub_copy(EvpPkey *out, const EvpPkey *pkey) { const RSAImpl *pk_rsa = reinterpret_cast(pkey->pkey); const BIGNUM *pk_n = RSA_get0_n(pk_rsa); const BIGNUM *pk_e = RSA_get0_e(pk_rsa); @@ -126,7 +126,7 @@ static bool rsa_pub_copy(EvpPkey *out, const EvpPkey *pkey) { return true; } -static int rsa_priv_encode(CBB *out, const EvpPkey *key) { +int rsa_priv_encode(CBB *out, const EvpPkey *key) { const RSA *rsa = reinterpret_cast(key->pkey); CBB pkcs8, algorithm, null, private_key; if (!CBB_add_asn1(out, &pkcs8, CBS_ASN1_SEQUENCE) || @@ -145,9 +145,9 @@ static int rsa_priv_encode(CBB *out, const EvpPkey *key) { return 1; } -static bssl::evp_decode_result_t rsa_priv_decode(const EVP_PKEY_ALG *alg, - EvpPkey *out, CBS *params, - CBS *key) { +bssl::evp_decode_result_t rsa_priv_decode(const EVP_PKEY_ALG *alg, + EvpPkey *out, CBS *params, + CBS *key) { // Per RFC 8017, A.1, the parameters have type NULL. CBS null; if (!CBS_get_asn1(params, &null, CBS_ASN1_NULL) || CBS_len(&null) != 0 || @@ -166,12 +166,12 @@ static bssl::evp_decode_result_t rsa_priv_decode(const EVP_PKEY_ALG *alg, return evp_decode_ok; } -static bool rsa_priv_present(const EvpPkey *pk) { +bool rsa_priv_present(const EvpPkey *pk) { const RSA *pk_rsa = reinterpret_cast(pk->pkey); return RSA_get0_n(pk_rsa) != nullptr && RSA_get0_d(pk_rsa) != nullptr; } -static bssl::evp_decode_result_t rsa_decode_pss_params( +bssl::evp_decode_result_t rsa_decode_pss_params( rsa_pss_params_t expected, CBS *params) { if (CBS_len(params) == 0) { return evp_decode_unsupported; @@ -186,7 +186,7 @@ static bssl::evp_decode_result_t rsa_decode_pss_params( return pss_params == expected ? evp_decode_ok : evp_decode_unsupported; } -static int rsa_pub_encode_pss(CBB *out, const EvpPkey *key) { +int rsa_pub_encode_pss(CBB *out, const EvpPkey *key) { const RSAImpl *rsa = reinterpret_cast(key->pkey); CBB spki, algorithm, key_bitstring; if (!CBB_add_asn1(out, &spki, CBS_ASN1_SEQUENCE) || @@ -205,17 +205,17 @@ static int rsa_pub_encode_pss(CBB *out, const EvpPkey *key) { return 1; } -static void evp_pkey_set0_pss(EvpPkey *out, const EVP_PKEY_ALG *alg, - UniquePtr rsa) { +void evp_pkey_set0_pss(EvpPkey *out, const EVP_PKEY_ALG *alg, + UniquePtr rsa) { BSSL_CHECK(alg->pkey_method->pkey_id == EVP_PKEY_RSA_PSS); const auto *alg_pss = static_cast(alg); FromOpaque(rsa.get())->pss_params = alg_pss->pss_params; evp_pkey_set0(out, alg->method, rsa.release()); } -static bssl::evp_decode_result_t rsa_pub_decode_pss(const EVP_PKEY_ALG *alg, - EvpPkey *out, CBS *params, - CBS *key) { +bssl::evp_decode_result_t rsa_pub_decode_pss(const EVP_PKEY_ALG *alg, + EvpPkey *out, CBS *params, + CBS *key) { const auto *alg_pss = static_cast(alg); evp_decode_result_t ret = rsa_decode_pss_params(alg_pss->pss_params, params); if (ret != evp_decode_ok) { @@ -232,7 +232,7 @@ static bssl::evp_decode_result_t rsa_pub_decode_pss(const EVP_PKEY_ALG *alg, return evp_decode_ok; } -static int rsa_priv_encode_pss(CBB *out, const EvpPkey *key) { +int rsa_priv_encode_pss(CBB *out, const EvpPkey *key) { const RSAImpl *rsa = reinterpret_cast(key->pkey); CBB pkcs8, algorithm, private_key; if (!CBB_add_asn1(out, &pkcs8, CBS_ASN1_SEQUENCE) || @@ -251,9 +251,9 @@ static int rsa_priv_encode_pss(CBB *out, const EvpPkey *key) { return 1; } -static bssl::evp_decode_result_t rsa_priv_decode_pss(const EVP_PKEY_ALG *alg, - EvpPkey *out, CBS *params, - CBS *key) { +bssl::evp_decode_result_t rsa_priv_decode_pss(const EVP_PKEY_ALG *alg, + EvpPkey *out, CBS *params, + CBS *key) { const auto *alg_pss = static_cast(alg); evp_decode_result_t ret = rsa_decode_pss_params(alg_pss->pss_params, params); if (ret != evp_decode_ok) { @@ -270,32 +270,32 @@ static bssl::evp_decode_result_t rsa_priv_decode_pss(const EVP_PKEY_ALG *alg, return evp_decode_ok; } -static int rsa_opaque(const EvpPkey *pkey) { +int rsa_opaque(const EvpPkey *pkey) { const RSA *rsa = reinterpret_cast(pkey->pkey); return RSA_is_opaque(rsa); } -static int int_rsa_size(const EvpPkey *pkey) { +int int_rsa_size(const EvpPkey *pkey) { const RSA *rsa = reinterpret_cast(pkey->pkey); return RSA_size(rsa); } -static int rsa_bits(const EvpPkey *pkey) { +int rsa_bits(const EvpPkey *pkey) { const RSA *rsa = reinterpret_cast(pkey->pkey); return RSA_bits(rsa); } -static void int_rsa_free(EvpPkey *pkey) { +void int_rsa_free(EvpPkey *pkey) { RSA_free(reinterpret_cast(pkey->pkey)); pkey->pkey = nullptr; } -static int rsa_pss_params_missing(const EvpPkey *pkey) { +int rsa_pss_params_missing(const EvpPkey *pkey) { const RSA *rsa = reinterpret_cast(pkey->pkey); return rsa == nullptr || FromOpaque(rsa)->pss_params == rsa_pss_none; } -static int rsa_pss_params_copy(EvpPkey *to, const EvpPkey *from) { +int rsa_pss_params_copy(EvpPkey *to, const EvpPkey *from) { const RSA *from_key = reinterpret_cast(from->pkey); if (from_key == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); @@ -316,7 +316,7 @@ static int rsa_pss_params_copy(EvpPkey *to, const EvpPkey *from) { return 1; } -static bool rsa_pss_params_equal(const EvpPkey *a, const EvpPkey *b) { +bool rsa_pss_params_equal(const EvpPkey *a, const EvpPkey *b) { const RSA *a_rsa = reinterpret_cast(a->pkey); const RSA *b_rsa = reinterpret_cast(b->pkey); if (a_rsa == nullptr || b_rsa == nullptr) { @@ -428,11 +428,11 @@ struct RSA_PKEY_CTX { Array oaep_label; }; -static bool is_pss_only(const EvpPkeyCtx *ctx) { +bool is_pss_only(const EvpPkeyCtx *ctx) { return ctx->pmeth->pkey_id == EVP_PKEY_RSA_PSS; } -static int pkey_rsa_init(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *alg) { +int pkey_rsa_init(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *alg) { RSA_PKEY_CTX *rctx = New(); if (!rctx) { return 0; @@ -462,7 +462,7 @@ static int pkey_rsa_init(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *alg) { return 1; } -static int pkey_rsa_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { +int pkey_rsa_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { RSA_PKEY_CTX *dctx, *sctx; if (!pkey_rsa_init(dst, nullptr)) { return 0; @@ -489,12 +489,12 @@ static int pkey_rsa_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { return 1; } -static void pkey_rsa_cleanup(EvpPkeyCtx *ctx) { +void pkey_rsa_cleanup(EvpPkeyCtx *ctx) { Delete(reinterpret_cast(ctx->data)); } -static int pkey_rsa_sign(EvpPkeyCtx *ctx, uint8_t *sig, size_t *siglen, - const uint8_t *tbs, size_t tbslen) { +int pkey_rsa_sign(EvpPkeyCtx *ctx, uint8_t *sig, size_t *siglen, + const uint8_t *tbs, size_t tbslen) { RSA_PKEY_CTX *rctx = reinterpret_cast(ctx->data); RSA *rsa = reinterpret_cast(ctx->pkey->pkey); const size_t key_len = EVP_PKEY_size(ctx->pkey.get()); @@ -531,8 +531,8 @@ static int pkey_rsa_sign(EvpPkeyCtx *ctx, uint8_t *sig, size_t *siglen, return RSA_sign_raw(rsa, siglen, sig, *siglen, tbs, tbslen, rctx->pad_mode); } -static int pkey_rsa_verify(EvpPkeyCtx *ctx, const uint8_t *sig, size_t siglen, - const uint8_t *tbs, size_t tbslen) { +int pkey_rsa_verify(EvpPkeyCtx *ctx, const uint8_t *sig, size_t siglen, + const uint8_t *tbs, size_t tbslen) { RSA_PKEY_CTX *rctx = reinterpret_cast(ctx->data); RSA *rsa = reinterpret_cast(ctx->pkey->pkey); @@ -566,9 +566,9 @@ static int pkey_rsa_verify(EvpPkeyCtx *ctx, const uint8_t *sig, size_t siglen, return 1; } -static int pkey_rsa_verify_recover(EvpPkeyCtx *ctx, uint8_t *out, - size_t *out_len, const uint8_t *sig, - size_t sig_len) { +int pkey_rsa_verify_recover(EvpPkeyCtx *ctx, uint8_t *out, + size_t *out_len, const uint8_t *sig, + size_t sig_len) { RSA_PKEY_CTX *rctx = reinterpret_cast(ctx->data); RSA *rsa = reinterpret_cast(ctx->pkey->pkey); const size_t key_len = EVP_PKEY_size(ctx->pkey.get()); @@ -626,8 +626,8 @@ static int pkey_rsa_verify_recover(EvpPkeyCtx *ctx, uint8_t *out, return 1; } -static int pkey_rsa_encrypt(EvpPkeyCtx *ctx, uint8_t *out, size_t *outlen, - const uint8_t *in, size_t inlen) { +int pkey_rsa_encrypt(EvpPkeyCtx *ctx, uint8_t *out, size_t *outlen, + const uint8_t *in, size_t inlen) { RSA_PKEY_CTX *rctx = reinterpret_cast(ctx->data); RSA *rsa = reinterpret_cast(ctx->pkey->pkey); const size_t key_len = EVP_PKEY_size(ctx->pkey.get()); @@ -658,8 +658,8 @@ static int pkey_rsa_encrypt(EvpPkeyCtx *ctx, uint8_t *out, size_t *outlen, return RSA_encrypt(rsa, outlen, out, *outlen, in, inlen, rctx->pad_mode); } -static int pkey_rsa_decrypt(EvpPkeyCtx *ctx, uint8_t *out, size_t *outlen, - const uint8_t *in, size_t inlen) { +int pkey_rsa_decrypt(EvpPkeyCtx *ctx, uint8_t *out, size_t *outlen, + const uint8_t *in, size_t inlen) { RSA_PKEY_CTX *rctx = reinterpret_cast(ctx->data); RSA *rsa = reinterpret_cast(ctx->pkey->pkey); const size_t key_len = EVP_PKEY_size(ctx->pkey.get()); @@ -692,7 +692,7 @@ static int pkey_rsa_decrypt(EvpPkeyCtx *ctx, uint8_t *out, size_t *outlen, return RSA_decrypt(rsa, outlen, out, key_len, in, inlen, rctx->pad_mode); } -static int check_padding_md(const EVP_MD *md, int padding) { +int check_padding_md(const EVP_MD *md, int padding) { if (!md) { return 1; } @@ -705,7 +705,7 @@ static int check_padding_md(const EVP_MD *md, int padding) { return 1; } -static int is_known_padding(int padding_mode) { +int is_known_padding(int padding_mode) { switch (padding_mode) { case RSA_PKCS1_PADDING: case RSA_NO_PADDING: @@ -717,7 +717,7 @@ static int is_known_padding(int padding_mode) { } } -static int pkey_rsa_ctrl(EvpPkeyCtx *ctx, int type, int p1, void *p2) { +int pkey_rsa_ctrl(EvpPkeyCtx *ctx, int type, int p1, void *p2) { RSA_PKEY_CTX *rctx = reinterpret_cast(ctx->data); switch (type) { case EVP_PKEY_CTRL_RSA_PADDING: @@ -870,7 +870,7 @@ static int pkey_rsa_ctrl(EvpPkeyCtx *ctx, int type, int p1, void *p2) { } } -static int pkey_rsa_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { +int pkey_rsa_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { RSA_PKEY_CTX *rctx = reinterpret_cast(ctx->data); if (!rctx->pub_exp) { rctx->pub_exp.reset(BN_new()); @@ -1042,12 +1042,8 @@ int EVP_PKEY_marshal_rsa_private_key(CBB *cbb, const EVP_PKEY *key) { return RSA_marshal_private_key(cbb, rsa); } -int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, RSA *key) { - if (EVP_PKEY_assign_RSA(pkey, key)) { - RSA_up_ref(key); - return 1; - } - return 0; +int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, const RSA *key) { + return EVP_PKEY_assign_RSA(pkey, RSA_dup_ref(key)); } int EVP_PKEY_assign_RSA(EVP_PKEY *pkey, RSA *key) { diff --git a/third_party/boringssl/src/crypto/evp/p_slhdsa.cc b/third_party/boringssl/src/crypto/evp/p_slhdsa.cc new file mode 100644 index 0000000..c6bb4fd --- /dev/null +++ b/third_party/boringssl/src/crypto/evp/p_slhdsa.cc @@ -0,0 +1,537 @@ +// Copyright 2026 The BoringSSL Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../mem_internal.h" +#include "internal.h" + +using namespace bssl; + +namespace { + +constexpr uint8_t kSLHDSASHA2_128SOID[] = {OBJ_ENC_SLH_DSA_SHA2_128s}; +constexpr uint8_t kSLHDSASHAKE_256FOID[] = {OBJ_ENC_SLH_DSA_SHAKE_256f}; +constexpr uint8_t kSLHDSASHA2_128SWithSHA256OID[] = { + OBJ_ENC_SLH_DSA_SHA2_128s_WITH_SHA256}; + +constexpr size_t kMaxContextLength = 255; + +struct SLHDSASHA2_128STraits { + static constexpr size_t kPublicKeyBytes = SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES; + static constexpr size_t kPrivateKeyBytes = SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES; + static constexpr size_t kSignatureBytes = SLHDSA_SHA2_128S_SIGNATURE_BYTES; + static constexpr int kType = EVP_PKEY_SLH_DSA_SHA2_128S; + static constexpr Span kOID = kSLHDSASHA2_128SOID; + static constexpr bool kPrehash = false; + + static constexpr auto GenerateKey = &SLHDSA_SHA2_128S_generate_key; + static constexpr auto Sign = &SLHDSA_SHA2_128S_sign; + static constexpr auto Verify = &SLHDSA_SHA2_128S_verify; +}; + +struct SLHDSASHAKE_256FTraits { + static constexpr size_t kPublicKeyBytes = SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES; + static constexpr size_t kPrivateKeyBytes = + SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES; + static constexpr size_t kSignatureBytes = SLHDSA_SHAKE_256F_SIGNATURE_BYTES; + static constexpr int kType = EVP_PKEY_SLH_DSA_SHAKE_256F; + static constexpr Span kOID = kSLHDSASHAKE_256FOID; + static constexpr bool kPrehash = false; + + static constexpr auto GenerateKey = &SLHDSA_SHAKE_256F_generate_key; + static constexpr auto Sign = &SLHDSA_SHAKE_256F_sign; + static constexpr auto Verify = &SLHDSA_SHAKE_256F_verify; +}; + +struct SLHDSASHA2_128SWithSHA256Traits { + static constexpr size_t kPublicKeyBytes = SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES; + static constexpr size_t kPrivateKeyBytes = SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES; + static constexpr size_t kSignatureBytes = SLHDSA_SHA2_128S_SIGNATURE_BYTES; + static constexpr int kType = EVP_PKEY_SLH_DSA_SHA2_128S_WITH_SHA256; + static constexpr Span kOID = kSLHDSASHA2_128SWithSHA256OID; + static constexpr bool kPrehash = true; + static constexpr size_t kDigestLength = SHA256_DIGEST_LENGTH; + static constexpr int kDigestNID = NID_sha256; + + static constexpr auto GenerateKey = &SLHDSA_SHA2_128S_generate_key; + static constexpr auto PrehashSign = &SLHDSA_SHA2_128S_prehash_sign; + static constexpr auto PrehashVerify = &SLHDSA_SHA2_128S_prehash_verify; +}; + +template +struct SLHDSA_KEY { + enum { kAllowUniquePtr = true }; + + // key is the 4n-byte SLH-DSA private key (SK.seed || SK.prf || PK.seed || + // PK.root). If `has_private` is false, the first 2n bytes are uninitialized + // and the 2n-byte public key (PK.seed || PK.root) is in the last 2n bytes. + uint8_t key[Traits::kPrivateKeyBytes]; + bool has_private; + + Span public_key() { + return MakeSpan(key).template last(); + } + Span public_key() const { + return MakeConstSpan(key).template last(); + } +}; + +struct SlhdsaPkeyCtx { + bssl::Array context; +}; + +template +struct SLHDSAImplementation { + static SLHDSA_KEY *GetKeyData(EvpPkey *pkey) { + assert(pkey->ameth == &asn1_method); + return static_cast *>(pkey->pkey); + } + + static const SLHDSA_KEY *GetKeyData(const EvpPkey *pkey) { + return GetKeyData(const_cast(pkey)); + } + + static void PkeyFree(EvpPkey *pkey) { + Delete(GetKeyData(pkey)); + pkey->pkey = nullptr; + } + + static int SetRawPrivate(EvpPkey *pkey, const uint8_t *in, size_t len) { + if (len != Traits::kPrivateKeyBytes) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return 0; + } + UniquePtr> key = MakeUnique>(); + if (key == nullptr) { + return 0; + } + OPENSSL_memcpy(key->key, in, Traits::kPrivateKeyBytes); + key->has_private = true; + evp_pkey_set0(pkey, &asn1_method, key.release()); + return 1; + } + + static int SetRawPublic(EvpPkey *pkey, const uint8_t *in, size_t len) { + if (len != Traits::kPublicKeyBytes) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return 0; + } + UniquePtr> key = MakeUnique>(); + if (key == nullptr) { + return 0; + } + OPENSSL_memcpy(key->public_key().data(), in, Traits::kPublicKeyBytes); + key->has_private = false; + evp_pkey_set0(pkey, &asn1_method, key.release()); + return 1; + } + + static int GetRawPrivate(const EvpPkey *pkey, uint8_t *out, size_t *out_len) { + const SLHDSA_KEY *key = GetKeyData(pkey); + if (!key->has_private) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); + return 0; + } + if (out == nullptr) { + *out_len = Traits::kPrivateKeyBytes; + return 1; + } + if (*out_len < Traits::kPrivateKeyBytes) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + OPENSSL_memcpy(out, key->key, Traits::kPrivateKeyBytes); + *out_len = Traits::kPrivateKeyBytes; + return 1; + } + + static int GetRawPublic(const EvpPkey *pkey, uint8_t *out, size_t *out_len) { + const SLHDSA_KEY *key = GetKeyData(pkey); + if (out == nullptr) { + *out_len = Traits::kPublicKeyBytes; + return 1; + } + if (*out_len < Traits::kPublicKeyBytes) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + OPENSSL_memcpy(out, key->public_key().data(), Traits::kPublicKeyBytes); + *out_len = Traits::kPublicKeyBytes; + return 1; + } + + static evp_decode_result_t DecodePublic(const EVP_PKEY_ALG *alg, EvpPkey *out, + CBS *params, CBS *key) { + // The parameters must be omitted. See RFC 9909, Sections 3 and 4. + if (CBS_len(params) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + return SetRawPublic(out, CBS_data(key), CBS_len(key)) ? evp_decode_ok + : evp_decode_error; + } + + static int EncodePublic(CBB *out, const EvpPkey *pkey) { + const SLHDSA_KEY *key = GetKeyData(pkey); + // See RFC 9909, Sections 3 and 4. + CBB spki, algorithm, key_bitstring; + if (!CBB_add_asn1(out, &spki, CBS_ASN1_SEQUENCE) || + !CBB_add_asn1(&spki, &algorithm, CBS_ASN1_SEQUENCE) || + !CBB_add_asn1_element(&algorithm, CBS_ASN1_OBJECT, Traits::kOID.data(), + Traits::kOID.size()) || + !CBB_add_asn1(&spki, &key_bitstring, CBS_ASN1_BITSTRING) || + !CBB_add_u8(&key_bitstring, 0 /* no unused bits */) || + !CBB_add_bytes(&key_bitstring, key->public_key().data(), + key->public_key().size()) || + !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); + return 0; + } + return 1; + } + + static bool EqualPublic(const EvpPkey *a, const EvpPkey *b) { + const SLHDSA_KEY *a_key = GetKeyData(a); + const SLHDSA_KEY *b_key = GetKeyData(b); + return OPENSSL_memcmp(a_key->public_key().data(), + b_key->public_key().data(), + Traits::kPublicKeyBytes) == 0; + } + + static bool HasPublic(const EvpPkey *pk) { return true; } + + static bool CopyPublic(EvpPkey *out, const EvpPkey *pk) { + const SLHDSA_KEY *key = GetKeyData(pk); + UniquePtr> public_copy = MakeUnique>(); + if (public_copy == nullptr) { + return false; + } + OPENSSL_memcpy(public_copy->public_key().data(), key->public_key().data(), + Traits::kPublicKeyBytes); + public_copy->has_private = false; + evp_pkey_set0(out, &asn1_method, public_copy.release()); + return true; + } + + static evp_decode_result_t DecodePrivate(const EVP_PKEY_ALG *alg, + EvpPkey *out, CBS *params, + CBS *key) { + // The parameters must be omitted. See RFC 9909, Sections 3 and 5. + if (CBS_len(params) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + return SetRawPrivate(out, CBS_data(key), CBS_len(key)) ? evp_decode_ok + : evp_decode_error; + } + + static int EncodePrivate(CBB *out, const EvpPkey *pkey) { + const SLHDSA_KEY *key = GetKeyData(pkey); + if (!key->has_private) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); + return 0; + } + // See RFC 9909, Sections 3 and 5. + CBB pkcs8, algorithm, private_key; + if (!CBB_add_asn1(out, &pkcs8, CBS_ASN1_SEQUENCE) || + !CBB_add_asn1_uint64(&pkcs8, 0 /* version */) || + !CBB_add_asn1(&pkcs8, &algorithm, CBS_ASN1_SEQUENCE) || + !CBB_add_asn1_element(&algorithm, CBS_ASN1_OBJECT, Traits::kOID.data(), + Traits::kOID.size()) || + !CBB_add_asn1(&pkcs8, &private_key, CBS_ASN1_OCTETSTRING) || + !CBB_add_bytes(&private_key, key->key, Traits::kPrivateKeyBytes) || + !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); + return 0; + } + return 1; + } + + static bool HasPrivate(const EvpPkey *pk) { + return GetKeyData(pk)->has_private; + } + + static int PkeySize(const EvpPkey *pkey) { return Traits::kSignatureBytes; } + static int PkeyBits(const EvpPkey *pkey) { + // OpenSSL counts the bits in the public key serialization. + return Traits::kPublicKeyBytes * 8; + } + + static int Init(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *) { + SlhdsaPkeyCtx *sctx = New(); + if (sctx == nullptr) { + return 0; + } + ctx->data = sctx; + return 1; + } + + static void Cleanup(EvpPkeyCtx *ctx) { + Delete(static_cast(ctx->data)); + } + + static int CopyContext(EvpPkeyCtx *dst, EvpPkeyCtx *src) { + if (!Init(dst, nullptr)) { + return 0; + } + SlhdsaPkeyCtx *sctx = static_cast(src->data); + SlhdsaPkeyCtx *dctx = static_cast(dst->data); + if (!dctx->context.CopyFrom(sctx->context)) { + return 0; + } + return 1; + } + + static int KeyGen(EvpPkeyCtx *ctx, EvpPkey *pkey) { + UniquePtr> key = MakeUnique>(); + if (key == nullptr) { + return 0; + } + uint8_t unused_public[Traits::kPublicKeyBytes]; + Traits::GenerateKey(unused_public, key->key); + key->has_private = true; + evp_pkey_set0(pkey, &asn1_method, key.release()); + return 1; + } + + static int SignMessage(EvpPkeyCtx *ctx, uint8_t *sig, size_t *siglen, + const uint8_t *tbs, size_t tbslen) { + const SLHDSA_KEY *key = GetKeyData(ctx->pkey.get()); + if (!key->has_private) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); + return 0; + } + if (sig == nullptr) { + *siglen = Traits::kSignatureBytes; + return 1; + } + if (*siglen < Traits::kSignatureBytes) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + SlhdsaPkeyCtx *sctx = static_cast(ctx->data); + if (!Traits::Sign(sig, key->key, tbs, tbslen, sctx->context.data(), + sctx->context.size())) { + return 0; + } + *siglen = Traits::kSignatureBytes; + return 1; + } + + static int VerifyMessage(EvpPkeyCtx *ctx, const uint8_t *sig, size_t siglen, + const uint8_t *tbs, size_t tbslen) { + const SLHDSA_KEY *key = GetKeyData(ctx->pkey.get()); + SlhdsaPkeyCtx *sctx = static_cast(ctx->data); + if (!Traits::Verify(sig, siglen, key->public_key().data(), tbs, tbslen, + sctx->context.data(), sctx->context.size())) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SIGNATURE); + return 0; + } + return 1; + } + + static int SignDigest(EvpPkeyCtx *ctx, uint8_t *sig, size_t *siglen, + const uint8_t *tbs, size_t tbslen) { + const SLHDSA_KEY *key = GetKeyData(ctx->pkey.get()); + if (!key->has_private) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); + return 0; + } + if (sig == nullptr) { + *siglen = Traits::kSignatureBytes; + return 1; + } + if (*siglen < Traits::kSignatureBytes) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + if (tbslen != Traits::kDigestLength) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_DIGEST_LENGTH); + return 0; + } + SlhdsaPkeyCtx *sctx = static_cast(ctx->data); + if (!Traits::PrehashSign(sig, key->key, tbs, tbslen, Traits::kDigestNID, + sctx->context.data(), sctx->context.size())) { + return 0; + } + *siglen = Traits::kSignatureBytes; + return 1; + } + + static int VerifyDigest(EvpPkeyCtx *ctx, const uint8_t *sig, size_t siglen, + const uint8_t *tbs, size_t tbslen) { + const SLHDSA_KEY *key = GetKeyData(ctx->pkey.get()); + if (tbslen != Traits::kDigestLength) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_DIGEST_LENGTH); + return 0; + } + SlhdsaPkeyCtx *sctx = static_cast(ctx->data); + if (!Traits::PrehashVerify(sig, siglen, key->public_key().data(), tbs, + tbslen, Traits::kDigestNID, + sctx->context.data(), sctx->context.size())) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SIGNATURE); + return 0; + } + return 1; + } + + static int Ctrl(EvpPkeyCtx *ctx, int type, int p1, void *p2) { + SlhdsaPkeyCtx *sctx = static_cast(ctx->data); + switch (type) { + case EVP_PKEY_CTRL_SIGNATURE_CONTEXT_STRING: { + const auto *context_string = + reinterpret_cast *>(p2); + if (context_string == nullptr || + context_string->size() > kMaxContextLength) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PARAMETERS); + return 0; + } + return sctx->context.CopyFrom(*context_string); + } + + case EVP_PKEY_CTRL_MD: { + if constexpr (!Traits::kPrehash) { + OPENSSL_PUT_ERROR(EVP, EVP_R_COMMAND_NOT_SUPPORTED); + return 0; + } else { + const auto *md = reinterpret_cast(p2); + if (md == nullptr || EVP_MD_type(md) != Traits::kDigestNID) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_DIGEST_TYPE); + return 0; + } + return 1; + } + } + + case EVP_PKEY_CTRL_GET_MD: { + if constexpr (!Traits::kPrehash) { + OPENSSL_PUT_ERROR(EVP, EVP_R_COMMAND_NOT_SUPPORTED); + return 0; + } else { + // Add a `Digest()` hook to the traits if other algorithms supported. + static_assert(Traits::kDigestNID == NID_sha256); + *reinterpret_cast(p2) = EVP_sha256(); + return 1; + } + } + + default: + OPENSSL_PUT_ERROR(EVP, EVP_R_COMMAND_NOT_SUPPORTED); + return 0; + } + } + + static constexpr EVP_PKEY_CTX_METHOD BuildPkeyMethod() { + EVP_PKEY_CTX_METHOD ret = { + Traits::kType, + &Init, + &CopyContext, + &Cleanup, + &KeyGen, + /*sign=*/nullptr, + /*sign_message=*/nullptr, + /*verify=*/nullptr, + /*verify_message=*/nullptr, + /*verify_recover=*/nullptr, + /*encrypt=*/nullptr, + /*decrypt=*/nullptr, + /*derive=*/nullptr, + /*paramgen=*/nullptr, + /*encap=*/nullptr, + /*decap=*/nullptr, + &Ctrl, + }; + if constexpr (Traits::kPrehash) { + ret.sign = &SignDigest; + ret.verify = &VerifyDigest; + } else { + ret.sign_message = &SignMessage; + ret.verify_message = &VerifyMessage; + } + return ret; + } + + static constexpr EVP_PKEY_CTX_METHOD pkey_method = BuildPkeyMethod(); + + static constexpr EVP_PKEY_ASN1_METHOD BuildASN1Method() { + EVP_PKEY_ASN1_METHOD ret = { + Traits::kType, + // The OID is filled in below. + /*oid=*/{}, + /*oid_len=*/0, + &pkey_method, + &DecodePublic, + &EncodePublic, + &EqualPublic, + &HasPublic, + &CopyPublic, + &DecodePrivate, + &EncodePrivate, + &HasPrivate, + &SetRawPrivate, + /*set_priv_seed=*/nullptr, + &SetRawPublic, + &GetRawPrivate, + /*get_priv_seed=*/nullptr, + &GetRawPublic, + /*set1_tls_encodedpoint=*/nullptr, + /*get1_tls_encodedpoint=*/nullptr, + /*pkey_opaque=*/nullptr, + &PkeySize, + &PkeyBits, + /*param_missing=*/nullptr, + /*param_copy=*/nullptr, + /*param_equal=*/nullptr, + &PkeyFree, + }; + constexpr auto oid = Traits::kOID; + static_assert(oid.size() <= sizeof(ret.oid)); + for (size_t i = 0; i < oid.size(); i++) { + ret.oid[i] = oid[i]; + } + ret.oid_len = oid.size(); + return ret; + } + + static constexpr EVP_PKEY_ASN1_METHOD asn1_method = BuildASN1Method(); + static constexpr EVP_PKEY_ALG pkey_alg = {&asn1_method, &pkey_method}; +}; + +} // namespace + +const EVP_PKEY_ALG *EVP_pkey_slh_dsa_sha2_128s() { + return &SLHDSAImplementation::pkey_alg; +} + +const EVP_PKEY_ALG *EVP_pkey_slh_dsa_shake_256f() { + return &SLHDSAImplementation::pkey_alg; +} + +const EVP_PKEY_ALG *EVP_pkey_slh_dsa_sha2_128s_with_sha256() { + return &SLHDSAImplementation::pkey_alg; +} diff --git a/third_party/boringssl/src/crypto/evp/p_x25519.cc b/third_party/boringssl/src/crypto/evp/p_x25519.cc index 91df6f4..2c53608 100644 --- a/third_party/boringssl/src/crypto/evp/p_x25519.cc +++ b/third_party/boringssl/src/crypto/evp/p_x25519.cc @@ -37,13 +37,13 @@ struct X25519_KEY { extern const EVP_PKEY_ASN1_METHOD x25519_asn1_meth; extern const EVP_PKEY_CTX_METHOD x25519_pkey_meth; -static void x25519_free(EvpPkey *pkey) { +void x25519_free(EvpPkey *pkey) { X25519_KEY *key = reinterpret_cast(pkey->pkey); OPENSSL_free(key); pkey->pkey = nullptr; } -static int x25519_set_priv_raw(EvpPkey *pkey, const uint8_t *in, size_t len) { +int x25519_set_priv_raw(EvpPkey *pkey, const uint8_t *in, size_t len) { if (len != 32) { OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); return 0; @@ -62,7 +62,7 @@ static int x25519_set_priv_raw(EvpPkey *pkey, const uint8_t *in, size_t len) { return 1; } -static int x25519_set_pub_raw(EvpPkey *pkey, const uint8_t *in, size_t len) { +int x25519_set_pub_raw(EvpPkey *pkey, const uint8_t *in, size_t len) { if (len != 32) { OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); return 0; @@ -80,8 +80,7 @@ static int x25519_set_pub_raw(EvpPkey *pkey, const uint8_t *in, size_t len) { return 1; } -static int x25519_get_priv_raw(const EvpPkey *pkey, uint8_t *out, - size_t *out_len) { +int x25519_get_priv_raw(const EvpPkey *pkey, uint8_t *out, size_t *out_len) { const X25519_KEY *key = reinterpret_cast(pkey->pkey); if (!key->has_private) { OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); @@ -103,8 +102,7 @@ static int x25519_get_priv_raw(const EvpPkey *pkey, uint8_t *out, return 1; } -static int x25519_get_pub_raw(const EvpPkey *pkey, uint8_t *out, - size_t *out_len) { +int x25519_get_pub_raw(const EvpPkey *pkey, uint8_t *out, size_t *out_len) { const X25519_KEY *key = reinterpret_cast(pkey->pkey); if (out == nullptr) { *out_len = 32; @@ -121,13 +119,11 @@ static int x25519_get_pub_raw(const EvpPkey *pkey, uint8_t *out, return 1; } -static int x25519_set1_tls_encodedpoint(EvpPkey *pkey, const uint8_t *in, - size_t len) { +int x25519_set1_tls_encodedpoint(EvpPkey *pkey, const uint8_t *in, size_t len) { return x25519_set_pub_raw(pkey, in, len); } -static size_t x25519_get1_tls_encodedpoint(const EvpPkey *pkey, - uint8_t **out_ptr) { +size_t x25519_get1_tls_encodedpoint(const EvpPkey *pkey, uint8_t **out_ptr) { const X25519_KEY *key = reinterpret_cast(pkey->pkey); if (key == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); @@ -138,9 +134,9 @@ static size_t x25519_get1_tls_encodedpoint(const EvpPkey *pkey, return *out_ptr == nullptr ? 0 : 32; } -static bssl::evp_decode_result_t x25519_pub_decode(const EVP_PKEY_ALG *alg, - EvpPkey *out, CBS *params, - CBS *key) { +bssl::evp_decode_result_t x25519_pub_decode(const EVP_PKEY_ALG *alg, + EvpPkey *out, CBS *params, + CBS *key) { // See RFC 8410, section 4. // The parameters must be omitted. Public keys have length 32. @@ -154,7 +150,7 @@ static bssl::evp_decode_result_t x25519_pub_decode(const EVP_PKEY_ALG *alg, : evp_decode_error; } -static int x25519_pub_encode(CBB *out, const EvpPkey *pkey) { +int x25519_pub_encode(CBB *out, const EvpPkey *pkey) { const X25519_KEY *key = reinterpret_cast(pkey->pkey); // See RFC 8410, section 4. @@ -174,15 +170,15 @@ static int x25519_pub_encode(CBB *out, const EvpPkey *pkey) { return 1; } -static bool x25519_pub_equal(const EvpPkey *a, const EvpPkey *b) { +bool x25519_pub_equal(const EvpPkey *a, const EvpPkey *b) { const X25519_KEY *a_key = reinterpret_cast(a->pkey); const X25519_KEY *b_key = reinterpret_cast(b->pkey); return OPENSSL_memcmp(a_key->pub, b_key->pub, 32) == 0; } -static bssl::evp_decode_result_t x25519_priv_decode(const EVP_PKEY_ALG *alg, - EvpPkey *out, CBS *params, - CBS *key) { +bssl::evp_decode_result_t x25519_priv_decode(const EVP_PKEY_ALG *alg, + EvpPkey *out, CBS *params, + CBS *key) { // See RFC 8410, section 7. // Parameters must be empty. The key is a 32-byte value wrapped in an extra @@ -199,7 +195,7 @@ static bssl::evp_decode_result_t x25519_priv_decode(const EVP_PKEY_ALG *alg, : evp_decode_error; } -static int x25519_priv_encode(CBB *out, const EvpPkey *pkey) { +int x25519_priv_encode(CBB *out, const EvpPkey *pkey) { const X25519_KEY *key = reinterpret_cast(pkey->pkey); if (!key->has_private) { OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); @@ -226,9 +222,9 @@ static int x25519_priv_encode(CBB *out, const EvpPkey *pkey) { return 1; } -static bool x25519_pub_present(const EvpPkey *) { return true; } +bool x25519_pub_present(const EvpPkey *) { return true; } -static bool x25519_pub_copy(EvpPkey *out, const EvpPkey *pkey) { +bool x25519_pub_copy(EvpPkey *out, const EvpPkey *pkey) { const X25519_KEY *pkey_x25519 = reinterpret_cast(pkey->pkey); X25519_KEY *public_copy = New(); @@ -241,14 +237,14 @@ static bool x25519_pub_copy(EvpPkey *out, const EvpPkey *pkey) { return true; } -static bool x25519_priv_present(const EvpPkey *pk) { +bool x25519_priv_present(const EvpPkey *pk) { const X25519_KEY *key = reinterpret_cast(pk->pkey); return key->has_private; } -static int x25519_size(const EvpPkey *pkey) { return 32; } +int x25519_size(const EvpPkey *pkey) { return 32; } -static int x25519_bits(const EvpPkey *pkey) { return 253; } +int x25519_bits(const EvpPkey *pkey) { return 253; } const EVP_PKEY_ASN1_METHOD x25519_asn1_meth = { EVP_PKEY_X25519, @@ -281,9 +277,9 @@ const EVP_PKEY_ASN1_METHOD x25519_asn1_meth = { }; // X25519 has no parameters to copy. -static int pkey_x25519_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { return 1; } +int pkey_x25519_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { return 1; } -static int pkey_x25519_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { +int pkey_x25519_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { X25519_KEY *key = New(); if (key == nullptr) { return 0; @@ -295,7 +291,7 @@ static int pkey_x25519_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { return 1; } -static int pkey_x25519_derive(EvpPkeyCtx *ctx, uint8_t *out, size_t *out_len) { +int pkey_x25519_derive(EvpPkeyCtx *ctx, uint8_t *out, size_t *out_len) { if (ctx->pkey == nullptr || ctx->peerkey == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_KEYS_NOT_SET); return 0; @@ -330,7 +326,7 @@ static int pkey_x25519_derive(EvpPkeyCtx *ctx, uint8_t *out, size_t *out_len) { return 1; } -static int pkey_x25519_ctrl(EvpPkeyCtx *ctx, int type, int p1, void *p2) { +int pkey_x25519_ctrl(EvpPkeyCtx *ctx, int type, int p1, void *p2) { switch (type) { case EVP_PKEY_CTRL_PEER_KEY: // `EVP_PKEY_derive_set_peer` requires the key implement this command, diff --git a/third_party/boringssl/src/crypto/evp/p_xwing.cc b/third_party/boringssl/src/crypto/evp/p_xwing.cc index 8479bf6..7d9362c 100644 --- a/third_party/boringssl/src/crypto/evp/p_xwing.cc +++ b/third_party/boringssl/src/crypto/evp/p_xwing.cc @@ -42,19 +42,19 @@ extern const EVP_PKEY_CTX_METHOD xwing_pkey_meth; // This is the length of `eseed` in draft-connolly-cfrg-xwing-kem-06. constexpr size_t kXwingEncapEntropyBytes = 64; -static void xwing_free(EvpPkey *pkey) { +void xwing_free(EvpPkey *pkey) { Delete(reinterpret_cast(pkey->pkey)); } -static bool xwing_pub_equal(const EvpPkey *a, const EvpPkey *b) { +bool xwing_pub_equal(const EvpPkey *a, const EvpPkey *b) { const XWING_KEY *a_key = reinterpret_cast(a->pkey); const XWING_KEY *b_key = reinterpret_cast(b->pkey); return OPENSSL_memcmp(a_key->pub, b_key->pub, XWING_PUBLIC_KEY_BYTES) == 0; } -static bool xwing_pub_present(const EvpPkey *) { return true; } +bool xwing_pub_present(const EvpPkey *) { return true; } -static bool xwing_pub_copy(EvpPkey *out, const EvpPkey *pkey) { +bool xwing_pub_copy(EvpPkey *out, const EvpPkey *pkey) { const XWING_KEY *pkey_xwing = reinterpret_cast(pkey->pkey); auto public_copy = MakeUnique(); if (public_copy == nullptr) { @@ -66,12 +66,12 @@ static bool xwing_pub_copy(EvpPkey *out, const EvpPkey *pkey) { return true; } -static bool xwing_priv_present(const EvpPkey *pk) { +bool xwing_priv_present(const EvpPkey *pk) { const XWING_KEY *key = reinterpret_cast(pk->pkey); return key->has_private; } -static int xwing_set_priv_seed(EvpPkey *pkey, const uint8_t *in, size_t len) { +int xwing_set_priv_seed(EvpPkey *pkey, const uint8_t *in, size_t len) { auto key = MakeUnique(); if (key == nullptr) { return 0; @@ -88,8 +88,7 @@ static int xwing_set_priv_seed(EvpPkey *pkey, const uint8_t *in, size_t len) { return 1; } -static int xwing_get_priv_seed(const EvpPkey *pkey, uint8_t *out, - size_t *out_len) { +int xwing_get_priv_seed(const EvpPkey *pkey, uint8_t *out, size_t *out_len) { const XWING_KEY *key = reinterpret_cast(pkey->pkey); if (key == nullptr || !key->has_private) { OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); @@ -113,7 +112,7 @@ static int xwing_get_priv_seed(const EvpPkey *pkey, uint8_t *out, return 1; } -static int xwing_set_pub_raw(EvpPkey *pkey, const uint8_t *in, size_t len) { +int xwing_set_pub_raw(EvpPkey *pkey, const uint8_t *in, size_t len) { if (len != XWING_PUBLIC_KEY_BYTES) { OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); return 0; @@ -128,8 +127,7 @@ static int xwing_set_pub_raw(EvpPkey *pkey, const uint8_t *in, size_t len) { return 1; } -static int xwing_get_pub_raw(const EvpPkey *pkey, uint8_t *out, - size_t *out_len) { +int xwing_get_pub_raw(const EvpPkey *pkey, uint8_t *out, size_t *out_len) { if (out == nullptr) { *out_len = XWING_PUBLIC_KEY_BYTES; return 1; @@ -144,16 +142,14 @@ static int xwing_get_pub_raw(const EvpPkey *pkey, uint8_t *out, return 1; } -static int xwing_size(const EvpPkey *pkey) { return XWING_CIPHERTEXT_BYTES; } +int xwing_size(const EvpPkey *pkey) { return XWING_CIPHERTEXT_BYTES; } -static int xwing_bits(const EvpPkey *pkey) { - return XWING_PUBLIC_KEY_BYTES * 8; -} +int xwing_bits(const EvpPkey *pkey) { return XWING_PUBLIC_KEY_BYTES * 8; } // X-Wing has no parameters to copy. -static int pkey_xwing_copy_ctx(EvpPkeyCtx *dst, EvpPkeyCtx *src) { return 1; } +int pkey_xwing_copy_ctx(EvpPkeyCtx *dst, EvpPkeyCtx *src) { return 1; } -static int pkey_xwing_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { +int pkey_xwing_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { auto key = MakeUnique(); if (key == nullptr || !XWING_generate_key(key->pub, &key->priv)) { OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR); @@ -164,8 +160,8 @@ static int pkey_xwing_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { return 1; } -static int xwing_kem_encap(Span out_ciphertext, - Span out_secret, const EVP_PKEY *peer_key) { +int xwing_kem_encap(const EVP_KEM *kem, Span out_ciphertext, + Span out_secret, const EVP_PKEY *peer_key) { if (out_ciphertext.size() != XWING_CIPHERTEXT_BYTES) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_CIPHERTEXT_LENGTH); return 0; @@ -180,10 +176,11 @@ static int xwing_kem_encap(Span out_ciphertext, peer_pubkey->pub); } -static int xwing_kem_encap_external_entropy(Span out_ciphertext, - Span out_secret, - const EVP_PKEY *peer_key, - Span entropy) { +int xwing_kem_encap_external_entropy(const EVP_KEM *kem, + Span out_ciphertext, + Span out_secret, + const EVP_PKEY *peer_key, + Span entropy) { if (out_ciphertext.size() != XWING_CIPHERTEXT_BYTES) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_CIPHERTEXT_LENGTH); return 0; @@ -202,9 +199,8 @@ static int xwing_kem_encap_external_entropy(Span out_ciphertext, peer_pubkey->pub, entropy.data()); } -static int xwing_kem_decap(Span out_secret, - Span ciphertext, - const EVP_PKEY *key) { +int xwing_kem_decap(const EVP_KEM *kem, Span out_secret, + Span ciphertext, const EVP_PKEY *key) { const XWING_KEY *priv = reinterpret_cast(FromOpaque(key)->pkey); if (priv == nullptr || !priv->has_private) { OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); @@ -223,11 +219,12 @@ static int xwing_kem_decap(Span out_secret, return XWING_decap(out_secret.data(), ciphertext.data(), &priv->priv); } -static const EVP_KEM xwing_evp_kem = { +const EVP_KEM xwing_evp_kem = { EVP_PKEY_XWING, // XWING_CIPHERTEXT_BYTES, // XWING_SHARED_SECRET_BYTES, // kXwingEncapEntropyBytes, // + /*check_key=*/nullptr, // &xwing_kem_encap, // &xwing_kem_encap_external_entropy, // &xwing_kem_decap, // diff --git a/third_party/boringssl/src/crypto/evp/sign.cc b/third_party/boringssl/src/crypto/evp/sign.cc index afccef5..3503c40 100644 --- a/third_party/boringssl/src/crypto/evp/sign.cc +++ b/third_party/boringssl/src/crypto/evp/sign.cc @@ -19,8 +19,6 @@ #include #include -#include "internal.h" - int EVP_SignInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl) { return EVP_DigestInit_ex(ctx, type, impl); @@ -35,7 +33,7 @@ int EVP_SignUpdate(EVP_MD_CTX *ctx, const void *data, size_t len) { } int EVP_SignFinal(const EVP_MD_CTX *ctx, uint8_t *sig, unsigned *out_sig_len, - EVP_PKEY *pkey) { + const EVP_PKEY *pkey) { // Ensure the final result will fit in `unsigned`. size_t sig_len = EVP_PKEY_size(pkey); if (sig_len > UINT_MAX) { @@ -75,7 +73,7 @@ int EVP_VerifyUpdate(EVP_MD_CTX *ctx, const void *data, size_t len) { } int EVP_VerifyFinal(EVP_MD_CTX *ctx, const uint8_t *sig, size_t sig_len, - EVP_PKEY *pkey) { + const EVP_PKEY *pkey) { uint8_t m[EVP_MAX_MD_SIZE]; unsigned m_len; bssl::ScopedEVP_MD_CTX tmp_ctx; @@ -85,11 +83,9 @@ int EVP_VerifyFinal(EVP_MD_CTX *ctx, const uint8_t *sig, size_t sig_len, } bssl::UniquePtr pkctx(EVP_PKEY_CTX_new(pkey, nullptr)); - if (!pkctx || - !EVP_PKEY_verify_init(pkctx.get()) || + if (!pkctx || !EVP_PKEY_verify_init(pkctx.get()) || !EVP_PKEY_CTX_set_signature_md(pkctx.get(), ctx->digest)) { return 0; } return EVP_PKEY_verify(pkctx.get(), sig, sig_len, m, m_len); } - diff --git a/third_party/boringssl/src/crypto/fipsmodule/aes/gcm.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/aes/gcm.cc.inc index 732a76c..7ead598 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/aes/gcm.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/aes/gcm.cc.inc @@ -295,8 +295,12 @@ void bssl::CRYPTO_gcm128_init_aes_key(GCM128_KEY *gcm_key, const uint8_t *key, #endif } -void bssl::CRYPTO_gcm128_init_ctx(const GCM128_KEY *key, GCM128_CONTEXT *ctx, - const uint8_t *iv, size_t iv_len) { +int bssl::CRYPTO_gcm128_init_ctx(const GCM128_KEY *key, GCM128_CONTEXT *ctx, + const uint8_t *iv, size_t iv_len) { + if (iv_len == 0 || uint64_t{iv_len} >= uint64_t{1} << 61) { + return 0; + } + #ifdef GCM_FUNCREF void (*gcm_gmult_p)(uint8_t Xi[16], const u128 Htable[16]) = key->gmult; #endif @@ -341,6 +345,7 @@ void bssl::CRYPTO_gcm128_init_ctx(const GCM128_KEY *key, GCM128_CONTEXT *ctx, key->block(ctx->Yi, ctx->EK0, &key->aes); ++ctr; CRYPTO_store_u32_be(ctx->Yi + 12, ctr); + return 1; } int bssl::CRYPTO_gcm128_aad(const GCM128_KEY *key, GCM128_CONTEXT *ctx, @@ -357,7 +362,7 @@ int bssl::CRYPTO_gcm128_aad(const GCM128_KEY *key, GCM128_CONTEXT *ctx, } uint64_t alen = ctx->len.aad + aad_len; - if (alen > (UINT64_C(1) << 61) || (sizeof(aad_len) == 8 && alen < aad_len)) { + if (alen >= (UINT64_C(1) << 61) || (sizeof(aad_len) == 8 && alen < aad_len)) { return 0; } ctx->len.aad = alen; diff --git a/third_party/boringssl/src/crypto/fipsmodule/aes/internal.h b/third_party/boringssl/src/crypto/fipsmodule/aes/internal.h index 3ee356c..05ac788 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/aes/internal.h +++ b/third_party/boringssl/src/crypto/fipsmodule/aes/internal.h @@ -92,16 +92,16 @@ extern "C" int aes_hw_set_encrypt_key(const uint8_t *user_key, int bits, AES_KEY *key); extern "C" int aes_hw_set_decrypt_key(const uint8_t *user_key, int bits, AES_KEY *key); -extern "C" void aes_hw_encrypt(const uint8_t *in, uint8_t *out, - const AES_KEY *key); -extern "C" void aes_hw_decrypt(const uint8_t *in, uint8_t *out, - const AES_KEY *key); -extern "C" void aes_hw_cbc_encrypt(const uint8_t *in, uint8_t *out, - size_t length, const AES_KEY *key, - uint8_t *ivec, int enc); -extern "C" void aes_hw_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, - size_t len, const AES_KEY *key, - const uint8_t ivec[16]); +DECLARE_ASM_FUNCTION(void, aes_hw_encrypt, + (const uint8_t *in, uint8_t *out, const AES_KEY *key)) +DECLARE_ASM_FUNCTION(void, aes_hw_decrypt, + (const uint8_t *in, uint8_t *out, const AES_KEY *key)) +DECLARE_ASM_FUNCTION(void, aes_hw_cbc_encrypt, + (const uint8_t *in, uint8_t *out, size_t length, + const AES_KEY *key, uint8_t *ivec, int enc)) +DECLARE_ASM_FUNCTION(void, aes_hw_ctr32_encrypt_blocks, + (const uint8_t *in, uint8_t *out, size_t len, + const AES_KEY *key, const uint8_t ivec[16])) #if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) // On x86 and x86_64, `aes_hw_set_decrypt_key` is implemented in terms of @@ -178,9 +178,9 @@ extern "C" void aes_hw_ecb_encrypt(const uint8_t *in, uint8_t *out, #if defined(BSAES) // Note `bsaes_cbc_encrypt` requires `enc` to be zero. -extern "C" void bsaes_cbc_encrypt(const uint8_t *in, uint8_t *out, - size_t length, const AES_KEY *key, - uint8_t ivec[16], int enc); +DECLARE_ASM_FUNCTION(void, bsaes_cbc_encrypt, + (const uint8_t *in, uint8_t *out, size_t length, + const AES_KEY *key, uint8_t ivec[16], int enc)) extern "C" void bsaes_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, const uint8_t ivec[16]); @@ -203,19 +203,25 @@ extern "C" int vpaes_set_encrypt_key(const uint8_t *userKey, int bits, extern "C" int vpaes_set_decrypt_key(const uint8_t *userKey, int bits, AES_KEY *key); -extern "C" void vpaes_encrypt(const uint8_t *in, uint8_t *out, - const AES_KEY *key); -extern "C" void vpaes_decrypt(const uint8_t *in, uint8_t *out, - const AES_KEY *key); +DECLARE_ASM_FUNCTION(void, vpaes_encrypt, + (const uint8_t *in, uint8_t *out, const AES_KEY *key)) +DECLARE_ASM_FUNCTION(void, vpaes_decrypt, + (const uint8_t *in, uint8_t *out, const AES_KEY *key)) #if defined(VPAES_CBC) -extern "C" void vpaes_cbc_encrypt(const uint8_t *in, uint8_t *out, - size_t length, const AES_KEY *key, - uint8_t *ivec, int enc); +DECLARE_ASM_FUNCTION(void, vpaes_cbc_encrypt, + (const uint8_t *in, uint8_t *out, size_t length, + const AES_KEY *key, uint8_t *ivec, int enc)) #endif -extern "C" void vpaes_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, - size_t len, const AES_KEY *key, - const uint8_t ivec[16]); + +#if defined(OPENSSL_X86) +void vpaes_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, size_t len, + const AES_KEY *key, const uint8_t ivec[16]); +#else +DECLARE_ASM_FUNCTION(void, vpaes_ctr32_encrypt_blocks, + (const uint8_t *in, uint8_t *out, size_t len, + const AES_KEY *key, const uint8_t ivec[16])) +#endif // OPENSSL_X86 #else inline int vpaes_capable() { return 0; } @@ -310,7 +316,9 @@ enum gcm_impl_t { gcm_arm64_aes_eor3, }; -typedef struct { uint64_t hi,lo; } u128; +typedef struct { + uint64_t hi, lo; +} u128; // gmult_func multiplies `Xi` by the GCM key and writes the result back to // `Xi`. @@ -364,9 +372,10 @@ void CRYPTO_ghash_init(gmult_func *out_mult, ghash_func *out_hash, void CRYPTO_gcm128_init_aes_key(GCM128_KEY *gcm_key, const uint8_t *key, size_t key_bytes); -// CRYPTO_gcm128_init_ctx initializes `ctx` to encrypt with `key` and `iv`. -void CRYPTO_gcm128_init_ctx(const GCM128_KEY *key, GCM128_CONTEXT *ctx, - const uint8_t *iv, size_t iv_len); +// CRYPTO_gcm128_init_ctx initializes `ctx` to encrypt with `key` and `iv`. It +// returns one on success and zero if `iv_len` is invalid. +int CRYPTO_gcm128_init_ctx(const GCM128_KEY *key, GCM128_CONTEXT *ctx, + const uint8_t *iv, size_t iv_len); // CRYPTO_gcm128_aad adds to the authenticated data for an instance of GCM. // This must be called before and data is encrypted. `key` must be the same @@ -412,21 +421,27 @@ void gcm_ghash_nohw(uint8_t Xi[16], const u128 Htable[16], const uint8_t *inp, #if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) #define GCM_FUNCREF extern "C" void gcm_init_clmul(u128 Htable[16], const uint64_t Xi[2]); -extern "C" void gcm_gmult_clmul(uint8_t Xi[16], const u128 Htable[16]); -extern "C" void gcm_ghash_clmul(uint8_t Xi[16], const u128 Htable[16], - const uint8_t *inp, size_t len); +DECLARE_ASM_FUNCTION(void, gcm_gmult_clmul, + (uint8_t Xi[16], const u128 Htable[16])) +DECLARE_ASM_FUNCTION(void, gcm_ghash_clmul, + (uint8_t Xi[16], const u128 Htable[16], const uint8_t *inp, + size_t len)) void gcm_init_ssse3(u128 Htable[16], const uint64_t Xi[2]); -extern "C" void gcm_gmult_ssse3(uint8_t Xi[16], const u128 Htable[16]); -extern "C" void gcm_ghash_ssse3(uint8_t Xi[16], const u128 Htable[16], - const uint8_t *in, size_t len); +DECLARE_ASM_FUNCTION(void, gcm_gmult_ssse3, + (uint8_t Xi[16], const u128 Htable[16])) +DECLARE_ASM_FUNCTION(void, gcm_ghash_ssse3, + (uint8_t Xi[16], const u128 Htable[16], const uint8_t *in, + size_t len)) #if defined(OPENSSL_X86_64) #define GHASH_ASM_X86_64 extern "C" void gcm_init_avx(u128 Htable[16], const uint64_t Xi[2]); -extern "C" void gcm_gmult_avx(uint8_t Xi[16], const u128 Htable[16]); -extern "C" void gcm_ghash_avx(uint8_t Xi[16], const u128 Htable[16], - const uint8_t *in, size_t len); +DECLARE_ASM_FUNCTION(void, gcm_gmult_avx, + (uint8_t Xi[16], const u128 Htable[16])) +DECLARE_ASM_FUNCTION(void, gcm_ghash_avx, + (uint8_t Xi[16], const u128 Htable[16], const uint8_t *in, + size_t len)) #define HW_GCM extern "C" size_t aesni_gcm_encrypt(const uint8_t *in, uint8_t *out, size_t len, @@ -437,10 +452,11 @@ extern "C" size_t aesni_gcm_decrypt(const uint8_t *in, uint8_t *out, size_t len, const u128 Htable[16], uint8_t Xi[16]); extern "C" void gcm_init_vpclmulqdq_avx2(u128 Htable[16], const uint64_t H[2]); -extern "C" void gcm_gmult_vpclmulqdq_avx2(uint8_t Xi[16], - const u128 Htable[16]); -extern "C" void gcm_ghash_vpclmulqdq_avx2(uint8_t Xi[16], const u128 Htable[16], - const uint8_t *in, size_t len); +DECLARE_ASM_FUNCTION(void, gcm_gmult_vpclmulqdq_avx2, + (uint8_t Xi[16], const u128 Htable[16])) +DECLARE_ASM_FUNCTION(void, gcm_ghash_vpclmulqdq_avx2, + (uint8_t Xi[16], const u128 Htable[16], const uint8_t *in, + size_t len)) extern "C" void aes_gcm_enc_update_vaes_avx2(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, const uint8_t ivec[16], @@ -454,11 +470,11 @@ extern "C" void aes_gcm_dec_update_vaes_avx2(const uint8_t *in, uint8_t *out, extern "C" void gcm_init_vpclmulqdq_avx512(u128 Htable[16], const uint64_t H[2]); -extern "C" void gcm_gmult_vpclmulqdq_avx512(uint8_t Xi[16], - const u128 Htable[16]); -extern "C" void gcm_ghash_vpclmulqdq_avx512(uint8_t Xi[16], - const u128 Htable[16], - const uint8_t *in, size_t len); +DECLARE_ASM_FUNCTION(void, gcm_gmult_vpclmulqdq_avx512, + (uint8_t Xi[16], const u128 Htable[16])) +DECLARE_ASM_FUNCTION(void, gcm_ghash_vpclmulqdq_avx512, + (uint8_t Xi[16], const u128 Htable[16], const uint8_t *in, + size_t len)) extern "C" void aes_gcm_enc_update_vaes_avx512(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, const uint8_t ivec[16], @@ -488,16 +504,20 @@ inline int gcm_eor3_capable() { } extern "C" void gcm_init_v8(u128 Htable[16], const uint64_t H[2]); -extern "C" void gcm_gmult_v8(uint8_t Xi[16], const u128 Htable[16]); -extern "C" void gcm_ghash_v8(uint8_t Xi[16], const u128 Htable[16], - const uint8_t *inp, size_t len); +DECLARE_ASM_FUNCTION(void, gcm_gmult_v8, + (uint8_t Xi[16], const u128 Htable[16])) +DECLARE_ASM_FUNCTION(void, gcm_ghash_v8, + (uint8_t Xi[16], const u128 Htable[16], const uint8_t *inp, + size_t len)) inline int gcm_neon_capable() { return CRYPTO_is_NEON_capable(); } extern "C" void gcm_init_neon(u128 Htable[16], const uint64_t H[2]); -extern "C" void gcm_gmult_neon(uint8_t Xi[16], const u128 Htable[16]); -extern "C" void gcm_ghash_neon(uint8_t Xi[16], const u128 Htable[16], - const uint8_t *inp, size_t len); +DECLARE_ASM_FUNCTION(void, gcm_gmult_neon, + (uint8_t Xi[16], const u128 Htable[16])) +DECLARE_ASM_FUNCTION(void, gcm_ghash_neon, + (uint8_t Xi[16], const u128 Htable[16], const uint8_t *inp, + size_t len)) #if defined(OPENSSL_AARCH64) #define HW_GCM diff --git a/third_party/boringssl/src/crypto/fipsmodule/bn/exponentiation.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/bn/exponentiation.cc.inc index dfdb907..81b6385 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/bn/exponentiation.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/bn/exponentiation.cc.inc @@ -376,39 +376,67 @@ static void copy_to_prebuf(const BIGNUM *b, int top, BN_ULONG *table, int idx, (void)ret; } +// Window sizes optimized for fixed window size modular exponentiation +// algorithm (BN_mod_exp_mont_consttime). +// +// TODO(davidben): These window sizes were originally set for 64-byte cache +// lines with a cache-line-dependent constant-time mitigation. They can probably +// be revised now that our implementation is no longer cache-time-dependent. +#define BN_window_bits_for_ctime_exponent_size(b) \ + ((b) > 937 ? 6 : (b) > 306 ? 5 : (b) > 89 ? 4 : (b) > 22 ? 3 : 1) +#define BN_MAX_MOD_EXP_CTIME_WINDOW (6) + static int copy_from_prebuf(BIGNUM *b, int top, const BN_ULONG *table, int idx, int window) { if (!bn_wexpand(b, top)) { return 0; } - OPENSSL_memset(b->d, 0, sizeof(BN_ULONG) * top); + assert(window > 0 && window <= BN_MAX_MOD_EXP_CTIME_WINDOW); + + // Compute the selection masks up front. The value barrier prevents Clang + // from adding a branch when `i != idx` and making this copy not constant + // time. const int width = 1 << window; - for (int i = 0; i < width; i++, table += top) { - // Use a value barrier to prevent Clang from adding a branch when `i != idx` - // and making this copy not constant time. Clang is still allowed to learn - // that `mask` is constant across the inner loop, so this won't inhibit any - // vectorization it might do. - BN_ULONG mask = value_barrier_w(constant_time_eq_int(i, idx)); - for (int j = 0; j < top; j++) { - b->d[j] |= table[j] & mask; + BN_ULONG masks[1 << BN_MAX_MOD_EXP_CTIME_WINDOW]; + for (int i = 0; i < width; i++) { + masks[i] = value_barrier_w(constant_time_eq_int(i, idx)); + } + + // Every table entry is read for every limb, independent of `idx`. The output + // is accumulated a few limbs at a time in registers. Updating `b->d` once per + // table entry instead adds a store-to-load dependency to every iteration, + // which the compiler cannot remove because `b->d` may alias `table`. + BN_ULONG *const d = b->d; + int j = 0; + for (; j + 4 <= top; j += 4) { + BN_ULONG a0 = 0, a1 = 0, a2 = 0, a3 = 0; + const BN_ULONG *t = table + j; + for (int i = 0; i < width; i++, t += top) { + BN_ULONG m = masks[i]; + a0 |= t[0] & m; + a1 |= t[1] & m; + a2 |= t[2] & m; + a3 |= t[3] & m; } + d[j] = a0; + d[j + 1] = a1; + d[j + 2] = a2; + d[j + 3] = a3; + } + for (; j < top; j++) { + BN_ULONG a = 0; + const BN_ULONG *t = table + j; + for (int i = 0; i < width; i++, t += top) { + a |= *t & masks[i]; + } + d[j] = a; } b->width = top; return 1; } -// Window sizes optimized for fixed window size modular exponentiation -// algorithm (BN_mod_exp_mont_consttime). -// -// TODO(davidben): These window sizes were originally set for 64-byte cache -// lines with a cache-line-dependent constant-time mitigation. They can probably -// be revised now that our implementation is no longer cache-time-dependent. -#define BN_window_bits_for_ctime_exponent_size(b) \ - ((b) > 937 ? 6 : (b) > 306 ? 5 : (b) > 89 ? 4 : (b) > 22 ? 3 : 1) -#define BN_MAX_MOD_EXP_CTIME_WINDOW (6) - // This variant of `BN_mod_exp_mont` uses fixed windows and fixed memory access // patterns to protect secret exponents (cf. the hyper-threading timing attacks // pointed out by Colin Percival, diff --git a/third_party/boringssl/src/crypto/fipsmodule/cipher/e_aes.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/cipher/e_aes.cc.inc index 83fa9ff..e0afeba 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/cipher/e_aes.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/cipher/e_aes.cc.inc @@ -225,13 +225,17 @@ static int aes_gcm_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, iv = gctx->iv; } if (iv) { - CRYPTO_gcm128_init_ctx(&gctx->key, &gctx->gcm, iv, gctx->ivlen); + if (!CRYPTO_gcm128_init_ctx(&gctx->key, &gctx->gcm, iv, gctx->ivlen)) { + return 0; + } gctx->iv_set = 1; } gctx->key_set = 1; } else { if (gctx->key_set) { - CRYPTO_gcm128_init_ctx(&gctx->key, &gctx->gcm, iv, gctx->ivlen); + if (!CRYPTO_gcm128_init_ctx(&gctx->key, &gctx->gcm, iv, gctx->ivlen)) { + return 0; + } } else { // The caller specified the IV before the key. Save the IV for later. OPENSSL_memcpy(gctx->iv, iv, gctx->ivlen); @@ -341,10 +345,12 @@ static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { return 1; case EVP_CTRL_GCM_IV_GEN: { - if (gctx->iv_gen == 0 || gctx->key_set == 0 || gctx->ivlen < 8) { + if (gctx->iv_gen == 0 || gctx->key_set == 0 || gctx->ivlen < 8 || + !CRYPTO_gcm128_init_ctx(&gctx->key, &gctx->gcm, gctx->iv, + gctx->ivlen)) { return 0; } - CRYPTO_gcm128_init_ctx(&gctx->key, &gctx->gcm, gctx->iv, gctx->ivlen); + if (arg <= 0 || arg > gctx->ivlen) { arg = gctx->ivlen; } @@ -361,7 +367,10 @@ static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { return 0; } OPENSSL_memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg); - CRYPTO_gcm128_init_ctx(&gctx->key, &gctx->gcm, gctx->iv, gctx->ivlen); + if (!CRYPTO_gcm128_init_ctx(&gctx->key, &gctx->gcm, gctx->iv, + gctx->ivlen)) { + return 0; + } gctx->iv_set = 1; return 1; @@ -787,15 +796,13 @@ static int aead_aes_gcm_sealv_impl(const struct aead_aes_gcm_ctx *gcm_ctx, return 0; } - if (nonce.size() == 0) { + const GCM128_KEY *key = &gcm_ctx->key; + GCM128_CONTEXT gcm; + if (!CRYPTO_gcm128_init_ctx(key, &gcm, nonce.data(), nonce.size())) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE_SIZE); return 0; } - const GCM128_KEY *key = &gcm_ctx->key; - GCM128_CONTEXT gcm; - CRYPTO_gcm128_init_ctx(key, &gcm, nonce.data(), nonce.size()); - for (const CRYPTO_IVEC &aadvec : aadvecs) { if (!CRYPTO_gcm128_aad(key, &gcm, aadvec.in, aadvec.len)) { return 0; @@ -829,13 +836,6 @@ static int aead_aes_gcm_openv_detached_impl( const struct aead_aes_gcm_ctx *gcm_ctx, Span iovecs, Span nonce, Span in_tag, Span aadvecs, size_t tag_len) { - uint8_t tag[EVP_AEAD_AES_GCM_TAG_LEN]; - - if (nonce.size() == 0) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE_SIZE); - return 0; - } - if (in_tag.size() != tag_len) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; @@ -843,7 +843,10 @@ static int aead_aes_gcm_openv_detached_impl( const GCM128_KEY *key = &gcm_ctx->key; GCM128_CONTEXT gcm; - CRYPTO_gcm128_init_ctx(key, &gcm, nonce.data(), nonce.size()); + if (!CRYPTO_gcm128_init_ctx(key, &gcm, nonce.data(), nonce.size())) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE_SIZE); + return 0; + } for (const CRYPTO_IVEC &aadvec : aadvecs) { if (!CRYPTO_gcm128_aad(key, &gcm, aadvec.in, aadvec.len)) { @@ -857,6 +860,7 @@ static int aead_aes_gcm_openv_detached_impl( } } + uint8_t tag[EVP_AEAD_AES_GCM_TAG_LEN]; CRYPTO_gcm128_tag(key, &gcm, tag, tag_len); if (CRYPTO_memcmp(tag, in_tag.data(), tag_len) != 0) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); diff --git a/third_party/boringssl/src/crypto/fipsmodule/cmac/cmac.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/cmac/cmac.cc.inc index 93e48f8..ed25471 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/cmac/cmac.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/cmac/cmac.cc.inc @@ -286,8 +286,8 @@ int CMAC_Final(CMAC_CTX *ctx, uint8_t *out, size_t *out_len) { out: FIPS_service_indicator_unlock_state(); - if (ret) { - FIPS_service_indicator_update_state(); + if (ret && out != nullptr) { + CMAC_verify_service_indicator(&ctx->cipher_ctx); } return ret; } diff --git a/third_party/boringssl/src/crypto/fipsmodule/dh/dh.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/dh/dh.cc.inc index d018f76..8dfcdee 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/dh/dh.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/dh/dh.cc.inc @@ -353,6 +353,13 @@ int DH_up_ref(DH *dh) { return 1; } +DH *DH_dup_ref(const DH *dh) { + if (dh == nullptr) { + return nullptr; + } + return FromOpaque(dh)->DupRefInternal(); +} + DH *DH_get_rfc7919_2048() { // This is the prime from https://tools.ietf.org/html/rfc7919#appendix-A.1, // which is specifically approved for FIPS in appendix D of SP 800-56Ar3. diff --git a/third_party/boringssl/src/crypto/fipsmodule/digest/digest.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/digest/digest.cc.inc index a7c6317..8d4b2aa 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/digest/digest.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/digest/digest.cc.inc @@ -84,8 +84,20 @@ void EVP_MD_CTX_free(EVP_MD_CTX *ctx) { void EVP_MD_CTX_destroy(EVP_MD_CTX *ctx) { EVP_MD_CTX_free(ctx); } int EVP_DigestFinalXOF(EVP_MD_CTX *ctx, uint8_t *out, size_t len) { - OPENSSL_PUT_ERROR(DIGEST, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); - return 0; + if (!EVP_DigestSqueeze(ctx, out, len)) { + return 0; + } + EVP_MD_CTX_cleanse(ctx); + return 1; +} + +int EVP_DigestSqueeze(EVP_MD_CTX *ctx, unsigned char *out, size_t len) { + if (ctx->digest->squeeze == nullptr) { + OPENSSL_PUT_ERROR(DIGEST, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return 0; + } + ctx->digest->squeeze(ctx, out, len); + return 1; } uint32_t EVP_MD_meth_get_flags(const EVP_MD *md) { return EVP_MD_flags(md); } diff --git a/third_party/boringssl/src/crypto/fipsmodule/digest/digests.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/digest/digests.cc.inc index a246a51..23b7409 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/digest/digests.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/digest/digests.cc.inc @@ -19,7 +19,6 @@ #include -#include "../../internal.h" #include "../bcm_interface.h" #include "../delocate.h" #include "internal.h" @@ -78,6 +77,7 @@ DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha224) { out->init = sha224_init; out->update = sha224_update; out->final = sha224_final; + out->squeeze = nullptr; out->block_size = 64; out->ctx_size = sizeof(SHA256_CTX); } @@ -103,6 +103,7 @@ DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha256) { out->init = sha256_init; out->update = sha256_update; out->final = sha256_final; + out->squeeze = nullptr; out->block_size = 64; out->ctx_size = sizeof(SHA256_CTX); } @@ -127,6 +128,7 @@ DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha384) { out->init = sha384_init; out->update = sha384_update; out->final = sha384_final; + out->squeeze = nullptr; out->block_size = 128; out->ctx_size = sizeof(SHA512_CTX); } @@ -152,6 +154,7 @@ DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha512) { out->init = sha512_init; out->update = sha512_update; out->final = sha512_final; + out->squeeze = nullptr; out->block_size = 128; out->ctx_size = sizeof(SHA512_CTX); } @@ -177,6 +180,7 @@ DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha512_256) { out->init = sha512_256_init; out->update = sha512_256_update; out->final = sha512_256_final; + out->squeeze = nullptr; out->block_size = 128; out->ctx_size = sizeof(SHA512_CTX); } diff --git a/third_party/boringssl/src/crypto/fipsmodule/digest/internal.h b/third_party/boringssl/src/crypto/fipsmodule/digest/internal.h index 52090ce..6b7ca78 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/digest/internal.h +++ b/third_party/boringssl/src/crypto/fipsmodule/digest/internal.h @@ -44,6 +44,10 @@ struct env_md_st { // final completes the hash and writes `md_size` bytes of digest to `out`. void (*final)(EVP_MD_CTX *ctx, uint8_t *out); + // squeeze writes the `out_len` bytes of digest to `out`. + // It is only applicable to extendable output functions. + void (*squeeze)(EVP_MD_CTX *ctx, uint8_t *out, size_t out_len); + // block_size contains the hash's native block size. unsigned block_size; diff --git a/third_party/boringssl/src/crypto/fipsmodule/digestsign/digestsign.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/digestsign/digestsign.cc.inc index 8920546..a886d46 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/digestsign/digestsign.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/digestsign/digestsign.cc.inc @@ -41,7 +41,7 @@ static int uses_prehash(EVP_PKEY_CTX *pctx, enum evp_sign_verify_t op) { } static int do_sigver_init(EVP_MD_CTX *ctx, EVP_PKEY_CTX **out_pctx, - const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey, + const EVP_MD *type, ENGINE *e, const EVP_PKEY *pkey, enum evp_sign_verify_t op) { UniquePtr pctx(EVP_PKEY_CTX_new(pkey, e)); if (pctx == nullptr) { @@ -84,12 +84,12 @@ static int do_sigver_init(EVP_MD_CTX *ctx, EVP_PKEY_CTX **out_pctx, } int EVP_DigestSignInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, const EVP_MD *type, - ENGINE *e, EVP_PKEY *pkey) { + ENGINE *e, const EVP_PKEY *pkey) { return do_sigver_init(ctx, pctx, type, e, pkey, evp_sign); } int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, - const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey) { + const EVP_MD *type, ENGINE *e, const EVP_PKEY *pkey) { return do_sigver_init(ctx, pctx, type, e, pkey, evp_verify); } @@ -143,8 +143,7 @@ int EVP_DigestSignFinal(EVP_MD_CTX *ctx, uint8_t *out_sig, } } -int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const uint8_t *sig, - size_t sig_len) { +int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const uint8_t *sig, size_t sig_len) { if (!uses_prehash(ctx->pctx, evp_verify)) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; diff --git a/third_party/boringssl/src/crypto/fipsmodule/ec/ec_key.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/ec/ec_key.cc.inc index 18979b9..078e541 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/ec/ec_key.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/ec/ec_key.cc.inc @@ -26,7 +26,6 @@ #include "../../internal.h" #include "../../mem_internal.h" -#include "../bcm_interface.h" #include "../delocate.h" #include "../ecdsa/internal.h" #include "../service_indicator/internal.h" @@ -147,6 +146,13 @@ int EC_KEY_up_ref(EC_KEY *r) { return 1; } +EC_KEY *EC_KEY_dup_ref(const EC_KEY *key) { + if (key == nullptr) { + return nullptr; + } + return FromOpaque(key)->DupRefInternal(); +} + int EC_KEY_is_opaque(const EC_KEY *key) { auto *impl = FromOpaque(key); return impl->ecdsa_meth && (impl->ecdsa_meth->flags & ECDSA_FLAG_OPAQUE); diff --git a/third_party/boringssl/src/crypto/fipsmodule/ec/p256-nistz.h b/third_party/boringssl/src/crypto/fipsmodule/ec/p256-nistz.h index 43da01c..9eb809a 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/ec/p256-nistz.h +++ b/third_party/boringssl/src/crypto/fipsmodule/ec/p256-nistz.h @@ -28,17 +28,16 @@ #include +#include "../../internal.h" #include "../bn/internal.h" -#if defined(__cplusplus) -extern "C" { -#endif - -#if !defined(OPENSSL_NO_ASM) && \ - (defined(OPENSSL_X86_64) || defined(OPENSSL_AARCH64)) && \ +#if !defined(OPENSSL_NO_ASM) && \ + (defined(OPENSSL_X86_64) || defined(OPENSSL_AARCH64)) && \ !defined(OPENSSL_SMALL) +BSSL_NAMESPACE_BEGIN + // P-256 field operations. // // An element mod P in P-256 is represented as a little-endian array of @@ -50,31 +49,32 @@ extern "C" { #define P256_LIMBS (256 / BN_BITS2) // ecp_nistz256_neg sets `res` to -`a` mod P. -void ecp_nistz256_neg(BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS]); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_neg, + (BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS])) // ecp_nistz256_mul_mont sets `res` to `a` * `b` * 2^-256 mod P. #if defined(OPENSSL_X86_64) -void ecp_nistz256_mul_mont_nohw(BN_ULONG res[P256_LIMBS], - const BN_ULONG a[P256_LIMBS], - const BN_ULONG b[P256_LIMBS]); -void ecp_nistz256_mul_mont_adx(BN_ULONG res[P256_LIMBS], - const BN_ULONG a[P256_LIMBS], - const BN_ULONG b[P256_LIMBS]); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_mul_mont_nohw, + (BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS], + const BN_ULONG b[P256_LIMBS])) +DECLARE_ASM_FUNCTION(void, ecp_nistz256_mul_mont_adx, + (BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS], + const BN_ULONG b[P256_LIMBS])) #else -void ecp_nistz256_mul_mont(BN_ULONG res[P256_LIMBS], - const BN_ULONG a[P256_LIMBS], - const BN_ULONG b[P256_LIMBS]); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_mul_mont, + (BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS], + const BN_ULONG b[P256_LIMBS])) #endif // ecp_nistz256_sqr_mont sets `res` to `a` * `a` * 2^-256 mod P. #if defined(OPENSSL_X86_64) -void ecp_nistz256_sqr_mont_nohw(BN_ULONG res[P256_LIMBS], - const BN_ULONG a[P256_LIMBS]); -void ecp_nistz256_sqr_mont_adx(BN_ULONG res[P256_LIMBS], - const BN_ULONG a[P256_LIMBS]); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_sqr_mont_nohw, + (BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS])) +DECLARE_ASM_FUNCTION(void, ecp_nistz256_sqr_mont_adx, + (BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS])) #else -void ecp_nistz256_sqr_mont(BN_ULONG res[P256_LIMBS], - const BN_ULONG a[P256_LIMBS]); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_sqr_mont, + (BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS])) #endif @@ -86,36 +86,39 @@ void ecp_nistz256_sqr_mont(BN_ULONG res[P256_LIMBS], // ecp_nistz256_ord_mul_mont sets `res` to `a` * `b` where inputs and outputs // are in Montgomery form. That is, `res` is `a` * `b` * 2^-256 mod N. #if defined(OPENSSL_X86_64) -void ecp_nistz256_ord_mul_mont_nohw(BN_ULONG res[P256_LIMBS], - const BN_ULONG a[P256_LIMBS], - const BN_ULONG b[P256_LIMBS]); -void ecp_nistz256_ord_mul_mont_adx(BN_ULONG res[P256_LIMBS], - const BN_ULONG a[P256_LIMBS], - const BN_ULONG b[P256_LIMBS]); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_ord_mul_mont_nohw, + (BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS], + const BN_ULONG b[P256_LIMBS])) +DECLARE_ASM_FUNCTION(void, ecp_nistz256_ord_mul_mont_adx, + (BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS], + const BN_ULONG b[P256_LIMBS])) #else -void ecp_nistz256_ord_mul_mont(BN_ULONG res[P256_LIMBS], - const BN_ULONG a[P256_LIMBS], - const BN_ULONG b[P256_LIMBS]); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_ord_mul_mont, + (BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS], + const BN_ULONG b[P256_LIMBS])) #endif // ecp_nistz256_ord_sqr_mont sets `res` to `a`^(2*`rep`) where inputs and // outputs are in Montgomery form. That is, `res` is // (`a` * 2^-256)^(2*`rep`) * 2^256 mod N. #if defined(OPENSSL_X86_64) -void ecp_nistz256_ord_sqr_mont_nohw(BN_ULONG res[P256_LIMBS], - const BN_ULONG a[P256_LIMBS], BN_ULONG rep); -void ecp_nistz256_ord_sqr_mont_adx(BN_ULONG res[P256_LIMBS], - const BN_ULONG a[P256_LIMBS], BN_ULONG rep); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_ord_sqr_mont_nohw, + (BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS], + BN_ULONG rep)) +DECLARE_ASM_FUNCTION(void, ecp_nistz256_ord_sqr_mont_adx, + (BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS], + BN_ULONG rep)) #else -void ecp_nistz256_ord_sqr_mont(BN_ULONG res[P256_LIMBS], - const BN_ULONG a[P256_LIMBS], BN_ULONG rep); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_ord_sqr_mont, + (BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS], + BN_ULONG rep)) #endif // beeu_mod_inverse_vartime sets out = a^-1 mod p using a Euclidean algorithm. // Assumption: 0 < a < p < 2^(256) and p is odd. -int beeu_mod_inverse_vartime(BN_ULONG out[P256_LIMBS], - const BN_ULONG a[P256_LIMBS], - const BN_ULONG p[P256_LIMBS]); +DECLARE_ASM_FUNCTION(int, beeu_mod_inverse_vartime, + (BN_ULONG out[P256_LIMBS], const BN_ULONG a[P256_LIMBS], + const BN_ULONG p[P256_LIMBS])) // P-256 point operations. @@ -141,67 +144,73 @@ typedef struct { // and all zeros (the point at infinity) if `index` is 0. This is done in // constant time. #if defined(OPENSSL_X86_64) -void ecp_nistz256_select_w5_nohw(P256_POINT *val, const P256_POINT in_t[16], - int index); -void ecp_nistz256_select_w5_avx2(P256_POINT *val, const P256_POINT in_t[16], - int index); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_select_w5_nohw, + (P256_POINT * val, const P256_POINT in_t[16], int index)) +DECLARE_ASM_FUNCTION(void, ecp_nistz256_select_w5_avx2, + (P256_POINT * val, const P256_POINT in_t[16], int index)) #else -void ecp_nistz256_select_w5(P256_POINT *val, const P256_POINT in_t[16], - int index); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_select_w5, + (P256_POINT * val, const P256_POINT in_t[16], int index)) #endif // ecp_nistz256_select_w7 sets `*val` to `in_t[index-1]` if 1 <= `index` <= 64 // and all zeros (the point at infinity) if `index` is 0. This is done in // constant time. #if defined(OPENSSL_X86_64) -void ecp_nistz256_select_w7_nohw(P256_POINT_AFFINE *val, - const P256_POINT_AFFINE in_t[64], int index); -void ecp_nistz256_select_w7_avx2(P256_POINT_AFFINE *val, - const P256_POINT_AFFINE in_t[64], int index); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_select_w7_nohw, + (P256_POINT_AFFINE * val, const P256_POINT_AFFINE in_t[64], + int index)) +DECLARE_ASM_FUNCTION(void, ecp_nistz256_select_w7_avx2, + (P256_POINT_AFFINE * val, const P256_POINT_AFFINE in_t[64], + int index)) #else -void ecp_nistz256_select_w7(P256_POINT_AFFINE *val, - const P256_POINT_AFFINE in_t[64], int index); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_select_w7, + (P256_POINT_AFFINE * val, const P256_POINT_AFFINE in_t[64], + int index)) #endif // ecp_nistz256_point_double sets `r` to `a` doubled. #if defined(OPENSSL_X86_64) -void ecp_nistz256_point_double_nohw(P256_POINT *r, const P256_POINT *a); -void ecp_nistz256_point_double_adx(P256_POINT *r, const P256_POINT *a); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_point_double_nohw, + (P256_POINT * r, const P256_POINT *a)) +DECLARE_ASM_FUNCTION(void, ecp_nistz256_point_double_adx, + (P256_POINT * r, const P256_POINT *a)) #else -void ecp_nistz256_point_double(P256_POINT *r, const P256_POINT *a); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_point_double, + (P256_POINT * r, const P256_POINT *a)) #endif // ecp_nistz256_point_add adds `a` to `b` and places the result in `r`. #if defined(OPENSSL_X86_64) -void ecp_nistz256_point_add_nohw(P256_POINT *r, const P256_POINT *a, - const P256_POINT *b); -void ecp_nistz256_point_add_adx(P256_POINT *r, const P256_POINT *a, - const P256_POINT *b); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_point_add_nohw, + (P256_POINT * r, const P256_POINT *a, const P256_POINT *b)) +DECLARE_ASM_FUNCTION(void, ecp_nistz256_point_add_adx, + (P256_POINT * r, const P256_POINT *a, const P256_POINT *b)) #else -void ecp_nistz256_point_add(P256_POINT *r, const P256_POINT *a, - const P256_POINT *b); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_point_add, + (P256_POINT * r, const P256_POINT *a, const P256_POINT *b)) #endif // ecp_nistz256_point_add_affine adds `a` to `b` and places the result in // `r`. `a` and `b` must not represent the same point unless they are both // infinity. #if defined(OPENSSL_X86_64) -void ecp_nistz256_point_add_affine_adx(P256_POINT *r, const P256_POINT *a, - const P256_POINT_AFFINE *b); -void ecp_nistz256_point_add_affine_nohw(P256_POINT *r, const P256_POINT *a, - const P256_POINT_AFFINE *b); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_point_add_affine_adx, + (P256_POINT * r, const P256_POINT *a, + const P256_POINT_AFFINE *b)) +DECLARE_ASM_FUNCTION(void, ecp_nistz256_point_add_affine_nohw, + (P256_POINT * r, const P256_POINT *a, + const P256_POINT_AFFINE *b)) #else -void ecp_nistz256_point_add_affine(P256_POINT *r, const P256_POINT *a, - const P256_POINT_AFFINE *b); +DECLARE_ASM_FUNCTION(void, ecp_nistz256_point_add_affine, + (P256_POINT * r, const P256_POINT *a, + const P256_POINT_AFFINE *b)) #endif -#endif /* !defined(OPENSSL_NO_ASM) && \ - (defined(OPENSSL_X86_64) || defined(OPENSSL_AARCH64)) && \ - !defined(OPENSSL_SMALL) */ +BSSL_NAMESPACE_END - -#if defined(__cplusplus) -} // extern C -#endif +#endif /* !defined(OPENSSL_NO_ASM) && \ + (defined(OPENSSL_X86_64) || defined(OPENSSL_AARCH64)) && \ + !defined(OPENSSL_SMALL) */ #endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_EC_P256_NISTZ_H diff --git a/third_party/boringssl/src/crypto/fipsmodule/entropy/jitter.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/entropy/jitter.cc.inc index ebe3a5c..8c75166 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/entropy/jitter.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/entropy/jitter.cc.inc @@ -32,6 +32,7 @@ #include +#include "../../internal.h" #include "internal.h" #include "sha512.cc.inc" @@ -88,6 +89,11 @@ class MemoryAccessSampler { array_size_ & (array_size_ - 1)) { abort(); } + + if (boringssl_fips_break_test("JITTER_APT")) { + // In this break test, array_[0] is used to keep state. See below. + array_[0] = 0; + } } ~MemoryAccessSampler() { OPENSSL_free(const_cast(array_)); } @@ -104,16 +110,28 @@ class MemoryAccessSampler { } bool Next(uint64_t *out) { - // Perform some memory accesses and measure how long it took. The LCG is - // intended to defeat any CPU predictors and thus expose this code to as - // much system entropy as possible. - for (unsigned i = 0; i < num_samples_; i++) { - // The lower bits of an LCG tend to fall into short cycles and so are - // discarded here. - array_[(lcg_.Next() >> 6) & (array_size_ - 1)] += 1; - } + if (boringssl_fips_break_test("JITTER_RCT")) { + // To break the repetition test a constant value is returned. + *out = 1; + } else if (boringssl_fips_break_test("JITTER_APT")) { + // To break the adaptive test, but not the repetition test, a counter + // that advances every fourth call is returned. Since samples are + // processed by `DeltaSampler`, the tests see 0,0,0,1,... which exceeds + // the APT cutoff (348/512) without tripping the RCT (26). + *out = array_[0] >> 2; + array_[0] += 1; + } else { + // Perform some memory accesses and measure how long it took. The LCG is + // intended to defeat any CPU predictors and thus expose this code to as + // much system entropy as possible. + for (unsigned i = 0; i < num_samples_; i++) { + // The lower bits of an LCG tend to fall into short cycles and so are + // discarded here. + array_[(lcg_.Next() >> 6) & (array_size_ - 1)] += 1; + } - *out = GetTimestamp(); + *out = GetTimestamp(); + } return true; } @@ -226,6 +244,9 @@ class RepetitionCountTest { last_sample_ = sample; } if (count_ >= kThreshold) { +#if defined(BORINGSSL_FIPS_BREAK_TESTS) + fprintf(stderr, "Jitter RCT failure.\n"); +#endif return false; } *out = sample; @@ -351,6 +372,9 @@ class AdaptiveProportionTest { const uint16_t new_count = ++counts_[sample]; if (new_count > kThreshold) { +#if defined(BORINGSSL_FIPS_BREAK_TESTS) + fprintf(stderr, "Jitter APT failure.\n"); +#endif return false; } diff --git a/third_party/boringssl/src/crypto/fipsmodule/keccak/internal.h b/third_party/boringssl/src/crypto/fipsmodule/keccak/internal.h index e7d79b0..d85e86b 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/keccak/internal.h +++ b/third_party/boringssl/src/crypto/fipsmodule/keccak/internal.h @@ -22,8 +22,20 @@ BSSL_NAMESPACE_BEGIN +#define BITS_TO_BYTES(BITS) ((BITS) / 8) +#define SHA3_256_DIGEST_LENGTH BITS_TO_BYTES(256) +#define SHA3_384_DIGEST_LENGTH BITS_TO_BYTES(384) +#define SHA3_512_DIGEST_LENGTH BITS_TO_BYTES(512) +#define SHA3_BLOCK_SIZE(BITS) BITS_TO_BYTES(1600 - 2 * (BITS)) +#define SHA3_256_CBLOCK SHA3_BLOCK_SIZE(256) +#define SHA3_384_CBLOCK SHA3_BLOCK_SIZE(384) +#define SHA3_512_CBLOCK SHA3_BLOCK_SIZE(512) +#define SHAKE128_CBLOCK SHA3_BLOCK_SIZE(128) +#define SHAKE256_CBLOCK SHA3_BLOCK_SIZE(256) + enum boringssl_keccak_config_t : int32_t { boringssl_sha3_256, + boringssl_sha3_384, boringssl_sha3_512, boringssl_shake128, boringssl_shake256, diff --git a/third_party/boringssl/src/crypto/fipsmodule/keccak/keccak.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/keccak/keccak.cc.inc index adb09a2..e808dd5 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/keccak/keccak.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/keccak/keccak.cc.inc @@ -205,6 +205,10 @@ static void keccak_init(struct BORINGSSL_keccak_st *ctx, capacity_bytes = 512 / 8; required_out_len = 32; break; + case boringssl_sha3_384: + capacity_bytes = 768 / 8; + required_out_len = 48; + break; case boringssl_sha3_512: capacity_bytes = 1024 / 8; required_out_len = 64; @@ -235,8 +239,9 @@ static void keccak_init(struct BORINGSSL_keccak_st *ctx, [[maybe_unused]] static bool keccak_can_parallel( enum boringssl_keccak_config_t config) { - return config == boringssl_sha3_256 || config == boringssl_sha3_512 || - config == boringssl_shake128 || config == boringssl_shake256; + return config == boringssl_sha3_256 || config == boringssl_sha3_384 || + config == boringssl_sha3_512 || config == boringssl_shake128 || + config == boringssl_shake256; } static bool keccak_is_cshake(enum boringssl_keccak_config_t config) { @@ -430,6 +435,7 @@ void bssl::BORINGSSL_cshake(uint8_t *out, size_t out_len, const uint8_t *in, static uint8_t keccak_terminator(struct BORINGSSL_keccak_st *ctx) { switch (ctx->config) { case boringssl_sha3_256: + case boringssl_sha3_384: case boringssl_sha3_512: return 0x06; case boringssl_shake128: diff --git a/third_party/boringssl/src/crypto/fipsmodule/mldsa/mldsa.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/mldsa/mldsa.cc.inc index e0fa058..3560ce7 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/mldsa/mldsa.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/mldsa/mldsa.cc.inc @@ -43,9 +43,11 @@ namespace mldsa { namespace { namespace fips { + void ensure_keygen_self_test(); void ensure_sign_self_test(); void ensure_verify_self_test(); + } // namespace fips constexpr int kDegree = 256; @@ -305,7 +307,7 @@ inline uint32_t reduce_once(uint32_t x) { // selects with the same condition into a branch instead of CMOV/CSEL. This // condition does not occur in ML-DSA, so omitting it seems to be generally // safe. However, see `coefficient_from_nibble`. - return (mask & x) | (~mask & subtracted); + return subtracted + (mask & kPrime); } // reduce_from_u32 returns `x mod kPrime`. `x` can be any `uint32_t`. @@ -359,7 +361,7 @@ inline uint32_t mod_sub(uint32_t a, uint32_t b) { // return r < 0 ? r + kPrime : r; uint32_t mask = 0u - (r >> 31); // See `reduce_once` for why this does not have a value barrier. - return (mask & (r + kPrime)) | (~mask & r); + return r + (mask & kPrime); } inline void scalar_add(scalar *out, const scalar *lhs, const scalar *rhs) { @@ -544,15 +546,24 @@ inline void vector_inverse_ntt_montgomery(vector *a) { } } +// matrix_mult_montgomery sets `out` to `m` times `a`, both in the number +// theoretically transformed state and fully reduced. Like +// `scalar_mult_montgomery`, each term gains an extra R^-1 factor. template inline void matrix_mult_montgomery(vector *out, const matrix *m, const vector *a) { - vector_zero(out); + // Rather than reducing every product, sum the L products for each + // coefficient and reduce once. The sum is at most L * (kPrime - 1)^2, which + // is within the range `reduce_montgomery` accepts. + static_assert(uint64_t{L} * (kPrime - 1) * (kPrime - 1) <= + (uint64_t{kPrime} << 32)); for (int i = 0; i < K; i++) { - for (int j = 0; j < L; j++) { - scalar product; - scalar_mult_montgomery(&product, &m->v[i][j], &a->v[j]); - scalar_add(&out->v[i], &out->v[i], &product); + for (int n = 0; n < kDegree; n++) { + uint64_t sum = 0; + for (int j = 0; j < L; j++) { + sum += uint64_t{m->v[i][j].c[n]} * a->v[j].c[n]; + } + out->v[i].c[n] = reduce_montgomery(sum); } } } @@ -615,7 +626,7 @@ inline uint32_t high_bits(uint32_t x) { r1 = (r1 * 11275 + (1 << 23)) >> 24; // For corner-case r1 = (Q-1)/(2 gamma2) = 44, we have to set r1=0. - r1 ^= ((uint32_t)(((int32_t)(43 - r1)) >> 31)) & r1; + r1 ^= ((uint32_t)(((int32_t)(43 - r1)) >> 31)) & 44u; } return r1; } @@ -1385,6 +1396,19 @@ inline void scalar_uniform_x4(scalar *out[4], } #endif +// Initializes `ctx` to output the bytes that `ExpandMask` decodes into the +// scalar at position `index`. +inline void sample_mask_keccak_init(struct BORINGSSL_keccak_st *ctx, + const uint8_t rho_prime[kRhoPrimeBytes], + size_t index) { + BORINGSSL_keccak_init(ctx, boringssl_shake256); + BORINGSSL_keccak_absorb(ctx, rho_prime, kRhoPrimeBytes); + uint8_t index_buf[2]; + index_buf[0] = static_cast(index); + index_buf[1] = static_cast(index >> 8); + BORINGSSL_keccak_absorb(ctx, index_buf, 2); +} + // FIPS 204, Algorithm 34 (`ExpandMask`), but just a single step. template inline void scalar_sample_mask(scalar *out, @@ -1392,16 +1416,49 @@ inline void scalar_sample_mask(scalar *out, size_t index) { uint8_t buf[scalar_le_gamma1_bytes()]; struct BORINGSSL_keccak_st ctx; - BORINGSSL_keccak_init(&ctx, boringssl_shake256); - BORINGSSL_keccak_absorb(&ctx, rho_prime, kRhoPrimeBytes); - uint8_t index_buf[2]; - index_buf[0] = static_cast(index); - index_buf[1] = static_cast(index >> 8); - BORINGSSL_keccak_absorb(&ctx, index_buf, 2); + sample_mask_keccak_init(&ctx, rho_prime, index); BORINGSSL_keccak_squeeze(&ctx, buf, sizeof(buf)); scalar_decode_signed() + 1, gamma1()>(out, buf); } +#if defined(HAVE_KECCAK_X2) +// Performs `scalar_sample_mask` for `index` and `index + 1` in parallel. +template +inline void scalar_sample_mask_x2(scalar *out[2], + const uint8_t rho_prime[kRhoPrimeBytes], + size_t index) { + BORINGSSL_keccak_st keccak_ctx[2]; + for (int k = 0; k < 2; k++) { + sample_mask_keccak_init(&keccak_ctx[k], rho_prime, index + k); + } + uint8_t buf[2][scalar_le_gamma1_bytes()]; + uint8_t *bufs[] = {buf[0], buf[1]}; + BORINGSSL_keccak_squeeze_x2(keccak_ctx, bufs, sizeof(buf[0])); + for (int k = 0; k < 2; k++) { + scalar_decode_signed() + 1, gamma1()>(out[k], buf[k]); + } +} +#endif + +#if defined(HAVE_KECCAK_X4) +// Performs `scalar_sample_mask` for `index` through `index + 3` in parallel. +template +inline void scalar_sample_mask_x4(scalar *out[4], + const uint8_t rho_prime[kRhoPrimeBytes], + size_t index) { + BORINGSSL_keccak_st keccak_ctx[4]; + for (int k = 0; k < 4; k++) { + sample_mask_keccak_init(&keccak_ctx[k], rho_prime, index + k); + } + uint8_t buf[4][scalar_le_gamma1_bytes()]; + uint8_t *bufs[] = {buf[0], buf[1], buf[2], buf[3]}; + BORINGSSL_keccak_squeeze_x4(keccak_ctx, bufs, sizeof(buf[0])); + for (int k = 0; k < 4; k++) { + scalar_decode_signed() + 1, gamma1()>(out[k], buf[k]); + } +} +#endif + // FIPS 204, Algorithm 29 (`SampleInBall`). inline void scalar_sample_in_ball_vartime(scalar *out, const uint8_t *seed, int len, int tau) { @@ -1630,9 +1687,27 @@ inline void vector_expand_mask(vector *out, size_t kappa) { assert(kappa + L <= 0x10000); - for (int i = 0; i < L; i++) { - size_t index = kappa + i; - scalar_sample_mask(&out->v[i], rho_prime, index); + // Each scalar is sampled independently, so use the parallel Keccak + // implementations where possible. + int i = 0; +#if defined(HAVE_KECCAK_X4) + if (BORINGSSL_have_keccak_x4()) { + for (; i + 4 <= L; i += 4) { + scalar *outs[] = {&out->v[i], &out->v[i + 1], &out->v[i + 2], + &out->v[i + 3]}; + scalar_sample_mask_x4(outs, rho_prime, kappa + i); + } + } +#endif +#if defined(HAVE_KECCAK_X2) + for (; i + 2 <= L; i += 2) { + scalar *outs[] = {&out->v[i], &out->v[i + 1]}; + scalar_sample_mask_x2(outs, rho_prime, kappa + i); + } +#endif + + for (; i < L; i++) { + scalar_sample_mask(&out->v[i], rho_prime, kappa + i); } } diff --git a/third_party/boringssl/src/crypto/fipsmodule/mlkem/mlkem.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/mlkem/mlkem.cc.inc index 8071a42..7b2cca7 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/mlkem/mlkem.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/mlkem/mlkem.cc.inc @@ -43,9 +43,11 @@ namespace mlkem { namespace { namespace fips { + void ensure_keygen_self_test(); void ensure_encap_self_test(); void ensure_decap_self_test(); + } // namespace fips // See @@ -220,7 +222,7 @@ inline uint16_t reduce_once(uint16_t x) { // selects with the same condition into a branch instead of CMOV/CSEL. This // condition does not occur in ML-KEM, so omitting it seems to be safe so far, // but see `scalar_centered_binomial_distribution_eta_2_with_prf`. - return (mask & x) | (~mask & subtracted); + return subtracted + (mask & kPrime); } // reduce_partial returns a number equivalent to x mod kPrime. The output is @@ -236,13 +238,6 @@ inline uint32_t reduce_partial(uint32_t x) { // `uint32_t`. inline uint16_t reduce(uint32_t x) { return reduce_once(reduce_partial(x)); } -inline void scalar_zero(scalar *out) { OPENSSL_memset(out, 0, sizeof(*out)); } - -template -inline void vector_zero(vector *out) { - OPENSSL_memset(out->v, 0, sizeof(scalar) * RANK); -} - // In place number theoretic transform of a given scalar. // Note that MLKEM's kPrime 3329 does not have a 512th root of unity, so this // transform leaves off the last iteration of the usual FFT code, with the 128 @@ -376,19 +371,75 @@ inline void scalar_sub(scalar *lhs, const scalar *rhs) { // 3329 does not have a 512th root of unity, this means we have to interpret // the 2*ith and (2*i+1)th entries of the scalar as elements of GF(3329)[X]/(X^2 // - 17^(2*bitreverse(i)+1)) The value of 17^(2*bitreverse(i)+1) mod 3329 is -// stored in the precomputed `kModRoots` table. Note that our Barrett transform -// only allows us to multiply two reduced numbers together, so we need some -// intermediate reduction steps, even if an uint64_t could hold 3 multiplied -// numbers. -inline void scalar_mult(scalar *out, const scalar *lhs, const scalar *rhs) { +// stored in the precomputed `kModRoots` table. +// +// Writing the two elements as a0 + a1*X and b0 + b1*X, and the root as zeta, +// their product is (a0*b0 + a1*(b1*zeta)) + (a0*b1 + a1*b0)*X. Products are +// only ever needed as terms of a sum, in matrix-vector and inner products, so +// they are computed lazily: +// +// - b1*zeta mod kPrime only depends on the right-hand side, which is shared by +// every row of a matrix-vector product. It is computed once per scalar and +// stored in a `scalar_mulcache`. This is the "asymmetric multiplication" of +// https://eprint.iacr.org/2021/986. +// - The terms are summed in a `scalar_accumulator` without any modular +// reduction, and the sum is reduced once, at the end. + +// scalar_mulcache holds, for a scalar b, b[2*i+1] * kModRoots[i] mod kPrime. +struct scalar_mulcache { + // On every function entry and exit, 0 <= c < kPrime. + uint16_t c[DEGREE / 2]; +}; + +template +struct vector_mulcache { + scalar_mulcache v[RANK]; +}; + +inline void scalar_mulcache_compute(scalar_mulcache *out, const scalar *b) { for (int i = 0; i < DEGREE / 2; i++) { - uint32_t real_real = (uint32_t)lhs->c[2 * i] * rhs->c[2 * i]; - uint32_t img_img = (uint32_t)lhs->c[2 * i + 1] * rhs->c[2 * i + 1]; - uint32_t real_img = (uint32_t)lhs->c[2 * i] * rhs->c[2 * i + 1]; - uint32_t img_real = (uint32_t)lhs->c[2 * i + 1] * rhs->c[2 * i]; - out->c[2 * i] = - reduce(real_real + (uint32_t)reduce(img_img) * kModRoots[i]); - out->c[2 * i + 1] = reduce(img_real + real_img); + out->c[i] = reduce(uint32_t{b->c[2 * i + 1]} * kModRoots[i]); + } +} + +template +inline void vector_mulcache_compute(vector_mulcache *out, + const vector *b) { + for (int i = 0; i < RANK; i++) { + scalar_mulcache_compute(&out->v[i], &b->v[i]); + } +} + +// scalar_accumulator holds a sum of products of scalars, not reduced mod +// kPrime. +struct scalar_accumulator { + uint32_t c[DEGREE]; +}; + +// Scalars are fully reduced, so each product adds at most 2 * (kPrime - 1)^2 to +// each element of a `scalar_accumulator`. Sums have at most RANK1024 terms, so +// the elements never overflow. +static_assert(uint64_t{RANK1024} * 2 * (kPrime - 1) * (kPrime - 1) <= + UINT32_MAX); + +// scalar_mult_accumulate adds `lhs * rhs` to `acc`. `rhs_cache` must have been +// computed from `rhs`. +inline void scalar_mult_accumulate(scalar_accumulator *acc, const scalar *lhs, + const scalar *rhs, + const scalar_mulcache *rhs_cache) { + for (int i = 0; i < DEGREE / 2; i++) { + const uint32_t lhs_real = lhs->c[2 * i]; + const uint32_t lhs_img = lhs->c[2 * i + 1]; + acc->c[2 * i] += lhs_real * rhs->c[2 * i] + lhs_img * rhs_cache->c[i]; + acc->c[2 * i + 1] += lhs_real * rhs->c[2 * i + 1] + lhs_img * rhs->c[2 * i]; + } +} + +// scalar_from_accumulator sets `out` to `acc` mod kPrime. +inline void scalar_from_accumulator(scalar *out, + const scalar_accumulator *acc) { + for (int i = 0; i < DEGREE; i++) { + out->c[i] = reduce(acc->c[i]); } } @@ -401,39 +452,39 @@ inline void vector_add(vector *lhs, const vector *rhs) { template inline void matrix_mult(vector *out, const matrix *m, - const vector *a) { - vector_zero(out); + const vector *a, + const vector_mulcache *a_cache) { for (int i = 0; i < RANK; i++) { + scalar_accumulator acc = {}; for (int j = 0; j < RANK; j++) { - scalar product; - scalar_mult(&product, &m->v[i][j], &a->v[j]); - scalar_add(&out->v[i], &product); + scalar_mult_accumulate(&acc, &m->v[i][j], &a->v[j], &a_cache->v[j]); } + scalar_from_accumulator(&out->v[i], &acc); } } template inline void matrix_mult_transpose(vector *out, const matrix *m, - const vector *a) { - vector_zero(out); + const vector *a, + const vector_mulcache *a_cache) { for (int i = 0; i < RANK; i++) { + scalar_accumulator acc = {}; for (int j = 0; j < RANK; j++) { - scalar product; - scalar_mult(&product, &m->v[j][i], &a->v[j]); - scalar_add(&out->v[i], &product); + scalar_mult_accumulate(&acc, &m->v[j][i], &a->v[j], &a_cache->v[j]); } + scalar_from_accumulator(&out->v[i], &acc); } } template inline void scalar_inner_product(scalar *out, const vector *lhs, - const vector *rhs) { - scalar_zero(out); + const vector *rhs, + const vector_mulcache *rhs_cache) { + scalar_accumulator acc = {}; for (int i = 0; i < RANK; i++) { - scalar product; - scalar_mult(&product, &lhs->v[i], &rhs->v[i]); - scalar_add(out, &product); + scalar_mult_accumulate(&acc, &lhs->v[i], &rhs->v[i], &rhs_cache->v[i]); } + scalar_from_accumulator(out, &acc); } inline void scalar_from_keccak_block_vartime(scalar *out, int *done, @@ -1088,11 +1139,13 @@ inline void decrypt_cpa(uint8_t out[32], const private_key *priv, vector_decode(&u, ciphertext); vector_decompress(&u, du); vector_ntt(&u); + vector_mulcache u_cache; + vector_mulcache_compute(&u_cache, &u); scalar v; scalar_decode(&v, ciphertext + compressed_vector_size(RANK)); scalar_decompress(&v, dv); scalar mask; - scalar_inner_product(&mask, &priv->s, &u); + scalar_inner_product(&mask, &priv->s, &u, &u_cache); scalar_inverse_ntt(&mask); scalar_sub(&v, &mask); scalar_compress(&v, 1); @@ -1141,7 +1194,9 @@ void mlkem_generate_key_external_seed_no_self_test( vector error; vector_generate_secret_eta_2(&error, &counter, sigma); vector_ntt(&error); - matrix_mult_transpose(&priv->pub.t, &priv->pub.m, &priv->s); + vector_mulcache s_cache; + vector_mulcache_compute(&s_cache, &priv->s); + matrix_mult_transpose(&priv->pub.t, &priv->pub.m, &priv->s, &s_cache); vector_add(&priv->pub.t, &error); // t is part of the public key and thus is public. CONSTTIME_DECLASSIFY(&priv->pub.t, sizeof(priv->pub.t)); @@ -1180,6 +1235,8 @@ void encrypt_cpa(uint8_t *out, const mlkem::public_key *pub, mlkem::vector secret; vector_generate_secret_eta_2(&secret, &counter, randomness); vector_ntt(&secret); + mlkem::vector_mulcache secret_cache; + vector_mulcache_compute(&secret_cache, &secret); mlkem::vector error; vector_generate_secret_eta_2(&error, &counter, randomness); uint8_t input[33]; @@ -1188,11 +1245,11 @@ void encrypt_cpa(uint8_t *out, const mlkem::public_key *pub, mlkem::scalar scalar_error; scalar_centered_binomial_distribution_eta_2_with_prf(&scalar_error, input); mlkem::vector u; - matrix_mult(&u, &pub->m, &secret); + matrix_mult(&u, &pub->m, &secret, &secret_cache); vector_inverse_ntt(&u); vector_add(&u, &error); mlkem::scalar v; - scalar_inner_product(&v, &pub->t, &secret); + scalar_inner_product(&v, &pub->t, &secret, &secret_cache); scalar_inverse_ntt(&v); scalar_add(&v, &scalar_error); mlkem::scalar expanded_message; @@ -1494,6 +1551,7 @@ void ensure_encap_self_test() {} void ensure_decap_self_test() {} #endif + } // namespace fips } // namespace @@ -1516,8 +1574,8 @@ bcm_status bssl::BCM_mlkem768_check_fips( uint8_t shared_secret2[MLKEM_SHARED_SECRET_BYTES]; mlkem::mlkem_decap_no_self_test(shared_secret2, ciphertext, priv); - if (CRYPTO_memcmp(shared_secret, shared_secret2, sizeof(shared_secret)) != - 0) { + if (constant_time_declassify_int(CRYPTO_memcmp(shared_secret, shared_secret2, + sizeof(shared_secret)) != 0)) { return bcm_status::failure; } return bcm_status::approved; @@ -1580,8 +1638,8 @@ bcm_status bssl::BCM_mlkem1024_check_fips( uint8_t shared_secret2[MLKEM_SHARED_SECRET_BYTES]; mlkem::mlkem_decap_no_self_test(shared_secret2, ciphertext, priv); - if (CRYPTO_memcmp(shared_secret, shared_secret2, sizeof(shared_secret)) != - 0) { + if (constant_time_declassify_int(CRYPTO_memcmp(shared_secret, shared_secret2, + sizeof(shared_secret)) != 0)) { return bcm_status::failure; } return bcm_status::approved; diff --git a/third_party/boringssl/src/crypto/fipsmodule/rand/rand.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/rand/rand.cc.inc index 5d4fc9f..839a03f 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/rand/rand.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/rand/rand.cc.inc @@ -381,8 +381,8 @@ bcm_infallible bssl::BCM_rand_bytes_with_additional_data( !CRYPTO_set_thread_local(OPENSSL_THREAD_LOCAL_RAND, state, rand_thread_state_free)) { // If the system is out of memory, use an ephemeral state on the - // stack. - Delete(state); + // stack. `rand_thread_state_free` has already been called by + // `CRYPTO_set_thread_local` on failure. state = &stack_state; } diff --git a/third_party/boringssl/src/crypto/fipsmodule/rsa/rsa.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/rsa/rsa.cc.inc index edec7ac..cf406b2 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/rsa/rsa.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/rsa/rsa.cc.inc @@ -31,7 +31,6 @@ #include "../../internal.h" #include "../../mem_internal.h" -#include "../bcm_interface.h" #include "../bn/internal.h" #include "../delocate.h" #include "internal.h" @@ -222,6 +221,13 @@ int RSA_up_ref(RSA *rsa) { return 1; } +RSA *RSA_dup_ref(const RSA *rsa) { + if (rsa == nullptr) { + return nullptr; + } + return FromOpaque(rsa)->DupRefInternal(); +} + unsigned RSA_bits(const RSA *rsa) { return BN_num_bits(FromOpaque(rsa)->n.get()); } diff --git a/third_party/boringssl/src/crypto/fipsmodule/service_indicator/internal.h b/third_party/boringssl/src/crypto/fipsmodule/service_indicator/internal.h index a46b1e0..c26678b 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/service_indicator/internal.h +++ b/third_party/boringssl/src/crypto/fipsmodule/service_indicator/internal.h @@ -62,6 +62,7 @@ void FIPS_service_indicator_unlock_state(); void AEAD_GCM_verify_service_indicator(const EVP_AEAD_CTX *ctx); void AEAD_CCM_verify_service_indicator(const EVP_AEAD_CTX *ctx); +void CMAC_verify_service_indicator(const EVP_CIPHER_CTX *ctx); void EC_KEY_keygen_verify_service_indicator(const EC_KEY *eckey); void ECDH_verify_service_indicator(const EC_KEY *ec_key); void EVP_Cipher_verify_service_indicator(const EVP_CIPHER_CTX *ctx); @@ -84,6 +85,9 @@ inline void AEAD_GCM_verify_service_indicator( inline void AEAD_CCM_verify_service_indicator( [[maybe_unused]] const EVP_AEAD_CTX *ctx) {} +inline void CMAC_verify_service_indicator( + [[maybe_unused]] const EVP_CIPHER_CTX *ctx) {} + inline void EC_KEY_keygen_verify_service_indicator( [[maybe_unused]] const EC_KEY *eckey) {} diff --git a/third_party/boringssl/src/crypto/fipsmodule/service_indicator/service_indicator.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/service_indicator/service_indicator.cc.inc index 20b2b0c..3e7e1a8 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/service_indicator/service_indicator.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/service_indicator/service_indicator.cc.inc @@ -230,12 +230,11 @@ static void evp_md_ctx_verify_service_indicator(const EVP_MD_CTX *ctx, } // The approved RSA key sizes for signing are 2048, 3072 and 4096 bits. - // Note: `EVP_PKEY_size` returns the size in bytes. - size_t pkey_size = EVP_PKEY_size(FromOpaque(ctx->pctx)->pkey.get()); + const int pkey_bits = EVP_PKEY_bits(pkey); // Check if the MD type and the RSA key size are approved. if (md_ok(md_type) && - (pkey_size == 256 || pkey_size == 384 || pkey_size == 512)) { + (pkey_bits == 2048 || pkey_bits == 3072 || pkey_bits == 4096)) { FIPS_service_indicator_update_state(); } } else if (pkey_type == EVP_PKEY_EC) { @@ -252,6 +251,16 @@ err: ERR_clear_error(); } +void bssl::CMAC_verify_service_indicator(const EVP_CIPHER_CTX *ctx) { + // Only AES-128 and AES-256 are tested with ACVP for CMAC. + switch (EVP_CIPHER_CTX_nid(ctx)) { + case NID_aes_128_cbc: + case NID_aes_256_cbc: + FIPS_service_indicator_update_state(); + break; + } +} + void bssl::EC_KEY_keygen_verify_service_indicator(const EC_KEY *eckey) { if (is_ec_fips_approved(EC_GROUP_get_curve_name(EC_KEY_get0_group(eckey)))) { FIPS_service_indicator_update_state(); diff --git a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/fors.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/fors.cc.inc index dafceda..2f16788 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/fors.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/fors.cc.inc @@ -53,14 +53,15 @@ static void fors_base_b(const slh_dsa_config *config, uint32_t *indices, // Implements Algorithm 14: fors_skGen function (page 29) void bssl::slhdsa_fors_sk_gen(const slh_dsa_config *config, uint8_t *fors_sk, uint32_t idx, const uint8_t *sk_seed, - const uint8_t *pk_seed, uint8_t addr[32]) { + const slhdsa_hash_ctx *hash_ctx, + uint8_t addr[32]) { uint8_t sk_addr[32]; OPENSSL_memcpy(sk_addr, addr, sizeof(sk_addr)); slhdsa_set_type(config, sk_addr, SLHDSA_ADDR_TYPE_FORSPRF); slhdsa_copy_keypair_addr(config, sk_addr, addr); slhdsa_set_tree_index(config, sk_addr, idx); - slhdsa_thash_prf(config, fors_sk, pk_seed, sk_seed, sk_addr); + slhdsa_thash_prf(config, fors_sk, hash_ctx, sk_seed, sk_addr); } // Implements Algorithm 15: fors_node function (page 30) @@ -68,7 +69,8 @@ void bssl::slhdsa_fors_treehash(const slh_dsa_config *config, uint8_t *root_node, const uint8_t *sk_seed, uint32_t i /*target node index*/, uint32_t z /*target node height*/, - const uint8_t *pk_seed, uint8_t addr[32]) { + const slhdsa_hash_ctx *hash_ctx, + uint8_t addr[32]) { BSSL_CHECK(z <= config->fors_height); const uint32_t nodes_in_tree = 1u << (config->fors_height - z); BSSL_CHECK(i < (uint32_t)(config->fors_trees * nodes_in_tree)); @@ -77,24 +79,24 @@ void bssl::slhdsa_fors_treehash(const slh_dsa_config *config, uint8_t sk[SLHDSA_MAX_N]; slhdsa_set_tree_height(config, addr, 0); slhdsa_set_tree_index(config, addr, i); - slhdsa_fors_sk_gen(config, sk, i, sk_seed, pk_seed, addr); - slhdsa_thash_f(config, root_node, sk, pk_seed, addr); + slhdsa_fors_sk_gen(config, sk, i, sk_seed, hash_ctx, addr); + slhdsa_thash_f(config, root_node, sk, hash_ctx, addr); } else { // Stores left node and right node. uint8_t nodes[2 * SLHDSA_MAX_N]; - slhdsa_fors_treehash(config, nodes, sk_seed, 2 * i, z - 1, pk_seed, addr); + slhdsa_fors_treehash(config, nodes, sk_seed, 2 * i, z - 1, hash_ctx, addr); slhdsa_fors_treehash(config, nodes + config->n, sk_seed, 2 * i + 1, z - 1, - pk_seed, addr); + hash_ctx, addr); slhdsa_set_tree_height(config, addr, z); slhdsa_set_tree_index(config, addr, i); - slhdsa_thash_h(config, root_node, nodes, pk_seed, addr); + slhdsa_thash_h(config, root_node, nodes, hash_ctx, addr); } } // Implements Algorithm 16: fors_sign function (page 31) void bssl::slhdsa_fors_sign(const slh_dsa_config *config, uint8_t *fors_sig, const uint8_t *message, const uint8_t *sk_seed, - const uint8_t *pk_seed, uint8_t addr[32]) { + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]) { uint32_t indices[SLHDSA_MAX_FORS_TREES]; BSSL_CHECK(config->fors_trees <= SLHDSA_MAX_FORS_TREES); BSSL_CHECK(config->fors_height <= SLHDSA_MAX_FORS_HEIGHT); @@ -111,13 +113,13 @@ void bssl::slhdsa_fors_sign(const slh_dsa_config *config, uint8_t *fors_sig, uint8_t *tree_sig = fors_sig + i * node_stride; slhdsa_fors_sk_gen(config, tree_sig, i * (1u << config->fors_height) + indices[i], sk_seed, - pk_seed, addr); + hash_ctx, addr); for (uint32_t j = 0; j < config->fors_height; ++j) { const size_t sibling = (indices[i] >> j) ^ 1u; // Write the FORS auth path element to the correct position. slhdsa_fors_treehash(config, tree_sig + (j + 1) * n, sk_seed, i * (1u << (config->fors_height - j)) + sibling, j, - pk_seed, addr); + hash_ctx, addr); } } } @@ -126,7 +128,8 @@ void bssl::slhdsa_fors_sign(const slh_dsa_config *config, uint8_t *fors_sig, void bssl::slhdsa_fors_pk_from_sig(const slh_dsa_config *config, uint8_t *fors_pk, const uint8_t *fors_sig, const uint8_t *message, - const uint8_t *pk_seed, uint8_t addr[32]) { + const slhdsa_hash_ctx *hash_ctx, + uint8_t addr[32]) { uint32_t indices[SLHDSA_MAX_FORS_TREES]; uint8_t tmp[2 * SLHDSA_MAX_N]; uint8_t roots[SLHDSA_MAX_FORS_TREES * SLHDSA_MAX_N]; @@ -149,7 +152,7 @@ void bssl::slhdsa_fors_pk_from_sig(const slh_dsa_config *config, uint32_t index = i * (1ULL << config->fors_height) + indices[i]; slhdsa_set_tree_index(config, addr, index); - slhdsa_thash_f(config, nodes, tree_sig, pk_seed, addr); + slhdsa_thash_f(config, nodes, tree_sig, hash_ctx, addr); for (uint32_t j = 0; j < config->fors_height; ++j) { slhdsa_set_tree_height(config, addr, j + 1); @@ -160,11 +163,11 @@ void bssl::slhdsa_fors_pk_from_sig(const slh_dsa_config *config, if (((indices[i] >> j) & 1) == 0) { OPENSSL_memcpy(tmp, nodes, n); OPENSSL_memcpy(tmp + n, auth + j * n, n); - slhdsa_thash_h(config, nodes + n, tmp, pk_seed, addr); + slhdsa_thash_h(config, nodes + n, tmp, hash_ctx, addr); } else { OPENSSL_memcpy(tmp, auth + j * n, n); OPENSSL_memcpy(tmp + n, nodes, n); - slhdsa_thash_h(config, nodes + n, tmp, pk_seed, addr); + slhdsa_thash_h(config, nodes + n, tmp, hash_ctx, addr); } OPENSSL_memcpy(nodes, nodes + n, n); } @@ -175,5 +178,5 @@ void bssl::slhdsa_fors_pk_from_sig(const slh_dsa_config *config, OPENSSL_memcpy(forspk_addr, addr, sizeof(forspk_addr)); slhdsa_set_type(config, forspk_addr, SLHDSA_ADDR_TYPE_FORSPK); slhdsa_copy_keypair_addr(config, forspk_addr, addr); - slhdsa_thash_tk(config, fors_pk, roots, pk_seed, forspk_addr); + slhdsa_thash_tk(config, fors_pk, roots, hash_ctx, forspk_addr); } diff --git a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/fors.h b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/fors.h index f123a22..9963778 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/fors.h +++ b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/fors.h @@ -16,6 +16,7 @@ #define OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_FORS_H #include "./params.h" +#include "./thash.h" BSSL_NAMESPACE_BEGIN @@ -23,25 +24,25 @@ BSSL_NAMESPACE_BEGIN // Implements Algorithm 14: fors_skGen function (page 29) void slhdsa_fors_sk_gen(const slh_dsa_config *config, uint8_t *fors_sk, uint32_t idx, const uint8_t *sk_seed, - const uint8_t *pk_seed, uint8_t addr[32]); + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]); // Implements Algorithm 15: fors_node function (page 30) void slhdsa_fors_treehash(const slh_dsa_config *config, uint8_t *root_node, const uint8_t *sk_seed, uint32_t i /*target node index*/, uint32_t z /*target node height*/, - const uint8_t *pk_seed, + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]); // Implements Algorithm 16: fors_sign function (page 31) void slhdsa_fors_sign(const slh_dsa_config *config, uint8_t *fors_sig, const uint8_t *message, const uint8_t *sk_seed, - const uint8_t *pk_seed, uint8_t addr[32]); + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]); // Implements Algorithm 17: fors_pkFromSig function (page 32) void slhdsa_fors_pk_from_sig(const slh_dsa_config *config, uint8_t *fors_pk, const uint8_t *fors_sig, const uint8_t *message, - const uint8_t *pk_seed, uint8_t addr[32]); + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]); BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/merkle.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/merkle.cc.inc index 84602c8..243982e 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/merkle.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/merkle.cc.inc @@ -29,58 +29,60 @@ using namespace bssl; // Implements Algorithm 9: xmss_node function (page 23) void bssl::slhdsa_treehash(const slh_dsa_config *config, uint8_t *out_pk, const uint8_t *sk_seed, uint32_t i, uint32_t z, - const uint8_t *pk_seed, uint8_t addr[32]) { + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]) { BSSL_CHECK(z <= config->tree_height); BSSL_CHECK(i < (uint32_t)(1u << (config->tree_height - z))); if (z == 0) { slhdsa_set_type(config, addr, SLHDSA_ADDR_TYPE_WOTS); slhdsa_set_keypair_addr(config, addr, i); - slhdsa_wots_pk_gen(config, out_pk, sk_seed, pk_seed, addr); + slhdsa_wots_pk_gen(config, out_pk, sk_seed, hash_ctx, addr); } else { // Stores left node and right node. uint8_t nodes[2 * SLHDSA_MAX_N]; - slhdsa_treehash(config, nodes, sk_seed, 2 * i, z - 1, pk_seed, addr); + slhdsa_treehash(config, nodes, sk_seed, 2 * i, z - 1, hash_ctx, addr); slhdsa_treehash(config, nodes + config->n, sk_seed, 2 * i + 1, z - 1, - pk_seed, addr); + hash_ctx, addr); slhdsa_set_type(config, addr, SLHDSA_ADDR_TYPE_HASHTREE); slhdsa_set_tree_height(config, addr, z); slhdsa_set_tree_index(config, addr, i); - slhdsa_thash_h(config, out_pk, nodes, pk_seed, addr); + slhdsa_thash_h(config, out_pk, nodes, hash_ctx, addr); } } // Implements Algorithm 10: xmss_sign function (page 24) void bssl::slhdsa_xmss_sign(const slh_dsa_config *config, uint8_t *sig, const uint8_t *msg, unsigned int idx, - const uint8_t *sk_seed, const uint8_t *pk_seed, + const uint8_t *sk_seed, + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]) { // Build authentication path const size_t wots_bytes = slhdsa_wots_bytes(config); const size_t n = config->n; for (size_t j = 0; j < config->tree_height; ++j) { unsigned int k = (idx >> j) ^ 1; - slhdsa_treehash(config, sig + wots_bytes + j * n, sk_seed, k, j, pk_seed, + slhdsa_treehash(config, sig + wots_bytes + j * n, sk_seed, k, j, hash_ctx, addr); } // Compute WOTS+ signature slhdsa_set_type(config, addr, SLHDSA_ADDR_TYPE_WOTS); slhdsa_set_keypair_addr(config, addr, idx); - slhdsa_wots_sign(config, sig, msg, sk_seed, pk_seed, addr); + slhdsa_wots_sign(config, sig, msg, sk_seed, hash_ctx, addr); } // Implements Algorithm 11: xmss_pkFromSig function (page 25) void bssl::slhdsa_xmss_pk_from_sig(const slh_dsa_config *config, uint8_t *root, const uint8_t *xmss_sig, unsigned int idx, - const uint8_t *msg, const uint8_t *pk_seed, + const uint8_t *msg, + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]) { // Stores node[0] and node[1] from Algorithm 11 slhdsa_set_type(config, addr, SLHDSA_ADDR_TYPE_WOTS); slhdsa_set_keypair_addr(config, addr, idx); uint8_t node[2 * SLHDSA_MAX_N]; const size_t n = config->n; - slhdsa_wots_pk_from_sig(config, node, xmss_sig, msg, pk_seed, addr); + slhdsa_wots_pk_from_sig(config, node, xmss_sig, msg, hash_ctx, addr); slhdsa_set_type(config, addr, SLHDSA_ADDR_TYPE_HASHTREE); slhdsa_set_tree_index(config, addr, idx); @@ -94,13 +96,13 @@ void bssl::slhdsa_xmss_pk_from_sig(const slh_dsa_config *config, uint8_t *root, slhdsa_get_tree_index(config, addr) >> 1); OPENSSL_memcpy(tmp, node, n); OPENSSL_memcpy(tmp + n, auth + k * n, n); - slhdsa_thash_h(config, node + n, tmp, pk_seed, addr); + slhdsa_thash_h(config, node + n, tmp, hash_ctx, addr); } else { slhdsa_set_tree_index(config, addr, (slhdsa_get_tree_index(config, addr) - 1) >> 1); OPENSSL_memcpy(tmp, auth + k * n, n); OPENSSL_memcpy(tmp + n, node, n); - slhdsa_thash_h(config, node + n, tmp, pk_seed, addr); + slhdsa_thash_h(config, node + n, tmp, hash_ctx, addr); } OPENSSL_memcpy(node, node + n, n); } @@ -111,14 +113,14 @@ void bssl::slhdsa_xmss_pk_from_sig(const slh_dsa_config *config, uint8_t *root, void bssl::slhdsa_ht_sign(const slh_dsa_config *config, uint8_t *sig, const uint8_t *message, uint64_t idx_tree, uint32_t idx_leaf, const uint8_t *sk_seed, - const uint8_t *pk_seed) { + const slhdsa_hash_ctx *hash_ctx) { uint8_t addr[32] = {0}; slhdsa_set_tree_addr(config, addr, idx_tree); // Layer 0 - slhdsa_xmss_sign(config, sig, message, idx_leaf, sk_seed, pk_seed, addr); + slhdsa_xmss_sign(config, sig, message, idx_leaf, sk_seed, hash_ctx, addr); uint8_t root[SLHDSA_MAX_N]; - slhdsa_xmss_pk_from_sig(config, root, sig, idx_leaf, message, pk_seed, addr); + slhdsa_xmss_pk_from_sig(config, root, sig, idx_leaf, message, hash_ctx, addr); sig += slhdsa_xmss_bytes(config); // All other layers @@ -129,9 +131,10 @@ void bssl::slhdsa_ht_sign(const slh_dsa_config *config, uint8_t *sig, idx_tree = idx_tree >> config->tree_height; slhdsa_set_layer_addr(config, addr, j); slhdsa_set_tree_addr(config, addr, idx_tree); - slhdsa_xmss_sign(config, sig, root, idx_leaf, sk_seed, pk_seed, addr); + slhdsa_xmss_sign(config, sig, root, idx_leaf, sk_seed, hash_ctx, addr); if (j < (config->d - 1)) { - slhdsa_xmss_pk_from_sig(config, root, sig, idx_leaf, root, pk_seed, addr); + slhdsa_xmss_pk_from_sig(config, root, sig, idx_leaf, root, hash_ctx, + addr); } sig += slhdsa_xmss_bytes(config); @@ -142,12 +145,12 @@ void bssl::slhdsa_ht_sign(const slh_dsa_config *config, uint8_t *sig, int bssl::slhdsa_ht_verify(const slh_dsa_config *config, const uint8_t *sig, const uint8_t *message, uint64_t idx_tree, uint32_t idx_leaf, const uint8_t *pk_root, - const uint8_t *pk_seed) { + const slhdsa_hash_ctx *hash_ctx) { uint8_t addr[32] = {0}; slhdsa_set_tree_addr(config, addr, idx_tree); uint8_t node[SLHDSA_MAX_N]; - slhdsa_xmss_pk_from_sig(config, node, sig, idx_leaf, message, pk_seed, addr); + slhdsa_xmss_pk_from_sig(config, node, sig, idx_leaf, message, hash_ctx, addr); BSSL_CHECK(config->tree_height <= SLHDSA_MAX_TREE_HEIGHT); const uint32_t leaf_mask = (1u << config->tree_height) - 1; @@ -158,7 +161,7 @@ int bssl::slhdsa_ht_verify(const slh_dsa_config *config, const uint8_t *sig, slhdsa_set_tree_addr(config, addr, idx_tree); slhdsa_xmss_pk_from_sig(config, node, sig + j * slhdsa_xmss_bytes(config), - idx_leaf, node, pk_seed, addr); + idx_leaf, node, hash_ctx, addr); } return memcmp(node, pk_root, config->n) == 0; } diff --git a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/merkle.h b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/merkle.h index c13b6ff..5d2a140 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/merkle.h +++ b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/merkle.h @@ -20,6 +20,7 @@ #include #include "./params.h" +#include "./thash.h" BSSL_NAMESPACE_BEGIN @@ -27,31 +28,33 @@ BSSL_NAMESPACE_BEGIN // Implements Algorithm 9: xmss_node function (page 23) void slhdsa_treehash(const slh_dsa_config *config, uint8_t *out_pk, const uint8_t *sk_seed, uint32_t i /*target node index*/, - uint32_t z /*target node height*/, const uint8_t *pk_seed, - uint8_t addr[32]); + uint32_t z /*target node height*/, + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]); // Implements Algorithm 10: xmss_sign function (page 24) void slhdsa_xmss_sign(const slh_dsa_config *config, uint8_t *sig, const uint8_t *msg, unsigned int idx, - const uint8_t *sk_seed, const uint8_t *pk_seed, + const uint8_t *sk_seed, const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]); // Implements Algorithm 11: xmss_pkFromSig function (page 25) void slhdsa_xmss_pk_from_sig(const slh_dsa_config *config, uint8_t *root, const uint8_t *xmss_sig, unsigned int idx, - const uint8_t *msg, const uint8_t *pk_seed, + const uint8_t *msg, + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]); // Implements Algorithm 12: ht_sign function (page 27) void slhdsa_ht_sign(const slh_dsa_config *config, uint8_t *sig, - const uint8_t *message, uint64_t idx_tree, uint32_t idx_leaf, - const uint8_t *sk_seed, const uint8_t *pk_seed); + const uint8_t *message, uint64_t idx_tree, + uint32_t idx_leaf, const uint8_t *sk_seed, + const slhdsa_hash_ctx *hash_ctx); // Implements Algorithm 13: ht_verify function (page 28) int slhdsa_ht_verify(const slh_dsa_config *config, const uint8_t *sig, const uint8_t *message, uint64_t idx_tree, uint32_t idx_leaf, const uint8_t *pk_root, - const uint8_t *pk_seed); + const slhdsa_hash_ctx *hash_ctx); BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/slhdsa.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/slhdsa.cc.inc index 7d56ebe..91c2564 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/slhdsa.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/slhdsa.cc.inc @@ -65,12 +65,15 @@ bcm_infallible generate_key_from_seed_no_self_test(const slh_dsa_config *config, // Initialize PK.seed from seed. OPENSSL_memcpy(out_public_key, seed + 2 * config->n, config->n); + slhdsa_hash_ctx hash_ctx; + slhdsa_hash_ctx_init(config, &hash_ctx, out_public_key); + uint8_t addr[32] = {0}; slhdsa_set_layer_addr(config, addr, config->d - 1); // Set PK.root slhdsa_treehash(config, out_public_key + config->n, out_secret_key, 0, - config->tree_height, out_public_key, addr); + config->tree_height, &hash_ctx, addr); OPENSSL_memcpy(out_secret_key + 3 * config->n, out_public_key + config->n, config->n); @@ -157,15 +160,17 @@ bcm_infallible sign_internal_no_self_test( slhdsa_set_type(config, addr, SLHDSA_ADDR_TYPE_FORSTREE); slhdsa_set_keypair_addr(config, addr, idx_leaf); - slhdsa_fors_sign(config, out_signature + n, fors_digest, sk_seed, pk_seed, + slhdsa_hash_ctx hash_ctx; + slhdsa_hash_ctx_init(config, &hash_ctx, pk_seed); + slhdsa_fors_sign(config, out_signature + n, fors_digest, sk_seed, &hash_ctx, addr); uint8_t pk_fors[SLHDSA_MAX_N]; slhdsa_fors_pk_from_sig(config, pk_fors, out_signature + n, fors_digest, - pk_seed, addr); + &hash_ctx, addr); slhdsa_ht_sign(config, out_signature + n + slhdsa_fors_bytes(config), pk_fors, - idx_tree, idx_leaf, sk_seed, pk_seed); + idx_tree, idx_leaf, sk_seed, &hash_ctx); return bcm_infallible::approved; } @@ -213,11 +218,13 @@ bcm_status verify_internal(const slh_dsa_config *config, slhdsa_set_keypair_addr(config, addr, idx_leaf); uint8_t pk_fors[SLHDSA_MAX_N]; - slhdsa_fors_pk_from_sig(config, pk_fors, sig_fors, fors_digest, pk_seed, + slhdsa_hash_ctx hash_ctx; + slhdsa_hash_ctx_init(config, &hash_ctx, pk_seed); + slhdsa_fors_pk_from_sig(config, pk_fors, sig_fors, fors_digest, &hash_ctx, addr); if (!slhdsa_ht_verify(config, sig_ht, pk_fors, idx_tree, idx_leaf, pk_root, - pk_seed)) { + &hash_ctx)) { return bcm_status::failure; } @@ -313,11 +320,14 @@ bcm_infallible bssl::BCM_slhdsa_sha2_128s_generate_key_from_seed( &kSLHDSAConfigSHA2_128s, out_public_key, out_secret_key, seed); } +// The `BCM_slhdsa_shake_256f_*` functions in this file are not FIPS approved +// because the module's CASTs only cover SLH-DSA-SHA2-128s. Thus they report +// `not_approved` and do not run the SHA2-128s self-tests. + bcm_infallible bssl::BCM_slhdsa_shake_256f_generate_key_from_seed( uint8_t out_public_key[BCM_SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], uint8_t out_secret_key[BCM_SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES], const uint8_t seed[3 * BCM_SLHDSA_SHAKE_256F_N]) { - fips::ensure_keygen_self_test(); return generate_key_from_seed_no_self_test( &kSLHDSAConfigSHAKE_256f, out_public_key, out_secret_key, seed); } @@ -343,7 +353,7 @@ bcm_status bssl::BCM_slhdsa_shake_256f_generate_key_from_seed_fips( } BCM_slhdsa_shake_256f_generate_key_from_seed(out_public_key, out_secret_key, seed); - return bcm_status::approved; + return bcm_status::not_approved; } bcm_infallible bssl::BCM_slhdsa_sha2_128s_generate_key( @@ -381,7 +391,7 @@ bcm_status bssl::BCM_slhdsa_shake_256f_generate_key_fips( return bcm_status::failure; } BCM_slhdsa_shake_256f_generate_key(out_public_key, out_private_key); - return bcm_status::approved; + return bcm_status::not_approved; } bcm_infallible bssl::BCM_slhdsa_sha2_128s_public_from_private( @@ -397,7 +407,7 @@ bcm_infallible bssl::BCM_slhdsa_shake_256f_public_from_private( const uint8_t private_key[BCM_SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES]) { OPENSSL_memcpy(out_public_key, private_key + 2 * BCM_SLHDSA_SHAKE_256F_N, BCM_SLHDSA_SHAKE_256F_N * 2); - return bcm_infallible::approved; + return bcm_infallible::not_approved; } bcm_status bssl::BCM_slhdsa_sha2_128s_sign( @@ -440,7 +450,7 @@ bcm_status bssl::BCM_slhdsa_shake_256f_sign( BCM_slhdsa_shake_256f_sign_internal(out_signature, private_key, M_prime_header, context, context_len, msg, msg_len, entropy); - return bcm_status::approved; + return bcm_status::not_approved; } static int slhdsa_get_context_and_oid(uint8_t *out_context_and_oid, @@ -508,10 +518,10 @@ bcm_infallible bssl::BCM_slhdsa_shake_256f_sign_internal( const uint8_t header[BCM_SLHDSA_M_PRIME_HEADER_LEN], const uint8_t *context, size_t context_len, const uint8_t *msg, size_t msg_len, const uint8_t entropy[BCM_SLHDSA_SHAKE_256F_N]) { - fips::ensure_sign_self_test(); - return sign_internal_no_self_test(&kSLHDSAConfigSHAKE_256f, out_signature, - secret_key, header, context, context_len, - msg, msg_len, entropy); + sign_internal_no_self_test(&kSLHDSAConfigSHAKE_256f, out_signature, + secret_key, header, context, context_len, msg, + msg_len, entropy); + return bcm_infallible::not_approved; } bcm_status bssl::BCM_slhdsa_sha2_128s_prehash_sign( @@ -569,7 +579,7 @@ bcm_status bssl::BCM_slhdsa_shake_256f_prehash_sign( BCM_slhdsa_shake_256f_sign_internal( out_signature, private_key, M_prime_header, context_and_oid, context_and_oid_len, hashed_msg, hashed_msg_len, entropy); - return bcm_status::approved; + return bcm_status::not_approved; } // Implements Algorithm 24: slh_verify function (Section 10.3, page 41) @@ -678,10 +688,9 @@ bcm_status bssl::BCM_slhdsa_shake_256f_verify_internal( const uint8_t public_key[BCM_SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], const uint8_t header[BCM_SLHDSA_M_PRIME_HEADER_LEN], const uint8_t *context, size_t context_len, const uint8_t *msg, size_t msg_len) { - fips::ensure_verify_self_test(); - return verify_internal(&kSLHDSAConfigSHAKE_256f, signature, signature_len, - public_key, header, context, context_len, msg, - msg_len); + return bcm_as_not_approved_status(bcm_success( + verify_internal(&kSLHDSAConfigSHAKE_256f, signature, signature_len, + public_key, header, context, context_len, msg, msg_len))); } int bssl::boringssl_self_test_slhdsa() { diff --git a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/thash.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/thash.cc.inc index 2cb608f..6e76b56 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/thash.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/thash.cc.inc @@ -20,28 +20,71 @@ #include #include "../../internal.h" +#include "../bcm_interface.h" #include "../keccak/internal.h" #include "./thash.h" using namespace bssl; -// Internal thash function used by F, H, and T_l for SHA-256 based parameter -// sets (Section 11.2, pages 44-46) +void bssl::slhdsa_hash_ctx_init(const slh_dsa_config *config, + slhdsa_hash_ctx *hash_ctx, + const uint8_t *pk_seed) { + hash_ctx->pk_seed = pk_seed; + if (config->hash_type != SLH_DSA_HASH_SHA2_256) { + return; + } + // Absorb PK.seed || toByte(0, 64 - n), which is exactly one SHA-256 block. + BSSL_CHECK(config->hash_block_bytes == SHA256_CBLOCK); + BSSL_CHECK(config->n <= SHA256_CBLOCK); + uint8_t block[SHA256_CBLOCK] = {0}; + OPENSSL_memcpy(block, pk_seed, config->n); + BCM_sha256_init(&hash_ctx->sha256_seeded); + BCM_sha256_update(&hash_ctx->sha256_seeded, block, sizeof(block)); +} + +// Internal thash function used by F, H, T_l, and PRF for SHA-256 based +// parameter sets (Section 11.2, pages 44-46). Every input starts with the same +// block, PK.seed || toByte(0, 64 - n), so this resumes from the state that +// `slhdsa_hash_ctx_init` precomputed after that block. static void slhdsa_thash_sha256(const slh_dsa_config *config, uint8_t *output, const uint8_t *input, size_t input_blocks, - const uint8_t *pk_seed, uint8_t addr[32]) { + const slhdsa_hash_ctx *hash_ctx, + uint8_t addr[32]) { BSSL_CHECK(config->hash_type == SLH_DSA_HASH_SHA2_256); - SHA256_CTX sha256; - SHA256_Init(&sha256); - - uint8_t zeros[SLHDSA_MAX_HASH_BLOCK_BYTES] = {0}; - BSSL_CHECK(config->hash_block_bytes <= sizeof(zeros)); - BSSL_CHECK(config->hash_block_bytes >= config->n); - SHA256_Update(&sha256, pk_seed, config->n); - SHA256_Update(&sha256, zeros, config->hash_block_bytes - config->n); + const size_t input_len = input_blocks * config->n; + const size_t msg_len = SLHDSA_ADDR_COMPRESSED_BYTES + input_len; + + // For F, H, and PRF, ADRSc || input fits in a single block together with the + // SHA-256 padding: a 0x80 byte and the 64-bit message length. Finish those + // with one compression function call, skipping the overhead of the generic + // SHA256_Update and SHA256_Final logic. This branch only depends on public + // parameters. + if (msg_len + 1 + 8 <= SHA256_CBLOCK) { + uint8_t block[SHA256_CBLOCK] = {0}; + OPENSSL_memcpy(block, addr, SLHDSA_ADDR_COMPRESSED_BYTES); + OPENSSL_memcpy(block + SLHDSA_ADDR_COMPRESSED_BYTES, input, input_len); + block[msg_len] = 0x80; + // The message length, in bits, includes the precomputed first block. + CRYPTO_store_u64_be(block + SHA256_CBLOCK - 8, + (uint64_t{SHA256_CBLOCK} + msg_len) * 8); + + uint32_t state[8]; + OPENSSL_memcpy(state, hash_ctx->sha256_seeded.h, sizeof(state)); + BCM_sha256_transform_blocks(state, block, 1); + + static_assert(SLHDSA_MAX_N <= SHA256_DIGEST_LENGTH, "n is too large"); + uint8_t hash[SHA256_DIGEST_LENGTH]; + for (size_t i = 0; i < 8; i++) { + CRYPTO_store_u32_be(hash + 4 * i, state[i]); + } + OPENSSL_memcpy(output, hash, config->n); + return; + } + + SHA256_CTX sha256 = hash_ctx->sha256_seeded; SHA256_Update(&sha256, addr, SLHDSA_ADDR_COMPRESSED_BYTES); - SHA256_Update(&sha256, input, input_blocks * config->n); + SHA256_Update(&sha256, input, input_len); uint8_t hash[SLHDSA_MAX_DIGEST_SIZE]; SHA256_Final(hash, &sha256); @@ -66,13 +109,15 @@ static void slhdsa_thash_shake(const slh_dsa_config *config, uint8_t *output, static void slhdsa_thash_dispatch(const slh_dsa_config *config, uint8_t *output, const uint8_t *input, size_t input_blocks, - const uint8_t *pk_seed, uint8_t addr[32]) { + const slhdsa_hash_ctx *hash_ctx, + uint8_t addr[32]) { switch (config->hash_type) { case SLH_DSA_HASH_SHA2_256: - slhdsa_thash_sha256(config, output, input, input_blocks, pk_seed, addr); + slhdsa_thash_sha256(config, output, input, input_blocks, hash_ctx, addr); return; case SLH_DSA_HASH_SHAKE_256: - slhdsa_thash_shake(config, output, input, input_blocks, pk_seed, addr); + slhdsa_thash_shake(config, output, input, input_blocks, hash_ctx->pk_seed, + addr); return; } BSSL_CHECK(false); @@ -260,9 +305,10 @@ void bssl::slhdsa_thash_hmsg(const slh_dsa_config *config, uint8_t *output, // Implements PRF function (Section 4.1, page 11 and Section 11.2, pages 44-46) static void slhdsa_thash_prf_sha256(const slh_dsa_config *config, - uint8_t *output, const uint8_t *pk_seed, + uint8_t *output, + const slhdsa_hash_ctx *hash_ctx, const uint8_t *sk_seed, uint8_t addr[32]) { - slhdsa_thash_sha256(config, output, sk_seed, 1, pk_seed, addr); + slhdsa_thash_sha256(config, output, sk_seed, 1, hash_ctx, addr); } static void slhdsa_thash_prf_shake(const slh_dsa_config *config, @@ -280,14 +326,14 @@ static void slhdsa_thash_prf_shake(const slh_dsa_config *config, } void bssl::slhdsa_thash_prf(const slh_dsa_config *config, uint8_t *output, - const uint8_t *pk_seed, const uint8_t *sk_seed, - uint8_t addr[32]) { + const slhdsa_hash_ctx *hash_ctx, + const uint8_t *sk_seed, uint8_t addr[32]) { switch (config->hash_type) { case SLH_DSA_HASH_SHA2_256: - slhdsa_thash_prf_sha256(config, output, pk_seed, sk_seed, addr); + slhdsa_thash_prf_sha256(config, output, hash_ctx, sk_seed, addr); return; case SLH_DSA_HASH_SHAKE_256: - slhdsa_thash_prf_shake(config, output, pk_seed, sk_seed, addr); + slhdsa_thash_prf_shake(config, output, hash_ctx->pk_seed, sk_seed, addr); return; } BSSL_CHECK(false); @@ -296,31 +342,31 @@ void bssl::slhdsa_thash_prf(const slh_dsa_config *config, uint8_t *output, // Implements T_l function for WOTS+ public key compression (Section 4.1, page // 11 and Section 11.2, pages 44-46) void bssl::slhdsa_thash_tl(const slh_dsa_config *config, uint8_t *output, - const uint8_t *input, const uint8_t *pk_seed, - uint8_t addr[32]) { - slhdsa_thash_dispatch(config, output, input, slhdsa_wots_len(config), pk_seed, - addr); + const uint8_t *input, + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]) { + slhdsa_thash_dispatch(config, output, input, slhdsa_wots_len(config), + hash_ctx, addr); } // Implements H function (Section 4.1, page 11 and Section 11.2, pages 44-46) void bssl::slhdsa_thash_h(const slh_dsa_config *config, uint8_t *output, - const uint8_t *input, const uint8_t *pk_seed, - uint8_t addr[32]) { - slhdsa_thash_dispatch(config, output, input, 2, pk_seed, addr); + const uint8_t *input, + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]) { + slhdsa_thash_dispatch(config, output, input, 2, hash_ctx, addr); } // Implements F function (Section 4.1, page 11 and Section 11.2, pages 44-46) void bssl::slhdsa_thash_f(const slh_dsa_config *config, uint8_t *output, - const uint8_t *input, const uint8_t *pk_seed, - uint8_t addr[32]) { - slhdsa_thash_dispatch(config, output, input, 1, pk_seed, addr); + const uint8_t *input, + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]) { + slhdsa_thash_dispatch(config, output, input, 1, hash_ctx, addr); } // Implements T_k function for FORS public key compression (Section 4.1, page 11 // and Section 11.2, pages 44-46) void bssl::slhdsa_thash_tk(const slh_dsa_config *config, uint8_t *output, - const uint8_t *input, const uint8_t *pk_seed, - uint8_t addr[32]) { - slhdsa_thash_dispatch(config, output, input, config->fors_trees, pk_seed, + const uint8_t *input, + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]) { + slhdsa_thash_dispatch(config, output, input, config->fors_trees, hash_ctx, addr); } diff --git a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/thash.h b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/thash.h index 23a42c6..b72e0fa 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/thash.h +++ b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/thash.h @@ -15,11 +15,31 @@ #ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_THASH_H #define OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_THASH_H +#include + #include "./params.h" BSSL_NAMESPACE_BEGIN +// slhdsa_hash_ctx holds the public seed, plus precomputed hash state, that is +// shared by every F, H, T_l, and PRF call made under a single key. +struct slhdsa_hash_ctx { + // pk_seed is PK.seed. It must outlive the context. + const uint8_t *pk_seed; + // sha256_seeded is only used for SHA-256 parameter sets. It holds the + // SHA-256 state after absorbing PK.seed || toByte(0, 64 - n), the first + // block of every F, H, T_l, and PRF input (Section 11.2, pages 44-46). + // Computing it once per key saves one compression function call per + // tweakable hash call. + SHA256_CTX sha256_seeded; +}; + +// slhdsa_hash_ctx_init initializes `hash_ctx` for computing tweakable hashes +// with public seed `pk_seed`, which must outlive `hash_ctx`. +void slhdsa_hash_ctx_init(const slh_dsa_config *config, + slhdsa_hash_ctx *hash_ctx, const uint8_t *pk_seed); + // Implements PRF_msg: a pseudo-random function that is used to generate the // randomizer r for the randomized hashing of the message to be signed. // (Section 4.1, page 11) @@ -39,31 +59,31 @@ void slhdsa_thash_hmsg(const slh_dsa_config *config, uint8_t *output, // Implements PRF: a pseudo-random function that is used to generate the secret // values in WOTS+ and FORS private keys. (Section 4.1, page 11) void slhdsa_thash_prf(const slh_dsa_config *config, uint8_t *output, - const uint8_t *pk_seed, const uint8_t *sk_seed, + const slhdsa_hash_ctx *hash_ctx, const uint8_t *sk_seed, uint8_t addr[32]); // Implements T_l: a hash function that maps an l*n-byte message to an n-byte // message. Used for WOTS+ public key compression. (Section 4.1, page 11) void slhdsa_thash_tl(const slh_dsa_config *config, uint8_t *output, - const uint8_t *input, const uint8_t *pk_seed, + const uint8_t *input, const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]); // Implements H: a hash function that takes a 2*n-byte message as input and // produces an n-byte output. (Section 4.1, page 11) void slhdsa_thash_h(const slh_dsa_config *config, uint8_t *output, - const uint8_t *input, const uint8_t *pk_seed, + const uint8_t *input, const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]); // Implements F: a hash function that takes an n-byte message as input and // produces an n-byte output. (Section 4.1, page 11) void slhdsa_thash_f(const slh_dsa_config *config, uint8_t *output, - const uint8_t *input, const uint8_t *pk_seed, + const uint8_t *input, const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]); // Implements T_k: a hash function that maps a k*n-byte message to an n-byte // message. Used for FORS public key compression. (Section 4.1, page 11) void slhdsa_thash_tk(const slh_dsa_config *config, uint8_t *output, - const uint8_t *input, const uint8_t *pk_seed, + const uint8_t *input, const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]); BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/wots.cc.inc b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/wots.cc.inc index e8bc990..7a073b9 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/wots.cc.inc +++ b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/wots.cc.inc @@ -30,7 +30,7 @@ using namespace bssl; // Implements Algorithm 5: chain function, page 18 static void chain(const slh_dsa_config *config, uint8_t *output, const uint8_t *input, uint32_t start, uint32_t steps, - const uint8_t *pub_seed, uint8_t addr[32]) { + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]) { assert(start < config->wots_w); assert(steps < config->wots_w); @@ -38,25 +38,26 @@ static void chain(const slh_dsa_config *config, uint8_t *output, for (uint32_t i = start; i < (start + steps) && i < config->wots_w; ++i) { slhdsa_set_hash_addr(config, addr, i); - slhdsa_thash_f(config, output, output, pub_seed, addr); + slhdsa_thash_f(config, output, output, hash_ctx, addr); } } static void slhdsa_wots_do_chain(const slh_dsa_config *config, uint8_t *out, uint8_t sk_addr[32], uint8_t addr[32], uint8_t value, const uint8_t *sk_seed, - const uint8_t *pub_seed, + const slhdsa_hash_ctx *hash_ctx, uint32_t chain_index) { uint8_t tmp_sk[SLHDSA_MAX_N]; slhdsa_set_chain_addr(config, sk_addr, chain_index); - slhdsa_thash_prf(config, tmp_sk, pub_seed, sk_seed, sk_addr); + slhdsa_thash_prf(config, tmp_sk, hash_ctx, sk_seed, sk_addr); slhdsa_set_chain_addr(config, addr, chain_index); - chain(config, out, tmp_sk, 0, value, pub_seed, addr); + chain(config, out, tmp_sk, 0, value, hash_ctx, addr); } // Implements Algorithm 6: wots_pkGen function, page 18 void bssl::slhdsa_wots_pk_gen(const slh_dsa_config *config, uint8_t *pk, - const uint8_t *sk_seed, const uint8_t *pub_seed, + const uint8_t *sk_seed, + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]) { uint8_t wots_pk_addr[32], sk_addr[32]; OPENSSL_memcpy(wots_pk_addr, addr, sizeof(wots_pk_addr)); @@ -70,19 +71,19 @@ void bssl::slhdsa_wots_pk_gen(const slh_dsa_config *config, uint8_t *pk, const uint32_t max_chain = config->wots_w - 1; for (uint32_t i = 0; i < wots_len; ++i) { slhdsa_wots_do_chain(config, tmp + i * n, sk_addr, addr, max_chain, sk_seed, - pub_seed, i); + hash_ctx, i); } // Compress pk slhdsa_set_type(config, wots_pk_addr, SLHDSA_ADDR_TYPE_WOTSPK); slhdsa_copy_keypair_addr(config, wots_pk_addr, addr); - slhdsa_thash_tl(config, pk, tmp, pub_seed, wots_pk_addr); + slhdsa_thash_tl(config, pk, tmp, hash_ctx, wots_pk_addr); } // Implements Algorithm 7: wots_sign function, page 20 void bssl::slhdsa_wots_sign(const slh_dsa_config *config, uint8_t *sig, const uint8_t *msg, const uint8_t *sk_seed, - const uint8_t *pub_seed, uint8_t addr[32]) { + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]) { BSSL_CHECK(config->wots_w == 16); const size_t n = config->n; const uint32_t max_chain = config->wots_w - 1; @@ -102,40 +103,41 @@ void bssl::slhdsa_wots_sign(const slh_dsa_config *config, uint8_t *sig, uint32_t chain_index = 0; for (size_t i = 0; i < n; ++i) { slhdsa_wots_do_chain(config, sig, sk_addr, addr, msg[i] >> 4, sk_seed, - pub_seed, chain_index++); + hash_ctx, chain_index++); sig += n; slhdsa_wots_do_chain(config, sig, sk_addr, addr, msg[i] & 15, sk_seed, - pub_seed, chain_index++); + hash_ctx, chain_index++); sig += n; } // Include the WOTS checksum values (len2 = 3 for the parameter sets we // support). slhdsa_wots_do_chain(config, sig, sk_addr, addr, (csum >> 8) & 15, sk_seed, - pub_seed, chain_index++); + hash_ctx, chain_index++); sig += n; slhdsa_wots_do_chain(config, sig, sk_addr, addr, (csum >> 4) & 15, sk_seed, - pub_seed, chain_index++); + hash_ctx, chain_index++); sig += n; - slhdsa_wots_do_chain(config, sig, sk_addr, addr, csum & 15, sk_seed, pub_seed, + slhdsa_wots_do_chain(config, sig, sk_addr, addr, csum & 15, sk_seed, hash_ctx, chain_index++); } static void slhdsa_wots_pk_from_sig_do_chain(const slh_dsa_config *config, uint8_t *out, uint8_t addr[32], const uint8_t *in, uint8_t value, - const uint8_t *pub_seed, + const slhdsa_hash_ctx *hash_ctx, uint32_t chain_index) { slhdsa_set_chain_addr(config, addr, chain_index); chain(config, out + chain_index * config->n, in + chain_index * config->n, - value, (config->wots_w - 1) - value, pub_seed, addr); + value, (config->wots_w - 1) - value, hash_ctx, addr); } // Implements Algorithm 8: wots_pkFromSig function, page 21 void bssl::slhdsa_wots_pk_from_sig(const slh_dsa_config *config, uint8_t *pk, const uint8_t *sig, const uint8_t *msg, - const uint8_t *pub_seed, uint8_t addr[32]) { + const slhdsa_hash_ctx *hash_ctx, + uint8_t addr[32]) { BSSL_CHECK(config->wots_w == 16); const size_t n = config->n; const uint32_t max_chain = config->wots_w - 1; @@ -153,20 +155,20 @@ void bssl::slhdsa_wots_pk_from_sig(const slh_dsa_config *config, uint8_t *pk, uint32_t chain_index = 0; for (size_t i = 0; i < n; ++i) { slhdsa_wots_pk_from_sig_do_chain(config, tmp, addr, sig, msg[i] >> 4, - pub_seed, chain_index++); + hash_ctx, chain_index++); slhdsa_wots_pk_from_sig_do_chain(config, tmp, addr, sig, msg[i] & 15, - pub_seed, chain_index++); + hash_ctx, chain_index++); } - slhdsa_wots_pk_from_sig_do_chain(config, tmp, addr, sig, csum >> 8, pub_seed, + slhdsa_wots_pk_from_sig_do_chain(config, tmp, addr, sig, csum >> 8, hash_ctx, chain_index++); slhdsa_wots_pk_from_sig_do_chain(config, tmp, addr, sig, (csum >> 4) & 15, - pub_seed, chain_index++); - slhdsa_wots_pk_from_sig_do_chain(config, tmp, addr, sig, csum & 15, pub_seed, + hash_ctx, chain_index++); + slhdsa_wots_pk_from_sig_do_chain(config, tmp, addr, sig, csum & 15, hash_ctx, chain_index++); // Compress pk slhdsa_set_type(config, wots_pk_addr, SLHDSA_ADDR_TYPE_WOTSPK); slhdsa_copy_keypair_addr(config, wots_pk_addr, addr); - slhdsa_thash_tl(config, pk, tmp, pub_seed, wots_pk_addr); + slhdsa_thash_tl(config, pk, tmp, hash_ctx, wots_pk_addr); } diff --git a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/wots.h b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/wots.h index 28afeb0..a41f26c 100644 --- a/third_party/boringssl/src/crypto/fipsmodule/slhdsa/wots.h +++ b/third_party/boringssl/src/crypto/fipsmodule/slhdsa/wots.h @@ -16,24 +16,25 @@ #define OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_WOTS_H #include "./params.h" +#include "./thash.h" BSSL_NAMESPACE_BEGIN // Implements Algorithm 6: wots_pkGen function, page 18 void slhdsa_wots_pk_gen(const slh_dsa_config *config, uint8_t *pk, - const uint8_t *sk_seed, const uint8_t *pub_seed, + const uint8_t *sk_seed, const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]); // Implements Algorithm 7: wots_sign function, page 20 void slhdsa_wots_sign(const slh_dsa_config *config, uint8_t *sig, const uint8_t *msg, const uint8_t *sk_seed, - const uint8_t *pub_seed, uint8_t addr[32]); + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]); // Implements Algorithm 8: wots_pkFromSig function, page 21 void slhdsa_wots_pk_from_sig(const slh_dsa_config *config, uint8_t *pk, const uint8_t *sig, const uint8_t *msg, - const uint8_t *pub_seed, uint8_t addr[32]); + const slhdsa_hash_ctx *hash_ctx, uint8_t addr[32]); BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/crypto/hpke/hpke.cc b/third_party/boringssl/src/crypto/hpke/hpke.cc index 11f61ba..70487fa 100644 --- a/third_party/boringssl/src/crypto/hpke/hpke.cc +++ b/third_party/boringssl/src/crypto/hpke/hpke.cc @@ -18,6 +18,7 @@ #include #include +#include #include #include @@ -25,17 +26,18 @@ #include #include #include +#include #include #include #include #include #include #include -#include #include #include #include +#include "../evp/internal.h" #include "../fipsmodule/ec/internal.h" #include "../fipsmodule/keccak/internal.h" #include "../internal.h" @@ -46,65 +48,86 @@ using namespace bssl; // This file implements RFC 9180. -#define MAX_SEED_LEN XWING_SEED_LEN #define MAX_SHARED_SECRET_LEN SHA256_DIGEST_LENGTH +#define MAX_DHKEM_DH_SHARED_KEY_LEN X25519_SHARED_KEY_LEN +#define MAX_DHKEM_PUBLIC_KEY_LEN 65 // kP256PublicValueLen -struct evp_hpke_kem_st { - uint16_t id; +namespace { - // evp_pkey_alg_func and evp_kem_func, if non-null, provide the EVP_PKEY_CTX - // and EVP_KEM functionality backing this EVP_HPKE_KEM. If these are non-null, - // then `init_key`, `generate_key`, `derive_key`, `encap_with_seed`, and - // `decap` are null and 'seed_len` and `enc_len` are zero (until fully - // migrated), and the `evp_*` function pointers are non-null. - // TODO(crbug.com/535883377): Unify EVP_HPKE_KEM and EVP_KEM for all supported - // HPKE KEMs. - const EVP_PKEY_ALG *(*evp_pkey_alg_func)(); - const EVP_KEM *(*evp_kem_func)(); +// HpkeKeyMethod implements the key-type-specific operations that HPKE performs +// on keys of a particular `EVP_PKEY_ALG` type. +struct HpkeKeyMethod { + // hpke_kem_id is the ID of the KEM in RFC 9180. + uint16_t hpke_kem_id; + // public_key_len corresponds to Npk in RFC 9180. size_t public_key_len; + // private_key_len corresponds to Nsk in RFC 9180. size_t private_key_len; - size_t seed_len; - size_t enc_len; - int (*init_key)(EVP_HPKE_KEY *key, const uint8_t *priv_key, - size_t priv_key_len); - int (*generate_key)(EVP_HPKE_KEY *key); - int (*derive_key)(EVP_HPKE_KEY *key, Span ikm); - int (*encap_with_seed)(const EVP_HPKE_KEM *kem, uint8_t *out_shared_secret, - size_t *out_shared_secret_len, uint8_t *out_enc, - size_t *out_enc_len, size_t max_enc, - const uint8_t *peer_public_key, - size_t peer_public_key_len, const uint8_t *seed, - size_t seed_len); - int (*decap)(const EVP_HPKE_KEY *key, uint8_t *out_shared_secret, - size_t *out_shared_secret_len, const uint8_t *enc, - size_t enc_len); - int (*auth_encap_with_seed)(const EVP_HPKE_KEY *key, - uint8_t *out_shared_secret, - size_t *out_shared_secret_len, uint8_t *out_enc, - size_t *out_enc_len, size_t max_enc, - const uint8_t *peer_public_key, - size_t peer_public_key_len, const uint8_t *seed, - size_t seed_len); - int (*auth_decap)(const EVP_HPKE_KEY *key, uint8_t *out_shared_secret, - size_t *out_shared_secret_len, const uint8_t *enc, - size_t enc_len, const uint8_t *peer_public_key, - size_t peer_public_key_len); - - // Hooks used for operations with `evp_pkey_alg_func` and `evp_kem_func`, when - // they are non-null. - // TODO(crbug.com/535883377): Unify EVP_HPKE_KEM and EVP_KEM for all supported - // HPKE KEMs. - EVP_PKEY *(*evp_deserialize_private_key)(const EVP_PKEY_ALG *alg, - const uint8_t *in, size_t len); - int (*evp_serialize_private_key)(const EVP_PKEY *pkey, uint8_t *out, - size_t *out_len); - EVP_PKEY *(*evp_deserialize_public_key)(const EVP_PKEY_ALG *alg, - const uint8_t *in, size_t len); - int (*evp_serialize_public_key)(const EVP_PKEY *pkey, uint8_t *out, - size_t *out_len); - EVP_PKEY *(*evp_derive_key_pair)(const EVP_PKEY_ALG *alg, - Span ikm); + + const EVP_PKEY_ALG *(*alg_func)(); + + // deserialize_private_key and serialize_private_key implement the + // DeserializePrivateKey and SerializePrivateKey operations for the key type + // from section 4 of RFC 9180, using the same format accepted by + // `EVP_HPKE_KEY_init`. + EVP_PKEY *(*deserialize_private_key)(const EVP_PKEY_ALG *alg, + const uint8_t *in, size_t len); + int (*serialize_private_key)(const EVP_PKEY *pkey, uint8_t *out, + size_t *out_len); + + // deserialize_public_key and serialize_public_key implement the + // DeserializePublicKey and SerializePublicKey operations from section 4 of + // RFC 9180. + EVP_PKEY *(*deserialize_public_key)(const EVP_PKEY_ALG *alg, + const uint8_t *in, size_t len); + int (*serialize_public_key)(const EVP_PKEY *pkey, uint8_t *out, + size_t *out_len); + + // derive_key_pair implements the DeriveKeyPair operation from section 4 of + // RFC 9180. + EVP_PKEY *(*derive_key_pair)(const EVP_PKEY_ALG *alg, uint16_t kem_suite_id, + Span ikm); +}; + +// EVP_KEM_DHKEM implements the DHKEM construction from RFC 9180 based on a +// DH group and an HKDF. +// +// In DHKEM, the encapsulated key is the serialized ephemeral public key, so +// Nenc (`ciphertext_len`) equals Npk (`public_key_len`). +struct EVP_KEM_DHKEM : public EVP_KEM { + // dh_shared_key_len corresponds to Ndh in RFC 9180. + size_t dh_shared_key_len; + + const HpkeKeyMethod *key_method; + const EVP_MD *(*hkdf_digest_func)(); + + // Generates the ephemeral encapsulation key from external entropy bytes + // provided as a "seed" for testing. The seed's format is variant-specific. + EVP_PKEY *(*key_from_encap_entropy)(const EVP_PKEY_ALG *alg, + const uint8_t *in, size_t len); +}; + +} // namespace + +struct evp_hpke_kem_st { + uint16_t id; + + const EVP_KEM *(*evp_kem_func)(); + const HpkeKeyMethod *key_method; + + int (*auth_encap)(const EVP_KEM *kem, Span out_ciphertext, + Span out_secret, const EVP_PKEY *peer_key, + const EVP_PKEY *auth_key); + int (*auth_encap_external_entropy)(const EVP_KEM *kem, + Span out_ciphertext, + Span out_secret, + const EVP_PKEY *peer_key, + const EVP_PKEY *auth_key, + Span entropy); + int (*auth_decap)(const EVP_KEM *kem, Span out_secret, + Span ciphertext, const EVP_PKEY *key, + const EVP_PKEY *auth_key); }; struct evp_hpke_kdf_st { @@ -118,20 +141,21 @@ struct evp_hpke_aead_st { const EVP_AEAD *(*aead_func)(); }; +namespace { // Low-level labeled KDF functions. -static const char kHpkeVersionId[] = "HPKE-v1"; +const char kHpkeVersionId[] = "HPKE-v1"; -static int add_label_string(CBB *cbb, const char *label) { +int add_label_string(CBB *cbb, const char *label) { return CBB_add_bytes(cbb, (const uint8_t *)label, strlen(label)); } -static int hpke_labeled_extract(const EVP_MD *hkdf_md, uint8_t *out_key, - size_t *out_len, const uint8_t *salt, - size_t salt_len, const uint8_t *suite_id, - size_t suite_id_len, const char *label, - const uint8_t *ikm, size_t ikm_len) { +int hpke_labeled_extract(const EVP_MD *hkdf_md, uint8_t *out_key, + size_t *out_len, const uint8_t *salt, size_t salt_len, + const uint8_t *suite_id, size_t suite_id_len, + const char *label, const uint8_t *ikm, + size_t ikm_len) { // labeledIKM = concat("HPKE-v1", suite_id, label, IKM) CBB labeled_ikm; int ok = CBB_init(&labeled_ikm, 0) && @@ -145,11 +169,11 @@ static int hpke_labeled_extract(const EVP_MD *hkdf_md, uint8_t *out_key, return ok; } -static int hpke_labeled_expand(const EVP_MD *hkdf_md, uint8_t *out_key, - size_t out_len, const uint8_t *prk, - size_t prk_len, const uint8_t *suite_id, - size_t suite_id_len, const char *label, - const uint8_t *info, size_t info_len) { +int hpke_labeled_expand(const EVP_MD *hkdf_md, uint8_t *out_key, size_t out_len, + const uint8_t *prk, size_t prk_len, + const uint8_t *suite_id, size_t suite_id_len, + const char *label, const uint8_t *info, + size_t info_len) { // labeledInfo = concat(I2OSP(L, 2), "HPKE-v1", suite_id, label, info) CBB labeled_info; int ok = CBB_init(&labeled_info, 0) && // @@ -164,17 +188,16 @@ static int hpke_labeled_expand(const EVP_MD *hkdf_md, uint8_t *out_key, return ok; } -static void absorb_u16(BORINGSSL_keccak_st *ctx, uint16_t n) { +void absorb_u16(BORINGSSL_keccak_st *ctx, uint16_t n) { uint8_t bytes[2]; CRYPTO_store_u16_be(bytes, n); BORINGSSL_keccak_absorb(ctx, bytes, sizeof(bytes)); } -static void hpke_shake256_labeled_derive(Span out, - Span ikm, - Span suite_id, - std::string_view label, - Span context) { +void hpke_shake256_labeled_derive(Span out, Span ikm, + Span suite_id, + std::string_view label, + Span context) { // https://www.ietf.org/archive/id/draft-ietf-hpke-hpke-03.html#name-labeled-derivation-function // https://www.ietf.org/archive/id/draft-ietf-hpke-pq-04.html#name-single-stage-kdfs BORINGSSL_keccak_st ctx; @@ -196,7 +219,7 @@ static void hpke_shake256_labeled_derive(Span out, // KEM implementations. -static std::array hpke_kem_suite_id(uint16_t kem_id) { +std::array hpke_kem_suite_id(uint16_t kem_id) { // concat("KEM", I2OSP(kem_id, 2)) return {'K', 'E', 'M', static_cast(kem_id >> 8), static_cast(kem_id)}; @@ -204,11 +227,11 @@ static std::array hpke_kem_suite_id(uint16_t kem_id) { // dhkem_extract_and_expand implements the ExtractAndExpand operation in the // DHKEM construction. See section 4.1 of RFC 9180. -static int dhkem_extract_and_expand(uint16_t kem_id, const EVP_MD *hkdf_md, - uint8_t *out_key, size_t out_len, - const uint8_t *dh, size_t dh_len, - const uint8_t *kem_context, - size_t kem_context_len) { +int dhkem_extract_and_expand(uint16_t kem_id, const EVP_MD *hkdf_md, + uint8_t *out_key, size_t out_len, + const uint8_t *dh, size_t dh_len, + const uint8_t *kem_context, + size_t kem_context_len) { auto suite_id = hpke_kem_suite_id(kem_id); uint8_t prk[EVP_MAX_MD_SIZE]; size_t prk_len; @@ -220,650 +243,597 @@ static int dhkem_extract_and_expand(uint16_t kem_id, const EVP_MD *hkdf_md, kem_context, kem_context_len); } -static int x25519_init_key(EVP_HPKE_KEY *key, const uint8_t *priv_key, - size_t priv_key_len) { - if (priv_key_len != X25519_PRIVATE_KEY_LEN) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; +bool dhkem_dh(const EVP_KEM_DHKEM *dhkem, Span out, + const EVP_PKEY *key, const EVP_PKEY *peer) { + assert(out.size() == dhkem->dh_shared_key_len); + UniquePtr pkctx(EVP_PKEY_CTX_new(key, nullptr)); + if (pkctx == nullptr) { + return false; } - - OPENSSL_memcpy(key->private_key, priv_key, priv_key_len); - X25519_public_from_private(key->public_key, priv_key); - return 1; + size_t out_len = out.size(); + return EVP_PKEY_derive_init(pkctx.get()) && + EVP_PKEY_derive_set_peer(pkctx.get(), peer) && + EVP_PKEY_derive(pkctx.get(), out.data(), &out_len) && + out_len == dhkem->dh_shared_key_len; } -static int x25519_generate_key(EVP_HPKE_KEY *key) { - X25519_keypair(key->public_key, key->private_key); - return 1; +bool dhkem_serialize_public_key(const EVP_KEM_DHKEM *dhkem, Span out, + const EVP_PKEY *key) { + if (out.size() != dhkem->key_method->public_key_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE); + return false; + } + size_t serialized_len = out.size(); + if (!dhkem->key_method->serialize_public_key(key, out.data(), + &serialized_len)) { + return false; + } + BSSL_CHECK(serialized_len == out.size()); + return true; } -static int x25519_derive_key(EVP_HPKE_KEY *key, Span ikm) { - // https://www.rfc-editor.org/rfc/rfc9180.html#name-derivekeypair - auto suite_id = hpke_kem_suite_id(EVP_HPKE_DHKEM_X25519_HKDF_SHA256); - uint8_t dkp_prk[SHA256_DIGEST_LENGTH]; - size_t dkp_prk_len; - uint8_t sk[32]; - if (!hpke_labeled_extract(EVP_sha256(), dkp_prk, &dkp_prk_len, nullptr, 0, - suite_id.data(), suite_id.size(), "dkp_prk", - ikm.data(), ikm.size()) || - !hpke_labeled_expand(EVP_sha256(), sk, sizeof(sk), dkp_prk, dkp_prk_len, - suite_id.data(), suite_id.size(), "sk", - /*info=*/nullptr, /*info_len=*/0)) { - return 0; +bool dhkem_serialize_public_keys(const EVP_KEM_DHKEM *dhkem, Span out, + const EVP_PKEY *key1, const EVP_PKEY *key2) { + const size_t public_len = dhkem->key_method->public_key_len; + if (out.size() != 2 * dhkem->key_method->public_key_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE); + return false; } - return x25519_init_key(key, sk, sizeof(sk)); + return dhkem_serialize_public_key(dhkem, out.subspan(0, public_len), key1) && + dhkem_serialize_public_key(dhkem, out.subspan(public_len), key2); } -static int x25519_encap_with_seed( - const EVP_HPKE_KEM *kem, uint8_t *out_shared_secret, - size_t *out_shared_secret_len, uint8_t *out_enc, size_t *out_enc_len, - size_t max_enc, const uint8_t *peer_public_key, size_t peer_public_key_len, - const uint8_t *seed, size_t seed_len) { - if (max_enc < X25519_PUBLIC_VALUE_LEN) { +bool dhkem_serialize_public_keys(const EVP_KEM_DHKEM *dhkem, Span out, + const EVP_PKEY *key1, const EVP_PKEY *key2, + const EVP_PKEY *key3) { + const size_t public_len = dhkem->key_method->public_key_len; + if (out.size() != 3 * public_len) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE); + return false; + } + return dhkem_serialize_public_key(dhkem, out.subspan(0, public_len), key1) && + dhkem_serialize_public_keys(dhkem, out.subspan(public_len), key2, + key3); +} + +int dhkem_encap_with_ephemeral_key(const EVP_KEM_DHKEM *dhkem, + Span out_ciphertext, + Span out_secret, + const EVP_PKEY *peer_key, + const EVP_PKEY *ephemeral_key) { + const size_t public_len = dhkem->key_method->public_key_len; + if (out_ciphertext.size() != public_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_CIPHERTEXT_LENGTH); return 0; } - if (seed_len != X25519_PRIVATE_KEY_LEN) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + if (out_secret.size() != dhkem->secret_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH); return 0; } - X25519_public_from_private(out_enc, seed); - - uint8_t dh[X25519_SHARED_KEY_LEN]; - if (peer_public_key_len != X25519_PUBLIC_VALUE_LEN || - !X25519(dh, seed, peer_public_key)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PEER_KEY); + // dh = DH(skE, pkR) + InplaceVector dh; + if (!dh.TryResizeForOverwrite(dhkem->dh_shared_key_len) || + !dhkem_dh(dhkem, Span(dh), ephemeral_key, peer_key)) { return 0; } - - uint8_t kem_context[2 * X25519_PUBLIC_VALUE_LEN]; - OPENSSL_memcpy(kem_context, out_enc, X25519_PUBLIC_VALUE_LEN); - OPENSSL_memcpy(kem_context + X25519_PUBLIC_VALUE_LEN, peer_public_key, - X25519_PUBLIC_VALUE_LEN); - if (!dhkem_extract_and_expand(kem->id, EVP_sha256(), out_shared_secret, - SHA256_DIGEST_LENGTH, dh, sizeof(dh), - kem_context, sizeof(kem_context))) { + // enc = SerializePublicKey(pkE) + // pkRm = SerializePublicKey(pkR) + // kem_context = concat(enc, pkRm) + InplaceVector kem_context; + if (!kem_context.TryResizeForOverwrite(2 * public_len) || + !dhkem_serialize_public_keys(dhkem, Span(kem_context), ephemeral_key, + peer_key)) { return 0; } - - *out_enc_len = X25519_PUBLIC_VALUE_LEN; - *out_shared_secret_len = SHA256_DIGEST_LENGTH; - return 1; + OPENSSL_memcpy(out_ciphertext.data(), kem_context.data(), public_len); + // shared_secret = ExtractAndExpand(dh, kem_context) + return dhkem_extract_and_expand(dhkem->key_method->hpke_kem_id, + dhkem->hkdf_digest_func(), out_secret.data(), + out_secret.size(), dh.data(), dh.size(), + kem_context.data(), kem_context.size()); } -static int x25519_decap(const EVP_HPKE_KEY *key, uint8_t *out_shared_secret, - size_t *out_shared_secret_len, const uint8_t *enc, - size_t enc_len) { - uint8_t dh[X25519_SHARED_KEY_LEN]; - if (enc_len != X25519_PUBLIC_VALUE_LEN || - !X25519(dh, key->private_key, enc)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PEER_KEY); +int dhkem_encap(const EVP_KEM *kem, Span out_ciphertext, + Span out_secret, const EVP_PKEY *peer_key) { + const auto *dhkem = static_cast(kem); + UniquePtr ephemeral_key( + EVP_PKEY_generate_from_alg(dhkem->key_method->alg_func())); + if (ephemeral_key == nullptr) { return 0; } + return dhkem_encap_with_ephemeral_key(dhkem, out_ciphertext, out_secret, + peer_key, ephemeral_key.get()); +} - uint8_t kem_context[2 * X25519_PUBLIC_VALUE_LEN]; - OPENSSL_memcpy(kem_context, enc, X25519_PUBLIC_VALUE_LEN); - OPENSSL_memcpy(kem_context + X25519_PUBLIC_VALUE_LEN, key->public_key, - X25519_PUBLIC_VALUE_LEN); - if (!dhkem_extract_and_expand(key->kem->id, EVP_sha256(), out_shared_secret, - SHA256_DIGEST_LENGTH, dh, sizeof(dh), - kem_context, sizeof(kem_context))) { +int dhkem_encap_external_entropy(const EVP_KEM *kem, + Span out_ciphertext, + Span out_secret, + const EVP_PKEY *peer_key, + Span entropy) { + const auto *dhkem = static_cast(kem); + UniquePtr ephemeral_key(dhkem->key_from_encap_entropy( + dhkem->key_method->alg_func(), entropy.data(), entropy.size())); + if (ephemeral_key == nullptr) { return 0; } - - *out_shared_secret_len = SHA256_DIGEST_LENGTH; - return 1; + return dhkem_encap_with_ephemeral_key(dhkem, out_ciphertext, out_secret, + peer_key, ephemeral_key.get()); } -static int x25519_auth_encap_with_seed( - const EVP_HPKE_KEY *key, uint8_t *out_shared_secret, - size_t *out_shared_secret_len, uint8_t *out_enc, size_t *out_enc_len, - size_t max_enc, const uint8_t *peer_public_key, size_t peer_public_key_len, - const uint8_t *seed, size_t seed_len) { - if (max_enc < X25519_PUBLIC_VALUE_LEN) { - OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE); +int dhkem_decap(const EVP_KEM *kem, Span out_secret, + Span ciphertext, const EVP_PKEY *key) { + const auto *dhkem = static_cast(kem); + const size_t public_len = dhkem->key_method->public_key_len; + if (ciphertext.size() != public_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_CIPHERTEXT_LENGTH); return 0; } - if (seed_len != X25519_PRIVATE_KEY_LEN) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + if (out_secret.size() != dhkem->secret_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH); return 0; } - X25519_public_from_private(out_enc, seed); - - uint8_t dh[2 * X25519_SHARED_KEY_LEN]; - if (peer_public_key_len != X25519_PUBLIC_VALUE_LEN || - !X25519(dh, seed, peer_public_key) || - !X25519(dh + X25519_SHARED_KEY_LEN, key->private_key, peer_public_key)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PEER_KEY); + // pkE = DeserializePublicKey(enc) + UniquePtr ephemeral_key(dhkem->key_method->deserialize_public_key( + dhkem->key_method->alg_func(), ciphertext.data(), ciphertext.size())); + if (ephemeral_key == nullptr) { return 0; } - - uint8_t kem_context[3 * X25519_PUBLIC_VALUE_LEN]; - OPENSSL_memcpy(kem_context, out_enc, X25519_PUBLIC_VALUE_LEN); - OPENSSL_memcpy(kem_context + X25519_PUBLIC_VALUE_LEN, peer_public_key, - X25519_PUBLIC_VALUE_LEN); - OPENSSL_memcpy(kem_context + 2 * X25519_PUBLIC_VALUE_LEN, key->public_key, - X25519_PUBLIC_VALUE_LEN); - if (!dhkem_extract_and_expand(key->kem->id, EVP_sha256(), out_shared_secret, - SHA256_DIGEST_LENGTH, dh, sizeof(dh), - kem_context, sizeof(kem_context))) { + // dh = DH(skR, pkE) + InplaceVector dh; + if (!dh.TryResizeForOverwrite(dhkem->dh_shared_key_len) || + !dhkem_dh(dhkem, Span(dh), key, ephemeral_key.get())) { return 0; } - - *out_enc_len = X25519_PUBLIC_VALUE_LEN; - *out_shared_secret_len = SHA256_DIGEST_LENGTH; - return 1; + // pkRm = SerializePublicKey(pk(skR)) + // kem_context = concat(enc, pkRm) + InplaceVector kem_context; + if (!kem_context.TryResizeForOverwrite(2 * public_len) || + !dhkem_serialize_public_key(dhkem, Span(kem_context).subspan(public_len), + key)) { + return 0; + } + OPENSSL_memcpy(kem_context.data(), ciphertext.data(), ciphertext.size()); + // shared_secret = ExtractAndExpand(dh, kem_context) + return dhkem_extract_and_expand(dhkem->key_method->hpke_kem_id, + dhkem->hkdf_digest_func(), out_secret.data(), + out_secret.size(), dh.data(), dh.size(), + kem_context.data(), kem_context.size()); +} + +int dhkem_auth_encap_with_ephemeral_key(const EVP_KEM_DHKEM *dhkem, + Span out_ciphertext, + Span out_secret, + const EVP_PKEY *peer_key, + const EVP_PKEY *auth_key, + const EVP_PKEY *ephemeral_key) { + const size_t public_len = dhkem->key_method->public_key_len; + if (out_ciphertext.size() != public_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_CIPHERTEXT_LENGTH); + return 0; + } + if (out_secret.size() != dhkem->secret_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH); + return 0; + } + // dh = concat(DH(skE, pkR), DH(skS, pkR)) + InplaceVector dh; + if (!dh.TryResizeForOverwrite(2 * dhkem->dh_shared_key_len) || + !dhkem_dh(dhkem, Span(dh).subspan(0, dhkem->dh_shared_key_len), + ephemeral_key, peer_key) || + !dhkem_dh(dhkem, Span(dh).subspan(dhkem->dh_shared_key_len), auth_key, + peer_key)) { + return 0; + } + // enc = SerializePublicKey(pkE) + // pkRm = SerializePublicKey(pkR) + // pkSm = SerializePublicKey(pk(skS)) + // kem_context = concat(enc, pkRm, pkSm) + InplaceVector kem_context; + if (!kem_context.TryResizeForOverwrite(3 * public_len) || + !dhkem_serialize_public_keys(dhkem, Span(kem_context), ephemeral_key, + peer_key, auth_key)) { + return 0; + } + OPENSSL_memcpy(out_ciphertext.data(), kem_context.data(), public_len); + // shared_secret = ExtractAndExpand(dh, kem_context) + return dhkem_extract_and_expand(dhkem->key_method->hpke_kem_id, + dhkem->hkdf_digest_func(), out_secret.data(), + out_secret.size(), dh.data(), dh.size(), + kem_context.data(), kem_context.size()); +} + +int dhkem_auth_encap(const EVP_KEM *kem, Span out_ciphertext, + Span out_secret, const EVP_PKEY *peer_key, + const EVP_PKEY *auth_key) { + const auto *dhkem = static_cast(kem); + UniquePtr ephemeral_key( + EVP_PKEY_generate_from_alg(dhkem->key_method->alg_func())); + if (ephemeral_key == nullptr) { + return 0; + } + return dhkem_auth_encap_with_ephemeral_key(dhkem, out_ciphertext, out_secret, + peer_key, auth_key, + ephemeral_key.get()); +} + +int dhkem_auth_encap_external_entropy(const EVP_KEM *kem, + Span out_ciphertext, + Span out_secret, + const EVP_PKEY *peer_key, + const EVP_PKEY *auth_key, + Span entropy) { + const auto *dhkem = static_cast(kem); + UniquePtr ephemeral_key(dhkem->key_from_encap_entropy( + dhkem->key_method->alg_func(), entropy.data(), entropy.size())); + if (ephemeral_key == nullptr) { + return 0; + } + return dhkem_auth_encap_with_ephemeral_key(dhkem, out_ciphertext, out_secret, + peer_key, auth_key, + ephemeral_key.get()); } -static int x25519_auth_decap(const EVP_HPKE_KEY *key, - uint8_t *out_shared_secret, - size_t *out_shared_secret_len, const uint8_t *enc, - size_t enc_len, const uint8_t *peer_public_key, - size_t peer_public_key_len) { - uint8_t dh[2 * X25519_SHARED_KEY_LEN]; - if (enc_len != X25519_PUBLIC_VALUE_LEN || - peer_public_key_len != X25519_PUBLIC_VALUE_LEN || - !X25519(dh, key->private_key, enc) || - !X25519(dh + X25519_SHARED_KEY_LEN, key->private_key, peer_public_key)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PEER_KEY); +int dhkem_auth_decap(const EVP_KEM *kem, Span out_secret, + Span ciphertext, const EVP_PKEY *key, + const EVP_PKEY *auth_key) { + const auto *dhkem = static_cast(kem); + const size_t public_len = dhkem->key_method->public_key_len; + if (ciphertext.size() != public_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_CIPHERTEXT_LENGTH); return 0; } - - uint8_t kem_context[3 * X25519_PUBLIC_VALUE_LEN]; - OPENSSL_memcpy(kem_context, enc, X25519_PUBLIC_VALUE_LEN); - OPENSSL_memcpy(kem_context + X25519_PUBLIC_VALUE_LEN, key->public_key, - X25519_PUBLIC_VALUE_LEN); - OPENSSL_memcpy(kem_context + 2 * X25519_PUBLIC_VALUE_LEN, peer_public_key, - X25519_PUBLIC_VALUE_LEN); - if (!dhkem_extract_and_expand(key->kem->id, EVP_sha256(), out_shared_secret, - SHA256_DIGEST_LENGTH, dh, sizeof(dh), - kem_context, sizeof(kem_context))) { + if (out_secret.size() != dhkem->secret_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH); + return 0; + } + // pkE = DeserializePublicKey(enc) + UniquePtr ephemeral_key(dhkem->key_method->deserialize_public_key( + dhkem->key_method->alg_func(), ciphertext.data(), ciphertext.size())); + if (ephemeral_key == nullptr) { return 0; } + // dh = concat(DH(skR, pkE), DH(skR, pkS)) + InplaceVector dh; + if (!dh.TryResizeForOverwrite(2 * dhkem->dh_shared_key_len) || + !dhkem_dh(dhkem, Span(dh).subspan(0, dhkem->dh_shared_key_len), key, + ephemeral_key.get()) || + !dhkem_dh(dhkem, Span(dh).subspan(dhkem->dh_shared_key_len), key, + auth_key)) { + return 0; + } + // pkRm = SerializePublicKey(pk(skR)) + // pkSm = SerializePublicKey(pkS) + // kem_context = concat(enc, pkRm, pkSm) + InplaceVector kem_context; + if (!kem_context.TryResizeForOverwrite(3 * public_len) || + !dhkem_serialize_public_keys(dhkem, Span(kem_context).subspan(public_len), + key, auth_key)) { + return 0; + } + OPENSSL_memcpy(kem_context.data(), ciphertext.data(), ciphertext.size()); + // shared_secret = ExtractAndExpand(dh, kem_context) + return dhkem_extract_and_expand(dhkem->key_method->hpke_kem_id, + dhkem->hkdf_digest_func(), out_secret.data(), + out_secret.size(), dh.data(), dh.size(), + kem_context.data(), kem_context.size()); +} - *out_shared_secret_len = SHA256_DIGEST_LENGTH; - return 1; +// RFC 9180: "For X25519 ..., the DeriveKeyPair() function applies a KDF to the +// input." Since HPKE uses X25519 only in the DHKEM(X25519, HKDF-SHA256) +// construction, this uses HKDF-SHA256 as the KDF. +EVP_PKEY *x25519_derive_key_pair(const EVP_PKEY_ALG *alg, uint16_t kem_suite_id, + Span ikm) { + // https://www.rfc-editor.org/rfc/rfc9180.html#name-derivekeypair + auto suite_id = hpke_kem_suite_id(kem_suite_id); + uint8_t dkp_prk[SHA256_DIGEST_LENGTH]; + size_t dkp_prk_len; + uint8_t sk[X25519_PRIVATE_KEY_LEN]; + if (!hpke_labeled_extract(EVP_sha256(), dkp_prk, &dkp_prk_len, nullptr, 0, + suite_id.data(), suite_id.size(), "dkp_prk", + ikm.data(), ikm.size()) || + !hpke_labeled_expand(EVP_sha256(), sk, sizeof(sk), dkp_prk, dkp_prk_len, + suite_id.data(), suite_id.size(), "sk", + /*info=*/nullptr, /*info_len=*/0)) { + return nullptr; + } + return EVP_PKEY_from_raw_private_key(alg, sk, sizeof(sk)); +} + +constexpr HpkeKeyMethod kX25519KeyMethod = { + /*hpke_kem_id=*/EVP_HPKE_DHKEM_X25519_HKDF_SHA256, + /*public_key_len=*/X25519_PUBLIC_VALUE_LEN, + /*private_key_len=*/X25519_PRIVATE_KEY_LEN, + /*alg_func=*/&EVP_pkey_x25519, + /*deserialize_private_key=*/&EVP_PKEY_from_raw_private_key, + /*serialize_private_key=*/&EVP_PKEY_get_raw_private_key, + /*deserialize_public_key=*/&EVP_PKEY_from_raw_public_key, + /*serialize_public_key=*/&EVP_PKEY_get_raw_public_key, + /*derive_key_pair=*/x25519_derive_key_pair, +}; + +} // namespace + +const EVP_KEM *EVP_kem_dhkem_x25519_hkdf_sha256() { + static constexpr EVP_KEM_DHKEM kDhkemX25519 = { + /*EVP_KEM=*/{ + /*pkey_id=*/EVP_PKEY_X25519, + /*ciphertext_len=*/X25519_PUBLIC_VALUE_LEN, + /*secret_len=*/SHA256_DIGEST_LENGTH, + /*entropy_len=*/X25519_PRIVATE_KEY_LEN, + /*check_key=*/nullptr, + /*encap=*/&dhkem_encap, + /*encap_external_entropy=*/&dhkem_encap_external_entropy, + /*decap=*/&dhkem_decap, + }, + /*dh_shared_key_len=*/X25519_SHARED_KEY_LEN, + /*key_method=*/&kX25519KeyMethod, + /*hkdf_digest_func=*/&EVP_sha256, + // The X25519 encap entropy is the ephemeral private key itself. + /*key_from_encap_entropy=*/&EVP_PKEY_from_raw_private_key, + }; + return &kDhkemX25519; } const EVP_HPKE_KEM *EVP_hpke_x25519_hkdf_sha256() { - static const EVP_HPKE_KEM kKEM = { + static constexpr EVP_HPKE_KEM kKEM = { /*id=*/EVP_HPKE_DHKEM_X25519_HKDF_SHA256, - // TODO(crbug.com/503758094): Expose this as an EVP_KEM. - /*evp_pkey_alg_func=*/nullptr, - /*evp_kem_func=*/nullptr, - /*public_key_len=*/X25519_PUBLIC_VALUE_LEN, - /*private_key_len=*/X25519_PRIVATE_KEY_LEN, - /*seed_len=*/X25519_PRIVATE_KEY_LEN, - /*enc_len=*/X25519_PUBLIC_VALUE_LEN, - x25519_init_key, - x25519_generate_key, - x25519_derive_key, - x25519_encap_with_seed, - x25519_decap, - x25519_auth_encap_with_seed, - x25519_auth_decap, - // TODO(crbug.com/503758094): Implement this in terms of an EVP_KEM. - /*evp_deserialize_private_key=*/nullptr, - /*evp_serialize_private_key=*/nullptr, - /*evp_deserialize_public_key=*/nullptr, - /*evp_serialize_public_key=*/nullptr, - /*evp_derive_key_pair=*/nullptr, + /*evp_kem_func=*/&EVP_kem_dhkem_x25519_hkdf_sha256, + /*key_method=*/&kX25519KeyMethod, + /*auth_encap=*/&dhkem_auth_encap, + /*auth_encap_external_entropy=*/&dhkem_auth_encap_external_entropy, + /*auth_decap=*/&dhkem_auth_decap, }; return &kKEM; } -#define P256_PRIVATE_KEY_LEN 32 -#define P256_PUBLIC_KEY_LEN 65 -#define P256_PUBLIC_VALUE_LEN 65 -#define P256_SEED_LEN 32 -#define P256_SHARED_KEY_LEN 32 - -static int p256_public_from_private(uint8_t out_pub[P256_PUBLIC_VALUE_LEN], - const uint8_t priv[P256_PRIVATE_KEY_LEN]) { - const EC_GROUP *const group = EC_group_p256(); - const uint8_t kAllZeros[P256_PRIVATE_KEY_LEN] = {0}; - EC_SCALAR private_scalar; - EC_JACOBIAN public_point; - EC_AFFINE public_point_affine; - - if (CRYPTO_memcmp(kAllZeros, priv, sizeof(kAllZeros)) == 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } +namespace { - if (!ec_scalar_from_bytes(group, &private_scalar, priv, - P256_PRIVATE_KEY_LEN) || - !ec_point_mul_scalar_base(group, &public_point, &private_scalar) || - !ec_jacobian_to_affine(group, &public_point_affine, &public_point)) { +constexpr size_t kP256PrivateKeyLen = 32; +constexpr size_t kP256PublicValueLen = 65; +constexpr size_t kP256SeedLen = 32; +constexpr size_t kP256SharedKeyLen = 32; + +// RFC 9180's SerializePublicKey format for DHKEM(P-256, HKDF-SHA256) is the +// uncompressed X9.62 point, and its private keys are the big-endian scalar. +int p256_serialize_public_key(const EVP_PKEY *pkey, uint8_t *out, + size_t *out_len) { + CBB cbb; + CBB_init_fixed(&cbb, out, *out_len); + if (!EVP_PKEY_marshal_ec_uncompressed_point(&cbb, pkey)) { return 0; } - - size_t out_len_x, out_len_y; - out_pub[0] = POINT_CONVERSION_UNCOMPRESSED; - ec_felem_to_bytes(group, &out_pub[1], &out_len_x, &public_point_affine.X); - ec_felem_to_bytes(group, &out_pub[33], &out_len_y, &public_point_affine.Y); + *out_len = CBB_len(&cbb); return 1; } -static int p256_init_key(EVP_HPKE_KEY *key, const uint8_t *priv_key, - size_t priv_key_len) { - if (priv_key_len != P256_PRIVATE_KEY_LEN) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - if (!p256_public_from_private(key->public_key, priv_key)) { +int p256_serialize_private_key(const EVP_PKEY *pkey, uint8_t *out, + size_t *out_len) { + CBB cbb; + CBB_init_fixed(&cbb, out, *out_len); + if (!EVP_PKEY_marshal_ec_private_scalar(&cbb, pkey)) { return 0; } - - OPENSSL_memcpy(key->private_key, priv_key, priv_key_len); + *out_len = CBB_len(&cbb); return 1; } -static int p256_private_key_from_seed(uint8_t out_priv[P256_PRIVATE_KEY_LEN], - const uint8_t *seed, size_t seed_len) { +EVP_PKEY *p256_derive_key_pair(const EVP_PKEY_ALG *alg, uint16_t kem_suite_id, + Span ikm) { // https://www.rfc-editor.org/rfc/rfc9180.html#name-derivekeypair - auto suite_id = hpke_kem_suite_id(EVP_HPKE_DHKEM_P256_HKDF_SHA256); - uint8_t dkp_prk[32]; + auto suite_id = hpke_kem_suite_id(kem_suite_id); + uint8_t dkp_prk[SHA256_DIGEST_LENGTH]; size_t dkp_prk_len; if (!hpke_labeled_extract(EVP_sha256(), dkp_prk, &dkp_prk_len, nullptr, 0, - suite_id.data(), suite_id.size(), "dkp_prk", seed, - seed_len)) { - return 0; + suite_id.data(), suite_id.size(), "dkp_prk", + ikm.data(), ikm.size())) { + return nullptr; } assert(dkp_prk_len == sizeof(dkp_prk)); - const EC_GROUP *const group = EC_group_p256(); - EC_SCALAR private_scalar; - for (unsigned counter = 0; counter < 256; counter++) { + // Rejection sampling. + uint8_t priv[kP256PrivateKeyLen]; + for (size_t counter = 0; counter < 256; counter++) { const uint8_t counter_byte = counter & 0xff; - if (!hpke_labeled_expand(EVP_sha256(), out_priv, P256_PRIVATE_KEY_LEN, - dkp_prk, sizeof(dkp_prk), suite_id.data(), - suite_id.size(), "candidate", &counter_byte, + if (!hpke_labeled_expand(EVP_sha256(), priv, sizeof(priv), dkp_prk, + sizeof(dkp_prk), suite_id.data(), suite_id.size(), + "candidate", &counter_byte, sizeof(counter_byte))) { - return 0; + return nullptr; } - + EC_SCALAR private_scalar; // `ec_scalar_from_bytes` checks that the scalar is less than the order. - if (ec_scalar_from_bytes(group, &private_scalar, out_priv, - P256_PRIVATE_KEY_LEN) && + if (ec_scalar_from_bytes(group, &private_scalar, priv, sizeof(priv)) && !ec_scalar_is_zero(group, &private_scalar)) { - return 1; + return EVP_PKEY_from_ec_private_scalar(alg, priv, sizeof(priv)); } } - // This happens with probability of 2^-(32*256). OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR); - return 0; -} - -static int p256_derive_key(EVP_HPKE_KEY *key, Span ikm) { - if (!p256_private_key_from_seed(key->private_key, ikm.data(), ikm.size()) || - !p256_public_from_private(key->public_key, key->private_key)) { - return 0; - } - return 1; -} - -static int p256_generate_key(EVP_HPKE_KEY *key) { - uint8_t seed[P256_SEED_LEN]; - RAND_bytes(seed, sizeof(seed)); - return p256_derive_key(key, seed); -} - -static int p256(uint8_t out_dh[P256_SHARED_KEY_LEN], - const uint8_t my_private[P256_PRIVATE_KEY_LEN], - const uint8_t their_public[P256_PUBLIC_VALUE_LEN]) { - const EC_GROUP *const group = EC_group_p256(); - EC_SCALAR private_scalar; - EC_FELEM x, y; - EC_JACOBIAN shared_point, their_point; - EC_AFFINE their_point_affine, shared_point_affine; - - if (their_public[0] != POINT_CONVERSION_UNCOMPRESSED || - !ec_felem_from_bytes(group, &x, &their_public[1], 32) || - !ec_felem_from_bytes(group, &y, &their_public[33], 32) || - !ec_point_set_affine_coordinates(group, &their_point_affine, &x, &y) || - !ec_scalar_from_bytes(group, &private_scalar, my_private, - P256_PRIVATE_KEY_LEN)) { - OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR); - return 0; - } - - ec_affine_to_jacobian(group, &their_point, &their_point_affine); - if (!ec_point_mul_scalar(group, &shared_point, &their_point, - &private_scalar) || - !ec_jacobian_to_affine(group, &shared_point_affine, &shared_point)) { - OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR); - return 0; - } - - size_t out_len; - ec_felem_to_bytes(group, out_dh, &out_len, &shared_point_affine.X); - assert(out_len == P256_SHARED_KEY_LEN); - return 1; -} - -static int p256_encap_with_seed(const EVP_HPKE_KEM *kem, - uint8_t *out_shared_secret, - size_t *out_shared_secret_len, uint8_t *out_enc, - size_t *out_enc_len, size_t max_enc, - const uint8_t *peer_public_key, - size_t peer_public_key_len, const uint8_t *seed, - size_t seed_len) { - if (max_enc < P256_PUBLIC_VALUE_LEN) { - OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE); - return 0; - } - if (seed_len != P256_SEED_LEN) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - uint8_t private_key[P256_PRIVATE_KEY_LEN]; - if (!p256_private_key_from_seed(private_key, seed, seed_len) || - !p256_public_from_private(out_enc, private_key)) { - return 0; - } - - uint8_t dh[P256_SHARED_KEY_LEN]; - if (peer_public_key_len != P256_PUBLIC_VALUE_LEN || - !p256(dh, private_key, peer_public_key)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PEER_KEY); - return 0; - } - - uint8_t kem_context[2 * P256_PUBLIC_VALUE_LEN]; - OPENSSL_memcpy(kem_context, out_enc, P256_PUBLIC_VALUE_LEN); - OPENSSL_memcpy(kem_context + P256_PUBLIC_VALUE_LEN, peer_public_key, - P256_PUBLIC_VALUE_LEN); - if (!dhkem_extract_and_expand(kem->id, EVP_sha256(), out_shared_secret, - SHA256_DIGEST_LENGTH, dh, sizeof(dh), - kem_context, sizeof(kem_context))) { - return 0; - } - - *out_enc_len = P256_PUBLIC_VALUE_LEN; - *out_shared_secret_len = SHA256_DIGEST_LENGTH; - return 1; + return nullptr; } -static int p256_decap(const EVP_HPKE_KEY *key, uint8_t *out_shared_secret, - size_t *out_shared_secret_len, const uint8_t *enc, - size_t enc_len) { - uint8_t dh[P256_SHARED_KEY_LEN]; - if (enc_len != P256_PUBLIC_VALUE_LEN || // - !p256(dh, key->private_key, enc)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PEER_KEY); - return 0; - } - - uint8_t kem_context[2 * P256_PUBLIC_VALUE_LEN]; - OPENSSL_memcpy(kem_context, enc, P256_PUBLIC_VALUE_LEN); - OPENSSL_memcpy(kem_context + P256_PUBLIC_VALUE_LEN, key->public_key, - P256_PUBLIC_VALUE_LEN); - if (!dhkem_extract_and_expand(key->kem->id, EVP_sha256(), out_shared_secret, - SHA256_DIGEST_LENGTH, dh, sizeof(dh), - kem_context, sizeof(kem_context))) { - return 0; - } - - *out_shared_secret_len = SHA256_DIGEST_LENGTH; - return 1; +// The P-256 encap entropy is ikmE, the input to DeriveKeyPair. +EVP_PKEY *p256_key_from_encap_entropy(const EVP_PKEY_ALG *alg, + const uint8_t *in, size_t len) { + return p256_derive_key_pair(alg, EVP_HPKE_DHKEM_P256_HKDF_SHA256, + Span(in, len)); } -static int p256_auth_encap_with_seed( - const EVP_HPKE_KEY *key, uint8_t *out_shared_secret, - size_t *out_shared_secret_len, uint8_t *out_enc, size_t *out_enc_len, - size_t max_enc, const uint8_t *peer_public_key, size_t peer_public_key_len, - const uint8_t *seed, size_t seed_len) { - if (max_enc < P256_PUBLIC_VALUE_LEN) { - OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE); - return 0; - } - if (seed_len != P256_SEED_LEN) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - uint8_t private_key[P256_PRIVATE_KEY_LEN]; - if (!p256_private_key_from_seed(private_key, seed, seed_len) || - !p256_public_from_private(out_enc, private_key)) { - return 0; - } - - uint8_t dh[2 * P256_SHARED_KEY_LEN]; - if (peer_public_key_len != P256_PUBLIC_VALUE_LEN || - !p256(dh, private_key, peer_public_key) || - !p256(dh + P256_SHARED_KEY_LEN, key->private_key, peer_public_key)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PEER_KEY); - return 0; - } - - uint8_t kem_context[3 * P256_PUBLIC_VALUE_LEN]; - OPENSSL_memcpy(kem_context, out_enc, P256_PUBLIC_VALUE_LEN); - OPENSSL_memcpy(kem_context + P256_PUBLIC_VALUE_LEN, peer_public_key, - P256_PUBLIC_VALUE_LEN); - OPENSSL_memcpy(kem_context + 2 * P256_PUBLIC_VALUE_LEN, key->public_key, - P256_PUBLIC_VALUE_LEN); - if (!dhkem_extract_and_expand(key->kem->id, EVP_sha256(), out_shared_secret, - SHA256_DIGEST_LENGTH, dh, sizeof(dh), - kem_context, sizeof(kem_context))) { - return 0; - } - - *out_enc_len = P256_PUBLIC_VALUE_LEN; - *out_shared_secret_len = SHA256_DIGEST_LENGTH; - return 1; +bool p256_check_key(const EVP_KEM *kem, const EVP_PKEY *key) { + const EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(key); + return ec_key != nullptr && + EC_GROUP_cmp(EC_KEY_get0_group(ec_key), EC_group_p256(), + /*ignored=*/nullptr) == 0; } -static int p256_auth_decap(const EVP_HPKE_KEY *key, uint8_t *out_shared_secret, - size_t *out_shared_secret_len, const uint8_t *enc, - size_t enc_len, const uint8_t *peer_public_key, - size_t peer_public_key_len) { - uint8_t dh[2 * P256_SHARED_KEY_LEN]; - if (enc_len != P256_PUBLIC_VALUE_LEN || - peer_public_key_len != P256_PUBLIC_VALUE_LEN || - !p256(dh, key->private_key, enc) || - !p256(dh + P256_SHARED_KEY_LEN, key->private_key, peer_public_key)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PEER_KEY); - return 0; - } +constexpr HpkeKeyMethod kP256KeyMethod = { + /*hpke_kem_id=*/EVP_HPKE_DHKEM_P256_HKDF_SHA256, + /*public_key_len=*/kP256PublicValueLen, + /*private_key_len=*/kP256PrivateKeyLen, + /*alg_func=*/&EVP_pkey_ec_p256, + /*deserialize_private_key=*/&EVP_PKEY_from_ec_private_scalar, + /*serialize_private_key=*/&p256_serialize_private_key, + /*deserialize_public_key=*/&EVP_PKEY_from_ec_uncompressed_point, + /*serialize_public_key=*/&p256_serialize_public_key, + /*derive_key_pair=*/&p256_derive_key_pair, +}; - uint8_t kem_context[3 * P256_PUBLIC_VALUE_LEN]; - OPENSSL_memcpy(kem_context, enc, P256_PUBLIC_VALUE_LEN); - OPENSSL_memcpy(kem_context + P256_PUBLIC_VALUE_LEN, key->public_key, - P256_PUBLIC_VALUE_LEN); - OPENSSL_memcpy(kem_context + 2 * P256_PUBLIC_VALUE_LEN, peer_public_key, - P256_PUBLIC_VALUE_LEN); - if (!dhkem_extract_and_expand(key->kem->id, EVP_sha256(), out_shared_secret, - SHA256_DIGEST_LENGTH, dh, sizeof(dh), - kem_context, sizeof(kem_context))) { - return 0; - } +} // namespace - *out_shared_secret_len = SHA256_DIGEST_LENGTH; - return 1; +const EVP_KEM *EVP_kem_dhkem_p256_hkdf_sha256() { + static constexpr EVP_KEM_DHKEM kDhkemP256 = { + /*EVP_KEM=*/{ + /*pkey_id=*/EVP_PKEY_EC, + /*ciphertext_len=*/kP256PublicValueLen, + /*secret_len=*/SHA256_DIGEST_LENGTH, + /*entropy_len=*/kP256SeedLen, + /*check_key=*/&p256_check_key, + /*encap=*/&dhkem_encap, + /*encap_external_entropy=*/&dhkem_encap_external_entropy, + /*decap=*/&dhkem_decap, + }, + /*dh_shared_key_len=*/kP256SharedKeyLen, + /*key_method=*/&kP256KeyMethod, + /*hkdf_digest_func=*/&EVP_sha256, + /*key_from_encap_entropy=*/&p256_key_from_encap_entropy, + }; + return &kDhkemP256; } const EVP_HPKE_KEM *EVP_hpke_p256_hkdf_sha256() { - static const EVP_HPKE_KEM kKEM = { + static constexpr EVP_HPKE_KEM kKEM = { /*id=*/EVP_HPKE_DHKEM_P256_HKDF_SHA256, - // TODO(crbug.com/503758094): Expose this as an EVP_KEM. - /*evp_pkey_alg_func=*/nullptr, - /*evp_kem_func=*/nullptr, - /*public_key_len=*/P256_PUBLIC_KEY_LEN, - /*private_key_len=*/P256_PRIVATE_KEY_LEN, - /*seed_len=*/P256_SEED_LEN, - /*enc_len=*/P256_PUBLIC_VALUE_LEN, - p256_init_key, - p256_generate_key, - p256_derive_key, - p256_encap_with_seed, - p256_decap, - p256_auth_encap_with_seed, - p256_auth_decap, - // TODO(crbug.com/503758094): Implement this in terms of an EVP_KEM. - /*evp_deserialize_private_key=*/nullptr, - /*evp_serialize_private_key=*/nullptr, - /*evp_deserialize_public_key=*/nullptr, - /*evp_serialize_public_key=*/nullptr, - /*evp_derive_key_pair=*/nullptr, + /*evp_kem_func=*/&EVP_kem_dhkem_p256_hkdf_sha256, + /*key_method=*/&kP256KeyMethod, + /*auth_encap=*/&dhkem_auth_encap, + /*auth_encap_external_entropy=*/&dhkem_auth_encap_external_entropy, + /*auth_decap=*/&dhkem_auth_decap, }; return &kKEM; } -#define XWING_PRIVATE_KEY_LEN XWING_PRIVATE_KEY_BYTES -#define XWING_PUBLIC_KEY_LEN XWING_PUBLIC_KEY_BYTES -#define XWING_PUBLIC_VALUE_LEN XWING_CIPHERTEXT_BYTES -#define XWING_SEED_LEN 64 -#define XWING_SHARED_KEY_LEN XWING_SHARED_SECRET_BYTES +namespace { -static EVP_PKEY *xwing_derive_key_pair(const EVP_PKEY_ALG *alg, - Span ikm) { - uint8_t seed[XWING_PRIVATE_KEY_BYTES]; - hpke_shake256_labeled_derive(seed, ikm, hpke_kem_suite_id(EVP_HPKE_XWING), +template +EVP_PKEY *shake256_derive_key_pair_from_private_seed(const EVP_PKEY_ALG *alg, + uint16_t kem_suite_id, + Span ikm) { + uint8_t seed[SEED_BYTES]; + hpke_shake256_labeled_derive(seed, ikm, hpke_kem_suite_id(kem_suite_id), "DeriveKeyPair", /*context=*/{}); return EVP_PKEY_from_private_seed(alg, seed, sizeof(seed)); } +constexpr HpkeKeyMethod kXwingKeyMethod = { + /*hpke_kem_id=*/EVP_HPKE_XWING, + /*public_key_len=*/XWING_PUBLIC_KEY_BYTES, + /*private_key_len=*/XWING_PRIVATE_KEY_BYTES, + /*alg_func=*/&EVP_pkey_xwing, + /*deserialize_private_key=*/&EVP_PKEY_from_private_seed, + /*serialize_private_key=*/&EVP_PKEY_get_private_seed, + /*deserialize_public_key=*/&EVP_PKEY_from_raw_public_key, + /*serialize_public_key=*/&EVP_PKEY_get_raw_public_key, + /*derive_key_pair=*/ + shake256_derive_key_pair_from_private_seed, +}; + +} // namespace const EVP_HPKE_KEM *EVP_hpke_xwing() { - static const EVP_HPKE_KEM kKEM = { + static constexpr EVP_HPKE_KEM kKEM = { /*id=*/EVP_HPKE_XWING, - /*evp_pkey_alg_func=*/&EVP_pkey_xwing, /*evp_kem_func=*/&EVP_kem_xwing, - /*public_key_len=*/XWING_PUBLIC_KEY_LEN, - /*private_key_len=*/XWING_PRIVATE_KEY_LEN, - /*seed_len=*/0, - /*enc_len=*/0, - /*init_key=*/nullptr, - /*generate_key=*/nullptr, - /*derive_key=*/nullptr, - /*encap_with_seed=*/nullptr, - /*decap=*/nullptr, + /*key_method=*/&kXwingKeyMethod, // X-Wing doesn't support authenticated encapsulation/decapsulation: // https://datatracker.ietf.org/doc/html/draft-connolly-cfrg-xwing-kem-08#name-use-in-hpke - /* auth_encap_with_seed= */ nullptr, - /* auth_decap= */ nullptr, - /*evp_deserialize_private_key=*/&EVP_PKEY_from_private_seed, - /*evp_serialize_private_key=*/&EVP_PKEY_get_private_seed, - /*evp_deserialize_public_key=*/&EVP_PKEY_from_raw_public_key, - /*evp_serialize_public_key=*/&EVP_PKEY_get_raw_public_key, - /*evp_derive_key_pair=*/xwing_derive_key_pair, + /*auth_encap=*/nullptr, + /*auth_encap_external_entropy=*/nullptr, + /*auth_decap=*/nullptr, }; return &kKEM; } -static EVP_PKEY *mlkem768_derive_key_pair(const EVP_PKEY_ALG *alg, - Span ikm) { - uint8_t seed[MLKEM_SEED_BYTES]; - hpke_shake256_labeled_derive(seed, ikm, hpke_kem_suite_id(EVP_HPKE_MLKEM768), - "DeriveKeyPair", /*context=*/{}); - return EVP_PKEY_from_private_seed(alg, seed, sizeof(seed)); -} +namespace { + +constexpr HpkeKeyMethod kMlkem768KeyMethod = { + /*hpke_kem_id=*/EVP_HPKE_MLKEM768, + /*public_key_len=*/MLKEM768_PUBLIC_KEY_BYTES, + /*private_key_len=*/MLKEM_SEED_BYTES, + /*alg_func=*/&EVP_pkey_ml_kem_768, + /*deserialize_private_key=*/&EVP_PKEY_from_private_seed, + /*serialize_private_key=*/&EVP_PKEY_get_private_seed, + /*deserialize_public_key=*/&EVP_PKEY_from_raw_public_key, + /*serialize_public_key=*/&EVP_PKEY_get_raw_public_key, + /*derive_key_pair=*/ + shake256_derive_key_pair_from_private_seed, +}; + +constexpr HpkeKeyMethod kMlkem1024KeyMethod = { + /*hpke_kem_id=*/EVP_HPKE_MLKEM1024, + /*public_key_len=*/MLKEM1024_PUBLIC_KEY_BYTES, + /*private_key_len=*/MLKEM_SEED_BYTES, + /*alg_func=*/&EVP_pkey_ml_kem_1024, + /*deserialize_private_key=*/&EVP_PKEY_from_private_seed, + /*serialize_private_key=*/&EVP_PKEY_get_private_seed, + /*deserialize_public_key=*/&EVP_PKEY_from_raw_public_key, + /*serialize_public_key=*/&EVP_PKEY_get_raw_public_key, + /*derive_key_pair=*/ + shake256_derive_key_pair_from_private_seed, +}; + +} // namespace const EVP_HPKE_KEM *EVP_hpke_mlkem768() { - static const EVP_HPKE_KEM kKEM = { + static constexpr EVP_HPKE_KEM kKEM = { /*id=*/EVP_HPKE_MLKEM768, - /*evp_pkey_alg_func=*/&EVP_pkey_ml_kem_768, /*evp_kem_func=*/&EVP_kem_ml_kem_768, - /*public_key_len=*/MLKEM768_PUBLIC_KEY_BYTES, - /*private_key_len=*/MLKEM_SEED_BYTES, - /*seed_len=*/0, - /*enc_len=*/0, - /*init_key=*/nullptr, - /*generate_key=*/nullptr, - /*derive_key=*/nullptr, - /*encap_with_seed=*/nullptr, - /*decap=*/nullptr, + /*key_method=*/&kMlkem768KeyMethod, // ML-KEM doesn't support authenticated encapsulation/decapsulation: // https://datatracker.ietf.org/doc/draft-ietf-hpke-pq/01/ - /*auth_encap_with_seed=*/nullptr, + /*auth_encap=*/nullptr, + /*auth_encap_external_entropy=*/nullptr, /*auth_decap=*/nullptr, - /*evp_deserialize_private_key=*/&EVP_PKEY_from_private_seed, - /*evp_serialize_private_key=*/&EVP_PKEY_get_private_seed, - /*evp_deserialize_public_key=*/&EVP_PKEY_from_raw_public_key, - /*evp_serialize_public_key=*/&EVP_PKEY_get_raw_public_key, - /*evp_derive_key_pair=*/mlkem768_derive_key_pair, }; return &kKEM; } -static EVP_PKEY *mlkem1024_derive_key_pair(const EVP_PKEY_ALG *alg, - Span ikm) { - uint8_t seed[MLKEM_SEED_BYTES]; - hpke_shake256_labeled_derive(seed, ikm, hpke_kem_suite_id(EVP_HPKE_MLKEM1024), - "DeriveKeyPair", /*context=*/{}); - return EVP_PKEY_from_private_seed(alg, seed, sizeof(seed)); -} - const EVP_HPKE_KEM *EVP_hpke_mlkem1024() { - static const EVP_HPKE_KEM kKEM = { + static constexpr EVP_HPKE_KEM kKEM = { /*id=*/EVP_HPKE_MLKEM1024, - /*evp_pkey_alg_func=*/&EVP_pkey_ml_kem_1024, /*evp_kem_func=*/&EVP_kem_ml_kem_1024, - /*public_key_len=*/MLKEM1024_PUBLIC_KEY_BYTES, - /*private_key_len=*/MLKEM_SEED_BYTES, - /*seed_len=*/0, - /*enc_len=*/0, - /*init_key=*/nullptr, - /*generate_key=*/nullptr, - /*derive_key=*/nullptr, - /*encap_with_seed=*/nullptr, - /*decap=*/nullptr, + /*key_method=*/&kMlkem1024KeyMethod, // ML-KEM doesn't support authenticated encapsulation/decapsulation: // https://datatracker.ietf.org/doc/draft-ietf-hpke-pq/01/ - /*auth_encap_with_seed=*/nullptr, + /*auth_encap=*/nullptr, + /*auth_encap_external_entropy=*/nullptr, /*auth_decap=*/nullptr, - /*evp_deserialize_private_key=*/&EVP_PKEY_from_private_seed, - /*evp_serialize_private_key=*/&EVP_PKEY_get_private_seed, - /*evp_deserialize_public_key=*/&EVP_PKEY_from_raw_public_key, - /*evp_serialize_public_key=*/&EVP_PKEY_get_raw_public_key, - /*evp_derive_key_pair=*/mlkem1024_derive_key_pair, }; return &kKEM; } -namespace { - -// Temporary helper to switch between EVP_KEM-based implementation and legacy -// EVP_HPKE_KEM implementation. -// TODO(crbug.com/535883377): Unify EVP_HPKE_KEM and EVP_KEM for all supported -// HPKE KEMs. - -bool uses_evp(const EVP_HPKE_KEM *kem) { - return kem->evp_pkey_alg_func != nullptr && kem->evp_kem_func != nullptr; -} - -} // namespace - uint16_t EVP_HPKE_KEM_id(const EVP_HPKE_KEM *kem) { return kem->id; } size_t EVP_HPKE_KEM_public_key_len(const EVP_HPKE_KEM *kem) { - return kem->public_key_len; + return kem->key_method->public_key_len; } size_t EVP_HPKE_KEM_private_key_len(const EVP_HPKE_KEM *kem) { - return kem->private_key_len; + return kem->key_method->private_key_len; } -// TODO(crbug.com/535883377): Implement in terms of EVP_KEM for all supported -// HPKE KEMs. size_t EVP_HPKE_KEM_enc_len(const EVP_HPKE_KEM *kem) { - if (uses_evp(kem)) { - return EVP_KEM_ciphertext_len(kem->evp_kem_func()); - } - return kem->enc_len; + return EVP_KEM_ciphertext_len(kem->evp_kem_func()); +} + +size_t EVP_HPKE_KEM_shared_secret_len(const EVP_HPKE_KEM *kem) { + return EVP_KEM_secret_len(kem->evp_kem_func()); } -// TODO(crbug.com/535883377): Implement in terms of EVP_KEM for all supported -// HPKE KEMs. void EVP_HPKE_KEY_zero(EVP_HPKE_KEY *key) { OPENSSL_memset(key, 0, sizeof(EVP_HPKE_KEY)); } -// TODO(crbug.com/535883377): Implement in terms of EVP_KEM for all supported -// HPKE KEMs. void EVP_HPKE_KEY_cleanup(EVP_HPKE_KEY *key) { EVP_PKEY_free(key->pkey); key->pkey = nullptr; @@ -885,12 +855,8 @@ void EVP_HPKE_KEY_free(EVP_HPKE_KEY *key) { } } -// TODO(crbug.com/535883377): Implement in terms of EVP_KEM for all supported -// HPKE KEMs. int EVP_HPKE_KEY_copy(EVP_HPKE_KEY *dst, const EVP_HPKE_KEY *src) { dst->kem = src->kem; - OPENSSL_memcpy(dst->private_key, src->private_key, sizeof(src->private_key)); - OPENSSL_memcpy(dst->public_key, src->public_key, sizeof(src->public_key)); dst->pkey = EVP_PKEY_dup_ref(src->pkey); return 1; } @@ -908,44 +874,26 @@ int EVP_HPKE_KEY_init(EVP_HPKE_KEY *key, const EVP_HPKE_KEM *kem, const uint8_t *priv_key, size_t priv_key_len) { EVP_HPKE_KEY_zero(key); key->kem = kem; - // TODO(crbug.com/535883377): Implement in terms of EVP_KEM for all supported - // HPKE KEMs. - if (uses_evp(kem)) { - UniquePtr pkey(kem->evp_deserialize_private_key( - kem->evp_pkey_alg_func(), priv_key, priv_key_len)); - if (pkey == nullptr) { - key->kem = nullptr; - return 0; - } - key->pkey = pkey.release(); - return 1; - } - if (!kem->init_key(key, priv_key, priv_key_len)) { + UniquePtr pkey(kem->key_method->deserialize_private_key( + kem->key_method->alg_func(), priv_key, priv_key_len)); + if (pkey == nullptr) { key->kem = nullptr; return 0; } + key->pkey = pkey.release(); return 1; } int EVP_HPKE_KEY_generate(EVP_HPKE_KEY *key, const EVP_HPKE_KEM *kem) { EVP_HPKE_KEY_zero(key); key->kem = kem; - // TODO(crbug.com/535883377): Implement in terms of EVP_KEM for all supported - // HPKE KEMs. - if (uses_evp(kem)) { - UniquePtr pkey( - EVP_PKEY_generate_from_alg(kem->evp_pkey_alg_func())); - if (pkey == nullptr) { - key->kem = nullptr; - return 0; - } - key->pkey = pkey.release(); - return 1; - } - if (!kem->generate_key(key)) { + UniquePtr pkey( + EVP_PKEY_generate_from_alg(kem->key_method->alg_func())); + if (pkey == nullptr) { key->kem = nullptr; return 0; } + key->pkey = pkey.release(); return 1; } @@ -953,22 +901,13 @@ int EVP_HPKE_KEY_derive(EVP_HPKE_KEY *key, const EVP_HPKE_KEM *kem, const uint8_t *ikm, size_t ikm_len) { EVP_HPKE_KEY_zero(key); key->kem = kem; - // TODO(crbug.com/535883377): Implement in terms of EVP_KEM for all supported - // HPKE KEMs. - if (uses_evp(kem)) { - UniquePtr pkey( - kem->evp_derive_key_pair(kem->evp_pkey_alg_func(), Span(ikm, ikm_len))); - if (pkey == nullptr) { - key->kem = nullptr; - return 0; - } - key->pkey = pkey.release(); - return 1; - } - if (!kem->derive_key(key, Span(ikm, ikm_len))) { + UniquePtr pkey(kem->key_method->derive_key_pair( + kem->key_method->alg_func(), kem->id, Span(ikm, ikm_len))); + if (pkey == nullptr) { key->kem = nullptr; return 0; } + key->pkey = pkey.release(); return 1; } @@ -978,36 +917,22 @@ const EVP_HPKE_KEM *EVP_HPKE_KEY_kem(const EVP_HPKE_KEY *key) { int EVP_HPKE_KEY_public_key(const EVP_HPKE_KEY *key, uint8_t *out, size_t *out_len, size_t max_out) { - if (max_out < key->kem->public_key_len) { + if (max_out < EVP_HPKE_KEM_public_key_len(key->kem)) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE); return 0; } - // TODO(crbug.com/535883377): Implement in terms of EVP_KEM for all supported - // HPKE KEMs. - if (uses_evp(key->kem)) { - *out_len = max_out; - return key->kem->evp_serialize_public_key(key->pkey, out, out_len); - } - OPENSSL_memcpy(out, key->public_key, key->kem->public_key_len); - *out_len = key->kem->public_key_len; - return 1; + *out_len = max_out; + return key->kem->key_method->serialize_public_key(key->pkey, out, out_len); } int EVP_HPKE_KEY_private_key(const EVP_HPKE_KEY *key, uint8_t *out, size_t *out_len, size_t max_out) { - if (max_out < key->kem->private_key_len) { + if (max_out < EVP_HPKE_KEM_private_key_len(key->kem)) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE); return 0; } - // TODO(crbug.com/535883377): Implement in terms of EVP_KEM for all supported - // HPKE KEMs. - if (uses_evp(key->kem)) { - *out_len = max_out; - return key->kem->evp_serialize_private_key(key->pkey, out, out_len); - } - OPENSSL_memcpy(out, key->private_key, key->kem->private_key_len); - *out_len = key->kem->private_key_len; - return 1; + *out_len = max_out; + return key->kem->key_method->serialize_private_key(key->pkey, out, out_len); } @@ -1056,7 +981,12 @@ const EVP_AEAD *EVP_HPKE_AEAD_aead(const EVP_HPKE_AEAD *aead) { // HPKE implementation. -static std::array hpke_full_suite_id(const EVP_HPKE_CTX *ctx) { +#define HPKE_MODE_BASE 0 +#define HPKE_MODE_AUTH 2 + +namespace { + +std::array hpke_full_suite_id(const EVP_HPKE_CTX *ctx) { return { 'H', 'P', @@ -1070,14 +1000,9 @@ static std::array hpke_full_suite_id(const EVP_HPKE_CTX *ctx) { static_cast(ctx->aead->id), }; } - -#define HPKE_MODE_BASE 0 -#define HPKE_MODE_AUTH 2 - -static int hpke_key_schedule(EVP_HPKE_CTX *ctx, uint8_t mode, - const uint8_t *shared_secret, - size_t shared_secret_len, const uint8_t *info, - size_t info_len) { +int hpke_key_schedule(EVP_HPKE_CTX *ctx, uint8_t mode, + const uint8_t *shared_secret, size_t shared_secret_len, + const uint8_t *info, size_t info_len) { auto suite_id = hpke_full_suite_id(ctx); // psk_id_hash = LabeledExtract("", "psk_id_hash", psk_id) @@ -1151,6 +1076,125 @@ static int hpke_key_schedule(EVP_HPKE_CTX *ctx, uint8_t mode, return 1; } +int hpke_setup_sender_impl(EVP_HPKE_CTX *ctx, uint8_t *out_enc, + size_t *out_enc_len, size_t max_enc, + const EVP_HPKE_KEM *kem, const EVP_HPKE_KDF *kdf, + const EVP_HPKE_AEAD *aead, + Span peer_public_key, + Span info, + std::optional> entropy) { + EVP_HPKE_CTX_zero(ctx); + ctx->is_sender = 1; + ctx->kem = kem; + ctx->kdf = kdf; + ctx->aead = aead; + + const EVP_KEM *evp_kem = kem->evp_kem_func(); + if (max_enc < EVP_KEM_ciphertext_len(evp_kem)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE); + return 0; + } + *out_enc_len = EVP_KEM_ciphertext_len(evp_kem); + + UniquePtr peer_pubkey(kem->key_method->deserialize_public_key( + kem->key_method->alg_func(), peer_public_key.data(), + peer_public_key.size())); + if (peer_pubkey == nullptr) { + return 0; + } + InplaceVector shared_secret; + if (!shared_secret.TryResizeForOverwrite(evp_kem->secret_len)) { + OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR); + return 0; + } + int encap_ok = + entropy.has_value() + ? EVP_KEM_encap_external_entropy_for_testing( + evp_kem, out_enc, *out_enc_len, shared_secret.data(), + shared_secret.size(), peer_pubkey.get(), entropy->data(), + entropy->size()) + : EVP_KEM_encap(evp_kem, out_enc, *out_enc_len, shared_secret.data(), + shared_secret.size(), peer_pubkey.get()); + if (!encap_ok || + !hpke_key_schedule(ctx, HPKE_MODE_BASE, shared_secret.data(), + shared_secret.size(), info.data(), info.size())) { + EVP_HPKE_CTX_cleanup(ctx); + return 0; + } + return 1; +} + +int hpke_setup_auth_sender_impl( + EVP_HPKE_CTX *ctx, uint8_t *out_enc, size_t *out_enc_len, size_t max_enc, + const EVP_HPKE_KEY *key, const EVP_HPKE_KDF *kdf, const EVP_HPKE_AEAD *aead, + Span peer_public_key, Span info, + std::optional> entropy) { + if (entropy.has_value() ? key->kem->auth_encap_external_entropy == nullptr + : key->kem->auth_encap == nullptr) { + // Not all HPKE KEMs support AuthEncap. + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + return 0; + } + + const EVP_KEM *kem = key->kem->evp_kem_func(); + EVP_HPKE_CTX_zero(ctx); + ctx->is_sender = 1; + ctx->kem = key->kem; + ctx->kdf = kdf; + ctx->aead = aead; + if (max_enc < kem->ciphertext_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE); + return 0; + } + UniquePtr peer_key(key->kem->key_method->deserialize_public_key( + key->kem->key_method->alg_func(), peer_public_key.data(), + peer_public_key.size())); + if (peer_key == nullptr) { + return 0; + } + + InplaceVector shared_secret; + if (!shared_secret.TryResizeForOverwrite(kem->secret_len)) { + OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR); + return 0; + } + Span enc_span(out_enc, kem->ciphertext_len); + Span secret_span(shared_secret); + int auth_encap_ok = + entropy.has_value() + ? key->kem->auth_encap_external_entropy( + kem, enc_span, secret_span, peer_key.get(), key->pkey, *entropy) + : key->kem->auth_encap(kem, enc_span, secret_span, peer_key.get(), + key->pkey); + if (!auth_encap_ok || + !hpke_key_schedule(ctx, HPKE_MODE_AUTH, secret_span.data(), + secret_span.size(), info.data(), info.size())) { + EVP_HPKE_CTX_cleanup(ctx); + return 0; + } + *out_enc_len = kem->ciphertext_len; + return 1; +} + +void hpke_nonce(const EVP_HPKE_CTX *ctx, uint8_t *out_nonce, size_t nonce_len) { + assert(nonce_len >= 8); + + // Write padded big-endian bytes of `ctx->seq` to `out_nonce`. + OPENSSL_memset(out_nonce, 0, nonce_len); + uint64_t seq_copy = ctx->seq; + for (size_t i = 0; i < 8; i++) { + out_nonce[nonce_len - i - 1] = seq_copy & 0xff; + seq_copy >>= 8; + } + + // XOR the encoded sequence with the `ctx->base_nonce`. + for (size_t i = 0; i < nonce_len; i++) { + out_nonce[i] ^= ctx->base_nonce[i]; + } +} + +} // namespace + void EVP_HPKE_CTX_zero(EVP_HPKE_CTX *ctx) { OPENSSL_memset(ctx, 0, sizeof(EVP_HPKE_CTX)); EVP_AEAD_CTX_zero(&ctx->aead_ctx); @@ -1176,6 +1220,7 @@ void EVP_HPKE_CTX_free(EVP_HPKE_CTX *ctx) { } } + int EVP_HPKE_CTX_setup_sender(EVP_HPKE_CTX *ctx, uint8_t *out_enc, size_t *out_enc_len, size_t max_enc, const EVP_HPKE_KEM *kem, const EVP_HPKE_KDF *kdf, @@ -1183,44 +1228,10 @@ int EVP_HPKE_CTX_setup_sender(EVP_HPKE_CTX *ctx, uint8_t *out_enc, const uint8_t *peer_public_key, size_t peer_public_key_len, const uint8_t *info, size_t info_len) { - // TODO(crbug.com/535883377): Implement in terms of EVP_KEM for all supported - // HPKE KEMs. - if (uses_evp(kem)) { - EVP_HPKE_CTX_zero(ctx); - ctx->is_sender = 1; - ctx->kem = kem; - ctx->kdf = kdf; - ctx->aead = aead; - uint8_t shared_secret[MAX_SHARED_SECRET_LEN]; - size_t shared_secret_len; - - const EVP_KEM *evp_kem = kem->evp_kem_func(); - if (max_enc < EVP_KEM_ciphertext_len(evp_kem)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE); - return 0; - } - *out_enc_len = EVP_KEM_ciphertext_len(evp_kem); - shared_secret_len = EVP_KEM_secret_len(evp_kem); - assert(size_t{MAX_SHARED_SECRET_LEN} >= shared_secret_len); - - UniquePtr peer_pubkey(kem->evp_deserialize_public_key( - kem->evp_pkey_alg_func(), peer_public_key, peer_public_key_len)); - if (peer_pubkey == nullptr || - !EVP_KEM_encap(evp_kem, out_enc, *out_enc_len, shared_secret, - shared_secret_len, peer_pubkey.get()) || - !hpke_key_schedule(ctx, HPKE_MODE_BASE, shared_secret, - shared_secret_len, info, info_len)) { - EVP_HPKE_CTX_cleanup(ctx); - return 0; - } - return 1; - } - - uint8_t seed[MAX_SEED_LEN]; - RAND_bytes(seed, kem->seed_len); - return EVP_HPKE_CTX_setup_sender_with_seed_for_testing( - ctx, out_enc, out_enc_len, max_enc, kem, kdf, aead, peer_public_key, - peer_public_key_len, info, info_len, seed, kem->seed_len); + return hpke_setup_sender_impl(ctx, out_enc, out_enc_len, max_enc, kem, kdf, + aead, + Span(peer_public_key, peer_public_key_len), + Span(info, info_len), /*entropy=*/std::nullopt); } int EVP_HPKE_CTX_setup_sender_with_seed_for_testing( @@ -1229,44 +1240,28 @@ int EVP_HPKE_CTX_setup_sender_with_seed_for_testing( const uint8_t *peer_public_key, size_t peer_public_key_len, const uint8_t *info, size_t info_len, const uint8_t *seed, size_t seed_len) { + return hpke_setup_sender_impl(ctx, out_enc, out_enc_len, max_enc, kem, kdf, + aead, + Span(peer_public_key, peer_public_key_len), + Span(info, info_len), Span(seed, seed_len)); +} + +int EVP_HPKE_CTX_setup_recipient_with_shared_secret( + EVP_HPKE_CTX *ctx, const EVP_HPKE_KEM *kem, const EVP_HPKE_KDF *kdf, + const EVP_HPKE_AEAD *aead, const uint8_t *shared_secret, + size_t shared_secret_len, const uint8_t *info, size_t info_len) { EVP_HPKE_CTX_zero(ctx); - ctx->is_sender = 1; + + if (shared_secret_len != EVP_HPKE_KEM_shared_secret_len(kem)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE); + return 0; + } + + ctx->is_sender = 0; ctx->kem = kem; ctx->kdf = kdf; ctx->aead = aead; - uint8_t shared_secret[MAX_SHARED_SECRET_LEN]; - size_t shared_secret_len; - - // TODO(crbug.com/535883377): Implement in terms of EVP_KEM for all supported - // HPKE KEMs. - if (uses_evp(kem)) { - const EVP_KEM *evp_kem = kem->evp_kem_func(); - if (max_enc < EVP_KEM_ciphertext_len(evp_kem)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE); - return 0; - } - *out_enc_len = EVP_KEM_ciphertext_len(evp_kem); - shared_secret_len = EVP_KEM_secret_len(evp_kem); - assert(size_t{MAX_SHARED_SECRET_LEN} >= shared_secret_len); - - UniquePtr peer_pubkey(kem->evp_deserialize_public_key( - kem->evp_pkey_alg_func(), peer_public_key, peer_public_key_len)); - if (peer_pubkey == nullptr || - !EVP_KEM_encap_external_entropy_for_testing( - evp_kem, out_enc, *out_enc_len, shared_secret, shared_secret_len, - peer_pubkey.get(), seed, seed_len) || - !hpke_key_schedule(ctx, HPKE_MODE_BASE, shared_secret, - shared_secret_len, info, info_len)) { - EVP_HPKE_CTX_cleanup(ctx); - return 0; - } - return 1; - } - - if (!kem->encap_with_seed(kem, shared_secret, &shared_secret_len, out_enc, - out_enc_len, max_enc, peer_public_key, - peer_public_key_len, seed, seed_len) || - !hpke_key_schedule(ctx, HPKE_MODE_BASE, shared_secret, shared_secret_len, + if (!hpke_key_schedule(ctx, HPKE_MODE_BASE, shared_secret, shared_secret_len, info, info_len)) { EVP_HPKE_CTX_cleanup(ctx); return 0; @@ -1280,57 +1275,31 @@ int EVP_HPKE_CTX_setup_recipient(EVP_HPKE_CTX *ctx, const EVP_HPKE_KEY *key, size_t enc_len, const uint8_t *info, size_t info_len) { EVP_HPKE_CTX_zero(ctx); - ctx->is_sender = 0; - ctx->kem = key->kem; - ctx->kdf = kdf; - ctx->aead = aead; - uint8_t shared_secret[MAX_SHARED_SECRET_LEN]; - size_t shared_secret_len; - - // TODO(crbug.com/535883377): Implement in terms of EVP_KEM for all supported - // HPKE KEMs. - if (uses_evp(key->kem)) { - const EVP_KEM *evp_kem = key->kem->evp_kem_func(); - const EVP_PKEY *decap_key = key->pkey; - shared_secret_len = EVP_KEM_secret_len(evp_kem); - assert(size_t{MAX_SHARED_SECRET_LEN} >= shared_secret_len); - - if (!EVP_KEM_decap(evp_kem, shared_secret, shared_secret_len, enc, enc_len, - decap_key) || - !hpke_key_schedule(ctx, HPKE_MODE_BASE, shared_secret, - shared_secret_len, info, info_len)) { - EVP_HPKE_CTX_cleanup(ctx); - return 0; - } - return 1; - } - if (!key->kem->decap(key, shared_secret, &shared_secret_len, enc, enc_len) || - !hpke_key_schedule(ctx, HPKE_MODE_BASE, shared_secret, shared_secret_len, - info, info_len)) { - EVP_HPKE_CTX_cleanup(ctx); + const EVP_KEM *evp_kem = key->kem->evp_kem_func(); + const EVP_PKEY *decap_key = key->pkey; + + InplaceVector shared_secret; + if (!shared_secret.TryResizeForOverwrite(evp_kem->secret_len)) { + OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR); return 0; } - return 1; + return EVP_KEM_decap(evp_kem, shared_secret.data(), shared_secret.size(), enc, + enc_len, decap_key) && + EVP_HPKE_CTX_setup_recipient_with_shared_secret( + ctx, key->kem, kdf, aead, shared_secret.data(), + shared_secret.size(), info, info_len); } - int EVP_HPKE_CTX_setup_auth_sender( EVP_HPKE_CTX *ctx, uint8_t *out_enc, size_t *out_enc_len, size_t max_enc, const EVP_HPKE_KEY *key, const EVP_HPKE_KDF *kdf, const EVP_HPKE_AEAD *aead, const uint8_t *peer_public_key, size_t peer_public_key_len, const uint8_t *info, size_t info_len) { - if (key->kem->auth_encap_with_seed == nullptr) { - // Not all HPKE KEMs support AuthEncap. - OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); - return 0; - } - assert(!uses_evp(key->kem)); - uint8_t seed[MAX_SEED_LEN]; - RAND_bytes(seed, key->kem->seed_len); - return EVP_HPKE_CTX_setup_auth_sender_with_seed_for_testing( - ctx, out_enc, out_enc_len, max_enc, key, kdf, aead, peer_public_key, - peer_public_key_len, info, info_len, seed, key->kem->seed_len); + return hpke_setup_auth_sender_impl( + ctx, out_enc, out_enc_len, max_enc, key, kdf, aead, + Span(peer_public_key, peer_public_key_len), Span(info, info_len), + /*entropy=*/std::nullopt); } int EVP_HPKE_CTX_setup_auth_sender_with_seed_for_testing( @@ -1339,28 +1308,10 @@ int EVP_HPKE_CTX_setup_auth_sender_with_seed_for_testing( const uint8_t *peer_public_key, size_t peer_public_key_len, const uint8_t *info, size_t info_len, const uint8_t *seed, size_t seed_len) { - if (key->kem->auth_encap_with_seed == nullptr) { - // Not all HPKE KEMs support AuthEncap. - OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); - return 0; - } - - EVP_HPKE_CTX_zero(ctx); - ctx->is_sender = 1; - ctx->kem = key->kem; - ctx->kdf = kdf; - ctx->aead = aead; - uint8_t shared_secret[MAX_SHARED_SECRET_LEN]; - size_t shared_secret_len; - if (!key->kem->auth_encap_with_seed( - key, shared_secret, &shared_secret_len, out_enc, out_enc_len, max_enc, - peer_public_key, peer_public_key_len, seed, seed_len) || - !hpke_key_schedule(ctx, HPKE_MODE_AUTH, shared_secret, shared_secret_len, - info, info_len)) { - EVP_HPKE_CTX_cleanup(ctx); - return 0; - } - return 1; + return hpke_setup_auth_sender_impl( + ctx, out_enc, out_enc_len, max_enc, key, kdf, aead, + Span(peer_public_key, peer_public_key_len), Span(info, info_len), + Span(seed, seed_len)); } int EVP_HPKE_CTX_setup_auth_recipient( @@ -1379,34 +1330,25 @@ int EVP_HPKE_CTX_setup_auth_recipient( ctx->kem = key->kem; ctx->kdf = kdf; ctx->aead = aead; - uint8_t shared_secret[MAX_SHARED_SECRET_LEN]; - size_t shared_secret_len; - if (!key->kem->auth_decap(key, shared_secret, &shared_secret_len, enc, - enc_len, peer_public_key, peer_public_key_len) || - !hpke_key_schedule(ctx, HPKE_MODE_AUTH, shared_secret, shared_secret_len, - info, info_len)) { - EVP_HPKE_CTX_cleanup(ctx); + const EVP_KEM *kem = key->kem->evp_kem_func(); + InplaceVector shared_secret; + if (!shared_secret.TryResizeForOverwrite(kem->secret_len)) { + OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR); return 0; } - return 1; -} - -static void hpke_nonce(const EVP_HPKE_CTX *ctx, uint8_t *out_nonce, - size_t nonce_len) { - assert(nonce_len >= 8); - - // Write padded big-endian bytes of `ctx->seq` to `out_nonce`. - OPENSSL_memset(out_nonce, 0, nonce_len); - uint64_t seq_copy = ctx->seq; - for (size_t i = 0; i < 8; i++) { - out_nonce[nonce_len - i - 1] = seq_copy & 0xff; - seq_copy >>= 8; + UniquePtr peer_key(key->kem->key_method->deserialize_public_key( + key->kem->key_method->alg_func(), peer_public_key, peer_public_key_len)); + if (peer_key == nullptr) { + return 0; } - - // XOR the encoded sequence with the `ctx->base_nonce`. - for (size_t i = 0; i < nonce_len; i++) { - out_nonce[i] ^= ctx->base_nonce[i]; + if (!key->kem->auth_decap(kem, Span(shared_secret), Span(enc, enc_len), + key->pkey, peer_key.get()) || + !hpke_key_schedule(ctx, HPKE_MODE_AUTH, shared_secret.data(), + shared_secret.size(), info, info_len)) { + EVP_HPKE_CTX_cleanup(ctx); + return 0; } + return 1; } int EVP_HPKE_CTX_open(EVP_HPKE_CTX *ctx, uint8_t *out, size_t *out_len, diff --git a/third_party/boringssl/src/crypto/internal.h b/third_party/boringssl/src/crypto/internal.h index e318a24..8cdd58a 100644 --- a/third_party/boringssl/src/crypto/internal.h +++ b/third_party/boringssl/src/crypto/internal.h @@ -26,6 +26,7 @@ #include #include +#include #if defined(BORINGSSL_CONSTANT_TIME_VALIDATION) #include @@ -48,8 +49,6 @@ #if defined(OPENSSL_THREADS) #include -#else -#include #endif #if defined(OPENSSL_WINDOWS_THREADS) @@ -657,7 +656,7 @@ class OPENSSL_EXPORT StaticMutex { // UnlockWrite releases a write lock. void UnlockWrite(); -protected: + protected: #if !defined(OPENSSL_THREADS) // Nothing. #elif defined(OPENSSL_WINDOWS_THREADS) @@ -669,7 +668,7 @@ class OPENSSL_EXPORT StaticMutex { #endif }; -class OPENSSL_EXPORT Mutex : public StaticMutex { +class OPENSSL_EXPORT Mutex : public StaticMutex { public: constexpr Mutex() = default; ~Mutex(); @@ -780,9 +779,9 @@ struct ExDataClass { // CRYPTO_get_ex_new_index_ex allocates a new index for `ex_data_class`. Each // class of object should provide a wrapper function that uses the correct // `ExDataClass`. It returns the new index on success and -1 on error. -OPENSSL_EXPORT int CRYPTO_get_ex_new_index_ex( - ExDataClass *ex_data_class, long argl, void *argp, - CRYPTO_EX_free *free_func); +OPENSSL_EXPORT int CRYPTO_get_ex_new_index_ex(ExDataClass *ex_data_class, + long argl, void *argp, + CRYPTO_EX_free *free_func); // CRYPTO_set_ex_data sets an extra data pointer on a given object. Each class // of object should provide a wrapper function. @@ -1031,7 +1030,7 @@ inline uint64_t CRYPTO_rotr_u64(uint64_t value, int shift) { // CRYPTO_bit_width returns the smallest number of bits needed to represent `n`. // It returns zero if `n` is zero. -inline int CRYPTO_bit_width(uint64_t n) { +inline constexpr int CRYPTO_bit_width(uint64_t n) { #if OPENSSL_HAS_BUILTIN(__builtin_clzll) static_assert(sizeof(unsigned long long) >= sizeof(uint64_t)); return n ? (sizeof(unsigned long long) * 8 - __builtin_clzll(n)) : 0; @@ -1398,6 +1397,12 @@ inline int CRYPTO_is_VPCLMULQDQ_capable() { // ARMV8_SHA3 indicates support for eor3 instructions. #define ARMV8_SHA3 (1 << 7) +// ARMV8_DIT indicates support for Data Independent Timing. +#define ARMV8_DIT (1 << 8) + +// ARMV8_SB indicates support for Speculation Barrier. +#define ARMV8_SB (1 << 9) + #if defined(OPENSSL_STATIC_ARMCAP) // We assume `CRYPTO_is_*_capable` already checked static capabilities. inline uint32_t OPENSSL_get_armcap() { return 0; } @@ -1413,7 +1418,7 @@ OPENSSL_ATTR_CONST uint32_t OPENSSL_get_armcap(); #endif // OPENSSL_STATIC_ARMCAP // Normalize some older feature flags to their modern ACLE values. -// https://developer.arm.com/architectures/system-architectures/software-standards/acle +// https://arm-software.github.io/acle/main/acle.html #if defined(__ARM_NEON__) && !defined(__ARM_NEON) #define __ARM_NEON 1 #endif @@ -1437,6 +1442,26 @@ inline int CRYPTO_is_NEON_capable() { #endif } +inline int CRYPTO_is_ARMv8_DIT_capable() { +// As of 2026 ACLE does not include DIT detection macro. +// Tracking issue: https://github.com/ARM-software/acle/issues/463 +// Additionally, macOS ARM support is first available on M1 chips, +// which is already ARMv8.4-A. ARMv8.4-A has made DIT mandatory. +// See +// https://support.arm.com/documentation/109697/2026_09/Feature-descriptions/The-Armv8-4-architecture-extension#md449-the-armv84-architecture-extension__feat_FEAT_DIT +#if defined(OPENSSL_MACOS) + return 1; +#else + return (OPENSSL_get_armcap() & ARMV8_DIT) != 0; +#endif +} + +inline int CRYPTO_is_ARMv8_SB_capable() { + // As of 2026 ACLE does not include SB detection macro. + // Tracking issue: https://github.com/ARM-software/acle/issues/463 + return (OPENSSL_get_armcap() & ARMV8_SB) != 0; +} + inline int CRYPTO_is_ARMv8_AES_capable() { #if defined(OPENSSL_STATIC_ARMCAP_AES) || defined(__ARM_FEATURE_AES) return 1; @@ -1493,6 +1518,102 @@ inline int CRYPTO_is_ARMv8_SHA3_capable() { #endif // OPENSSL_ARM || OPENSSL_AARCH64 +// We cannot support Windows at the moment. The platform does not expose DIT +// feature detection. +#if defined(OPENSSL_AARCH64) && !defined(OPENSSL_NO_ASM) && \ + !defined(OPENSSL_WINDOWS) +#define OPENSSL_ARM_DIT +#define OPENSSL_ARM_SB +// Clang only supports the GCC target specifier format since Clang 16 (2023). +// We should unify the style earliest from 2028. +#if defined(__clang__) +#define SB_FEATURE __attribute__((target("sb"))) +#else +#define SB_FEATURE +#endif +#endif + +// ConstTimeGuard is a guard type to designate a program region in which +// constant time arithmetic is guaranteed. NOTE: inputs and outputs must be +// marked with `WillReadSecret` and `DidComputeResult` to prevent the compiler +// from reordering code. +class ConstTimeGuard { + public: +#if defined(OPENSSL_ARM_DIT) + ConstTimeGuard(); + ~ConstTimeGuard(); +#else + // No-op + ConstTimeGuard() = default; + ~ConstTimeGuard() = default; +#endif + ConstTimeGuard(const ConstTimeGuard &) = delete; + ConstTimeGuard &operator=(const ConstTimeGuard &) = delete; + ConstTimeGuard(ConstTimeGuard &&) = delete; + ConstTimeGuard &operator=(ConstTimeGuard &&) = delete; + + // Mark an input in scope of constant-time guard. This prevents the compiler + // from moving computation depending on `val` before this call. + template + void WillReadSecret(T *val) { +#if defined(OPENSSL_ARM_DIT) && (defined(__GNUC__) || defined(__clang__)) + // Tell the compiler that we might write to secret memory reachable from + // `val`. We do not actually write, but this prevents the compiler from + // moving secret-dependent computation before this "write". + __asm__ __volatile__("" : : "r"(val) : "memory"); +#else + (void)val; +#endif + } + + // Mark an input in scope of constant-time guard. This prevents the compiler + // from moving computation depending on `val` before this call. + template + void WillReadSecret(Span val) { + WillReadSecret(val.data()); + } + + // Mark an input in scope of constant-time guard. This prevents the compiler + // from moving computation depending on `val` before this call. + template + void WillReadSecret(T &val) { + WillReadSecret(&val); + } + + // Mark an output in scope of constant-time guard. This prevents the compiler + // from moving the computation of `val` to after this call. + template + void DidComputeResult(T *val) { +#if defined(OPENSSL_ARM_DIT) && (defined(__GNUC__) || defined(__clang__)) + // Tell the compiler that we might read from the results reachable from + // `val`. We do not actually read, but this prevents the compiler from + // moving the computation after this "read". + __asm__ __volatile__("" : : "r"(val) : "memory"); +#else + (void)val; +#endif + } + + // Mark an output in scope of constant-time guard. This prevents the compiler + // from moving the computation of `val` to after this call. + template + void DidComputeResult(Span val) { + DidComputeResult(val.data()); + } + + // Mark an output in scope of constant-time guard. This prevents the compiler + // from moving the computation of `val` to after this call. + template + void DidComputeResult(T &val) { + DidComputeResult(&val); + } + + private: +#if defined(OPENSSL_ARM_DIT) + bool previous_dit_ = false; +#endif // OPENSSL_AARCH64 +}; + #if defined(BORINGSSL_DISPATCH_TEST) // Runtime CPU dispatch testing support @@ -1526,7 +1647,7 @@ OPENSSL_EXPORT int OPENSSL_vasprintf_internal(char **str, const char *format, // CRYPTO_fuzzer_mode_enabled returns whether fuzzer mode is enabled. See // `CRYPTO_set_fuzzer_mode`. In non-fuzzer builds, this function statically // returns zero so the codepaths will be deleted by the optimizer. -int CRYPTO_fuzzer_mode_enabled(); +OPENSSL_EXPORT int CRYPTO_fuzzer_mode_enabled(); #else inline int CRYPTO_fuzzer_mode_enabled() { return 0; } #endif @@ -1761,6 +1882,34 @@ inline const typename Public::ImplType *FromOpaque(const Public *p) { return static_cast(p); } +template +inline constexpr decltype(auto) AsmThunk(Args... args) noexcept( + noexcept(F(std::forward(args)...))) { + return F(std::forward(args)...); +} + +template +struct AsmRaw { + static inline constexpr auto kRaw = Item; +}; + +// TODO(crbug.com/585160970): We should replace this with a more long term +// solution. A better design is possible. +#define DECLARE_ASM_FUNCTION(ret, name, params) \ + namespace asm_raw { \ + \ + extern "C" ret name params noexcept; \ + \ + } \ + \ + inline constexpr decltype(asm_raw::name) &name = AsmThunk; \ + \ + template <> \ + struct AsmRaw { \ + static inline constexpr auto kRaw = asm_raw::name; \ + }; + + BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/crypto/md5/md5.cc b/third_party/boringssl/src/crypto/md5/md5.cc index 0604ddc..ba9147e 100644 --- a/third_party/boringssl/src/crypto/md5/md5.cc +++ b/third_party/boringssl/src/crypto/md5/md5.cc @@ -82,6 +82,48 @@ int MD5_Final(uint8_t out[MD5_DIGEST_LENGTH], MD5_CTX *c) { return 1; } +int MD5_marshal_state(const MD5_CTX *md5, uint8_t out[MD5_STATE_MAX_BYTES], + size_t *out_len) { + BSSL_CHECK(md5->num < MD5_CBLOCK); + CRYPTO_store_u32_le(out, md5->h[0]); + CRYPTO_store_u32_le(out + 4, md5->h[1]); + CRYPTO_store_u32_le(out + 8, md5->h[2]); + CRYPTO_store_u32_le(out + 12, md5->h[3]); + CRYPTO_store_u32_le(out + 16, md5->Nl); + CRYPTO_store_u32_le(out + 20, md5->Nh); + OPENSSL_memcpy(out + 24, md5->data, md5->num); + *out_len = 24 + md5->num; + return 1; +} + +int MD5_parse_state(MD5_CTX *md5, const uint8_t *in, size_t in_len) { + if (in_len < 24 || in_len > MD5_STATE_MAX_BYTES) { + return 0; + } + uint32_t nl = CRYPTO_load_u32_le(in + 16); + if ((nl & 7) != 0) { + return 0; + } + // The number of bytes left in `data` is the number of bits divided by 8, + // modulo the block size. + static_assert((MD5_CBLOCK & (MD5_CBLOCK - 1)) == 0, + "MD5_CBLOCK must be a power of 2"); + unsigned num = (nl >> 3) & (MD5_CBLOCK - 1); + if (in_len != 24 + num) { + return 0; + } + OPENSSL_memset(md5, 0, sizeof(MD5_CTX)); + md5->h[0] = CRYPTO_load_u32_le(in); + md5->h[1] = CRYPTO_load_u32_le(in + 4); + md5->h[2] = CRYPTO_load_u32_le(in + 8); + md5->h[3] = CRYPTO_load_u32_le(in + 12); + md5->Nl = nl; + md5->Nh = CRYPTO_load_u32_le(in + 20); + md5->num = num; + OPENSSL_memcpy(md5->data, in + 24, num); + return 1; +} + // As pointed out by Wei Dai , the above can be // simplified to the code below. Wei attributes these optimizations // to Peter Gutmann's SHS code, and he attributes it to Rich Schroeppel. diff --git a/third_party/boringssl/src/crypto/mem_internal.h b/third_party/boringssl/src/crypto/mem_internal.h index 59927e1..488052f 100644 --- a/third_party/boringssl/src/crypto/mem_internal.h +++ b/third_party/boringssl/src/crypto/mem_internal.h @@ -135,6 +135,13 @@ class RefCounted { // ref-count variable. CRYPTO_refcount_inc(&references_); } + + // Only the implementations of `FOO_dup_ref` should call these. + Derived *DupRefInternal() const { + UpRefInternal(); + return const_cast(static_cast(this)); + } + bool DecRefInternal() { if (CRYPTO_refcount_dec_and_test_zero(&references_)) { Derived *d = static_cast(this); diff --git a/third_party/boringssl/src/crypto/obj/obj_dat.h b/third_party/boringssl/src/crypto/obj/obj_dat.h index ced3582..9721235 100644 --- a/third_party/boringssl/src/crypto/obj/obj_dat.h +++ b/third_party/boringssl/src/crypto/obj/obj_dat.h @@ -16,7 +16,7 @@ BSSL_NAMESPACE_BEGIN -#define NUM_NID 982 +#define NUM_NID 981 static const uint8_t kObjectData[] = { /* NID_rsadsi */ @@ -7146,39 +7146,6 @@ static const uint8_t kObjectData[] = { 0x04, 0x04, 0x02, - /* NID_alg_mtcProof_draft */ - 0x2b, - 0x06, - 0x01, - 0x04, - 0x01, - 0x82, - 0xda, - 0x4b, - 0x2f, - 0x00, - /* NID_rdna_trustAnchorID_draft */ - 0x2b, - 0x06, - 0x01, - 0x04, - 0x01, - 0x82, - 0xda, - 0x4b, - 0x2f, - 0x01, - /* NID_pe_mtcCertificationAuthority_draft */ - 0x2b, - 0x06, - 0x01, - 0x04, - 0x01, - 0x82, - 0xda, - 0x4b, - 0x2f, - 0x02, /* NID_SLH_DSA_SHA2_128s */ 0x60, 0x86, @@ -7209,6 +7176,51 @@ static const uint8_t kObjectData[] = { 0x04, 0x03, 0x23, + /* NID_alg_mtcProof */ + 0x2b, + 0x06, + 0x01, + 0x05, + 0x05, + 0x07, + 0x06, + 0x43, + /* NID_rdna_trustAnchorID */ + 0x2b, + 0x06, + 0x01, + 0x05, + 0x05, + 0x07, + 0x19, + 0x03, + /* NID_pe_mtcCertificationAuthority_SHA256 */ + 0x2b, + 0x06, + 0x01, + 0x05, + 0x05, + 0x07, + 0x01, + 0x26, + /* NID_alg_unsigned */ + 0x2b, + 0x06, + 0x01, + 0x05, + 0x05, + 0x07, + 0x06, + 0x24, + /* NID_rdna_unsigned */ + 0x2b, + 0x06, + 0x01, + 0x05, + 0x05, + 0x07, + 0x19, + 0x01, }; static const ASN1_OBJECT kObjects[NUM_NID] = { @@ -8865,21 +8877,23 @@ static const ASN1_OBJECT kObjects[NUM_NID] = { 0}, {NULL, NULL, NID_undef, 0, NULL, 0}, {"X-Wing", "X-Wing", NID_X_Wing, 0, NULL, 0}, - {NULL, NULL, NID_undef, 0, NULL, 0}, - {NULL, NULL, NID_undef, 0, NULL, 0}, - {NULL, NULL, NID_undef, 0, NULL, 0}, - {"alg-mtcProof-draft", "alg-mtcProof-draft", NID_alg_mtcProof_draft, 10, - &kObjectData[6241], 0}, - {"rdna-trustAnchorID-draft", "rdna-trustAnchorID-draft", - NID_rdna_trustAnchorID_draft, 10, &kObjectData[6251], 0}, - {"pe-mtcCertificationAuthority-draft", "pe-mtcCertificationAuthority-draft", - NID_pe_mtcCertificationAuthority_draft, 10, &kObjectData[6261], 0}, {"id-slh-dsa-sha2-128s", "SLH-DSA-SHA2-128s", NID_SLH_DSA_SHA2_128s, 9, - &kObjectData[6271], 0}, + &kObjectData[6241], 0}, {"id-slh-dsa-shake-256f", "SLH-DSA-SHAKE-256f", NID_SLH_DSA_SHAKE_256f, 9, - &kObjectData[6280], 0}, + &kObjectData[6250], 0}, {"id-hash-slh-dsa-sha2-128s-with-sha256", "SLH-DSA-SHA2-128s-WITH-SHA256", - NID_SLH_DSA_SHA2_128s_WITH_SHA256, 9, &kObjectData[6289], 0}, + NID_SLH_DSA_SHA2_128s_WITH_SHA256, 9, &kObjectData[6259], 0}, + {"alg-mtcProof", "alg-mtcProof", NID_alg_mtcProof, 8, &kObjectData[6268], + 0}, + {"rdna-trustAnchorID", "rdna-trustAnchorID", NID_rdna_trustAnchorID, 8, + &kObjectData[6276], 0}, + {"pe-mtcCertificationAuthority-SHA256", + "pe-mtcCertificationAuthority-SHA256", + NID_pe_mtcCertificationAuthority_SHA256, 8, &kObjectData[6284], 0}, + {"alg-unsigned", "alg-unsigned", NID_alg_unsigned, 8, &kObjectData[6292], + 0}, + {"rdna-unsigned", "rdna-unsigned", NID_rdna_unsigned, 8, &kObjectData[6300], + 0}, }; static const uint16_t kNIDsInShortNameOrder[] = { @@ -9095,7 +9109,8 @@ static const uint16_t kNIDsInShortNameOrder[] = { 368 /* acceptableResponses */, 446 /* account */, 363 /* ad_timestamping */, - 976 /* alg-mtcProof-draft */, + 976 /* alg-mtcProof */, + 979 /* alg-unsigned */, 376 /* algorithm */, 405 /* ansi-X9-62 */, 910 /* anyExtendedKeyUsage */, @@ -9354,7 +9369,7 @@ static const uint16_t kNIDsInShortNameOrder[] = { 331 /* id-cmc-transactionId */, 787 /* id-ct-asciiTextWithCRLF */, 408 /* id-ecPublicKey */, - 981 /* id-hash-slh-dsa-sha2-128s-with-sha256 */, + 975 /* id-hash-slh-dsa-sha2-128s-with-sha256 */, 508 /* id-hex-multipart-message */, 507 /* id-hex-partial-message */, 260 /* id-it */, @@ -9426,8 +9441,8 @@ static const uint16_t kNIDsInShortNameOrder[] = { 322 /* id-regInfo-certReq */, 321 /* id-regInfo-utf8Pairs */, 512 /* id-set */, - 979 /* id-slh-dsa-sha2-128s */, - 980 /* id-slh-dsa-shake-256f */, + 973 /* id-slh-dsa-sha2-128s */, + 974 /* id-slh-dsa-shake-256f */, 191 /* id-smime-aa */, 215 /* id-smime-aa-contentHint */, 218 /* id-smime-aa-contentIdentifier */, @@ -9560,7 +9575,7 @@ static const uint16_t kNIDsInShortNameOrder[] = { 489 /* pagerTelephoneNumber */, 374 /* path */, 112 /* pbeWithMD5AndCast5CBC */, - 978 /* pe-mtcCertificationAuthority-draft */, + 978 /* pe-mtcCertificationAuthority-SHA256 */, 499 /* personalSignature */, 487 /* personalTitle */, 464 /* photo */, @@ -9614,7 +9629,8 @@ static const uint16_t kNIDsInShortNameOrder[] = { 286 /* qcStatements */, 457 /* qualityLabelledData */, 450 /* rFC822localPart */, - 977 /* rdna-trustAnchorID-draft */, + 977 /* rdna-trustAnchorID */, + 980 /* rdna-unsigned */, 870 /* registeredAddress */, 400 /* role */, 877 /* roleOccupant */, @@ -9955,9 +9971,9 @@ static const uint16_t kNIDsInLongNameOrder[] = { 2 /* RSA Data Security, Inc. PKCS */, 188 /* S/MIME */, 167 /* S/MIME Capabilities */, - 979 /* SLH-DSA-SHA2-128s */, - 981 /* SLH-DSA-SHA2-128s-WITH-SHA256 */, - 980 /* SLH-DSA-SHAKE-256f */, + 973 /* SLH-DSA-SHA2-128s */, + 975 /* SLH-DSA-SHA2-128s-WITH-SHA256 */, + 974 /* SLH-DSA-SHAKE-256f */, 387 /* SNMPv2 */, 512 /* Secure Electronic Transactions */, 386 /* Security */, @@ -10041,7 +10057,8 @@ static const uint16_t kNIDsInLongNameOrder[] = { 901 /* aes-256-gcm */, 428 /* aes-256-ofb */, 914 /* aes-256-xts */, - 976 /* alg-mtcProof-draft */, + 976 /* alg-mtcProof */, + 979 /* alg-unsigned */, 376 /* algorithm */, 484 /* associatedDomain */, 485 /* associatedName */, @@ -10520,7 +10537,7 @@ static const uint16_t kNIDsInLongNameOrder[] = { 145 /* pbeWithSHA1And40BitRC4 */, 170 /* pbeWithSHA1AndDES-CBC */, 68 /* pbeWithSHA1AndRC2-CBC */, - 978 /* pe-mtcCertificationAuthority-draft */, + 978 /* pe-mtcCertificationAuthority-SHA256 */, 499 /* personalSignature */, 487 /* personalTitle */, 464 /* photo */, @@ -10580,7 +10597,8 @@ static const uint16_t kNIDsInLongNameOrder[] = { 122 /* rc5-cfb */, 121 /* rc5-ecb */, 123 /* rc5-ofb */, - 977 /* rdna-trustAnchorID-draft */, + 977 /* rdna-trustAnchorID */, + 980 /* rdna-unsigned */, 870 /* registeredAddress */, 460 /* rfc822Mailbox */, 117 /* ripemd160 */, @@ -10823,8 +10841,8 @@ static const uint16_t kNIDsInLongNameOrder[] = { static const uint16_t kNIDsInOIDOrder[] = { 434 /* 0.9 (OBJ_data) */, 182 /* 1.2 (OBJ_member_body) */, - 379 /* 1.3 (OBJ_org) */, 676 /* 1.3 (OBJ_identified_organization) */, + 379 /* 1.3 (OBJ_org) */, 11 /* 2.5 (OBJ_X500) */, 647 /* 2.23 (OBJ_international_organizations) */, 380 /* 1.3.6 (OBJ_dod) */, @@ -11322,6 +11340,7 @@ static const uint16_t kNIDsInOIDOrder[] = { 397 /* 1.3.6.1.5.5.7.1.10 (OBJ_ac_proxying) */, 398 /* 1.3.6.1.5.5.7.1.11 (OBJ_sinfo_access) */, 663 /* 1.3.6.1.5.5.7.1.14 (OBJ_proxyCertInfo) */, + 978 /* 1.3.6.1.5.5.7.1.38 (OBJ_pe_mtcCertificationAuthority_SHA256) */, 164 /* 1.3.6.1.5.5.7.2.1 (OBJ_id_qt_cps) */, 165 /* 1.3.6.1.5.5.7.2.2 (OBJ_id_qt_unotice) */, 293 /* 1.3.6.1.5.5.7.2.3 (OBJ_textNotice) */, @@ -11357,6 +11376,8 @@ static const uint16_t kNIDsInOIDOrder[] = { 324 /* 1.3.6.1.5.5.7.6.2 (OBJ_id_alg_noSignature) */, 325 /* 1.3.6.1.5.5.7.6.3 (OBJ_id_alg_dh_sig_hmac_sha1) */, 326 /* 1.3.6.1.5.5.7.6.4 (OBJ_id_alg_dh_pop) */, + 979 /* 1.3.6.1.5.5.7.6.36 (OBJ_alg_unsigned) */, + 976 /* 1.3.6.1.5.5.7.6.67 (OBJ_alg_mtcProof) */, 327 /* 1.3.6.1.5.5.7.7.1 (OBJ_id_cmc_statusInfo) */, 328 /* 1.3.6.1.5.5.7.7.2 (OBJ_id_cmc_identification) */, 329 /* 1.3.6.1.5.5.7.7.3 (OBJ_id_cmc_identityProof) */, @@ -11397,6 +11418,8 @@ static const uint16_t kNIDsInOIDOrder[] = { 664 /* 1.3.6.1.5.5.7.21.0 (OBJ_id_ppl_anyLanguage) */, 665 /* 1.3.6.1.5.5.7.21.1 (OBJ_id_ppl_inheritAll) */, 667 /* 1.3.6.1.5.5.7.21.2 (OBJ_Independent) */, + 980 /* 1.3.6.1.5.5.7.25.1 (OBJ_rdna_unsigned) */, + 977 /* 1.3.6.1.5.5.7.25.3 (OBJ_rdna_trustAnchorID) */, 178 /* 1.3.6.1.5.5.7.48.1 (OBJ_ad_OCSP) */, 179 /* 1.3.6.1.5.5.7.48.2 (OBJ_ad_ca_issuers) */, 363 /* 1.3.6.1.5.5.7.48.3 (OBJ_ad_timeStamping) */, @@ -11535,9 +11558,9 @@ static const uint16_t kNIDsInOIDOrder[] = { 967 /* 2.16.840.1.101.3.4.3.17 (OBJ_ML_DSA_44) */, 968 /* 2.16.840.1.101.3.4.3.18 (OBJ_ML_DSA_65) */, 969 /* 2.16.840.1.101.3.4.3.19 (OBJ_ML_DSA_87) */, - 979 /* 2.16.840.1.101.3.4.3.20 (OBJ_SLH_DSA_SHA2_128s) */, - 980 /* 2.16.840.1.101.3.4.3.31 (OBJ_SLH_DSA_SHAKE_256f) */, - 981 /* 2.16.840.1.101.3.4.3.35 (OBJ_SLH_DSA_SHA2_128s_WITH_SHA256) */, + 973 /* 2.16.840.1.101.3.4.3.20 (OBJ_SLH_DSA_SHA2_128s) */, + 974 /* 2.16.840.1.101.3.4.3.31 (OBJ_SLH_DSA_SHAKE_256f) */, + 975 /* 2.16.840.1.101.3.4.3.35 (OBJ_SLH_DSA_SHA2_128s_WITH_SHA256) */, 970 /* 2.16.840.1.101.3.4.4.2 (OBJ_ML_KEM_768) */, 966 /* 2.16.840.1.101.3.4.4.3 (OBJ_ML_KEM_1024) */, 71 /* 2.16.840.1.113730.1.1 (OBJ_netscape_cert_type) */, @@ -11637,9 +11660,6 @@ static const uint16_t kNIDsInOIDOrder[] = { 138 /* 1.3.6.1.4.1.311.10.3.4 (OBJ_ms_efs) */, 648 /* 1.3.6.1.4.1.311.20.2.2 (OBJ_ms_smartcard_login) */, 649 /* 1.3.6.1.4.1.311.20.2.3 (OBJ_ms_upn) */, - 976 /* 1.3.6.1.4.1.44363.47.0 (OBJ_alg_mtcProof_draft) */, - 977 /* 1.3.6.1.4.1.44363.47.1 (OBJ_rdna_trustAnchorID_draft) */, - 978 /* 1.3.6.1.4.1.44363.47.2 (OBJ_pe_mtcCertificationAuthority_draft) */, 751 /* 1.2.392.200011.61.1.1.1.2 (OBJ_camellia_128_cbc) */, 752 /* 1.2.392.200011.61.1.1.1.3 (OBJ_camellia_192_cbc) */, 753 /* 1.2.392.200011.61.1.1.1.4 (OBJ_camellia_256_cbc) */, diff --git a/third_party/boringssl/src/crypto/pem/pem_all.cc b/third_party/boringssl/src/crypto/pem/pem_all.cc index 550923c..7d0f1e3 100644 --- a/third_party/boringssl/src/crypto/pem/pem_all.cc +++ b/third_party/boringssl/src/crypto/pem/pem_all.cc @@ -26,21 +26,19 @@ #include "internal.h" -static RSA *pkey_get_rsa(EVP_PKEY *key, RSA **rsa); -static DSA *pkey_get_dsa(EVP_PKEY *key, DSA **dsa); -static EC_KEY *pkey_get_eckey(EVP_PKEY *key, EC_KEY **eckey); - IMPLEMENT_PEM_rw(X509_REQ, X509_REQ, PEM_STRING_X509_REQ, X509_REQ) IMPLEMENT_PEM_write(X509_REQ_NEW, X509_REQ, PEM_STRING_X509_REQ_OLD, X509_REQ) IMPLEMENT_PEM_rw(X509_CRL, X509_CRL, PEM_STRING_X509_CRL, X509_CRL) IMPLEMENT_PEM_rw(PKCS7, PKCS7, PEM_STRING_PKCS7, PKCS7) +namespace { + // We treat RSA or DSA private keys as a special case. For private keys we // read in an EVP_PKEY structure with PEM_read_bio_PrivateKey() and extract // the relevant private key: this means can handle "traditional" and PKCS#8 // formats transparently. -static RSA *pkey_get_rsa(EVP_PKEY *key, RSA **rsa) { +RSA *pkey_get_rsa(EVP_PKEY *key, RSA **rsa) { if (!key) { return nullptr; } @@ -60,6 +58,8 @@ static RSA *pkey_get_rsa(EVP_PKEY *key, RSA **rsa) { return rtmp; } +} // namespace + RSA *PEM_read_bio_RSAPrivateKey(BIO *bp, RSA **rsa, pem_password_cb *cb, void *u) { bssl::UniquePtr pkey(PEM_read_bio_PrivateKey(bp, nullptr, cb, u)); @@ -76,8 +76,11 @@ IMPLEMENT_PEM_write_cb(RSAPrivateKey, RSA, PEM_STRING_RSA, RSAPrivateKey) IMPLEMENT_PEM_rw(RSAPublicKey, RSA, PEM_STRING_RSA_PUBLIC, RSAPublicKey) IMPLEMENT_PEM_rw(RSA_PUBKEY, RSA, PEM_STRING_PUBLIC, RSA_PUBKEY) + #ifndef OPENSSL_NO_DSA -static DSA *pkey_get_dsa(EVP_PKEY *key, DSA **dsa) { +namespace { + +DSA *pkey_get_dsa(EVP_PKEY *key, DSA **dsa) { DSA *dtmp; if (!key) { return nullptr; @@ -94,6 +97,8 @@ static DSA *pkey_get_dsa(EVP_PKEY *key, DSA **dsa) { return dtmp; } +} // namespace + DSA *PEM_read_bio_DSAPrivateKey(BIO *bp, DSA **dsa, pem_password_cb *cb, void *u) { EVP_PKEY *pktmp; @@ -112,7 +117,10 @@ DSA *PEM_read_DSAPrivateKey(FILE *fp, DSA **dsa, pem_password_cb *cb, void *u) { IMPLEMENT_PEM_rw(DSAparams, DSA, PEM_STRING_DSAPARAMS, DSAparams) #endif -static EC_KEY *pkey_get_eckey(EVP_PKEY *key, EC_KEY **eckey) { + +namespace { + +EC_KEY *pkey_get_eckey(EVP_PKEY *key, EC_KEY **eckey) { EC_KEY *dtmp; if (!key) { return nullptr; @@ -129,6 +137,8 @@ static EC_KEY *pkey_get_eckey(EVP_PKEY *key, EC_KEY **eckey) { return dtmp; } +} // namespace + EC_KEY *PEM_read_bio_ECPrivateKey(BIO *bp, EC_KEY **key, pem_password_cb *cb, void *u) { EVP_PKEY *pktmp; diff --git a/third_party/boringssl/src/crypto/pem/pem_info.cc b/third_party/boringssl/src/crypto/pem/pem_info.cc index 55d0040..271e795 100644 --- a/third_party/boringssl/src/crypto/pem/pem_info.cc +++ b/third_party/boringssl/src/crypto/pem/pem_info.cc @@ -33,9 +33,11 @@ using namespace bssl; -static X509_PKEY *X509_PKEY_new() { return New(); } +namespace { -static void X509_PKEY_free(X509_PKEY *x) { +X509_PKEY *X509_PKEY_new() { return New(); } + +void X509_PKEY_free(X509_PKEY *x) { if (x == nullptr) { return; } @@ -44,7 +46,9 @@ static void X509_PKEY_free(X509_PKEY *x) { Delete(x); } -static X509_INFO *X509_INFO_new() { return New(); } +X509_INFO *X509_INFO_new() { return New(); } + +} // namespace void X509_INFO_free(X509_INFO *x) { if (x == nullptr) { @@ -71,14 +75,16 @@ STACK_OF(X509_INFO) *PEM_X509_INFO_read(FILE *fp, STACK_OF(X509_INFO) *sk, return ret; } +namespace { + enum parse_result_t { parse_ok, parse_error, parse_new_entry, }; -static enum parse_result_t parse_x509(X509_INFO *info, const uint8_t *data, - size_t len, int key_type) { +enum parse_result_t parse_x509(X509_INFO *info, const uint8_t *data, size_t len, + int key_type) { if (info->x509 != nullptr) { return parse_new_entry; } @@ -86,8 +92,8 @@ static enum parse_result_t parse_x509(X509_INFO *info, const uint8_t *data, return info->x509 != nullptr ? parse_ok : parse_error; } -static enum parse_result_t parse_x509_aux(X509_INFO *info, const uint8_t *data, - size_t len, int key_type) { +enum parse_result_t parse_x509_aux(X509_INFO *info, const uint8_t *data, + size_t len, int key_type) { if (info->x509 != nullptr) { return parse_new_entry; } @@ -95,8 +101,8 @@ static enum parse_result_t parse_x509_aux(X509_INFO *info, const uint8_t *data, return info->x509 != nullptr ? parse_ok : parse_error; } -static enum parse_result_t parse_crl(X509_INFO *info, const uint8_t *data, - size_t len, int key_type) { +enum parse_result_t parse_crl(X509_INFO *info, const uint8_t *data, size_t len, + int key_type) { if (info->crl != nullptr) { return parse_new_entry; } @@ -104,8 +110,8 @@ static enum parse_result_t parse_crl(X509_INFO *info, const uint8_t *data, return info->crl != nullptr ? parse_ok : parse_error; } -static enum parse_result_t parse_key(X509_INFO *info, const uint8_t *data, - size_t len, int key_type) { +enum parse_result_t parse_key(X509_INFO *info, const uint8_t *data, size_t len, + int key_type) { if (info->x_pkey != nullptr) { return parse_new_entry; } @@ -117,6 +123,8 @@ static enum parse_result_t parse_key(X509_INFO *info, const uint8_t *data, return info->x_pkey->dec_pkey != nullptr ? parse_ok : parse_error; } +} // namespace + STACK_OF(X509_INFO) *PEM_X509_INFO_read_bio(BIO *bp, STACK_OF(X509_INFO) *sk, pem_password_cb *cb, void *u) { X509_INFO *info = nullptr; diff --git a/third_party/boringssl/src/crypto/pem/pem_lib.cc b/third_party/boringssl/src/crypto/pem/pem_lib.cc index 83266f4..de3b287 100644 --- a/third_party/boringssl/src/crypto/pem/pem_lib.cc +++ b/third_party/boringssl/src/crypto/pem/pem_lib.cc @@ -42,13 +42,12 @@ using namespace bssl; -static int load_iv(const char **fromp, unsigned char *to, size_t num); -static bool check_pem(std::string_view name, std::string_view expected); +namespace { // PEM_dek_info appends a DEK-Info header to `buf`, with an algorithm of `type` // and a single parameter, specified by hex-encoding `len` bytes from `str`. -static void PEM_dek_info(char buf[PEM_BUFSIZE], const char *type, size_t len, - char *str) { +void PEM_dek_info(char buf[PEM_BUFSIZE], const char *type, size_t len, + char *str) { static const unsigned char map[17] = "0123456789ABCDEF"; OPENSSL_strlcat(buf, "DEK-Info: ", PEM_BUFSIZE); @@ -69,19 +68,7 @@ static void PEM_dek_info(char buf[PEM_BUFSIZE], const char *type, size_t len, buf[used + len * 2 + 1] = '\0'; } -void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x, - pem_password_cb *cb, void *u) { - BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); - if (b == nullptr) { - OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB); - return nullptr; - } - void *ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u); - BIO_free(b); - return ret; -} - -static bool check_pem(std::string_view name, std::string_view expected) { +bool check_pem(std::string_view name, std::string_view expected) { // `PEM_STRING_EVP_PKEY` is not a real PEM type, but a placeholder that // matches one of several private key types. if (expected == PEM_STRING_EVP_PKEY) { @@ -122,7 +109,7 @@ static bool check_pem(std::string_view name, std::string_view expected) { return false; } -static const EVP_CIPHER *cipher_by_name(const std::string_view name) { +const EVP_CIPHER *cipher_by_name(const std::string_view name) { // This is similar to the (deprecated) function `EVP_get_cipherbyname`. Note // the PEM code assumes that ciphers have at least 8 bytes of IV, at most 20 // bytes of overhead and generally behave like CBC mode. @@ -141,6 +128,42 @@ static const EVP_CIPHER *cipher_by_name(const std::string_view name) { } } +int load_iv(const char **fromp, unsigned char *to, size_t num) { + uint8_t v; + const char *from; + + from = *fromp; + for (size_t i = 0; i < num; i++) { + to[i] = 0; + } + num *= 2; + for (size_t i = 0; i < num; i++) { + if (!OPENSSL_fromxdigit(&v, *from)) { + OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_IV_CHARS); + return 0; + } + from++; + to[i / 2] |= v << (!(i & 1)) * 4; + } + + *fromp = from; + return 1; +} + +} // namespace + +void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x, + pem_password_cb *cb, void *u) { + BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); + if (b == nullptr) { + OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB); + return nullptr; + } + void *ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u); + BIO_free(b); + return ret; +} + int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm, const char *expected_name, BIO *bp, pem_password_cb *cb, void *u) { @@ -406,28 +429,6 @@ int bssl::PEM_get_EVP_CIPHER_INFO(const char *header, EVP_CIPHER_INFO *cipher) { return 1; } -static int load_iv(const char **fromp, unsigned char *to, size_t num) { - uint8_t v; - const char *from; - - from = *fromp; - for (size_t i = 0; i < num; i++) { - to[i] = 0; - } - num *= 2; - for (size_t i = 0; i < num; i++) { - if (!OPENSSL_fromxdigit(&v, *from)) { - OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_IV_CHARS); - return 0; - } - from++; - to[i / 2] |= v << (!(i & 1)) * 4; - } - - *fromp = from; - return 1; -} - int PEM_write(FILE *fp, const char *name, const char *header, const unsigned char *data, long len) { BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); diff --git a/third_party/boringssl/src/crypto/pem/pem_pk8.cc b/third_party/boringssl/src/crypto/pem/pem_pk8.cc index aa1e13d..69232f2 100644 --- a/third_party/boringssl/src/crypto/pem/pem_pk8.cc +++ b/third_party/boringssl/src/crypto/pem/pem_pk8.cc @@ -25,45 +25,11 @@ #include "internal.h" -static int do_pk8pkey(BIO *bp, const EVP_PKEY *x, int isder, int nid, - const EVP_CIPHER *enc, const char *pass, int pass_len, - pem_password_cb *cb, void *u); -static int do_pk8pkey_fp(FILE *bp, const EVP_PKEY *x, int isder, int nid, - const EVP_CIPHER *enc, const char *pass, int pass_len, - pem_password_cb *cb, void *u); +namespace { -// These functions write a private key in PKCS#8 format: it is a "drop in" -// replacement for PEM_write_bio_PrivateKey() and friends. As usual if 'enc' -// is NULL then it uses the unencrypted private key form. The 'nid' versions -// uses PKCS#5 v1.5 PBE algorithms whereas the others use PKCS#5 v2.0. - -int PEM_write_bio_PKCS8PrivateKey_nid(BIO *bp, const EVP_PKEY *x, int nid, - const char *pass, int pass_len, - pem_password_cb *cb, void *u) { - return do_pk8pkey(bp, x, 0, nid, nullptr, pass, pass_len, cb, u); -} - -int PEM_write_bio_PKCS8PrivateKey(BIO *bp, const EVP_PKEY *x, - const EVP_CIPHER *enc, const char *pass, - int pass_len, pem_password_cb *cb, void *u) { - return do_pk8pkey(bp, x, 0, -1, enc, pass, pass_len, cb, u); -} - -int i2d_PKCS8PrivateKey_bio(BIO *bp, const EVP_PKEY *x, const EVP_CIPHER *enc, - const char *pass, int pass_len, pem_password_cb *cb, - void *u) { - return do_pk8pkey(bp, x, 1, -1, enc, pass, pass_len, cb, u); -} - -int i2d_PKCS8PrivateKey_nid_bio(BIO *bp, const EVP_PKEY *x, int nid, - const char *pass, int pass_len, - pem_password_cb *cb, void *u) { - return do_pk8pkey(bp, x, 1, nid, nullptr, pass, pass_len, cb, u); -} - -static int do_pk8pkey(BIO *bp, const EVP_PKEY *x, int isder, int nid, - const EVP_CIPHER *enc, const char *pass, int pass_len, - pem_password_cb *cb, void *u) { +int do_pk8pkey(BIO *bp, const EVP_PKEY *x, int isder, int nid, + const EVP_CIPHER *enc, const char *pass, int pass_len, + pem_password_cb *cb, void *u) { X509_SIG *p8; PKCS8_PRIV_KEY_INFO *p8inf; char buf[PEM_BUFSIZE]; @@ -109,6 +75,51 @@ static int do_pk8pkey(BIO *bp, const EVP_PKEY *x, int isder, int nid, } } +int do_pk8pkey_fp(FILE *fp, const EVP_PKEY *x, int isder, int nid, + const EVP_CIPHER *enc, const char *pass, int pass_len, + pem_password_cb *cb, void *u) { + BIO *bp; + int ret; + if (!(bp = BIO_new_fp(fp, BIO_NOCLOSE))) { + OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB); + return 0; + } + ret = do_pk8pkey(bp, x, isder, nid, enc, pass, pass_len, cb, u); + BIO_free(bp); + return ret; +} + +} // namespace + +// These functions write a private key in PKCS#8 format: it is a "drop in" +// replacement for PEM_write_bio_PrivateKey() and friends. As usual if 'enc' +// is NULL then it uses the unencrypted private key form. The 'nid' versions +// uses PKCS#5 v1.5 PBE algorithms whereas the others use PKCS#5 v2.0. + +int PEM_write_bio_PKCS8PrivateKey_nid(BIO *bp, const EVP_PKEY *x, int nid, + const char *pass, int pass_len, + pem_password_cb *cb, void *u) { + return do_pk8pkey(bp, x, 0, nid, nullptr, pass, pass_len, cb, u); +} + +int PEM_write_bio_PKCS8PrivateKey(BIO *bp, const EVP_PKEY *x, + const EVP_CIPHER *enc, const char *pass, + int pass_len, pem_password_cb *cb, void *u) { + return do_pk8pkey(bp, x, 0, -1, enc, pass, pass_len, cb, u); +} + +int i2d_PKCS8PrivateKey_bio(BIO *bp, const EVP_PKEY *x, const EVP_CIPHER *enc, + const char *pass, int pass_len, pem_password_cb *cb, + void *u) { + return do_pk8pkey(bp, x, 1, -1, enc, pass, pass_len, cb, u); +} + +int i2d_PKCS8PrivateKey_nid_bio(BIO *bp, const EVP_PKEY *x, int nid, + const char *pass, int pass_len, + pem_password_cb *cb, void *u) { + return do_pk8pkey(bp, x, 1, nid, nullptr, pass, pass_len, cb, u); +} + EVP_PKEY *d2i_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u) { PKCS8_PRIV_KEY_INFO *p8inf = nullptr; @@ -176,20 +187,6 @@ int PEM_write_PKCS8PrivateKey(FILE *fp, const EVP_PKEY *x, return do_pk8pkey_fp(fp, x, 0, -1, enc, pass, pass_len, cb, u); } -static int do_pk8pkey_fp(FILE *fp, const EVP_PKEY *x, int isder, int nid, - const EVP_CIPHER *enc, const char *pass, int pass_len, - pem_password_cb *cb, void *u) { - BIO *bp; - int ret; - if (!(bp = BIO_new_fp(fp, BIO_NOCLOSE))) { - OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB); - return 0; - } - ret = do_pk8pkey(bp, x, isder, nid, enc, pass, pass_len, cb, u); - BIO_free(bp); - return ret; -} - EVP_PKEY *d2i_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u) { BIO *bp; diff --git a/third_party/boringssl/src/crypto/pkcs7/internal.h b/third_party/boringssl/src/crypto/pkcs7/internal.h index a6ab04e..32c74c2 100644 --- a/third_party/boringssl/src/crypto/pkcs7/internal.h +++ b/third_party/boringssl/src/crypto/pkcs7/internal.h @@ -59,8 +59,9 @@ int pkcs7_add_signed_data(CBB *out, uint64_t signed_data_version, // // Note: CMS v1 and PKCS#7 v1.5 are not completely compatible, but they overlap // in all cases implemented by this function. -int pkcs7_add_external_signature(CBB *out, X509 *sign_cert, EVP_PKEY *key, - const EVP_MD *md, BIO *data, bool use_key_id); +int pkcs7_add_external_signature(CBB *out, const X509 *sign_cert, + const EVP_PKEY *key, const EVP_MD *md, + BIO *data, bool use_key_id); BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/crypto/pkcs7/pkcs7.cc b/third_party/boringssl/src/crypto/pkcs7/pkcs7.cc index b1c2139..9ca6a47 100644 --- a/third_party/boringssl/src/crypto/pkcs7/pkcs7.cc +++ b/third_party/boringssl/src/crypto/pkcs7/pkcs7.cc @@ -26,6 +26,8 @@ using namespace bssl; +namespace { + // 1.2.840.113549.1.7.1 static const uint8_t kPKCS7Data[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01}; @@ -34,6 +36,8 @@ static const uint8_t kPKCS7Data[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, static const uint8_t kPKCS7SignedData[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02}; +} // namespace + // pkcs7_parse_header reads the non-certificate/non-CRL prefix of a PKCS#7 // SignedData blob from `cbs` and sets `*out` to point to the rest of the // input. If the input is in BER format, then `*der_bytes` will be set to a @@ -132,7 +136,9 @@ int PKCS7_get_raw_certificates(STACK_OF(CRYPTO_BUFFER) *out_certs, CBS *cbs, return ret; } -static int pkcs7_bundle_raw_certificates_cb(CBB *out, void *arg) { +namespace { + +int pkcs7_bundle_raw_certificates_cb(CBB *out, void *arg) { const STACK_OF(CRYPTO_BUFFER) *certs = reinterpret_cast(arg); CBB certificates; @@ -155,6 +161,8 @@ static int pkcs7_bundle_raw_certificates_cb(CBB *out, void *arg) { return CBB_flush_asn1_set_of(&certificates) && CBB_flush(out); } +} // namespace + int PKCS7_bundle_raw_certificates(CBB *out, const STACK_OF(CRYPTO_BUFFER) *certs) { return pkcs7_add_signed_data(out, /*signed_data_version=*/1, diff --git a/third_party/boringssl/src/crypto/pkcs7/pkcs7_x509.cc b/third_party/boringssl/src/crypto/pkcs7/pkcs7_x509.cc index cb9a725..4ca06ef 100644 --- a/third_party/boringssl/src/crypto/pkcs7/pkcs7_x509.cc +++ b/third_party/boringssl/src/crypto/pkcs7/pkcs7_x509.cc @@ -177,7 +177,9 @@ int PKCS7_get_PEM_CRLs(STACK_OF(X509_CRL) *out_crls, BIO *pem_bio) { return ret; } -static int pkcs7_bundle_certificates_cb(CBB *out, void *arg) { +namespace { + +int pkcs7_bundle_certificates_cb(CBB *out, void *arg) { auto *certs = static_cast(arg); size_t i; CBB certificates; @@ -203,6 +205,8 @@ static int pkcs7_bundle_certificates_cb(CBB *out, void *arg) { return CBB_flush_asn1_set_of(&certificates) && CBB_flush(out); } +} // namespace + int PKCS7_bundle_certificates(CBB *out, const STACK_OF(X509) *certs) { return pkcs7_add_signed_data( out, /*signed_data_version=*/1, @@ -210,7 +214,9 @@ int PKCS7_bundle_certificates(CBB *out, const STACK_OF(X509) *certs) { /*signer_infos_cb=*/nullptr, const_cast(certs)); } -static int pkcs7_bundle_crls_cb(CBB *out, void *arg) { +namespace { + +int pkcs7_bundle_crls_cb(CBB *out, void *arg) { auto *crls = static_cast(arg); size_t i; CBB crl_data; @@ -236,6 +242,8 @@ static int pkcs7_bundle_crls_cb(CBB *out, void *arg) { return CBB_flush_asn1_set_of(&crl_data) && CBB_flush(out); } +} // namespace + int PKCS7_bundle_CRLs(CBB *out, const STACK_OF(X509_CRL) *crls) { return pkcs7_add_signed_data( out, /*signed_data_version=*/1, @@ -243,7 +251,9 @@ int PKCS7_bundle_CRLs(CBB *out, const STACK_OF(X509_CRL) *crls) { /*signer_infos_cb=*/nullptr, const_cast(crls)); } -static PKCS7 *pkcs7_new(CBS *cbs) { +namespace { + +PKCS7 *pkcs7_new(CBS *cbs) { CBS copy = *cbs, copy2 = *cbs; PKCS7 *ret = New(); if (ret == nullptr) { @@ -286,6 +296,8 @@ static PKCS7 *pkcs7_new(CBS *cbs) { return nullptr; } +} // namespace + PKCS7 *d2i_PKCS7(PKCS7 **out, const uint8_t **inp, size_t len) { CBS cbs; CBS_init(&cbs, *inp, len); @@ -372,7 +384,9 @@ int PKCS7_type_is_enveloped(const PKCS7 *p7) { return 0; } int PKCS7_type_is_signed(const PKCS7 *p7) { return 1; } int PKCS7_type_is_signedAndEnveloped(const PKCS7 *p7) { return 0; } -static bool digest_sign_update(EVP_MD_CTX *ctx, BIO *data) { +namespace { + +bool digest_sign_update(EVP_MD_CTX *ctx, BIO *data) { for (;;) { uint8_t buf[4096]; const int n = BIO_read(data, buf, sizeof(buf)); @@ -384,15 +398,13 @@ static bool digest_sign_update(EVP_MD_CTX *ctx, BIO *data) { } } -namespace { struct signer_info_data { - X509 *sign_cert = nullptr; + const X509 *sign_cert = nullptr; ScopedEVP_MD_CTX sign_ctx; bool use_key_id = false; }; -} // namespace -static int write_signer_digest_algos(CBB *digest_algos_set, void *arg) { +int write_signer_digest_algos(CBB *digest_algos_set, void *arg) { auto *si_data = static_cast(arg); // https://www.rfc-editor.org/rfc/rfc5754.html#section-2 // "Implementations MUST generate SHA2 AlgorithmIdentifiers with absent @@ -405,7 +417,7 @@ static int write_signer_digest_algos(CBB *digest_algos_set, void *arg) { // https://www.rfc-editor.org/rfc/rfc2315.html#section-9.2 and // https://www.rfc-editor.org/rfc/rfc5652.html#section-5.3 to `out`. It returns // one on success or zero on error. -static int write_signer_info(CBB *out, void *arg) { +int write_signer_info(CBB *out, void *arg) { auto *si_data = static_cast(arg); uint64_t version = si_data->use_key_id ? 3u : 1u; @@ -472,9 +484,11 @@ static int write_signer_info(CBB *out, void *arg) { return 1; } -int bssl::pkcs7_add_external_signature(CBB *out, X509 *sign_cert, EVP_PKEY *key, - const EVP_MD *md, BIO *data, - bool use_key_id) { +} // namespace + +int bssl::pkcs7_add_external_signature(CBB *out, const X509 *sign_cert, + const EVP_PKEY *key, const EVP_MD *md, + BIO *data, bool use_key_id) { signer_info_data si_data; si_data.use_key_id = use_key_id; si_data.sign_cert = sign_cert; @@ -494,8 +508,8 @@ int bssl::pkcs7_add_external_signature(CBB *out, X509 *sign_cert, EVP_PKEY *key, /*cert_crl_cb=*/nullptr, write_signer_info, &si_data); } -PKCS7 *PKCS7_sign(X509 *sign_cert, EVP_PKEY *pkey, STACK_OF(X509) *certs, - BIO *data, int flags) { +PKCS7 *PKCS7_sign(const X509 *sign_cert, const EVP_PKEY *pkey, + const STACK_OF(X509) *certs, BIO *data, int flags) { ScopedCBB cbb; if (!CBB_init(cbb.get(), 2048)) { return nullptr; diff --git a/third_party/boringssl/src/crypto/pkcs8/p5_pbev2.cc b/third_party/boringssl/src/crypto/pkcs8/p5_pbev2.cc index e1307bd..6ecdd79 100644 --- a/third_party/boringssl/src/crypto/pkcs8/p5_pbev2.cc +++ b/third_party/boringssl/src/crypto/pkcs8/p5_pbev2.cc @@ -25,12 +25,13 @@ #include #include -#include "../internal.h" #include "internal.h" using namespace bssl; +namespace { + // 1.2.840.113549.1.5.12 static const uint8_t kPBKDF2[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0c}; @@ -80,7 +81,7 @@ static const struct { &EVP_aes_256_cbc}, }; -static const EVP_CIPHER *cbs_to_cipher(const CBS *cbs) { +const EVP_CIPHER *cbs_to_cipher(const CBS *cbs) { for (const auto &cipher : kCipherOIDs) { if (CBS_mem_equal(cbs, cipher.oid, cipher.oid_len)) { return cipher.cipher_func(); @@ -90,7 +91,7 @@ static const EVP_CIPHER *cbs_to_cipher(const CBS *cbs) { return nullptr; } -static int add_cipher_oid(CBB *out, int nid) { +int add_cipher_oid(CBB *out, int nid) { for (const auto &cipher : kCipherOIDs) { if (cipher.nid == nid) { return CBB_add_asn1_element(out, CBS_ASN1_OBJECT, cipher.oid, @@ -102,20 +103,11 @@ static int add_cipher_oid(CBB *out, int nid) { return 0; } -const EVP_CIPHER *bssl::pkcs5_pbe2_nid_to_cipher(int nid) { - for (const auto &cipher : kCipherOIDs) { - if (cipher.nid == nid) { - return cipher.cipher_func(); - } - } - return nullptr; -} - -static int pkcs5_pbe2_cipher_init(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, - const EVP_MD *pbkdf2_md, uint32_t iterations, - const char *pass, size_t pass_len, - const uint8_t *salt, size_t salt_len, - const uint8_t *iv, size_t iv_len, int enc) { +int pkcs5_pbe2_cipher_init(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, + const EVP_MD *pbkdf2_md, uint32_t iterations, + const char *pass, size_t pass_len, + const uint8_t *salt, size_t salt_len, + const uint8_t *iv, size_t iv_len, int enc) { if (iv_len != EVP_CIPHER_iv_length(cipher)) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_ERROR_SETTING_CIPHER_PARAMS); return 0; @@ -129,6 +121,17 @@ static int pkcs5_pbe2_cipher_init(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, return ret; } +} // namespace + +const EVP_CIPHER *bssl::pkcs5_pbe2_nid_to_cipher(int nid) { + for (const auto &cipher : kCipherOIDs) { + if (cipher.nid == nid) { + return cipher.cipher_func(); + } + } + return nullptr; +} + int bssl::PKCS5_pbe2_encrypt_init(CBB *out, EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, uint32_t iterations, const char *pass, size_t pass_len, @@ -261,8 +264,8 @@ int bssl::PKCS5_pbe2_decrypt_init(const struct pbe_suite *suite, // All supported PRFs use a NULL parameter. CBS null; - if (!CBS_get_asn1(&alg_id, &null, CBS_ASN1_NULL) || - CBS_len(&null) != 0 || + if (!CBS_get_asn1(&alg_id, &null, CBS_ASN1_NULL) || // + CBS_len(&null) != 0 || // CBS_len(&alg_id) != 0) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR); return 0; diff --git a/third_party/boringssl/src/crypto/pkcs8/pkcs8.cc b/third_party/boringssl/src/crypto/pkcs8/pkcs8.cc index 2bc9d60..21cf456 100644 --- a/third_party/boringssl/src/crypto/pkcs8/pkcs8.cc +++ b/third_party/boringssl/src/crypto/pkcs8/pkcs8.cc @@ -26,15 +26,16 @@ #include #include -#include "../bytestring/internal.h" #include "../internal.h" #include "internal.h" using namespace bssl; -static int pkcs12_encode_password(const char *in, size_t in_len, uint8_t **out, - size_t *out_len) { +namespace { + +int pkcs12_encode_password(const char *in, size_t in_len, uint8_t **out, + size_t *out_len) { ScopedCBB cbb; if (!CBB_init(cbb.get(), in_len * 2)) { return 0; @@ -60,6 +61,8 @@ static int pkcs12_encode_password(const char *in, size_t in_len, uint8_t **out, return 1; } +} // namespace + int bssl::pkcs12_key_gen(const char *pass, size_t pass_len, const uint8_t *salt, size_t salt_len, uint8_t id, uint32_t iterations, size_t out_len, uint8_t *out, const EVP_MD *md) { @@ -186,11 +189,12 @@ int bssl::pkcs12_key_gen(const char *pass, size_t pass_len, const uint8_t *salt, return ret; } -static int pkcs12_pbe_cipher_init(const struct pbe_suite *suite, - EVP_CIPHER_CTX *ctx, uint32_t iterations, - const char *pass, size_t pass_len, - const uint8_t *salt, size_t salt_len, - int is_encrypt) { +namespace { + +int pkcs12_pbe_cipher_init(const struct pbe_suite *suite, EVP_CIPHER_CTX *ctx, + uint32_t iterations, const char *pass, + size_t pass_len, const uint8_t *salt, + size_t salt_len, int is_encrypt) { const EVP_CIPHER *cipher = suite->cipher_func(); const EVP_MD *md = suite->md_func(); @@ -210,9 +214,8 @@ static int pkcs12_pbe_cipher_init(const struct pbe_suite *suite, return ret; } -static int pkcs12_pbe_decrypt_init(const struct pbe_suite *suite, - EVP_CIPHER_CTX *ctx, const char *pass, - size_t pass_len, CBS *param) { +int pkcs12_pbe_decrypt_init(const struct pbe_suite *suite, EVP_CIPHER_CTX *ctx, + const char *pass, size_t pass_len, CBS *param) { CBS pbe_param, salt; uint64_t iterations; if (!CBS_get_asn1(param, &pbe_param, CBS_ASN1_SEQUENCE) || @@ -233,7 +236,7 @@ static int pkcs12_pbe_decrypt_init(const struct pbe_suite *suite, 0 /* decrypt */); } -static const struct bssl::pbe_suite kBuiltinPBE[] = { +static const struct pbe_suite kBuiltinPBE[] = { { NID_pbe_WithSHA1And40BitRC2_CBC, // 1.2.840.113549.1.12.1.6 @@ -272,7 +275,7 @@ static const struct bssl::pbe_suite kBuiltinPBE[] = { }, }; -static const struct bssl::pbe_suite *get_pkcs12_pbe_suite(int pbe_nid) { +const struct pbe_suite *get_pkcs12_pbe_suite(int pbe_nid) { for (const auto &pbe : kBuiltinPBE) { if (pbe.pbe_nid == pbe_nid && // If `cipher_func` or `md_func` are missing, this is a PBES2 scheme. @@ -284,6 +287,8 @@ static const struct bssl::pbe_suite *get_pkcs12_pbe_suite(int pbe_nid) { return nullptr; } +} // namespace + int bssl::pkcs12_pbe_encrypt_init(CBB *out, EVP_CIPHER_CTX *ctx, int alg_nid, const EVP_CIPHER *alg_cipher, uint32_t iterations, const char *pass, diff --git a/third_party/boringssl/src/crypto/pkcs8/pkcs8_x509.cc b/third_party/boringssl/src/crypto/pkcs8/pkcs8_x509.cc index 2c0f3b6..81941e6 100644 --- a/third_party/boringssl/src/crypto/pkcs8/pkcs8_x509.cc +++ b/third_party/boringssl/src/crypto/pkcs8/pkcs8_x509.cc @@ -194,6 +194,8 @@ X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher, const char *pass, return ret; } +namespace { + struct pkcs12_context { EVP_PKEY **out_key; STACK_OF(X509) *out_certs; @@ -203,9 +205,9 @@ struct pkcs12_context { // PKCS12_handle_sequence parses a BER-encoded SEQUENCE of elements in a PKCS#12 // structure. -static int PKCS12_handle_sequence( - CBS *sequence, struct pkcs12_context *ctx, - int (*handle_element)(CBS *cbs, struct pkcs12_context *ctx)) { +int PKCS12_handle_sequence(CBS *sequence, struct pkcs12_context *ctx, + int (*handle_element)(CBS *cbs, + struct pkcs12_context *ctx)) { uint8_t *storage = nullptr; CBS in; int ret = 0; @@ -272,8 +274,8 @@ static const uint8_t kX509Certificate[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, // It sets `*out_friendly_name` to a newly-allocated copy of the friendly name, // encoded as a UTF-8 string, or NULL if there is none. It returns one on // success and zero on error. -static int parse_bag_attributes(CBS *attrs, uint8_t **out_friendly_name, - size_t *out_friendly_name_len) { +int parse_bag_attributes(CBS *attrs, uint8_t **out_friendly_name, + size_t *out_friendly_name_len) { *out_friendly_name = nullptr; *out_friendly_name_len = 0; @@ -326,7 +328,7 @@ static int parse_bag_attributes(CBS *attrs, uint8_t **out_friendly_name, // PKCS12_handle_safe_bag parses a single SafeBag element in a PKCS#12 // structure. -static int PKCS12_handle_safe_bag(CBS *safe_bag, struct pkcs12_context *ctx) { +int PKCS12_handle_safe_bag(CBS *safe_bag, struct pkcs12_context *ctx) { CBS bag_id, wrapped_value, bag_attrs; if (!CBS_get_asn1(safe_bag, &bag_id, CBS_ASN1_OBJECT) || !CBS_get_asn1(safe_bag, &wrapped_value, @@ -437,8 +439,7 @@ static const uint8_t kPKCS7EncryptedData[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, // PKCS12_handle_content_info parses a single PKCS#7 ContentInfo element in a // PKCS#12 structure. -static int PKCS12_handle_content_info(CBS *content_info, - struct pkcs12_context *ctx) { +int PKCS12_handle_content_info(CBS *content_info, struct pkcs12_context *ctx) { CBS content_type, wrapped_contents, contents; int ret = 0; uint8_t *storage = nullptr; @@ -514,10 +515,9 @@ static int PKCS12_handle_content_info(CBS *content_info, return ret; } -static int pkcs12_check_mac(int *out_mac_ok, const char *password, - size_t password_len, const CBS *salt, - uint32_t iterations, const EVP_MD *md, - const CBS *authsafes, const CBS *expected_mac) { +int pkcs12_check_mac(int *out_mac_ok, const char *password, size_t password_len, + const CBS *salt, uint32_t iterations, const EVP_MD *md, + const CBS *authsafes, const CBS *expected_mac) { int ret = 0; uint8_t hmac_key[EVP_MAX_MD_SIZE]; if (!pkcs12_key_gen(password, password_len, CBS_data(salt), CBS_len(salt), @@ -544,6 +544,8 @@ static int pkcs12_check_mac(int *out_mac_ok, const char *password, return ret; } +} // namespace + int PKCS12_get_key_and_certs(EVP_PKEY **out_key, STACK_OF(X509) *out_certs, CBS *ber_in, const char *password) { @@ -902,10 +904,12 @@ int PKCS12_verify_mac(const PKCS12 *p12, const char *password, return 1; } +namespace { + // add_bag_attributes adds the bagAttributes field of a SafeBag structure, // containing the specified friendlyName and localKeyId attributes. -static int add_bag_attributes(CBB *bag, const char *name, size_t name_len, - const uint8_t *key_id, size_t key_id_len) { +int add_bag_attributes(CBB *bag, const char *name, size_t name_len, + const uint8_t *key_id, size_t key_id_len) { if (name == nullptr && key_id_len == 0) { return 1; // Omit the OPTIONAL SET. } @@ -947,8 +951,8 @@ static int add_bag_attributes(CBB *bag, const char *name, size_t name_len, return CBB_flush_asn1_set_of(&attrs) && CBB_flush(bag); } -static int add_cert_bag(CBB *cbb, X509 *cert, const char *name, - const uint8_t *key_id, size_t key_id_len) { +int add_cert_bag(CBB *cbb, const X509 *cert, const char *name, + const uint8_t *key_id, size_t key_id_len) { CBB bag, bag_contents, cert_bag, wrapped_cert, cert_value; if ( // See https://tools.ietf.org/html/rfc7292#section-4.2. !CBB_add_asn1(cbb, &bag, CBS_ASN1_SEQUENCE) || @@ -990,9 +994,9 @@ static int add_cert_bag(CBB *cbb, X509 *cert, const char *name, return 1; } -static int add_cert_safe_contents(CBB *cbb, X509 *cert, - const STACK_OF(X509) *chain, const char *name, - const uint8_t *key_id, size_t key_id_len) { +int add_cert_safe_contents(CBB *cbb, const X509 *cert, + const STACK_OF(X509) *chain, const char *name, + const uint8_t *key_id, size_t key_id_len) { CBB safe_contents; if (!CBB_add_asn1(cbb, &safe_contents, CBS_ASN1_SEQUENCE) || (cert != nullptr && @@ -1014,11 +1018,9 @@ static int add_cert_safe_contents(CBB *cbb, X509 *cert, // add_encrypted_data encrypts `in` with `pbe_nid` and `pbe_cipher`, writing the // result to `out`. It returns one on success and zero on error. `pbe_nid` and // `pbe_cipher` are interpreted as in `PKCS8_encrypt`. -static int add_encrypted_data(CBB *out, int pbe_nid, - const EVP_CIPHER *pbe_cipher, - const char *password, size_t password_len, - uint32_t iterations, const uint8_t *in, - size_t in_len) { +int add_encrypted_data(CBB *out, int pbe_nid, const EVP_CIPHER *pbe_cipher, + const char *password, size_t password_len, + uint32_t iterations, const uint8_t *in, size_t in_len) { uint8_t salt[PKCS5_SALT_LEN]; if (!RAND_bytes(salt, sizeof(salt))) { return 0; @@ -1070,8 +1072,10 @@ static int add_encrypted_data(CBB *out, int pbe_nid, return 1; } +} // namespace + PKCS12 *PKCS12_create(const char *password, const char *name, - const EVP_PKEY *pkey, X509 *cert, + const EVP_PKEY *pkey, const X509 *cert, const STACK_OF(X509) *chain, int key_nid, int cert_nid, int iterations, int mac_iterations, int key_type) { if (key_nid == 0) { diff --git a/third_party/boringssl/src/crypto/poly1305/poly1305.cc b/third_party/boringssl/src/crypto/poly1305/poly1305.cc index 05bfff8..869722d 100644 --- a/third_party/boringssl/src/crypto/poly1305/poly1305.cc +++ b/third_party/boringssl/src/crypto/poly1305/poly1305.cc @@ -19,17 +19,19 @@ #include #include -#include +#include // IWYU pragma: keep #include "../internal.h" -#include "internal.h" +#include "internal.h" // IWYU pragma: keep using namespace bssl; #if !defined(BORINGSSL_HAS_UINT128) || !defined(OPENSSL_X86_64) -static uint64_t mul32x32_64(uint32_t a, uint32_t b) { return (uint64_t)a * b; } +namespace { + +uint64_t mul32x32_64(uint32_t a, uint32_t b) { return (uint64_t)a * b; } struct poly1305_state_st { uint32_t r0, r1, r2, r3, r4; @@ -44,15 +46,15 @@ static_assert( sizeof(struct poly1305_state_st) + 63 <= sizeof(poly1305_state), "poly1305_state isn't large enough to hold aligned poly1305_state_st"); -static struct poly1305_state_st *poly1305_aligned_state(poly1305_state *state) { +struct poly1305_state_st *poly1305_aligned_state(poly1305_state *state) { return reinterpret_cast(align_pointer(state, 64)); } // poly1305_blocks updates `state` given some amount of input data. This // function may only be called with a `len` that is not a multiple of 16 at the // end of the data. Otherwise the input must be buffered into 16 byte blocks. -static void poly1305_update(struct poly1305_state_st *state, const uint8_t *in, - size_t len) { +void poly1305_update(struct poly1305_state_st *state, const uint8_t *in, + size_t len) { uint32_t t0, t1, t2, t3; uint64_t t[5]; uint32_t b; @@ -145,6 +147,8 @@ static void poly1305_update(struct poly1305_state_st *state, const uint8_t *in, goto poly1305_donna_mul; } +} // namespace + void CRYPTO_poly1305_init(poly1305_state *statep, const uint8_t key[32]) { struct poly1305_state_st *state = poly1305_aligned_state(statep); uint32_t t0, t1, t2, t3; diff --git a/third_party/boringssl/src/crypto/poly1305/poly1305_arm.cc b/third_party/boringssl/src/crypto/poly1305/poly1305_arm.cc index f55d7cb..1221eb2 100644 --- a/third_party/boringssl/src/crypto/poly1305/poly1305_arm.cc +++ b/third_party/boringssl/src/crypto/poly1305/poly1305_arm.cc @@ -18,10 +18,12 @@ #include #include -#include +#include // IWYU pragma: keep +// IWYU pragma: begin_keep #include "../internal.h" #include "internal.h" +// IWYU pragma: end_keep BSSL_NAMESPACE_BEGIN @@ -31,7 +33,9 @@ BSSL_NAMESPACE_BEGIN #define addmulmod openssl_poly1305_neon2_addmulmod #define blocks openssl_poly1305_neon2_blocks -static void freeze(fe1305x2 *r) { +namespace { + +void freeze(fe1305x2 *r) { int i; uint32_t x0 = r->v[0]; @@ -96,7 +100,7 @@ static void freeze(fe1305x2 *r) { r->v[8] = y4; } -static void fe1305x2_tobytearray(uint8_t r[16], fe1305x2 *x) { +void fe1305x2_tobytearray(uint8_t r[16], fe1305x2 *x) { uint32_t x0 = x->v[0]; uint32_t x1 = x->v[2]; uint32_t x2 = x->v[4]; @@ -118,7 +122,7 @@ static void fe1305x2_tobytearray(uint8_t r[16], fe1305x2 *x) { CRYPTO_store_u32_le(r + 12, (x3 >> 18) + (x4 << 8)); } -static void fe1305x2_frombytearray(fe1305x2 *r, const uint8_t *x, size_t xlen) { +void fe1305x2_frombytearray(fe1305x2 *r, const uint8_t *x, size_t xlen) { size_t i; uint8_t t[17]; @@ -170,10 +174,12 @@ static_assert( sizeof(struct poly1305_state_st) + 63 <= sizeof(poly1305_state), "poly1305_state isn't large enough to hold aligned poly1305_state_st."); -static poly1305_state_st *poly1305_aligned_state(poly1305_state *state) { +poly1305_state_st *poly1305_aligned_state(poly1305_state *state) { return reinterpret_cast(align_pointer(state, 64)); } +} // namespace + void CRYPTO_poly1305_init_neon(poly1305_state *state, const uint8_t key[32]) { poly1305_state_st *st = poly1305_aligned_state(state); fe1305x2 *const r = &st->r; diff --git a/third_party/boringssl/src/crypto/poly1305/poly1305_vec.cc b/third_party/boringssl/src/crypto/poly1305/poly1305_vec.cc index 9b5e4c3..c0a5852 100644 --- a/third_party/boringssl/src/crypto/poly1305/poly1305_vec.cc +++ b/third_party/boringssl/src/crypto/poly1305/poly1305_vec.cc @@ -36,11 +36,11 @@ namespace { typedef __m128i xmmi; -alignas(16) const uint32_t poly1305_x64_sse2_message_mask[4] = { +alignas(16) static const uint32_t poly1305_x64_sse2_message_mask[4] = { (1 << 26) - 1, 0, (1 << 26) - 1, 0}; -alignas(16) const uint32_t poly1305_x64_sse2_5[4] = {5, 0, 5, 0}; -alignas(16) const uint32_t poly1305_x64_sse2_1shl128[4] = {(1 << 24), 0, - (1 << 24), 0}; +alignas(16) static const uint32_t poly1305_x64_sse2_5[4] = {5, 0, 5, 0}; +alignas(16) static const uint32_t poly1305_x64_sse2_1shl128[4] = {(1 << 24), 0, + (1 << 24), 0}; uint128_t add128(uint128_t a, uint128_t b) { return a + b; } diff --git a/third_party/boringssl/src/crypto/pool/pool.cc b/third_party/boringssl/src/crypto/pool/pool.cc index 8b1f5bc..21e2203 100644 --- a/third_party/boringssl/src/crypto/pool/pool.cc +++ b/third_party/boringssl/src/crypto/pool/pool.cc @@ -95,6 +95,13 @@ int CRYPTO_BUFFER_POOL_up_ref(CRYPTO_BUFFER_POOL *pool) { return 1; } +CRYPTO_BUFFER_POOL *CRYPTO_BUFFER_POOL_dup_ref(const CRYPTO_BUFFER_POOL *pool) { + if (pool == nullptr) { + return nullptr; + } + return FromOpaque(pool)->DupRefInternal(); +} + void CryptoBuffer::UpRefInternal() const { // This is safe in the case that `buf->pool` is NULL because it's just // standard reference counting in that case. @@ -264,6 +271,9 @@ int CRYPTO_BUFFER_up_ref(CRYPTO_BUFFER *buf) { } CRYPTO_BUFFER *CRYPTO_BUFFER_dup_ref(const CRYPTO_BUFFER *buf) { + if (buf == nullptr) { + return nullptr; + } auto *buf_ = const_cast(buf); FromOpaque(buf_)->UpRefInternal(); return buf_; diff --git a/third_party/boringssl/src/crypto/rand/deterministic.cc b/third_party/boringssl/src/crypto/rand/deterministic.cc index 187e2c1..ce16d0f 100644 --- a/third_party/boringssl/src/crypto/rand/deterministic.cc +++ b/third_party/boringssl/src/crypto/rand/deterministic.cc @@ -14,8 +14,10 @@ #include +// IWYU pragma: begin_keep #include "../bcm_support.h" #include "internal.h" +// IWYU pragma: end_keep #if defined(OPENSSL_RAND_DETERMINISTIC) @@ -28,13 +30,17 @@ using namespace bssl; +namespace { + // g_num_calls is the number of calls to `CRYPTO_sysrand` that have occurred. // // This is intentionally not thread-safe. If the fuzzer mode is ever used in a // multi-threaded program, replace this with a thread-local. (A mutex would not // be deterministic.) -static uint64_t g_num_calls = 0; -static StaticMutex g_num_calls_lock; +uint64_t g_num_calls = 0; +StaticMutex g_num_calls_lock; + +} // namespace void RAND_reset_for_fuzzing() { g_num_calls = 0; } diff --git a/third_party/boringssl/src/crypto/rand/fork_detect.cc b/third_party/boringssl/src/crypto/rand/fork_detect.cc index 4216887..d6683e9 100644 --- a/third_party/boringssl/src/crypto/rand/fork_detect.cc +++ b/third_party/boringssl/src/crypto/rand/fork_detect.cc @@ -56,7 +56,9 @@ using namespace bssl; #if defined(OPENSSL_FORK_DETECTION_WIPEONFORK) -static bool wipeonfork(void *addr, size_t page_size) { +namespace { + +bool wipeonfork(void *addr, size_t page_size) { #if defined(OPENSSL_LINUX) // Linux flavor, >=4.14. // Some versions of qemu (up to at least 5.0.0-rc4, see linux-user/syscall.c) @@ -75,14 +77,14 @@ static bool wipeonfork(void *addr, size_t page_size) { #endif } -static int g_force_madv_wipeonfork; -static int g_force_madv_wipeonfork_enabled; -static CRYPTO_once_t g_fork_detect_once = CRYPTO_ONCE_INIT; -static StaticMutex g_fork_detect_lock; -static Atomic *g_fork_detect_addr; -static uint64_t g_fork_generation; +int g_force_madv_wipeonfork; +int g_force_madv_wipeonfork_enabled; +CRYPTO_once_t g_fork_detect_once = CRYPTO_ONCE_INIT; +StaticMutex g_fork_detect_lock; +Atomic *g_fork_detect_addr; +uint64_t g_fork_generation; -static void init_fork_detect() { +void init_fork_detect() { if (g_force_madv_wipeonfork) { return; } @@ -107,6 +109,8 @@ static void init_fork_detect() { g_fork_generation = 1; } +} // namespace + uint64_t bssl::CRYPTO_get_fork_generation() { CRYPTO_once(&g_fork_detect_once, init_fork_detect); @@ -178,10 +182,12 @@ void bssl::CRYPTO_fork_detect_force_madv_wipeonfork_for_testing(int on) { #elif defined(OPENSSL_FORK_DETECTION_PTHREAD_ATFORK) -static CRYPTO_once_t g_pthread_fork_detection_once = CRYPTO_ONCE_INIT; -static uint64_t g_atfork_fork_generation; +namespace { -static void we_are_forked() { +CRYPTO_once_t g_pthread_fork_detection_once = CRYPTO_ONCE_INIT; +uint64_t g_atfork_fork_generation; + +void we_are_forked() { // Immediately after a fork, the process must be single-threaded. uint64_t value = g_atfork_fork_generation + 1; if (value == 0) { @@ -190,13 +196,15 @@ static void we_are_forked() { g_atfork_fork_generation = value; } -static void init_pthread_fork_detection() { +void init_pthread_fork_detection() { if (pthread_atfork(nullptr, nullptr, we_are_forked) != 0) { abort(); } g_atfork_fork_generation = 1; } +} // namespace + uint64_t bssl::CRYPTO_get_fork_generation() { CRYPTO_once(&g_pthread_fork_detection_once, init_pthread_fork_detection); diff --git a/third_party/boringssl/src/crypto/rand/forkunsafe.cc b/third_party/boringssl/src/crypto/rand/forkunsafe.cc index 32760b2..77858d7 100644 --- a/third_party/boringssl/src/crypto/rand/forkunsafe.cc +++ b/third_party/boringssl/src/crypto/rand/forkunsafe.cc @@ -22,9 +22,13 @@ using namespace bssl; +namespace { + // g_buffering_enabled is one if fork-unsafe buffering has been enabled and zero // otherwise. -static bssl::Atomic g_buffering_enabled; +bssl::Atomic g_buffering_enabled; + +} // namespace #if !defined(OPENSSL_WINDOWS) void RAND_enable_fork_unsafe_buffering(int fd) { diff --git a/third_party/boringssl/src/crypto/rand/rand.cc b/third_party/boringssl/src/crypto/rand/rand.cc index ea304bd..8d18ac8 100644 --- a/third_party/boringssl/src/crypto/rand/rand.cc +++ b/third_party/boringssl/src/crypto/rand/rand.cc @@ -56,11 +56,15 @@ int RAND_poll() { return 1; } int RAND_status() { return 1; } +namespace { + static const struct rand_meth_st kSSLeayMethod = { RAND_seed, RAND_bytes, RAND_cleanup, RAND_add, RAND_pseudo_bytes, RAND_status, }; +} // namespace + RAND_METHOD *RAND_SSLeay() { return (RAND_METHOD *)&kSSLeayMethod; } RAND_METHOD *RAND_OpenSSL() { return RAND_SSLeay(); } diff --git a/third_party/boringssl/src/crypto/rand/urandom.cc b/third_party/boringssl/src/crypto/rand/urandom.cc index b5aabde..9349c7f 100644 --- a/third_party/boringssl/src/crypto/rand/urandom.cc +++ b/third_party/boringssl/src/crypto/rand/urandom.cc @@ -41,7 +41,9 @@ void __msan_unpoison(void *, size_t); } #endif -static ssize_t boringssl_getrandom(void *buf, size_t buf_len, unsigned flags) { +namespace { + +ssize_t boringssl_getrandom(void *buf, size_t buf_len, unsigned flags) { ssize_t ret; do { ret = syscall(__NR_getrandom, buf, buf_len, flags); @@ -63,14 +65,14 @@ static ssize_t boringssl_getrandom(void *buf, size_t buf_len, unsigned flags) { static const int kHaveGetrandom = -3; // urandom_fd is a file descriptor to /dev/urandom. It's protected by `once`. -static int urandom_fd; +int urandom_fd; -static CRYPTO_once_t rand_once = CRYPTO_ONCE_INIT; +CRYPTO_once_t g_rand_once = CRYPTO_ONCE_INIT; // init_once initializes the state of this module to values previously // requested. This is the only function that modifies `urandom_fd`, which may be // read safely after calling the once. -static void init_once() { +void init_once() { int have_getrandom; uint8_t dummy; ssize_t getrandom_ret = @@ -113,7 +115,9 @@ static void init_once() { urandom_fd = fd; } -void bssl::CRYPTO_init_sysrand() { CRYPTO_once(&rand_once, init_once); } +} // namespace + +void bssl::CRYPTO_init_sysrand() { CRYPTO_once(&g_rand_once, init_once); } // CRYPTO_sysrand writes `len` bytes of entropy into `out`. void bssl::CRYPTO_sysrand(uint8_t *out, size_t len) { diff --git a/third_party/boringssl/src/crypto/rand/windows.cc b/third_party/boringssl/src/crypto/rand/windows.cc index ebd0d4a..30aac3f 100644 --- a/third_party/boringssl/src/crypto/rand/windows.cc +++ b/third_party/boringssl/src/crypto/rand/windows.cc @@ -14,9 +14,11 @@ #include +// IWYU pragma: begin_keep #include "../bcm_support.h" #include "../internal.h" #include "internal.h" +// IWYU pragma: end_keep #if defined(OPENSSL_RAND_WINDOWS) @@ -56,11 +58,13 @@ void bssl::CRYPTO_sysrand(uint8_t *out, size_t requested) { #else +namespace { + // See: https://learn.microsoft.com/en-us/windows/win32/seccng/processprng typedef BOOL(WINAPI *ProcessPrngFunction)(PBYTE pbData, SIZE_T cbData); -static ProcessPrngFunction g_processprng_fn = nullptr; +ProcessPrngFunction g_processprng_fn = nullptr; -static void init_processprng() { +void init_processprng() { HMODULE hmod = LoadLibraryW(L"bcryptprimitives"); if (hmod == nullptr) { abort(); @@ -71,6 +75,8 @@ static void init_processprng() { } } +} // namespace + void bssl::CRYPTO_init_sysrand() { static CRYPTO_once_t once = CRYPTO_ONCE_INIT; CRYPTO_once(&once, init_processprng); diff --git a/third_party/boringssl/src/crypto/rsa/rsa_asn1.cc b/third_party/boringssl/src/crypto/rsa/rsa_asn1.cc index eb61d5e..18d977c 100644 --- a/third_party/boringssl/src/crypto/rsa/rsa_asn1.cc +++ b/third_party/boringssl/src/crypto/rsa/rsa_asn1.cc @@ -35,7 +35,9 @@ using namespace bssl; -static int parse_integer(CBS *cbs, UniquePtr *out) { +namespace { + +int parse_integer(CBS *cbs, UniquePtr *out) { assert(*out == nullptr); out->reset(BN_new()); if (*out == nullptr) { @@ -44,7 +46,7 @@ static int parse_integer(CBS *cbs, UniquePtr *out) { return BN_parse_asn1_unsigned(cbs, out->get()); } -static int marshal_integer(CBB *cbb, const BIGNUM *bn) { +int marshal_integer(CBB *cbb, const BIGNUM *bn) { if (bn == nullptr) { // An RSA object may be missing some components. OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING); @@ -53,15 +55,17 @@ static int marshal_integer(CBB *cbb, const BIGNUM *bn) { return BN_marshal_asn1(cbb, bn); } +} // namespace + RSA *RSA_parse_public_key(CBS *cbs) { RSAImpl *ret = FromOpaque(RSA_new()); if (ret == nullptr) { return nullptr; } CBS child; - if (!CBS_get_asn1(cbs, &child, CBS_ASN1_SEQUENCE) || - !parse_integer(&child, &ret->n) || - !parse_integer(&child, &ret->e) || + if (!CBS_get_asn1(cbs, &child, CBS_ASN1_SEQUENCE) || // + !parse_integer(&child, &ret->n) || // + !parse_integer(&child, &ret->e) || // CBS_len(&child) != 0) { OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_ENCODING); RSA_free(ret); @@ -92,9 +96,9 @@ RSA *RSA_public_key_from_bytes(const uint8_t *in, size_t in_len) { int RSA_marshal_public_key(CBB *cbb, const RSA *rsa) { CBB child; const RSAImpl *impl = FromOpaque(rsa); - if (!CBB_add_asn1(cbb, &child, CBS_ASN1_SEQUENCE) || - !marshal_integer(&child, impl->n.get()) || - !marshal_integer(&child, impl->e.get()) || // + if (!CBB_add_asn1(cbb, &child, CBS_ASN1_SEQUENCE) || // + !marshal_integer(&child, impl->n.get()) || // + !marshal_integer(&child, impl->e.get()) || // !CBB_flush(cbb)) { OPENSSL_PUT_ERROR(RSA, RSA_R_ENCODE_ERROR); return 0; @@ -106,8 +110,8 @@ int RSA_public_key_to_bytes(uint8_t **out_bytes, size_t *out_len, const RSA *rsa) { CBB cbb; CBB_zero(&cbb); - if (!CBB_init(&cbb, 0) || - !RSA_marshal_public_key(&cbb, rsa) || + if (!CBB_init(&cbb, 0) || // + !RSA_marshal_public_key(&cbb, rsa) || // !CBB_finish(&cbb, out_bytes, out_len)) { OPENSSL_PUT_ERROR(RSA, RSA_R_ENCODE_ERROR); CBB_cleanup(&cbb); @@ -116,10 +120,14 @@ int RSA_public_key_to_bytes(uint8_t **out_bytes, size_t *out_len, return 1; } +namespace { + // kVersionTwoPrime is the value of the version field for a two-prime // RSAPrivateKey structure (RFC 8017). static const uint64_t kVersionTwoPrime = 0; +} // namespace + RSA *RSA_parse_private_key(CBS *cbs) { RSAImpl *ret = FromOpaque(RSA_new()); if (ret == nullptr) { @@ -139,13 +147,13 @@ RSA *RSA_parse_private_key(CBS *cbs) { goto err; } - if (!parse_integer(&child, &ret->n) || - !parse_integer(&child, &ret->e) || - !parse_integer(&child, &ret->d) || - !parse_integer(&child, &ret->p) || - !parse_integer(&child, &ret->q) || - !parse_integer(&child, &ret->dmp1) || - !parse_integer(&child, &ret->dmq1) || + if (!parse_integer(&child, &ret->n) || // + !parse_integer(&child, &ret->e) || // + !parse_integer(&child, &ret->d) || // + !parse_integer(&child, &ret->p) || // + !parse_integer(&child, &ret->q) || // + !parse_integer(&child, &ret->dmp1) || // + !parse_integer(&child, &ret->dmq1) || // !parse_integer(&child, &ret->iqmp)) { goto err; } @@ -182,16 +190,16 @@ RSA *RSA_private_key_from_bytes(const uint8_t *in, size_t in_len) { int RSA_marshal_private_key(CBB *cbb, const RSA *rsa) { const RSAImpl *impl = FromOpaque(rsa); CBB child; - if (!CBB_add_asn1(cbb, &child, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1_uint64(&child, kVersionTwoPrime) || - !marshal_integer(&child, impl->n.get()) || - !marshal_integer(&child, impl->e.get()) || - !marshal_integer(&child, impl->d.get()) || - !marshal_integer(&child, impl->p.get()) || - !marshal_integer(&child, impl->q.get()) || - !marshal_integer(&child, impl->dmp1.get()) || - !marshal_integer(&child, impl->dmq1.get()) || - !marshal_integer(&child, impl->iqmp.get()) || // + if (!CBB_add_asn1(cbb, &child, CBS_ASN1_SEQUENCE) || // + !CBB_add_asn1_uint64(&child, kVersionTwoPrime) || // + !marshal_integer(&child, impl->n.get()) || // + !marshal_integer(&child, impl->e.get()) || // + !marshal_integer(&child, impl->d.get()) || // + !marshal_integer(&child, impl->p.get()) || // + !marshal_integer(&child, impl->q.get()) || // + !marshal_integer(&child, impl->dmp1.get()) || // + !marshal_integer(&child, impl->dmq1.get()) || // + !marshal_integer(&child, impl->iqmp.get()) || // !CBB_flush(cbb)) { OPENSSL_PUT_ERROR(RSA, RSA_R_ENCODE_ERROR); return 0; @@ -203,8 +211,8 @@ int RSA_private_key_to_bytes(uint8_t **out_bytes, size_t *out_len, const RSA *rsa) { CBB cbb; CBB_zero(&cbb); - if (!CBB_init(&cbb, 0) || - !RSA_marshal_private_key(&cbb, rsa) || + if (!CBB_init(&cbb, 0) || // + !RSA_marshal_private_key(&cbb, rsa) || // !CBB_finish(&cbb, out_bytes, out_len)) { OPENSSL_PUT_ERROR(RSA, RSA_R_ENCODE_ERROR); CBB_cleanup(&cbb); @@ -255,6 +263,8 @@ RSA *RSAPrivateKey_dup(const RSA *rsa) { return ret; } +namespace { + static const uint8_t kPSSParamsSHA256[] = { 0x30, 0x34, 0xa0, 0x0f, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0xa1, 0x1c, 0x30, @@ -276,6 +286,8 @@ static const uint8_t kPSSParamsSHA512[] = { 0x08, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0xa2, 0x03, 0x02, 0x01, 0x40}; +} // namespace + const EVP_MD *bssl::rsa_pss_params_get_md(rsa_pss_params_t params) { switch (params) { case rsa_pss_none: @@ -310,10 +322,14 @@ int bssl::rsa_marshal_pss_params(CBB *cbb, rsa_pss_params_t params) { return CBB_add_bytes(cbb, bytes.data(), bytes.size()); } +namespace { + // 1.2.840.113549.1.1.8 static const uint8_t kMGF1OID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x08}; +} // namespace + int bssl::rsa_parse_pss_params(CBS *cbs, rsa_pss_params_t *out, int allow_explicit_trailer) { // See RFC 4055, section 3.1. diff --git a/third_party/boringssl/src/crypto/rsa/rsa_crypt.cc b/third_party/boringssl/src/crypto/rsa/rsa_crypt.cc index fe4e2d9..47254d9 100644 --- a/third_party/boringssl/src/crypto/rsa/rsa_crypt.cc +++ b/third_party/boringssl/src/crypto/rsa/rsa_crypt.cc @@ -31,7 +31,9 @@ using namespace bssl; -static void rand_nonzero(uint8_t *out, size_t len) { +namespace { + +void rand_nonzero(uint8_t *out, size_t len) { RAND_bytes(out, len); for (size_t i = 0; i < len; i++) { @@ -43,6 +45,8 @@ static void rand_nonzero(uint8_t *out, size_t len) { } } +} // namespace + int RSA_padding_add_PKCS1_OAEP_mgf1(uint8_t *to, size_t to_len, const uint8_t *from, size_t from_len, const uint8_t *param, size_t param_len, @@ -220,8 +224,10 @@ int bssl::RSA_padding_check_PKCS1_OAEP_mgf1(uint8_t *out, size_t *out_len, return 0; } -static int rsa_padding_add_PKCS1_type_2(uint8_t *to, size_t to_len, - const uint8_t *from, size_t from_len) { +namespace { + +int rsa_padding_add_PKCS1_type_2(uint8_t *to, size_t to_len, + const uint8_t *from, size_t from_len) { // See RFC 8017, section 7.2.1. if (to_len < RSA_PKCS1_PADDING_SIZE) { OPENSSL_PUT_ERROR(RSA, RSA_R_KEY_SIZE_TOO_SMALL); @@ -243,9 +249,9 @@ static int rsa_padding_add_PKCS1_type_2(uint8_t *to, size_t to_len, return 1; } -static int rsa_padding_check_PKCS1_type_2(uint8_t *out, size_t *out_len, - size_t max_out, const uint8_t *from, - size_t from_len) { +int rsa_padding_check_PKCS1_type_2(uint8_t *out, size_t *out_len, + size_t max_out, const uint8_t *from, + size_t from_len) { if (from_len == 0) { OPENSSL_PUT_ERROR(RSA, RSA_R_EMPTY_PUBLIC_KEY); return 0; @@ -310,6 +316,8 @@ static int rsa_padding_check_PKCS1_type_2(uint8_t *out, size_t *out_len, return 1; } +} // namespace + int RSA_public_encrypt(size_t flen, const uint8_t *from, uint8_t *to, RSA *rsa, int padding) { size_t out_len; @@ -426,9 +434,10 @@ int RSA_encrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, return ret; } -static int rsa_default_decrypt(RSA *rsa, size_t *out_len, uint8_t *out, - size_t max_out, const uint8_t *in, size_t in_len, - int padding) { +namespace { + +int rsa_default_decrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, + const uint8_t *in, size_t in_len, int padding) { const unsigned rsa_size = RSA_size(rsa); uint8_t *buf = nullptr; int ret = 0; @@ -491,6 +500,8 @@ static int rsa_default_decrypt(RSA *rsa, size_t *out_len, uint8_t *out, return ret; } +} // namespace + int RSA_decrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, const uint8_t *in, size_t in_len, int padding) { auto *impl = FromOpaque(rsa); diff --git a/third_party/boringssl/src/crypto/rsa/rsa_print.cc b/third_party/boringssl/src/crypto/rsa/rsa_print.cc index 52d7732..274df3f 100644 --- a/third_party/boringssl/src/crypto/rsa/rsa_print.cc +++ b/third_party/boringssl/src/crypto/rsa/rsa_print.cc @@ -19,7 +19,6 @@ int RSA_print(BIO *bio, const RSA *rsa, int indent) { bssl::UniquePtr pkey(EVP_PKEY_new()); - return pkey != nullptr && - EVP_PKEY_set1_RSA(pkey.get(), const_cast(rsa)) && + return pkey != nullptr && EVP_PKEY_set1_RSA(pkey.get(), rsa) && EVP_PKEY_print_private(bio, pkey.get(), indent, nullptr); } diff --git a/third_party/boringssl/src/crypto/sha/sha1.cc b/third_party/boringssl/src/crypto/sha/sha1.cc index 6b06961..5cb31c7 100644 --- a/third_party/boringssl/src/crypto/sha/sha1.cc +++ b/third_party/boringssl/src/crypto/sha/sha1.cc @@ -36,15 +36,6 @@ int SHA1_Final(uint8_t out[SHA_DIGEST_LENGTH], SHA_CTX *sha) { return 1; } -uint8_t *SHA1(const uint8_t *data, size_t len, uint8_t out[SHA_DIGEST_LENGTH]) { - SHA_CTX ctx; - BCM_sha1_init(&ctx); - BCM_sha1_update(&ctx, data, len); - BCM_sha1_final(out, &ctx); - OPENSSL_cleanse(&ctx, sizeof(ctx)); - return out; -} - void SHA1_Transform(SHA_CTX *sha, const uint8_t block[SHA_CBLOCK]) { BCM_sha1_transform(sha, block); } diff --git a/third_party/boringssl/src/crypto/sha/sha256.cc b/third_party/boringssl/src/crypto/sha/sha256.cc index 3ef66bc..4528177 100644 --- a/third_party/boringssl/src/crypto/sha/sha256.cc +++ b/third_party/boringssl/src/crypto/sha/sha256.cc @@ -36,16 +36,6 @@ int SHA224_Final(uint8_t out[SHA224_DIGEST_LENGTH], SHA256_CTX *sha) { return 1; } -uint8_t *SHA224(const uint8_t *data, size_t len, - uint8_t out[SHA224_DIGEST_LENGTH]) { - SHA256_CTX ctx; - BCM_sha224_init(&ctx); - BCM_sha224_update(&ctx, data, len); - BCM_sha224_final(out, &ctx); - OPENSSL_cleanse(&ctx, sizeof(ctx)); - return out; -} - int SHA256_Init(SHA256_CTX *sha) { BCM_sha256_init(sha); return 1; @@ -69,16 +59,6 @@ int SHA256_Final(uint8_t out[SHA256_DIGEST_LENGTH], SHA256_CTX *sha) { return 1; } -uint8_t *SHA256(const uint8_t *data, size_t len, - uint8_t out[SHA256_DIGEST_LENGTH]) { - SHA256_CTX ctx; - BCM_sha256_init(&ctx); - BCM_sha256_update(&ctx, data, len); - BCM_sha256_final(out, &ctx); - OPENSSL_cleanse(&ctx, sizeof(ctx)); - return out; -} - void SHA256_Transform(SHA256_CTX *sha, const uint8_t block[SHA256_CBLOCK]) { BCM_sha256_transform(sha, block); } diff --git a/third_party/boringssl/src/crypto/sha/sha512.cc b/third_party/boringssl/src/crypto/sha/sha512.cc index afb5516..87c94a2 100644 --- a/third_party/boringssl/src/crypto/sha/sha512.cc +++ b/third_party/boringssl/src/crypto/sha/sha512.cc @@ -36,16 +36,6 @@ int SHA384_Final(uint8_t out[SHA384_DIGEST_LENGTH], SHA512_CTX *sha) { return 1; } -uint8_t *SHA384(const uint8_t *data, size_t len, - uint8_t out[SHA384_DIGEST_LENGTH]) { - SHA512_CTX ctx; - BCM_sha384_init(&ctx); - BCM_sha384_update(&ctx, data, len); - BCM_sha384_final(out, &ctx); - OPENSSL_cleanse(&ctx, sizeof(ctx)); - return out; -} - int SHA512_256_Init(SHA512_CTX *sha) { BCM_sha512_256_init(sha); return 1; @@ -61,16 +51,6 @@ int SHA512_256_Final(uint8_t out[SHA512_256_DIGEST_LENGTH], SHA512_CTX *sha) { return 1; } -uint8_t *SHA512_256(const uint8_t *data, size_t len, - uint8_t out[SHA512_256_DIGEST_LENGTH]) { - SHA512_CTX ctx; - BCM_sha512_256_init(&ctx); - BCM_sha512_256_update(&ctx, data, len); - BCM_sha512_256_final(out, &ctx); - OPENSSL_cleanse(&ctx, sizeof(ctx)); - return out; -} - int SHA512_Init(SHA512_CTX *sha) { BCM_sha512_init(sha); return 1; @@ -91,16 +71,6 @@ int SHA512_Final(uint8_t out[SHA512_DIGEST_LENGTH], SHA512_CTX *sha) { return 1; } -uint8_t *SHA512(const uint8_t *data, size_t len, - uint8_t out[SHA512_DIGEST_LENGTH]) { - SHA512_CTX ctx; - BCM_sha512_init(&ctx); - BCM_sha512_update(&ctx, data, len); - BCM_sha512_final(out, &ctx); - OPENSSL_cleanse(&ctx, sizeof(ctx)); - return out; -} - void SHA512_Transform(SHA512_CTX *sha, const uint8_t block[SHA512_CBLOCK]) { BCM_sha512_transform(sha, block); } diff --git a/third_party/boringssl/src/crypto/trust_token/trust_token.cc b/third_party/boringssl/src/crypto/trust_token/trust_token.cc index d0e5c24..b295a6b 100644 --- a/third_party/boringssl/src/crypto/trust_token/trust_token.cc +++ b/third_party/boringssl/src/crypto/trust_token/trust_token.cc @@ -279,13 +279,13 @@ int TRUST_TOKEN_CLIENT_add_key(TRUST_TOKEN_CLIENT *ctx, size_t *out_key_index, return 1; } -int TRUST_TOKEN_CLIENT_set_srr_key(TRUST_TOKEN_CLIENT *ctx, EVP_PKEY *key) { +int TRUST_TOKEN_CLIENT_set_srr_key(TRUST_TOKEN_CLIENT *ctx, + const EVP_PKEY *key) { if (!ctx->method->has_srr) { return 1; } EVP_PKEY_free(ctx->srr_key); - EVP_PKEY_up_ref(key); - ctx->srr_key = key; + ctx->srr_key = EVP_PKEY_dup_ref(key); return 1; } @@ -515,10 +515,10 @@ int TRUST_TOKEN_ISSUER_add_key(TRUST_TOKEN_ISSUER *ctx, const uint8_t *key, return 1; } -int TRUST_TOKEN_ISSUER_set_srr_key(TRUST_TOKEN_ISSUER *ctx, EVP_PKEY *key) { +int TRUST_TOKEN_ISSUER_set_srr_key(TRUST_TOKEN_ISSUER *ctx, + const EVP_PKEY *key) { EVP_PKEY_free(ctx->srr_key); - EVP_PKEY_up_ref(key); - ctx->srr_key = key; + ctx->srr_key = EVP_PKEY_dup_ref(key); return 1; } diff --git a/third_party/boringssl/src/crypto/x509/a_sign.cc b/third_party/boringssl/src/crypto/x509/a_sign.cc index 3e313d4..f09e80a 100644 --- a/third_party/boringssl/src/crypto/x509/a_sign.cc +++ b/third_party/boringssl/src/crypto/x509/a_sign.cc @@ -31,7 +31,7 @@ using namespace bssl; int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2, - ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey, + ASN1_BIT_STRING *signature, void *asn, const EVP_PKEY *pkey, const EVP_MD *type) { if (signature->type != V_ASN1_BIT_STRING) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE); diff --git a/third_party/boringssl/src/crypto/x509/a_verify.cc b/third_party/boringssl/src/crypto/x509/a_verify.cc index e7b8bd9..e3ae122 100644 --- a/third_party/boringssl/src/crypto/x509/a_verify.cc +++ b/third_party/boringssl/src/crypto/x509/a_verify.cc @@ -33,7 +33,7 @@ using namespace bssl; int bssl::x509_verify_signature(const X509_ALGOR *sigalg, const ASN1_BIT_STRING *signature, - Span in, EVP_PKEY *pkey) { + Span in, const EVP_PKEY *pkey) { if (signature->type == V_ASN1_BIT_STRING && ASN1_BIT_STRING_unused_bits(signature) != 0) { OPENSSL_PUT_ERROR(X509, X509_R_INVALID_BIT_STRING_BITS_LEFT); @@ -46,7 +46,8 @@ int bssl::x509_verify_signature(const X509_ALGOR *sigalg, int bssl::x509_verify_signature_bytes(const X509_ALGOR *sigalg, Span signature, - Span in, EVP_PKEY *pkey) { + Span in, + const EVP_PKEY *pkey) { if (!pkey) { OPENSSL_PUT_ERROR(X509, ERR_R_PASSED_NULL_PARAMETER); return 0; @@ -66,7 +67,7 @@ int bssl::x509_verify_signature_bytes(const X509_ALGOR *sigalg, int ASN1_item_verify(const ASN1_ITEM *it, const X509_ALGOR *sigalg, const ASN1_BIT_STRING *signature, void *asn, - EVP_PKEY *pkey) { + const EVP_PKEY *pkey) { uint8_t *in = nullptr; int in_len = ASN1_item_i2d(reinterpret_cast(asn), &in, it); if (in_len < 0) { diff --git a/third_party/boringssl/src/crypto/x509/algorithm.cc b/third_party/boringssl/src/crypto/x509/algorithm.cc index 2a5a6da..1e5afbc 100644 --- a/third_party/boringssl/src/crypto/x509/algorithm.cc +++ b/third_party/boringssl/src/crypto/x509/algorithm.cc @@ -30,8 +30,10 @@ using namespace bssl; // signature algorithm into a small enum and convert them to/from `EVP_PKEY_CTX` // and `X509_ALGOR`. +namespace { + // Restrict the digests that are allowed in X509 certificates -static int x509_digest_nid_ok(const int digest_nid) { +int x509_digest_nid_ok(const int digest_nid) { switch (digest_nid) { case NID_md4: case NID_md5: @@ -40,6 +42,8 @@ static int x509_digest_nid_ok(const int digest_nid) { return 1; } +} // namespace + int bssl::x509_digest_sign_algorithm(EVP_MD_CTX *ctx, X509_ALGOR *algor) { EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx->pctx); if (pkey == nullptr) { @@ -103,7 +107,7 @@ int bssl::x509_digest_sign_algorithm(EVP_MD_CTX *ctx, X509_ALGOR *algor) { } int bssl::x509_digest_verify_init(EVP_MD_CTX *ctx, const X509_ALGOR *sigalg, - EVP_PKEY *pkey) { + const EVP_PKEY *pkey) { // Convert the signature OID into digest and public key OIDs. int sigalg_nid = OBJ_obj2nid(sigalg->algorithm); int digest_nid, pkey_nid; diff --git a/third_party/boringssl/src/crypto/x509/asn1_gen.cc b/third_party/boringssl/src/crypto/x509/asn1_gen.cc index 4fb4f50..a8adc50 100644 --- a/third_party/boringssl/src/crypto/x509/asn1_gen.cc +++ b/third_party/boringssl/src/crypto/x509/asn1_gen.cc @@ -48,45 +48,25 @@ using namespace bssl; #define ASN1_GEN_FORMAT_HEX 3 #define ASN1_GEN_FORMAT_BITLIST 4 +namespace { + // generate_v3 converts `str` into an ASN.1 structure and writes the result to // `cbb`. It returns one on success and zero on error. `depth` bounds recursion, // and `format` specifies the current format modifier. // // If `tag` is non-zero, the structure is implicitly tagged with `tag`. `tag` // must not have the constructed bit set. -static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, - CBS_ASN1_TAG tag, int format, int depth); - -static int bitstr_cb(const char *elem, size_t len, void *bitstr); - -ASN1_TYPE *bssl::ASN1_generate_v3(const char *str, const X509V3_CTX *cnf) { - ScopedCBB cbb; - if (!CBB_init(cbb.get(), 0) || // - !generate_v3(cbb.get(), str, cnf, /*tag=*/0, ASN1_GEN_FORMAT_ASCII, - /*depth=*/0)) { - return nullptr; - } - - // While not strictly necessary to avoid a DoS (we rely on any super-linear - // checks being performed internally), cap the overall output to - // `ASN1_GEN_MAX_OUTPUT` so the externally-visible behavior is consistent. - if (CBB_len(cbb.get()) > ASN1_GEN_MAX_OUTPUT) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_TOO_LONG); - return nullptr; - } - - const uint8_t *der = CBB_data(cbb.get()); - return d2i_ASN1_TYPE(nullptr, &der, CBB_len(cbb.get())); -} +int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, + CBS_ASN1_TAG tag, int format, int depth); -static int cbs_str_equal(const CBS *cbs, const char *str) { +int cbs_str_equal(const CBS *cbs, const char *str) { return CBS_len(cbs) == strlen(str) && OPENSSL_memcmp(CBS_data(cbs), str, strlen(str)) == 0; } // parse_tag decodes a tag specifier in `cbs`. It returns the tag on success or // zero on error. -static CBS_ASN1_TAG parse_tag(const CBS *cbs) { +CBS_ASN1_TAG parse_tag(const CBS *cbs) { CBS copy = *cbs; uint64_t num; if (!CBS_get_u64_decimal(©, &num) || num > CBS_ASN1_TAG_NUMBER_MASK) { @@ -132,9 +112,8 @@ static CBS_ASN1_TAG parse_tag(const CBS *cbs) { return tag_class | (CBS_ASN1_TAG)num; } -static int generate_wrapped(CBB *cbb, const char *str, const X509V3_CTX *cnf, - CBS_ASN1_TAG tag, int padding, int format, - int depth) { +int generate_wrapped(CBB *cbb, const char *str, const X509V3_CTX *cnf, + CBS_ASN1_TAG tag, int padding, int format, int depth) { CBB child; return CBB_add_asn1(cbb, &child, tag) && (!padding || CBB_add_u8(&child, 0)) && @@ -142,8 +121,33 @@ static int generate_wrapped(CBB *cbb, const char *str, const X509V3_CTX *cnf, CBB_flush(cbb); } -static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, - CBS_ASN1_TAG tag, int format, int depth) { +int bitstr_cb(const char *elem, size_t len, void *bitstr) { + CBS cbs; + CBS_init(&cbs, (const uint8_t *)elem, len); + uint64_t bitnum; + if (!CBS_get_u64_decimal(&cbs, &bitnum) || CBS_len(&cbs) != 0 || + // Cap the highest allowed bit so this mechanism cannot be used to create + // extremely large allocations with short inputs. The highest named bit in + // RFC 5280 is 8, so 256 should give comfortable margin but still only + // allow a 32-byte allocation. + // + // We do not consider this function to be safe with untrusted inputs (even + // without bugs, it is prone to string injection vulnerabilities), so DoS + // is not truly a concern, but the limit is necessary to keep fuzzing + // effective. + bitnum > 256) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_NUMBER); + return 0; + } + if (!ASN1_BIT_STRING_set_bit(reinterpret_cast(bitstr), + (int)bitnum, 1)) { + return 0; + } + return 1; +} + +int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, + CBS_ASN1_TAG tag, int format, int depth) { assert((tag & CBS_ASN1_CONSTRUCTED) == 0); if (depth > ASN1_GEN_MAX_DEPTH) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_NESTED_TAGGING); @@ -514,27 +518,24 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, } } -static int bitstr_cb(const char *elem, size_t len, void *bitstr) { - CBS cbs; - CBS_init(&cbs, (const uint8_t *)elem, len); - uint64_t bitnum; - if (!CBS_get_u64_decimal(&cbs, &bitnum) || CBS_len(&cbs) != 0 || - // Cap the highest allowed bit so this mechanism cannot be used to create - // extremely large allocations with short inputs. The highest named bit in - // RFC 5280 is 8, so 256 should give comfortable margin but still only - // allow a 32-byte allocation. - // - // We do not consider this function to be safe with untrusted inputs (even - // without bugs, it is prone to string injection vulnerabilities), so DoS - // is not truly a concern, but the limit is necessary to keep fuzzing - // effective. - bitnum > 256) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_NUMBER); - return 0; +} // namespace + +ASN1_TYPE *bssl::ASN1_generate_v3(const char *str, const X509V3_CTX *cnf) { + ScopedCBB cbb; + if (!CBB_init(cbb.get(), 0) || // + !generate_v3(cbb.get(), str, cnf, /*tag=*/0, ASN1_GEN_FORMAT_ASCII, + /*depth=*/0)) { + return nullptr; } - if (!ASN1_BIT_STRING_set_bit(reinterpret_cast(bitstr), - (int)bitnum, 1)) { - return 0; + + // While not strictly necessary to avoid a DoS (we rely on any super-linear + // checks being performed internally), cap the overall output to + // `ASN1_GEN_MAX_OUTPUT` so the externally-visible behavior is consistent. + if (CBB_len(cbb.get()) > ASN1_GEN_MAX_OUTPUT) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_TOO_LONG); + return nullptr; } - return 1; + + const uint8_t *der = CBB_data(cbb.get()); + return d2i_ASN1_TYPE(nullptr, &der, CBB_len(cbb.get())); } diff --git a/third_party/boringssl/src/crypto/x509/by_dir.cc b/third_party/boringssl/src/crypto/x509/by_dir.cc index a1aeecf..eeb7aa7 100644 --- a/third_party/boringssl/src/crypto/x509/by_dir.cc +++ b/third_party/boringssl/src/crypto/x509/by_dir.cc @@ -30,6 +30,8 @@ BSSL_NAMESPACE_BEGIN +namespace { + // A ByDirEntry tracks state for a single directory, notably the starting suffix // for CRL lookups. class ByDirEntry { @@ -53,7 +55,8 @@ class ByDirEntry { int GetCRLSuffix(uint32_t hash) const { MutexReadLock lock(&lock_); - auto it = std::lower_bound(crl_suffixes_.begin(), crl_suffixes_.end(), hash); + auto it = + std::lower_bound(crl_suffixes_.begin(), crl_suffixes_.end(), hash); if (it == crl_suffixes_.end() || it->hash != hash) { return 0; } @@ -62,7 +65,8 @@ class ByDirEntry { bool UpdateCRLSuffix(uint32_t hash, int suffix) { MutexWriteLock lock(&lock_); - auto it = std::lower_bound(crl_suffixes_.begin(), crl_suffixes_.end(), hash); + auto it = + std::lower_bound(crl_suffixes_.begin(), crl_suffixes_.end(), hash); if (it != crl_suffixes_.end() && it->hash == hash) { it->suffix = std::max(suffix, it->suffix); return true; @@ -94,40 +98,7 @@ struct ByDir { Vector> dirs; }; -static int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, - char **ret); -static int new_dir(X509_LOOKUP *lu); -static void free_dir(X509_LOOKUP *lu); -static int add_cert_dir(ByDir *ctx, const char *dir, int type); -static int get_cert_by_subject(X509_LOOKUP *xl, int type, const X509_NAME *name, - X509_OBJECT *ret); -static const X509_LOOKUP_METHOD x509_dir_lookup = { - new_dir, // new - free_dir, // free - dir_ctrl, // ctrl - get_cert_by_subject, // get_by_subject -}; - -static int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, - char **retp) { - ByDir *ld = reinterpret_cast(ctx->method_data); - switch (cmd) { - case X509_L_ADD_DIR: - if (argl == X509_FILETYPE_DEFAULT) { - const char *dir = getenv(X509_get_default_cert_dir_env()); - if (!add_cert_dir(ld, dir ? dir : X509_get_default_cert_dir(), - X509_FILETYPE_PEM)) { - OPENSSL_PUT_ERROR(X509, X509_R_LOADING_CERT_DIR); - return 0; - } - return 1; - } - return add_cert_dir(ld, argp, (int)argl); - } - return 0; -} - -static int new_dir(X509_LOOKUP *lu) { +int new_dir(X509_LOOKUP *lu) { ByDir *a = New(); if (a == nullptr) { return 0; @@ -136,7 +107,7 @@ static int new_dir(X509_LOOKUP *lu) { return 1; } -static void free_dir(X509_LOOKUP *lu) { +void free_dir(X509_LOOKUP *lu) { Delete(reinterpret_cast(lu->method_data)); } @@ -146,7 +117,7 @@ static void free_dir(X509_LOOKUP *lu) { #define DIR_HASH_SEPARATOR ':' #endif -static int add_cert_dir(ByDir *ctx, const char *inp, int type) { +int add_cert_dir(ByDir *ctx, const char *inp, int type) { if (inp == nullptr || !*inp) { OPENSSL_PUT_ERROR(X509, X509_R_INVALID_DIRECTORY); return 0; @@ -180,8 +151,27 @@ static int add_cert_dir(ByDir *ctx, const char *inp, int type) { return 1; } -static int get_cert_by_subject(X509_LOOKUP *xl, int type, const X509_NAME *name, - X509_OBJECT *ret) { +int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, + char **retp) { + ByDir *ld = reinterpret_cast(ctx->method_data); + switch (cmd) { + case X509_L_ADD_DIR: + if (argl == X509_FILETYPE_DEFAULT) { + const char *dir = getenv(X509_get_default_cert_dir_env()); + if (!add_cert_dir(ld, dir ? dir : X509_get_default_cert_dir(), + X509_FILETYPE_PEM)) { + OPENSSL_PUT_ERROR(X509, X509_R_LOADING_CERT_DIR); + return 0; + } + return 1; + } + return add_cert_dir(ld, argp, (int)argl); + } + return 0; +} + +int get_cert_by_subject(X509_LOOKUP *xl, int type, const X509_NAME *name, + X509_OBJECT *ret) { if (name == nullptr) { return 0; } @@ -290,6 +280,15 @@ static int get_cert_by_subject(X509_LOOKUP *xl, int type, const X509_NAME *name, return 0; } +const X509_LOOKUP_METHOD x509_dir_lookup = { + new_dir, // new + free_dir, // free + dir_ctrl, // ctrl + get_cert_by_subject, // get_by_subject +}; + +} // namespace + BSSL_NAMESPACE_END const X509_LOOKUP_METHOD *X509_LOOKUP_hash_dir() { diff --git a/third_party/boringssl/src/crypto/x509/by_file.cc b/third_party/boringssl/src/crypto/x509/by_file.cc index f7d124a..39de096 100644 --- a/third_party/boringssl/src/crypto/x509/by_file.cc +++ b/third_party/boringssl/src/crypto/x509/by_file.cc @@ -20,19 +20,10 @@ #include "internal.h" -static int by_file_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc, long argl, - char **ret); -static const X509_LOOKUP_METHOD x509_file_lookup = { - nullptr, // new - nullptr, // free - by_file_ctrl, // ctrl - nullptr, // get_by_subject -}; - -const X509_LOOKUP_METHOD *X509_LOOKUP_file() { return &x509_file_lookup; } +namespace { -static int by_file_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, - char **ret) { +int by_file_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, + char **ret) { if (cmd != X509_L_FILE_LOAD) { return 0; } @@ -53,6 +44,17 @@ static int by_file_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, return 0; } +const X509_LOOKUP_METHOD x509_file_lookup = { + nullptr, // new + nullptr, // free + by_file_ctrl, // ctrl + nullptr, // get_by_subject +}; + +} // namespace + +const X509_LOOKUP_METHOD *X509_LOOKUP_file() { return &x509_file_lookup; } + int X509_load_cert_file(X509_LOOKUP *ctx, const char *file, int type) { int ret = 0; BIO *in = nullptr; diff --git a/third_party/boringssl/src/crypto/x509/internal.h b/third_party/boringssl/src/crypto/x509/internal.h index f5a76da..fb5b7d7 100644 --- a/third_party/boringssl/src/crypto/x509/internal.h +++ b/third_party/boringssl/src/crypto/x509/internal.h @@ -61,7 +61,7 @@ class X509Pubkey : public X509_pubkey_st { int x509_parse_public_key(CBS *cbs, X509_PUBKEY *out, Span algs); int x509_marshal_public_key(CBB *cbb, const X509_PUBKEY *in); -int x509_pubkey_set1(X509_PUBKEY *key, EVP_PKEY *pkey); +int x509_pubkey_set1(X509_PUBKEY *key, const EVP_PKEY *pkey); // X509_PUBKEY is an `ASN1_ITEM` whose ASN.1 type is SubjectPublicKeyInfo and C // type is `X509_PUBKEY*`. @@ -170,18 +170,18 @@ class X509Impl : public x509_st, public RefCounted { UniquePtr buf; CRYPTO_EX_DATA ex_data; // These contain copies of various extension values - long ex_pathlen = -1; - uint32_t ex_flags = 0; - uint32_t ex_kusage = 0; - uint32_t ex_xkusage = 0; - UniquePtr skid; - UniquePtr akid; - UniquePtr crldp; - UniquePtr altname; - UniquePtr nc; - unsigned char cert_hash[SHA256_DIGEST_LENGTH] = {}; + mutable long ex_pathlen = -1; + mutable uint32_t ex_flags = 0; + mutable uint32_t ex_kusage = 0; + mutable uint32_t ex_xkusage = 0; + mutable UniquePtr skid; + mutable UniquePtr akid; + mutable UniquePtr crldp; + mutable UniquePtr altname; + mutable UniquePtr nc; + mutable unsigned char cert_hash[SHA256_DIGEST_LENGTH] = {}; bssl::X509_CERT_AUX *aux = nullptr; - Mutex lock; + mutable Mutex lock; private: friend RefCounted; @@ -263,22 +263,6 @@ DECLARE_ASN1_FUNCTIONS_const(X509_CRL_INFO) BSSL_NAMESPACE_END -// Values in idp_flags field -// IDP present -#define IDP_PRESENT 0x1 -// IDP values inconsistent -#define IDP_INVALID 0x2 -// onlyuser true -#define IDP_ONLYUSER 0x4 -// onlyCA true -#define IDP_ONLYCA 0x8 -// onlyattr true -#define IDP_ONLYATTR 0x10 -// indirectCRL true -#define IDP_INDIRECT 0x20 -// onlysomereasons present -#define IDP_REASONS 0x40 - struct X509_crl_st { // actual signature bssl::X509_CRL_INFO *crl; @@ -289,8 +273,6 @@ struct X509_crl_st { // Copies of various extensions AUTHORITY_KEYID *akid; ISSUING_DIST_POINT *idp; - // Convenient breakdown of IDP - int idp_flags; unsigned char crl_hash[SHA256_DIGEST_LENGTH]; } /* X509_CRL */; @@ -416,18 +398,12 @@ struct x509_store_ctx_st { // Callbacks for various operations X509_STORE_CTX_verify_cb verify_cb; // error callback - // The following is built up - int last_untrusted; // index of last untrusted cert STACK_OF(X509) *chain; // chain of X509s - built up and trusted // When something goes wrong, this is why int error_depth; int error; X509 *current_cert; - X509_CRL *current_crl; // current CRL - - X509 *current_crl_issuer; // issuer of current CRL - int current_crl_score; // score of current CRL CRYPTO_EX_DATA ex_data; } /* X509_STORE_CTX */; @@ -446,7 +422,7 @@ int X509_CERT_AUX_print(BIO *bp, X509_CERT_AUX *x, int indent); // `NID_rsassaPss`) and key `pkey`. It returns one on success and zero on // error. int x509_rsa_pss_to_ctx(EVP_MD_CTX *ctx, const X509_ALGOR *sigalg, - EVP_PKEY *pkey); + const EVP_PKEY *pkey); // x509_rsa_pss_to_ctx sets `algor` to the signature algorithm parameters for // `ctx`, which must have been configured for an RSA-PSS signing operation. It @@ -472,26 +448,30 @@ int x509_digest_sign_algorithm(EVP_MD_CTX *ctx, X509_ALGOR *algor); // have been initialised with `EVP_MD_CTX_init`. It returns one on success, or // zero on error. int x509_digest_verify_init(EVP_MD_CTX *ctx, const X509_ALGOR *sigalg, - EVP_PKEY *pkey); + const EVP_PKEY *pkey); // x509_verify_signature verifies a `signature` using `sigalg` and `pkey` over // `in`. It returns one if the signature is valid and zero on error. int x509_verify_signature(const X509_ALGOR *sigalg, const ASN1_BIT_STRING *signature, - Span in, EVP_PKEY *pkey); + Span in, const EVP_PKEY *pkey); // x509_verify_signature_bytes behaves like `x509_verify_signature` but takes in // a span containing the signature bytes (without ASN.1 headers). It returns one // if the signature is valid and zero on error. int x509_verify_signature_bytes(const X509_ALGOR *sigalg, Span signature, - Span in, EVP_PKEY *pkey); + Span in, const EVP_PKEY *pkey); // x509_sign_to_bit_string signs `in` using `ctx` and saves the result in `out`. // It returns the length of the signature on success and zero on error. int x509_sign_to_bit_string(EVP_MD_CTX *ctx, ASN1_BIT_STRING *out, Span in); +// x509_sig_nid_allowed returns whether a signature algorithm with NID `sig_nid` +// may be used for a certificate verification with `ctx`. +bool x509_sig_nid_allowed(const X509_STORE_CTX *ctx, int sig_nid); + // Path-building functions. @@ -499,12 +479,11 @@ int x509_sign_to_bit_string(EVP_MD_CTX *ctx, ASN1_BIT_STRING *out, // the user-initial-policy-set. If `user_policies` is NULL or empty, it is // interpreted as anyPolicy. `flags` is a set of `X509_V_FLAG_*` values to // apply. It returns `X509_V_OK` on success and `X509_V_ERR_*` on error. It -// additionally sets `*out_current_cert` to the certificate where the error -// occurred. If the function succeeded, or the error applies to the entire -// chain, it sets `*out_current_cert` to NULL. +// additionally sets `*out_error_depth` to the index of certificate where the +// error occurred. int X509_policy_check(const STACK_OF(X509) *certs, const STACK_OF(ASN1_OBJECT) *user_policies, - unsigned long flags, X509 **out_current_cert); + unsigned long flags, int *out_error_depth); // x509_check_issued_with_callback calls `X509_check_issued`, but allows the // verify callback to override the result. It returns one on success and zero on @@ -545,7 +524,7 @@ OPENSSL_EXPORT int x509v3_looks_like_dns_name(const unsigned char *in, // x509v3_cache_extensions fills in a number of fields relating to X.509 // extensions in `x`. It returns one on success and zero if some extensions were // invalid. -OPENSSL_EXPORT int x509v3_cache_extensions(X509 *x); +OPENSSL_EXPORT int x509v3_cache_extensions(const X509 *x); // x509v3_a2i_ipadd decodes `ipasc` as an IPv4 or IPv6 address. IPv6 addresses // use colon-separated syntax while IPv4 addresses use dotted decimal syntax. If @@ -622,13 +601,13 @@ STACK_OF(CONF_VALUE) *X509V3_parse_list(const char *line); ERR_add_error_data(6, "section:", (val)->section, ",name:", (val)->name, \ ",value:", (val)->value); -// GENERAL_NAME_cmp returns zero if `a` and `b` are equal and a non-zero -// value otherwise. Note this function does not provide a comparison suitable -// for sorting. -// -// This function is exported for testing. -OPENSSL_EXPORT int GENERAL_NAME_cmp(const GENERAL_NAME *a, - const GENERAL_NAME *b); +// GENERAL_NAME_cmp compares `a` and `b`. It returns zero if they are equal, and +// a negative or positive value if `a` sorts before or after `b`, respectively. +// Names are ordered first by type, then by type-specific contents. The order +// is arbitrary but suitable for sorting, with one exception: if a directoryName +// cannot be serialized, `X509_NAME_cmp`, and thus this function, returns -2. +// This cannot happen for parsed names that have not since been modified. +int GENERAL_NAME_cmp(const GENERAL_NAME *a, const GENERAL_NAME *b); // X509_VERIFY_PARAM_lookup returns a pre-defined `X509_VERIFY_PARAM` named by // `name`, or NULL if no such name is defined. @@ -650,9 +629,6 @@ int X509_is_valid_trust_id(int trust); int X509_PURPOSE_get_trust(const X509_PURPOSE *xp); -// TODO(https://crbug.com/boringssl/695): Remove this. -int DIST_POINT_set_dpname(DIST_POINT_NAME *dpn, X509_NAME *iname); - // x509_parse_name parses a DER-encoded, X.509 Name from `cbs` and writes the // result to `*out`. It returns one on success and zero on error. int x509_parse_name(CBS *cbs, X509_NAME *out); @@ -670,7 +646,7 @@ int x509_name_copy(X509_NAME *dst, const X509_NAME *src); // Merkle Tree Certificate (MTC) verification functions. // x509_is_merkle_tree_ca returns whether `x509` contains an extension of type -// id-pe-mtcCertificationAuthority. +// id-pe-mtcCertificationAuthority-SHA256. bool x509_is_merkle_tree_ca(const X509 *x509); // x509_evaluate_mtc_subtree_inclusion_proof carries out the procedure in @@ -690,11 +666,12 @@ bool x509_evaluate_mtc_subtree_inclusion_proof( uint64_t subtree_end); // x509_verify_mtc verifies `x509` as a Merkle Tree Certificate issued by -// `issuer`, which must be an MTC CA represented in X.509 format. `pkey` is the -// `issuer`'s public key. It returns one if the MTC is valid, or zero on error. -// This function only checks the MTC proof itself and does not perform a full -// certificate validation. -int x509_verify_mtc(const X509 *x509, const EVP_PKEY *pkey, const X509 *issuer); +// `issuer`, which must be an MTC CA represented in X.509 format, as part of a +// verification operation for `ctx`. `pkey` is the `issuer`'s public key. It +// returns one if the MTC is valid, or zero on error. This function only checks +// the MTC proof itself and does not perform a full certificate validation. +int x509_verify_mtc(const X509_STORE_CTX *ctx, const X509 *x509, + const EVP_PKEY *pkey, const X509 *issuer); // Standard extensions. diff --git a/third_party/boringssl/src/crypto/x509/name_print.cc b/third_party/boringssl/src/crypto/x509/name_print.cc index 568b474..ffe7dc1 100644 --- a/third_party/boringssl/src/crypto/x509/name_print.cc +++ b/third_party/boringssl/src/crypto/x509/name_print.cc @@ -23,13 +23,15 @@ #include -static int maybe_write(BIO *out, const void *buf, int len) { +namespace { + +int maybe_write(BIO *out, const void *buf, int len) { // If `out` is NULL, ignore the output but report the length. return out == nullptr || BIO_write(out, buf, len) == len; } // do_indent prints `indent` spaces to `out`. -static int do_indent(BIO *out, int indent) { +int do_indent(BIO *out, int indent) { for (int i = 0; i < indent; i++) { if (!maybe_write(out, " ", 1)) { return 0; @@ -41,8 +43,7 @@ static int do_indent(BIO *out, int indent) { #define FN_WIDTH_LN 25 #define FN_WIDTH_SN 10 -static int do_name_ex(BIO *out, const X509_NAME *n, int indent, - unsigned long flags) { +int do_name_ex(BIO *out, const X509_NAME *n, int indent, unsigned long flags) { int prev = -1, orflags; int outlen, len; const char *sep_dn, *sep_mv, *sep_eq; @@ -162,6 +163,8 @@ static int do_name_ex(BIO *out, const X509_NAME *n, int indent, return outlen; } +} // namespace + int X509_NAME_print_ex(BIO *out, const X509_NAME *nm, int indent, unsigned long flags) { if (flags == XN_FLAG_COMPAT) { diff --git a/third_party/boringssl/src/crypto/x509/policy.cc b/third_party/boringssl/src/crypto/x509/policy.cc index b2c5fba..f4488b6 100644 --- a/third_party/boringssl/src/crypto/x509/policy.cc +++ b/third_party/boringssl/src/crypto/x509/policy.cc @@ -178,7 +178,8 @@ int policyinfo_cmp(const POLICYINFO *const *a, const POLICYINFO *const *b) { // whether anyPolicy is allowed or inhibited, taking into account the exception // for self-issued certificates. bool process_certificate_policies(const X509 *x509, X509PolicyLevel *level, - int any_policy_allowed) { + bool any_policy_allowed, + bool is_trust_anchor) { int critical; UniquePtr policies( reinterpret_cast(X509_get_ext_d2i( @@ -189,7 +190,20 @@ bool process_certificate_policies(const X509 *x509, X509PolicyLevel *level, } // RFC 5280, section 6.1.3, step (e). - level->Clear(); + // + // We skip this step for the trust anchor. Lack of certificatePolicies on + // the trust anchor is treated as anyPolicy rather than no policy. This is + // neither supported nor contradicted by RFC 5280, which does not consider + // the trust anchor to be path of the certification path. However, RFC 5937 + // considers this case to not constrain the path, so we align with that. + // + // Additionally, practically speaking, if we applied RFC 5280's intermediate + // processing to trust anchors here, we would likely break some + // applications. certificatePolicies is the only case where a missing + // extension applies a constraint instead of leaving things unconstrained. + if (!is_trust_anchor) { + level->Clear(); + } return true; } @@ -571,56 +585,73 @@ int asn1_object_cmp(const ASN1_OBJECT *const *a, const ASN1_OBJECT *const *b) { int X509_policy_check(const STACK_OF(X509) *certs, const STACK_OF(ASN1_OBJECT) *user_policies, - unsigned long flags, X509 **out_current_cert) { - *out_current_cert = nullptr; + unsigned long flags, int *out_error_depth) { + *out_error_depth = 0; - // Skip policy checking if the chain is just the trust anchor. + // See RFC 5280, section 6.1.2, steps (d) through (f). Note that `n` in RFC + // 5280 is `num_certs - 1` because RFC 5280 paths do not include the trust + // anchor. However, we use `num_certs + 1`, not `num_certs` because, unlike + // RFC 5280, we include an extra loop iteration for the trust anchor. const size_t num_certs = sk_X509_num(certs); - if (num_certs <= 1) { - return X509_V_OK; - } - - // See RFC 5280, section 6.1.2, steps (d) through (f). size_t explicit_policy = (flags & X509_V_FLAG_EXPLICIT_POLICY) ? 0 : num_certs + 1; size_t inhibit_any_policy = (flags & X509_V_FLAG_INHIBIT_ANY) ? 0 : num_certs + 1; size_t policy_mapping = (flags & X509_V_FLAG_INHIBIT_MAP) ? 0 : num_certs + 1; + // Start at `num_certs - 1`, i.e. including the trust anchor. This applies + // constraints from the trust anchor, analogously to RFC 5937, but we + // implement it with intermediate processing. This differs from RFC 5937: + // + // 1. RFC 5937 specifies no handling for policyMappings in the trust anchor. + // We apply them, rather than silently ignore them. + // + // 2. RFC 5937 applies certificatePolicies to user-initial-policy-set. This + // gives subtly different semantics from chain processing. See + // https://crbug.com/1403258. + // + // 3. RFC 5937 ignores the numerical value of policyConstraints and + // inhibitAnyPolicy, treating their presence as a boolean. We apply them in + // full. Vector levels; std::optional level; - for (size_t i = num_certs - 2; i < num_certs; i--) { + for (size_t i = num_certs - 1; i < num_certs; i--) { X509 *cert = sk_X509_value(certs, i); uint32_t ex_flags = X509_get_extension_flags(cert); if (ex_flags & EXFLAG_INVALID) { + *out_error_depth = static_cast(i); return X509_V_ERR_OUT_OF_MEM; } const bool is_self_issued = (ex_flags & EXFLAG_SI) != 0; + const bool is_trust_anchor = i == num_certs - 1; // In all but the first iteration, the previous iteration will have prepared // "expected_policy_set" for us as a staging level. if (!level.has_value()) { - assert(i == num_certs - 2); + assert(is_trust_anchor); level.emplace(); level->set_has_any_policy(true); } // RFC 5280, section 6.1.3, steps (d) and (e). `any_policy_allowed` is // computed as in step (d.2). - const int any_policy_allowed = + const bool any_policy_allowed = inhibit_any_policy > 0 || (i > 0 && is_self_issued); - if (!process_certificate_policies(cert, &*level, any_policy_allowed)) { - *out_current_cert = cert; + if (!process_certificate_policies(cert, &*level, any_policy_allowed, + is_trust_anchor)) { + *out_error_depth = static_cast(i); return X509_V_ERR_INVALID_POLICY_EXTENSION; } // RFC 5280, section 6.1.3, step (f). if (explicit_policy == 0 && level->is_empty()) { + *out_error_depth = static_cast(i); return X509_V_ERR_NO_EXPLICIT_POLICY; } // Insert the completed level into the list. if (!levels.Push(*std::exchange(level, std::nullopt))) { + *out_error_depth = static_cast(i); return X509_V_ERR_OUT_OF_MEM; } level = std::nullopt; @@ -631,7 +662,7 @@ int X509_policy_check(const STACK_OF(X509) *certs, // RFC 5280, section 6.1.4, steps (a) and (b). level = process_policy_mappings(cert, &levels.back(), policy_mapping > 0); if (!level.has_value()) { - *out_current_cert = cert; + *out_error_depth = static_cast(i); return X509_V_ERR_INVALID_POLICY_EXTENSION; } } @@ -653,7 +684,7 @@ int X509_policy_check(const STACK_OF(X509) *certs, } if (!process_policy_constraints(cert, &explicit_policy, &policy_mapping, &inhibit_any_policy)) { - *out_current_cert = cert; + *out_error_depth = static_cast(i); return X509_V_ERR_INVALID_POLICY_EXTENSION; } } diff --git a/third_party/boringssl/src/crypto/x509/rsa_pss.cc b/third_party/boringssl/src/crypto/x509/rsa_pss.cc index 352e3a9..3a0ebeb 100644 --- a/third_party/boringssl/src/crypto/x509/rsa_pss.cc +++ b/third_party/boringssl/src/crypto/x509/rsa_pss.cc @@ -32,8 +32,10 @@ using namespace bssl; -static int rsa_pss_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, - void *exarg) { +namespace { + +int rsa_pss_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, + void *exarg) { if (operation == ASN1_OP_FREE_PRE) { RSA_PSS_PARAMS *pss = asn1_load_ptr_as(pval); X509_ALGOR_free(pss->maskHash); @@ -41,17 +43,7 @@ static int rsa_pss_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, return 1; } -ASN1_SEQUENCE_cb(RSA_PSS_PARAMS, rsa_pss_cb) = { - ASN1_EXP_OPT(RSA_PSS_PARAMS, hashAlgorithm, X509_ALGOR, 0), - ASN1_EXP_OPT(RSA_PSS_PARAMS, maskGenAlgorithm, X509_ALGOR, 1), - ASN1_EXP_OPT(RSA_PSS_PARAMS, saltLength, ASN1_INTEGER, 2), - ASN1_EXP_OPT(RSA_PSS_PARAMS, trailerField, ASN1_INTEGER, 3), -} ASN1_SEQUENCE_END_cb(RSA_PSS_PARAMS, RSA_PSS_PARAMS) - -IMPLEMENT_ASN1_FUNCTIONS_const(RSA_PSS_PARAMS) - - -static int rsa_pss_decode(const X509_ALGOR *alg, rsa_pss_params_t *out) { +int rsa_pss_decode(const X509_ALGOR *alg, rsa_pss_params_t *out) { if (alg->parameter == nullptr || alg->parameter->type != V_ASN1_SEQUENCE) { return 0; } @@ -65,6 +57,17 @@ static int rsa_pss_decode(const X509_ALGOR *alg, rsa_pss_params_t *out) { CBS_len(&cbs) == 0; } +} // namespace + +ASN1_SEQUENCE_cb(RSA_PSS_PARAMS, rsa_pss_cb) = { + ASN1_EXP_OPT(RSA_PSS_PARAMS, hashAlgorithm, X509_ALGOR, 0), + ASN1_EXP_OPT(RSA_PSS_PARAMS, maskGenAlgorithm, X509_ALGOR, 1), + ASN1_EXP_OPT(RSA_PSS_PARAMS, saltLength, ASN1_INTEGER, 2), + ASN1_EXP_OPT(RSA_PSS_PARAMS, trailerField, ASN1_INTEGER, 3), +} ASN1_SEQUENCE_END_cb(RSA_PSS_PARAMS, RSA_PSS_PARAMS) + +IMPLEMENT_ASN1_FUNCTIONS_const(RSA_PSS_PARAMS) + int bssl::x509_rsa_ctx_to_pss(EVP_MD_CTX *ctx, X509_ALGOR *algor) { const EVP_MD *sigmd, *mgf1md; int saltlen; @@ -122,7 +125,7 @@ int bssl::x509_rsa_ctx_to_pss(EVP_MD_CTX *ctx, X509_ALGOR *algor) { } int bssl::x509_rsa_pss_to_ctx(EVP_MD_CTX *ctx, const X509_ALGOR *sigalg, - EVP_PKEY *pkey) { + const EVP_PKEY *pkey) { assert(OBJ_obj2nid(sigalg->algorithm) == NID_rsassaPss); rsa_pss_params_t params; if (!rsa_pss_decode(sigalg, ¶ms)) { diff --git a/third_party/boringssl/src/crypto/x509/v3_akey.cc b/third_party/boringssl/src/crypto/x509/v3_akey.cc index 1b9ef88..2c82870 100644 --- a/third_party/boringssl/src/crypto/x509/v3_akey.cc +++ b/third_party/boringssl/src/crypto/x509/v3_akey.cc @@ -28,31 +28,11 @@ using namespace bssl; -static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID( - const X509V3_EXT_METHOD *method, void *ext, STACK_OF(CONF_VALUE) *extlist); -static void *v2i_AUTHORITY_KEYID(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *values); +namespace { -const X509V3_EXT_METHOD bssl::v3_akey_id = { - NID_authority_key_identifier, - X509V3_EXT_MULTILINE, - ASN1_ITEM_ref(AUTHORITY_KEYID), - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - i2v_AUTHORITY_KEYID, - v2i_AUTHORITY_KEYID, - nullptr, - nullptr, - nullptr, -}; - -static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID( - const X509V3_EXT_METHOD *method, void *ext, STACK_OF(CONF_VALUE) *extlist) { +STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID(const X509V3_EXT_METHOD *method, + void *ext, + STACK_OF(CONF_VALUE) *extlist) { const AUTHORITY_KEYID *akeyid = reinterpret_cast(ext); int extlist_was_null = extlist == nullptr; @@ -94,9 +74,9 @@ static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID( // - issuer: Use the issuer's issuer and serial number. The default is to only // use this if the key ID is not present. The value 'always' means it's always // included. -static void *v2i_AUTHORITY_KEYID(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *values) { +void *v2i_AUTHORITY_KEYID(const X509V3_EXT_METHOD *method, + const X509V3_CTX *ctx, + const STACK_OF(CONF_VALUE) *values) { enum Option { kOff = 0, kOn = 1, kAlways = 2 }; Option use_key_id = kOff, use_issuer = kOff; for (const CONF_VALUE *cnf : values) { @@ -172,3 +152,22 @@ static void *v2i_AUTHORITY_KEYID(const X509V3_EXT_METHOD *method, akid->keyid = key_id.release(); return akid.release(); } + +} // namespace + +const X509V3_EXT_METHOD bssl::v3_akey_id = { + NID_authority_key_identifier, + X509V3_EXT_MULTILINE, + ASN1_ITEM_ref(AUTHORITY_KEYID), + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + i2v_AUTHORITY_KEYID, + v2i_AUTHORITY_KEYID, + nullptr, + nullptr, + nullptr, +}; diff --git a/third_party/boringssl/src/crypto/x509/v3_alt.cc b/third_party/boringssl/src/crypto/x509/v3_alt.cc index e64d323..ffc2177 100644 --- a/third_party/boringssl/src/crypto/x509/v3_alt.cc +++ b/third_party/boringssl/src/crypto/x509/v3_alt.cc @@ -27,24 +27,315 @@ using namespace bssl; -static void *v2i_subject_alt(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval); -static void *v2i_issuer_alt(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval); -static int copy_email(const X509V3_CTX *ctx, GENERAL_NAMES *gens, int move_p); -static int copy_issuer(const X509V3_CTX *ctx, GENERAL_NAMES *gens); -static int do_othername(GENERAL_NAME *gen, const char *value, - const X509V3_CTX *ctx); -static int do_dirname(GENERAL_NAME *gen, const char *value, - const X509V3_CTX *ctx); - -static STACK_OF(CONF_VALUE) *i2v_GENERAL_NAMES_cb( - const X509V3_EXT_METHOD *method, void *ext, STACK_OF(CONF_VALUE) *ret) { +namespace { + +STACK_OF(CONF_VALUE) *i2v_GENERAL_NAMES_cb(const X509V3_EXT_METHOD *method, + void *ext, + STACK_OF(CONF_VALUE) *ret) { return i2v_GENERAL_NAMES(method, reinterpret_cast(ext), ret); } +// Append subject altname of issuer to issuer alt name of subject +int copy_issuer(const X509V3_CTX *ctx, GENERAL_NAMES *gens) { + if (ctx && (ctx->flags == X509V3_CTX_TEST)) { + return 1; + } + if (!ctx || !ctx->issuer_cert) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_NO_ISSUER_DETAILS); + return 0; + } + int i = X509_get_ext_by_NID(ctx->issuer_cert, NID_subject_alt_name, -1); + if (i < 0) { + return 1; + } + + int ret = 0; + GENERAL_NAMES *ialt = nullptr; + X509_EXTENSION *ext; + if (!(ext = X509_get_ext(ctx->issuer_cert, i)) || + !(ialt = reinterpret_cast(X509V3_EXT_d2i(ext)))) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_ISSUER_DECODE_ERROR); + goto err; + } + + for (size_t j = 0; j < sk_GENERAL_NAME_num(ialt); j++) { + GENERAL_NAME *gen = sk_GENERAL_NAME_value(ialt, j); + if (!sk_GENERAL_NAME_push(gens, gen)) { + goto err; + } + // Ownership of `gen` has moved from `ialt` to `gens`. + sk_GENERAL_NAME_set(ialt, j, nullptr); + } + + ret = 1; + +err: + GENERAL_NAMES_free(ialt); + return ret; +} + +void *v2i_issuer_alt(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, + const STACK_OF(CONF_VALUE) *nval) { + GENERAL_NAMES *gens = sk_GENERAL_NAME_new_null(); + if (gens == nullptr) { + return nullptr; + } + for (size_t i = 0; i < sk_CONF_VALUE_num(nval); i++) { + const CONF_VALUE *cnf = sk_CONF_VALUE_value(nval, i); + if (x509v3_conf_name_matches(cnf->name, "issuer") && cnf->value && + !strcmp(cnf->value, "copy")) { + if (!copy_issuer(ctx, gens)) { + goto err; + } + } else { + GENERAL_NAME *gen = v2i_GENERAL_NAME(method, ctx, cnf); + if (gen == nullptr || !sk_GENERAL_NAME_push(gens, gen)) { + GENERAL_NAME_free(gen); + goto err; + } + } + } + return gens; +err: + sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free); + return nullptr; +} + +// Copy any email addresses in a certificate or request to GENERAL_NAMES +int copy_email(const X509V3_CTX *ctx, GENERAL_NAMES *gens, int move_p) { + X509_NAME *nm; + ASN1_IA5STRING *email = nullptr; + X509_NAME_ENTRY *ne; + GENERAL_NAME *gen = nullptr; + int i; + if (ctx != nullptr && ctx->flags == X509V3_CTX_TEST) { + return 1; + } + if (!ctx || (!ctx->subject_cert && !ctx->subject_req)) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_NO_SUBJECT_DETAILS); + goto err; + } + // Find the subject name + if (ctx->subject_cert) { + nm = X509_get_subject_name(ctx->subject_cert); + } else { + nm = X509_REQ_get_subject_name(ctx->subject_req); + } + + // Now add any email address(es) to STACK + i = -1; + while ((i = X509_NAME_get_index_by_NID(nm, NID_pkcs9_emailAddress, i)) >= 0) { + ne = X509_NAME_get_entry(nm, i); + email = ASN1_STRING_dup(X509_NAME_ENTRY_get_data(ne)); + if (move_p) { + X509_NAME_delete_entry(nm, i); + X509_NAME_ENTRY_free(ne); + i--; + } + if (!email || !(gen = GENERAL_NAME_new())) { + goto err; + } + gen->d.ia5 = email; + email = nullptr; + gen->type = GEN_EMAIL; + if (!sk_GENERAL_NAME_push(gens, gen)) { + goto err; + } + gen = nullptr; + } + + return 1; + +err: + GENERAL_NAME_free(gen); + ASN1_IA5STRING_free(email); + return 0; +} + +void *v2i_subject_alt(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, + const STACK_OF(CONF_VALUE) *nval) { + GENERAL_NAMES *gens = sk_GENERAL_NAME_new_null(); + if (gens == nullptr) { + return nullptr; + } + for (size_t i = 0; i < sk_CONF_VALUE_num(nval); i++) { + const CONF_VALUE *cnf = sk_CONF_VALUE_value(nval, i); + if (x509v3_conf_name_matches(cnf->name, "email") && cnf->value && + !strcmp(cnf->value, "copy")) { + if (!copy_email(ctx, gens, 0)) { + goto err; + } + } else if (x509v3_conf_name_matches(cnf->name, "email") && cnf->value && + !strcmp(cnf->value, "move")) { + if (!copy_email(ctx, gens, 1)) { + goto err; + } + } else { + GENERAL_NAME *gen = v2i_GENERAL_NAME(method, ctx, cnf); + if (gen == nullptr || !sk_GENERAL_NAME_push(gens, gen)) { + GENERAL_NAME_free(gen); + goto err; + } + } + } + return gens; +err: + sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free); + return nullptr; +} + +int do_othername(GENERAL_NAME *gen, const char *value, const X509V3_CTX *ctx) { + const char *semicolon = strchr(value, ';'); + if (semicolon == nullptr) { + return 0; + } + + OTHERNAME *name = OTHERNAME_new(); + if (name == nullptr) { + return 0; + } + + char *objtmp = OPENSSL_strndup(value, semicolon - value); + if (objtmp == nullptr) { + goto err; + } + ASN1_OBJECT_free(name->type_id); + name->type_id = OBJ_txt2obj(objtmp, /*dont_search_names=*/0); + OPENSSL_free(objtmp); + if (name->type_id == nullptr) { + goto err; + } + + ASN1_TYPE_free(name->value); + name->value = ASN1_generate_v3(semicolon + 1, ctx); + if (name->value == nullptr) { + goto err; + } + + gen->type = GEN_OTHERNAME; + gen->d.otherName = name; + return 1; + +err: + OTHERNAME_free(name); + return 0; +} + +int do_dirname(GENERAL_NAME *gen, const char *value, const X509V3_CTX *ctx) { + int ret = 0; + const STACK_OF(CONF_VALUE) *sk = X509V3_get_section(ctx, value); + X509_NAME *nm = X509_NAME_new(); + if (nm == nullptr) { + goto err; + } + if (sk == nullptr) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_SECTION_NOT_FOUND); + ERR_add_error_data(2, "section=", value); + goto err; + } + // FIXME: should allow other character types... + if (!X509V3_NAME_from_section(nm, sk, MBSTRING_ASC)) { + goto err; + } + gen->type = GEN_DIRNAME; + gen->d.dirn = nm; + ret = 1; + +err: + if (!ret) { + X509_NAME_free(nm); + } + return ret; +} + +GENERAL_NAME *a2i_GENERAL_NAME(GENERAL_NAME *out, + const X509V3_EXT_METHOD *method, + const X509V3_CTX *ctx, int gen_type, + const char *value, int is_nc) { + if (!value) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_MISSING_VALUE); + return nullptr; + } + + GENERAL_NAME *gen = nullptr; + if (out) { + gen = out; + } else { + gen = GENERAL_NAME_new(); + if (gen == nullptr) { + return nullptr; + } + } + + switch (gen_type) { + case GEN_URI: + case GEN_EMAIL: + case GEN_DNS: { + ASN1_IA5STRING *str = ASN1_IA5STRING_new(); + if (str == nullptr || !ASN1_STRING_set(str, value, strlen(value))) { + ASN1_STRING_free(str); + goto err; + } + gen->type = gen_type; + gen->d.ia5 = str; + break; + } + + case GEN_RID: { + ASN1_OBJECT *obj; + if (!(obj = OBJ_txt2obj(value, 0))) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_BAD_OBJECT); + ERR_add_error_data(2, "value=", value); + goto err; + } + gen->type = GEN_RID; + gen->d.rid = obj; + break; + } + + case GEN_IPADD: + gen->type = GEN_IPADD; + if (is_nc) { + gen->d.ip = a2i_IPADDRESS_NC(value); + } else { + gen->d.ip = a2i_IPADDRESS(value); + } + if (gen->d.ip == nullptr) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_BAD_IP_ADDRESS); + ERR_add_error_data(2, "value=", value); + goto err; + } + break; + + case GEN_DIRNAME: + if (!do_dirname(gen, value, ctx)) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_DIRNAME_ERROR); + goto err; + } + break; + + case GEN_OTHERNAME: + if (!do_othername(gen, value, ctx)) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_OTHERNAME_ERROR); + goto err; + } + break; + default: + OPENSSL_PUT_ERROR(X509V3, X509V3_R_UNSUPPORTED_TYPE); + goto err; + } + + return gen; + +err: + if (!out) { + GENERAL_NAME_free(gen); + } + return nullptr; +} + +} // namespace + const X509V3_EXT_METHOD bssl::v3_subject_alt_name = { NID_subject_alt_name, 0, @@ -194,231 +485,78 @@ STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(const X509V3_EXT_METHOD *method, if (!X509V3_add_value("IP Address", oline, &ret)) { return nullptr; } - break; - - case GEN_RID: - i2t_ASN1_OBJECT(oline, 256, gen->d.rid); - if (!X509V3_add_value("Registered ID", oline, &ret)) { - return nullptr; - } - break; - } - return ret; -} - -int GENERAL_NAME_print(BIO *out, const GENERAL_NAME *gen) { - switch (gen->type) { - case GEN_OTHERNAME: - BIO_printf(out, "othername:"); - break; - - case GEN_X400: - BIO_printf(out, "X400Name:"); - break; - - case GEN_EDIPARTY: - // Maybe fix this: it is supported now - BIO_printf(out, "EdiPartyName:"); - break; - - case GEN_EMAIL: - BIO_printf(out, "email:"); - ASN1_STRING_print(out, gen->d.ia5); - break; - - case GEN_DNS: - BIO_printf(out, "DNS:"); - ASN1_STRING_print(out, gen->d.ia5); - break; - - case GEN_URI: - BIO_printf(out, "URI:"); - ASN1_STRING_print(out, gen->d.ia5); - break; - - case GEN_DIRNAME: - BIO_printf(out, "DirName: "); - X509_NAME_print_ex(out, gen->d.dirn, 0, XN_FLAG_ONELINE); - break; - - case GEN_IPADD: { - const unsigned char *p = gen->d.ip->data; - if (gen->d.ip->length == 4) { - BIO_printf(out, "IP Address:%d.%d.%d.%d", p[0], p[1], p[2], p[3]); - } else if (gen->d.ip->length == 16) { - BIO_printf(out, "IP Address"); - for (int i = 0; i < 8; i++) { - uint16_t v = ((uint16_t)p[0] << 8) | p[1]; - BIO_printf(out, ":%X", v); - p += 2; - } - BIO_puts(out, "\n"); - } else { - BIO_printf(out, "IP Address:"); - break; - } - break; - } - - case GEN_RID: - BIO_printf(out, "Registered ID"); - i2a_ASN1_OBJECT(out, gen->d.rid); - break; - } - return 1; -} - -static void *v2i_issuer_alt(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval) { - GENERAL_NAMES *gens = sk_GENERAL_NAME_new_null(); - if (gens == nullptr) { - return nullptr; - } - for (size_t i = 0; i < sk_CONF_VALUE_num(nval); i++) { - const CONF_VALUE *cnf = sk_CONF_VALUE_value(nval, i); - if (x509v3_conf_name_matches(cnf->name, "issuer") && cnf->value && - !strcmp(cnf->value, "copy")) { - if (!copy_issuer(ctx, gens)) { - goto err; - } - } else { - GENERAL_NAME *gen = v2i_GENERAL_NAME(method, ctx, cnf); - if (gen == nullptr || !sk_GENERAL_NAME_push(gens, gen)) { - GENERAL_NAME_free(gen); - goto err; - } - } - } - return gens; -err: - sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free); - return nullptr; -} - -// Append subject altname of issuer to issuer alt name of subject - -static int copy_issuer(const X509V3_CTX *ctx, GENERAL_NAMES *gens) { - if (ctx && (ctx->flags == X509V3_CTX_TEST)) { - return 1; - } - if (!ctx || !ctx->issuer_cert) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_NO_ISSUER_DETAILS); - return 0; - } - int i = X509_get_ext_by_NID(ctx->issuer_cert, NID_subject_alt_name, -1); - if (i < 0) { - return 1; - } - - int ret = 0; - GENERAL_NAMES *ialt = nullptr; - X509_EXTENSION *ext; - if (!(ext = X509_get_ext(ctx->issuer_cert, i)) || - !(ialt = reinterpret_cast(X509V3_EXT_d2i(ext)))) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_ISSUER_DECODE_ERROR); - goto err; - } - - for (size_t j = 0; j < sk_GENERAL_NAME_num(ialt); j++) { - GENERAL_NAME *gen = sk_GENERAL_NAME_value(ialt, j); - if (!sk_GENERAL_NAME_push(gens, gen)) { - goto err; - } - // Ownership of `gen` has moved from `ialt` to `gens`. - sk_GENERAL_NAME_set(ialt, j, nullptr); - } - - ret = 1; - -err: - GENERAL_NAMES_free(ialt); - return ret; -} - -static void *v2i_subject_alt(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval) { - GENERAL_NAMES *gens = sk_GENERAL_NAME_new_null(); - if (gens == nullptr) { - return nullptr; - } - for (size_t i = 0; i < sk_CONF_VALUE_num(nval); i++) { - const CONF_VALUE *cnf = sk_CONF_VALUE_value(nval, i); - if (x509v3_conf_name_matches(cnf->name, "email") && cnf->value && - !strcmp(cnf->value, "copy")) { - if (!copy_email(ctx, gens, 0)) { - goto err; - } - } else if (x509v3_conf_name_matches(cnf->name, "email") && cnf->value && - !strcmp(cnf->value, "move")) { - if (!copy_email(ctx, gens, 1)) { - goto err; - } - } else { - GENERAL_NAME *gen = v2i_GENERAL_NAME(method, ctx, cnf); - if (gen == nullptr || !sk_GENERAL_NAME_push(gens, gen)) { - GENERAL_NAME_free(gen); - goto err; + break; + + case GEN_RID: + i2t_ASN1_OBJECT(oline, 256, gen->d.rid); + if (!X509V3_add_value("Registered ID", oline, &ret)) { + return nullptr; } - } + break; } - return gens; -err: - sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free); - return nullptr; + return ret; } -// Copy any email addresses in a certificate or request to GENERAL_NAMES +int GENERAL_NAME_print(BIO *out, const GENERAL_NAME *gen) { + switch (gen->type) { + case GEN_OTHERNAME: + BIO_printf(out, "othername:"); + break; -static int copy_email(const X509V3_CTX *ctx, GENERAL_NAMES *gens, int move_p) { - X509_NAME *nm; - ASN1_IA5STRING *email = nullptr; - X509_NAME_ENTRY *ne; - GENERAL_NAME *gen = nullptr; - int i; - if (ctx != nullptr && ctx->flags == X509V3_CTX_TEST) { - return 1; - } - if (!ctx || (!ctx->subject_cert && !ctx->subject_req)) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_NO_SUBJECT_DETAILS); - goto err; - } - // Find the subject name - if (ctx->subject_cert) { - nm = X509_get_subject_name(ctx->subject_cert); - } else { - nm = X509_REQ_get_subject_name(ctx->subject_req); - } + case GEN_X400: + BIO_printf(out, "X400Name:"); + break; - // Now add any email address(es) to STACK - i = -1; - while ((i = X509_NAME_get_index_by_NID(nm, NID_pkcs9_emailAddress, i)) >= 0) { - ne = X509_NAME_get_entry(nm, i); - email = ASN1_STRING_dup(X509_NAME_ENTRY_get_data(ne)); - if (move_p) { - X509_NAME_delete_entry(nm, i); - X509_NAME_ENTRY_free(ne); - i--; - } - if (!email || !(gen = GENERAL_NAME_new())) { - goto err; - } - gen->d.ia5 = email; - email = nullptr; - gen->type = GEN_EMAIL; - if (!sk_GENERAL_NAME_push(gens, gen)) { - goto err; + case GEN_EDIPARTY: + // Maybe fix this: it is supported now + BIO_printf(out, "EdiPartyName:"); + break; + + case GEN_EMAIL: + BIO_printf(out, "email:"); + ASN1_STRING_print(out, gen->d.ia5); + break; + + case GEN_DNS: + BIO_printf(out, "DNS:"); + ASN1_STRING_print(out, gen->d.ia5); + break; + + case GEN_URI: + BIO_printf(out, "URI:"); + ASN1_STRING_print(out, gen->d.ia5); + break; + + case GEN_DIRNAME: + BIO_printf(out, "DirName: "); + X509_NAME_print_ex(out, gen->d.dirn, 0, XN_FLAG_ONELINE); + break; + + case GEN_IPADD: { + const unsigned char *p = gen->d.ip->data; + if (gen->d.ip->length == 4) { + BIO_printf(out, "IP Address:%d.%d.%d.%d", p[0], p[1], p[2], p[3]); + } else if (gen->d.ip->length == 16) { + BIO_printf(out, "IP Address"); + for (int i = 0; i < 8; i++) { + uint16_t v = ((uint16_t)p[0] << 8) | p[1]; + BIO_printf(out, ":%X", v); + p += 2; + } + BIO_puts(out, "\n"); + } else { + BIO_printf(out, "IP Address:"); + break; + } + break; } - gen = nullptr; - } + case GEN_RID: + BIO_printf(out, "Registered ID"); + i2a_ASN1_OBJECT(out, gen->d.rid); + break; + } return 1; - -err: - GENERAL_NAME_free(gen); - ASN1_IA5STRING_free(email); - return 0; } GENERAL_NAMES *bssl::v2i_GENERAL_NAMES(const X509V3_EXT_METHOD *method, @@ -448,92 +586,6 @@ GENERAL_NAME *bssl::v2i_GENERAL_NAME(const X509V3_EXT_METHOD *method, return v2i_GENERAL_NAME_ex(nullptr, method, ctx, cnf, 0); } -static GENERAL_NAME *a2i_GENERAL_NAME(GENERAL_NAME *out, - const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, int gen_type, - const char *value, int is_nc) { - if (!value) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_MISSING_VALUE); - return nullptr; - } - - GENERAL_NAME *gen = nullptr; - if (out) { - gen = out; - } else { - gen = GENERAL_NAME_new(); - if (gen == nullptr) { - return nullptr; - } - } - - switch (gen_type) { - case GEN_URI: - case GEN_EMAIL: - case GEN_DNS: { - ASN1_IA5STRING *str = ASN1_IA5STRING_new(); - if (str == nullptr || !ASN1_STRING_set(str, value, strlen(value))) { - ASN1_STRING_free(str); - goto err; - } - gen->type = gen_type; - gen->d.ia5 = str; - break; - } - - case GEN_RID: { - ASN1_OBJECT *obj; - if (!(obj = OBJ_txt2obj(value, 0))) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_BAD_OBJECT); - ERR_add_error_data(2, "value=", value); - goto err; - } - gen->type = GEN_RID; - gen->d.rid = obj; - break; - } - - case GEN_IPADD: - gen->type = GEN_IPADD; - if (is_nc) { - gen->d.ip = a2i_IPADDRESS_NC(value); - } else { - gen->d.ip = a2i_IPADDRESS(value); - } - if (gen->d.ip == nullptr) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_BAD_IP_ADDRESS); - ERR_add_error_data(2, "value=", value); - goto err; - } - break; - - case GEN_DIRNAME: - if (!do_dirname(gen, value, ctx)) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_DIRNAME_ERROR); - goto err; - } - break; - - case GEN_OTHERNAME: - if (!do_othername(gen, value, ctx)) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_OTHERNAME_ERROR); - goto err; - } - break; - default: - OPENSSL_PUT_ERROR(X509V3, X509V3_R_UNSUPPORTED_TYPE); - goto err; - } - - return gen; - -err: - if (!out) { - GENERAL_NAME_free(gen); - } - return nullptr; -} - GENERAL_NAME *bssl::v2i_GENERAL_NAME_ex(GENERAL_NAME *out, const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, @@ -568,69 +620,3 @@ GENERAL_NAME *bssl::v2i_GENERAL_NAME_ex(GENERAL_NAME *out, return a2i_GENERAL_NAME(out, method, ctx, type, value, is_nc); } - -static int do_othername(GENERAL_NAME *gen, const char *value, - const X509V3_CTX *ctx) { - const char *semicolon = strchr(value, ';'); - if (semicolon == nullptr) { - return 0; - } - - OTHERNAME *name = OTHERNAME_new(); - if (name == nullptr) { - return 0; - } - - char *objtmp = OPENSSL_strndup(value, semicolon - value); - if (objtmp == nullptr) { - goto err; - } - ASN1_OBJECT_free(name->type_id); - name->type_id = OBJ_txt2obj(objtmp, /*dont_search_names=*/0); - OPENSSL_free(objtmp); - if (name->type_id == nullptr) { - goto err; - } - - ASN1_TYPE_free(name->value); - name->value = ASN1_generate_v3(semicolon + 1, ctx); - if (name->value == nullptr) { - goto err; - } - - gen->type = GEN_OTHERNAME; - gen->d.otherName = name; - return 1; - -err: - OTHERNAME_free(name); - return 0; -} - -static int do_dirname(GENERAL_NAME *gen, const char *value, - const X509V3_CTX *ctx) { - int ret = 0; - const STACK_OF(CONF_VALUE) *sk = X509V3_get_section(ctx, value); - X509_NAME *nm = X509_NAME_new(); - if (nm == nullptr) { - goto err; - } - if (sk == nullptr) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_SECTION_NOT_FOUND); - ERR_add_error_data(2, "section=", value); - goto err; - } - // FIXME: should allow other character types... - if (!X509V3_NAME_from_section(nm, sk, MBSTRING_ASC)) { - goto err; - } - gen->type = GEN_DIRNAME; - gen->d.dirn = nm; - ret = 1; - -err: - if (!ret) { - X509_NAME_free(nm); - } - return ret; -} diff --git a/third_party/boringssl/src/crypto/x509/v3_bcons.cc b/third_party/boringssl/src/crypto/x509/v3_bcons.cc index 6119400..d70c8d0 100644 --- a/third_party/boringssl/src/crypto/x509/v3_bcons.cc +++ b/third_party/boringssl/src/crypto/x509/v3_bcons.cc @@ -27,29 +27,6 @@ using namespace bssl; -static STACK_OF(CONF_VALUE) *i2v_BASIC_CONSTRAINTS( - const X509V3_EXT_METHOD *method, void *ext, STACK_OF(CONF_VALUE) *extlist); -static void *v2i_BASIC_CONSTRAINTS(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *values); - -const X509V3_EXT_METHOD bssl::v3_bcons = { - NID_basic_constraints, - 0, - ASN1_ITEM_ref(BASIC_CONSTRAINTS), - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - i2v_BASIC_CONSTRAINTS, - v2i_BASIC_CONSTRAINTS, - nullptr, - nullptr, - nullptr, -}; - ASN1_SEQUENCE(BASIC_CONSTRAINTS) = { ASN1_OPT(BASIC_CONSTRAINTS, ca, ASN1_FBOOLEAN), ASN1_OPT(BASIC_CONSTRAINTS, pathlen, ASN1_INTEGER), @@ -57,8 +34,11 @@ ASN1_SEQUENCE(BASIC_CONSTRAINTS) = { IMPLEMENT_ASN1_FUNCTIONS_const(BASIC_CONSTRAINTS) -static STACK_OF(CONF_VALUE) *i2v_BASIC_CONSTRAINTS( - const X509V3_EXT_METHOD *method, void *ext, STACK_OF(CONF_VALUE) *extlist) { +namespace { + +STACK_OF(CONF_VALUE) *i2v_BASIC_CONSTRAINTS(const X509V3_EXT_METHOD *method, + void *ext, + STACK_OF(CONF_VALUE) *extlist) { const BASIC_CONSTRAINTS *bcons = reinterpret_cast(ext); X509V3_add_value_bool("CA", bcons->ca, &extlist); @@ -66,9 +46,9 @@ static STACK_OF(CONF_VALUE) *i2v_BASIC_CONSTRAINTS( return extlist; } -static void *v2i_BASIC_CONSTRAINTS(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *values) { +void *v2i_BASIC_CONSTRAINTS(const X509V3_EXT_METHOD *method, + const X509V3_CTX *ctx, + const STACK_OF(CONF_VALUE) *values) { BASIC_CONSTRAINTS *bcons = nullptr; if (!(bcons = BASIC_CONSTRAINTS_new())) { return nullptr; @@ -94,3 +74,22 @@ static void *v2i_BASIC_CONSTRAINTS(const X509V3_EXT_METHOD *method, BASIC_CONSTRAINTS_free(bcons); return nullptr; } + +} // namespace + +const X509V3_EXT_METHOD bssl::v3_bcons = { + NID_basic_constraints, + 0, + ASN1_ITEM_ref(BASIC_CONSTRAINTS), + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + i2v_BASIC_CONSTRAINTS, + v2i_BASIC_CONSTRAINTS, + nullptr, + nullptr, + nullptr, +}; diff --git a/third_party/boringssl/src/crypto/x509/v3_bitst.cc b/third_party/boringssl/src/crypto/x509/v3_bitst.cc index 9b3acc8..2c4abca 100644 --- a/third_party/boringssl/src/crypto/x509/v3_bitst.cc +++ b/third_party/boringssl/src/crypto/x509/v3_bitst.cc @@ -25,14 +25,16 @@ using namespace bssl; -static const BIT_STRING_BITNAME ns_cert_type_table[] = { +namespace { + +const BIT_STRING_BITNAME ns_cert_type_table[] = { {0, "SSL Client", "client"}, {1, "SSL Server", "server"}, {2, "S/MIME", "email"}, {3, "Object Signing", "objsign"}, {4, "Unused", "reserved"}, {5, "SSL CA", "sslCA"}, {6, "S/MIME CA", "emailCA"}, {7, "Object Signing CA", "objCA"}, {-1, nullptr, nullptr}}; -static const BIT_STRING_BITNAME key_usage_type_table[] = { +const BIT_STRING_BITNAME key_usage_type_table[] = { {0, "Digital Signature", "digitalSignature"}, {1, "Non Repudiation", "nonRepudiation"}, {2, "Key Encipherment", "keyEncipherment"}, @@ -44,8 +46,9 @@ static const BIT_STRING_BITNAME key_usage_type_table[] = { {8, "Decipher Only", "decipherOnly"}, {-1, nullptr, nullptr}}; -static STACK_OF(CONF_VALUE) *i2v_ASN1_BIT_STRING( - const X509V3_EXT_METHOD *method, void *ext, STACK_OF(CONF_VALUE) *ret) { +STACK_OF(CONF_VALUE) *i2v_ASN1_BIT_STRING(const X509V3_EXT_METHOD *method, + void *ext, + STACK_OF(CONF_VALUE) *ret) { const ASN1_BIT_STRING *bits = reinterpret_cast(ext); const BIT_STRING_BITNAME *bnam; for (bnam = reinterpret_cast(method->usr_data); @@ -57,9 +60,9 @@ static STACK_OF(CONF_VALUE) *i2v_ASN1_BIT_STRING( return ret; } -static void *v2i_ASN1_BIT_STRING(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval) { +void *v2i_ASN1_BIT_STRING(const X509V3_EXT_METHOD *method, + const X509V3_CTX *ctx, + const STACK_OF(CONF_VALUE) *nval) { ASN1_BIT_STRING *bs; if (!(bs = ASN1_BIT_STRING_new())) { return nullptr; @@ -87,12 +90,23 @@ static void *v2i_ASN1_BIT_STRING(const X509V3_EXT_METHOD *method, return bs; } -#define EXT_BITSTRING(nid, table) \ - { \ - nid, 0, ASN1_ITEM_ref(ASN1_BIT_STRING), 0, 0, 0, 0, 0, 0, \ - i2v_ASN1_BIT_STRING, v2i_ASN1_BIT_STRING, nullptr, nullptr, \ - (void *)(table) \ - } +} // namespace + +#define EXT_BITSTRING(nid, table) \ + {nid, \ + 0, \ + ASN1_ITEM_ref(ASN1_BIT_STRING), \ + 0, \ + 0, \ + 0, \ + 0, \ + 0, \ + 0, \ + i2v_ASN1_BIT_STRING, \ + v2i_ASN1_BIT_STRING, \ + nullptr, \ + nullptr, \ + (void *)(table)} const X509V3_EXT_METHOD bssl::v3_nscert = EXT_BITSTRING(NID_netscape_cert_type, ns_cert_type_table); diff --git a/third_party/boringssl/src/crypto/x509/v3_conf.cc b/third_party/boringssl/src/crypto/x509/v3_conf.cc index 2d478c9..d80447c 100644 --- a/third_party/boringssl/src/crypto/x509/v3_conf.cc +++ b/third_party/boringssl/src/crypto/x509/v3_conf.cc @@ -31,64 +31,35 @@ using namespace bssl; -static int v3_check_critical(const char **value); -static int v3_check_generic(const char **value); -static X509_EXTENSION *do_ext_nconf(const CONF *conf, const X509V3_CTX *ctx, - int ext_nid, int crit, const char *value); -static X509_EXTENSION *v3_generic_extension(const char *ext, const char *value, - int crit, int type, - const X509V3_CTX *ctx); -static X509_EXTENSION *do_ext_i2d(const X509V3_EXT_METHOD *method, int ext_nid, - int crit, void *ext_struc); -static unsigned char *generic_asn1(const char *value, const X509V3_CTX *ctx, - size_t *ext_len); +namespace { -X509_EXTENSION *X509V3_EXT_nconf(const CONF *conf, const X509V3_CTX *ctx, - const char *name, const char *value) { - // If omitted, fill in an empty `X509V3_CTX`. - X509V3_CTX ctx_tmp; - if (ctx == nullptr) { - X509V3_set_ctx(&ctx_tmp, nullptr, nullptr, nullptr, nullptr, 0); - X509V3_set_nconf(&ctx_tmp, conf); - ctx = &ctx_tmp; - } - - int crit = v3_check_critical(&value); - int ext_type = v3_check_generic(&value); - if (ext_type != 0) { - return v3_generic_extension(name, value, crit, ext_type, ctx); - } - X509_EXTENSION *ret = do_ext_nconf(conf, ctx, OBJ_sn2nid(name), crit, value); - if (!ret) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_ERROR_IN_EXTENSION); - ERR_add_error_data(4, "name=", name, ", value=", value); +X509_EXTENSION *do_ext_i2d(const X509V3_EXT_METHOD *method, int ext_nid, + int crit, void *ext_struc) { + // Convert the extension's internal representation to DER. + unsigned char *ext_der = nullptr; + int ext_len = ASN1_item_i2d(reinterpret_cast(ext_struc), + &ext_der, ASN1_ITEM_ptr(method->it)); + if (ext_len < 0) { + return nullptr; } - return ret; -} -X509_EXTENSION *X509V3_EXT_nconf_nid(const CONF *conf, const X509V3_CTX *ctx, - int ext_nid, const char *value) { - // If omitted, fill in an empty `X509V3_CTX`. - X509V3_CTX ctx_tmp; - if (ctx == nullptr) { - X509V3_set_ctx(&ctx_tmp, nullptr, nullptr, nullptr, nullptr, 0); - X509V3_set_nconf(&ctx_tmp, conf); - ctx = &ctx_tmp; + ASN1_OCTET_STRING *ext_oct = ASN1_OCTET_STRING_new(); + if (ext_oct == nullptr) { + OPENSSL_free(ext_der); + return nullptr; } + ASN1_STRING_set0(ext_oct, ext_der, ext_len); - int crit = v3_check_critical(&value); - int ext_type = v3_check_generic(&value); - if (ext_type != 0) { - return v3_generic_extension(OBJ_nid2sn(ext_nid), value, crit, ext_type, - ctx); - } - return do_ext_nconf(conf, ctx, ext_nid, crit, value); + X509_EXTENSION *ext = + X509_EXTENSION_create_by_NID(nullptr, ext_nid, crit, ext_oct); + ASN1_OCTET_STRING_free(ext_oct); + return ext; } // CONF *conf: Config file // char *value: Value -static X509_EXTENSION *do_ext_nconf(const CONF *conf, const X509V3_CTX *ctx, - int ext_nid, int crit, const char *value) { +X509_EXTENSION *do_ext_nconf(const CONF *conf, const X509V3_CTX *ctx, + int ext_nid, int crit, const char *value) { const X509V3_EXT_METHOD *method; X509_EXTENSION *ext; const STACK_OF(CONF_VALUE) *nval; @@ -156,42 +127,8 @@ static X509_EXTENSION *do_ext_nconf(const CONF *conf, const X509V3_CTX *ctx, return ext; } -static X509_EXTENSION *do_ext_i2d(const X509V3_EXT_METHOD *method, int ext_nid, - int crit, void *ext_struc) { - // Convert the extension's internal representation to DER. - unsigned char *ext_der = nullptr; - int ext_len = ASN1_item_i2d(reinterpret_cast(ext_struc), - &ext_der, ASN1_ITEM_ptr(method->it)); - if (ext_len < 0) { - return nullptr; - } - - ASN1_OCTET_STRING *ext_oct = ASN1_OCTET_STRING_new(); - if (ext_oct == nullptr) { - OPENSSL_free(ext_der); - return nullptr; - } - ASN1_STRING_set0(ext_oct, ext_der, ext_len); - - X509_EXTENSION *ext = - X509_EXTENSION_create_by_NID(nullptr, ext_nid, crit, ext_oct); - ASN1_OCTET_STRING_free(ext_oct); - return ext; -} - -// Given an internal structure, nid and critical flag create an extension - -X509_EXTENSION *X509V3_EXT_i2d(int ext_nid, int crit, void *ext_struc) { - const X509V3_EXT_METHOD *method; - if (!(method = X509V3_EXT_get_nid(ext_nid))) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_UNKNOWN_EXTENSION); - return nullptr; - } - return do_ext_i2d(method, ext_nid, crit, ext_struc); -} - // Check the extension string for critical flag -static int v3_check_critical(const char **value) { +int v3_check_critical(const char **value) { const char *p = *value; if ((strlen(p) < 9) || strncmp(p, "critical,", 9)) { return 0; @@ -205,7 +142,7 @@ static int v3_check_critical(const char **value) { } // Check extension string for generic extension and return the type -static int v3_check_generic(const char **value) { +int v3_check_generic(const char **value) { int gen_type = 0; const char *p = *value; if ((strlen(p) >= 4) && !strncmp(p, "DER:", 4)) { @@ -225,10 +162,26 @@ static int v3_check_generic(const char **value) { return gen_type; } +unsigned char *generic_asn1(const char *value, const X509V3_CTX *ctx, + size_t *ext_len) { + ASN1_TYPE *typ = ASN1_generate_v3(value, ctx); + if (typ == nullptr) { + return nullptr; + } + unsigned char *ext_der = nullptr; + int len = i2d_ASN1_TYPE(typ, &ext_der); + ASN1_TYPE_free(typ); + if (len < 0) { + return nullptr; + } + *ext_len = len; + return ext_der; +} + // Create a generic extension: for now just handle DER type -static X509_EXTENSION *v3_generic_extension(const char *ext, const char *value, - int crit, int gen_type, - const X509V3_CTX *ctx) { +X509_EXTENSION *v3_generic_extension(const char *ext, const char *value, + int crit, int gen_type, + const X509V3_CTX *ctx) { UniquePtr obj(OBJ_txt2obj(ext, 0)); if (obj == nullptr) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_EXTENSION_NAME_ERROR); @@ -266,20 +219,59 @@ static X509_EXTENSION *v3_generic_extension(const char *ext, const char *value, return X509_EXTENSION_create_by_OBJ(nullptr, obj.get(), crit, oct.get()); } -static unsigned char *generic_asn1(const char *value, const X509V3_CTX *ctx, - size_t *ext_len) { - ASN1_TYPE *typ = ASN1_generate_v3(value, ctx); - if (typ == nullptr) { - return nullptr; +} // namespace + +X509_EXTENSION *X509V3_EXT_nconf(const CONF *conf, const X509V3_CTX *ctx, + const char *name, const char *value) { + // If omitted, fill in an empty `X509V3_CTX`. + X509V3_CTX ctx_tmp; + if (ctx == nullptr) { + X509V3_set_ctx(&ctx_tmp, nullptr, nullptr, nullptr, nullptr, 0); + X509V3_set_nconf(&ctx_tmp, conf); + ctx = &ctx_tmp; } - unsigned char *ext_der = nullptr; - int len = i2d_ASN1_TYPE(typ, &ext_der); - ASN1_TYPE_free(typ); - if (len < 0) { + + int crit = v3_check_critical(&value); + int ext_type = v3_check_generic(&value); + if (ext_type != 0) { + return v3_generic_extension(name, value, crit, ext_type, ctx); + } + X509_EXTENSION *ret = do_ext_nconf(conf, ctx, OBJ_sn2nid(name), crit, value); + if (!ret) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_ERROR_IN_EXTENSION); + ERR_add_error_data(4, "name=", name, ", value=", value); + } + return ret; +} + +X509_EXTENSION *X509V3_EXT_nconf_nid(const CONF *conf, const X509V3_CTX *ctx, + int ext_nid, const char *value) { + // If omitted, fill in an empty `X509V3_CTX`. + X509V3_CTX ctx_tmp; + if (ctx == nullptr) { + X509V3_set_ctx(&ctx_tmp, nullptr, nullptr, nullptr, nullptr, 0); + X509V3_set_nconf(&ctx_tmp, conf); + ctx = &ctx_tmp; + } + + int crit = v3_check_critical(&value); + int ext_type = v3_check_generic(&value); + if (ext_type != 0) { + return v3_generic_extension(OBJ_nid2sn(ext_nid), value, crit, ext_type, + ctx); + } + return do_ext_nconf(conf, ctx, ext_nid, crit, value); +} + +// Given an internal structure, nid and critical flag create an extension + +X509_EXTENSION *X509V3_EXT_i2d(int ext_nid, int crit, void *ext_struc) { + const X509V3_EXT_METHOD *method; + if (!(method = X509V3_EXT_get_nid(ext_nid))) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_UNKNOWN_EXTENSION); return nullptr; } - *ext_len = len; - return ext_der; + return do_ext_i2d(method, ext_nid, crit, ext_struc); } // This is the main function: add a bunch of extensions based on a config diff --git a/third_party/boringssl/src/crypto/x509/v3_cpols.cc b/third_party/boringssl/src/crypto/x509/v3_cpols.cc index 840262e..a183b33 100644 --- a/third_party/boringssl/src/crypto/x509/v3_cpols.cc +++ b/third_party/boringssl/src/crypto/x509/v3_cpols.cc @@ -33,38 +33,6 @@ using namespace bssl; // Certificate policies extension support: this one is a bit complex... -static int i2r_certpol(const X509V3_EXT_METHOD *method, void *ext, BIO *out, - int indent); -static void *r2i_certpol(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, - const char *value); -static void print_qualifiers(BIO *out, const STACK_OF(POLICYQUALINFO) *quals, - int indent); -static void print_notice(BIO *out, const USERNOTICE *notice, int indent); -static UniquePtr policy_section(const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *polstrs, - int ia5org); -static UniquePtr notice_section( - const X509V3_CTX *ctx, const STACK_OF(CONF_VALUE) *unot, int ia5org); -static int nref_nos(STACK_OF(ASN1_INTEGER) *nnums, - const STACK_OF(CONF_VALUE) *nos); - -const X509V3_EXT_METHOD bssl::v3_cpols = { - NID_certificate_policies, - 0, - ASN1_ITEM_ref(CERTIFICATEPOLICIES), - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - i2r_certpol, - r2i_certpol, - nullptr, -}; - ASN1_SEQUENCE(NOTICEREF) = { ASN1_SIMPLE(NOTICEREF, organization, DISPLAYTEXT), ASN1_SEQUENCE_OF(NOTICEREF, noticenos, ASN1_INTEGER), @@ -109,64 +77,107 @@ ASN1_ITEM_TEMPLATE_END(CERTIFICATEPOLICIES) IMPLEMENT_ASN1_FUNCTIONS_const(CERTIFICATEPOLICIES) -static void *r2i_certpol(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, - const char *value) { - UniquePtr pols(sk_POLICYINFO_new_null()); - if (pols == nullptr) { +namespace { + +int nref_nos(STACK_OF(ASN1_INTEGER) *nnums, const STACK_OF(CONF_VALUE) *nos) { + for (size_t i = 0; i < sk_CONF_VALUE_num(nos); i++) { + const CONF_VALUE *cnf = sk_CONF_VALUE_value(nos, i); + ASN1_INTEGER *aint = s2i_ASN1_INTEGER(nullptr, cnf->name); + if (aint == nullptr) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NUMBER); + return 0; + } + if (!sk_ASN1_INTEGER_push(nnums, aint)) { + ASN1_INTEGER_free(aint); + return 0; + } + } + return 1; +} + +UniquePtr notice_section(const X509V3_CTX *ctx, + const STACK_OF(CONF_VALUE) *unot, + int ia5org) { + UniquePtr qual(POLICYQUALINFO_new()); + if (qual == nullptr) { return nullptr; } - UniquePtr vals(X509V3_parse_list(value)); - if (vals == nullptr) { - OPENSSL_PUT_ERROR(X509V3, ERR_R_X509V3_LIB); + qual->pqualid = OBJ_nid2obj(NID_id_qt_unotice); + if (qual->pqualid == nullptr) { + OPENSSL_PUT_ERROR(X509V3, ERR_R_INTERNAL_ERROR); return nullptr; } - int ia5org = 0; - for (const CONF_VALUE *cnf : vals.get()) { - if (cnf->value || !cnf->name) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_POLICY_IDENTIFIER); - X509V3_conf_err(cnf); - return nullptr; - } - UniquePtr pol; - const char *pstr = cnf->name; - if (!strcmp(pstr, "ia5org")) { - ia5org = 1; - continue; - } else if (*pstr == '@') { - const STACK_OF(CONF_VALUE) *polsect = X509V3_get_section(ctx, pstr + 1); - if (!polsect) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_SECTION); - - X509V3_conf_err(cnf); + USERNOTICE *notice = USERNOTICE_new(); + if (notice == nullptr) { + return nullptr; + } + qual->d.usernotice = notice; + for (const CONF_VALUE *cnf : unot) { + if (!strcmp(cnf->name, "explicitText")) { + notice->exptext = ASN1_VISIBLESTRING_new(); + if (notice->exptext == nullptr) { return nullptr; } - pol = policy_section(ctx, polsect, ia5org); - if (!pol) { + if (!ASN1_STRING_set(notice->exptext, cnf->value, strlen(cnf->value))) { return nullptr; } - } else { - UniquePtr pobj(OBJ_txt2obj(cnf->name, 0)); - if (pobj == nullptr) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_OBJECT_IDENTIFIER); + } else if (!strcmp(cnf->name, "organization")) { + NOTICEREF *nref; + if (!notice->noticeref) { + if (!(nref = NOTICEREF_new())) { + return nullptr; + } + notice->noticeref = nref; + } else { + nref = notice->noticeref; + } + if (ia5org) { + nref->organization->type = V_ASN1_IA5STRING; + } else { + nref->organization->type = V_ASN1_VISIBLESTRING; + } + if (!ASN1_STRING_set(nref->organization, cnf->value, + strlen(cnf->value))) { + return nullptr; + } + } else if (!strcmp(cnf->name, "noticeNumbers")) { + NOTICEREF *nref; + if (!notice->noticeref) { + if (!(nref = NOTICEREF_new())) { + return nullptr; + } + notice->noticeref = nref; + } else { + nref = notice->noticeref; + } + UniquePtr nos(X509V3_parse_list(cnf->value)); + if (!nos || !sk_CONF_VALUE_num(nos.get())) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NUMBERS); X509V3_conf_err(cnf); return nullptr; } - pol.reset(POLICYINFO_new()); - if (pol == nullptr) { + if (!nref_nos(nref->noticenos, nos.get())) { return nullptr; } - pol->policyid = pobj.release(); - } - if (!PushToStack(pols.get(), std::move(pol))) { + } else { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_OPTION); + X509V3_conf_err(cnf); return nullptr; } } - return pols.release(); + + if (notice->noticeref && + (!notice->noticeref->noticenos || !notice->noticeref->organization)) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_NEED_ORGANIZATION_AND_NUMBERS); + return nullptr; + } + + return qual; } -static UniquePtr policy_section(const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *polstrs, - int ia5org) { +UniquePtr policy_section(const X509V3_CTX *ctx, + const STACK_OF(CONF_VALUE) *polstrs, + int ia5org) { UniquePtr pol(POLICYINFO_new()); if (pol == nullptr) { return nullptr; @@ -244,145 +255,62 @@ static UniquePtr policy_section(const X509V3_CTX *ctx, return pol; } -static UniquePtr notice_section( - const X509V3_CTX *ctx, const STACK_OF(CONF_VALUE) *unot, int ia5org) { - UniquePtr qual(POLICYQUALINFO_new()); - if (qual == nullptr) { - return nullptr; - } - qual->pqualid = OBJ_nid2obj(NID_id_qt_unotice); - if (qual->pqualid == nullptr) { - OPENSSL_PUT_ERROR(X509V3, ERR_R_INTERNAL_ERROR); +void *r2i_certpol(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, + const char *value) { + UniquePtr pols(sk_POLICYINFO_new_null()); + if (pols == nullptr) { return nullptr; } - USERNOTICE *notice = USERNOTICE_new(); - if (notice == nullptr) { + UniquePtr vals(X509V3_parse_list(value)); + if (vals == nullptr) { + OPENSSL_PUT_ERROR(X509V3, ERR_R_X509V3_LIB); return nullptr; } - qual->d.usernotice = notice; - for (const CONF_VALUE *cnf : unot) { - if (!strcmp(cnf->name, "explicitText")) { - notice->exptext = ASN1_VISIBLESTRING_new(); - if (notice->exptext == nullptr) { - return nullptr; - } - if (!ASN1_STRING_set(notice->exptext, cnf->value, strlen(cnf->value))) { + int ia5org = 0; + for (const CONF_VALUE *cnf : vals.get()) { + if (cnf->value || !cnf->name) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_POLICY_IDENTIFIER); + X509V3_conf_err(cnf); + return nullptr; + } + UniquePtr pol; + const char *pstr = cnf->name; + if (!strcmp(pstr, "ia5org")) { + ia5org = 1; + continue; + } else if (*pstr == '@') { + const STACK_OF(CONF_VALUE) *polsect = X509V3_get_section(ctx, pstr + 1); + if (!polsect) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_SECTION); + + X509V3_conf_err(cnf); return nullptr; } - } else if (!strcmp(cnf->name, "organization")) { - NOTICEREF *nref; - if (!notice->noticeref) { - if (!(nref = NOTICEREF_new())) { - return nullptr; - } - notice->noticeref = nref; - } else { - nref = notice->noticeref; - } - if (ia5org) { - nref->organization->type = V_ASN1_IA5STRING; - } else { - nref->organization->type = V_ASN1_VISIBLESTRING; - } - if (!ASN1_STRING_set(nref->organization, cnf->value, - strlen(cnf->value))) { + pol = policy_section(ctx, polsect, ia5org); + if (!pol) { return nullptr; } - } else if (!strcmp(cnf->name, "noticeNumbers")) { - NOTICEREF *nref; - if (!notice->noticeref) { - if (!(nref = NOTICEREF_new())) { - return nullptr; - } - notice->noticeref = nref; - } else { - nref = notice->noticeref; - } - UniquePtr nos(X509V3_parse_list(cnf->value)); - if (!nos || !sk_CONF_VALUE_num(nos.get())) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NUMBERS); + } else { + UniquePtr pobj(OBJ_txt2obj(cnf->name, 0)); + if (pobj == nullptr) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_OBJECT_IDENTIFIER); X509V3_conf_err(cnf); return nullptr; } - if (!nref_nos(nref->noticenos, nos.get())) { + pol.reset(POLICYINFO_new()); + if (pol == nullptr) { return nullptr; } - } else { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_OPTION); - X509V3_conf_err(cnf); - return nullptr; - } - } - - if (notice->noticeref && - (!notice->noticeref->noticenos || !notice->noticeref->organization)) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_NEED_ORGANIZATION_AND_NUMBERS); - return nullptr; - } - - return qual; -} - -static int nref_nos(STACK_OF(ASN1_INTEGER) *nnums, - const STACK_OF(CONF_VALUE) *nos) { - for (size_t i = 0; i < sk_CONF_VALUE_num(nos); i++) { - const CONF_VALUE *cnf = sk_CONF_VALUE_value(nos, i); - ASN1_INTEGER *aint = s2i_ASN1_INTEGER(nullptr, cnf->name); - if (aint == nullptr) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NUMBER); - return 0; - } - if (!sk_ASN1_INTEGER_push(nnums, aint)) { - ASN1_INTEGER_free(aint); - return 0; - } - } - return 1; -} - -static int i2r_certpol(const X509V3_EXT_METHOD *method, void *ext, BIO *out, - int indent) { - const STACK_OF(POLICYINFO) *pol = - reinterpret_cast(ext); - // First print out the policy OIDs - for (size_t i = 0; i < sk_POLICYINFO_num(pol); i++) { - const POLICYINFO *pinfo = sk_POLICYINFO_value(pol, i); - BIO_printf(out, "%*sPolicy: ", indent, ""); - i2a_ASN1_OBJECT(out, pinfo->policyid); - BIO_puts(out, "\n"); - if (pinfo->qualifiers) { - print_qualifiers(out, pinfo->qualifiers, indent + 2); + pol->policyid = pobj.release(); } - } - return 1; -} - -static void print_qualifiers(BIO *out, const STACK_OF(POLICYQUALINFO) *quals, - int indent) { - for (size_t i = 0; i < sk_POLICYQUALINFO_num(quals); i++) { - const POLICYQUALINFO *qualinfo = sk_POLICYQUALINFO_value(quals, i); - switch (OBJ_obj2nid(qualinfo->pqualid)) { - case NID_id_qt_cps: - BIO_printf(out, "%*sCPS: %.*s\n", indent, "", - qualinfo->d.cpsuri->length, qualinfo->d.cpsuri->data); - break; - - case NID_id_qt_unotice: - BIO_printf(out, "%*sUser Notice:\n", indent, ""); - print_notice(out, qualinfo->d.usernotice, indent + 2); - break; - - default: - BIO_printf(out, "%*sUnknown Qualifier: ", indent + 2, ""); - - i2a_ASN1_OBJECT(out, qualinfo->pqualid); - BIO_puts(out, "\n"); - break; + if (!PushToStack(pols.get(), std::move(pol))) { + return nullptr; } } + return pols.release(); } -static void print_notice(BIO *out, const USERNOTICE *notice, int indent) { +void print_notice(BIO *out, const USERNOTICE *notice, int indent) { if (notice->noticeref) { NOTICEREF *ref; ref = notice->noticeref; @@ -415,3 +343,64 @@ static void print_notice(BIO *out, const USERNOTICE *notice, int indent) { notice->exptext->length, notice->exptext->data); } } + +void print_qualifiers(BIO *out, const STACK_OF(POLICYQUALINFO) *quals, + int indent) { + for (size_t i = 0; i < sk_POLICYQUALINFO_num(quals); i++) { + const POLICYQUALINFO *qualinfo = sk_POLICYQUALINFO_value(quals, i); + switch (OBJ_obj2nid(qualinfo->pqualid)) { + case NID_id_qt_cps: + BIO_printf(out, "%*sCPS: %.*s\n", indent, "", + qualinfo->d.cpsuri->length, qualinfo->d.cpsuri->data); + break; + + case NID_id_qt_unotice: + BIO_printf(out, "%*sUser Notice:\n", indent, ""); + print_notice(out, qualinfo->d.usernotice, indent + 2); + break; + + default: + BIO_printf(out, "%*sUnknown Qualifier: ", indent + 2, ""); + + i2a_ASN1_OBJECT(out, qualinfo->pqualid); + BIO_puts(out, "\n"); + break; + } + } +} + +int i2r_certpol(const X509V3_EXT_METHOD *method, void *ext, BIO *out, + int indent) { + const STACK_OF(POLICYINFO) *pol = + reinterpret_cast(ext); + // First print out the policy OIDs + for (size_t i = 0; i < sk_POLICYINFO_num(pol); i++) { + const POLICYINFO *pinfo = sk_POLICYINFO_value(pol, i); + BIO_printf(out, "%*sPolicy: ", indent, ""); + i2a_ASN1_OBJECT(out, pinfo->policyid); + BIO_puts(out, "\n"); + if (pinfo->qualifiers) { + print_qualifiers(out, pinfo->qualifiers, indent + 2); + } + } + return 1; +} + +} // namespace + +const X509V3_EXT_METHOD bssl::v3_cpols = { + NID_certificate_policies, + 0, + ASN1_ITEM_ref(CERTIFICATEPOLICIES), + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + i2r_certpol, + r2i_certpol, + nullptr, +}; diff --git a/third_party/boringssl/src/crypto/x509/v3_crld.cc b/third_party/boringssl/src/crypto/x509/v3_crld.cc index 48d1538..1e02784 100644 --- a/third_party/boringssl/src/crypto/x509/v3_crld.cc +++ b/third_party/boringssl/src/crypto/x509/v3_crld.cc @@ -33,38 +33,42 @@ using namespace bssl; -static void *v2i_crld(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval); -static int i2r_crldp(const X509V3_EXT_METHOD *method, void *pcrldp, BIO *out, - int indent); +ASN1_CHOICE(DIST_POINT_NAME) = { + ASN1_IMP_SEQUENCE_OF(DIST_POINT_NAME, name.fullname, GENERAL_NAME, 0), + ASN1_IMP_SET_OF(DIST_POINT_NAME, name.relativename, X509_NAME_ENTRY, 1), +} ASN1_CHOICE_END(DIST_POINT_NAME) -const X509V3_EXT_METHOD bssl::v3_crld = { - NID_crl_distribution_points, - 0, - ASN1_ITEM_ref(CRL_DIST_POINTS), - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - v2i_crld, - i2r_crldp, - nullptr, - nullptr, -}; +IMPLEMENT_ASN1_ALLOC_FUNCTIONS(DIST_POINT_NAME) -const X509V3_EXT_METHOD bssl::v3_freshest_crl = { - NID_freshest_crl, 0, ASN1_ITEM_ref(CRL_DIST_POINTS), - nullptr, nullptr, nullptr, - nullptr, nullptr, nullptr, - nullptr, v2i_crld, i2r_crldp, - nullptr, nullptr, -}; +ASN1_SEQUENCE(DIST_POINT) = { + ASN1_EXP_OPT(DIST_POINT, distpoint, DIST_POINT_NAME, 0), + ASN1_IMP_OPT(DIST_POINT, reasons, ASN1_BIT_STRING, 1), + ASN1_IMP_SEQUENCE_OF_OPT(DIST_POINT, CRLissuer, GENERAL_NAME, 2), +} ASN1_SEQUENCE_END(DIST_POINT) + +IMPLEMENT_ASN1_ALLOC_FUNCTIONS(DIST_POINT) + +ASN1_ITEM_TEMPLATE(CRL_DIST_POINTS) = ASN1_EX_TEMPLATE_TYPE( + ASN1_TFLG_SEQUENCE_OF, 0, CRLDistributionPoints, DIST_POINT) +ASN1_ITEM_TEMPLATE_END(CRL_DIST_POINTS) + +IMPLEMENT_ASN1_FUNCTIONS_const(CRL_DIST_POINTS) + +ASN1_SEQUENCE(ISSUING_DIST_POINT) = { + ASN1_EXP_OPT(ISSUING_DIST_POINT, distpoint, DIST_POINT_NAME, 0), + ASN1_IMP_OPT(ISSUING_DIST_POINT, onlyuser, ASN1_FBOOLEAN, 1), + ASN1_IMP_OPT(ISSUING_DIST_POINT, onlyCA, ASN1_FBOOLEAN, 2), + ASN1_IMP_OPT(ISSUING_DIST_POINT, onlysomereasons, ASN1_BIT_STRING, 3), + ASN1_IMP_OPT(ISSUING_DIST_POINT, indirectCRL, ASN1_FBOOLEAN, 4), + ASN1_IMP_OPT(ISSUING_DIST_POINT, onlyattr, ASN1_FBOOLEAN, 5), +} ASN1_SEQUENCE_END(ISSUING_DIST_POINT) + +IMPLEMENT_ASN1_FUNCTIONS_const(ISSUING_DIST_POINT) -static UniquePtr gnames_from_sectname(const X509V3_CTX *ctx, - const char *sect) { +namespace { + +UniquePtr gnames_from_sectname(const X509V3_CTX *ctx, + const char *sect) { const STACK_OF(CONF_VALUE) *gnsect; UniquePtr gnsect_owned; if (*sect == '@') { @@ -84,8 +88,8 @@ static UniquePtr gnames_from_sectname(const X509V3_CTX *ctx, // result in `*pdp`. It returns 1 on success, -1 on error, and 0 if `cnf` used // an unrecognized input type. The zero return can be used by callers to support // additional syntax. -static int set_dist_point_name(DIST_POINT_NAME **pdp, const X509V3_CTX *ctx, - const CONF_VALUE *cnf) { +int set_dist_point_name(DIST_POINT_NAME **pdp, const X509V3_CTX *ctx, + const CONF_VALUE *cnf) { UniquePtr fnm; UniquePtr rnm; if (!strcmp(cnf->name, "fullname")) { @@ -150,7 +154,7 @@ static int set_dist_point_name(DIST_POINT_NAME **pdp, const X509V3_CTX *ctx, return 1; } -static const BIT_STRING_BITNAME reason_flags[] = { +const BIT_STRING_BITNAME reason_flags[] = { {0, "Unused", "unused"}, {1, "Key Compromise", "keyCompromise"}, {2, "CA Compromise", "CACompromise"}, @@ -162,7 +166,7 @@ static const BIT_STRING_BITNAME reason_flags[] = { {8, "AA Compromise", "AACompromise"}, }; -static int set_reasons(ASN1_BIT_STRING **preas, const char *value) { +int set_reasons(ASN1_BIT_STRING **preas, const char *value) { if (*preas) { // Duplicate "reasons" or "onlysomereasons" key. OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_VALUE); @@ -191,8 +195,8 @@ static int set_reasons(ASN1_BIT_STRING **preas, const char *value) { return 1; } -static int print_reasons(BIO *out, const char *rname, ASN1_BIT_STRING *rflags, - int indent) { +int print_reasons(BIO *out, const char *rname, ASN1_BIT_STRING *rflags, + int indent) { bool first = true; BIO_printf(out, "%*s%s:\n%*s", indent, "", rname, indent + 2, ""); for (const BIT_STRING_BITNAME &reason : reason_flags) { @@ -213,8 +217,8 @@ static int print_reasons(BIO *out, const char *rname, ASN1_BIT_STRING *rflags, return 1; } -static UniquePtr crldp_from_section( - const X509V3_CTX *ctx, const STACK_OF(CONF_VALUE) *nval) { +UniquePtr crldp_from_section(const X509V3_CTX *ctx, + const STACK_OF(CONF_VALUE) *nval) { UniquePtr point(DIST_POINT_new()); if (!point) { return nullptr; @@ -244,8 +248,8 @@ static UniquePtr crldp_from_section( return point; } -static void *v2i_crld(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval) { +void *v2i_crld(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, + const STACK_OF(CONF_VALUE) *nval) { UniquePtr crld(sk_DIST_POINT_new_null()); if (crld == nullptr) { return nullptr; @@ -286,79 +290,8 @@ static void *v2i_crld(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, return crld.release(); } -static int dpn_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, - void *exarg) { - DIST_POINT_NAME *dpn = asn1_load_ptr_as(pval); - - switch (operation) { - case ASN1_OP_NEW_POST: - dpn->dpname = nullptr; - break; - - case ASN1_OP_FREE_POST: - X509_NAME_free(dpn->dpname); - break; - } - return 1; -} - - -ASN1_CHOICE_cb(DIST_POINT_NAME, dpn_cb) = { - ASN1_IMP_SEQUENCE_OF(DIST_POINT_NAME, name.fullname, GENERAL_NAME, 0), - ASN1_IMP_SET_OF(DIST_POINT_NAME, name.relativename, X509_NAME_ENTRY, 1), -} ASN1_CHOICE_END_cb(DIST_POINT_NAME, DIST_POINT_NAME, type) - -IMPLEMENT_ASN1_ALLOC_FUNCTIONS(DIST_POINT_NAME) - -ASN1_SEQUENCE(DIST_POINT) = { - ASN1_EXP_OPT(DIST_POINT, distpoint, DIST_POINT_NAME, 0), - ASN1_IMP_OPT(DIST_POINT, reasons, ASN1_BIT_STRING, 1), - ASN1_IMP_SEQUENCE_OF_OPT(DIST_POINT, CRLissuer, GENERAL_NAME, 2), -} ASN1_SEQUENCE_END(DIST_POINT) - -IMPLEMENT_ASN1_ALLOC_FUNCTIONS(DIST_POINT) - -ASN1_ITEM_TEMPLATE(CRL_DIST_POINTS) = ASN1_EX_TEMPLATE_TYPE( - ASN1_TFLG_SEQUENCE_OF, 0, CRLDistributionPoints, DIST_POINT) -ASN1_ITEM_TEMPLATE_END(CRL_DIST_POINTS) - -IMPLEMENT_ASN1_FUNCTIONS_const(CRL_DIST_POINTS) - -ASN1_SEQUENCE(ISSUING_DIST_POINT) = { - ASN1_EXP_OPT(ISSUING_DIST_POINT, distpoint, DIST_POINT_NAME, 0), - ASN1_IMP_OPT(ISSUING_DIST_POINT, onlyuser, ASN1_FBOOLEAN, 1), - ASN1_IMP_OPT(ISSUING_DIST_POINT, onlyCA, ASN1_FBOOLEAN, 2), - ASN1_IMP_OPT(ISSUING_DIST_POINT, onlysomereasons, ASN1_BIT_STRING, 3), - ASN1_IMP_OPT(ISSUING_DIST_POINT, indirectCRL, ASN1_FBOOLEAN, 4), - ASN1_IMP_OPT(ISSUING_DIST_POINT, onlyattr, ASN1_FBOOLEAN, 5), -} ASN1_SEQUENCE_END(ISSUING_DIST_POINT) - -IMPLEMENT_ASN1_FUNCTIONS_const(ISSUING_DIST_POINT) - -static int i2r_idp(const X509V3_EXT_METHOD *method, void *pidp, BIO *out, - int indent); -static void *v2i_idp(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval); - -const X509V3_EXT_METHOD bssl::v3_idp = { - NID_issuing_distribution_point, - X509V3_EXT_MULTILINE, - ASN1_ITEM_ref(ISSUING_DIST_POINT), - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - v2i_idp, - i2r_idp, - nullptr, - nullptr, -}; - -static void *v2i_idp(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval) { +void *v2i_idp(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, + const STACK_OF(CONF_VALUE) *nval) { ISSUING_DIST_POINT *idp = ISSUING_DIST_POINT_new(); if (!idp) { goto err; @@ -407,7 +340,7 @@ static void *v2i_idp(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, return nullptr; } -static int print_gens(BIO *out, STACK_OF(GENERAL_NAME) *gens, int indent) { +int print_gens(BIO *out, STACK_OF(GENERAL_NAME) *gens, int indent) { size_t i; for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) { BIO_printf(out, "%*s", indent + 2, ""); @@ -417,7 +350,7 @@ static int print_gens(BIO *out, STACK_OF(GENERAL_NAME) *gens, int indent) { return 1; } -static int print_distpoint(BIO *out, DIST_POINT_NAME *dpn, int indent) { +int print_distpoint(BIO *out, DIST_POINT_NAME *dpn, int indent) { if (dpn->type == 0) { BIO_printf(out, "%*sFull Name:\n", indent, ""); print_gens(out, dpn->name.fullname, indent); @@ -435,8 +368,7 @@ static int print_distpoint(BIO *out, DIST_POINT_NAME *dpn, int indent) { return 1; } -static int i2r_idp(const X509V3_EXT_METHOD *method, void *pidp, BIO *out, - int indent) { +int i2r_idp(const X509V3_EXT_METHOD *method, void *pidp, BIO *out, int indent) { ISSUING_DIST_POINT *idp = reinterpret_cast(pidp); if (idp->distpoint) { print_distpoint(out, idp->distpoint, indent); @@ -465,8 +397,8 @@ static int i2r_idp(const X509V3_EXT_METHOD *method, void *pidp, BIO *out, return 1; } -static int i2r_crldp(const X509V3_EXT_METHOD *method, void *pcrldp, BIO *out, - int indent) { +int i2r_crldp(const X509V3_EXT_METHOD *method, void *pcrldp, BIO *out, + int indent) { STACK_OF(DIST_POINT) *crld = reinterpret_cast(pcrldp); DIST_POINT *point; size_t i; @@ -487,31 +419,46 @@ static int i2r_crldp(const X509V3_EXT_METHOD *method, void *pcrldp, BIO *out, return 1; } -int bssl::DIST_POINT_set_dpname(DIST_POINT_NAME *dpn, X509_NAME *iname) { - size_t i; - STACK_OF(X509_NAME_ENTRY) *frag; - X509_NAME_ENTRY *ne; - if (!dpn || (dpn->type != 1)) { - return 1; - } - frag = dpn->name.relativename; - dpn->dpname = X509_NAME_dup(iname); - if (!dpn->dpname) { - return 0; - } - for (i = 0; i < sk_X509_NAME_ENTRY_num(frag); i++) { - ne = sk_X509_NAME_ENTRY_value(frag, i); - if (!X509_NAME_add_entry(dpn->dpname, ne, -1, i ? 0 : 1)) { - X509_NAME_free(dpn->dpname); - dpn->dpname = nullptr; - return 0; - } - } - // generate cached encoding of name - if (i2d_X509_NAME(dpn->dpname, nullptr) < 0) { - X509_NAME_free(dpn->dpname); - dpn->dpname = nullptr; - return 0; - } - return 1; -} +} // namespace + +const X509V3_EXT_METHOD bssl::v3_crld = { + NID_crl_distribution_points, + 0, + ASN1_ITEM_ref(CRL_DIST_POINTS), + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + v2i_crld, + i2r_crldp, + nullptr, + nullptr, +}; + +const X509V3_EXT_METHOD bssl::v3_freshest_crl = { + NID_freshest_crl, 0, ASN1_ITEM_ref(CRL_DIST_POINTS), + nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, + nullptr, v2i_crld, i2r_crldp, + nullptr, nullptr, +}; + +const X509V3_EXT_METHOD bssl::v3_idp = { + NID_issuing_distribution_point, + X509V3_EXT_MULTILINE, + ASN1_ITEM_ref(ISSUING_DIST_POINT), + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + v2i_idp, + i2r_idp, + nullptr, + nullptr, +}; diff --git a/third_party/boringssl/src/crypto/x509/v3_enum.cc b/third_party/boringssl/src/crypto/x509/v3_enum.cc index 41440fe..524761e 100644 --- a/third_party/boringssl/src/crypto/x509/v3_enum.cc +++ b/third_party/boringssl/src/crypto/x509/v3_enum.cc @@ -24,9 +24,11 @@ using namespace bssl; +namespace { + typedef BIT_STRING_BITNAME ENUMERATED_NAMES; -static const ENUMERATED_NAMES crl_reasons[] = { +const ENUMERATED_NAMES crl_reasons[] = { {CRL_REASON_UNSPECIFIED, "Unspecified", "unspecified"}, {CRL_REASON_KEY_COMPROMISE, "Key Compromise", "keyCompromise"}, {CRL_REASON_CA_COMPROMISE, "CA Compromise", "CACompromise"}, @@ -42,8 +44,7 @@ static const ENUMERATED_NAMES crl_reasons[] = { {CRL_REASON_AA_COMPROMISE, "AA Compromise", "AACompromise"}, {-1, nullptr, nullptr}}; -static char *i2s_ASN1_ENUMERATED_TABLE(const X509V3_EXT_METHOD *method, - void *ext) { +char *i2s_ASN1_ENUMERATED_TABLE(const X509V3_EXT_METHOD *method, void *ext) { const ASN1_ENUMERATED *e = reinterpret_cast(ext); long strval = ASN1_ENUMERATED_get(e); for (const ENUMERATED_NAMES *enam = @@ -56,6 +57,8 @@ static char *i2s_ASN1_ENUMERATED_TABLE(const X509V3_EXT_METHOD *method, return i2s_ASN1_ENUMERATED(method, e); } +} // namespace + const X509V3_EXT_METHOD bssl::v3_crl_reason = { NID_crl_reason, 0, diff --git a/third_party/boringssl/src/crypto/x509/v3_extku.cc b/third_party/boringssl/src/crypto/x509/v3_extku.cc index 60c6238..46e6f11 100644 --- a/third_party/boringssl/src/crypto/x509/v3_extku.cc +++ b/third_party/boringssl/src/crypto/x509/v3_extku.cc @@ -25,37 +25,17 @@ using namespace bssl; -static void *v2i_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval); -static STACK_OF(CONF_VALUE) *i2v_EXTENDED_KEY_USAGE( - const X509V3_EXT_METHOD *method, void *eku, STACK_OF(CONF_VALUE) *extlist); - -const X509V3_EXT_METHOD bssl::v3_ext_ku = { - NID_ext_key_usage, - 0, - ASN1_ITEM_ref(EXTENDED_KEY_USAGE), - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - i2v_EXTENDED_KEY_USAGE, - v2i_EXTENDED_KEY_USAGE, - nullptr, - nullptr, - nullptr, -}; - ASN1_ITEM_TEMPLATE(EXTENDED_KEY_USAGE) = ASN1_EX_TEMPLATE_TYPE( ASN1_TFLG_SEQUENCE_OF, 0, EXTENDED_KEY_USAGE, ASN1_OBJECT) ASN1_ITEM_TEMPLATE_END(EXTENDED_KEY_USAGE) IMPLEMENT_ASN1_FUNCTIONS_const(EXTENDED_KEY_USAGE) -static STACK_OF(CONF_VALUE) *i2v_EXTENDED_KEY_USAGE( - const X509V3_EXT_METHOD *method, void *a, STACK_OF(CONF_VALUE) *ext_list) { +namespace { + +STACK_OF(CONF_VALUE) *i2v_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD *method, + void *a, + STACK_OF(CONF_VALUE) *ext_list) { const EXTENDED_KEY_USAGE *eku = reinterpret_cast(a); for (size_t i = 0; i < sk_ASN1_OBJECT_num(eku); i++) { @@ -67,9 +47,9 @@ static STACK_OF(CONF_VALUE) *i2v_EXTENDED_KEY_USAGE( return ext_list; } -static void *v2i_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval) { +void *v2i_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD *method, + const X509V3_CTX *ctx, + const STACK_OF(CONF_VALUE) *nval) { EXTENDED_KEY_USAGE *extku = sk_ASN1_OBJECT_new_null(); if (extku == nullptr) { return nullptr; @@ -95,3 +75,22 @@ static void *v2i_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD *method, return extku; } + +} // namespace + +const X509V3_EXT_METHOD bssl::v3_ext_ku = { + NID_ext_key_usage, + 0, + ASN1_ITEM_ref(EXTENDED_KEY_USAGE), + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + i2v_EXTENDED_KEY_USAGE, + v2i_EXTENDED_KEY_USAGE, + nullptr, + nullptr, + nullptr, +}; diff --git a/third_party/boringssl/src/crypto/x509/v3_genn.cc b/third_party/boringssl/src/crypto/x509/v3_genn.cc index 67a0743..1f0c9de 100644 --- a/third_party/boringssl/src/crypto/x509/v3_genn.cc +++ b/third_party/boringssl/src/crypto/x509/v3_genn.cc @@ -74,16 +74,19 @@ IMPLEMENT_ASN1_FUNCTIONS_const(GENERAL_NAMES) IMPLEMENT_ASN1_DUP_FUNCTION_const(GENERAL_NAME) -static int edipartyname_cmp(const EDIPARTYNAME *a, const EDIPARTYNAME *b) { - // nameAssigner is optional and may be NULL. - if (a->nameAssigner == nullptr) { - if (b->nameAssigner != nullptr) { - return -1; +namespace { + +int edipartyname_cmp(const EDIPARTYNAME *a, const EDIPARTYNAME *b) { + // nameAssigner is optional and may be NULL. An absent nameAssigner sorts + // before a present one. + if (a->nameAssigner == nullptr || b->nameAssigner == nullptr) { + if (a->nameAssigner != b->nameAssigner) { + return a->nameAssigner == nullptr ? -1 : 1; } } else { - if (b->nameAssigner == nullptr || - ASN1_STRING_cmp(a->nameAssigner, b->nameAssigner) != 0) { - return -1; + int ret = ASN1_STRING_cmp(a->nameAssigner, b->nameAssigner); + if (ret != 0) { + return ret; } } @@ -91,26 +94,21 @@ static int edipartyname_cmp(const EDIPARTYNAME *a, const EDIPARTYNAME *b) { return ASN1_STRING_cmp(a->partyName, b->partyName); } -// Returns 0 if they are equal, != 0 otherwise. -static int othername_cmp(const OTHERNAME *a, const OTHERNAME *b) { - int result = -1; - - if (!a || !b) { - return -1; - } +// a and b are guaranteed to be non-NULL. +int othername_cmp(const OTHERNAME *a, const OTHERNAME *b) { // Check their type first. - if ((result = OBJ_cmp(a->type_id, b->type_id)) != 0) { - return result; + int ret = OBJ_cmp(a->type_id, b->type_id); + if (ret != 0) { + return ret; } - // Check the value. - result = ASN1_TYPE_cmp(a->value, b->value); - return result; + return ASN1_TYPE_cmp(a->value, b->value); } -// Returns 0 if they are equal, != 0 otherwise. +} // namespace + int bssl::GENERAL_NAME_cmp(const GENERAL_NAME *a, const GENERAL_NAME *b) { - if (!a || !b || a->type != b->type) { - return -1; + if (a->type != b->type) { + return a->type < b->type ? -1 : 1; } switch (a->type) { @@ -138,7 +136,8 @@ int bssl::GENERAL_NAME_cmp(const GENERAL_NAME *a, const GENERAL_NAME *b) { return OBJ_cmp(a->d.rid, b->d.rid); } - return -1; + // Unreachable: `type` is always one of the CHOICE arms above. + abort(); } void GENERAL_NAME_set0_value(GENERAL_NAME *a, int type, void *value) { diff --git a/third_party/boringssl/src/crypto/x509/v3_ia5.cc b/third_party/boringssl/src/crypto/x509/v3_ia5.cc index a6b8aed..a51ae74 100644 --- a/third_party/boringssl/src/crypto/x509/v3_ia5.cc +++ b/third_party/boringssl/src/crypto/x509/v3_ia5.cc @@ -28,7 +28,9 @@ using namespace bssl; -static char *i2s_ASN1_IA5STRING(const X509V3_EXT_METHOD *method, void *ext) { +namespace { + +char *i2s_ASN1_IA5STRING(const X509V3_EXT_METHOD *method, void *ext) { const ASN1_IA5STRING *ia5 = reinterpret_cast(ext); char *tmp; if (!ia5 || !ia5->length) { @@ -42,8 +44,8 @@ static char *i2s_ASN1_IA5STRING(const X509V3_EXT_METHOD *method, void *ext) { return tmp; } -static void *s2i_ASN1_IA5STRING(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, const char *str) { +void *s2i_ASN1_IA5STRING(const X509V3_EXT_METHOD *method, + const X509V3_CTX *ctx, const char *str) { ASN1_IA5STRING *ia5; if (!str) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_ARGUMENT); @@ -61,6 +63,8 @@ static void *s2i_ASN1_IA5STRING(const X509V3_EXT_METHOD *method, return nullptr; } +} // namespace + #define EXT_IA5STRING(nid) \ { \ nid, 0, ASN1_ITEM_ref(ASN1_IA5STRING), 0, 0, 0, 0, i2s_ASN1_IA5STRING, \ diff --git a/third_party/boringssl/src/crypto/x509/v3_info.cc b/third_party/boringssl/src/crypto/x509/v3_info.cc index 21d4638..be017f5 100644 --- a/third_party/boringssl/src/crypto/x509/v3_info.cc +++ b/third_party/boringssl/src/crypto/x509/v3_info.cc @@ -28,46 +28,6 @@ using namespace bssl; -static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS( - const X509V3_EXT_METHOD *method, void *ext, STACK_OF(CONF_VALUE) *ret); -static void *v2i_AUTHORITY_INFO_ACCESS(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval); - -const X509V3_EXT_METHOD bssl::v3_info = { - NID_info_access, - X509V3_EXT_MULTILINE, - ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS), - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - i2v_AUTHORITY_INFO_ACCESS, - v2i_AUTHORITY_INFO_ACCESS, - nullptr, - nullptr, - nullptr, -}; - -const X509V3_EXT_METHOD bssl::v3_sinfo = { - NID_sinfo_access, - X509V3_EXT_MULTILINE, - ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS), - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - i2v_AUTHORITY_INFO_ACCESS, - v2i_AUTHORITY_INFO_ACCESS, - nullptr, - nullptr, - nullptr, -}; - ASN1_SEQUENCE(ACCESS_DESCRIPTION) = { ASN1_SIMPLE(ACCESS_DESCRIPTION, method, ASN1_OBJECT), ASN1_SIMPLE(ACCESS_DESCRIPTION, location, GENERAL_NAME), @@ -81,8 +41,11 @@ ASN1_ITEM_TEMPLATE_END(AUTHORITY_INFO_ACCESS) IMPLEMENT_ASN1_FUNCTIONS_const(AUTHORITY_INFO_ACCESS) -static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS( - const X509V3_EXT_METHOD *method, void *ext, STACK_OF(CONF_VALUE) *ret) { +namespace { + +STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS(const X509V3_EXT_METHOD *method, + void *ext, + STACK_OF(CONF_VALUE) *ret) { const AUTHORITY_INFO_ACCESS *ainfo = reinterpret_cast(ext); ACCESS_DESCRIPTION *desc; @@ -120,9 +83,9 @@ static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS( return nullptr; } -static void *v2i_AUTHORITY_INFO_ACCESS(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval) { +void *v2i_AUTHORITY_INFO_ACCESS(const X509V3_EXT_METHOD *method, + const X509V3_CTX *ctx, + const STACK_OF(CONF_VALUE) *nval) { UniquePtr ainfo(sk_ACCESS_DESCRIPTION_new_null()); if (ainfo == nullptr) { return nullptr; @@ -160,3 +123,39 @@ static void *v2i_AUTHORITY_INFO_ACCESS(const X509V3_EXT_METHOD *method, } return ainfo.release(); } + +} // namespace + +const X509V3_EXT_METHOD bssl::v3_info = { + NID_info_access, + X509V3_EXT_MULTILINE, + ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS), + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + i2v_AUTHORITY_INFO_ACCESS, + v2i_AUTHORITY_INFO_ACCESS, + nullptr, + nullptr, + nullptr, +}; + +const X509V3_EXT_METHOD bssl::v3_sinfo = { + NID_sinfo_access, + X509V3_EXT_MULTILINE, + ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS), + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + i2v_AUTHORITY_INFO_ACCESS, + v2i_AUTHORITY_INFO_ACCESS, + nullptr, + nullptr, + nullptr, +}; diff --git a/third_party/boringssl/src/crypto/x509/v3_int.cc b/third_party/boringssl/src/crypto/x509/v3_int.cc index 7d072d1..608e565 100644 --- a/third_party/boringssl/src/crypto/x509/v3_int.cc +++ b/third_party/boringssl/src/crypto/x509/v3_int.cc @@ -22,15 +22,19 @@ using namespace bssl; -static char *i2s_ASN1_INTEGER_cb(const X509V3_EXT_METHOD *method, void *ext) { +namespace { + +char *i2s_ASN1_INTEGER_cb(const X509V3_EXT_METHOD *method, void *ext) { return i2s_ASN1_INTEGER(method, reinterpret_cast(ext)); } -static void *s2i_asn1_int(const X509V3_EXT_METHOD *meth, const X509V3_CTX *ctx, - const char *value) { +void *s2i_asn1_int(const X509V3_EXT_METHOD *meth, const X509V3_CTX *ctx, + const char *value) { return s2i_ASN1_INTEGER(meth, value); } +} // namespace + const X509V3_EXT_METHOD bssl::v3_crl_num = { NID_crl_number, 0, diff --git a/third_party/boringssl/src/crypto/x509/v3_lib.cc b/third_party/boringssl/src/crypto/x509/v3_lib.cc index 676e38c..a2cf9e4 100644 --- a/third_party/boringssl/src/crypto/x509/v3_lib.cc +++ b/third_party/boringssl/src/crypto/x509/v3_lib.cc @@ -29,10 +29,14 @@ using namespace bssl; +namespace { + // This is indirected though a pointer to avoid a global destructor. If we ever // add bssl::NoDestructor, we can avoid this, but this API is already // problematic and not thread-safe. -static bssl::Vector *ext_list = nullptr; +bssl::Vector *ext_list = nullptr; + +} // namespace int X509V3_EXT_add(X509V3_EXT_METHOD *ext) { // We only support `ASN1_ITEM`-based extensions. diff --git a/third_party/boringssl/src/crypto/x509/v3_ocsp.cc b/third_party/boringssl/src/crypto/x509/v3_ocsp.cc index f70ba2e..f9ba151 100644 --- a/third_party/boringssl/src/crypto/x509/v3_ocsp.cc +++ b/third_party/boringssl/src/crypto/x509/v3_ocsp.cc @@ -25,13 +25,33 @@ using namespace bssl; // OCSP extensions and a couple of CRL entry extensions -static int i2r_ocsp_acutoff(const X509V3_EXT_METHOD *method, void *nonce, - BIO *out, int indent); +namespace { -static int i2r_ocsp_nocheck(const X509V3_EXT_METHOD *method, void *nocheck, - BIO *out, int indent); -static void *s2i_ocsp_nocheck(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, const char *str); +int i2r_ocsp_acutoff(const X509V3_EXT_METHOD *method, void *cutoff, BIO *bp, + int ind) { + if (BIO_printf(bp, "%*s", ind, "") <= 0) { + return 0; + } + if (!ASN1_GENERALIZEDTIME_print( + bp, reinterpret_cast(cutoff))) { + return 0; + } + return 1; +} + +// Nocheck is just a single NULL. Don't print anything and always set it + +int i2r_ocsp_nocheck(const X509V3_EXT_METHOD *method, void *nocheck, BIO *out, + int indent) { + return 1; +} + +void *s2i_ocsp_nocheck(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, + const char *str) { + return ASN1_NULL_new(); +} + +} // namespace const X509V3_EXT_METHOD bssl::v3_crl_invdate = { NID_invalidity_date, @@ -66,27 +86,3 @@ const X509V3_EXT_METHOD bssl::v3_ocsp_nocheck = { nullptr, nullptr, }; - -static int i2r_ocsp_acutoff(const X509V3_EXT_METHOD *method, void *cutoff, - BIO *bp, int ind) { - if (BIO_printf(bp, "%*s", ind, "") <= 0) { - return 0; - } - if (!ASN1_GENERALIZEDTIME_print( - bp, reinterpret_cast(cutoff))) { - return 0; - } - return 1; -} - -// Nocheck is just a single NULL. Don't print anything and always set it - -static int i2r_ocsp_nocheck(const X509V3_EXT_METHOD *method, void *nocheck, - BIO *out, int indent) { - return 1; -} - -static void *s2i_ocsp_nocheck(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, const char *str) { - return ASN1_NULL_new(); -} diff --git a/third_party/boringssl/src/crypto/x509/v3_pcons.cc b/third_party/boringssl/src/crypto/x509/v3_pcons.cc index f74d89c..eaf7ef8 100644 --- a/third_party/boringssl/src/crypto/x509/v3_pcons.cc +++ b/third_party/boringssl/src/crypto/x509/v3_pcons.cc @@ -27,29 +27,6 @@ using namespace bssl; -static STACK_OF(CONF_VALUE) *i2v_POLICY_CONSTRAINTS( - const X509V3_EXT_METHOD *method, void *bcons, - STACK_OF(CONF_VALUE) *extlist); -static void *v2i_POLICY_CONSTRAINTS(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *values); - -const X509V3_EXT_METHOD bssl::v3_policy_constraints = { - NID_policy_constraints, - 0, - ASN1_ITEM_ref(POLICY_CONSTRAINTS), - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - i2v_POLICY_CONSTRAINTS, - v2i_POLICY_CONSTRAINTS, - nullptr, - nullptr, - nullptr}; - ASN1_SEQUENCE(POLICY_CONSTRAINTS) = { ASN1_IMP_OPT(POLICY_CONSTRAINTS, requireExplicitPolicy, ASN1_INTEGER, 0), ASN1_IMP_OPT(POLICY_CONSTRAINTS, inhibitPolicyMapping, ASN1_INTEGER, 1), @@ -57,8 +34,11 @@ ASN1_SEQUENCE(POLICY_CONSTRAINTS) = { IMPLEMENT_ASN1_ALLOC_FUNCTIONS(POLICY_CONSTRAINTS) -static STACK_OF(CONF_VALUE) *i2v_POLICY_CONSTRAINTS( - const X509V3_EXT_METHOD *method, void *a, STACK_OF(CONF_VALUE) *extlist) { +namespace { + +STACK_OF(CONF_VALUE) *i2v_POLICY_CONSTRAINTS(const X509V3_EXT_METHOD *method, + void *a, + STACK_OF(CONF_VALUE) *extlist) { const POLICY_CONSTRAINTS *pcons = reinterpret_cast(a); X509V3_add_value_int("Require Explicit Policy", pcons->requireExplicitPolicy, &extlist); @@ -67,9 +47,9 @@ static STACK_OF(CONF_VALUE) *i2v_POLICY_CONSTRAINTS( return extlist; } -static void *v2i_POLICY_CONSTRAINTS(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *values) { +void *v2i_POLICY_CONSTRAINTS(const X509V3_EXT_METHOD *method, + const X509V3_CTX *ctx, + const STACK_OF(CONF_VALUE) *values) { POLICY_CONSTRAINTS *pcons = nullptr; if (!(pcons = POLICY_CONSTRAINTS_new())) { return nullptr; @@ -100,3 +80,21 @@ static void *v2i_POLICY_CONSTRAINTS(const X509V3_EXT_METHOD *method, POLICY_CONSTRAINTS_free(pcons); return nullptr; } + +} // namespace + +const X509V3_EXT_METHOD bssl::v3_policy_constraints = { + NID_policy_constraints, + 0, + ASN1_ITEM_ref(POLICY_CONSTRAINTS), + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + i2v_POLICY_CONSTRAINTS, + v2i_POLICY_CONSTRAINTS, + nullptr, + nullptr, + nullptr}; diff --git a/third_party/boringssl/src/crypto/x509/v3_pmaps.cc b/third_party/boringssl/src/crypto/x509/v3_pmaps.cc index bb5fa50..ab262d0 100644 --- a/third_party/boringssl/src/crypto/x509/v3_pmaps.cc +++ b/third_party/boringssl/src/crypto/x509/v3_pmaps.cc @@ -25,29 +25,6 @@ using namespace bssl; -static void *v2i_POLICY_MAPPINGS(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval); -static STACK_OF(CONF_VALUE) *i2v_POLICY_MAPPINGS( - const X509V3_EXT_METHOD *method, void *pmps, STACK_OF(CONF_VALUE) *extlist); - -const X509V3_EXT_METHOD bssl::v3_policy_mappings = { - NID_policy_mappings, - 0, - ASN1_ITEM_ref(POLICY_MAPPINGS), - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - i2v_POLICY_MAPPINGS, - v2i_POLICY_MAPPINGS, - nullptr, - nullptr, - nullptr, -}; - ASN1_SEQUENCE(POLICY_MAPPING) = { ASN1_SIMPLE(POLICY_MAPPING, issuerDomainPolicy, ASN1_OBJECT), ASN1_SIMPLE(POLICY_MAPPING, subjectDomainPolicy, ASN1_OBJECT), @@ -59,8 +36,11 @@ ASN1_ITEM_TEMPLATE_END(POLICY_MAPPINGS) IMPLEMENT_ASN1_ALLOC_FUNCTIONS(POLICY_MAPPING) -static STACK_OF(CONF_VALUE) *i2v_POLICY_MAPPINGS( - const X509V3_EXT_METHOD *method, void *a, STACK_OF(CONF_VALUE) *ext_list) { +namespace { + +STACK_OF(CONF_VALUE) *i2v_POLICY_MAPPINGS(const X509V3_EXT_METHOD *method, + void *a, + STACK_OF(CONF_VALUE) *ext_list) { const POLICY_MAPPINGS *pmaps = reinterpret_cast(a); for (size_t i = 0; i < sk_POLICY_MAPPING_num(pmaps); i++) { const POLICY_MAPPING *pmap = sk_POLICY_MAPPING_value(pmaps, i); @@ -72,9 +52,9 @@ static STACK_OF(CONF_VALUE) *i2v_POLICY_MAPPINGS( return ext_list; } -static void *v2i_POLICY_MAPPINGS(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval) { +void *v2i_POLICY_MAPPINGS(const X509V3_EXT_METHOD *method, + const X509V3_CTX *ctx, + const STACK_OF(CONF_VALUE) *nval) { POLICY_MAPPINGS *pmaps = sk_POLICY_MAPPING_new_null(); if (pmaps == nullptr) { return nullptr; @@ -108,3 +88,22 @@ static void *v2i_POLICY_MAPPINGS(const X509V3_EXT_METHOD *method, sk_POLICY_MAPPING_pop_free(pmaps, POLICY_MAPPING_free); return nullptr; } + +} // namespace + +const X509V3_EXT_METHOD bssl::v3_policy_mappings = { + NID_policy_mappings, + 0, + ASN1_ITEM_ref(POLICY_MAPPINGS), + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + i2v_POLICY_MAPPINGS, + v2i_POLICY_MAPPINGS, + nullptr, + nullptr, + nullptr, +}; diff --git a/third_party/boringssl/src/crypto/x509/v3_prn.cc b/third_party/boringssl/src/crypto/x509/v3_prn.cc index c2da548..ecf8c5d 100644 --- a/third_party/boringssl/src/crypto/x509/v3_prn.cc +++ b/third_party/boringssl/src/crypto/x509/v3_prn.cc @@ -23,12 +23,11 @@ // Extension printing routines -static int unknown_ext_print(BIO *out, const X509_EXTENSION *ext, - unsigned long flag, int indent, int supported); +namespace { // Print out a name+value stack -static void X509V3_EXT_val_prn(BIO *out, const STACK_OF(CONF_VALUE) *val, - int indent, int ml) { +void X509V3_EXT_val_prn(BIO *out, const STACK_OF(CONF_VALUE) *val, int indent, + int ml) { if (!val) { return; } @@ -58,6 +57,34 @@ static void X509V3_EXT_val_prn(BIO *out, const STACK_OF(CONF_VALUE) *val, } } +int unknown_ext_print(BIO *out, const X509_EXTENSION *ext, unsigned long flag, + int indent, int supported) { + switch (flag & X509V3_EXT_UNKNOWN_MASK) { + case X509V3_EXT_DEFAULT: + return 0; + + case X509V3_EXT_ERROR_UNKNOWN: + if (supported) { + BIO_printf(out, "%*s", indent, ""); + } else { + BIO_printf(out, "%*s", indent, ""); + } + return 1; + + case X509V3_EXT_PARSE_UNKNOWN: + case X509V3_EXT_DUMP_UNKNOWN: { + const ASN1_STRING *data = X509_EXTENSION_get_data(ext); + return BIO_hexdump(out, ASN1_STRING_get0_data(data), + ASN1_STRING_length(data), indent); + } + + default: + return 1; + } +} + +} // namespace + // Main routine: print out a general extension int X509V3_EXT_print(BIO *out, const X509_EXTENSION *ext, unsigned long flag, @@ -144,32 +171,6 @@ int X509V3_extensions_print(BIO *bp, const char *title, return 1; } -static int unknown_ext_print(BIO *out, const X509_EXTENSION *ext, - unsigned long flag, int indent, int supported) { - switch (flag & X509V3_EXT_UNKNOWN_MASK) { - case X509V3_EXT_DEFAULT: - return 0; - - case X509V3_EXT_ERROR_UNKNOWN: - if (supported) { - BIO_printf(out, "%*s", indent, ""); - } else { - BIO_printf(out, "%*s", indent, ""); - } - return 1; - - case X509V3_EXT_PARSE_UNKNOWN: - case X509V3_EXT_DUMP_UNKNOWN: { - const ASN1_STRING *data = X509_EXTENSION_get_data(ext); - return BIO_hexdump(out, ASN1_STRING_get0_data(data), - ASN1_STRING_length(data), indent); - } - - default: - return 1; - } -} - int X509V3_EXT_print_fp(FILE *fp, const X509_EXTENSION *ext, int flag, int indent) { BIO *bio_tmp; diff --git a/third_party/boringssl/src/crypto/x509/v3_purp.cc b/third_party/boringssl/src/crypto/x509/v3_purp.cc index d832c5b..0ffe349 100644 --- a/third_party/boringssl/src/crypto/x509/v3_purp.cc +++ b/third_party/boringssl/src/crypto/x509/v3_purp.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -43,29 +44,132 @@ struct x509_purpose_st { ((FromOpaque(x)->ex_flags & EXFLAG_XKUSAGE) && \ !(FromOpaque(x)->ex_xkusage & (usage))) -static int check_ca(const X509 *x); -static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x, - int ca); -static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x, - int ca); -static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x, - int ca); -static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x, - int ca); -static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x, - int ca); -static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x, - int ca); -static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x, - int ca); -static int no_check(const X509_PURPOSE *xp, const X509 *x, int ca); +namespace { + +int setup_crldp(const X509 *x) { + int j; + auto *impl = FromOpaque(x); + impl->crldp.reset(reinterpret_cast( + X509_get_ext_d2i(x, NID_crl_distribution_points, &j, nullptr))); + if (impl->crldp == nullptr && j != -1) { + return 0; + } + return 1; +} + +// check_ca returns one if `x` should be considered a CA certificate and zero +// otherwise. +int check_ca(const X509 *x) { + // keyUsage if present should allow cert signing + if (ku_reject(x, X509v3_KU_KEY_CERT_SIGN)) { + return 0; + } + // Version 1 certificates are considered CAs and don't have extensions. + const auto *impl = FromOpaque(x); + if ((impl->ex_flags & V1_ROOT) == V1_ROOT) { + return 1; + } + // Otherwise, it's only a CA if basicConstraints says so. + return ((impl->ex_flags & EXFLAG_BCONS) && (impl->ex_flags & EXFLAG_CA)); +} + +// check_purpose returns one if `x` is a valid part of a certificate path for +// extended key usage `required_xku` and at least one of key usages in +// `required_kus`. `ca` indicates whether `x` is a CA or end-entity certificate. +int check_purpose(const X509 *x, int ca, int required_xku, int required_kus) { + // Check extended key usage on the entire chain. + if (required_xku != 0 && xku_reject(x, required_xku)) { + return 0; + } + + // Check key usages only on the end-entity certificate. + return ca || !ku_reject(x, required_kus); +} + +int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x, int ca) { + // We need to do digital signatures or key agreement. + // + // TODO(davidben): We do not implement any TLS client certificate modes based + // on key agreement. + return check_purpose(x, ca, XKU_SSL_CLIENT, + X509v3_KU_DIGITAL_SIGNATURE | X509v3_KU_KEY_AGREEMENT); +} + +// Key usage needed for TLS/SSL server: digital signature, encipherment or +// key agreement. The ssl code can check this more thoroughly for individual +// key types. +#define X509v3_KU_TLS \ + (X509v3_KU_DIGITAL_SIGNATURE | X509v3_KU_KEY_ENCIPHERMENT | \ + X509v3_KU_KEY_AGREEMENT) + +int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x, int ca) { + return check_purpose(x, ca, XKU_SSL_SERVER, X509v3_KU_TLS); +} + +int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x, int ca) { + // We need to encipher or Netscape complains. + return check_purpose(x, ca, XKU_SSL_SERVER, X509v3_KU_KEY_ENCIPHERMENT); +} + +int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x, int ca) { + return check_purpose(x, ca, XKU_SMIME, + X509v3_KU_DIGITAL_SIGNATURE | X509v3_KU_NON_REPUDIATION); +} + +int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x, int ca) { + return check_purpose(x, ca, XKU_SMIME, X509v3_KU_KEY_ENCIPHERMENT); +} + +int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x, int ca) { + return check_purpose(x, ca, /*required_xku=*/0, X509v3_KU_CRL_SIGN); +} + +int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x, + int ca) { + if (ca) { + return 1; + } + + // Check the optional key usage field: + // if Key Usage is present, it must be one of digitalSignature + // and/or nonRepudiation (other values are not consistent and shall + // be rejected). + const auto *impl = FromOpaque(x); + if ((impl->ex_flags & EXFLAG_KUSAGE) && + ((impl->ex_kusage & + ~(X509v3_KU_NON_REPUDIATION | X509v3_KU_DIGITAL_SIGNATURE)) || + !(impl->ex_kusage & + (X509v3_KU_NON_REPUDIATION | X509v3_KU_DIGITAL_SIGNATURE)))) { + return 0; + } + + // Only time stamp key usage is permitted and it's required. + // + // TODO(davidben): Should we check EKUs up the chain like the other cases? + if (!(impl->ex_flags & EXFLAG_XKUSAGE) || impl->ex_xkusage != XKU_TIMESTAMP) { + return 0; + } + + // Extended Key Usage MUST be critical + int i_ext = X509_get_ext_by_NID(x, NID_ext_key_usage, -1); + if (i_ext >= 0) { + const X509_EXTENSION *ext = X509_get_ext(x, i_ext); + if (!X509_EXTENSION_get_critical(ext)) { + return 0; + } + } + + return 1; +} + +int no_check(const X509_PURPOSE *xp, const X509 *x, int ca) { return 1; } // X509_TRUST_NONE is not a valid `X509_TRUST_*` constant. It is used by // `X509_PURPOSE_ANY` to indicate that it has no corresponding trust type and // cannot be used with `X509_STORE_CTX_set_purpose`. #define X509_TRUST_NONE (-1) -static const X509_PURPOSE xstandard[] = { +const X509_PURPOSE xstandard[] = { {X509_PURPOSE_SSL_CLIENT, X509_TRUST_SSL_CLIENT, check_purpose_ssl_client, "sslclient"}, {X509_PURPOSE_SSL_SERVER, X509_TRUST_SSL_SERVER, check_purpose_ssl_server, @@ -86,7 +190,9 @@ static const X509_PURPOSE xstandard[] = { "timestampsign"}, }; -int X509_check_purpose(X509 *x, int id, int ca) { +} // namespace + +int X509_check_purpose(const X509 *x, int id, int ca) { // This differs from OpenSSL, which uses -1 to indicate a fatal error and 0 to // indicate an invalid certificate. BoringSSL uses 0 for both. if (!x509v3_cache_extensions(x)) { @@ -142,46 +248,11 @@ int X509_supported_extension(const X509_EXTENSION *ex) { nid == NID_policy_constraints || // nid == NID_name_constraints || // nid == NID_policy_mappings || // - nid == NID_inhibit_any_policy || - nid == NID_pe_mtcCertificationAuthority_draft; -} - -static int setup_dp(X509 *x, DIST_POINT *dp) { - if (!dp->distpoint || (dp->distpoint->type != 1)) { - return 1; - } - X509_NAME *iname = nullptr; - for (size_t i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) { - GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i); - if (gen->type == GEN_DIRNAME) { - iname = gen->d.directoryName; - break; - } - } - if (!iname) { - iname = X509_get_issuer_name(x); - } - - return DIST_POINT_set_dpname(dp->distpoint, iname); + nid == NID_inhibit_any_policy || // + nid == NID_pe_mtcCertificationAuthority_SHA256; } -static int setup_crldp(X509 *x) { - int j; - auto *impl = FromOpaque(x); - impl->crldp.reset(reinterpret_cast( - X509_get_ext_d2i(x, NID_crl_distribution_points, &j, nullptr))); - if (impl->crldp == nullptr && j != -1) { - return 0; - } - for (size_t i = 0; i < sk_DIST_POINT_num(impl->crldp.get()); i++) { - if (!setup_dp(x, sk_DIST_POINT_value(impl->crldp.get(), i))) { - return 0; - } - } - return 1; -} - -int bssl::x509v3_cache_extensions(X509 *x) { +int bssl::x509v3_cache_extensions(const X509 *x) { BASIC_CONSTRAINTS *bs; ASN1_BIT_STRING *usage; EXTENDED_KEY_USAGE *extusage; @@ -348,134 +419,20 @@ int bssl::x509v3_cache_extensions(X509 *x) { return (impl->ex_flags & EXFLAG_INVALID) == 0; } -// check_ca returns one if `x` should be considered a CA certificate and zero -// otherwise. -static int check_ca(const X509 *x) { - // keyUsage if present should allow cert signing - if (ku_reject(x, X509v3_KU_KEY_CERT_SIGN)) { - return 0; - } - // Version 1 certificates are considered CAs and don't have extensions. - const auto *impl = FromOpaque(x); - if ((impl->ex_flags & V1_ROOT) == V1_ROOT) { - return 1; - } - // Otherwise, it's only a CA if basicConstraints says so. - return ((impl->ex_flags & EXFLAG_BCONS) && (impl->ex_flags & EXFLAG_CA)); -} - int X509_check_ca(const X509 *x) { - if (!x509v3_cache_extensions(const_cast(x))) { + if (!x509v3_cache_extensions(x)) { return 0; } return check_ca(x); } -// check_purpose returns one if `x` is a valid part of a certificate path for -// extended key usage `required_xku` and at least one of key usages in -// `required_kus`. `ca` indicates whether `x` is a CA or end-entity certificate. -static int check_purpose(const X509 *x, int ca, int required_xku, - int required_kus) { - // Check extended key usage on the entire chain. - if (required_xku != 0 && xku_reject(x, required_xku)) { - return 0; - } - - // Check key usages only on the end-entity certificate. - return ca || !ku_reject(x, required_kus); -} - -static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x, - int ca) { - // We need to do digital signatures or key agreement. - // - // TODO(davidben): We do not implement any TLS client certificate modes based - // on key agreement. - return check_purpose(x, ca, XKU_SSL_CLIENT, - X509v3_KU_DIGITAL_SIGNATURE | X509v3_KU_KEY_AGREEMENT); -} - -// Key usage needed for TLS/SSL server: digital signature, encipherment or -// key agreement. The ssl code can check this more thoroughly for individual -// key types. -#define X509v3_KU_TLS \ - (X509v3_KU_DIGITAL_SIGNATURE | X509v3_KU_KEY_ENCIPHERMENT | \ - X509v3_KU_KEY_AGREEMENT) - -static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x, - int ca) { - return check_purpose(x, ca, XKU_SSL_SERVER, X509v3_KU_TLS); -} - -static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x, - int ca) { - // We need to encipher or Netscape complains. - return check_purpose(x, ca, XKU_SSL_SERVER, X509v3_KU_KEY_ENCIPHERMENT); -} - -static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x, - int ca) { - return check_purpose(x, ca, XKU_SMIME, - X509v3_KU_DIGITAL_SIGNATURE | X509v3_KU_NON_REPUDIATION); -} - -static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x, - int ca) { - return check_purpose(x, ca, XKU_SMIME, X509v3_KU_KEY_ENCIPHERMENT); -} - -static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x, - int ca) { - return check_purpose(x, ca, /*required_xku=*/0, X509v3_KU_CRL_SIGN); -} - -static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x, - int ca) { - if (ca) { - return 1; - } - - // Check the optional key usage field: - // if Key Usage is present, it must be one of digitalSignature - // and/or nonRepudiation (other values are not consistent and shall - // be rejected). - const auto *impl = FromOpaque(x); - if ((impl->ex_flags & EXFLAG_KUSAGE) && - ((impl->ex_kusage & - ~(X509v3_KU_NON_REPUDIATION | X509v3_KU_DIGITAL_SIGNATURE)) || - !(impl->ex_kusage & - (X509v3_KU_NON_REPUDIATION | X509v3_KU_DIGITAL_SIGNATURE)))) { - return 0; - } - - // Only time stamp key usage is permitted and it's required. - // - // TODO(davidben): Should we check EKUs up the chain like the other cases? - if (!(impl->ex_flags & EXFLAG_XKUSAGE) || impl->ex_xkusage != XKU_TIMESTAMP) { - return 0; - } - - // Extended Key Usage MUST be critical - int i_ext = X509_get_ext_by_NID(x, NID_ext_key_usage, -1); - if (i_ext >= 0) { - const X509_EXTENSION *ext = X509_get_ext(x, i_ext); - if (!X509_EXTENSION_get_critical(ext)) { - return 0; - } - } - - return 1; -} - -static int no_check(const X509_PURPOSE *xp, const X509 *x, int ca) { return 1; } - int X509_check_issued(const X509 *issuer, const X509 *subject) { if (X509_NAME_cmp(X509_get_subject_name(issuer), X509_get_issuer_name(subject))) { return X509_V_ERR_SUBJECT_ISSUER_MISMATCH; } - if (!x509v3_cache_extensions(const_cast(issuer)) || - !x509v3_cache_extensions(const_cast(subject))) { + if (!x509v3_cache_extensions(issuer) || + !x509v3_cache_extensions(subject)) { return X509_V_ERR_UNSPECIFIED; } @@ -528,7 +485,7 @@ int bssl::X509_check_akid(const X509 *issuer, const AUTHORITY_KEYID *akid) { return X509_V_OK; } -uint32_t X509_get_extension_flags(X509 *x) { +uint32_t X509_get_extension_flags(const X509 *x) { // Ignore the return value. On failure, `impl->ex_flags` will include // `EXFLAG_INVALID`. x509v3_cache_extensions(x); @@ -536,7 +493,7 @@ uint32_t X509_get_extension_flags(X509 *x) { return impl->ex_flags; } -uint32_t X509_get_key_usage(X509 *x) { +uint32_t X509_get_key_usage(const X509 *x) { if (!x509v3_cache_extensions(x)) { return 0; } @@ -550,7 +507,7 @@ uint32_t X509_get_key_usage(X509 *x) { return UINT32_MAX; } -uint32_t X509_get_extended_key_usage(X509 *x) { +uint32_t X509_get_extended_key_usage(const X509 *x) { if (!x509v3_cache_extensions(x)) { return 0; } @@ -563,7 +520,7 @@ uint32_t X509_get_extended_key_usage(X509 *x) { return UINT32_MAX; } -const ASN1_OCTET_STRING *X509_get0_subject_key_id(X509 *x509) { +const ASN1_OCTET_STRING *X509_get0_subject_key_id(const X509 *x509) { if (!x509v3_cache_extensions(x509)) { return nullptr; } @@ -571,7 +528,7 @@ const ASN1_OCTET_STRING *X509_get0_subject_key_id(X509 *x509) { return impl->skid.get(); } -const ASN1_OCTET_STRING *X509_get0_authority_key_id(X509 *x509) { +const ASN1_OCTET_STRING *X509_get0_authority_key_id(const X509 *x509) { if (!x509v3_cache_extensions(x509)) { return nullptr; } @@ -579,7 +536,7 @@ const ASN1_OCTET_STRING *X509_get0_authority_key_id(X509 *x509) { return impl->akid != nullptr ? impl->akid->keyid : nullptr; } -const GENERAL_NAMES *X509_get0_authority_issuer(X509 *x509) { +const GENERAL_NAMES *X509_get0_authority_issuer(const X509 *x509) { if (!x509v3_cache_extensions(x509)) { return nullptr; } @@ -587,7 +544,7 @@ const GENERAL_NAMES *X509_get0_authority_issuer(X509 *x509) { return impl->akid != nullptr ? impl->akid->issuer : nullptr; } -const ASN1_INTEGER *X509_get0_authority_serial(X509 *x509) { +const ASN1_INTEGER *X509_get0_authority_serial(const X509 *x509) { auto *impl = FromOpaque(x509); if (!x509v3_cache_extensions(impl)) { return nullptr; @@ -595,7 +552,7 @@ const ASN1_INTEGER *X509_get0_authority_serial(X509 *x509) { return impl->akid != nullptr ? impl->akid->serial : nullptr; } -long X509_get_pathlen(X509 *x509) { +long X509_get_pathlen(const X509 *x509) { auto *impl = FromOpaque(x509); if (!x509v3_cache_extensions(x509) || (impl->ex_flags & EXFLAG_BCONS) == 0) { return -1; diff --git a/third_party/boringssl/src/crypto/x509/v3_skey.cc b/third_party/boringssl/src/crypto/x509/v3_skey.cc index 3eed1cc..841f679 100644 --- a/third_party/boringssl/src/crypto/x509/v3_skey.cc +++ b/third_party/boringssl/src/crypto/x509/v3_skey.cc @@ -27,45 +27,15 @@ using namespace bssl; -char *i2s_ASN1_OCTET_STRING(const X509V3_EXT_METHOD *method, - const ASN1_OCTET_STRING *oct) { - return x509v3_bytes_to_hex(oct->data, oct->length); -} +namespace { -ASN1_OCTET_STRING *s2i_ASN1_OCTET_STRING(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const char *str) { - size_t len; - uint8_t *data = x509v3_hex_to_bytes(str, &len); - ASN1_OCTET_STRING *oct; - if (data == nullptr) { - return nullptr; - } - if (len > INT_MAX) { - OPENSSL_PUT_ERROR(X509V3, ERR_R_OVERFLOW); - goto err; - } - - oct = ASN1_OCTET_STRING_new(); - if (oct == nullptr) { - goto err; - } - ASN1_STRING_set0(oct, data, (int)len); - return oct; - -err: - OPENSSL_free(data); - return nullptr; -} - -static char *i2s_ASN1_OCTET_STRING_cb(const X509V3_EXT_METHOD *method, - void *ext) { +char *i2s_ASN1_OCTET_STRING_cb(const X509V3_EXT_METHOD *method, void *ext) { return i2s_ASN1_OCTET_STRING(method, reinterpret_cast(ext)); } -static void *s2i_skey_id(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, - const char *str) { +void *s2i_skey_id(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, + const char *str) { ASN1_OCTET_STRING *oct; const ASN1_BIT_STRING *pk; unsigned char pkey_dig[EVP_MAX_MD_SIZE]; @@ -110,6 +80,39 @@ static void *s2i_skey_id(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, return nullptr; } +} // namespace + +char *i2s_ASN1_OCTET_STRING(const X509V3_EXT_METHOD *method, + const ASN1_OCTET_STRING *oct) { + return x509v3_bytes_to_hex(oct->data, oct->length); +} + +ASN1_OCTET_STRING *s2i_ASN1_OCTET_STRING(const X509V3_EXT_METHOD *method, + const X509V3_CTX *ctx, + const char *str) { + size_t len; + uint8_t *data = x509v3_hex_to_bytes(str, &len); + ASN1_OCTET_STRING *oct; + if (data == nullptr) { + return nullptr; + } + if (len > INT_MAX) { + OPENSSL_PUT_ERROR(X509V3, ERR_R_OVERFLOW); + goto err; + } + + oct = ASN1_OCTET_STRING_new(); + if (oct == nullptr) { + goto err; + } + ASN1_STRING_set0(oct, data, (int)len); + return oct; + +err: + OPENSSL_free(data); + return nullptr; +} + const X509V3_EXT_METHOD bssl::v3_skey_id = { NID_subject_key_identifier, 0, diff --git a/third_party/boringssl/src/crypto/x509/v3_utl.cc b/third_party/boringssl/src/crypto/x509/v3_utl.cc index 324e149..caca589 100644 --- a/third_party/boringssl/src/crypto/x509/v3_utl.cc +++ b/third_party/boringssl/src/crypto/x509/v3_utl.cc @@ -36,24 +36,11 @@ using namespace bssl; -static char *strip_spaces(char *name); -static int sk_strcmp(const char *const *a, const char *const *b); -static UniquePtr get_email(const X509_NAME *name, - const GENERAL_NAMES *gens); -static void str_free(OPENSSL_STRING str); -static int append_ia5(UniquePtr *sk, - const ASN1_IA5STRING *email); - -static int ipv4_from_asc(uint8_t v4[4], const char *in); -static int ipv6_from_asc(uint8_t v6[16], const char *in); -static int ipv6_cb(const char *elem, size_t len, void *usr); -static int ipv6_hex(uint8_t *out, const char *in, size_t inlen); +namespace { // Add a CONF_VALUE name value pair to stack - -static int x509V3_add_len_value(const char *name, const char *value, - size_t value_len, int omit_value, - STACK_OF(CONF_VALUE) **extlist) { +int x509V3_add_len_value(const char *name, const char *value, size_t value_len, + int omit_value, STACK_OF(CONF_VALUE) **extlist) { CONF_VALUE *vtmp = nullptr; char *tname = nullptr, *tvalue = nullptr; int extlist_was_null = *extlist == nullptr; @@ -95,40 +82,7 @@ static int x509V3_add_len_value(const char *name, const char *value, return 0; } -int bssl::X509V3_add_value(const char *name, const char *value, - STACK_OF(CONF_VALUE) **extlist) { - return x509V3_add_len_value(name, value, value != nullptr ? strlen(value) : 0, - /*omit_value=*/value == nullptr, extlist); -} - -int bssl::x509V3_add_value_asn1_string(const char *name, - const ASN1_STRING *value, - STACK_OF(CONF_VALUE) **extlist) { - return x509V3_add_len_value(name, (const char *)value->data, value->length, - /*omit_value=*/0, extlist); -} - -// Free function for STACK_OF(CONF_VALUE) - -void X509V3_conf_free(CONF_VALUE *conf) { - if (!conf) { - return; - } - OPENSSL_free(conf->name); - OPENSSL_free(conf->value); - OPENSSL_free(conf->section); - OPENSSL_free(conf); -} - -int bssl::X509V3_add_value_bool(const char *name, int asn1_bool, - STACK_OF(CONF_VALUE) **extlist) { - if (asn1_bool) { - return X509V3_add_value(name, "TRUE", extlist); - } - return X509V3_add_value(name, "FALSE", extlist); -} - -static char *bignum_to_string(const BIGNUM *bn) { +char *bignum_to_string(const BIGNUM *bn) { char *tmp, *ret; // Display large numbers in hex and small numbers in decimal. Converting to @@ -152,809 +106,1026 @@ static char *bignum_to_string(const BIGNUM *bn) { return ret; } -char *i2s_ASN1_ENUMERATED(const X509V3_EXT_METHOD *method, - const ASN1_ENUMERATED *a) { - BIGNUM *bntmp = nullptr; - char *strtmp = nullptr; - if (!a) { +// Delete leading and trailing spaces from a string +char *strip_spaces(char *name) { + char *p, *q; + // Skip over leading spaces + p = name; + while (*p && OPENSSL_isspace((unsigned char)*p)) { + p++; + } + if (!*p) { return nullptr; } - if (!(bntmp = ASN1_ENUMERATED_to_BN(a, nullptr)) || - !(strtmp = bignum_to_string(bntmp))) { + q = p + strlen(p) - 1; + while ((q != p) && OPENSSL_isspace((unsigned char)*q)) { + q--; } - BN_free(bntmp); - return strtmp; -} - -char *i2s_ASN1_INTEGER(const X509V3_EXT_METHOD *method, const ASN1_INTEGER *a) { - BIGNUM *bntmp = nullptr; - char *strtmp = nullptr; - if (!a) { - return nullptr; + if (p != q) { + q[1] = 0; } - if (!(bntmp = ASN1_INTEGER_to_BN(a, nullptr)) || - !(strtmp = bignum_to_string(bntmp))) { + if (!*p) { + return nullptr; } - BN_free(bntmp); - return strtmp; + return p; } -ASN1_INTEGER *s2i_ASN1_INTEGER(const X509V3_EXT_METHOD *method, - const char *value) { - BIGNUM *bn = nullptr; - ASN1_INTEGER *aint; - int isneg, ishex; - int ret; - if (!value) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_VALUE); - return nullptr; - } - bn = BN_new(); - if (value[0] == '-') { - value++; - isneg = 1; - } else { - isneg = 0; - } +int sk_strcmp(const char *const *a, const char *const *b) { + return strcmp(*a, *b); +} - if (value[0] == '0' && ((value[1] == 'x') || (value[1] == 'X'))) { - value += 2; - ishex = 1; - } else { - ishex = 0; - } +void str_free(OPENSSL_STRING str) { OPENSSL_free(str); } - if (ishex) { - ret = BN_hex2bn(&bn, value); - } else { - // Decoding from decimal scales quadratically in the input length. Bound the - // largest decimal input we accept in the config parser. 8,192 decimal - // digits allows values up to 27,213 bits. This exceeds the largest RSA, - // DSA, or DH modulus we support, and those are not usefully represented in - // decimal. - if (strlen(value) > 8192) { - BN_free(bn); - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NUMBER); - return nullptr; - } - ret = BN_dec2bn(&bn, value); +int append_ia5(UniquePtr *sk, + const ASN1_IA5STRING *email) { + // First some sanity checks + if (email->type != V_ASN1_IA5STRING) { + return 1; } - - if (!ret || value[ret]) { - BN_free(bn); - OPENSSL_PUT_ERROR(X509V3, X509V3_R_BN_DEC2BN_ERROR); - return nullptr; + if (email->data == nullptr || email->length == 0) { + return 1; } - - if (isneg && BN_is_zero(bn)) { - isneg = 0; + // `OPENSSL_STRING` cannot represent strings with embedded NULs. Do not + // report them as outputs. + if (OPENSSL_memchr(email->data, 0, email->length) != nullptr) { + return 1; } - aint = BN_to_ASN1_INTEGER(bn, nullptr); - BN_free(bn); - if (!aint) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_BN_TO_ASN1_INTEGER_ERROR); - return nullptr; + if (!*sk) { + sk->reset(sk_OPENSSL_STRING_new(sk_strcmp)); } - if (isneg) { - aint->type |= V_ASN1_NEG; + if (!*sk) { + return 0; } - return aint; -} -int bssl::X509V3_add_value_int(const char *name, const ASN1_INTEGER *aint, - STACK_OF(CONF_VALUE) **extlist) { - char *strtmp; - int ret; - if (!aint) { - return 1; - } - if (!(strtmp = i2s_ASN1_INTEGER(nullptr, aint))) { + UniquePtr emtmp( + OPENSSL_strndup((const char *)email->data, email->length)); + if (emtmp == nullptr || !PushToStack(sk->get(), std::move(emtmp))) { return 0; } - ret = X509V3_add_value(name, strtmp, extlist); - OPENSSL_free(strtmp); - return ret; + return 1; } -int bssl::X509V3_bool_from_string(const char *str, ASN1_BOOLEAN *out_bool) { - if (!strcmp(str, "TRUE") || !strcmp(str, "true") || !strcmp(str, "Y") || - !strcmp(str, "y") || !strcmp(str, "YES") || !strcmp(str, "yes")) { - *out_bool = ASN1_BOOLEAN_TRUE; - return 1; +UniquePtr get_email(const X509_NAME *name, + const GENERAL_NAMES *gens) { + UniquePtr ret; + int i = -1; + while ((i = X509_NAME_get_index_by_NID(name, NID_pkcs9_emailAddress, i)) >= + 0) { + const X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i); + const ASN1_IA5STRING *email = X509_NAME_ENTRY_get_data(ne); + if (!append_ia5(&ret, email)) { + return nullptr; + } } - if (!strcmp(str, "FALSE") || !strcmp(str, "false") || !strcmp(str, "N") || - !strcmp(str, "n") || !strcmp(str, "NO") || !strcmp(str, "no")) { - *out_bool = ASN1_BOOLEAN_FALSE; - return 1; + for (const GENERAL_NAME *gen : gens) { + if (gen->type == GEN_EMAIL && !append_ia5(&ret, gen->d.ia5)) { + return nullptr; + } } - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_BOOLEAN_STRING); - return 0; + sk_OPENSSL_STRING_sort_and_dedup(ret.get(), str_free); + return ret; } -int bssl::X509V3_get_value_bool(const CONF_VALUE *value, - ASN1_BOOLEAN *out_bool) { - const char *btmp = value->value; - if (btmp == nullptr) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_BOOLEAN_STRING); - goto err; +typedef int (*equal_fn)(const unsigned char *pattern, size_t pattern_len, + const unsigned char *subject, size_t subject_len, + unsigned int flags); + +// Compare while ASCII ignoring case. +int equal_nocase(const unsigned char *pattern, size_t pattern_len, + const unsigned char *subject, size_t subject_len, + unsigned int flags) { + if (pattern_len != subject_len) { + return 0; } - if (!X509V3_bool_from_string(btmp, out_bool)) { - goto err; + while (pattern_len) { + unsigned char l = *pattern; + unsigned char r = *subject; + // The pattern must not contain NUL characters. + if (l == 0) { + return 0; + } + if (l != r) { + if (OPENSSL_tolower(l) != OPENSSL_tolower(r)) { + return 0; + } + } + ++pattern; + ++subject; + --pattern_len; } return 1; +} -err: - X509V3_conf_err(value); - return 0; +// Compare using OPENSSL_memcmp. +int equal_case(const unsigned char *pattern, size_t pattern_len, + const unsigned char *subject, size_t subject_len, + unsigned int flags) { + if (pattern_len != subject_len) { + return 0; + } + return !OPENSSL_memcmp(pattern, subject, pattern_len); } -int bssl::X509V3_get_value_int(const CONF_VALUE *value, ASN1_INTEGER **aint) { - ASN1_INTEGER *itmp; - if (!(itmp = s2i_ASN1_INTEGER(nullptr, value->value))) { - X509V3_conf_err(value); +// RFC 5280, section 7.5, requires that only the domain is compared in a +// case-insensitive manner. +int equal_email(const unsigned char *a, size_t a_len, const unsigned char *b, + size_t b_len, unsigned int unused_flags) { + size_t i = a_len; + if (a_len != b_len) { return 0; } - ASN1_INTEGER_free(*aint); - *aint = itmp; - return 1; + // We search backwards for the '@' character, so that we do not have to + // deal with quoted local-parts. The domain part is compared in a + // case-insensitive manner. + while (i > 0) { + --i; + if (a[i] == '@' || b[i] == '@') { + if (!equal_nocase(a + i, a_len - i, b + i, a_len - i, 0)) { + return 0; + } + break; + } + } + if (i == 0) { + i = a_len; + } + return equal_case(a, i, b, i, 0); } -#define HDR_NAME 1 -#define HDR_VALUE 2 +// Compare the prefix and suffix with the subject, and check that the +// characters in-between are valid. +int wildcard_match(const unsigned char *prefix, size_t prefix_len, + const unsigned char *suffix, size_t suffix_len, + const unsigned char *subject, size_t subject_len, + unsigned int flags) { + const unsigned char *wildcard_start; + const unsigned char *wildcard_end; + const unsigned char *p; + int allow_idna = 0; -STACK_OF(CONF_VALUE) *bssl::X509V3_parse_list(const char *line) { - char *p, *q, c; - char *ntmp, *vtmp; - STACK_OF(CONF_VALUE) *values = nullptr; - char *linebuf; - int state; - // We are going to modify the line so copy it first - // TODO(davidben): Rewrite this parser with `std::string_view`. It doesn't - // need to copy the string. - linebuf = OPENSSL_strdup(line); - if (linebuf == nullptr) { - goto err; + if (subject_len < prefix_len + suffix_len) { + return 0; } - state = HDR_NAME; - ntmp = nullptr; - // Go through all characters - for (p = linebuf, q = linebuf; (c = *p) && (c != '\r') && (c != '\n'); p++) { - switch (state) { - case HDR_NAME: - if (c == ':') { - state = HDR_VALUE; - *p = 0; - ntmp = strip_spaces(q); - if (!ntmp) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_NAME); - goto err; - } - q = p + 1; - } else if (c == ',') { - *p = 0; - ntmp = strip_spaces(q); - q = p + 1; - if (!ntmp) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_NAME); - goto err; - } - X509V3_add_value(ntmp, nullptr, &values); - } - break; + if (!equal_nocase(prefix, prefix_len, subject, prefix_len, flags)) { + return 0; + } + wildcard_start = subject + prefix_len; + wildcard_end = subject + (subject_len - suffix_len); + if (!equal_nocase(wildcard_end, suffix_len, suffix, suffix_len, flags)) { + return 0; + } + // If the wildcard makes up the entire first label, it must match at + // least one character. + if (prefix_len == 0 && *suffix == '.') { + if (wildcard_start == wildcard_end) { + return 0; + } + allow_idna = 1; + } + // IDNA labels cannot match partial wildcards + if (!allow_idna && subject_len >= 4 && + OPENSSL_strncasecmp((char *)subject, "xn--", 4) == 0) { + return 0; + } + // The wildcard may match a literal '*' + if (wildcard_end == wildcard_start + 1 && *wildcard_start == '*') { + return 1; + } + // Check that the part matched by the wildcard contains only + // permitted characters and only matches a single label. + for (p = wildcard_start; p != wildcard_end; ++p) { + if (!OPENSSL_isalnum(*p) && *p != '-') { + return 0; + } + } + return 1; +} - case HDR_VALUE: - if (c == ',') { - state = HDR_NAME; - *p = 0; - vtmp = strip_spaces(q); - if (!vtmp) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_VALUE); - goto err; - } - X509V3_add_value(ntmp, vtmp, &values); - ntmp = nullptr; - q = p + 1; - } +#define LABEL_START (1 << 0) +#define LABEL_END (1 << 1) +#define LABEL_HYPHEN (1 << 2) +#define LABEL_IDNA (1 << 3) + +const unsigned char *valid_star(const unsigned char *p, size_t len, + unsigned int flags) { + const unsigned char *star = nullptr; + size_t i; + int state = LABEL_START; + int dots = 0; + for (i = 0; i < len; ++i) { + // Locate first and only legal wildcard, either at the start + // or end of a non-IDNA first and not final label. + if (p[i] == '*') { + int atstart = (state & LABEL_START); + int atend = (i == len - 1 || p[i + 1] == '.'); + // At most one wildcard per pattern. + // No wildcards in IDNA labels. + // No wildcards after the first label. + if (star != nullptr || (state & LABEL_IDNA) != 0 || dots) { + return nullptr; + } + // Only full-label '*.example.com' wildcards. + if (!atstart || !atend) { + return nullptr; + } + star = &p[i]; + state &= ~LABEL_START; + } else if (OPENSSL_isalnum(p[i])) { + if ((state & LABEL_START) != 0 && len - i >= 4 && + OPENSSL_strncasecmp((char *)&p[i], "xn--", 4) == 0) { + state |= LABEL_IDNA; + } + state &= ~(LABEL_HYPHEN | LABEL_START); + } else if (p[i] == '.') { + if ((state & (LABEL_HYPHEN | LABEL_START)) != 0) { + return nullptr; + } + state = LABEL_START; + ++dots; + } else if (p[i] == '-') { + // no domain/subdomain starts with '-' + if ((state & LABEL_START) != 0) { + return nullptr; + } + state |= LABEL_HYPHEN; + } else { + return nullptr; } } - if (state == HDR_VALUE) { - vtmp = strip_spaces(q); - if (!vtmp) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_VALUE); - goto err; + // The final label must not end in a hyphen or ".", and + // there must be at least two dots after the star. + if ((state & (LABEL_START | LABEL_HYPHEN)) != 0 || dots < 2) { + return nullptr; + } + return star; +} + +// Compare using wildcards. +int equal_wildcard(const unsigned char *pattern, size_t pattern_len, + const unsigned char *subject, size_t subject_len, + unsigned int flags) { + const unsigned char *star = nullptr; + + // Subject names starting with '.' can only match a wildcard pattern + // via a subject sub-domain pattern suffix match. + if (!(subject_len > 1 && subject[0] == '.')) { + star = valid_star(pattern, pattern_len, flags); + } + if (star == nullptr) { + return equal_nocase(pattern, pattern_len, subject, subject_len, flags); + } + return wildcard_match(pattern, star - pattern, star + 1, + (pattern + pattern_len) - star - 1, subject, + subject_len, flags); +} + +// Compare an ASN1_STRING to a supplied string. If they match return 1. If +// cmp_type > 0 only compare if string matches the type, otherwise convert it +// to UTF8. +int do_check_string(const ASN1_STRING *a, int cmp_type, equal_fn equal, + unsigned int flags, int check_type, const char *b, + size_t blen, char **peername) { + int rv = 0; + + if (!a->data || !a->length) { + return 0; + } + if (cmp_type > 0) { + if (cmp_type != a->type) { + return 0; + } + if (cmp_type == V_ASN1_IA5STRING) { + rv = equal(a->data, a->length, (unsigned char *)b, blen, flags); + } else if (a->length == (int)blen && !OPENSSL_memcmp(a->data, b, blen)) { + rv = 1; + } + if (rv > 0 && peername) { + *peername = OPENSSL_strndup((char *)a->data, a->length); + if (*peername == nullptr) { + return -1; + } } - X509V3_add_value(ntmp, vtmp, &values); } else { - ntmp = strip_spaces(q); - if (!ntmp) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_NAME); - goto err; + int astrlen; + unsigned char *astr; + astrlen = ASN1_STRING_to_UTF8(&astr, a); + if (astrlen < 0) { + return -1; } - X509V3_add_value(ntmp, nullptr, &values); + // We check the common name against DNS name constraints if it passes + // `x509v3_looks_like_dns_name`. Thus we must not consider common names + // for DNS fallbacks if they fail this check. + if (check_type == GEN_DNS && !x509v3_looks_like_dns_name(astr, astrlen)) { + rv = 0; + } else { + rv = equal(astr, astrlen, (unsigned char *)b, blen, flags); + } + if (rv > 0 && peername) { + *peername = OPENSSL_strndup((char *)astr, astrlen); + if (*peername == nullptr) { + return -1; + } + } + OPENSSL_free(astr); } - OPENSSL_free(linebuf); - return values; - -err: - OPENSSL_free(linebuf); - sk_CONF_VALUE_pop_free(values, X509V3_conf_free); - return nullptr; + return rv; } -// Delete leading and trailing spaces from a string -static char *strip_spaces(char *name) { - char *p, *q; - // Skip over leading spaces - p = name; - while (*p && OPENSSL_isspace((unsigned char)*p)) { - p++; +int do_x509_check(const X509 *x, const char *chk, size_t chklen, + unsigned int flags, int check_type, char **peername) { + int cnid = NID_undef; + int alt_type; + int rv = 0; + equal_fn equal; + if (check_type == GEN_EMAIL) { + cnid = NID_pkcs9_emailAddress; + alt_type = V_ASN1_IA5STRING; + equal = equal_email; + } else if (check_type == GEN_DNS) { + cnid = NID_commonName; + alt_type = V_ASN1_IA5STRING; + if (flags & X509_CHECK_FLAG_NO_WILDCARDS) { + equal = equal_nocase; + } else { + equal = equal_wildcard; + } + } else { + alt_type = V_ASN1_OCTET_STRING; + equal = equal_case; } - if (!*p) { - return nullptr; + + int critical; + UniquePtr gens(reinterpret_cast( + X509_get_ext_d2i(x, NID_subject_alt_name, &critical, nullptr))); + if (gens) { + for (const GENERAL_NAME *gen : gens.get()) { + if (gen->type != check_type) { + continue; + } + const ASN1_STRING *cstr; + if (check_type == GEN_EMAIL) { + cstr = gen->d.rfc822Name; + } else if (check_type == GEN_DNS) { + cstr = gen->d.dNSName; + } else { + cstr = gen->d.iPAddress; + } + // Positive on success, negative on error! + if ((rv = do_check_string(cstr, alt_type, equal, flags, check_type, chk, + chklen, peername)) != 0) { + break; + } + } + return rv; + } else if (critical != -1) { + // Syntax error in the subjectAltName extension. + return 0; } - q = p + strlen(p) - 1; - while ((q != p) && OPENSSL_isspace((unsigned char)*q)) { - q--; + + // We're done if CN-ID is not pertinent + if (cnid == NID_undef || (flags & X509_CHECK_FLAG_NEVER_CHECK_SUBJECT)) { + return 0; } - if (p != q) { - q[1] = 0; + + int j = -1; + const X509_NAME *name = X509_get_subject_name(x); + while ((j = X509_NAME_get_index_by_NID(name, cnid, j)) >= 0) { + const X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, j); + const ASN1_STRING *str = X509_NAME_ENTRY_get_data(ne); + // Positive on success, negative on error! + if ((rv = do_check_string(str, -1, equal, flags, check_type, chk, chklen, + peername)) != 0) { + return rv; + } } - if (!*p) { - return nullptr; + return 0; +} + +// get_ipv4_component consumes one IPv4 component, terminated by either '.' or +// the end of the string, from `*str`. On success, it returns one, sets `*out` +// to the component, and advances `*str` to the first unconsumed character. On +// invalid input, it returns zero. +int get_ipv4_component(uint8_t *out_byte, const char **str) { + // Store a slightly larger intermediary so the overflow check is easier. + uint32_t out = 0; + for (;;) { + if (!OPENSSL_isdigit(**str)) { + return 0; + } + out = (out * 10) + (**str - '0'); + if (out > 255) { + // Components must be 8-bit. + return 0; + } + (*str)++; + if ((**str) == '.' || (**str) == '\0') { + *out_byte = (uint8_t)out; + return 1; + } + if (out == 0) { + // Reject extra leading zeros. Parsers sometimes treat them as octal, so + // accepting them would misinterpret input. + return 0; + } } - return p; } -// hex string utilities +// get_ipv4_dot consumes a '.' from `*str` and advances it. It returns one on +// success and zero if `*str` does not point to a '.'. +int get_ipv4_dot(const char **str) { + if (**str != '.') { + return 0; + } + (*str)++; + return 1; +} -char *bssl::x509v3_bytes_to_hex(const uint8_t *in, size_t len) { - CBB cbb; - if (!CBB_init(&cbb, len * 3 + 1)) { - goto err; +int ipv4_from_asc(uint8_t v4[4], const char *in) { + if (!get_ipv4_component(&v4[0], &in) || !get_ipv4_dot(&in) || + !get_ipv4_component(&v4[1], &in) || !get_ipv4_dot(&in) || + !get_ipv4_component(&v4[2], &in) || !get_ipv4_dot(&in) || + !get_ipv4_component(&v4[3], &in) || *in != '\0') { + return 0; } - for (size_t i = 0; i < len; i++) { - static const char hex[] = "0123456789ABCDEF"; - if ((i > 0 && !CBB_add_u8(&cbb, ':')) || - !CBB_add_u8(&cbb, hex[in[i] >> 4]) || - !CBB_add_u8(&cbb, hex[in[i] & 0xf])) { - goto err; + return 1; +} + +typedef struct { + // Temporary store for IPV6 output + uint8_t tmp[16]; + // Total number of bytes in tmp + int total; + // The position of a zero (corresponding to '::') + int zero_pos; + // Number of zeroes + int zero_cnt; +} IPV6_STAT; + +// Convert a string of up to 4 hex digits into the corresponding IPv6 form. +int ipv6_hex(uint8_t *out, const char *in, size_t inlen) { + if (inlen > 4) { + return 0; + } + uint16_t num = 0; + while (inlen--) { + uint8_t val; + if (!OPENSSL_fromxdigit(&val, *in++)) { + return 0; } + num = (num << 4) | val; + } + out[0] = num >> 8; + out[1] = num & 0xff; + return 1; +} + +int ipv6_cb(const char *elem, size_t len, void *usr) { + IPV6_STAT *s = reinterpret_cast(usr); + // Error if 16 bytes written + if (s->total == 16) { + return 0; } - uint8_t *ret; - size_t unused_len; - if (!CBB_add_u8(&cbb, 0) || !CBB_finish(&cbb, &ret, &unused_len)) { - goto err; + if (len == 0) { + // Zero length element, corresponds to '::' + if (s->zero_pos == -1) { + s->zero_pos = s->total; + } else if (s->zero_pos != s->total) { + // If we've already got a :: its an error + return 0; + } + if (s->zero_cnt >= 3) { + // More than three zeros is an error. + return 0; + } + s->zero_cnt++; + } else { + // If more than 4 characters could be final a.b.c.d form + if (len > 4) { + // Need at least 4 bytes left + if (s->total > 12) { + return 0; + } + // Must be end of string + if (elem[len]) { + return 0; + } + if (!ipv4_from_asc(s->tmp + s->total, elem)) { + return 0; + } + s->total += 4; + } else { + if (!ipv6_hex(s->tmp + s->total, elem, len)) { + return 0; + } + s->total += 2; + } } - - return (char *)ret; - -err: - CBB_cleanup(&cbb); - return nullptr; + return 1; } -unsigned char *bssl::x509v3_hex_to_bytes(const char *str, size_t *len) { - unsigned char *hexbuf, *q; - unsigned char ch, cl, *p; - uint8_t high, low; - if (!str) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_ARGUMENT); - return nullptr; - } - if (!(hexbuf = - reinterpret_cast(OPENSSL_malloc(strlen(str) >> 1)))) { - goto err; +int ipv6_from_asc(uint8_t v6[16], const char *in) { + IPV6_STAT v6stat; + v6stat.total = 0; + v6stat.zero_pos = -1; + v6stat.zero_cnt = 0; + // Treat the IPv6 representation as a list of values separated by ':'. + // The presence of a '::' will parse as one, two or three zero length + // elements. + if (!CONF_parse_list(in, ':', 0, ipv6_cb, &v6stat)) { + return 0; } - for (p = (unsigned char *)str, q = hexbuf; *p;) { - ch = *p++; - if (ch == ':') { - continue; - } - cl = *p++; - if (!cl) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_ODD_NUMBER_OF_DIGITS); - OPENSSL_free(hexbuf); - return nullptr; + + if (v6stat.zero_pos == -1) { + // If no '::' must have exactly 16 bytes + if (v6stat.total != 16) { + return 0; } - if (!OPENSSL_fromxdigit(&high, ch)) { - goto badhex; + } else { + // If '::' must have less than 16 bytes + if (v6stat.total >= 16) { + return 0; } - if (!OPENSSL_fromxdigit(&low, cl)) { - goto badhex; + if (v6stat.zero_cnt > 3) { + // More than three zeroes is an error + return 0; + } else if (v6stat.zero_cnt == 3) { + // Can only have three zeroes if nothing else present + if (v6stat.total > 0) { + return 0; + } + } else if (v6stat.zero_cnt == 2) { + // Can only have two zeroes if at start or end + if (v6stat.zero_pos != 0 && v6stat.zero_pos != v6stat.total) { + return 0; + } + } else { + // Can only have one zero if *not* start or end + if (v6stat.zero_pos == 0 || v6stat.zero_pos == v6stat.total) { + return 0; + } } - *q++ = (high << 4) | low; } - if (len) { - *len = q - hexbuf; + // Format the result. + if (v6stat.zero_pos >= 0) { + // Copy initial part + OPENSSL_memcpy(v6, v6stat.tmp, v6stat.zero_pos); + // Zero middle + OPENSSL_memset(v6 + v6stat.zero_pos, 0, 16 - v6stat.total); + // Copy final part + if (v6stat.total != v6stat.zero_pos) { + OPENSSL_memcpy(v6 + v6stat.zero_pos + 16 - v6stat.total, + v6stat.tmp + v6stat.zero_pos, + v6stat.total - v6stat.zero_pos); + } + } else { + OPENSSL_memcpy(v6, v6stat.tmp, 16); } - return hexbuf; + return 1; +} -err: - OPENSSL_free(hexbuf); - return nullptr; +} // namespace -badhex: - OPENSSL_free(hexbuf); - OPENSSL_PUT_ERROR(X509V3, X509V3_R_ILLEGAL_HEX_DIGIT); - return nullptr; +int bssl::X509V3_add_value(const char *name, const char *value, + STACK_OF(CONF_VALUE) **extlist) { + return x509V3_add_len_value(name, value, value != nullptr ? strlen(value) : 0, + /*omit_value=*/value == nullptr, extlist); } -int bssl::x509v3_conf_name_matches(const char *name, const char *cmp) { - // `name` must begin with `cmp`. - size_t len = strlen(cmp); - if (strncmp(name, cmp, len) != 0) { - return 0; - } - // `name` must either be equal to `cmp` or begin with `cmp`, followed by '.'. - return name[len] == '\0' || name[len] == '.'; +int bssl::x509V3_add_value_asn1_string(const char *name, + const ASN1_STRING *value, + STACK_OF(CONF_VALUE) **extlist) { + return x509V3_add_len_value(name, (const char *)value->data, value->length, + /*omit_value=*/0, extlist); } -static int sk_strcmp(const char *const *a, const char *const *b) { - return strcmp(*a, *b); -} +// Free function for STACK_OF(CONF_VALUE) -STACK_OF(OPENSSL_STRING) *X509_get1_email(const X509 *x) { - int critical; - UniquePtr gens(reinterpret_cast( - X509_get_ext_d2i(x, NID_subject_alt_name, &critical, nullptr))); - if (!gens && critical != -1) { - return nullptr; +void X509V3_conf_free(CONF_VALUE *conf) { + if (!conf) { + return; } - return get_email(X509_get_subject_name(x), gens.get()).release(); + OPENSSL_free(conf->name); + OPENSSL_free(conf->value); + OPENSSL_free(conf->section); + OPENSSL_free(conf); } -STACK_OF(OPENSSL_STRING) *X509_get1_ocsp(const X509 *x) { - UniquePtr info( - reinterpret_cast( - X509_get_ext_d2i(x, NID_info_access, nullptr, nullptr))); - if (!info) { - return nullptr; - } - UniquePtr ret; - for (const ACCESS_DESCRIPTION *ad : info.get()) { - if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) { - if (ad->location->type == GEN_URI) { - if (!append_ia5(&ret, ad->location->d.uniformResourceIdentifier)) { - return nullptr; - } - } - } +int bssl::X509V3_add_value_bool(const char *name, int asn1_bool, + STACK_OF(CONF_VALUE) **extlist) { + if (asn1_bool) { + return X509V3_add_value(name, "TRUE", extlist); } - sk_OPENSSL_STRING_sort_and_dedup(ret.get(), str_free); - return ret.release(); + return X509V3_add_value(name, "FALSE", extlist); } -STACK_OF(OPENSSL_STRING) *X509_REQ_get1_email(const X509_REQ *x) { - UniquePtr exts(X509_REQ_get_extensions(x)); - int critical; - UniquePtr gens(reinterpret_cast( - X509V3_get_d2i(exts.get(), NID_subject_alt_name, &critical, nullptr))); - if (!gens && critical != -1) { +char *i2s_ASN1_ENUMERATED(const X509V3_EXT_METHOD *method, + const ASN1_ENUMERATED *a) { + BIGNUM *bntmp = nullptr; + char *strtmp = nullptr; + if (!a) { return nullptr; } - return get_email(X509_REQ_get_subject_name(x), gens.get()).release(); + if (!(bntmp = ASN1_ENUMERATED_to_BN(a, nullptr)) || + !(strtmp = bignum_to_string(bntmp))) { + } + BN_free(bntmp); + return strtmp; } -static UniquePtr get_email( - const X509_NAME *name, const GENERAL_NAMES *gens) { - UniquePtr ret; - int i = -1; - while ((i = X509_NAME_get_index_by_NID(name, NID_pkcs9_emailAddress, i)) >= - 0) { - const X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i); - const ASN1_IA5STRING *email = X509_NAME_ENTRY_get_data(ne); - if (!append_ia5(&ret, email)) { - return nullptr; - } +char *i2s_ASN1_INTEGER(const X509V3_EXT_METHOD *method, const ASN1_INTEGER *a) { + BIGNUM *bntmp = nullptr; + char *strtmp = nullptr; + if (!a) { + return nullptr; } - for (const GENERAL_NAME *gen : gens) { - if (gen->type == GEN_EMAIL && !append_ia5(&ret, gen->d.ia5)) { - return nullptr; - } + if (!(bntmp = ASN1_INTEGER_to_BN(a, nullptr)) || + !(strtmp = bignum_to_string(bntmp))) { } - sk_OPENSSL_STRING_sort_and_dedup(ret.get(), str_free); - return ret; + BN_free(bntmp); + return strtmp; } -static void str_free(OPENSSL_STRING str) { OPENSSL_free(str); } - -static int append_ia5(UniquePtr *sk, - const ASN1_IA5STRING *email) { - // First some sanity checks - if (email->type != V_ASN1_IA5STRING) { - return 1; - } - if (email->data == nullptr || email->length == 0) { - return 1; +ASN1_INTEGER *s2i_ASN1_INTEGER(const X509V3_EXT_METHOD *method, + const char *value) { + BIGNUM *bn = nullptr; + ASN1_INTEGER *aint; + int isneg, ishex; + int ret; + if (!value) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_VALUE); + return nullptr; } - // `OPENSSL_STRING` cannot represent strings with embedded NULs. Do not - // report them as outputs. - if (OPENSSL_memchr(email->data, 0, email->length) != nullptr) { - return 1; + bn = BN_new(); + if (value[0] == '-') { + value++; + isneg = 1; + } else { + isneg = 0; } - if (!*sk) { - sk->reset(sk_OPENSSL_STRING_new(sk_strcmp)); - } - if (!*sk) { - return 0; + if (value[0] == '0' && ((value[1] == 'x') || (value[1] == 'X'))) { + value += 2; + ishex = 1; + } else { + ishex = 0; } - UniquePtr emtmp( - OPENSSL_strndup((const char *)email->data, email->length)); - if (emtmp == nullptr || !PushToStack(sk->get(), std::move(emtmp))) { - return 0; + if (ishex) { + ret = BN_hex2bn(&bn, value); + } else { + // Decoding from decimal scales quadratically in the input length. Bound the + // largest decimal input we accept in the config parser. 8,192 decimal + // digits allows values up to 27,213 bits. This exceeds the largest RSA, + // DSA, or DH modulus we support, and those are not usefully represented in + // decimal. + if (strlen(value) > 8192) { + BN_free(bn); + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NUMBER); + return nullptr; + } + ret = BN_dec2bn(&bn, value); } - return 1; -} -void X509_email_free(STACK_OF(OPENSSL_STRING) *sk) { - sk_OPENSSL_STRING_pop_free(sk, str_free); -} + if (!ret || value[ret]) { + BN_free(bn); + OPENSSL_PUT_ERROR(X509V3, X509V3_R_BN_DEC2BN_ERROR); + return nullptr; + } -typedef int (*equal_fn)(const unsigned char *pattern, size_t pattern_len, - const unsigned char *subject, size_t subject_len, - unsigned int flags); + if (isneg && BN_is_zero(bn)) { + isneg = 0; + } -// Compare while ASCII ignoring case. -static int equal_nocase(const unsigned char *pattern, size_t pattern_len, - const unsigned char *subject, size_t subject_len, - unsigned int flags) { - if (pattern_len != subject_len) { - return 0; + aint = BN_to_ASN1_INTEGER(bn, nullptr); + BN_free(bn); + if (!aint) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_BN_TO_ASN1_INTEGER_ERROR); + return nullptr; } - while (pattern_len) { - unsigned char l = *pattern; - unsigned char r = *subject; - // The pattern must not contain NUL characters. - if (l == 0) { - return 0; - } - if (l != r) { - if (OPENSSL_tolower(l) != OPENSSL_tolower(r)) { - return 0; - } - } - ++pattern; - ++subject; - --pattern_len; + if (isneg) { + aint->type |= V_ASN1_NEG; } - return 1; + return aint; } -// Compare using OPENSSL_memcmp. -static int equal_case(const unsigned char *pattern, size_t pattern_len, - const unsigned char *subject, size_t subject_len, - unsigned int flags) { - if (pattern_len != subject_len) { +int bssl::X509V3_add_value_int(const char *name, const ASN1_INTEGER *aint, + STACK_OF(CONF_VALUE) **extlist) { + char *strtmp; + int ret; + if (!aint) { + return 1; + } + if (!(strtmp = i2s_ASN1_INTEGER(nullptr, aint))) { return 0; } - return !OPENSSL_memcmp(pattern, subject, pattern_len); + ret = X509V3_add_value(name, strtmp, extlist); + OPENSSL_free(strtmp); + return ret; } -// RFC 5280, section 7.5, requires that only the domain is compared in a -// case-insensitive manner. -static int equal_email(const unsigned char *a, size_t a_len, - const unsigned char *b, size_t b_len, - unsigned int unused_flags) { - size_t i = a_len; - if (a_len != b_len) { - return 0; - } - // We search backwards for the '@' character, so that we do not have to - // deal with quoted local-parts. The domain part is compared in a - // case-insensitive manner. - while (i > 0) { - --i; - if (a[i] == '@' || b[i] == '@') { - if (!equal_nocase(a + i, a_len - i, b + i, a_len - i, 0)) { - return 0; - } - break; - } +int bssl::X509V3_bool_from_string(const char *str, ASN1_BOOLEAN *out_bool) { + if (!strcmp(str, "TRUE") || !strcmp(str, "true") || !strcmp(str, "Y") || + !strcmp(str, "y") || !strcmp(str, "YES") || !strcmp(str, "yes")) { + *out_bool = ASN1_BOOLEAN_TRUE; + return 1; } - if (i == 0) { - i = a_len; + if (!strcmp(str, "FALSE") || !strcmp(str, "false") || !strcmp(str, "N") || + !strcmp(str, "n") || !strcmp(str, "NO") || !strcmp(str, "no")) { + *out_bool = ASN1_BOOLEAN_FALSE; + return 1; } - return equal_case(a, i, b, i, 0); + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_BOOLEAN_STRING); + return 0; } -// Compare the prefix and suffix with the subject, and check that the -// characters in-between are valid. -static int wildcard_match(const unsigned char *prefix, size_t prefix_len, - const unsigned char *suffix, size_t suffix_len, - const unsigned char *subject, size_t subject_len, - unsigned int flags) { - const unsigned char *wildcard_start; - const unsigned char *wildcard_end; - const unsigned char *p; - int allow_idna = 0; - - if (subject_len < prefix_len + suffix_len) { - return 0; - } - if (!equal_nocase(prefix, prefix_len, subject, prefix_len, flags)) { - return 0; - } - wildcard_start = subject + prefix_len; - wildcard_end = subject + (subject_len - suffix_len); - if (!equal_nocase(wildcard_end, suffix_len, suffix, suffix_len, flags)) { - return 0; +int bssl::X509V3_get_value_bool(const CONF_VALUE *value, + ASN1_BOOLEAN *out_bool) { + const char *btmp = value->value; + if (btmp == nullptr) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_BOOLEAN_STRING); + goto err; } - // If the wildcard makes up the entire first label, it must match at - // least one character. - if (prefix_len == 0 && *suffix == '.') { - if (wildcard_start == wildcard_end) { - return 0; - } - allow_idna = 1; + if (!X509V3_bool_from_string(btmp, out_bool)) { + goto err; } - // IDNA labels cannot match partial wildcards - if (!allow_idna && subject_len >= 4 && - OPENSSL_strncasecmp((char *)subject, "xn--", 4) == 0) { + return 1; + +err: + X509V3_conf_err(value); + return 0; +} + +int bssl::X509V3_get_value_int(const CONF_VALUE *value, ASN1_INTEGER **aint) { + ASN1_INTEGER *itmp; + if (!(itmp = s2i_ASN1_INTEGER(nullptr, value->value))) { + X509V3_conf_err(value); return 0; } - // The wildcard may match a literal '*' - if (wildcard_end == wildcard_start + 1 && *wildcard_start == '*') { - return 1; - } - // Check that the part matched by the wildcard contains only - // permitted characters and only matches a single label. - for (p = wildcard_start; p != wildcard_end; ++p) { - if (!OPENSSL_isalnum(*p) && *p != '-') { - return 0; - } - } + ASN1_INTEGER_free(*aint); + *aint = itmp; return 1; } -#define LABEL_START (1 << 0) -#define LABEL_END (1 << 1) -#define LABEL_HYPHEN (1 << 2) -#define LABEL_IDNA (1 << 3) +#define HDR_NAME 1 +#define HDR_VALUE 2 -static const unsigned char *valid_star(const unsigned char *p, size_t len, - unsigned int flags) { - const unsigned char *star = nullptr; - size_t i; - int state = LABEL_START; - int dots = 0; - for (i = 0; i < len; ++i) { - // Locate first and only legal wildcard, either at the start - // or end of a non-IDNA first and not final label. - if (p[i] == '*') { - int atstart = (state & LABEL_START); - int atend = (i == len - 1 || p[i + 1] == '.'); - // At most one wildcard per pattern. - // No wildcards in IDNA labels. - // No wildcards after the first label. - if (star != nullptr || (state & LABEL_IDNA) != 0 || dots) { - return nullptr; - } - // Only full-label '*.example.com' wildcards. - if (!atstart || !atend) { - return nullptr; - } - star = &p[i]; - state &= ~LABEL_START; - } else if (OPENSSL_isalnum(p[i])) { - if ((state & LABEL_START) != 0 && len - i >= 4 && - OPENSSL_strncasecmp((char *)&p[i], "xn--", 4) == 0) { - state |= LABEL_IDNA; - } - state &= ~(LABEL_HYPHEN | LABEL_START); - } else if (p[i] == '.') { - if ((state & (LABEL_HYPHEN | LABEL_START)) != 0) { - return nullptr; - } - state = LABEL_START; - ++dots; - } else if (p[i] == '-') { - // no domain/subdomain starts with '-' - if ((state & LABEL_START) != 0) { - return nullptr; - } - state |= LABEL_HYPHEN; - } else { - return nullptr; +STACK_OF(CONF_VALUE) *bssl::X509V3_parse_list(const char *line) { + char *p, *q, c; + char *ntmp, *vtmp; + STACK_OF(CONF_VALUE) *values = nullptr; + char *linebuf; + int state; + // We are going to modify the line so copy it first + // TODO(davidben): Rewrite this parser with `std::string_view`. It doesn't + // need to copy the string. + linebuf = OPENSSL_strdup(line); + if (linebuf == nullptr) { + goto err; + } + state = HDR_NAME; + ntmp = nullptr; + // Go through all characters + for (p = linebuf, q = linebuf; (c = *p) && (c != '\r') && (c != '\n'); p++) { + switch (state) { + case HDR_NAME: + if (c == ':') { + state = HDR_VALUE; + *p = 0; + ntmp = strip_spaces(q); + if (!ntmp) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_NAME); + goto err; + } + q = p + 1; + } else if (c == ',') { + *p = 0; + ntmp = strip_spaces(q); + q = p + 1; + if (!ntmp) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_NAME); + goto err; + } + X509V3_add_value(ntmp, nullptr, &values); + } + break; + + case HDR_VALUE: + if (c == ',') { + state = HDR_NAME; + *p = 0; + vtmp = strip_spaces(q); + if (!vtmp) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_VALUE); + goto err; + } + X509V3_add_value(ntmp, vtmp, &values); + ntmp = nullptr; + q = p + 1; + } } } - // The final label must not end in a hyphen or ".", and - // there must be at least two dots after the star. - if ((state & (LABEL_START | LABEL_HYPHEN)) != 0 || dots < 2) { - return nullptr; + if (state == HDR_VALUE) { + vtmp = strip_spaces(q); + if (!vtmp) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_VALUE); + goto err; + } + X509V3_add_value(ntmp, vtmp, &values); + } else { + ntmp = strip_spaces(q); + if (!ntmp) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_NAME); + goto err; + } + X509V3_add_value(ntmp, nullptr, &values); } - return star; + OPENSSL_free(linebuf); + return values; + +err: + OPENSSL_free(linebuf); + sk_CONF_VALUE_pop_free(values, X509V3_conf_free); + return nullptr; } -// Compare using wildcards. -static int equal_wildcard(const unsigned char *pattern, size_t pattern_len, - const unsigned char *subject, size_t subject_len, - unsigned int flags) { - const unsigned char *star = nullptr; +// hex string utilities - // Subject names starting with '.' can only match a wildcard pattern - // via a subject sub-domain pattern suffix match. - if (!(subject_len > 1 && subject[0] == '.')) { - star = valid_star(pattern, pattern_len, flags); +char *bssl::x509v3_bytes_to_hex(const uint8_t *in, size_t len) { + CBB cbb; + if (!CBB_init(&cbb, len * 3 + 1)) { + goto err; } - if (star == nullptr) { - return equal_nocase(pattern, pattern_len, subject, subject_len, flags); + for (size_t i = 0; i < len; i++) { + static const char hex[] = "0123456789ABCDEF"; + if ((i > 0 && !CBB_add_u8(&cbb, ':')) || + !CBB_add_u8(&cbb, hex[in[i] >> 4]) || + !CBB_add_u8(&cbb, hex[in[i] & 0xf])) { + goto err; + } + } + uint8_t *ret; + size_t unused_len; + if (!CBB_add_u8(&cbb, 0) || !CBB_finish(&cbb, &ret, &unused_len)) { + goto err; } - return wildcard_match(pattern, star - pattern, star + 1, - (pattern + pattern_len) - star - 1, subject, - subject_len, flags); -} -int bssl::x509v3_looks_like_dns_name(const unsigned char *in, size_t len) { - // This function is used as a heuristic for whether a common name is a - // hostname to be matched, or merely a decorative name to describe the - // subject. This heuristic must be applied to both name constraints and the - // common name fallback, so it must be loose enough to accept hostname - // common names, and tight enough to reject decorative common names. + return (char *)ret; - if (len > 0 && in[len - 1] == '.') { - len--; - } +err: + CBB_cleanup(&cbb); + return nullptr; +} - // Wildcards are allowed in front. - if (len >= 2 && in[0] == '*' && in[1] == '.') { - in += 2; - len -= 2; +unsigned char *bssl::x509v3_hex_to_bytes(const char *str, size_t *len) { + unsigned char *hexbuf, *q; + unsigned char ch, cl, *p; + uint8_t high, low; + if (!str) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_ARGUMENT); + return nullptr; } - - if (len == 0) { - return 0; + if (!(hexbuf = + reinterpret_cast(OPENSSL_malloc(strlen(str) >> 1)))) { + goto err; } - - size_t label_start = 0; - for (size_t i = 0; i < len; i++) { - unsigned char c = in[i]; - if (OPENSSL_isalnum(c) || (c == '-' && i > label_start) || - // These are not valid characters in hostnames, but commonly found - // in deployments outside the Web PKI. - c == '_' || c == ':') { + for (p = (unsigned char *)str, q = hexbuf; *p;) { + ch = *p++; + if (ch == ':') { continue; } - - // Labels must not be empty. - if (c == '.' && i > label_start && i < len - 1) { - label_start = i + 1; - continue; + cl = *p++; + if (!cl) { + OPENSSL_PUT_ERROR(X509V3, X509V3_R_ODD_NUMBER_OF_DIGITS); + OPENSSL_free(hexbuf); + return nullptr; + } + if (!OPENSSL_fromxdigit(&high, ch)) { + goto badhex; + } + if (!OPENSSL_fromxdigit(&low, cl)) { + goto badhex; } + *q++ = (high << 4) | low; + } - return 0; + if (len) { + *len = q - hexbuf; } - return 1; -} + return hexbuf; -// Compare an ASN1_STRING to a supplied string. If they match return 1. If -// cmp_type > 0 only compare if string matches the type, otherwise convert it -// to UTF8. +err: + OPENSSL_free(hexbuf); + return nullptr; -static int do_check_string(const ASN1_STRING *a, int cmp_type, equal_fn equal, - unsigned int flags, int check_type, const char *b, - size_t blen, char **peername) { - int rv = 0; +badhex: + OPENSSL_free(hexbuf); + OPENSSL_PUT_ERROR(X509V3, X509V3_R_ILLEGAL_HEX_DIGIT); + return nullptr; +} - if (!a->data || !a->length) { +int bssl::x509v3_conf_name_matches(const char *name, const char *cmp) { + // `name` must begin with `cmp`. + size_t len = strlen(cmp); + if (strncmp(name, cmp, len) != 0) { return 0; } - if (cmp_type > 0) { - if (cmp_type != a->type) { - return 0; - } - if (cmp_type == V_ASN1_IA5STRING) { - rv = equal(a->data, a->length, (unsigned char *)b, blen, flags); - } else if (a->length == (int)blen && !OPENSSL_memcmp(a->data, b, blen)) { - rv = 1; - } - if (rv > 0 && peername) { - *peername = OPENSSL_strndup((char *)a->data, a->length); - if (*peername == nullptr) { - return -1; - } - } - } else { - int astrlen; - unsigned char *astr; - astrlen = ASN1_STRING_to_UTF8(&astr, a); - if (astrlen < 0) { - return -1; - } - // We check the common name against DNS name constraints if it passes - // `x509v3_looks_like_dns_name`. Thus we must not consider common names - // for DNS fallbacks if they fail this check. - if (check_type == GEN_DNS && !x509v3_looks_like_dns_name(astr, astrlen)) { - rv = 0; - } else { - rv = equal(astr, astrlen, (unsigned char *)b, blen, flags); - } - if (rv > 0 && peername) { - *peername = OPENSSL_strndup((char *)astr, astrlen); - if (*peername == nullptr) { - return -1; - } - } - OPENSSL_free(astr); - } - return rv; + // `name` must either be equal to `cmp` or begin with `cmp`, followed by '.'. + return name[len] == '\0' || name[len] == '.'; } -static int do_x509_check(const X509 *x, const char *chk, size_t chklen, - unsigned int flags, int check_type, char **peername) { - int cnid = NID_undef; - int alt_type; - int rv = 0; - equal_fn equal; - if (check_type == GEN_EMAIL) { - cnid = NID_pkcs9_emailAddress; - alt_type = V_ASN1_IA5STRING; - equal = equal_email; - } else if (check_type == GEN_DNS) { - cnid = NID_commonName; - alt_type = V_ASN1_IA5STRING; - if (flags & X509_CHECK_FLAG_NO_WILDCARDS) { - equal = equal_nocase; - } else { - equal = equal_wildcard; - } - } else { - alt_type = V_ASN1_OCTET_STRING; - equal = equal_case; - } - +STACK_OF(OPENSSL_STRING) *X509_get1_email(const X509 *x) { int critical; UniquePtr gens(reinterpret_cast( X509_get_ext_d2i(x, NID_subject_alt_name, &critical, nullptr))); - if (gens) { - for (const GENERAL_NAME *gen : gens.get()) { - if (gen->type != check_type) { - continue; - } - const ASN1_STRING *cstr; - if (check_type == GEN_EMAIL) { - cstr = gen->d.rfc822Name; - } else if (check_type == GEN_DNS) { - cstr = gen->d.dNSName; - } else { - cstr = gen->d.iPAddress; - } - // Positive on success, negative on error! - if ((rv = do_check_string(cstr, alt_type, equal, flags, check_type, chk, - chklen, peername)) != 0) { - break; + if (!gens && critical != -1) { + return nullptr; + } + return get_email(X509_get_subject_name(x), gens.get()).release(); +} + +STACK_OF(OPENSSL_STRING) *X509_get1_ocsp(const X509 *x) { + UniquePtr info( + reinterpret_cast( + X509_get_ext_d2i(x, NID_info_access, nullptr, nullptr))); + if (!info) { + return nullptr; + } + UniquePtr ret; + for (const ACCESS_DESCRIPTION *ad : info.get()) { + if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) { + if (ad->location->type == GEN_URI) { + if (!append_ia5(&ret, ad->location->d.uniformResourceIdentifier)) { + return nullptr; + } } } - return rv; - } else if (critical != -1) { - // Syntax error in the subjectAltName extension. - return 0; } + sk_OPENSSL_STRING_sort_and_dedup(ret.get(), str_free); + return ret.release(); +} - // We're done if CN-ID is not pertinent - if (cnid == NID_undef || (flags & X509_CHECK_FLAG_NEVER_CHECK_SUBJECT)) { +STACK_OF(OPENSSL_STRING) *X509_REQ_get1_email(const X509_REQ *x) { + UniquePtr exts(X509_REQ_get_extensions(x)); + int critical; + UniquePtr gens(reinterpret_cast( + X509V3_get_d2i(exts.get(), NID_subject_alt_name, &critical, nullptr))); + if (!gens && critical != -1) { + return nullptr; + } + return get_email(X509_REQ_get_subject_name(x), gens.get()).release(); +} + +void X509_email_free(STACK_OF(OPENSSL_STRING) *sk) { + sk_OPENSSL_STRING_pop_free(sk, str_free); +} + +int bssl::x509v3_looks_like_dns_name(const unsigned char *in, size_t len) { + // This function is used as a heuristic for whether a common name is a + // hostname to be matched, or merely a decorative name to describe the + // subject. This heuristic must be applied to both name constraints and the + // common name fallback, so it must be loose enough to accept hostname + // common names, and tight enough to reject decorative common names. + + if (len > 0 && in[len - 1] == '.') { + len--; + } + + // Wildcards are allowed in front. + if (len >= 2 && in[0] == '*' && in[1] == '.') { + in += 2; + len -= 2; + } + + if (len == 0) { return 0; } - int j = -1; - const X509_NAME *name = X509_get_subject_name(x); - while ((j = X509_NAME_get_index_by_NID(name, cnid, j)) >= 0) { - const X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, j); - const ASN1_STRING *str = X509_NAME_ENTRY_get_data(ne); - // Positive on success, negative on error! - if ((rv = do_check_string(str, -1, equal, flags, check_type, chk, chklen, - peername)) != 0) { - return rv; + size_t label_start = 0; + for (size_t i = 0; i < len; i++) { + unsigned char c = in[i]; + if (OPENSSL_isalnum(c) || (c == '-' && i > label_start) || + // These are not valid characters in hostnames, but commonly found + // in deployments outside the Web PKI. + c == '_' || c == ':') { + continue; + } + + // Labels must not be empty. + if (c == '.' && i > label_start && i < len - 1) { + label_start = i + 1; + continue; } + + return 0; } - return 0; + + return 1; } int X509_check_host(const X509 *x, const char *chk, size_t chklen, @@ -1090,191 +1261,6 @@ int bssl::x509v3_a2i_ipadd(uint8_t ipout[16], const char *ipasc) { } } -// get_ipv4_component consumes one IPv4 component, terminated by either '.' or -// the end of the string, from `*str`. On success, it returns one, sets `*out` -// to the component, and advances `*str` to the first unconsumed character. On -// invalid input, it returns zero. -static int get_ipv4_component(uint8_t *out_byte, const char **str) { - // Store a slightly larger intermediary so the overflow check is easier. - uint32_t out = 0; - for (;;) { - if (!OPENSSL_isdigit(**str)) { - return 0; - } - out = (out * 10) + (**str - '0'); - if (out > 255) { - // Components must be 8-bit. - return 0; - } - (*str)++; - if ((**str) == '.' || (**str) == '\0') { - *out_byte = (uint8_t)out; - return 1; - } - if (out == 0) { - // Reject extra leading zeros. Parsers sometimes treat them as octal, so - // accepting them would misinterpret input. - return 0; - } - } -} - -// get_ipv4_dot consumes a '.' from `*str` and advances it. It returns one on -// success and zero if `*str` does not point to a '.'. -static int get_ipv4_dot(const char **str) { - if (**str != '.') { - return 0; - } - (*str)++; - return 1; -} - -static int ipv4_from_asc(uint8_t v4[4], const char *in) { - if (!get_ipv4_component(&v4[0], &in) || !get_ipv4_dot(&in) || - !get_ipv4_component(&v4[1], &in) || !get_ipv4_dot(&in) || - !get_ipv4_component(&v4[2], &in) || !get_ipv4_dot(&in) || - !get_ipv4_component(&v4[3], &in) || *in != '\0') { - return 0; - } - return 1; -} - -typedef struct { - // Temporary store for IPV6 output - uint8_t tmp[16]; - // Total number of bytes in tmp - int total; - // The position of a zero (corresponding to '::') - int zero_pos; - // Number of zeroes - int zero_cnt; -} IPV6_STAT; - -static int ipv6_from_asc(uint8_t v6[16], const char *in) { - IPV6_STAT v6stat; - v6stat.total = 0; - v6stat.zero_pos = -1; - v6stat.zero_cnt = 0; - // Treat the IPv6 representation as a list of values separated by ':'. - // The presence of a '::' will parse as one, two or three zero length - // elements. - if (!CONF_parse_list(in, ':', 0, ipv6_cb, &v6stat)) { - return 0; - } - - if (v6stat.zero_pos == -1) { - // If no '::' must have exactly 16 bytes - if (v6stat.total != 16) { - return 0; - } - } else { - // If '::' must have less than 16 bytes - if (v6stat.total >= 16) { - return 0; - } - if (v6stat.zero_cnt > 3) { - // More than three zeroes is an error - return 0; - } else if (v6stat.zero_cnt == 3) { - // Can only have three zeroes if nothing else present - if (v6stat.total > 0) { - return 0; - } - } else if (v6stat.zero_cnt == 2) { - // Can only have two zeroes if at start or end - if (v6stat.zero_pos != 0 && v6stat.zero_pos != v6stat.total) { - return 0; - } - } else { - // Can only have one zero if *not* start or end - if (v6stat.zero_pos == 0 || v6stat.zero_pos == v6stat.total) { - return 0; - } - } - } - - // Format the result. - if (v6stat.zero_pos >= 0) { - // Copy initial part - OPENSSL_memcpy(v6, v6stat.tmp, v6stat.zero_pos); - // Zero middle - OPENSSL_memset(v6 + v6stat.zero_pos, 0, 16 - v6stat.total); - // Copy final part - if (v6stat.total != v6stat.zero_pos) { - OPENSSL_memcpy(v6 + v6stat.zero_pos + 16 - v6stat.total, - v6stat.tmp + v6stat.zero_pos, - v6stat.total - v6stat.zero_pos); - } - } else { - OPENSSL_memcpy(v6, v6stat.tmp, 16); - } - - return 1; -} - -static int ipv6_cb(const char *elem, size_t len, void *usr) { - IPV6_STAT *s = reinterpret_cast(usr); - // Error if 16 bytes written - if (s->total == 16) { - return 0; - } - if (len == 0) { - // Zero length element, corresponds to '::' - if (s->zero_pos == -1) { - s->zero_pos = s->total; - } else if (s->zero_pos != s->total) { - // If we've already got a :: its an error - return 0; - } - if (s->zero_cnt >= 3) { - // More than three zeros is an error. - return 0; - } - s->zero_cnt++; - } else { - // If more than 4 characters could be final a.b.c.d form - if (len > 4) { - // Need at least 4 bytes left - if (s->total > 12) { - return 0; - } - // Must be end of string - if (elem[len]) { - return 0; - } - if (!ipv4_from_asc(s->tmp + s->total, elem)) { - return 0; - } - s->total += 4; - } else { - if (!ipv6_hex(s->tmp + s->total, elem, len)) { - return 0; - } - s->total += 2; - } - } - return 1; -} - -// Convert a string of up to 4 hex digits into the corresponding IPv6 form. - -static int ipv6_hex(uint8_t *out, const char *in, size_t inlen) { - if (inlen > 4) { - return 0; - } - uint16_t num = 0; - while (inlen--) { - uint8_t val; - if (!OPENSSL_fromxdigit(&val, *in++)) { - return 0; - } - num = (num << 4) | val; - } - out[0] = num >> 8; - out[1] = num & 0xff; - return 1; -} - int bssl::X509V3_NAME_from_section(X509_NAME *nm, const STACK_OF(CONF_VALUE) *dn_sk, int chtype) { diff --git a/third_party/boringssl/src/crypto/x509/x509_cmp.cc b/third_party/boringssl/src/crypto/x509/x509_cmp.cc index 4dea236..dcb8836 100644 --- a/third_party/boringssl/src/crypto/x509/x509_cmp.cc +++ b/third_party/boringssl/src/crypto/x509/x509_cmp.cc @@ -107,8 +107,8 @@ int X509_cmp(const X509 *a, const X509 *b) { // comparison and may cause misbehaving sorts by transitivity. For now, we // retain the old OpenSSL behavior, which was to ignore the error. See // https://crbug.com/boringssl/355. - x509v3_cache_extensions((X509Impl *)a_impl); - x509v3_cache_extensions((X509Impl *)b_impl); + x509v3_cache_extensions(a_impl); + x509v3_cache_extensions(b_impl); return OPENSSL_memcmp(a_impl->cert_hash, b_impl->cert_hash, SHA256_DIGEST_LENGTH); @@ -238,6 +238,6 @@ int X509_check_private_key(const X509 *x, const EVP_PKEY *k) { // Not strictly speaking an "up_ref" as a STACK doesn't have a reference // count but it has the same effect by duping the STACK and upping the ref of // each X509 structure. -STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *chain) { +STACK_OF(X509) *X509_chain_up_ref(const STACK_OF(X509) *chain) { return sk_X509_deep_copy(chain, X509_dup_ref, X509_free); } diff --git a/third_party/boringssl/src/crypto/x509/x509_ext.cc b/third_party/boringssl/src/crypto/x509/x509_ext.cc index db99212..b2ddb57 100644 --- a/third_party/boringssl/src/crypto/x509/x509_ext.cc +++ b/third_party/boringssl/src/crypto/x509/x509_ext.cc @@ -24,6 +24,20 @@ using namespace bssl; +namespace { + +X509_EXTENSION *delete_ext(STACK_OF(X509_EXTENSION) **exts, int loc) { + X509_EXTENSION *ext = X509v3_delete_ext(*exts, loc); + // Empty extension lists are omitted. + if (*exts != nullptr && sk_X509_EXTENSION_num(*exts) == 0) { + sk_X509_EXTENSION_pop_free(*exts, X509_EXTENSION_free); + *exts = nullptr; + } + return ext; +} + +} // namespace + int X509_CRL_get_ext_count(const X509_CRL *x) { return X509v3_get_ext_count(x->crl->extensions); } @@ -45,16 +59,6 @@ X509_EXTENSION *X509_CRL_get_ext(const X509_CRL *x, int loc) { return X509v3_get_ext(x->crl->extensions, loc); } -static X509_EXTENSION *delete_ext(STACK_OF(X509_EXTENSION) **exts, int loc) { - X509_EXTENSION *ext = X509v3_delete_ext(*exts, loc); - // Empty extension lists are omitted. - if (*exts != nullptr && sk_X509_EXTENSION_num(*exts) == 0) { - sk_X509_EXTENSION_pop_free(*exts, X509_EXTENSION_free); - *exts = nullptr; - } - return ext; -} - X509_EXTENSION *X509_CRL_delete_ext(X509_CRL *x, int loc) { return delete_ext(&x->crl->extensions, loc); } diff --git a/third_party/boringssl/src/crypto/x509/x509_lu.cc b/third_party/boringssl/src/crypto/x509/x509_lu.cc index 126bf33..896337f 100644 --- a/third_party/boringssl/src/crypto/x509/x509_lu.cc +++ b/third_party/boringssl/src/crypto/x509/x509_lu.cc @@ -30,22 +30,10 @@ using namespace bssl; -static int X509_OBJECT_idx_by_subject(STACK_OF(X509_OBJECT) *h, int type, - const X509_NAME *name); -static X509_OBJECT *X509_OBJECT_retrieve_by_subject(STACK_OF(X509_OBJECT) *h, - int type, - const X509_NAME *name); -static X509_OBJECT *X509_OBJECT_retrieve_match(STACK_OF(X509_OBJECT) *h, - X509_OBJECT *x); -static int X509_OBJECT_up_ref_count(X509_OBJECT *a); - -static X509_LOOKUP *X509_LOOKUP_new(const X509_LOOKUP_METHOD *method, - X509_STORE *store); -static int X509_LOOKUP_by_subject(X509_LOOKUP *ctx, int type, - const X509_NAME *name, X509_OBJECT *ret); - -static X509_LOOKUP *X509_LOOKUP_new(const X509_LOOKUP_METHOD *method, - X509_STORE *store) { +namespace { + +X509_LOOKUP *X509_LOOKUP_new(const X509_LOOKUP_METHOD *method, + X509_STORE *store) { X509_LOOKUP *ret = New(); if (ret == nullptr) { return nullptr; @@ -60,30 +48,8 @@ static X509_LOOKUP *X509_LOOKUP_new(const X509_LOOKUP_METHOD *method, return ret; } -void X509_LOOKUP_free(X509_LOOKUP *ctx) { - if (ctx == nullptr) { - return; - } - if (ctx->method != nullptr && ctx->method->free != nullptr) { - (*ctx->method->free)(ctx); - } - Delete(ctx); -} - -int X509_LOOKUP_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc, long argl, - char **ret) { - if (ctx->method == nullptr) { - return -1; - } - if (ctx->method->ctrl != nullptr) { - return ctx->method->ctrl(ctx, cmd, argc, argl, ret); - } else { - return 1; - } -} - -static int X509_LOOKUP_by_subject(X509_LOOKUP *ctx, int type, - const X509_NAME *name, X509_OBJECT *ret) { +int X509_LOOKUP_by_subject(X509_LOOKUP *ctx, int type, const X509_NAME *name, + X509_OBJECT *ret) { if (ctx->method == nullptr || ctx->method->get_by_subject == nullptr) { return 0; } @@ -96,8 +62,8 @@ static int X509_LOOKUP_by_subject(X509_LOOKUP *ctx, int type, // x509_object_cmp_name compares `a` against the specified type and name. This // avoids needing to construct a reference certificate or CRL. -static int x509_object_cmp_name(const X509_OBJECT *a, int type, - const X509_NAME *name) { +int x509_object_cmp_name(const X509_OBJECT *a, int type, + const X509_NAME *name) { int ret = a->type - type; if (ret) { return ret; @@ -113,7 +79,7 @@ static int x509_object_cmp_name(const X509_OBJECT *a, int type, } } -static int x509_object_cmp(const X509_OBJECT *a, const X509_OBJECT *b) { +int x509_object_cmp(const X509_OBJECT *a, const X509_OBJECT *b) { switch (b->type) { case X509_LU_X509: return x509_object_cmp_name(a, b->type, @@ -126,11 +92,182 @@ static int x509_object_cmp(const X509_OBJECT *a, const X509_OBJECT *b) { } } -static int x509_object_cmp_sk(const X509_OBJECT *const *a, - const X509_OBJECT *const *b) { +int x509_object_cmp_sk(const X509_OBJECT *const *a, + const X509_OBJECT *const *b) { return x509_object_cmp(*a, *b); } +int X509_OBJECT_up_ref_count(X509_OBJECT *a) { + switch (a->type) { + case X509_LU_X509: + X509_up_ref(a->data.x509); + break; + case X509_LU_CRL: + X509_CRL_up_ref(a->data.crl); + break; + } + return 1; +} + +int x509_object_idx_cnt(STACK_OF(X509_OBJECT) *h, int type, + const X509_NAME *name, int *out_num_match) { + sk_X509_OBJECT_sort(h); + + // Find the first matching object. `sk_X509_OBJECT_find` would require + // constructing an `X509` or `X509_CRL` object, so implement our own binary + // search. + size_t start = 0, end = sk_X509_OBJECT_num(h); + while (end - start > 1) { + // Bias `mid` towards `start`. The range has more than one element, so `mid` + // is not the last element. + size_t mid = start + (end - start - 1) / 2; + assert(start <= mid && mid + 1 < end); + int r = x509_object_cmp_name(sk_X509_OBJECT_value(h, mid), type, name); + if (r < 0) { + start = mid + 1; // `mid` is too low. + } else if (r > 0) { + end = mid; // `mid` is too high. + } else { + // `mid` matches, but we need to keep searching to find the first match. + end = mid + 1; + } + } + if (start == end || + x509_object_cmp_name(sk_X509_OBJECT_value(h, start), type, name) != 0) { + return -1; + } + + if (out_num_match != nullptr) { + *out_num_match = 1; + for (size_t tidx = start + 1; tidx < sk_X509_OBJECT_num(h); tidx++) { + const X509_OBJECT *tobj = sk_X509_OBJECT_value(h, tidx); + if (x509_object_cmp_name(tobj, type, name) != 0) { + break; + } + (*out_num_match)++; + } + } + + assert(start <= INT_MAX); // `STACK_OF(T)` never stores more than `INT_MAX`. + return static_cast(start); +} + +int X509_OBJECT_idx_by_subject(STACK_OF(X509_OBJECT) *h, int type, + const X509_NAME *name) { + return x509_object_idx_cnt(h, type, name, nullptr); +} + +X509_OBJECT *X509_OBJECT_retrieve_by_subject(STACK_OF(X509_OBJECT) *h, int type, + const X509_NAME *name) { + int idx; + idx = X509_OBJECT_idx_by_subject(h, type, name); + if (idx == -1) { + return nullptr; + } + return sk_X509_OBJECT_value(h, idx); +} + +X509_OBJECT *x509_object_dup(const X509_OBJECT *obj) { + X509_OBJECT *ret = X509_OBJECT_new(); + if (ret == nullptr) { + return nullptr; + } + ret->type = obj->type; + ret->data = obj->data; + X509_OBJECT_up_ref_count(ret); + return ret; +} + +X509_OBJECT *X509_OBJECT_retrieve_match(STACK_OF(X509_OBJECT) *h, + X509_OBJECT *x) { + sk_X509_OBJECT_sort(h); + size_t idx; + if (!sk_X509_OBJECT_find(h, &idx, x)) { + return nullptr; + } + if ((x->type != X509_LU_X509) && (x->type != X509_LU_CRL)) { + return sk_X509_OBJECT_value(h, idx); + } + for (size_t i = idx; i < sk_X509_OBJECT_num(h); i++) { + X509_OBJECT *obj = sk_X509_OBJECT_value(h, i); + if (x509_object_cmp(obj, x)) { + return nullptr; + } + if (x->type == X509_LU_X509) { + if (!X509_cmp(obj->data.x509, x->data.x509)) { + return obj; + } + } else if (x->type == X509_LU_CRL) { + if (!X509_CRL_match(obj->data.crl, x->data.crl)) { + return obj; + } + } else { + return obj; + } + } + return nullptr; +} + +int x509_store_add(X509Store *ctx, const void *x, int is_crl) { + if (x == nullptr) { + return 0; + } + + X509_OBJECT *const obj = X509_OBJECT_new(); + if (obj == nullptr) { + return 0; + } + + if (is_crl) { + obj->type = X509_LU_CRL; + obj->data.crl = X509_CRL_dup_ref(static_cast(x)); + } else { + obj->type = X509_LU_X509; + obj->data.x509 = X509_dup_ref(static_cast(x)); + } + + ctx->objs_lock.LockWrite(); + + int ret = 1; + int added = 0; + // Duplicates are silently ignored + if (!X509_OBJECT_retrieve_match(ctx->objs.get(), obj)) { + ret = added = (sk_X509_OBJECT_push(ctx->objs.get(), obj) != 0); + } + + ctx->objs_lock.UnlockWrite(); + + if (!added) { + X509_OBJECT_free(obj); + } + + return ret; +} + +} // namespace + +void X509_LOOKUP_free(X509_LOOKUP *ctx) { + if (ctx == nullptr) { + return; + } + if (ctx->method != nullptr && ctx->method->free != nullptr) { + (*ctx->method->free)(ctx); + } + Delete(ctx); +} + +int X509_LOOKUP_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc, long argl, + char **ret) { + if (ctx->method == nullptr) { + return -1; + } + if (ctx->method->ctrl != nullptr) { + return ctx->method->ctrl(ctx, cmd, argc, argl, ret); + } else { + return 1; + } +} + X509Store::X509Store() : RefCounted(CheckSubClass()), objs(sk_X509_OBJECT_new(x509_object_cmp_sk)), @@ -149,6 +286,13 @@ int X509_STORE_up_ref(X509_STORE *store) { return 1; } +X509_STORE *X509_STORE_dup_ref(const X509_STORE *store) { + if (store == nullptr) { + return nullptr; + } + return FromOpaque(store)->DupRefInternal(); +} + void X509_STORE_free(X509_STORE *vfy) { if (vfy == nullptr) { return; @@ -204,48 +348,11 @@ int X509_STORE_CTX_get_by_subject(X509_STORE_CTX *vs, int type, return 1; } -static int x509_store_add(X509Store *ctx, void *x, int is_crl) { - if (x == nullptr) { - return 0; - } - - X509_OBJECT *const obj = X509_OBJECT_new(); - if (obj == nullptr) { - return 0; - } - - if (is_crl) { - obj->type = X509_LU_CRL; - obj->data.crl = (X509_CRL *)x; - } else { - obj->type = X509_LU_X509; - obj->data.x509 = (X509 *)x; - } - X509_OBJECT_up_ref_count(obj); - - ctx->objs_lock.LockWrite(); - - int ret = 1; - int added = 0; - // Duplicates are silently ignored - if (!X509_OBJECT_retrieve_match(ctx->objs.get(), obj)) { - ret = added = (sk_X509_OBJECT_push(ctx->objs.get(), obj) != 0); - } - - ctx->objs_lock.UnlockWrite(); - - if (!added) { - X509_OBJECT_free(obj); - } - - return ret; -} - -int X509_STORE_add_cert(X509_STORE *ctx, X509 *x) { +int X509_STORE_add_cert(X509_STORE *ctx, const X509 *x) { return x509_store_add(FromOpaque(ctx), x, /*is_crl=*/0); } -int X509_STORE_add_crl(X509_STORE *ctx, X509_CRL *x) { +int X509_STORE_add_crl(X509_STORE *ctx, const X509_CRL *x) { return x509_store_add(FromOpaque(ctx), x, /*is_crl=*/1); } @@ -259,18 +366,6 @@ void X509_OBJECT_free(X509_OBJECT *obj) { Delete(obj); } -static int X509_OBJECT_up_ref_count(X509_OBJECT *a) { - switch (a->type) { - case X509_LU_X509: - X509_up_ref(a->data.x509); - break; - case X509_LU_CRL: - X509_CRL_up_ref(a->data.crl); - break; - } - return 1; -} - void X509_OBJECT_free_contents(X509_OBJECT *a) { switch (a->type) { case X509_LU_X509: @@ -293,76 +388,6 @@ X509 *X509_OBJECT_get0_X509(const X509_OBJECT *a) { return a->data.x509; } -static int x509_object_idx_cnt(STACK_OF(X509_OBJECT) *h, int type, - const X509_NAME *name, int *out_num_match) { - sk_X509_OBJECT_sort(h); - - // Find the first matching object. `sk_X509_OBJECT_find` would require - // constructing an `X509` or `X509_CRL` object, so implement our own binary - // search. - size_t start = 0, end = sk_X509_OBJECT_num(h); - while (end - start > 1) { - // Bias `mid` towards `start`. The range has more than one element, so `mid` - // is not the last element. - size_t mid = start + (end - start - 1) / 2; - assert(start <= mid && mid + 1 < end); - int r = x509_object_cmp_name(sk_X509_OBJECT_value(h, mid), type, name); - if (r < 0) { - start = mid + 1; // `mid` is too low. - } else if (r > 0) { - end = mid; // `mid` is too high. - } else { - // `mid` matches, but we need to keep searching to find the first match. - end = mid + 1; - } - } - if (start == end || - x509_object_cmp_name(sk_X509_OBJECT_value(h, start), type, name) != 0) { - return -1; - } - - if (out_num_match != nullptr) { - *out_num_match = 1; - for (size_t tidx = start + 1; tidx < sk_X509_OBJECT_num(h); tidx++) { - const X509_OBJECT *tobj = sk_X509_OBJECT_value(h, tidx); - if (x509_object_cmp_name(tobj, type, name) != 0) { - break; - } - (*out_num_match)++; - } - } - - assert(start <= INT_MAX); // `STACK_OF(T)` never stores more than `INT_MAX`. - return static_cast(start); -} - -static int X509_OBJECT_idx_by_subject(STACK_OF(X509_OBJECT) *h, int type, - const X509_NAME *name) { - return x509_object_idx_cnt(h, type, name, nullptr); -} - -static X509_OBJECT *X509_OBJECT_retrieve_by_subject(STACK_OF(X509_OBJECT) *h, - int type, - const X509_NAME *name) { - int idx; - idx = X509_OBJECT_idx_by_subject(h, type, name); - if (idx == -1) { - return nullptr; - } - return sk_X509_OBJECT_value(h, idx); -} - -static X509_OBJECT *x509_object_dup(const X509_OBJECT *obj) { - X509_OBJECT *ret = X509_OBJECT_new(); - if (ret == nullptr) { - return nullptr; - } - ret->type = obj->type; - ret->data = obj->data; - X509_OBJECT_up_ref_count(ret); - return ret; -} - STACK_OF(X509_OBJECT) *X509_STORE_get1_objects(X509_STORE *store) { auto *impl = FromOpaque(store); MutexReadLock lock(&impl->objs_lock); @@ -456,36 +481,6 @@ STACK_OF(X509_CRL) *X509_STORE_CTX_get1_crls(X509_STORE_CTX *ctx, return sk; } -static X509_OBJECT *X509_OBJECT_retrieve_match(STACK_OF(X509_OBJECT) *h, - X509_OBJECT *x) { - sk_X509_OBJECT_sort(h); - size_t idx; - if (!sk_X509_OBJECT_find(h, &idx, x)) { - return nullptr; - } - if ((x->type != X509_LU_X509) && (x->type != X509_LU_CRL)) { - return sk_X509_OBJECT_value(h, idx); - } - for (size_t i = idx; i < sk_X509_OBJECT_num(h); i++) { - X509_OBJECT *obj = sk_X509_OBJECT_value(h, i); - if (x509_object_cmp(obj, x)) { - return nullptr; - } - if (x->type == X509_LU_X509) { - if (!X509_cmp(obj->data.x509, x->data.x509)) { - return obj; - } - } else if (x->type == X509_LU_CRL) { - if (!X509_CRL_match(obj->data.crl, x->data.crl)) { - return obj; - } - } else { - return obj; - } - } - return nullptr; -} - int X509_STORE_CTX_get1_issuer(X509 **out_issuer, X509_STORE_CTX *ctx, const X509 *x) { X509_OBJECT obj; diff --git a/third_party/boringssl/src/crypto/x509/x509_mtc.cc b/third_party/boringssl/src/crypto/x509/x509_mtc.cc index 989dd42..87466da 100644 --- a/third_party/boringssl/src/crypto/x509/x509_mtc.cc +++ b/third_party/boringssl/src/crypto/x509/x509_mtc.cc @@ -38,17 +38,16 @@ namespace { // Prefix for domain separation to denote a Merkle Tree leaf or interior node. constexpr uint8_t kMTCLeafDomainSeparator[] = {0x00}; constexpr uint8_t kMTCNodeDomainSeparator[] = {0x01}; -// DER encoding of AlgorithmIdentifier for alg-mtcProof-draft with absent -// parameters. -// SEQUENCE (12 bytes) { -// OBJECT IDENTIFIER 1.3.6.1.4.1.44363.47.0 (10 bytes) +// DER encoding of AlgorithmIdentifier for alg-mtcProof with absent parameters. +// SEQUENCE (10 bytes) { +// OBJECT IDENTIFIER 1.3.6.1.5.5.7.6.67 (8 bytes) // } constexpr uint8_t kMTCAlgorithmIdentifier[] = { 0x30, // SEQUENCE tag - 12, // tag + len + OID bytes + 10, // tag + len + OID bytes 0x06, // OBJECT tag - 10, // OID length - OBJ_ENC_alg_mtcProof_draft, + 8, // OID length + OBJ_ENC_alg_mtcProof, }; // MTCLogEntryType enum value for tbs_cert_entry. constexpr uint8_t kMTCLogEntryTypeTBSCertEntry[] = {0x00, 0x01}; @@ -64,6 +63,8 @@ constexpr uint8_t kASCIIOIDPrefix[16] = {'o', 'i', 'd', '/', '1', '.', '4', '.', '1', '.'}; // DER encoded OID component found in trust anchor IDs for issuance logs. constexpr uint8_t kEncOIDLogs = 0x00; +// draft-ietf-tls-trust-anchor-ids-06 limits trust anchor IDs to 32 bytes. +constexpr size_t kMaxTrustAnchorIdBytes = 32; constexpr CBS_ASN1_TAG kTBSVersionTag = CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0; @@ -88,10 +89,18 @@ inline bool lsb(uint64_t n) { return n & 1; } // is_mtc_proof returns whether `algor` is an mtcProof AlgorithmIdentifier. bool is_mtc_proof(const X509_ALGOR *algor) { - return OBJ_obj2nid(algor->algorithm) == NID_alg_mtcProof_draft && + return OBJ_obj2nid(algor->algorithm) == NID_alg_mtcProof && algor->parameter == nullptr; } +// is_mtc_serial_valid returns whether `serial` is within +// (mtcMinSerial..mtcMaxSerial), which implies the log number is > 0. +bool is_mtc_serial_valid(uint64_t serial) { + // mtcMinSerial is 2^48. mtcMaxSerial is 2^64-1, the largest number + // representable as uint64_t, so is not checked explicitly. + return serial >> 48; +} + // Returns the first hash value (of size `log_hash_size`) remaining in // `inclusion_proof` and advances `inclusion_proof` past the returned value. // Returns an empty span if there are no more hash values of the appropriate @@ -135,8 +144,32 @@ bool DigestUpdateNextASN1Element(EVP_MD_CTX *ctx, CBS *cbs) { return EVP_DigestUpdate(ctx, CBS_data(&element), CBS_len(&element)); } +// CheckMTCLogEntryExtensions returns whether `extensions` is a well-formed list +// of MTCLogEntryExtension structures, sorted in strictly ascending order by +// extension type (see section 5.2.1). No extension types are currently +// recognized, so the contents are otherwise ignored (see section 12.5). +bool CheckMTCLogEntryExtensions(CBS extensions) { + std::optional prev_type; + while (CBS_len(&extensions) > 0) { + uint16_t type; + CBS data; + if (!CBS_get_u16(&extensions, &type) || + !CBS_get_u16_length_prefixed(&extensions, &data)) { + OPENSSL_PUT_ERROR(X509, X509_R_INVALID_MTC_PROOF); + return false; + } + if (prev_type.has_value() && *prev_type >= type) { + OPENSSL_PUT_ERROR(X509, X509_R_INVALID_MTC_PROOF); + return false; + } + prev_type = type; + } + return true; +} + // MTCCACosigner represents a Merkle Tree CA and its corresponding CA cosigner // (see draft-ietf-plants-merkle-tree-certs, section 5.5). +// Only id-pe-mtcCertificationAuthority-SHA256 is supported. class MTCCACosigner { public: MTCCACosigner() = default; @@ -147,65 +180,71 @@ class MTCCACosigner { // its MTCCertificationAuthority extension. `pkey` is the public key // previously parsed from `x509`. Returns true if successfully initialized an // MTCCACosigner representing a valid MTC CA, or false on error. - bool Init(const X509 *x509, const EVP_PKEY *pkey) { + bool Init(const X509_STORE_CTX *ctx, const X509 *x509, const EVP_PKEY *pkey) { // Get and parse the MTCCertificationAuthority extension (see section 5.5). int ext_index = - X509_get_ext_by_NID(x509, NID_pe_mtcCertificationAuthority_draft, -1); + X509_get_ext_by_NID(x509, NID_pe_mtcCertificationAuthority_SHA256, -1); const X509_EXTENSION *ext = X509_get_ext(x509, ext_index); - if (ext == nullptr || !X509_EXTENSION_get_critical(ext)) { + if (ext == nullptr || !X509_EXTENSION_get_critical(ext) || + // Check for duplicate MTC CA extensions. + // TODO(crbug.com/42290240): If the parser is tightened to check for + // duplicate extensions earlier, this check can be removed. + X509_get_ext_by_NID(x509, NID_pe_mtcCertificationAuthority_SHA256, + ext_index) >= 0) { OPENSSL_PUT_ERROR(X509, X509_R_INVALID_MTC_CA); return false; } const ASN1_STRING *value = X509_EXTENSION_get_data(ext); - CBS ext_value; + CBS ext_value, seq; CBS_init(&ext_value, ASN1_STRING_get0_data(value), ASN1_STRING_length(value)); - - CBS seq, log_hash; - if (!CBS_get_asn1(&ext_value, &seq, CBS_ASN1_SEQUENCE) || // - !CBS_get_asn1_element(&seq, &log_hash, CBS_ASN1_SEQUENCE) || // - !x509_parse_algorithm(&seq, cosign_sigalg_.get()) || // - !CBS_get_asn1_uint64(&seq, &min_serial_) || // - !CBS_get_asn1_uint64(&seq, &max_serial_) || // + if (!CBS_get_asn1(&ext_value, &seq, CBS_ASN1_SEQUENCE) || // + CBS_len(&ext_value) != 0 || // + !x509_parse_algorithm(&seq, cosign_sigalg_.get()) || // + !CBS_get_asn1_uint64(&seq, &min_serial_) || // + !CBS_get_asn1_uint64(&seq, &max_serial_) || // CBS_len(&seq) != 0) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); return false; } - log_hash_ = EVP_parse_digest_algorithm(&log_hash); - if (log_hash_ == nullptr) { + if (!x509_sig_nid_allowed(ctx, OBJ_obj2nid(cosign_sigalg_->algorithm))) { + OPENSSL_PUT_ERROR(X509, X509_R_INVALID_MTC_CA); return false; } - if (CBS_len(&log_hash) != 0) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + if (!is_mtc_serial_valid(min_serial_) || + !is_mtc_serial_valid(max_serial_)) { + OPENSSL_PUT_ERROR(X509, X509_R_INVALID_MTC_CA); return false; } - // Extract the CA ID from the subject (see section 5.1). const X509_NAME *subject = X509_get_subject_name(x509); int tai_index = - X509_NAME_get_index_by_NID(subject, NID_rdna_trustAnchorID_draft, -1); + X509_NAME_get_index_by_NID(subject, NID_rdna_trustAnchorID, -1); if (tai_index < 0 || X509_NAME_entry_count(subject) != 1) { OPENSSL_PUT_ERROR(X509, X509_R_INVALID_MTC_CA); return false; } - // For initial experimentation, the attribute's value is a UTF8String - // containing the trust anchor ID's ASCII representation. - const ASN1_STRING *tai_ascii = + const ASN1_STRING *tai = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject, tai_index)); - if (ASN1_STRING_type(tai_ascii) != V_ASN1_UTF8STRING) { + // RELATIVE-OID has no dedicated ASN1_STRING representation, so the value + // is stored as V_ASN1_OTHER containing the entire element. + if (ASN1_STRING_type(tai) != V_ASN1_OTHER) { OPENSSL_PUT_ERROR(X509, X509_R_WRONG_TYPE); return false; } - std::string_view tai_ascii_str = BytesAsStringView( - Span(ASN1_STRING_get0_data(tai_ascii), ASN1_STRING_length(tai_ascii))); - ScopedCBB ca_id_enc; - if (!CBB_init(ca_id_enc.get(), 64) || - !CBB_add_asn1_relative_oid_from_text( - ca_id_enc.get(), tai_ascii_str.data(), tai_ascii_str.size())) { + CBS tai_elem, tai_relative_oid; + CBS_init(&tai_elem, ASN1_STRING_get0_data(tai), ASN1_STRING_length(tai)); + if (!CBS_get_asn1(&tai_elem, &tai_relative_oid, CBS_ASN1_RELATIVE_OID) || + CBS_len(&tai_elem) != 0 || + !CBS_is_valid_asn1_relative_oid(&tai_relative_oid)) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_OBJECT_ENCODING); return false; } - if (!CBBFinishArray(ca_id_enc.get(), &ca_id_enc_oid_)) { + if (CBS_len(&tai_relative_oid) > kMaxTrustAnchorIdBytes) { + OPENSSL_PUT_ERROR(X509, X509_R_INVALID_MTC_CA); + return false; + } + if (!ca_id_enc_oid_.CopyFrom(tai_relative_oid)) { OPENSSL_PUT_ERROR(X509, ERR_R_INTERNAL_ERROR); return false; } @@ -215,7 +254,9 @@ class MTCCACosigner { } bool IsSerialInRange(uint64_t serial) const { - return min_serial_ <= serial && serial <= max_serial_; + bool ok = min_serial_ <= serial && serial <= max_serial_; + assert(!ok || is_mtc_serial_valid(serial)); + return ok; } // Constructs CosignedMessage and computes signature. @@ -248,7 +289,7 @@ class MTCCACosigner { return trust_anchor_id == ca_id_enc_oid_; } - const EVP_MD *log_hash() const { return log_hash_; } + const EVP_MD *log_hash() const { return EVP_sha256(); } private: // WriteTaiAscii concatenates the trust anchor ID prefix with the CA ID as a @@ -256,9 +297,9 @@ class MTCCACosigner { // OID components from `oid_suffix`, and writes the ASCII string // representation of the full trust anchor ID to `out`. bool WriteTaiAscii(CBB *out, Span oid_suffix = {}) const { - // Trust anchor IDs are constrained to 256 bytes by spec (and are typically - // much shorter). - uint8_t id[256]; + // Trust anchor IDs such as the CA ID are limited to 32 bytes by spec, but + // `oid_suffix` may add additional bytes. + uint8_t id[2 * kMaxTrustAnchorIdBytes]; CBB id_cbb; if (!CBB_init_fixed(&id_cbb, id, sizeof(id)) || !CBB_add_bytes(&id_cbb, ca_id_enc_oid_.data(), ca_id_enc_oid_.size())) { @@ -301,21 +342,20 @@ class MTCCACosigner { // 5.1 and 5.4), in the form of a DER-encoded relative OID. This does not // include any framing, only the element's contents. Array ca_id_enc_oid_; - // Log hash algorithm. - const EVP_MD *log_hash_ = nullptr; // Public key of the CA cosigner. UniquePtr cosign_pubkey_; // Signature algorithm for CA cosigner signatures. ScopedX509Algor cosign_sigalg_; - // Min and max allowed serial number, (0..2^64-1). + // Min and max allowed serial number, both (2^48 .. 2^64-1). uint64_t min_serial_ = 0u; uint64_t max_serial_ = 0u; }; } // namespace +// Only id-pe-mtcCertificationAuthority-SHA256 is supported. bool x509_is_merkle_tree_ca(const X509 *x509) { - return X509_get_ext_by_NID(x509, NID_pe_mtcCertificationAuthority_draft, + return X509_get_ext_by_NID(x509, NID_pe_mtcCertificationAuthority_SHA256, -1) >= 0; } @@ -387,10 +427,10 @@ bool x509_evaluate_mtc_subtree_inclusion_proof( return true; } -int x509_verify_mtc(const X509 *x509, const EVP_PKEY *pkey, - const X509 *issuer) { +int x509_verify_mtc(const X509_STORE_CTX *ctx, const X509 *x509, + const EVP_PKEY *pkey, const X509 *issuer) { MTCCACosigner issuer_mtc_ca; - if (!issuer_mtc_ca.Init(issuer, pkey)) { + if (!issuer_mtc_ca.Init(ctx, issuer, pkey)) { return 0; } @@ -420,11 +460,14 @@ int x509_verify_mtc(const X509 *x509, const EVP_PKEY *pkey, !CBS_get_u48(&mtc_proof, &subtree_start) || !CBS_get_u48(&mtc_proof, &subtree_end) || !CBS_get_u16_length_prefixed(&mtc_proof, &inclusion_proof) || - !CBS_get_u16_length_prefixed(&mtc_proof, &signatures) || + !CBS_get_u24_length_prefixed(&mtc_proof, &signatures) || CBS_len(&mtc_proof) != 0) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); return 0; } + if (!CheckMTCLogEntryExtensions(extensions)) { + return 0; + } // Iterate through the subtree signatures array to check that they conform to // spec, and identify the subtree signature from the CA cosigner. @@ -434,8 +477,7 @@ int x509_verify_mtc(const X509 *x509, const EVP_PKEY *pkey, while (CBS_len(&signatures) > 0) { if (!CBS_get_u8_length_prefixed(&signatures, &cosigner_id) || CBS_len(&cosigner_id) == 0 || - !CBS_get_u16_length_prefixed(&signatures, &signature) || - CBS_len(&signature) == 0) { + !CBS_get_u16_length_prefixed(&signatures, &signature)) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); return 0; } @@ -496,12 +538,9 @@ int x509_verify_mtc(const X509 *x509, const EVP_PKEY *pkey, return 0; } // `index` is the least significant 48 bits of `serial`. - uint64_t index = serial & ((uint64_t{1} << 48) - 1); - uint64_t log_number = serial >> 48; - if (log_number == 0) { - OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PARAMETER); - return 0; - } + const uint64_t index = serial & ((uint64_t{1} << 48) - 1); + const uint64_t log_number = serial >> 48; + assert(is_mtc_serial_valid(serial)); // The TBSCertificate's `signature` field must match the expected MTC // signature algorithm identifier. @@ -544,9 +583,13 @@ int x509_verify_mtc(const X509 *x509, const EVP_PKEY *pkey, } uint8_t spki_digest[EVP_MAX_MD_SIZE]; unsigned int spki_digest_len; + // The short-form DER length can only encode lengths up to 127 (0x7f). The MTC + // spec permits longer hash lengths up to 255 (0xff), which would require a + // long-form length, but no `EVP_MD` currently outputs more than 127 bytes, so + // reject them here instead of supporting both short and long encoding forms. if (!EVP_Digest(CBS_data(&spki), CBS_len(&spki), spki_digest, &spki_digest_len, issuer_mtc_ca.log_hash(), nullptr) || - spki_digest_len == 0 || spki_digest_len > 0xff) { + spki_digest_len == 0 || spki_digest_len > 0x7f) { OPENSSL_PUT_ERROR(X509, ERR_R_INTERNAL_ERROR); return 0; } diff --git a/third_party/boringssl/src/crypto/x509/x509_req.cc b/third_party/boringssl/src/crypto/x509/x509_req.cc index be68c4f..8ed277f 100644 --- a/third_party/boringssl/src/crypto/x509/x509_req.cc +++ b/third_party/boringssl/src/crypto/x509/x509_req.cc @@ -28,6 +28,22 @@ using namespace bssl; +namespace { + +int X509_REQ_add0_attr(X509_REQ *req, X509_ATTRIBUTE *attr) { + if (req->req_info->attributes == nullptr) { + req->req_info->attributes = sk_X509_ATTRIBUTE_new_null(); + } + if (req->req_info->attributes == nullptr || + !sk_X509_ATTRIBUTE_push(req->req_info->attributes, attr)) { + return 0; + } + + return 1; +} + +} // namespace + long X509_REQ_get_version(const X509_REQ *req) { return ASN1_INTEGER_get(req->req_info->version); } @@ -169,18 +185,6 @@ X509_ATTRIBUTE *X509_REQ_delete_attr(X509_REQ *req, int loc) { return sk_X509_ATTRIBUTE_delete(req->req_info->attributes, loc); } -static int X509_REQ_add0_attr(X509_REQ *req, X509_ATTRIBUTE *attr) { - if (req->req_info->attributes == nullptr) { - req->req_info->attributes = sk_X509_ATTRIBUTE_new_null(); - } - if (req->req_info->attributes == nullptr || - !sk_X509_ATTRIBUTE_push(req->req_info->attributes, attr)) { - return 0; - } - - return 1; -} - int X509_REQ_add1_attr(X509_REQ *req, const X509_ATTRIBUTE *attr) { X509_ATTRIBUTE *new_attr = X509_ATTRIBUTE_dup(attr); if (new_attr == nullptr || !X509_REQ_add0_attr(req, new_attr)) { diff --git a/third_party/boringssl/src/crypto/x509/x509_set.cc b/third_party/boringssl/src/crypto/x509/x509_set.cc index ae45063..2ede541 100644 --- a/third_party/boringssl/src/crypto/x509/x509_set.cc +++ b/third_party/boringssl/src/crypto/x509/x509_set.cc @@ -143,7 +143,7 @@ void X509_get0_uids(const X509 *x509, const ASN1_BIT_STRING **out_issuer_uid, } } -int X509_set_pubkey(X509 *x, EVP_PKEY *pkey) { +int X509_set_pubkey(X509 *x, const EVP_PKEY *pkey) { if (x == nullptr) { return 0; } diff --git a/third_party/boringssl/src/crypto/x509/x509_trs.cc b/third_party/boringssl/src/crypto/x509/x509_trs.cc index f558992..7990ecd 100644 --- a/third_party/boringssl/src/crypto/x509/x509_trs.cc +++ b/third_party/boringssl/src/crypto/x509/x509_trs.cc @@ -23,20 +23,60 @@ using namespace bssl; +namespace { + typedef struct x509_trust_st X509_TRUST; struct x509_trust_st { int trust; - int (*check_trust)(const X509_TRUST *, X509 *); + int (*check_trust)(const X509_TRUST *, const X509 *); int nid; } /* X509_TRUST */; -static int trust_1oidany(const X509_TRUST *trust, X509 *x); -static int trust_compat(const X509_TRUST *trust, X509 *x); +int obj_trust(int id, const X509 *x) { + auto *impl = FromOpaque(x); + X509_CERT_AUX *ax = impl->aux; + if (!ax) { + return X509_TRUST_UNTRUSTED; + } + for (size_t i = 0; i < sk_ASN1_OBJECT_num(ax->reject); i++) { + const ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(ax->reject, i); + if (OBJ_obj2nid(obj) == id) { + return X509_TRUST_REJECTED; + } + } + for (size_t i = 0; i < sk_ASN1_OBJECT_num(ax->trust); i++) { + const ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(ax->trust, i); + if (OBJ_obj2nid(obj) == id) { + return X509_TRUST_TRUSTED; + } + } + return X509_TRUST_UNTRUSTED; +} + +int trust_compat(const X509_TRUST *trust, const X509 *x) { + auto *impl = FromOpaque(x); + if (!x509v3_cache_extensions(x)) { + return X509_TRUST_UNTRUSTED; + } + if (impl->ex_flags & EXFLAG_SS) { + return X509_TRUST_TRUSTED; + } else { + return X509_TRUST_UNTRUSTED; + } +} -static int obj_trust(int id, X509 *x); +int trust_1oidany(const X509_TRUST *trust, const X509 *x) { + auto *impl = FromOpaque(x); + if (impl->aux && (impl->aux->trust || impl->aux->reject)) { + return obj_trust(trust->nid, impl); + } + // we don't have any trust settings: for compatibility we return trusted + // if it is self signed + return trust_compat(trust, impl); +} -static const X509_TRUST trstandard[] = { +const X509_TRUST trstandard[] = { {X509_TRUST_COMPAT, trust_compat, 0}, {X509_TRUST_SSL_CLIENT, trust_1oidany, NID_client_auth}, {X509_TRUST_SSL_SERVER, trust_1oidany, NID_server_auth}, @@ -44,7 +84,7 @@ static const X509_TRUST trstandard[] = { {X509_TRUST_OBJECT_SIGN, trust_1oidany, NID_code_sign}, {X509_TRUST_TSA, trust_1oidany, NID_time_stamp}}; -static const X509_TRUST *X509_TRUST_get0(int id) { +const X509_TRUST *X509_TRUST_get0(int id) { for (const auto &t : trstandard) { if (t.trust == id) { return &t; @@ -53,7 +93,9 @@ static const X509_TRUST *X509_TRUST_get0(int id) { return nullptr; } -int X509_check_trust(X509 *x, int id, int flags) { +} // namespace + +int X509_check_trust(const X509 *x, int id, int flags) { if (id == -1) { return X509_TRUST_TRUSTED; } @@ -78,46 +120,3 @@ int X509_check_trust(X509 *x, int id, int flags) { int bssl::X509_is_valid_trust_id(int trust) { return X509_TRUST_get0(trust) != nullptr; } - -static int trust_1oidany(const X509_TRUST *trust, X509 *x) { - auto *impl = FromOpaque(x); - if (impl->aux && (impl->aux->trust || impl->aux->reject)) { - return obj_trust(trust->nid, impl); - } - // we don't have any trust settings: for compatibility we return trusted - // if it is self signed - return trust_compat(trust, impl); -} - -static int trust_compat(const X509_TRUST *trust, X509 *x) { - auto *impl = FromOpaque(x); - if (!x509v3_cache_extensions(x)) { - return X509_TRUST_UNTRUSTED; - } - if (impl->ex_flags & EXFLAG_SS) { - return X509_TRUST_TRUSTED; - } else { - return X509_TRUST_UNTRUSTED; - } -} - -static int obj_trust(int id, X509 *x) { - auto *impl = FromOpaque(x); - X509_CERT_AUX *ax = impl->aux; - if (!ax) { - return X509_TRUST_UNTRUSTED; - } - for (size_t i = 0; i < sk_ASN1_OBJECT_num(ax->reject); i++) { - const ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(ax->reject, i); - if (OBJ_obj2nid(obj) == id) { - return X509_TRUST_REJECTED; - } - } - for (size_t i = 0; i < sk_ASN1_OBJECT_num(ax->trust); i++) { - const ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(ax->trust, i); - if (OBJ_obj2nid(obj) == id) { - return X509_TRUST_TRUSTED; - } - } - return X509_TRUST_UNTRUSTED; -} diff --git a/third_party/boringssl/src/crypto/x509/x509_vfy.cc b/third_party/boringssl/src/crypto/x509/x509_vfy.cc index 90a9d1f..36f2bb1 100644 --- a/third_party/boringssl/src/crypto/x509/x509_vfy.cc +++ b/third_party/boringssl/src/crypto/x509/x509_vfy.cc @@ -12,7 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include +#include + #include #include #include @@ -22,6 +23,7 @@ #include #include #include +#include #include #include "../internal.h" @@ -31,8 +33,6 @@ using namespace bssl; -static ExDataClass g_ex_data_class(/*with_app_data=*/true); - // CRL score values // No unhandled critical extensions @@ -60,35 +60,22 @@ static ExDataClass g_ex_data_class(/*with_app_data=*/true); // CRL issuer matches CRL AKID #define CRL_SCORE_AKID 0x004 -static int null_callback(int ok, X509_STORE_CTX *e); -static X509 *find_issuer(X509_STORE_CTX *ctx, const STACK_OF(X509) *sk, - const X509 *x); -static int check_chain_extensions(X509_STORE_CTX *ctx); -static int check_name_constraints(X509_STORE_CTX *ctx); -static int check_id(X509_STORE_CTX *ctx); -static int check_trust(X509_STORE_CTX *ctx); -static int check_revocation(X509_STORE_CTX *ctx); -static int check_cert(X509_STORE_CTX *ctx); -static int check_policy(X509_STORE_CTX *ctx); - -static UniquePtr get_trusted_issuer(X509_STORE_CTX *ctx, const X509 *x); -static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer, X509_CRL *crl, - X509 *x); -static int get_crl(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509 *x); -static int crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer, - int *pcrl_score); -static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score); -static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl); -static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x); - -static int internal_verify(X509_STORE_CTX *ctx); - -static int null_callback(int ok, X509_STORE_CTX *e) { return ok; } +namespace { + +ExDataClass g_ex_data_class(/*with_app_data=*/true); + +struct CRLInfo { + UniquePtr crl; + X509 *issuer = nullptr; + int score = 0; +}; + +int null_callback(int ok, X509_STORE_CTX *e) { return ok; } // cert_self_signed checks if `x` is self-signed. If `x` is valid, it returns // one and sets `*out_is_self_signed` to the result. If `x` is invalid, it // returns zero. -static int cert_self_signed(X509 *x, int *out_is_self_signed) { +int cert_self_signed(X509 *x, int *out_is_self_signed) { if (!x509v3_cache_extensions(x)) { return 0; } @@ -97,7 +84,7 @@ static int cert_self_signed(X509 *x, int *out_is_self_signed) { return 1; } -static int call_verify_cb(int ok, X509_STORE_CTX *ctx) { +int call_verify_cb(int ok, X509_STORE_CTX *ctx) { ok = ctx->verify_cb(ok, ctx); // Historically, callbacks returning values like -1 would be treated as a mix // of success or failure. Insert that callers check correctly. @@ -108,9 +95,27 @@ static int call_verify_cb(int ok, X509_STORE_CTX *ctx) { return ok; } +// TODO(crbug.com/42290549): Switch remaining `call_verify_cb` calls to this +// function. +int call_verify_cb_at_depth(int ok, X509_STORE_CTX *ctx, int depth) { + ctx->current_cert = sk_X509_value(ctx->chain, depth); + ctx->error_depth = depth; + return call_verify_cb(ok, ctx); +} + // Given a certificate try and find an exact match in the store -static UniquePtr lookup_cert_match(X509_STORE_CTX *ctx, const X509 *x) { - // Lookup all certs with matching subject name +UniquePtr lookup_cert_match(X509_STORE_CTX *ctx, const X509 *x) { + if (ctx->trusted_stack != nullptr) { + // Ignore the store and use the configured stack instead. + for (X509 *found : ctx->trusted_stack) { + if (X509_cmp(found, x) == 0) { + return UpRef(found); + } + } + return nullptr; + } + + // Lookup all certs with matching subject name. UniquePtr certs( X509_STORE_CTX_get1_certs(ctx, X509_get_subject_name(x))); if (certs == nullptr) { @@ -125,244 +130,9 @@ static UniquePtr lookup_cert_match(X509_STORE_CTX *ctx, const X509 *x) { return nullptr; } -int X509_verify_cert(X509_STORE_CTX *ctx) { - int ok = 0; - Cleanup set_ctx_error = [&] { - // Safety net, error returns must set ctx->error - if (!ok && ctx->error == X509_V_OK) { - ctx->error = X509_V_ERR_UNSPECIFIED; - } - }; - - const X509_VERIFY_PARAM *param = ctx->param; - if (ctx->cert == nullptr) { - OPENSSL_PUT_ERROR(X509, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY); - ctx->error = X509_V_ERR_INVALID_CALL; - return 0; - } - - if (ctx->chain != nullptr) { - // This X509_STORE_CTX has already been used to verify a cert. We - // cannot do another one. - OPENSSL_PUT_ERROR(X509, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); - ctx->error = X509_V_ERR_INVALID_CALL; - return 0; - } - - if (param->flags & - (X509_V_FLAG_EXTENDED_CRL_SUPPORT | X509_V_FLAG_USE_DELTAS)) { - // We do not support indirect or delta CRLs. The flags still exist for - // compatibility with bindings libraries, but to ensure we do not - // inadvertently skip a CRL check that the caller expects, fail closed. - OPENSSL_PUT_ERROR(X509, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); - ctx->error = X509_V_ERR_INVALID_CALL; - return 0; - } - - // first we make sure the chain we are going to build is present and that - // the first entry is in place - ctx->chain = sk_X509_new_null(); - if (ctx->chain == nullptr || !PushToStack(ctx->chain, UpRef(ctx->cert))) { - ctx->error = X509_V_ERR_OUT_OF_MEM; - return 0; - } - ctx->last_untrusted = 1; - - // We use a temporary STACK so we can chop and hack at it. `sktmp` is not a - // `UniquePtr` because that would do a deep free and this is a - // shallow free. - STACK_OF(X509) *sktmp = nullptr; - Cleanup free_sktmp = [&] { sk_X509_free(sktmp); }; - if (ctx->untrusted != nullptr && - (sktmp = sk_X509_dup(ctx->untrusted)) == nullptr) { - ctx->error = X509_V_ERR_OUT_OF_MEM; - return 0; - } - - // Maintain invariants: `num` is always the size of `ctx->chain` and `last` is - // always the last element. - int num = (int)sk_X509_num(ctx->chain); - X509 *last = sk_X509_last(ctx->chain); - // `param->depth` does not include the leaf certificate or the trust anchor, - // so the maximum size is 2 more. - int max_chain = param->depth >= INT_MAX - 2 ? INT_MAX : param->depth + 2; - - for (;;) { - if (num >= max_chain) { - // FIXME: If this happens, we should take note of it and, if - // appropriate, use the X509_V_ERR_CERT_CHAIN_TOO_LONG error code later. - break; - } - - int is_self_signed; - if (!cert_self_signed(last, &is_self_signed)) { - ctx->error = X509_V_ERR_INVALID_EXTENSION; - return 0; - } - - // If we are self signed, we break - if (is_self_signed) { - break; - } - // See if we can find issuer in trusted store first. - if (UniquePtr trusted = get_trusted_issuer(ctx, last); - trusted != nullptr) { - // Free the certificate. It will be picked up again later. - break; - } - - // If we were passed a cert chain, use it first - if (sktmp != nullptr) { - X509 *issuer = find_issuer(ctx, sktmp, last); - if (issuer != nullptr) { - if (!PushToStack(ctx->chain, UpRef(issuer))) { - ctx->error = X509_V_ERR_OUT_OF_MEM; - return 0; - } - (void)sk_X509_delete_ptr(sktmp, issuer); - ctx->last_untrusted++; - last = issuer; - num++; - // reparse the full chain for the next one - continue; - } - } - break; - } - - // At this point, chain should contain a list of untrusted certificates. - // We now need to add at least one trusted one, if possible, otherwise we - // complain. - assert(num == static_cast(sk_X509_num(ctx->chain))); - assert(last == sk_X509_last(ctx->chain)); - - // Examine last certificate in chain and see if it is self signed. - int is_self_signed; - if (!cert_self_signed(last, &is_self_signed)) { - ctx->error = X509_V_ERR_INVALID_EXTENSION; - return 0; - } - - int bad_chain = 0; - UniquePtr chain_ss; - if (is_self_signed) { - // we have a self signed certificate - if (sk_X509_num(ctx->chain) == 1) { - // We have a single self signed certificate: see if we can - // find it in the store. We must have an exact match to avoid - // possible impersonation. - UniquePtr issuer = get_trusted_issuer(ctx, last); - if (issuer == nullptr || X509_cmp(last, issuer.get()) != 0) { - ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT; - ctx->current_cert = last; - ctx->error_depth = num - 1; - bad_chain = 1; - if (!call_verify_cb(0, ctx)) { - return 0; - } - } else { - // We have a match: replace certificate with store - // version so we get any trust settings. - X509_free(last); - last = issuer.release(); - (void)sk_X509_set(ctx->chain, num - 1, last); - ctx->last_untrusted = 0; - } - } else { - // extract and save self signed certificate for later use - chain_ss.reset(sk_X509_pop(ctx->chain)); - ctx->last_untrusted--; - num--; - last = sk_X509_value(ctx->chain, num - 1); - } - } - // We now lookup certs from the certificate store - for (;;) { - if (num >= max_chain) { - // FIXME: If this happens, we should take note of it and, if - // appropriate, use the X509_V_ERR_CERT_CHAIN_TOO_LONG error code - // later. - break; - } - if (!cert_self_signed(last, &is_self_signed)) { - ctx->error = X509_V_ERR_INVALID_EXTENSION; - return 0; - } - // If we are self signed, we break - if (is_self_signed) { - break; - } - UniquePtr issuer = get_trusted_issuer(ctx, last); - if (issuer == nullptr) { - break; - } - last = issuer.get(); - if (!PushToStack(ctx->chain, std::move(issuer))) { - ctx->error = X509_V_ERR_OUT_OF_MEM; - return 0; - } - num++; - } - - // we now have our chain, lets check it... - int trust = check_trust(ctx); - - // If explicitly rejected error - if (trust == X509_TRUST_REJECTED) { - return 0; - } - - // If not explicitly trusted then indicate error unless it's a single - // self signed certificate in which case we've indicated an error already - // and set bad_chain == 1 - if (trust != X509_TRUST_TRUSTED && !bad_chain) { - if (chain_ss == nullptr || - !x509_check_issued_with_callback(ctx, last, chain_ss.get())) { - if (ctx->last_untrusted >= num) { - ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY; - } else { - ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT; - } - ctx->current_cert = last; - } else { - if (!PushToStack(ctx->chain, std::move(chain_ss))) { - ctx->error = X509_V_ERR_OUT_OF_MEM; - return 0; - } - num++; - ctx->last_untrusted = num; - ctx->current_cert = sk_X509_last(ctx->chain); - ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN; - } - - ctx->error_depth = num - 1; - bad_chain = 1; - if (!call_verify_cb(0, ctx)) { - return 0; - } - } - - // We have the chain complete: now we need to check its purpose - if (!check_chain_extensions(ctx) || // - !check_id(ctx) || - // We check revocation status after copying parameters because they may - // be needed for CRL signature verification. - !check_revocation(ctx) || // - !internal_verify(ctx) || // - !check_name_constraints(ctx) || - // TODO(davidben): Does `check_policy` still need to be conditioned on - // |!bad_chain|? DoS concerns have been resolved. - (!bad_chain && !check_policy(ctx))) { - return 0; - } - - ok = 1; - return 1; -} - // Given a STACK_OF(X509) find the issuer of cert (if any) -static X509 *find_issuer(X509_STORE_CTX *ctx, const STACK_OF(X509) *sk, - const X509 *x) { +X509 *find_issuer(X509_STORE_CTX *ctx, const STACK_OF(X509) *sk, + const X509 *x) { for (X509 *issuer : sk) { if (x509_check_issued_with_callback(ctx, x, issuer)) { return issuer; @@ -371,25 +141,7 @@ static X509 *find_issuer(X509_STORE_CTX *ctx, const STACK_OF(X509) *sk, return nullptr; } -// Given a possible certificate and issuer check them -int bssl::x509_check_issued_with_callback(X509_STORE_CTX *ctx, const X509 *x, - const X509 *issuer) { - int ret; - ret = X509_check_issued(issuer, x); - if (ret == X509_V_OK) { - return 1; - } - // If we haven't asked for issuer errors don't set ctx - if (!(ctx->param->flags & X509_V_FLAG_CB_ISSUER_CHECK)) { - return 0; - } - - ctx->error = ret; - ctx->current_cert = const_cast(x); - return call_verify_cb(0, ctx); -} - -static UniquePtr get_trusted_issuer(X509_STORE_CTX *ctx, const X509 *x) { +UniquePtr get_trusted_issuer(X509_STORE_CTX *ctx, const X509 *x) { if (ctx->trusted_stack != nullptr) { // Ignore the store and use the configured stack instead. return UpRef(find_issuer(ctx, ctx->trusted_stack, x)); @@ -405,19 +157,16 @@ static UniquePtr get_trusted_issuer(X509_STORE_CTX *ctx, const X509 *x) { // Check a certificate chains extensions for consistency with the supplied // purpose -static int check_chain_extensions(X509_STORE_CTX *ctx) { +int check_chain_extensions(X509_STORE_CTX *ctx) { int plen = 0; int purpose = ctx->param->purpose; - - // Check all untrusted certificates - for (int i = 0; i < ctx->last_untrusted; i++) { + int num = static_cast(sk_X509_num(ctx->chain)); + for (int i = 0; i < num; i++) { X509Impl *x = FromOpaque(sk_X509_value(ctx->chain, i)); if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) && (x->ex_flags & EXFLAG_CRITICAL)) { ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION; - ctx->error_depth = i; - ctx->current_cert = x; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, i)) { return 0; } } @@ -425,18 +174,14 @@ static int check_chain_extensions(X509_STORE_CTX *ctx) { int must_be_ca = i > 0; if (must_be_ca && !X509_check_ca(x)) { ctx->error = X509_V_ERR_INVALID_CA; - ctx->error_depth = i; - ctx->current_cert = x; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, i)) { return 0; } } if (ctx->param->purpose > 0 && X509_check_purpose(x, purpose, must_be_ca) != 1) { ctx->error = X509_V_ERR_INVALID_PURPOSE; - ctx->error_depth = i; - ctx->current_cert = x; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, i)) { return 0; } } @@ -451,9 +196,7 @@ static int check_chain_extensions(X509_STORE_CTX *ctx) { // considered - they are just not counted as part of the path length! if (i > 1 && x->ex_pathlen != -1 && plen > x->ex_pathlen + 1) { ctx->error = X509_V_ERR_PATH_LENGTH_EXCEEDED; - ctx->error_depth = i; - ctx->current_cert = x; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, i)) { return 0; } } @@ -469,7 +212,7 @@ static int check_chain_extensions(X509_STORE_CTX *ctx) { return 1; } -static int reject_dns_name_in_common_name(X509 *x509) { +int reject_dns_name_in_common_name(X509 *x509) { const X509_NAME *name = X509_get_subject_name(x509); int i = -1; for (;;) { @@ -495,7 +238,7 @@ static int reject_dns_name_in_common_name(X509 *x509) { } } -static int check_name_constraints(X509_STORE_CTX *ctx) { +int check_name_constraints(X509_STORE_CTX *ctx) { int i, j, rv; int has_name_constraints = 0; // Check name constraints for all certificates @@ -522,9 +265,7 @@ static int check_name_constraints(X509_STORE_CTX *ctx) { return 0; default: ctx->error = rv; - ctx->error_depth = i; - ctx->current_cert = x; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, i)) { return 0; } break; @@ -554,9 +295,7 @@ static int check_name_constraints(X509_STORE_CTX *ctx) { return 0; default: ctx->error = rv; - ctx->error_depth = 0; - ctx->current_cert = leaf; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, /*depth=*/0)) { return 0; } break; @@ -566,14 +305,12 @@ static int check_name_constraints(X509_STORE_CTX *ctx) { return 1; } -static int check_id_error(X509_STORE_CTX *ctx, int errcode) { +int check_id_error(X509_STORE_CTX *ctx, int errcode) { ctx->error = errcode; - ctx->current_cert = ctx->cert; - ctx->error_depth = 0; - return call_verify_cb(0, ctx); + return call_verify_cb_at_depth(0, ctx, /*depth=*/0); } -static int check_hosts(X509 *x, X509_VERIFY_PARAM *param) { +int check_hosts(X509 *x, X509_VERIFY_PARAM *param) { size_t i; size_t n = sk_OPENSSL_STRING_num(param->hosts); char *name; @@ -587,7 +324,7 @@ static int check_hosts(X509 *x, X509_VERIFY_PARAM *param) { return n == 0; } -static int check_id(X509_STORE_CTX *ctx) { +int check_id(X509_STORE_CTX *ctx) { X509_VERIFY_PARAM *vpm = ctx->param; X509 *x = ctx->cert; if (vpm->poison) { @@ -613,110 +350,39 @@ static int check_id(X509_STORE_CTX *ctx) { return 1; } -static int check_trust(X509_STORE_CTX *ctx) { - // Check all trusted certificates in chain - for (size_t i = ctx->last_untrusted; i < sk_X509_num(ctx->chain); i++) { - X509 *x = sk_X509_value(ctx->chain, i); - int trust = X509_check_trust(x, ctx->param->trust, 0); - // If explicitly trusted return trusted - if (trust == X509_TRUST_TRUSTED) { - return X509_TRUST_TRUSTED; - } - // If explicitly rejected notify callback and reject if not - // overridden. - if (trust == X509_TRUST_REJECTED) { - ctx->error_depth = (int)i; - ctx->current_cert = x; - ctx->error = X509_V_ERR_CERT_REJECTED; - if (!call_verify_cb(0, ctx)) { - return X509_TRUST_REJECTED; - } - } - } - // If we accept partial chains and have at least one trusted certificate - // return success. - if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) { - if (ctx->last_untrusted < (int)sk_X509_num(ctx->chain)) { - return X509_TRUST_TRUSTED; - } - X509 *x = sk_X509_value(ctx->chain, 0); - UniquePtr mx = lookup_cert_match(ctx, x); - if (mx) { - (void)sk_X509_set(ctx->chain, 0, mx.release()); - X509_free(x); - ctx->last_untrusted = 0; - return X509_TRUST_TRUSTED; - } - } - - // If no trusted certs in chain at all return untrusted and allow - // standard (no issuer cert) etc errors to be indicated. - return X509_TRUST_UNTRUSTED; -} - -static int check_revocation(X509_STORE_CTX *ctx) { - if (!(ctx->param->flags & X509_V_FLAG_CRL_CHECK)) { - return 1; - } - int last; - if (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL) { - last = (int)sk_X509_num(ctx->chain) - 1; - } else { - last = 0; +int check_trust(X509_STORE_CTX *ctx) { + // If this function is called, `ctx->chain` must end with some certificate + // from the store. Determine if we should treat it as a trust anchor in this + // context. + X509 *last = sk_X509_last(ctx->chain); + int trust = X509_check_trust(last, ctx->param->trust, /*flags=*/0); + if (trust == X509_TRUST_TRUSTED) { + return X509_TRUST_TRUSTED; } - for (int i = 0; i <= last; i++) { - ctx->error_depth = i; - if (!check_cert(ctx)) { - return 0; + if (trust == X509_TRUST_REJECTED) { + // Notify callback and reject if not overridden. + ctx->error = X509_V_ERR_CERT_REJECTED; + if (!call_verify_cb_at_depth(0, ctx, sk_X509_num(ctx->chain) - 1)) { + return X509_TRUST_REJECTED; } } - return 1; -} -static int check_cert(X509_STORE_CTX *ctx) { - X509_CRL *crl = nullptr; - int ok = 0, cnum = ctx->error_depth; - X509 *x = sk_X509_value(ctx->chain, cnum); - ctx->current_cert = x; - ctx->current_crl_issuer = nullptr; - ctx->current_crl_score = 0; - - // Try to retrieve the relevant CRL. Note that `get_crl` sets - // `current_crl_issuer` and `current_crl_score`, which `check_crl` then reads. - // - // TODO(davidben): The awkward internal calling convention is a historical - // artifact of when these functions were user-overridable callbacks, even - // though there was no way to set them correctly. These callbacks have since - // been removed, so we can pass input and output parameters more directly. - if (!get_crl(ctx, &crl, x)) { - ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL; - ok = call_verify_cb(0, ctx); - goto err; - } - - ctx->current_crl = crl; - if (!check_crl(ctx, crl) || // - !cert_crl(ctx, crl, x)) { - goto err; + // If we accept partial chains, every certificate in the store is a trust + // anchor. + if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) { + return X509_TRUST_TRUSTED; } - ok = 1; - -err: - X509_CRL_free(crl); - ctx->current_crl = nullptr; - return ok; + return X509_TRUST_UNTRUSTED; } // Check CRL times against values in X509_STORE_CTX -static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify) { +int check_crl_time(X509_STORE_CTX *ctx, const X509_CRL *crl, bool notify, + int depth) { if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME) { return 1; } - if (notify) { - ctx->current_crl = crl; - } int64_t ptime; if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME) { ptime = ctx->param->check_time; @@ -730,7 +396,7 @@ static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify) { return 0; } ctx->error = X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, depth)) { return 0; } } @@ -740,7 +406,7 @@ static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify) { return 0; } ctx->error = X509_V_ERR_CRL_NOT_YET_VALID; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, depth)) { return 0; } } @@ -753,7 +419,7 @@ static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify) { return 0; } ctx->error = X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, depth)) { return 0; } } @@ -762,139 +428,87 @@ static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify) { return 0; } ctx->error = X509_V_ERR_CRL_HAS_EXPIRED; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, depth)) { return 0; } } } - if (notify) { - ctx->current_crl = nullptr; - } - return 1; } -static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509 **pissuer, - int *pscore, STACK_OF(X509_CRL) *crls) { - int crl_score, best_score = *pscore; - X509 *x = ctx->current_cert; - X509_CRL *best_crl = nullptr; - X509 *crl_issuer = nullptr, *best_crl_issuer = nullptr; +int check_blocklist(X509_STORE_CTX *ctx) { + static const uint8_t kBlockList[][32] = { + {0xe0, 0x25, 0x4c, 0x7f, 0xcd, 0xc2, 0x65, 0xe2, 0xf0, 0xf8, 0xa4, + 0x28, 0xda, 0xbb, 0x75, 0xab, 0x4a, 0xe0, 0x39, 0xb4, 0x87, 0x2d, + 0x62, 0xf5, 0xee, 0x57, 0xf0, 0x87, 0x7d, 0x5a, 0x8a, 0x41}, + {0x43, 0xbf, 0xfa, 0x19, 0xd6, 0xef, 0x65, 0x14, 0x51, 0xf6, 0x84, + 0x1e, 0x01, 0x99, 0x31, 0xe9, 0x6f, 0x6f, 0x2e, 0xae, 0xff, 0x28, + 0xab, 0x4b, 0x6f, 0x1c, 0xe4, 0x57, 0x6d, 0xe2, 0x71, 0x7b}, + {0xeb, 0xed, 0x64, 0x75, 0xc2, 0xc2, 0xd8, 0x0f, 0xcb, 0x19, 0x9f, + 0x3f, 0xe8, 0xdd, 0x6e, 0x6b, 0x3c, 0xe6, 0x0b, 0x77, 0xeb, 0x15, + 0xd4, 0xe4, 0x2c, 0x3d, 0xec, 0x0c, 0x6f, 0x5b, 0x51, 0x05}, + {0x5c, 0x06, 0x60, 0xa2, 0xb1, 0x64, 0x91, 0x0d, 0x8f, 0xf5, 0x89, + 0xc1, 0x8e, 0x14, 0x55, 0x2e, 0x9e, 0x0e, 0xc2, 0x37, 0xdc, 0xef, + 0xe2, 0xcb, 0x73, 0x6d, 0x41, 0xa4, 0x81, 0x1f, 0x81, 0xa0}, + {0x63, 0xec, 0xef, 0xee, 0x43, 0x1d, 0x49, 0x52, 0x3b, 0xc1, 0x13, + 0x6c, 0x4e, 0x72, 0xd0, 0x20, 0x6a, 0x47, 0x70, 0x86, 0xca, 0xf6, + 0x06, 0xcd, 0x5c, 0xf0, 0x25, 0x68, 0x6c, 0x10, 0x9c, 0xf8}, + {0x49, 0xdd, 0x35, 0x3d, 0xc2, 0xb9, 0x19, 0xa3, 0x77, 0x06, 0x45, + 0x11, 0x7d, 0x0e, 0x60, 0xc1, 0x61, 0x15, 0xe7, 0xd1, 0xbc, 0x25, + 0x9e, 0xef, 0xe7, 0x34, 0xb0, 0x0e, 0xa4, 0x34, 0xfe, 0x5f}, + {0xec, 0x4f, 0xfa, 0x1a, 0xd0, 0xac, 0x88, 0x08, 0x13, 0x14, 0xb7, + 0xaa, 0xff, 0xef, 0x6a, 0x91, 0xf9, 0x7c, 0xd5, 0x72, 0x91, 0xbb, + 0x5b, 0xa6, 0x86, 0xc5, 0x41, 0x5f, 0x5e, 0xb4, 0xf6, 0xb6}, + {0x92, 0xc0, 0x63, 0xd6, 0x7e, 0x8f, 0x14, 0xdb, 0x71, 0xd2, 0x88, + 0xe1, 0x12, 0x66, 0xff, 0xda, 0xf6, 0x9c, 0xbf, 0x11, 0x5f, 0x7b, + 0xab, 0x14, 0xf3, 0xbc, 0x2f, 0x68, 0xd2, 0x5e, 0x0e, 0x30}, + }; - for (size_t i = 0; i < sk_X509_CRL_num(crls); i++) { - X509_CRL *crl = sk_X509_CRL_value(crls, i); - crl_score = get_crl_score(ctx, &crl_issuer, crl, x); - if (crl_score < best_score || crl_score == 0) { - continue; + const size_t num = sk_X509_num(ctx->chain); + for (size_t i = 0; i < num; i++) { + const X509 *x = sk_X509_value(ctx->chain, i); + ScopedCBB cbb; + if (!CBB_init(cbb.get(), 64) || + !x509_marshal_public_key(cbb.get(), X509_get_X509_PUBKEY(x))) { + ctx->error = X509_V_ERR_OUT_OF_MEM; + return 0; } - // If current CRL is equivalent use it if it is newer - if (crl_score == best_score && best_crl != nullptr) { - int day, sec; - if (ASN1_TIME_diff(&day, &sec, X509_CRL_get0_lastUpdate(best_crl), - X509_CRL_get0_lastUpdate(crl)) == 0) { - continue; - } - // ASN1_TIME_diff never returns inconsistent signs for `day` - // and `sec`. - if (day <= 0 && sec <= 0) { - continue; + uint8_t spki_hash[SHA256_DIGEST_LENGTH]; + SHA256(CBB_data(cbb.get()), CBB_len(cbb.get()), spki_hash); + for (const auto &block : kBlockList) { + if (Span(spki_hash) == Span(block)) { + ctx->error = X509_V_ERR_CERT_REVOKED; + if (!call_verify_cb_at_depth(0, ctx, static_cast(i))) { + return 0; + } } } - best_crl = crl; - best_crl_issuer = crl_issuer; - best_score = crl_score; } - - if (best_crl) { - if (*pcrl) { - X509_CRL_free(*pcrl); - } - *pcrl = best_crl; - *pissuer = best_crl_issuer; - *pscore = best_score; - X509_CRL_up_ref(best_crl); - } - - if (best_score >= CRL_SCORE_VALID) { - return 1; - } - - return 0; -} - -// For a given CRL return how suitable it is for the supplied certificate -// 'x'. The return value is a mask of several criteria. If the issuer is not -// the certificate issuer this is returned in *pissuer. -static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer, X509_CRL *crl, - X509 *x) { - int crl_score = 0; - - // First see if we can reject CRL straight away - - // Invalid IDP cannot be processed - if (crl->idp_flags & IDP_INVALID) { - return 0; - } - // Reason codes and indirect CRLs are not supported. - if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS)) { - return 0; - } - // We do not support indirect CRLs, so the issuer names must match. - if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl))) { - return 0; - } - crl_score |= CRL_SCORE_ISSUER_NAME; - - if (!(crl->flags & EXFLAG_CRITICAL)) { - crl_score |= CRL_SCORE_NOCRITICAL; - } - - // Check expiry - if (check_crl_time(ctx, crl, 0)) { - crl_score |= CRL_SCORE_TIME; - } - - // Check authority key ID and locate certificate issuer - if (!crl_akid_check(ctx, crl, pissuer, &crl_score)) { - // If we can't locate certificate issuer at this point forget it - return 0; - } - - // Check cert for matching CRL distribution points - if (crl_crldp_check(x, crl, crl_score)) { - crl_score |= CRL_SCORE_SCOPE; - } - - return crl_score; + return 1; } -static int crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer, - int *pcrl_score) { - X509 *crl_issuer = nullptr; - X509_NAME *cnm = X509_CRL_get_issuer(crl); - int cidx = ctx->error_depth; - - if ((size_t)cidx != sk_X509_num(ctx->chain) - 1) { - cidx++; - } - - crl_issuer = sk_X509_value(ctx->chain, cidx); +int crl_akid_check(X509_STORE_CTX *ctx, const X509_CRL *crl, X509 **out_issuer, + int *out_crl_score, int depth) { + const X509_NAME *crl_name = X509_CRL_get_issuer(crl); + depth++; + assert(depth < static_cast(sk_X509_num(ctx->chain))); + X509 *crl_issuer = sk_X509_value(ctx->chain, depth); if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) { - *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_ISSUER_CERT; - *pissuer = crl_issuer; + *out_crl_score |= CRL_SCORE_AKID | CRL_SCORE_ISSUER_CERT; + *out_issuer = crl_issuer; return 1; } - for (cidx++; cidx < (int)sk_X509_num(ctx->chain); cidx++) { - crl_issuer = sk_X509_value(ctx->chain, cidx); - if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm)) { + for (depth++; depth < (int)sk_X509_num(ctx->chain); depth++) { + crl_issuer = sk_X509_value(ctx->chain, depth); + if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), crl_name)) { continue; } if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) { - *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_SAME_PATH; - *pissuer = crl_issuer; + *out_crl_score |= CRL_SCORE_AKID | CRL_SCORE_SAME_PATH; + *out_issuer = crl_issuer; return 1; } } @@ -902,93 +516,76 @@ static int crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer, return 0; } -// Check for match between two dist point names: three separate cases. 1. -// Both are relative names and compare X509_NAME types. 2. One full, one -// relative. Compare X509_NAME to GENERAL_NAMES. 3. Both are full names and -// compare two GENERAL_NAMES. 4. One is NULL: automatic match. -static int idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b) { - X509_NAME *nm = nullptr; - GENERAL_NAMES *gens = nullptr; - GENERAL_NAME *gena, *genb; - size_t i, j; - if (!a || !b) { +int idp_check_dp(const DIST_POINT_NAME *dp_cert, + const DIST_POINT_NAME *dp_crl) { + // If the CRL IDP does not have a distributionPoint field, the CRL is scoped + // to the entire CA and matches everything. + // + // TODO(crbug.com/42290219): This covers a null `dp_crl`, but not `dp_cert`. + // If `dp_cert` is null, that means the certificate's DistributionPoint lacks + // a distributionPoint. However, DistributionPoints are required to have + // either distributionPoint or cRLIssuer (indirect CRL) and we reject the + // latter. However, we don't seem to check this in the parser. Enforce this so + // that `dp_cert` cannot be null. + if (!dp_cert || !dp_crl) { return 1; } - if (a->type == 1) { - if (!a->dpname) { - return 0; - } - // Case 1: two X509_NAME - if (b->type == 1) { - if (!b->dpname) { - return 0; - } - if (!X509_NAME_cmp(a->dpname, b->dpname)) { - return 1; - } else { - return 0; - } - } - // Case 2: set name and GENERAL_NAMES appropriately - nm = a->dpname; - gens = b->name.fullname; - } else if (b->type == 1) { - if (!b->dpname) { - return 0; - } - // Case 2: set name and GENERAL_NAMES appropriately - gens = a->name.fullname; - nm = b->dpname; + // We only support fullName, not nameRelativeToCRLIssuer. + if (dp_cert->type != 0 || dp_crl->type != 0) { + return 0; } - - // Handle case 2 with one GENERAL_NAMES and one X509_NAME - if (nm) { - for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) { - gena = sk_GENERAL_NAME_value(gens, i); - if (gena->type != GEN_DIRNAME) { - continue; - } - if (!X509_NAME_cmp(nm, gena->d.directoryName)) { - return 1; - } - } + // Check that the CRL's distributionPoint has some name in common with the + // certificate's. A CA might shard across multiple CRLs. This check ensures we + // are looking at the right shard. + const size_t crl_names_count = sk_GENERAL_NAME_num(dp_crl->name.fullname); + if (crl_names_count == 0) { + return 0; + } + const size_t cert_names_count = sk_GENERAL_NAME_num(dp_cert->name.fullname); + if (cert_names_count == 0) { return 0; } - // Else case 3: two GENERAL_NAMES + const GENERAL_NAMES *longer = crl_names_count >= cert_names_count + ? dp_crl->name.fullname + : dp_cert->name.fullname; + const GENERAL_NAMES *shorter = crl_names_count < cert_names_count + ? dp_crl->name.fullname + : dp_cert->name.fullname; + bssl::Array sorted; + if (!sorted.InitForOverwrite(sk_GENERAL_NAME_num(shorter))) { + return 0; + } + size_t i = 0; + for (const GENERAL_NAME *s : shorter) { + sorted[i++] = s; + } - for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) { - gena = sk_GENERAL_NAME_value(a->name.fullname, i); - for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) { - genb = sk_GENERAL_NAME_value(b->name.fullname, j); - if (!GENERAL_NAME_cmp(gena, genb)) { - return 1; - } + auto cmp_func = [](const GENERAL_NAME *a, const GENERAL_NAME *b) { + return GENERAL_NAME_cmp(a, b) < 0; + }; + std::sort(sorted.begin(), sorted.end(), cmp_func); + for (const GENERAL_NAME *name : longer) { + if (std::binary_search(sorted.begin(), sorted.end(), name, cmp_func)) { + return 1; } } - return 0; } // Check CRLDP and IDP -static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score) { +int crl_crldp_check(const X509 *x, const X509_CRL *crl, int crl_score) { auto *impl = FromOpaque(x); - // TODO(bbe): crbug.com/409778435 Make tests for the corner cases we hit - // here so that we stay correct for RFC 5280 6.3.3 steps b.1 and b.2 - if (crl->idp_flags & IDP_ONLYATTR) { - return 0; - } if (impl->ex_flags & EXFLAG_CA) { - if (crl->idp_flags & IDP_ONLYUSER) { + if (crl->idp && crl->idp->onlyuser) { return 0; } } else { - if (crl->idp_flags & IDP_ONLYCA) { + if (crl->idp && crl->idp->onlyCA) { return 0; } } - for (size_t i = 0; i < sk_DIST_POINT_num(impl->crldp.get()); i++) { - DIST_POINT *dp = sk_DIST_POINT_value(impl->crldp.get(), i); + for (const DIST_POINT *dp : impl->crldp.get()) { // Skip distribution points with a reasons field or a CRL issuer: // // We do not support CRLs partitioned by reason code. RFC 5280 requires CAs @@ -1003,120 +600,164 @@ static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score) { // the certificate issuer (and set CRL_SCORE_ISSUER_NAME); // RFC 5280 Section 6.3.3 step b.2 - if (!crl->idp || idp_check_dp(dp->distpoint, crl->idp->distpoint)){ + if (!crl->idp || idp_check_dp(dp->distpoint, crl->idp->distpoint)) { return 1; } } // If the CRL does not specify an issuing distribution point, allow it to - // match anything. - // - // TODO(davidben): Does this match RFC 5280? It's hard to follow because RFC - // 5280 starts from distribution points, while this starts from CRLs. + // match anything. This partially implements RFC 5280. The final paragraph of + // RFC 5280, section 6.3.3, specifies a default CRL-DP. This default would + // match IDP-less CRLs and CRLs with an IDP of the default CRL-DP. We do not + // implement the second condition. return !crl->idp || !crl->idp->distpoint; } -// Retrieve CRL corresponding to current certificate. -static int get_crl(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509 *x) { - X509 *issuer = nullptr; - int crl_score = 0; - X509_CRL *crl = nullptr; - STACK_OF(X509_CRL) *skcrl = nullptr; - if (get_crl_sk(ctx, &crl, &issuer, &crl_score, ctx->crls)) { - goto done; +// For a given CRL return how suitable it is for the supplied certificate +// 'x'. The return value is a mask of several criteria, or zero if the CRL is +// unusable. The certificate issuer is returned in `*out_issuer`. +int get_crl_score(X509_STORE_CTX *ctx, X509 **out_issuer, const X509_CRL *crl, + const X509 *x, int depth) { + if (crl->idp) { + // Per RFC 5280, section 5.2.5, at most one of onlyContainsUserCerts, + // onlyContainsCACerts, and onlyContainsAttributeCerts may be true. + // TODO(crbug.com/42290307): Move this check to the `ISSUING_DIST_POINT` + // parser. + int num_only = + (!!crl->idp->onlyuser) + (!!crl->idp->onlyCA) + (!!crl->idp->onlyattr); + if (num_only > 1) { + return 0; + } + // Reason codes and indirect CRLs are not supported. + if (crl->idp->indirectCRL || crl->idp->onlysomereasons) { + return 0; + } } - // Lookup CRLs from store - skcrl = X509_STORE_CTX_get1_crls(ctx, X509_get_issuer_name(x)); + // We do not support indirect CRLs, so the issuer names must match. + if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl))) { + return 0; + } - // If no CRLs found and a near match from get_crl_sk use that - if (!skcrl && crl) { - goto done; + int crl_score = CRL_SCORE_ISSUER_NAME; + if (!(crl->flags & EXFLAG_CRITICAL)) { + crl_score |= CRL_SCORE_NOCRITICAL; } - get_crl_sk(ctx, &crl, &issuer, &crl_score, skcrl); + // Check expiry + if (check_crl_time(ctx, crl, /*notify=*/false, depth)) { + crl_score |= CRL_SCORE_TIME; + } - sk_X509_CRL_pop_free(skcrl, X509_CRL_free); + // Check authority key ID and locate certificate issuer + if (!crl_akid_check(ctx, crl, out_issuer, &crl_score, depth)) { + // If we can't locate certificate issuer at this point forget it + return 0; + } -done: - // If we got any kind of CRL use it and return success - if (crl) { - ctx->current_crl_issuer = issuer; - ctx->current_crl_score = crl_score; - *pcrl = crl; - return 1; + // Check cert for matching CRL distribution points + if (crl_crldp_check(x, crl, crl_score)) { + crl_score |= CRL_SCORE_SCOPE; } - return 0; + return crl_score; } -// Check CRL validity -static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl) { - X509Impl *issuer = nullptr; - int cnum = ctx->error_depth; - int chnum = (int)sk_X509_num(ctx->chain) - 1; - // If we have an alternative CRL issuer cert use that. Otherwise, it is the - // issuer of the current certificate. - if (ctx->current_crl_issuer) { - issuer = FromOpaque(ctx->current_crl_issuer); - } else if (cnum < chnum) { - issuer = FromOpaque(sk_X509_value(ctx->chain, cnum + 1)); - } else { - issuer = FromOpaque(sk_X509_value(ctx->chain, chnum)); - // If not self signed, can't check signature - if (!x509_check_issued_with_callback(ctx, issuer, issuer)) { - ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER; - if (!call_verify_cb(0, ctx)) { - return 0; +int get_crl_sk(X509_STORE_CTX *ctx, CRLInfo *best, STACK_OF(X509_CRL) *crls, + const X509 *x, int depth) { + for (X509_CRL *crl : crls) { + X509 *crl_issuer = nullptr; + int crl_score = get_crl_score(ctx, &crl_issuer, crl, x, depth); + if (crl_score < best->score || crl_score == 0) { + continue; + } + assert(crl_issuer != nullptr); + // If current CRL is equivalent use it if it is newer + if (crl_score == best->score && best->crl != nullptr) { + int day, sec; + if (ASN1_TIME_diff(&day, &sec, X509_CRL_get0_lastUpdate(best->crl.get()), + X509_CRL_get0_lastUpdate(crl)) == 0) { + continue; + } + // ASN1_TIME_diff never returns inconsistent signs for `day` + // and `sec`. + if (day <= 0 && sec <= 0) { + continue; } } + best->crl = UpRef(crl); + best->issuer = crl_issuer; + best->score = crl_score; } - if (issuer) { - // Check for cRLSign bit if keyUsage present - if ((issuer->ex_flags & EXFLAG_KUSAGE) && - !(issuer->ex_kusage & X509v3_KU_CRL_SIGN)) { - ctx->error = X509_V_ERR_KEYUSAGE_NO_CRL_SIGN; - if (!call_verify_cb(0, ctx)) { - return 0; - } + return best->score >= CRL_SCORE_VALID; +} + +// Retrieve CRL corresponding to current certificate. +int get_crl(X509_STORE_CTX *ctx, CRLInfo *out_crl_info, const X509 *x, + int depth) { + CRLInfo best; + if (!get_crl_sk(ctx, &best, ctx->crls, x, depth)) { + // If we haven't yet found a CRL with sufficiently high score, lookup CRLs + // from the store. + UniquePtr skcrl( + X509_STORE_CTX_get1_crls(ctx, X509_get_issuer_name(x))); + if (skcrl) { + get_crl_sk(ctx, &best, skcrl.get(), x, depth); } + } - if (!(ctx->current_crl_score & CRL_SCORE_SCOPE)) { - ctx->error = X509_V_ERR_DIFFERENT_CRL_SCOPE; - if (!call_verify_cb(0, ctx)) { - return 0; - } + // If we got any kind of CRL use it and return success + if (best.crl) { + *out_crl_info = std::move(best); + return 1; + } + + return 0; +} + +// Check CRL validity +int check_crl(X509_STORE_CTX *ctx, const CRLInfo &crl_info, int depth) { + X509_CRL *crl = crl_info.crl.get(); + X509Impl *issuer = FromOpaque(crl_info.issuer); + + // Check for cRLSign bit if keyUsage present + if ((issuer->ex_flags & EXFLAG_KUSAGE) && + !(issuer->ex_kusage & X509v3_KU_CRL_SIGN)) { + ctx->error = X509_V_ERR_KEYUSAGE_NO_CRL_SIGN; + if (!call_verify_cb_at_depth(0, ctx, depth)) { + return 0; } + } - if (crl->idp_flags & IDP_INVALID) { - ctx->error = X509_V_ERR_INVALID_EXTENSION; - if (!call_verify_cb(0, ctx)) { - return 0; - } + if (!(crl_info.score & CRL_SCORE_SCOPE)) { + ctx->error = X509_V_ERR_DIFFERENT_CRL_SCOPE; + if (!call_verify_cb_at_depth(0, ctx, depth)) { + return 0; } + } - if (!(ctx->current_crl_score & CRL_SCORE_TIME)) { - if (!check_crl_time(ctx, crl, 1)) { - return 0; - } + if (!(crl_info.score & CRL_SCORE_TIME)) { + if (!check_crl_time(ctx, crl, /*notify=*/true, depth)) { + return 0; } + } - // Attempt to get issuer certificate public key - EVP_PKEY *ikey = X509_get0_pubkey(issuer); - if (!ikey) { - ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY; - if (!call_verify_cb(0, ctx)) { + // Attempt to get issuer certificate public key + EVP_PKEY *ikey = X509_get0_pubkey(issuer); + if (!ikey) { + ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY; + if (!call_verify_cb_at_depth(0, ctx, depth)) { + return 0; + } + } else { + // Verify CRL signature + if (!x509_sig_nid_allowed(ctx, X509_CRL_get_signature_nid(crl)) || + X509_CRL_verify(crl, ikey) <= 0) { + ctx->error = X509_V_ERR_CRL_SIGNATURE_FAILURE; + if (!call_verify_cb_at_depth(0, ctx, depth)) { return 0; } - } else { - // Verify CRL signature - if (X509_CRL_verify(crl, ikey) <= 0) { - ctx->error = X509_V_ERR_CRL_SIGNATURE_FAILURE; - if (!call_verify_cb(0, ctx)) { - return 0; - } - } } } @@ -1124,7 +765,7 @@ static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl) { } // Check certificate against CRL -static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x) { +int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, const X509 *x, int depth) { // The rules changed for this... previously if a CRL contained unhandled // critical extensions it could still be used to indicate a certificate // was revoked. This has since been changed since critical extension can @@ -1132,7 +773,7 @@ static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x) { if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) && (crl->flags & EXFLAG_CRITICAL)) { ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, depth)) { return 0; } } @@ -1140,7 +781,7 @@ static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x) { X509_REVOKED *rev; if (X509_CRL_get0_by_cert(crl, &rev, x)) { ctx->error = X509_V_ERR_CERT_REVOKED; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, depth)) { return 0; } } @@ -1148,23 +789,57 @@ static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x) { return 1; } -static int check_policy(X509_STORE_CTX *ctx) { - X509 *current_cert = nullptr; +int check_revocation_for_cert(X509_STORE_CTX *ctx, int depth) { + X509 *x = sk_X509_value(ctx->chain, depth); + CRLInfo crl_info; + if (!get_crl(ctx, &crl_info, x, depth)) { + ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL; + return call_verify_cb_at_depth(0, ctx, depth); + } + + if (!check_crl(ctx, crl_info, depth) || // + !cert_crl(ctx, crl_info.crl.get(), x, depth)) { + return 0; + } + + return 1; +} + +int check_revocation(X509_STORE_CTX *ctx) { + if (!(ctx->param->flags & X509_V_FLAG_CRL_CHECK) || + sk_X509_num(ctx->chain) <= 1) { + return 1; + } + // Check either only the leaf, or everything but the trust anchor. The trust + // anchor is not formally part of RFC 5280 certification path and, without an + // issuer, we could not usefully process a CRL anyway. + const int num_to_check = (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL) + ? static_cast(sk_X509_num(ctx->chain)) - 1 + : 1; + for (int i = 0; i < num_to_check; i++) { + if (!check_revocation_for_cert(ctx, i)) { + return 0; + } + } + return 1; +} + +int check_policy(X509_STORE_CTX *ctx) { + int error_depth; int ret = X509_policy_check(ctx->chain, ctx->param->policies, - ctx->param->flags, ¤t_cert); + ctx->param->flags, &error_depth); if (ret != X509_V_OK) { - ctx->current_cert = current_cert; ctx->error = ret; if (ret == X509_V_ERR_OUT_OF_MEM) { return 0; } - return call_verify_cb(0, ctx); + return call_verify_cb_at_depth(0, ctx, error_depth); } return 1; } -static int check_cert_time(X509_STORE_CTX *ctx, X509 *x) { +int check_cert_time(X509_STORE_CTX *ctx, X509 *x, int depth) { if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME) { return 1; } @@ -1181,16 +856,14 @@ static int check_cert_time(X509_STORE_CTX *ctx, X509 *x) { : X509_cmp_time_posix(X509_get_notBefore(x), ptime); if (i == 0) { ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD; - ctx->current_cert = x; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, depth)) { return 0; } } if (i > 0) { ctx->error = X509_V_ERR_CERT_NOT_YET_VALID; - ctx->current_cert = x; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, depth)) { return 0; } } @@ -1200,16 +873,14 @@ static int check_cert_time(X509_STORE_CTX *ctx, X509 *x) { : X509_cmp_time_posix(X509_get_notAfter(x), ptime); if (i == 0) { ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD; - ctx->current_cert = x; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, depth)) { return 0; } } if (i < 0) { ctx->error = X509_V_ERR_CERT_HAS_EXPIRED; - ctx->current_cert = x; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, depth)) { return 0; } } @@ -1217,87 +888,259 @@ static int check_cert_time(X509_STORE_CTX *ctx, X509 *x) { return 1; } -static int verify_signature(X509_STORE_CTX *ctx, const X509 *x509, - const X509 *issuer, EVP_PKEY *pkey) { - int ret; - if ((ctx->param->flags & X509_V_FLAG_USE_MTC_DRAFT_PLANTS_05) && - x509_is_merkle_tree_ca(issuer)) { - ret = x509_verify_mtc(x509, pkey, issuer); - } else { - ret = X509_verify(x509, pkey); +int verify_signature(X509_STORE_CTX *ctx, const X509 *x509, + const X509 *issuer) { + EVP_PKEY *pkey = X509_get0_pubkey(issuer); + if (pkey == nullptr) { + return X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY; } + + int ret = x509_is_merkle_tree_ca(issuer) + ? x509_verify_mtc(ctx, x509, pkey, issuer) + : x509_sig_nid_allowed(ctx, X509_get_signature_nid(x509)) && + X509_verify(x509, pkey); return ret ? X509_V_OK : X509_V_ERR_CERT_SIGNATURE_FAILURE; } -static int internal_verify(X509_STORE_CTX *ctx) { - // TODO(davidben): This logic is incredibly confusing. Rewrite this: - // - // First, don't allow the verify callback to suppress - // X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, which will simplify the - // signature check. Then replace jumping into the middle of the loop. It's - // trying to ensure that all certificates see `check_cert_time`, then checking - // the root's self signature when requested, but not breaking partial chains - // in the process. - int n = (int)sk_X509_num(ctx->chain); - ctx->error_depth = n - 1; - n--; - X509 *xi = sk_X509_value(ctx->chain, n); - X509 *xs; - if (x509_check_issued_with_callback(ctx, xi, xi)) { - xs = xi; - } else { - if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) { - xs = xi; - goto check_cert; - } - if (n <= 0) { - ctx->error = X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE; - ctx->current_cert = xi; - return call_verify_cb(0, ctx); - } - n--; - ctx->error_depth = n; - xs = sk_X509_value(ctx->chain, n); - } - - // ctx->error=0; not needed - while (n >= 0) { - ctx->error_depth = n; - - // Skip signature check for self signed certificates unless - // explicitly asked for. It doesn't add any security and just wastes - // time. - if (xs != xi || (ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE)) { - EVP_PKEY *pkey = X509_get0_pubkey(xi); - int err = pkey == nullptr ? X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY - : verify_signature(ctx, xs, xi, pkey); - if (err != X509_V_OK) { +int check_chain_signatures_and_time(X509_STORE_CTX *ctx) { + size_t num = sk_X509_num(ctx->chain); + for (size_t i = num - 1; i < num; i--) { + X509 *x509 = sk_X509_value(ctx->chain, i); + if (i < num - 1) { + X509 *issuer = sk_X509_value(ctx->chain, i + 1); + if (int err = verify_signature(ctx, x509, issuer); err != X509_V_OK) { ctx->error = err; - ctx->current_cert = xs; - if (!call_verify_cb(0, ctx)) { + if (!call_verify_cb_at_depth(0, ctx, static_cast(i))) { return 0; } } } - check_cert: - if (!check_cert_time(ctx, xs)) { + if (!check_cert_time(ctx, x509, static_cast(i))) { return 0; } // The last error (if any) is still in the error value - ctx->current_cert = xs; - if (!call_verify_cb(1, ctx)) { + if (!call_verify_cb_at_depth(1, ctx, static_cast(i))) { + return 0; + } + } + + return 1; +} + +} // namespace + +bool bssl::x509_sig_nid_allowed(const X509_STORE_CTX *ctx, int sig_nid) { + // TODO(crbug.com/579959247): This check duplicates some logic from + // `x509_digest_verify_init` and makes assumptions about what algorithms it + // supports. Unify this. + int digest_nid, pkey_nid; + if (OBJ_find_sigid_algs(sig_nid, &digest_nid, &pkey_nid) && + digest_nid == NID_sha1 && + (ctx->param->flags & X509_V_FLAG_ALLOW_SHA1) == 0) { + return false; + } + return true; +} + +// Given a possible certificate and issuer check them +int bssl::x509_check_issued_with_callback(X509_STORE_CTX *ctx, const X509 *x, + const X509 *issuer) { + int ret; + ret = X509_check_issued(issuer, x); + if (ret == X509_V_OK) { + return 1; + } + // If we haven't asked for issuer errors don't set ctx + if (!(ctx->param->flags & X509_V_FLAG_CB_ISSUER_CHECK)) { + return 0; + } + + ctx->error = ret; + ctx->current_cert = const_cast(x); + return call_verify_cb(0, ctx); +} + +int X509_verify_cert(X509_STORE_CTX *ctx) { + int ok = 0; + Cleanup set_ctx_error = [&] { + // Safety net, error returns must set ctx->error + if (!ok && ctx->error == X509_V_OK) { + ctx->error = X509_V_ERR_UNSPECIFIED; + } + }; + + const X509_VERIFY_PARAM *param = ctx->param; + if (ctx->cert == nullptr) { + OPENSSL_PUT_ERROR(X509, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY); + ctx->error = X509_V_ERR_INVALID_CALL; + return 0; + } + + if (ctx->chain != nullptr) { + // This X509_STORE_CTX has already been used to verify a cert. We + // cannot do another one. + OPENSSL_PUT_ERROR(X509, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + ctx->error = X509_V_ERR_INVALID_CALL; + return 0; + } + + if (param->flags & + (X509_V_FLAG_EXTENDED_CRL_SUPPORT | X509_V_FLAG_USE_DELTAS)) { + // We do not support indirect or delta CRLs. The flags still exist for + // compatibility with bindings libraries, but to ensure we do not + // inadvertently skip a CRL check that the caller expects, fail closed. + OPENSSL_PUT_ERROR(X509, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + ctx->error = X509_V_ERR_INVALID_CALL; + return 0; + } + + // Copy the untrusted certificates so we can track which have been used. + // `untrusted` is not a `UniquePtr` because that would do a + // deep free and this is a shallow free. + STACK_OF(X509) *untrusted = nullptr; + Cleanup free_untrusted = [&] { sk_X509_free(untrusted); }; + if (ctx->untrusted != nullptr && + (untrusted = sk_X509_dup(ctx->untrusted)) == nullptr) { + ctx->error = X509_V_ERR_OUT_OF_MEM; + return 0; + } + + // `param->depth` does not include the leaf certificate or the trust anchor, + // so the maximum size is 2 more. + int max_chain = param->depth >= INT_MAX - 2 ? INT_MAX : param->depth + 2; + int trust = X509_TRUST_UNTRUSTED; + + // First, check if the target certificate already exists in the trust store as + // a trust "anchor". + if (UniquePtr store_cert = lookup_cert_match(ctx, ctx->cert); + store_cert != nullptr) { + ctx->chain = sk_X509_new_null(); + if (ctx->chain == nullptr || + !PushToStack(ctx->chain, std::move(store_cert))) { + ctx->error = X509_V_ERR_OUT_OF_MEM; + return 0; + } + trust = check_trust(ctx); + if (trust == X509_TRUST_REJECTED) { return 0; } + } - n--; - if (n >= 0) { - xi = xs; - xs = sk_X509_value(ctx->chain, n); + // If it was not a directly trusted (or distrusted) leaf, build a chain the + // usual way. (This is the common case.) + if (trust == X509_TRUST_UNTRUSTED) { + // Start with the target certificate. Clear `ctx->chain` in case there is + // any remnant of a failed trusted leaf above. + sk_X509_pop_free(ctx->chain, X509_free); + ctx->chain = sk_X509_new_null(); + if (ctx->chain == nullptr || !PushToStack(ctx->chain, UpRef(ctx->cert))) { + ctx->error = X509_V_ERR_OUT_OF_MEM; + return 0; } + + // Add certificates to the path until we reach a trust anchor, or fail. + bool have_store_cert = false; + for (;;) { + if (static_cast(sk_X509_num(ctx->chain)) >= max_chain) { + break; + } + + // If the last certificate is already self-signed, we won't get anywhere + // by looking further. + X509 *last = sk_X509_last(ctx->chain); + int is_self_signed; + if (!cert_self_signed(last, &is_self_signed)) { + ctx->error = X509_V_ERR_INVALID_EXTENSION; + return 0; + } + if (is_self_signed) { + break; + } + + // Prioritize looking for issuers in the store. + if (UniquePtr issuer = get_trusted_issuer(ctx, last); + issuer != nullptr) { + if (!PushToStack(ctx->chain, std::move(issuer))) { + ctx->error = X509_V_ERR_OUT_OF_MEM; + return 0; + } + have_store_cert = true; + // Certificates from the store are candidates to be trust anchors. + trust = check_trust(ctx); + if (trust == X509_TRUST_REJECTED) { + return 0; + } + if (trust == X509_TRUST_TRUSTED) { + break; + } + continue; + } + + // Look for an issuer among peer-provided untrusted intermediates, but + // only if we included a certificate from the store. For now, we match + // OpenSSL by not interleaving them, but the logic that relied on this has + // been removed. + if (!have_store_cert) { + if (X509 *issuer = find_issuer(ctx, untrusted, last); + issuer != nullptr) { + if (!PushToStack(ctx->chain, UpRef(issuer))) { + ctx->error = X509_V_ERR_OUT_OF_MEM; + return 0; + } + (void)sk_X509_delete_ptr(untrusted, issuer); + // We must not call `check_trust` here because the last certificate in + // the chain is not from the store. Otherwise, `check_trust` might + // mistake it for a trust anchor. + continue; + } + } + + // Couldn't find anything. + break; + } + + // `X509_TRUST_REJECTED` should have returned early. + assert(trust == X509_TRUST_UNTRUSTED || X509_TRUST_TRUSTED); + if (trust == X509_TRUST_UNTRUSTED) { + if (static_cast(sk_X509_num(ctx->chain)) >= max_chain) { + ctx->error = X509_V_ERR_CERT_CHAIN_TOO_LONG; + } else if (have_store_cert) { + ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT; + } else { + int is_self_signed; + if (!cert_self_signed(sk_X509_last(ctx->chain), &is_self_signed)) { + ctx->error = X509_V_ERR_INVALID_EXTENSION; + } else if (!is_self_signed) { + ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY; + } else if (sk_X509_num(ctx->chain) == 1) { + ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT; + } else { + ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN; + } + } + if (!call_verify_cb_at_depth(0, ctx, sk_X509_num(ctx->chain) - 1)) { + return 0; + } + } + } + + // Perform path validation. If the caller did not suppress some error with the + // verify callback, we now have either a path from the target certificate to + // some trust anchor or a directly trusted leaf. + assert(sk_X509_num(ctx->chain) >= 1); + if (!check_chain_extensions(ctx) || // + !check_id(ctx) || // + !check_revocation(ctx) || // + !check_blocklist(ctx) || // + !check_chain_signatures_and_time(ctx) || // + !check_name_constraints(ctx) || // + !check_policy(ctx)) { + return 0; } + ok = 1; return 1; } @@ -1393,10 +1236,6 @@ STACK_OF(X509) *X509_STORE_CTX_get1_chain(const X509_STORE_CTX *ctx) { return X509_chain_up_ref(ctx->chain); } -X509_CRL *X509_STORE_CTX_get0_current_crl(const X509_STORE_CTX *ctx) { - return ctx->current_crl; -} - X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(const X509_STORE_CTX *ctx) { // In OpenSSL, an `X509_STORE_CTX` sometimes has a parent context during CRL // path validation for indirect CRLs. We require the CRL to be issued diff --git a/third_party/boringssl/src/crypto/x509/x509_vpm.cc b/third_party/boringssl/src/crypto/x509/x509_vpm.cc index 9841ad7..775a24f 100644 --- a/third_party/boringssl/src/crypto/x509/x509_vpm.cc +++ b/third_party/boringssl/src/crypto/x509/x509_vpm.cc @@ -30,13 +30,15 @@ using namespace bssl; // X509_VERIFY_PARAM functions +namespace { + #define SET_HOST 0 #define ADD_HOST 1 -static void str_free(char *s) { OPENSSL_free(s); } +void str_free(char *s) { OPENSSL_free(s); } -static int int_x509_param_set_hosts(X509_VERIFY_PARAM *param, int mode, - const char *name, size_t namelen) { +int int_x509_param_set_hosts(X509_VERIFY_PARAM *param, int mode, + const char *name, size_t namelen) { char *copy; if (name == nullptr || namelen == 0) { @@ -78,27 +80,7 @@ static int int_x509_param_set_hosts(X509_VERIFY_PARAM *param, int mode, return 1; } -X509_VERIFY_PARAM *X509_VERIFY_PARAM_new() { - X509_VERIFY_PARAM *param = New(); - if (!param) { - return nullptr; - } - param->depth = -1; - return param; -} - -void X509_VERIFY_PARAM_free(X509_VERIFY_PARAM *param) { - if (param == nullptr) { - return; - } - sk_ASN1_OBJECT_pop_free(param->policies, ASN1_OBJECT_free); - sk_OPENSSL_STRING_pop_free(param->hosts, str_free); - OPENSSL_free(param->email); - OPENSSL_free(param->ip); - Delete(param); -} - -static bool should_copy(bool dest_is_set, bool src_is_set, bool prefer_src) { +bool should_copy(bool dest_is_set, bool src_is_set, bool prefer_src) { if (prefer_src) { // We prefer the source, so as long as there is a value to copy, copy it. return src_is_set; @@ -109,8 +91,7 @@ static bool should_copy(bool dest_is_set, bool src_is_set, bool prefer_src) { } template -static void copy_int_param(T *dest, const T *src, T default_val, - bool prefer_src) { +void copy_int_param(T *dest, const T *src, T default_val, bool prefer_src) { static_assert(std::is_integral_v); if (should_copy(*dest != default_val, *src != default_val, prefer_src)) { *dest = *src; @@ -120,9 +101,8 @@ static void copy_int_param(T *dest, const T *src, T default_val, // x509_verify_param_merge merges fields from `src` to `dest`. If both `src` and // `dest` have some field set, `prefer_src` determines whether `src` or `dest`'s // version is used. -static int x509_verify_param_merge(X509_VERIFY_PARAM *dest, - const X509_VERIFY_PARAM *src, - bool prefer_src) { +int x509_verify_param_merge(X509_VERIFY_PARAM *dest, + const X509_VERIFY_PARAM *src, bool prefer_src) { if (src == nullptr) { return 1; } @@ -183,22 +163,8 @@ static int x509_verify_param_merge(X509_VERIFY_PARAM *dest, return 1; } -int X509_VERIFY_PARAM_inherit(X509_VERIFY_PARAM *dest, - const X509_VERIFY_PARAM *src) { - // Prefer the destination. That is, this function only changes unset - // parameters in `dest`. - return x509_verify_param_merge(dest, src, /*prefer_src=*/false); -} - -int X509_VERIFY_PARAM_set1(X509_VERIFY_PARAM *to, - const X509_VERIFY_PARAM *from) { - // Prefer the source. That is, values in `to` are only preserved if they were - // unset in `from`. - return x509_verify_param_merge(to, from, /*prefer_src=*/true); -} - -static int int_x509_param_set1(char **pdest, size_t *pdestlen, const char *src, - size_t srclen) { +int int_x509_param_set1(char **pdest, size_t *pdestlen, const char *src, + size_t srclen) { void *tmp; if (src == nullptr || srclen == 0) { // Unlike OpenSSL, we do not allow an empty string to disable previously @@ -221,6 +187,107 @@ static int int_x509_param_set1(char **pdest, size_t *pdestlen, const char *src, return 1; } +const X509_VERIFY_PARAM kDefaultParam = { + /*check_time=*/0, + /*flags=*/X509_V_FLAG_ALLOW_SHA1, // TODO(crbug.com/461736992): remove once + // no longer needed. + /*purpose=*/0, + /*trust=*/0, + /*depth=*/100, + /*policies=*/nullptr, + /*hosts=*/nullptr, + /*hostflags=*/0, + /*email=*/nullptr, + /*emaillen=*/0, + /*ip=*/nullptr, + /*iplen=*/0, + /*poison=*/0, +}; + +const X509_VERIFY_PARAM kSMIMESignParam = { + /*check_time=*/0, + /*flags=*/0, + /*purpose=*/X509_PURPOSE_SMIME_SIGN, + /*trust=*/X509_TRUST_EMAIL, + /*depth=*/-1, + /*policies=*/nullptr, + /*hosts=*/nullptr, + /*hostflags=*/0, + /*email=*/nullptr, + /*emaillen=*/0, + /*ip=*/nullptr, + /*iplen=*/0, + /*poison=*/0, +}; + +const X509_VERIFY_PARAM kSSLClientParam = { + /*check_time=*/0, + /*flags=*/0, + /*purpose=*/X509_PURPOSE_SSL_CLIENT, + /*trust=*/X509_TRUST_SSL_CLIENT, + /*depth=*/-1, + /*policies=*/nullptr, + /*hosts=*/nullptr, + /*hostflags=*/0, + /*email=*/nullptr, + /*emaillen=*/0, + /*ip=*/nullptr, + /*iplen=*/0, + /*poison=*/0, +}; + +const X509_VERIFY_PARAM kSSLServerParam = { + /*check_time=*/0, + /*flags=*/0, + /*purpose=*/X509_PURPOSE_SSL_SERVER, + /*trust=*/X509_TRUST_SSL_SERVER, + /*depth=*/-1, + /*policies=*/nullptr, + /*hosts=*/nullptr, + /*hostflags=*/0, + /*email=*/nullptr, + /*emaillen=*/0, + /*ip=*/nullptr, + /*iplen=*/0, + /*poison=*/0, +}; + +} // namespace + +X509_VERIFY_PARAM *X509_VERIFY_PARAM_new() { + X509_VERIFY_PARAM *param = New(); + if (!param) { + return nullptr; + } + param->depth = -1; + return param; +} + +void X509_VERIFY_PARAM_free(X509_VERIFY_PARAM *param) { + if (param == nullptr) { + return; + } + sk_ASN1_OBJECT_pop_free(param->policies, ASN1_OBJECT_free); + sk_OPENSSL_STRING_pop_free(param->hosts, str_free); + OPENSSL_free(param->email); + OPENSSL_free(param->ip); + Delete(param); +} + +int X509_VERIFY_PARAM_inherit(X509_VERIFY_PARAM *dest, + const X509_VERIFY_PARAM *src) { + // Prefer the destination. That is, this function only changes unset + // parameters in `dest`. + return x509_verify_param_merge(dest, src, /*prefer_src=*/false); +} + +int X509_VERIFY_PARAM_set1(X509_VERIFY_PARAM *to, + const X509_VERIFY_PARAM *from) { + // Prefer the source. That is, values in `to` are only preserved if they were + // unset in `from`. + return x509_verify_param_merge(to, from, /*prefer_src=*/true); +} + int X509_VERIFY_PARAM_set_flags(X509_VERIFY_PARAM *param, unsigned long flags) { param->flags |= flags; return 1; @@ -364,70 +431,6 @@ int X509_VERIFY_PARAM_get_depth(const X509_VERIFY_PARAM *param) { return param->depth; } -static const X509_VERIFY_PARAM kDefaultParam = { - /*check_time=*/0, - /*flags=*/0, - /*purpose=*/0, - /*trust=*/0, - /*depth=*/100, - /*policies=*/nullptr, - /*hosts=*/nullptr, - /*hostflags=*/0, - /*email=*/nullptr, - /*emaillen=*/0, - /*ip=*/nullptr, - /*iplen=*/0, - /*poison=*/0, -}; - -static const X509_VERIFY_PARAM kSMIMESignParam = { - /*check_time=*/0, - /*flags=*/0, - /*purpose=*/X509_PURPOSE_SMIME_SIGN, - /*trust=*/X509_TRUST_EMAIL, - /*depth=*/-1, - /*policies=*/nullptr, - /*hosts=*/nullptr, - /*hostflags=*/0, - /*email=*/nullptr, - /*emaillen=*/0, - /*ip=*/nullptr, - /*iplen=*/0, - /*poison=*/0, -}; - -static const X509_VERIFY_PARAM kSSLClientParam = { - /*check_time=*/0, - /*flags=*/0, - /*purpose=*/X509_PURPOSE_SSL_CLIENT, - /*trust=*/X509_TRUST_SSL_CLIENT, - /*depth=*/-1, - /*policies=*/nullptr, - /*hosts=*/nullptr, - /*hostflags=*/0, - /*email=*/nullptr, - /*emaillen=*/0, - /*ip=*/nullptr, - /*iplen=*/0, - /*poison=*/0, -}; - -static const X509_VERIFY_PARAM kSSLServerParam = { - /*check_time=*/0, - /*flags=*/0, - /*purpose=*/X509_PURPOSE_SSL_SERVER, - /*trust=*/X509_TRUST_SSL_SERVER, - /*depth=*/-1, - /*policies=*/nullptr, - /*hosts=*/nullptr, - /*hostflags=*/0, - /*email=*/nullptr, - /*emaillen=*/0, - /*ip=*/nullptr, - /*iplen=*/0, - /*poison=*/0, -}; - const X509_VERIFY_PARAM *bssl::X509_VERIFY_PARAM_lookup(const char *name) { if (strcmp(name, "default") == 0) { return &kDefaultParam; diff --git a/third_party/boringssl/src/crypto/x509/x509cset.cc b/third_party/boringssl/src/crypto/x509/x509cset.cc index 19e938a..5ece53d 100644 --- a/third_party/boringssl/src/crypto/x509/x509cset.cc +++ b/third_party/boringssl/src/crypto/x509/x509cset.cc @@ -103,6 +103,15 @@ int X509_CRL_up_ref(X509_CRL *crl) { return 1; } +X509_CRL *X509_CRL_dup_ref(const X509_CRL *crl) { + if (crl == nullptr) { + return nullptr; + } + auto *ptr = const_cast(crl); + CRYPTO_refcount_inc(&ptr->references); + return ptr; +} + long X509_CRL_get_version(const X509_CRL *crl) { return ASN1_INTEGER_get(crl->crl->version); } diff --git a/third_party/boringssl/src/crypto/x509/x509rset.cc b/third_party/boringssl/src/crypto/x509/x509rset.cc index 076a3bf..010d453 100644 --- a/third_party/boringssl/src/crypto/x509/x509rset.cc +++ b/third_party/boringssl/src/crypto/x509/x509rset.cc @@ -31,14 +31,14 @@ int X509_REQ_set_version(X509_REQ *x, long version) { return ASN1_INTEGER_set_int64(x->req_info->version, version); } -int X509_REQ_set_subject_name(X509_REQ *x, X509_NAME *name) { +int X509_REQ_set_subject_name(X509_REQ *x, const X509_NAME *name) { if ((x == nullptr) || (x->req_info == nullptr)) { return 0; } return (X509_NAME_set(&x->req_info->subject, name)); } -int X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey) { +int X509_REQ_set_pubkey(X509_REQ *x, const EVP_PKEY *pkey) { if ((x == nullptr) || (x->req_info == nullptr)) { return 0; } diff --git a/third_party/boringssl/src/crypto/x509/x509spki.cc b/third_party/boringssl/src/crypto/x509/x509spki.cc index 67b0799..c630c0b 100644 --- a/third_party/boringssl/src/crypto/x509/x509spki.cc +++ b/third_party/boringssl/src/crypto/x509/x509spki.cc @@ -19,7 +19,7 @@ #include #include -int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey) { +int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, const EVP_PKEY *pkey) { if ((x == nullptr) || (x->spkac == nullptr)) { return 0; } @@ -64,7 +64,7 @@ NETSCAPE_SPKI *NETSCAPE_SPKI_b64_decode(const char *str, ossl_ssize_t len) { // Generate a base64 encoded string from an SPKI -char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *spki) { +char *NETSCAPE_SPKI_b64_encode(const NETSCAPE_SPKI *spki) { unsigned char *der_spki, *p; char *b64_str; size_t b64_len; diff --git a/third_party/boringssl/src/crypto/x509/x_algor.cc b/third_party/boringssl/src/crypto/x509/x_algor.cc index b4591e5..93926c3 100644 --- a/third_party/boringssl/src/crypto/x509/x_algor.cc +++ b/third_party/boringssl/src/crypto/x509/x_algor.cc @@ -209,15 +209,10 @@ int X509_ALGOR_set_md(X509_ALGOR *alg, const EVP_MD *md) { nullptr); } -// X509_ALGOR_cmp returns 0 if `a` and `b` are equal and non-zero otherwise. int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b) { - int rv; - rv = OBJ_cmp(a->algorithm, b->algorithm); - if (rv) { - return rv; - } - if (!a->parameter && !b->parameter) { - return 0; + int ret = OBJ_cmp(a->algorithm, b->algorithm); + if (ret != 0) { + return ret; } return ASN1_TYPE_cmp(a->parameter, b->parameter); } diff --git a/third_party/boringssl/src/crypto/x509/x_all.cc b/third_party/boringssl/src/crypto/x509/x_all.cc index b9990b8..988574a 100644 --- a/third_party/boringssl/src/crypto/x509/x_all.cc +++ b/third_party/boringssl/src/crypto/x509/x_all.cc @@ -35,7 +35,7 @@ using namespace bssl; -int X509_verify(const X509 *x509, EVP_PKEY *pkey) { +int X509_verify(const X509 *x509, const EVP_PKEY *pkey) { auto *impl = FromOpaque(x509); if (X509_ALGOR_cmp(impl->sig_alg.get(), impl->tbs_sig_alg.get())) { OPENSSL_PUT_ERROR(X509, X509_R_SIGNATURE_ALGORITHM_MISMATCH); @@ -51,12 +51,12 @@ int X509_verify(const X509 *x509, EVP_PKEY *pkey) { pkey); } -int X509_REQ_verify(const X509_REQ *req, EVP_PKEY *pkey) { +int X509_REQ_verify(const X509_REQ *req, const EVP_PKEY *pkey) { return ASN1_item_verify(ASN1_ITEM_rptr(X509_REQ_INFO), req->sig_alg, req->signature, req->req_info, pkey); } -int X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md) { +int X509_sign(X509 *x, const EVP_PKEY *pkey, const EVP_MD *md) { ScopedEVP_MD_CTX ctx; if (!EVP_DigestSignInit(ctx.get(), nullptr, md, nullptr, pkey)) { return 0; @@ -64,6 +64,25 @@ int X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md) { return X509_sign_ctx(x, ctx.get()); } +int X509_set_unsigned(X509 *x509) { + if (ScopedX509Algor algor; + !X509_ALGOR_set0(algor.get(), OBJ_nid2obj(NID_alg_unsigned), V_ASN1_UNDEF, + nullptr) || + !X509_set1_signature_algo(x509, algor.get())) { + return 0; + } + if (X509_NAME_entry_count(X509_get_issuer_name(x509)) == 0) { + if (UniquePtr name(X509_NAME_new()); + !name || + !X509_NAME_add_entry_by_NID(name.get(), NID_rdna_unsigned, + V_ASN1_UTF8STRING, nullptr, 0, -1, 0) || + !X509_set_issuer_name(x509, name.get())) { + return 0; + } + } + return X509_set1_signature_value(x509, nullptr, 0); +} + int X509_sign_ctx(X509 *x, EVP_MD_CTX *ctx) { // Historically, this function called `EVP_MD_CTX_cleanup` on return. Some // callers rely on this to avoid memory leaks. @@ -89,7 +108,7 @@ int X509_sign_ctx(X509 *x, EVP_MD_CTX *ctx) { CBBAsSpan(cbb.get())); } -int X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md) { +int X509_REQ_sign(X509_REQ *x, const EVP_PKEY *pkey, const EVP_MD *md) { asn1_encoding_clear(&x->req_info->enc); return ASN1_item_sign(ASN1_ITEM_rptr(X509_REQ_INFO), x->sig_alg, nullptr, x->signature, x->req_info, pkey, md); @@ -101,7 +120,7 @@ int X509_REQ_sign_ctx(X509_REQ *x, EVP_MD_CTX *ctx) { x->signature, x->req_info, ctx); } -int X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md) { +int X509_CRL_sign(X509_CRL *x, const EVP_PKEY *pkey, const EVP_MD *md) { asn1_encoding_clear(&x->crl->enc); return ASN1_item_sign(ASN1_ITEM_rptr(X509_CRL_INFO), x->crl->sig_alg, x->sig_alg, x->signature, x->crl, pkey, md); @@ -113,12 +132,13 @@ int X509_CRL_sign_ctx(X509_CRL *x, EVP_MD_CTX *ctx) { x->sig_alg, x->signature, x->crl, ctx); } -int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *x, EVP_PKEY *pkey, const EVP_MD *md) { +int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *x, const EVP_PKEY *pkey, + const EVP_MD *md) { return ASN1_item_sign(ASN1_ITEM_rptr(NETSCAPE_SPKAC), x->sig_algor, nullptr, x->signature, x->spkac, pkey, md); } -int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *spki, EVP_PKEY *pkey) { +int NETSCAPE_SPKI_verify(const NETSCAPE_SPKI *spki, const EVP_PKEY *pkey) { return ASN1_item_verify(ASN1_ITEM_rptr(NETSCAPE_SPKAC), spki->sig_algor, spki->signature, spki->spkac, pkey); } diff --git a/third_party/boringssl/src/crypto/x509/x_crl.cc b/third_party/boringssl/src/crypto/x509/x_crl.cc index d30c172..05af8b4 100644 --- a/third_party/boringssl/src/crypto/x509/x_crl.cc +++ b/third_party/boringssl/src/crypto/x509/x_crl.cc @@ -31,28 +31,18 @@ using namespace bssl; -static int X509_REVOKED_cmp(const X509_REVOKED *const *a, - const X509_REVOKED *const *b); -static int setup_idp(X509_CRL *crl, ISSUING_DIST_POINT *idp); +namespace { -BSSL_NAMESPACE_BEGIN - -ASN1_SEQUENCE(X509_REVOKED) = { - ASN1_SIMPLE(X509_REVOKED, serialNumber, ASN1_INTEGER), - ASN1_SIMPLE(X509_REVOKED, revocationDate, ASN1_TIME), - ASN1_SEQUENCE_OF_OPT(X509_REVOKED, extensions, X509_EXTENSION), -} ASN1_SEQUENCE_END(X509_REVOKED) - -BSSL_NAMESPACE_END - -static int crl_lookup(X509_CRL *crl, X509_REVOKED **ret, - const ASN1_INTEGER *serial, const X509_NAME *issuer); +int X509_REVOKED_cmp(const X509_REVOKED *const *a, + const X509_REVOKED *const *b) { + return ASN1_STRING_cmp((*a)->serialNumber, (*b)->serialNumber); +} // The X509_CRL_INFO structure needs a bit of customisation. Since we cache // the original encoding the signature won't be affected by reordering of the // revoked field. -static int crl_inf_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, - void *exarg) { +int crl_inf_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, + void *exarg) { X509_CRL_INFO *a = asn1_load_ptr_as(pval); if (!a || !a->revoked) { return 1; @@ -67,21 +57,7 @@ static int crl_inf_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, return 1; } -BSSL_NAMESPACE_BEGIN - -ASN1_SEQUENCE_enc(X509_CRL_INFO, enc, crl_inf_cb) = { - ASN1_OPT(X509_CRL_INFO, version, ASN1_INTEGER), - ASN1_SIMPLE(X509_CRL_INFO, sig_alg, X509_ALGOR), - ASN1_SIMPLE(X509_CRL_INFO, issuer, X509_NAME), - ASN1_SIMPLE(X509_CRL_INFO, lastUpdate, ASN1_TIME), - ASN1_OPT(X509_CRL_INFO, nextUpdate, ASN1_TIME), - ASN1_SEQUENCE_OF_OPT(X509_CRL_INFO, revoked, X509_REVOKED), - ASN1_EXP_SEQUENCE_OF_OPT(X509_CRL_INFO, extensions, X509_EXTENSION, 0), -} ASN1_SEQUENCE_END_enc(X509_CRL_INFO, X509_CRL_INFO) - -BSSL_NAMESPACE_END - -static int crl_parse_entry_extensions(X509_CRL *crl) { +int crl_parse_entry_extensions(X509_CRL *crl) { long version = ASN1_INTEGER_get(crl->crl->version); STACK_OF(X509_REVOKED) *revoked = X509_CRL_get_REVOKED(crl); for (size_t i = 0; i < sk_X509_REVOKED_num(revoked); i++) { @@ -131,8 +107,7 @@ static int crl_parse_entry_extensions(X509_CRL *crl) { // The X509_CRL structure needs a bit of customisation. Cache some extensions // and hash of the whole CRL. -static int crl_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, - void *exarg) { +int crl_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { X509_CRL *crl = asn1_load_ptr_as(pval); int i; @@ -141,7 +116,6 @@ static int crl_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, crl->idp = nullptr; crl->akid = nullptr; crl->flags = 0; - crl->idp_flags = 0; break; case ASN1_OP_D2I_POST: { @@ -176,11 +150,7 @@ static int crl_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, crl->idp = reinterpret_cast(X509_CRL_get_ext_d2i( crl, NID_issuing_distribution_point, &i, nullptr)); - if (crl->idp != nullptr) { - if (!setup_idp(crl, crl->idp)) { - return 0; - } - } else if (i != -1) { + if (crl->idp == nullptr && i != -1) { return 0; } @@ -223,51 +193,74 @@ static int crl_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, return 1; } -// Convert IDP into a more convenient form -// -// TODO(davidben): Each of these flags are already booleans, so this is not -// really more convenient. We can probably remove `idp_flags`. -static int setup_idp(X509_CRL *crl, ISSUING_DIST_POINT *idp) { - int idp_only = 0; - // Set various flags according to IDP - crl->idp_flags |= IDP_PRESENT; - if (idp->onlyuser > 0) { - idp_only++; - crl->idp_flags |= IDP_ONLYUSER; - } - if (idp->onlyCA > 0) { - idp_only++; - crl->idp_flags |= IDP_ONLYCA; - } - if (idp->onlyattr > 0) { - idp_only++; - crl->idp_flags |= IDP_ONLYATTR; - } +int crl_revoked_issuer_match(const X509_CRL *crl, const X509_NAME *nm, + const X509_REVOKED *rev) { + return nm == nullptr || X509_NAME_cmp(nm, X509_CRL_get_issuer(crl)) == 0; +} - // Per RFC 5280, section 5.2.5, at most one of onlyContainsUserCerts, - // onlyContainsCACerts, and onlyContainsAttributeCerts may be true. - // - // TODO(crbug.com/boringssl/443): Move this check to the `ISSUING_DIST_POINT` - // parser. - if (idp_only > 1) { - crl->idp_flags |= IDP_INVALID; - } +StaticMutex g_crl_sort_lock; - if (idp->indirectCRL > 0) { - crl->idp_flags |= IDP_INDIRECT; - } +int crl_lookup(X509_CRL *crl, X509_REVOKED **ret, const ASN1_INTEGER *serial, + const X509_NAME *issuer) { + // Use an assert, rather than a runtime error, because returning nothing for a + // CRL is arguably failing open, rather than closed. + assert(serial->type == V_ASN1_INTEGER || serial->type == V_ASN1_NEG_INTEGER); + X509_REVOKED rtmp; + size_t idx; + rtmp.serialNumber = (ASN1_INTEGER *)serial; + // Sort revoked into serial number order if not already sorted. Do this + // under a lock to avoid race condition. + + g_crl_sort_lock.LockRead(); + const int is_sorted = sk_X509_REVOKED_is_sorted(crl->crl->revoked); + g_crl_sort_lock.UnlockRead(); - if (idp->onlysomereasons) { - crl->idp_flags |= IDP_REASONS; + if (!is_sorted) { + MutexWriteLock lock(&g_crl_sort_lock); + if (!sk_X509_REVOKED_is_sorted(crl->crl->revoked)) { + sk_X509_REVOKED_sort(crl->crl->revoked); + } } - // TODO(davidben): The new verifier does not support nameRelativeToCRLIssuer. - // Remove this? - return DIST_POINT_set_dpname(idp->distpoint, X509_CRL_get_issuer(crl)); + if (!sk_X509_REVOKED_find(crl->crl->revoked, &idx, &rtmp)) { + return 0; + } + // Need to look for matching name + for (; idx < sk_X509_REVOKED_num(crl->crl->revoked); idx++) { + X509_REVOKED *rev = sk_X509_REVOKED_value(crl->crl->revoked, idx); + if (ASN1_INTEGER_cmp(rev->serialNumber, serial)) { + return 0; + } + if (crl_revoked_issuer_match(crl, issuer, rev)) { + if (ret) { + *ret = rev; + } + return 1; + } + } + return 0; } +} // namespace + BSSL_NAMESPACE_BEGIN +ASN1_SEQUENCE(X509_REVOKED) = { + ASN1_SIMPLE(X509_REVOKED, serialNumber, ASN1_INTEGER), + ASN1_SIMPLE(X509_REVOKED, revocationDate, ASN1_TIME), + ASN1_SEQUENCE_OF_OPT(X509_REVOKED, extensions, X509_EXTENSION), +} ASN1_SEQUENCE_END(X509_REVOKED) + +ASN1_SEQUENCE_enc(X509_CRL_INFO, enc, crl_inf_cb) = { + ASN1_OPT(X509_CRL_INFO, version, ASN1_INTEGER), + ASN1_SIMPLE(X509_CRL_INFO, sig_alg, X509_ALGOR), + ASN1_SIMPLE(X509_CRL_INFO, issuer, X509_NAME), + ASN1_SIMPLE(X509_CRL_INFO, lastUpdate, ASN1_TIME), + ASN1_OPT(X509_CRL_INFO, nextUpdate, ASN1_TIME), + ASN1_SEQUENCE_OF_OPT(X509_CRL_INFO, revoked, X509_REVOKED), + ASN1_EXP_SEQUENCE_OF_OPT(X509_CRL_INFO, extensions, X509_EXTENSION, 0), +} ASN1_SEQUENCE_END_enc(X509_CRL_INFO, X509_CRL_INFO) + ASN1_SEQUENCE_ref(X509_CRL, crl_cb) = { ASN1_SIMPLE(X509_CRL, crl, X509_CRL_INFO), ASN1_SIMPLE(X509_CRL, sig_alg, X509_ALGOR), @@ -288,11 +281,6 @@ BSSL_NAMESPACE_END IMPLEMENT_ASN1_FUNCTIONS_const(X509_CRL) IMPLEMENT_ASN1_DUP_FUNCTION_const(X509_CRL) -static int X509_REVOKED_cmp(const X509_REVOKED *const *a, - const X509_REVOKED *const *b) { - return ASN1_STRING_cmp((*a)->serialNumber, (*b)->serialNumber); -} - int X509_CRL_add0_revoked(X509_CRL *crl, X509_REVOKED *rev) { X509_CRL_INFO *inf = crl->crl; if (!inf->revoked) { @@ -305,7 +293,7 @@ int X509_CRL_add0_revoked(X509_CRL *crl, X509_REVOKED *rev) { return 1; } -int X509_CRL_verify(const X509_CRL *crl, EVP_PKEY *pkey) { +int X509_CRL_verify(const X509_CRL *crl, const EVP_PKEY *pkey) { if (X509_ALGOR_cmp(crl->sig_alg, crl->crl->sig_alg) != 0) { OPENSSL_PUT_ERROR(X509, X509_R_SIGNATURE_ALGORITHM_MISMATCH); return 0; @@ -324,51 +312,3 @@ int X509_CRL_get0_by_cert(X509_CRL *crl, X509_REVOKED **ret, const X509 *x) { return crl_lookup(crl, ret, X509_get0_serialNumber(x), X509_get_issuer_name(x)); } - -static int crl_revoked_issuer_match(const X509_CRL *crl, const X509_NAME *nm, - const X509_REVOKED *rev) { - return nm == nullptr || X509_NAME_cmp(nm, X509_CRL_get_issuer(crl)) == 0; -} - -static StaticMutex g_crl_sort_lock; - -static int crl_lookup(X509_CRL *crl, X509_REVOKED **ret, - const ASN1_INTEGER *serial, const X509_NAME *issuer) { - // Use an assert, rather than a runtime error, because returning nothing for a - // CRL is arguably failing open, rather than closed. - assert(serial->type == V_ASN1_INTEGER || serial->type == V_ASN1_NEG_INTEGER); - X509_REVOKED rtmp; - size_t idx; - rtmp.serialNumber = (ASN1_INTEGER *)serial; - // Sort revoked into serial number order if not already sorted. Do this - // under a lock to avoid race condition. - - g_crl_sort_lock.LockRead(); - const int is_sorted = sk_X509_REVOKED_is_sorted(crl->crl->revoked); - g_crl_sort_lock.UnlockRead(); - - if (!is_sorted) { - MutexWriteLock lock(&g_crl_sort_lock); - if (!sk_X509_REVOKED_is_sorted(crl->crl->revoked)) { - sk_X509_REVOKED_sort(crl->crl->revoked); - } - } - - if (!sk_X509_REVOKED_find(crl->crl->revoked, &idx, &rtmp)) { - return 0; - } - // Need to look for matching name - for (; idx < sk_X509_REVOKED_num(crl->crl->revoked); idx++) { - X509_REVOKED *rev = sk_X509_REVOKED_value(crl->crl->revoked, idx); - if (ASN1_INTEGER_cmp(rev->serialNumber, serial)) { - return 0; - } - if (crl_revoked_issuer_match(crl, issuer, rev)) { - if (ret) { - *ret = rev; - } - return 1; - } - } - return 0; -} diff --git a/third_party/boringssl/src/crypto/x509/x_name.cc b/third_party/boringssl/src/crypto/x509/x_name.cc index ac1a8cc..753d653 100644 --- a/third_party/boringssl/src/crypto/x509/x_name.cc +++ b/third_party/boringssl/src/crypto/x509/x_name.cc @@ -40,17 +40,79 @@ using namespace bssl; // X509_NAME_MAX is the length of the maximum encoded `X509_NAME` we accept. #define X509_NAME_MAX (1024 * 1024) -static int asn1_marshal_string_canon(CBB *cbb, const ASN1_STRING *in); +namespace { -bssl::X509NameEntry::X509NameEntry() { - object.reset(const_cast(OBJ_get_undef())); -} +int asn1_marshal_string_canon(CBB *cbb, const ASN1_STRING *in) { + int (*decode_func)(CBS *, uint32_t *); + int error; + switch (in->type) { + case V_ASN1_UTF8STRING: + decode_func = CBS_get_utf8; + error = ASN1_R_INVALID_UTF8STRING; + break; + case V_ASN1_BMPSTRING: + decode_func = CBS_get_ucs2_be; + error = ASN1_R_INVALID_BMPSTRING; + break; + case V_ASN1_UNIVERSALSTRING: + decode_func = CBS_get_utf32_be; + error = ASN1_R_INVALID_UNIVERSALSTRING; + break; + case V_ASN1_PRINTABLESTRING: + case V_ASN1_T61STRING: + case V_ASN1_IA5STRING: + case V_ASN1_VISIBLESTRING: + decode_func = CBS_get_latin1; + error = ERR_R_INTERNAL_ERROR; // Latin-1 inputs are never invalid. + break; + default: + // Other string types are not canonicalized. + return asn1_marshal_any_string(cbb, in); + } -X509_NAME_ENTRY *X509_NAME_ENTRY_new() { return New(); } + CBB child; + if (!CBB_add_asn1(cbb, &child, CBS_ASN1_UTF8STRING)) { + return 0; + } -void X509_NAME_ENTRY_free(X509_NAME_ENTRY *entry) { Delete(FromOpaque(entry)); } + bool empty = true; + bool in_whitespace = false; + CBS cbs; + CBS_init(&cbs, in->data, in->length); + while (CBS_len(&cbs) != 0) { + uint32_t c; + if (!decode_func(&cbs, &c)) { + OPENSSL_PUT_ERROR(ASN1, error); + return 0; + } + if (OPENSSL_isspace(c)) { + if (empty) { + continue; // Trim leading whitespace. + } + in_whitespace = true; + } else { + if (in_whitespace) { + // Collapse the previous run of whitespace into one space. + if (!CBB_add_u8(&child, ' ')) { + return 0; + } + } + in_whitespace = false; + // Lowecase ASCII codepoints. + if (c <= 0x7f) { + c = OPENSSL_tolower(c); + } + if (!CBB_add_utf8(&child, c)) { + return 0; + } + empty = false; + } + } -static int x509_parse_name_entry(CBS *cbs, X509_NAME_ENTRY *out) { + return CBB_flush(cbb); +} + +int x509_parse_name_entry(CBS *cbs, X509_NAME_ENTRY *out) { auto *out_impl = FromOpaque(out); CBS seq; if (!CBS_get_asn1(cbs, &seq, CBS_ASN1_SEQUENCE)) { @@ -67,8 +129,8 @@ static int x509_parse_name_entry(CBS *cbs, X509_NAME_ENTRY *out) { return 1; } -static int x509_marshal_name_entry(CBB *cbb, const X509_NAME_ENTRY *entry, - int canonicalize) { +int x509_marshal_name_entry(CBB *cbb, const X509_NAME_ENTRY *entry, + int canonicalize) { auto *entry_impl = FromOpaque(entry); CBB seq; if (!CBB_add_asn1(cbb, &seq, CBS_ASN1_SEQUENCE) || @@ -84,11 +146,51 @@ static int x509_marshal_name_entry(CBB *cbb, const X509_NAME_ENTRY *entry, return CBB_flush(cbb); } -static int x509_marshal_name_entry_no_canon(CBB *cbb, - const X509_NAME_ENTRY *entry) { +int x509_marshal_name_entry_no_canon(CBB *cbb, const X509_NAME_ENTRY *entry) { return x509_marshal_name_entry(cbb, entry, /*canonicalize=*/0); } +int x509_marshal_name_entries(CBB *out, const X509_NAME *name, + int canonicalize) { + auto *impl = FromOpaque(name); + if (sk_X509_NAME_ENTRY_num(impl->entries.get()) == 0) { + return 1; + } + + // Bootstrap the first RDN. + int set = FromOpaque(sk_X509_NAME_ENTRY_value(impl->entries.get(), 0))->set; + CBB rdn; + if (!CBB_add_asn1(out, &rdn, CBS_ASN1_SET)) { + return 0; + } + + for (const X509_NAME_ENTRY *entry : impl->entries.get()) { + if (FromOpaque(entry)->set != set) { + // Flush the previous RDN and start a new one. + if (!CBB_flush_asn1_set_of(&rdn) || + !CBB_add_asn1(out, &rdn, CBS_ASN1_SET)) { + return 0; + } + set = FromOpaque(entry)->set; + } + if (!x509_marshal_name_entry(&rdn, entry, canonicalize)) { + return 0; + } + } + + return CBB_flush_asn1_set_of(&rdn) && CBB_flush(out); +} + +} // namespace + +bssl::X509NameEntry::X509NameEntry() { + object.reset(const_cast(OBJ_get_undef())); +} + +X509_NAME_ENTRY *X509_NAME_ENTRY_new() { return New(); } + +void X509_NAME_ENTRY_free(X509_NAME_ENTRY *entry) { Delete(FromOpaque(entry)); } + BSSL_NAMESPACE_BEGIN IMPLEMENT_EXTERN_ASN1_PARSE_INTO(X509_NAME_ENTRY, X509_NAME_ENTRY_new, @@ -158,37 +260,6 @@ int bssl::x509_parse_name(CBS *cbs, X509_NAME *out) { return x509_name_get_cache(impl) != nullptr; } -static int x509_marshal_name_entries(CBB *out, const X509_NAME *name, - int canonicalize) { - auto *impl = FromOpaque(name); - if (sk_X509_NAME_ENTRY_num(impl->entries.get()) == 0) { - return 1; - } - - // Bootstrap the first RDN. - int set = FromOpaque(sk_X509_NAME_ENTRY_value(impl->entries.get(), 0))->set; - CBB rdn; - if (!CBB_add_asn1(out, &rdn, CBS_ASN1_SET)) { - return 0; - } - - for (const X509_NAME_ENTRY *entry : impl->entries.get()) { - if (FromOpaque(entry)->set != set) { - // Flush the previous RDN and start a new one. - if (!CBB_flush_asn1_set_of(&rdn) || - !CBB_add_asn1(out, &rdn, CBS_ASN1_SET)) { - return 0; - } - set = FromOpaque(entry)->set; - } - if (!x509_marshal_name_entry(&rdn, entry, canonicalize)) { - return 0; - } - } - - return CBB_flush_asn1_set_of(&rdn) && CBB_flush(out); -} - const X509NameCache *bssl::x509_name_get_cache(const X509_NAME *name) { auto *impl = FromOpaque(name); const X509NameCache *cache = impl->cache.load(); @@ -197,6 +268,9 @@ const X509NameCache *bssl::x509_name_get_cache(const X509_NAME *name) { } UniquePtr new_cache = MakeUnique(); + if (new_cache == nullptr) { + return nullptr; + } // Cache the DER encoding, including the outer TLV. ScopedCBB cbb; CBB seq; @@ -307,76 +381,6 @@ IMPLEMENT_EXTERN_ASN1_PARSE_INTO(X509_NAME, X509_NAME_new, X509_NAME_free, CBS_ASN1_SEQUENCE, x509_parse_name, x509_marshal_name) -static int asn1_marshal_string_canon(CBB *cbb, const ASN1_STRING *in) { - int (*decode_func)(CBS *, uint32_t *); - int error; - switch (in->type) { - case V_ASN1_UTF8STRING: - decode_func = CBS_get_utf8; - error = ASN1_R_INVALID_UTF8STRING; - break; - case V_ASN1_BMPSTRING: - decode_func = CBS_get_ucs2_be; - error = ASN1_R_INVALID_BMPSTRING; - break; - case V_ASN1_UNIVERSALSTRING: - decode_func = CBS_get_utf32_be; - error = ASN1_R_INVALID_UNIVERSALSTRING; - break; - case V_ASN1_PRINTABLESTRING: - case V_ASN1_T61STRING: - case V_ASN1_IA5STRING: - case V_ASN1_VISIBLESTRING: - decode_func = CBS_get_latin1; - error = ERR_R_INTERNAL_ERROR; // Latin-1 inputs are never invalid. - break; - default: - // Other string types are not canonicalized. - return asn1_marshal_any_string(cbb, in); - } - - CBB child; - if (!CBB_add_asn1(cbb, &child, CBS_ASN1_UTF8STRING)) { - return 0; - } - - bool empty = true; - bool in_whitespace = false; - CBS cbs; - CBS_init(&cbs, in->data, in->length); - while (CBS_len(&cbs) != 0) { - uint32_t c; - if (!decode_func(&cbs, &c)) { - OPENSSL_PUT_ERROR(ASN1, error); - return 0; - } - if (OPENSSL_isspace(c)) { - if (empty) { - continue; // Trim leading whitespace. - } - in_whitespace = true; - } else { - if (in_whitespace) { - // Collapse the previous run of whitespace into one space. - if (!CBB_add_u8(&child, ' ')) { - return 0; - } - } - in_whitespace = false; - // Lowecase ASCII codepoints. - if (c <= 0x7f) { - c = OPENSSL_tolower(c); - } - if (!CBB_add_utf8(&child, c)) { - return 0; - } - empty = false; - } - } - - return CBB_flush(cbb); -} - int X509_NAME_set(X509_NAME **xn, const X509_NAME *name) { UniquePtr copy(X509_NAME_dup(name)); if (copy == nullptr) { diff --git a/third_party/boringssl/src/crypto/x509/x_pubkey.cc b/third_party/boringssl/src/crypto/x509/x_pubkey.cc index 4862f1f..7cce8af 100644 --- a/third_party/boringssl/src/crypto/x509/x_pubkey.cc +++ b/third_party/boringssl/src/crypto/x509/x_pubkey.cc @@ -37,12 +37,10 @@ using namespace bssl; -X509_PUBKEY *X509_PUBKEY_new() { return New(); } - -void X509_PUBKEY_free(X509_PUBKEY *key) { Delete(FromOpaque(key)); } +namespace { -static void x509_pubkey_changed(X509Pubkey *pub, - Span algs) { +void x509_pubkey_changed(X509Pubkey *pub, + Span algs) { pub->pkey = nullptr; // Re-encode the `X509_PUBKEY` to DER and parse it with EVP's APIs. If the @@ -63,6 +61,16 @@ static void x509_pubkey_changed(X509Pubkey *pub, pub->pkey = std::move(pkey); } +int x509_parse_public_key_default(CBS *cbs, X509_PUBKEY *out) { + return x509_parse_public_key(cbs, FromOpaque(out), GetDefaultEVPAlgorithms()); +} + +} // namespace + +X509_PUBKEY *X509_PUBKEY_new() { return New(); } + +void X509_PUBKEY_free(X509_PUBKEY *key) { Delete(FromOpaque(key)); } + int bssl::x509_parse_public_key(CBS *cbs, X509_PUBKEY *out, Span algs) { auto *out_impl = FromOpaque(out); @@ -78,10 +86,6 @@ int bssl::x509_parse_public_key(CBS *cbs, X509_PUBKEY *out, return 1; } -static int x509_parse_public_key_default(CBS *cbs, X509_PUBKEY *out) { - return x509_parse_public_key(cbs, FromOpaque(out), GetDefaultEVPAlgorithms()); -} - int bssl::x509_marshal_public_key(CBB *cbb, const X509_PUBKEY *in) { auto *in_impl = FromOpaque(in); CBB seq; @@ -118,7 +122,7 @@ IMPLEMENT_EXTERN_ASN1_PARSE_INTO(X509_PUBKEY, X509_PUBKEY_new, X509_PUBKEY_free, BSSL_NAMESPACE_END -int bssl::x509_pubkey_set1(X509_PUBKEY *key, EVP_PKEY *pkey) { +int bssl::x509_pubkey_set1(X509_PUBKEY *key, const EVP_PKEY *pkey) { ScopedCBB cbb; if (!CBB_init(cbb.get(), 64) || !EVP_marshal_public_key(cbb.get(), pkey)) { OPENSSL_PUT_ERROR(X509, X509_R_PUBLIC_KEY_ENCODE_ERROR); @@ -133,7 +137,7 @@ int bssl::x509_pubkey_set1(X509_PUBKEY *key, EVP_PKEY *pkey) { return x509_parse_public_key(&cbs, key, GetDefaultEVPAlgorithms()); } -int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey) { +int X509_PUBKEY_set(X509_PUBKEY **x, const EVP_PKEY *pkey) { UniquePtr new_key(X509_PUBKEY_new()); if (new_key == nullptr || !x509_pubkey_set1(FromOpaque(new_key.get()), pkey)) { diff --git a/third_party/boringssl/src/crypto/x509/x_req.cc b/third_party/boringssl/src/crypto/x509/x_req.cc index 31fb09f..92f1e7e 100644 --- a/third_party/boringssl/src/crypto/x509/x_req.cc +++ b/third_party/boringssl/src/crypto/x509/x_req.cc @@ -23,15 +23,16 @@ using namespace bssl; +namespace { + // X509_REQ_INFO is handled in an unusual way to get round invalid encodings. // Some broken certificate requests don't encode the attributes field if it // is empty. This is in violation of PKCS#10 but we need to tolerate it. We // do this by making the attributes field OPTIONAL then using the callback to // initialise it to an empty STACK. This means that the field will be // correctly encoded unless we NULL out the field. - -static int rinf_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, - void *exarg) { +int rinf_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, + void *exarg) { X509_REQ_INFO *rinf = asn1_load_ptr_as(pval); if (operation == ASN1_OP_NEW_POST) { @@ -55,6 +56,8 @@ static int rinf_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, return 1; } +} // namespace + BSSL_NAMESPACE_BEGIN ASN1_SEQUENCE_enc(X509_REQ_INFO, enc, rinf_cb) = { diff --git a/third_party/boringssl/src/crypto/x509/x_x509.cc b/third_party/boringssl/src/crypto/x509/x_x509.cc index 413c40f..f7d82ad 100644 --- a/third_party/boringssl/src/crypto/x509/x_x509.cc +++ b/third_party/boringssl/src/crypto/x509/x_x509.cc @@ -35,15 +35,76 @@ using namespace bssl; -static ExDataClass g_ex_data_class; +namespace { -static constexpr CBS_ASN1_TAG kVersionTag = +ExDataClass g_ex_data_class; + +constexpr CBS_ASN1_TAG kVersionTag = CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0; -static constexpr CBS_ASN1_TAG kIssuerUIDTag = CBS_ASN1_CONTEXT_SPECIFIC | 1; -static constexpr CBS_ASN1_TAG kSubjectUIDTag = CBS_ASN1_CONTEXT_SPECIFIC | 2; -static constexpr CBS_ASN1_TAG kExtensionsTag = +constexpr CBS_ASN1_TAG kIssuerUIDTag = CBS_ASN1_CONTEXT_SPECIFIC | 1; +constexpr CBS_ASN1_TAG kSubjectUIDTag = CBS_ASN1_CONTEXT_SPECIFIC | 2; +constexpr CBS_ASN1_TAG kExtensionsTag = CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 3; +UniquePtr x509_parse(CBS *cbs) { + CBS cert; + if (!CBS_get_asn1_element(cbs, &cert, CBS_ASN1_SEQUENCE)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return nullptr; + } + + UniquePtr buf(CRYPTO_BUFFER_new_from_CBS(&cert, nullptr)); + if (buf == nullptr) { + return nullptr; + } + return UniquePtr(X509_parse_from_buffer(buf.get())); +} + +int x509_marshal(CBB *cbb, const X509 *x509) { + CBB cert; + auto *impl = FromOpaque(x509); + return CBB_add_asn1(cbb, &cert, CBS_ASN1_SEQUENCE) && + x509_marshal_tbs_cert(&cert, x509) && + x509_marshal_algorithm(&cert, impl->sig_alg.get()) && + asn1_marshal_bit_string(&cert, impl->signature.get(), /*tag=*/0) && + CBB_flush(cbb); +} + +// Serialize trusted certificate to *pp or just return the required buffer +// length if pp == NULL. We ultimately want to avoid modifying *pp in the +// error path, but that depends on similar hygiene in lower-level functions. +// Here we avoid compounding the problem. +int i2d_x509_aux_internal(const X509 *a, unsigned char **pp) { + int length, tmplen; + unsigned char *start = pp != nullptr ? *pp : nullptr; + + assert(pp == nullptr || *pp != nullptr); + + // This might perturb *pp on error, but fixing that belongs in i2d_X509() + // not here. It should be that if a == NULL length is zero, but we check + // both just in case. + length = i2d_X509(a, pp); + if (length <= 0 || a == nullptr) { + return length; + } + + auto *impl = FromOpaque(a); + if (impl->aux != nullptr) { + tmplen = i2d_X509_CERT_AUX(impl->aux, pp); + if (tmplen < 0) { + if (start != nullptr) { + *pp = start; + } + return tmplen; + } + length += tmplen; + } + + return length; +} + +} // namespace + X509Impl::X509Impl() : RefCounted(CheckSubClass()) { CRYPTO_new_ex_data(&ex_data); } @@ -65,7 +126,7 @@ void X509_free(X509 *x509) { impl->DecRefInternal(); } -X509 *X509_parse_with_algorithms(CRYPTO_BUFFER *buf, +X509 *X509_parse_with_algorithms(const CRYPTO_BUFFER *buf, const EVP_PKEY_ALG *const *algs, size_t num_algs) { UniquePtr ret(FromOpaque(X509_new())); @@ -179,25 +240,11 @@ X509 *X509_parse_with_algorithms(CRYPTO_BUFFER *buf, return ret.release(); } -X509 *X509_parse_from_buffer(CRYPTO_BUFFER *buf) { +X509 *X509_parse_from_buffer(const CRYPTO_BUFFER *buf) { auto algs = GetDefaultEVPAlgorithms(); return X509_parse_with_algorithms(buf, algs.data(), algs.size()); } -static UniquePtr x509_parse(CBS *cbs) { - CBS cert; - if (!CBS_get_asn1_element(cbs, &cert, CBS_ASN1_SEQUENCE)) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); - return nullptr; - } - - UniquePtr buf(CRYPTO_BUFFER_new_from_CBS(&cert, nullptr)); - if (buf == nullptr) { - return nullptr; - } - return UniquePtr(X509_parse_from_buffer(buf.get())); -} - int bssl::x509_marshal_tbs_cert(CBB *cbb, const X509 *x509) { auto *impl = FromOpaque(x509); if (impl->buf != nullptr) { @@ -280,16 +327,6 @@ int bssl::x509_get_or_marshal_tbs_cert(CBS *out, Array *scratch, return 1; } -static int x509_marshal(CBB *cbb, const X509 *x509) { - CBB cert; - auto *impl = FromOpaque(x509); - return CBB_add_asn1(cbb, &cert, CBS_ASN1_SEQUENCE) && - x509_marshal_tbs_cert(&cert, x509) && - x509_marshal_algorithm(&cert, impl->sig_alg.get()) && - asn1_marshal_bit_string(&cert, impl->signature.get(), /*tag=*/0) && - CBB_flush(cbb); -} - X509 *d2i_X509(X509 **out, const uint8_t **inp, long len) { return D2IFromCBS(out, inp, len, x509_parse); } @@ -328,10 +365,10 @@ int X509_up_ref(X509 *x) { } X509 *X509_dup_ref(const X509 *x) { - auto *x_ref = const_cast(x); - // We know that this call always returns one. - X509_up_ref(x_ref); - return x_ref; + if (x == nullptr) { + return nullptr; + } + return FromOpaque(x)->DupRefInternal(); } int X509_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused, @@ -387,39 +424,6 @@ X509 *d2i_X509_AUX(X509 **a, const unsigned char **pp, long length) { return nullptr; } -// Serialize trusted certificate to *pp or just return the required buffer -// length if pp == NULL. We ultimately want to avoid modifying *pp in the -// error path, but that depends on similar hygiene in lower-level functions. -// Here we avoid compounding the problem. -static int i2d_x509_aux_internal(const X509 *a, unsigned char **pp) { - int length, tmplen; - unsigned char *start = pp != nullptr ? *pp : nullptr; - - assert(pp == nullptr || *pp != nullptr); - - // This might perturb *pp on error, but fixing that belongs in i2d_X509() - // not here. It should be that if a == NULL length is zero, but we check - // both just in case. - length = i2d_X509(a, pp); - if (length <= 0 || a == nullptr) { - return length; - } - - auto *impl = FromOpaque(a); - if (impl->aux != nullptr) { - tmplen = i2d_X509_CERT_AUX(impl->aux, pp); - if (tmplen < 0) { - if (start != nullptr) { - *pp = start; - } - return tmplen; - } - length += tmplen; - } - - return length; -} - // Serialize trusted certificate to *pp, or just return the required buffer // length if pp == NULL. // diff --git a/third_party/boringssl/src/crypto/x509/x_x509a.cc b/third_party/boringssl/src/crypto/x509/x_x509a.cc index 5e6030c..bc32624 100644 --- a/third_party/boringssl/src/crypto/x509/x_x509a.cc +++ b/third_party/boringssl/src/crypto/x509/x_x509a.cc @@ -44,7 +44,9 @@ IMPLEMENT_ASN1_FUNCTIONS_const(X509_CERT_AUX) BSSL_NAMESPACE_END -static X509_CERT_AUX *aux_get(X509Impl *x) { +namespace { + +X509_CERT_AUX *aux_get(X509Impl *x) { if (!x) { return nullptr; } @@ -54,6 +56,8 @@ static X509_CERT_AUX *aux_get(X509Impl *x) { return x->aux; } +} // namespace + int X509_alias_set1(X509 *x, const uint8_t *name, ossl_ssize_t len) { auto *impl = FromOpaque(x); X509_CERT_AUX *aux; diff --git a/third_party/boringssl/src/gen/crypto/err_data.cc b/third_party/boringssl/src/gen/crypto/err_data.cc index 9e0884a..b365a54 100644 --- a/third_party/boringssl/src/gen/crypto/err_data.cc +++ b/third_party/boringssl/src/gen/crypto/err_data.cc @@ -207,53 +207,53 @@ const uint32_t kOpenSSLReasonValues[] = { 0x283500f7, 0x28358cc1, 0x2836099a, - 0x2c323524, + 0x2c32353c, 0x2c32945a, - 0x2c333532, - 0x2c33b544, - 0x2c343558, - 0x2c34b56a, - 0x2c353585, - 0x2c35b597, - 0x2c3635c7, + 0x2c33354a, + 0x2c33b55c, + 0x2c343570, + 0x2c34b582, + 0x2c35359d, + 0x2c35b5af, + 0x2c3635df, 0x2c36833a, - 0x2c3735d4, - 0x2c37b600, - 0x2c38365f, - 0x2c38b676, - 0x2c393694, - 0x2c39b6a4, - 0x2c3a36b6, - 0x2c3ab6ca, - 0x2c3b36db, - 0x2c3bb6fa, + 0x2c3735ec, + 0x2c37b618, + 0x2c383677, + 0x2c38b68e, + 0x2c3936ac, + 0x2c39b6bc, + 0x2c3a36ce, + 0x2c3ab6e2, + 0x2c3b36f3, + 0x2c3bb712, 0x2c3c146c, 0x2c3c9482, - 0x2c3d373f, + 0x2c3d3757, 0x2c3d949b, - 0x2c3e3769, - 0x2c3eb777, - 0x2c3f378f, - 0x2c3fb7a7, - 0x2c4037d1, + 0x2c3e3781, + 0x2c3eb78f, + 0x2c3f37a7, + 0x2c3fb7bf, + 0x2c4037e9, 0x2c409347, - 0x2c4137e2, - 0x2c41b7f5, + 0x2c4137fa, + 0x2c41b80d, 0x2c42130d, - 0x2c42b806, + 0x2c42b81e, 0x2c43076d, - 0x2c43b6ec, - 0x2c443634, - 0x2c44b7b4, - 0x2c4535aa, - 0x2c45b5e6, - 0x2c463684, - 0x2c46b70e, - 0x2c473723, - 0x2c47b75c, - 0x2c483646, - 0x2c48b613, - 0x2c493622, + 0x2c43b704, + 0x2c44364c, + 0x2c44b7cc, + 0x2c4535c2, + 0x2c45b5fe, + 0x2c46369c, + 0x2c46b726, + 0x2c47373b, + 0x2c47b774, + 0x2c48365e, + 0x2c48b62b, + 0x2c49363a, 0x30320000, 0x30328015, 0x3033001f, @@ -455,154 +455,154 @@ const uint32_t kOpenSSLReasonValues[] = { 0x404fa30c, 0x405023c8, 0x4050a3dc, - 0x40512429, - 0x40522439, - 0x4052a469, - 0x40532481, - 0x4053a494, - 0x405424a9, - 0x4054a4cc, - 0x405524f7, - 0x4055a534, - 0x40562559, - 0x4056a572, - 0x4057258a, - 0x4057a59d, - 0x405825b2, - 0x4058a5d9, - 0x40592608, - 0x4059a648, - 0x405aa65c, - 0x405b2674, - 0x405ba685, - 0x405c2698, - 0x405ca6ed, - 0x405d26fa, - 0x405da71f, - 0x405e275d, + 0x40512441, + 0x40522451, + 0x4052a481, + 0x40532499, + 0x4053a4ac, + 0x405424c1, + 0x4054a4e4, + 0x4055250f, + 0x4055a54c, + 0x40562571, + 0x4056a58a, + 0x405725a2, + 0x4057a5b5, + 0x405825ca, + 0x4058a5f1, + 0x40592620, + 0x4059a660, + 0x405aa674, + 0x405b268c, + 0x405ba69d, + 0x405c26b0, + 0x405ca705, + 0x405d2712, + 0x405da737, + 0x405e2775, 0x405e8afe, - 0x405f278d, - 0x405fa79a, - 0x406027a8, - 0x4060a7ca, - 0x4061283e, - 0x4061a876, - 0x4062288d, - 0x4062a89e, - 0x406328eb, - 0x4063a900, - 0x40642917, - 0x4064a943, - 0x4065295e, - 0x4065a975, - 0x4066298d, - 0x4066a9b7, - 0x406729e2, - 0x4067aa27, - 0x40682a6f, - 0x4068aa90, - 0x40692ac2, - 0x4069aaf0, - 0x406a2b11, - 0x406aab31, - 0x406b2cb9, - 0x406bacdc, - 0x406c2cf2, - 0x406caffc, - 0x406d302b, - 0x406db053, - 0x406e3081, - 0x406eb0ce, - 0x406f3127, - 0x406fb15f, - 0x40703172, - 0x4070b18f, + 0x405f27a5, + 0x405fa7b2, + 0x406027c0, + 0x4060a7e2, + 0x40612856, + 0x4061a88e, + 0x406228a5, + 0x4062a8b6, + 0x40632903, + 0x4063a918, + 0x4064292f, + 0x4064a95b, + 0x40652976, + 0x4065a98d, + 0x406629a5, + 0x4066a9cf, + 0x406729fa, + 0x4067aa3f, + 0x40682a87, + 0x4068aaa8, + 0x40692ada, + 0x4069ab08, + 0x406a2b29, + 0x406aab49, + 0x406b2cd1, + 0x406bacf4, + 0x406c2d0a, + 0x406cb014, + 0x406d3043, + 0x406db06b, + 0x406e3099, + 0x406eb0e6, + 0x406f313f, + 0x406fb177, + 0x4070318a, + 0x4070b1a7, 0x4071084d, - 0x4071b1a1, - 0x407231b4, - 0x4072b1ea, - 0x40733202, + 0x4071b1b9, + 0x407231cc, + 0x4072b202, + 0x4073321a, 0x40739684, - 0x40743216, - 0x4074b230, - 0x40753241, - 0x4075b255, - 0x40763263, + 0x4074322e, + 0x4074b248, + 0x40753259, + 0x4075b26d, + 0x4076327b, 0x4076940a, - 0x407732a0, - 0x4077b2fc, - 0x40783317, - 0x4078b369, - 0x40793380, - 0x4079b396, - 0x407a33c2, - 0x407ab3d5, - 0x407b33ea, - 0x407bb3fc, - 0x407c342d, - 0x407cb436, - 0x407d2aab, + 0x407732b8, + 0x4077b314, + 0x4078332f, + 0x4078b381, + 0x40793398, + 0x4079b3ae, + 0x407a33da, + 0x407ab3ed, + 0x407b3402, + 0x407bb414, + 0x407c3445, + 0x407cb44e, + 0x407d2ac3, 0x407da334, - 0x407e332c, - 0x407ea5e9, + 0x407e3344, + 0x407ea601, 0x407f1ee9, 0x407fa0dd, 0x408022a6, 0x40809f22, - 0x40812457, + 0x4081246f, 0x4081a1e4, - 0x4082306c, + 0x40823084, 0x40829c64, - 0x408325c4, - 0x4083a928, + 0x408325dc, + 0x4083a940, 0x40841f46, - 0x4084a621, - 0x408526a9, - 0x4085a805, - 0x4086273f, + 0x4084a639, + 0x408526c1, + 0x4085a81d, + 0x40862757, 0x4086a380, - 0x408730b2, - 0x4087a853, + 0x408730ca, + 0x4087a86b, 0x40881ca2, - 0x4088aa3a, + 0x4088aa52, 0x40891cf1, 0x40899c7e, - 0x408a2d2a, + 0x408a2d42, 0x408a9a9c, - 0x408b3411, - 0x408bb13c, - 0x408c26cf, + 0x408b3429, + 0x408bb154, + 0x408c26e7, 0x408d202e, 0x408d9f78, 0x408e215e, - 0x408ea514, - 0x408f2a4e, - 0x408fa821, - 0x40902a03, - 0x4090a711, - 0x40912d12, + 0x408ea52c, + 0x408f2a66, + 0x408fa839, + 0x40902a1b, + 0x4090a729, + 0x40912d2a, 0x40919ad4, 0x40921d3e, - 0x4092b0ed, - 0x409331cd, + 0x4092b105, + 0x409331e5, 0x4093a391, 0x40941f5a, - 0x4094ad43, - 0x409528af, - 0x4095b3a2, - 0x40963099, + 0x4094ad5b, + 0x409528c7, + 0x4095b3ba, + 0x409630b1, 0x4096a2bf, - 0x40972411, + 0x40972429, 0x4097a1ad, 0x40981d9e, - 0x4098a8c3, - 0x40993109, - 0x4099a541, - 0x409a24da, + 0x4098a8db, + 0x40993121, + 0x4099a559, + 0x409a24f2, 0x409a9ab8, 0x409b1fb4, 0x409b9fdf, - 0x409c32de, + 0x409c32f6, 0x409ca007, 0x409d227b, 0x409da1fa, @@ -613,57 +613,58 @@ const uint32_t kOpenSSLReasonValues[] = { 0x40a0231c, 0x40a0a1c7, 0x40a12215, - 0x40a1a635, + 0x40a1a64d, 0x40a223ad, - 0x40a2a77e, - 0x40a327f2, - 0x40a3b2c2, - 0x40a423f7, + 0x40a2a796, + 0x40a3280a, + 0x40a3b2da, + 0x40a4240f, 0x40a4a22c, 0x40a51f36, 0x40a5a34e, - 0x40a626b9, + 0x40a626d1, 0x40a6a24e, - 0x40a73288, - 0x40a7a44b, + 0x40a732a0, + 0x40a7a463, 0x40a82369, - 0x40a8b350, + 0x40a8b368, 0x40a92266, 0x40a99f11, - 0x41f42be4, - 0x41f92c76, - 0x41fe2b69, - 0x41feae1f, - 0x41ff2f4d, - 0x42032bfd, - 0x42082c1f, - 0x4208ac5b, - 0x42092b4d, - 0x4209ac95, - 0x420a2ba4, - 0x420aab84, - 0x420b2bc4, - 0x420bac3d, - 0x420c2f69, - 0x420cad53, - 0x420d2e06, - 0x420dae3d, - 0x42122e70, - 0x42172f30, - 0x4217aeb2, - 0x421c2ed4, - 0x421f2e8f, - 0x42212fe1, - 0x42262f13, - 0x422b2fbf, - 0x422bade1, - 0x422c2fa1, - 0x422cad94, - 0x422d2d6d, - 0x422daf80, - 0x422e2dc0, - 0x42302eef, - 0x4230ae57, + 0x40aa23f7, + 0x41f42bfc, + 0x41f92c8e, + 0x41fe2b81, + 0x41feae37, + 0x41ff2f65, + 0x42032c15, + 0x42082c37, + 0x4208ac73, + 0x42092b65, + 0x4209acad, + 0x420a2bbc, + 0x420aab9c, + 0x420b2bdc, + 0x420bac55, + 0x420c2f81, + 0x420cad6b, + 0x420d2e1e, + 0x420dae55, + 0x42122e88, + 0x42172f48, + 0x4217aeca, + 0x421c2eec, + 0x421f2ea7, + 0x42212ff9, + 0x42262f2b, + 0x422b2fd7, + 0x422badf9, + 0x422c2fb9, + 0x422cadac, + 0x422d2d85, + 0x422daf98, + 0x422e2dd8, + 0x42302f07, + 0x4230ae6f, 0x44320778, 0x44328787, 0x44330793, @@ -719,71 +720,71 @@ const uint32_t kOpenSSLReasonValues[] = { 0x4c419564, 0x4c4216cd, 0x4c4294ac, - 0x50323818, - 0x5032b827, - 0x50333832, - 0x5033b842, - 0x5034385b, - 0x5034b875, - 0x50353883, - 0x5035b899, - 0x503638ab, - 0x5036b8c1, - 0x503738da, - 0x5037b8ed, - 0x50383905, - 0x5038b916, - 0x5039392b, - 0x5039b93f, - 0x503a395f, - 0x503ab975, - 0x503b398d, - 0x503bb99f, - 0x503c39bb, - 0x503cb9d2, - 0x503d39eb, - 0x503dba01, - 0x503e3a0e, - 0x503eba24, - 0x503f3a36, + 0x50323830, + 0x5032b83f, + 0x5033384a, + 0x5033b85a, + 0x50343873, + 0x5034b88d, + 0x5035389b, + 0x5035b8b1, + 0x503638c3, + 0x5036b8d9, + 0x503738f2, + 0x5037b905, + 0x5038391d, + 0x5038b92e, + 0x50393943, + 0x5039b957, + 0x503a3977, + 0x503ab98d, + 0x503b39a5, + 0x503bb9b7, + 0x503c39d3, + 0x503cb9ea, + 0x503d3a03, + 0x503dba19, + 0x503e3a26, + 0x503eba3c, + 0x503f3a4e, 0x503f83b3, - 0x50403a49, - 0x5040ba59, - 0x50413a73, - 0x5041ba82, - 0x50423a9c, - 0x5042bab9, - 0x50433ac9, - 0x5043bad9, - 0x50443af6, + 0x50403a61, + 0x5040ba71, + 0x50413a8b, + 0x5041ba9a, + 0x50423ab4, + 0x5042bad1, + 0x50433ae1, + 0x5043baf1, + 0x50443b0e, 0x50448469, - 0x50453b0a, - 0x5045bb28, - 0x50463b3b, - 0x5046bb51, - 0x50473b63, - 0x5047bb78, - 0x50483b9e, - 0x5048bbac, - 0x50493bbf, - 0x5049bbd4, - 0x504a3bea, - 0x504abbfa, - 0x504b3c1a, - 0x504bbc2d, - 0x504c3c50, - 0x504cbc7e, - 0x504d3cab, - 0x504dbcc8, - 0x504e3ce3, - 0x504ebcff, - 0x504f3d11, - 0x504fbd28, - 0x50503d37, + 0x50453b22, + 0x5045bb40, + 0x50463b53, + 0x5046bb69, + 0x50473b7b, + 0x5047bb90, + 0x50483bb6, + 0x5048bbc4, + 0x50493bd7, + 0x5049bbec, + 0x504a3c02, + 0x504abc12, + 0x504b3c32, + 0x504bbc45, + 0x504c3c68, + 0x504cbc96, + 0x504d3cc3, + 0x504dbce0, + 0x504e3cfb, + 0x504ebd17, + 0x504f3d29, + 0x504fbd40, + 0x50503d4f, 0x50508729, - 0x50513d4a, - 0x5051bae8, - 0x50523c90, + 0x50513d62, + 0x5051bb00, + 0x50523ca8, 0x58321011, 0x68320fd3, 0x68328d2b, @@ -828,19 +829,19 @@ const uint32_t kOpenSSLReasonValues[] = { 0x7c321323, 0x80321577, 0x80328090, - 0x803334f3, + 0x8033350b, 0x803380b9, - 0x80343502, - 0x8034b46a, - 0x80353488, - 0x8035b516, - 0x803634ca, - 0x8036b479, - 0x803734bc, - 0x8037b457, - 0x803834dd, - 0x8038b499, - 0x803934ae, + 0x8034351a, + 0x8034b482, + 0x803534a0, + 0x8035b52e, + 0x803634e2, + 0x8036b491, + 0x803734d4, + 0x8037b46f, + 0x803834f5, + 0x8038b4b1, + 0x803934c6, 0x84320bb0, 0x84328bc9, }; @@ -1296,6 +1297,7 @@ const char kOpenSSLReasonStringData[] = "INVALID_SPAKE2PLUSV1_VALUE\0" "INVALID_SSL_SESSION\0" "INVALID_TICKET_KEYS_LENGTH\0" + "INVALID_TRUST_ANCHOR_ID\0" "INVALID_TRUST_ANCHOR_LIST\0" "KEY_USAGE_BIT_INCORRECT\0" "LENGTH_MISMATCH\0" diff --git a/third_party/boringssl/src/include/openssl/asn1.h b/third_party/boringssl/src/include/openssl/asn1.h index 1dae5f7..1adae57 100644 --- a/third_party/boringssl/src/include/openssl/asn1.h +++ b/third_party/boringssl/src/include/openssl/asn1.h @@ -30,13 +30,18 @@ extern "C" { // Legacy ASN.1 library. // -// This header is part of OpenSSL's ASN.1 implementation. It is retained for -// compatibility but should not be used by new code. The functions are difficult -// to use correctly, and have buggy or non-standard behaviors. They are thus -// particularly prone to behavior changes and API removals, as BoringSSL -// iterates on these issues. +// This header is part of an ASN.1 implementation derived from OpenSSL. Compared +// to other OpenSSL-derived parts of BoringSSL, it is particularly impacted by +// that legacy. Many functions are difficult to use correctly and have a number +// of known bugs or non-standard behaviors. // -// Use the new `CBS` and `CBB` library in instead. +// As BoringSSL iterates on these issues, this header will be particularly prone +// to behavior changes and API removals. In particular, avoid depending on any +// lax parsing. BoringSSL generally aims to implement strict DER parsing. +// +// For new code that does not otherwise need to interact with these types, +// prefer to use the new `CBS` and `CBB` library in +// instead. // Tag constants. @@ -90,6 +95,7 @@ extern "C" { #define V_ASN1_REAL 9 #define V_ASN1_ENUMERATED 10 #define V_ASN1_UTF8STRING 12 +#define V_ASN1_RELATIVE_OID 13 #define V_ASN1_SEQUENCE 16 #define V_ASN1_SET 17 #define V_ASN1_NUMERICSTRING 18 @@ -516,23 +522,12 @@ OPENSSL_EXPORT int ASN1_STRING_type(const ASN1_STRING *str); OPENSSL_EXPORT const unsigned char *ASN1_STRING_get0_data( const ASN1_STRING *str); -// ASN1_STRING_data returns a mutable pointer to `str`'s contents. Callers -// should use `ASN1_STRING_length` to determine the length of the string. The -// string may have embedded NUL bytes and may not be NUL-terminated. -// -// The contents of an `ASN1_STRING` encode the value in some type-specific -// representation that does not always correspond to the DER encoding of the -// type. See the documentation for `ASN1_STRING` for details. -// -// Prefer `ASN1_STRING_get0_data`. -OPENSSL_EXPORT unsigned char *ASN1_STRING_data(ASN1_STRING *str); - -// ASN1_STRING_length returns the length of `str`, in bytes. +// ASN1_STRING_get_length returns the length of `str`, in bytes. // // The contents of an `ASN1_STRING` encode the value in some type-specific // representation that does not always correspond to the DER encoding of the // type. See the documentation for `ASN1_STRING` for details. -OPENSSL_EXPORT int ASN1_STRING_length(const ASN1_STRING *str); +OPENSSL_EXPORT size_t ASN1_STRING_get_length(const ASN1_STRING *str); // ASN1_STRING_cmp compares `a` and `b`'s type and contents. It returns an // integer equal to, less than, or greater than zero if `a` is equal to, less @@ -546,14 +541,16 @@ OPENSSL_EXPORT int ASN1_STRING_length(const ASN1_STRING *str); // values numerically. For a numerical comparison, use `ASN1_INTEGER_cmp`. OPENSSL_EXPORT int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b); -// ASN1_STRING_set sets the contents of `str` to a copy of `len` bytes from -// `data`. It returns one on success and zero on error. If `data` is NULL, it -// updates the length and allocates the buffer as needed, but does not -// initialize the contents. +// ASN1_STRING_set1_data sets the contents of `str` to `len` bytes from `data`. // // If `str` is a BIT STRING, this function sets the number of unused bits to // zero. `ASN1_BIT_STRING_set1` may be used to set a BIT STRING that is not a // whole number of bytes. +OPENSSL_EXPORT int ASN1_STRING_set1_data(ASN1_STRING *str, const uint8_t *data, + size_t len); + +// ASN1_STRING_set behaves like `ASN1_STRING_set1_data` except that, if `len` is +// negative, it implicitly calls `strlen` on data to determine the length. OPENSSL_EXPORT int ASN1_STRING_set(ASN1_STRING *str, const void *data, ossl_ssize_t len); @@ -1127,9 +1124,6 @@ OPENSSL_EXPORT void ASN1_UTCTIME_free(ASN1_UTCTIME *str); // d2i_ASN1_UTCTIME parses up to `len` bytes from `*inp` as a DER-encoded // ASN.1 UTCTime, as described in `d2i_SAMPLE`. -// -// TODO(https://crbug.com/boringssl/354): This function currently also accepts -// BER, but this will be removed in the future. OPENSSL_EXPORT ASN1_UTCTIME *d2i_ASN1_UTCTIME(ASN1_UTCTIME **out, const uint8_t **inp, long len); @@ -1236,9 +1230,6 @@ OPENSSL_EXPORT void ASN1_TIME_free(ASN1_TIME *str); // d2i_ASN1_TIME parses up to `len` bytes from `*inp` as a DER-encoded X.509 // Time (RFC 5280), as described in `d2i_SAMPLE`. -// -// TODO(https://crbug.com/boringssl/354): This function currently also accepts -// BER, but this will be removed in the future. OPENSSL_EXPORT ASN1_TIME *d2i_ASN1_TIME(ASN1_TIME **out, const uint8_t **inp, long len); @@ -1522,9 +1513,11 @@ OPENSSL_EXPORT void ASN1_TYPE_set(ASN1_TYPE *a, int type, void *value); // of `value`. It returns one on success and zero on error. OPENSSL_EXPORT int ASN1_TYPE_set1(ASN1_TYPE *a, int type, const void *value); -// ASN1_TYPE_cmp returns zero if `a` and `b` are equal and some non-zero value -// otherwise. Note this function can only be used for equality checks, not an -// ordering. +// ASN1_TYPE_cmp compares `a` and `b`. It returns zero if they are equal, and a +// negative or positive value if `a` sorts before or after `b`, respectively. +// NULL sorts before any non-NULL value. Otherwise, values are ordered first by +// type, then by contents. The order is arbitrary but suitable for sorting. +// Callers should not rely on the exact order. OPENSSL_EXPORT int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b); typedef STACK_OF(ASN1_TYPE) ASN1_SEQUENCE_ANY; @@ -1809,6 +1802,25 @@ OPENSSL_EXPORT unsigned long ASN1_STRING_get_default_mask(void); // ASN1_STRING_TABLE_cleanup does nothing. OPENSSL_EXPORT void ASN1_STRING_TABLE_cleanup(void); +// ASN1_STRING_data returns a mutable pointer to `str`'s contents. Callers +// should use `ASN1_STRING_length` to determine the length of the string. The +// string may have embedded NUL bytes and may not be NUL-terminated. +// +// The contents of an `ASN1_STRING` encode the value in some type-specific +// representation that does not always correspond to the DER encoding of the +// type. See the documentation for `ASN1_STRING` for details. +// +// Prefer `ASN1_STRING_get0_data`. See crbug.com/574019297. +OPENSSL_EXPORT unsigned char *ASN1_STRING_data(ASN1_STRING *str); + +// ASN1_STRING_length returns the length of `str`, in bytes. Prefer +// `ASN1_STRING_get_length`. +// +// The contents of an `ASN1_STRING` encode the value in some type-specific +// representation that does not always correspond to the DER encoding of the +// type. See the documentation for `ASN1_STRING` for details. +OPENSSL_EXPORT int ASN1_STRING_length(const ASN1_STRING *str); + // M_ASN1_* are legacy aliases for various `ASN1_STRING` functions. Use the // functions themselves. #define M_ASN1_STRING_length(x) ASN1_STRING_length(x) diff --git a/third_party/boringssl/src/include/openssl/base.h b/third_party/boringssl/src/include/openssl/base.h index 83cc91b..39afcde 100644 --- a/third_party/boringssl/src/include/openssl/base.h +++ b/third_party/boringssl/src/include/openssl/base.h @@ -73,7 +73,7 @@ extern "C" { // A consumer may use this symbol in the preprocessor to temporarily build // against multiple revisions of BoringSSL at the same time. It is not // recommended to do so for longer than is necessary. -#define BORINGSSL_API_VERSION 43 +#define BORINGSSL_API_VERSION 45 #if defined(BORINGSSL_SHARED_LIBRARY) @@ -287,6 +287,7 @@ typedef struct cbs_st CBS; typedef struct cmac_ctx_st CMAC_CTX; typedef struct conf_st CONF; typedef struct conf_value_st CONF_VALUE; +typedef struct cpace_ctx_st CPACE_CTX; typedef struct crypto_buffer_pool_st CRYPTO_BUFFER_POOL; typedef struct crypto_buffer_st CRYPTO_BUFFER; typedef struct crypto_ivec_st CRYPTO_IVEC; @@ -379,6 +380,7 @@ typedef void *OPENSSL_BLOCK; #define BORINGSSL_NO_CXX #endif +// clang-format off #if defined(BORINGSSL_PREFIX) #define BSSL_NAMESPACE_BEGIN \ namespace bssl { \ @@ -390,11 +392,12 @@ typedef void *OPENSSL_BLOCK; #define BSSL_NAMESPACE_BEGIN namespace bssl { #define BSSL_NAMESPACE_END } #endif +// clang-format on #if defined(BORINGSSL_NO_CXX) #define BORINGSSL_MAKE_DELETER(type, deleter) -#define BORINGSSL_MAKE_UP_REF(type, up_ref_func) +#define BORINGSSL_MAKE_UP_REF(type, dup_ref_func) #define BORINGSSL_MAKE_STACK_TRAITS(type, init_func, cleanup_func) #define BORINGSSL_MAKE_STACK_TRAITS_MOVABLE(type, init_func, cleanup_func, \ move_func) @@ -494,30 +497,36 @@ class StackAllocatedMovable { #define BORINGSSL_MAKE_DELETER(type, deleter) \ namespace internal { \ + \ template <> \ struct DeleterImpl { \ static void Free(type *ptr) { deleter(ptr); } \ }; \ + \ } #define BORINGSSL_MAKE_STACK_TRAITS(type, init_func, cleanup_func) \ namespace internal { \ + \ template <> \ struct StackAllocatedTraits { \ static void Init(type *ptr) { init_func(ptr); } \ static void Cleanup(type *ptr) { cleanup_func(ptr); } \ }; \ + \ } #define BORINGSSL_MAKE_STACK_TRAITS_MOVABLE(type, init_func, cleanup_func, \ move_func) \ namespace internal { \ + \ template <> \ struct StackAllocatedMovableTraits { \ static void Init(type *ptr) { init_func(ptr); } \ static void Cleanup(type *ptr) { cleanup_func(ptr); } \ static void Move(type *out, type *in) { move_func(out, in); } \ }; \ + \ } // Holds ownership of heap-allocated BoringSSL structures. Sample usage: @@ -526,12 +535,9 @@ class StackAllocatedMovable { template using UniquePtr = std::unique_ptr; -#define BORINGSSL_MAKE_UP_REF(type, up_ref_func) \ - inline UniquePtr UpRef(type *v) { \ - if (v != nullptr) { \ - up_ref_func(v); \ - } \ - return UniquePtr(v); \ +#define BORINGSSL_MAKE_UP_REF(type, dup_ref_func) \ + inline UniquePtr UpRef(const type *v) { \ + return UniquePtr(dup_ref_func(v)); \ } \ \ inline UniquePtr UpRef(const UniquePtr &ptr) { \ diff --git a/third_party/boringssl/src/include/openssl/base64.h b/third_party/boringssl/src/include/openssl/base64.h index 752cb93..c693c2f 100644 --- a/third_party/boringssl/src/include/openssl/base64.h +++ b/third_party/boringssl/src/include/openssl/base64.h @@ -126,8 +126,7 @@ OPENSSL_EXPORT int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, uint8_t *out, // `dst`. It returns the number of bytes written or -1 on error. // // WARNING: EVP_DecodeBlock's return value does not take padding into -// account. It also strips leading whitespace and trailing -// whitespace and minuses. +// account. It also strips leading spaces and tabs, and trailing whitespace. OPENSSL_EXPORT int EVP_DecodeBlock(uint8_t *dst, const uint8_t *src, size_t src_len); diff --git a/third_party/boringssl/src/include/openssl/bio.h b/third_party/boringssl/src/include/openssl/bio.h index 630be3e..d3978eb 100644 --- a/third_party/boringssl/src/include/openssl/bio.h +++ b/third_party/boringssl/src/include/openssl/bio.h @@ -15,7 +15,7 @@ #ifndef OPENSSL_HEADER_BIO_H #define OPENSSL_HEADER_BIO_H -#include // IWYU pragma: export +#include // IWYU pragma: export #include // For FILE @@ -65,6 +65,10 @@ OPENSSL_EXPORT void BIO_vfree(BIO *bio); // BIO_up_ref increments the reference count of `bio` and returns one. OPENSSL_EXPORT int BIO_up_ref(BIO *bio); +// BIO_dup_ref increments the reference count of `bio` and returns the same +// handle. +OPENSSL_EXPORT BIO *BIO_dup_ref(const BIO *bio); + // Basic I/O. @@ -613,18 +617,20 @@ OPENSSL_EXPORT int BIO_do_connect(BIO *bio); #define BIO_CTRL_DGRAM_QUERY_MTU 40 // as kernel for current MTU -#define BIO_CTRL_DGRAM_SET_MTU 42 /* set cached value for MTU. want to use - this if asking the kernel fails */ +#define BIO_CTRL_DGRAM_SET_MTU \ + 42 /* set cached value for MTU. want to use \ + this if asking the kernel fails */ -#define BIO_CTRL_DGRAM_MTU_EXCEEDED 43 /* check whether the MTU was exceed in - the previous write operation. */ +#define BIO_CTRL_DGRAM_MTU_EXCEEDED \ + 43 /* check whether the MTU was exceed in \ + the previous write operation. */ // BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT is unsupported as it is unused by consumers // and depends on `timeval`, which is not 2038-clean on all platforms. -#define BIO_CTRL_DGRAM_GET_PEER 46 +#define BIO_CTRL_DGRAM_GET_PEER 46 -#define BIO_CTRL_DGRAM_GET_FALLBACK_MTU 47 +#define BIO_CTRL_DGRAM_GET_FALLBACK_MTU 47 // BIO Pairs. @@ -859,7 +865,8 @@ typedef BIO_info_cb bio_info_cb; // it, and decodes data read from it. `BIO_gets` is not supported. Call // `BIO_flush` when done writing, to signal that no more data are to be // encoded. The flag `BIO_FLAGS_BASE64_NO_NL` may be set to encode all the data -// on one line. +// on one line. When decoding, `BIO_FLAGS_BASE64_NO_NL` disables skipping +// leading lines that are not base64. // // Use `EVP_EncodeBlock` and `EVP_DecodeBase64` instead. OPENSSL_EXPORT const BIO_METHOD *BIO_f_base64(void); @@ -1031,7 +1038,7 @@ extern "C++" { BSSL_NAMESPACE_BEGIN BORINGSSL_MAKE_DELETER(BIO, BIO_free) -BORINGSSL_MAKE_UP_REF(BIO, BIO_up_ref) +BORINGSSL_MAKE_UP_REF(BIO, BIO_dup_ref) BORINGSSL_MAKE_DELETER(BIO_METHOD, BIO_meth_free) BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/include/openssl/bn.h b/third_party/boringssl/src/include/openssl/bn.h index dbb8376..5f34ab8 100644 --- a/third_party/boringssl/src/include/openssl/bn.h +++ b/third_party/boringssl/src/include/openssl/bn.h @@ -169,7 +169,8 @@ OPENSSL_EXPORT int BN_bn2cbb_padded(CBB *out, size_t len, const BIGNUM *in); // BN_bn2hex returns an allocated string that contains a NUL-terminated, hex // representation of `bn`. If `bn` is negative, the first char in the resulting -// string will be '-'. Returns NULL on allocation failure. +// string will be '-'. Returns NULL on allocation failure. The resulting string +// must be freed with `OPENSSL_free`. OPENSSL_EXPORT char *BN_bn2hex(const BIGNUM *bn); // BN_hex2bn parses the leading hex number from `in`, which may be proceeded by @@ -182,7 +183,8 @@ OPENSSL_EXPORT int BN_hex2bn(BIGNUM **outp, const char *in); // BN_bn2dec returns an allocated string that contains a NUL-terminated, // decimal representation of `bn`. If `bn` is negative, the first char in the -// resulting string will be '-'. Returns NULL on allocation failure. +// resulting string will be '-'. Returns NULL on allocation failure. The +// resulting string must be freed with `OPENSSL_free`. // // Converting an arbitrarily large integer to decimal is quadratic in the bit // length of `a`. This function assumes the caller has capped the input within diff --git a/third_party/boringssl/src/include/openssl/bytestring.h b/third_party/boringssl/src/include/openssl/bytestring.h index d1d607c..619a37a 100644 --- a/third_party/boringssl/src/include/openssl/bytestring.h +++ b/third_party/boringssl/src/include/openssl/bytestring.h @@ -238,6 +238,7 @@ OPENSSL_EXPORT int CBS_get_u64_decimal(CBS *cbs, uint64_t *out); #define CBS_ASN1_OBJECT 0x6u #define CBS_ASN1_ENUMERATED 0xau #define CBS_ASN1_UTF8STRING 0xcu +#define CBS_ASN1_RELATIVE_OID 0xdu #define CBS_ASN1_SEQUENCE (0x10u | CBS_ASN1_CONSTRUCTED) #define CBS_ASN1_SET (0x11u | CBS_ASN1_CONSTRUCTED) #define CBS_ASN1_NUMERICSTRING 0x12u @@ -397,6 +398,12 @@ OPENSSL_EXPORT int CBS_is_valid_asn1_integer(const CBS *cbs, // ASN.1 INTEGER body and zero otherwise. OPENSSL_EXPORT int CBS_is_unsigned_asn1_integer(const CBS *cbs); +// CBS_is_valid_asn1_set_of returns one if `cbs` is an ASN.1 SET OF contents +// (not including the element framing) with members sorted in nondescending +// order according to DER rules, and zero otherwise. This function does not +// parse the members and does not check that they are of any particular type. +OPENSSL_EXPORT int CBS_is_valid_asn1_set_of(const CBS *cbs); + // CBS_is_valid_asn1_oid returns one if `cbs` is a valid DER-encoded ASN.1 // OBJECT IDENTIFIER contents (not including the element framing) and zero // otherwise. This function tolerates arbitrarily large OID components. diff --git a/third_party/boringssl/src/include/openssl/cms.h b/third_party/boringssl/src/include/openssl/cms.h index d365a46..5a44517 100644 --- a/third_party/boringssl/src/include/openssl/cms.h +++ b/third_party/boringssl/src/include/openssl/cms.h @@ -15,7 +15,7 @@ #ifndef OPENSSL_HEADER_CMS_H #define OPENSSL_HEADER_CMS_H -#include // IWYU pragma: export +#include // IWYU pragma: export #include @@ -69,8 +69,9 @@ DECLARE_STACK_OF(X509) // incomplete. `data` will then be ignored and should be NULL. The caller can // then continue configuring it and finalizing it with `CMS_final`. Otherwise, // the object will be finalized with `data` and `flags` passed to `CMS_final`. -OPENSSL_EXPORT CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, - STACK_OF(X509) *certs, BIO *data, +OPENSSL_EXPORT CMS_ContentInfo *CMS_sign(const X509 *signcert, + const EVP_PKEY *pkey, + const STACK_OF(X509) *certs, BIO *data, uint32_t flags); // CMS_ContentInfo_free releases memory associated with `cms`. @@ -102,7 +103,8 @@ OPENSSL_EXPORT void CMS_ContentInfo_free(CMS_ContentInfo *cms); // Subsequent calls will fail. Additionally, only RSA keys are currently // supported for `pkey`. OPENSSL_EXPORT CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, - X509 *signcert, EVP_PKEY *pkey, + const X509 *signcert, + const EVP_PKEY *pkey, const EVP_MD *md, uint32_t flags); diff --git a/third_party/boringssl/src/include/openssl/curve25519.h b/third_party/boringssl/src/include/openssl/curve25519.h index f7ee156..1eac821 100644 --- a/third_party/boringssl/src/include/openssl/curve25519.h +++ b/third_party/boringssl/src/include/openssl/curve25519.h @@ -15,7 +15,8 @@ #ifndef OPENSSL_HEADER_CURVE25519_H #define OPENSSL_HEADER_CURVE25519_H -#include // IWYU pragma: export +#include // IWYU pragma: export +#include #if defined(__cplusplus) extern "C" { @@ -163,10 +164,11 @@ enum spake2_role_t { // bound into the protocol. For example MAC addresses, hostnames, usernames // etc. These values are not exposed and can avoid context-confusion attacks // when a password is shared between several devices. -OPENSSL_EXPORT SPAKE2_CTX *SPAKE2_CTX_new( - enum spake2_role_t my_role, - const uint8_t *my_name, size_t my_name_len, - const uint8_t *their_name, size_t their_name_len); +OPENSSL_EXPORT SPAKE2_CTX *SPAKE2_CTX_new(enum spake2_role_t my_role, + const uint8_t *my_name, + size_t my_name_len, + const uint8_t *their_name, + size_t their_name_len); // SPAKE2_CTX_free frees `ctx` and all the resources that it has allocated. OPENSSL_EXPORT void SPAKE2_CTX_free(SPAKE2_CTX *ctx); @@ -219,6 +221,75 @@ OPENSSL_EXPORT int SPAKE2_process_msg(SPAKE2_CTX *ctx, uint8_t *out_key, size_t their_msg_len); +// CPace. +// +// See https://datatracker.ietf.org/doc/draft-irtf-cfrg-cpace/ + +// The role that a party plays in the CPACE key agreement protocol. +enum cpace_role_t { + // This role corresponds to the party A in the specification. + cpace_role_initiator, + // This role corresponds to the party B in the specification. + cpace_role_responder, +}; + +// CPACE_CTX_new returns a newly-allocated `CPACE_CTX` object that implements +// one side of the CPace protocol, or nullptr on error. This function implements +// CPACE-X25519-SHA512 in initiator-responder mode, acting as `role` and with +// `password` as the password-related string (PRS). +// +// `channel_id` and `session_id` are the channel identifier (CI) and session +// identifier (sid) values, respectively. Both values must match for the +// exchange to proceed. `assoc_data` is the cleartext associated data (ADa or +// ADb) to be sent to the peer. These values may be empty if not used. See +// Section 4.1 of draft-irtf-cfrg-cpace-21 for details. +// +// The application-level identities of each party in the protocol should be +// incorporated into either `channel_id` or each party's respective `assoc_data` +// values. See Section 10.1 of draft-irtf-cfrg-cpace-21. +// +// Once a `CPACE_CTX` is successfully created, the caller should call +// `CPACE_generate_msg` to generate the message to send to the peer. +OPENSSL_EXPORT CPACE_CTX *CPACE_CTX_new( + enum cpace_role_t role, const uint8_t *password, size_t password_len, + const uint8_t *channel_id, size_t channel_id_len, const uint8_t *assoc_data, + size_t assoc_data_len, const uint8_t *session_id, size_t session_id_len); + +// CPACE_CTX_free frees `ctx` and all the resources that it has allocated. +OPENSSL_EXPORT void CPACE_CTX_free(CPACE_CTX *ctx); + +#define CPACE_MSG_LEN 32 +#define CPACE_SHARED_SECRET_LEN 64 + +// CPACE_generate_msg generates the message to be sent to the peer. On success, +// it writes the message to `out_msg` and returns one. Otherwise, it returns +// zero. `ctx` must have been allocated by `CPACE_CTX_new`, with no subsequent +// functions called on it. +// +// `out_msg` only contains the Ya or Yb value. It does not include ADa or ADb. +// On success, the caller should separately send `out_msg` and their +// `assoc_data` value to the peer. It is the caller's responsibility to send +// `assoc_data` together with `out_msg`. After receiving the peer's reply, the +// caller should call `CPACE_process_msg` to complete the protocol. +OPENSSL_EXPORT int CPACE_generate_msg(CPACE_CTX *ctx, + uint8_t out_msg[CPACE_MSG_LEN]); + +// CPACE_process_msg processes `msg` and `peer_assoc_data` from the peer and +// computes the shared secret, or intermediate session key (ISK). On success, it +// writes the secret to `out_shared_secret` and returns one; it also writes a +// derived session ID if `out_sid` is not NULL. Otherwise, it returns zero. +// `ctx` must have successfully been passed to `CPACE_generate_msg`, with no +// subsequent functions called on it. +// +// `msg` should contain the peer's Ya or Yb value, and `peer_assoc_data` the +// peer's ADa or ADb value. +OPENSSL_EXPORT int CPACE_process_msg( + CPACE_CTX *ctx, const uint8_t in_msg[CPACE_MSG_LEN], + const uint8_t *peer_assoc_data, size_t peer_assoc_data_len, + uint8_t shared_secret[CPACE_SHARED_SECRET_LEN], + uint8_t sid_out[SHA512_DIGEST_LENGTH]); + + #if defined(__cplusplus) } // extern C @@ -226,6 +297,7 @@ extern "C++" { BSSL_NAMESPACE_BEGIN +BORINGSSL_MAKE_DELETER(CPACE_CTX, CPACE_CTX_free) BORINGSSL_MAKE_DELETER(SPAKE2_CTX, SPAKE2_CTX_free) BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/include/openssl/dh.h b/third_party/boringssl/src/include/openssl/dh.h index 59e8c9c..6cb5d9e 100644 --- a/third_party/boringssl/src/include/openssl/dh.h +++ b/third_party/boringssl/src/include/openssl/dh.h @@ -15,7 +15,7 @@ #ifndef OPENSSL_HEADER_DH_H #define OPENSSL_HEADER_DH_H -#include // IWYU pragma: export +#include // IWYU pragma: export #if defined(__cplusplus) extern "C" { @@ -49,6 +49,11 @@ OPENSSL_EXPORT void DH_free(DH *dh); // mutate `dh` for thread-safety purposes and may be used concurrently. OPENSSL_EXPORT int DH_up_ref(DH *dh); +// DH_dup_ref increments the reference count of `dh` and returns the same +// handle. It does not mutate `dh` for thread-safety purposes and may be used +// concurrently. +OPENSSL_EXPORT DH *DH_dup_ref(const DH *dh); + // Properties. @@ -317,7 +322,7 @@ extern "C++" { BSSL_NAMESPACE_BEGIN BORINGSSL_MAKE_DELETER(DH, DH_free) -BORINGSSL_MAKE_UP_REF(DH, DH_up_ref) +BORINGSSL_MAKE_UP_REF(DH, DH_dup_ref) BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/include/openssl/digest.h b/third_party/boringssl/src/include/openssl/digest.h index 8a81bc1..93d8e85 100644 --- a/third_party/boringssl/src/include/openssl/digest.h +++ b/third_party/boringssl/src/include/openssl/digest.h @@ -48,6 +48,36 @@ OPENSSL_EXPORT const EVP_MD *EVP_blake2b256(void); // MD5 and SHA-1, as used in TLS 1.1 and below. OPENSSL_EXPORT const EVP_MD *EVP_md5_sha1(void); +// SHA-3 family of digest functions. +// +// WARNING: Prefer to use SHA-2 (e.g. `EVP_sha256`) over SHA-3. Despite being a +// newer hash function, SHA-3 performs poorly and should only be used when +// necessary for interoperability with existing systems. + +OPENSSL_EXPORT const EVP_MD *EVP_sha3_256(void); +OPENSSL_EXPORT const EVP_MD *EVP_sha3_384(void); +OPENSSL_EXPORT const EVP_MD *EVP_sha3_512(void); + +// SHAKE functions. +// +// These EVP_MD objects are extendable-output functions (XOFs), meaning they can +// return arbitrarily many bytes of output. See `EVP_DigestSqueeze`. + +// EVP_turboshake* implement TurboSHAKE (RFC 9861). TurboSHAKE is similar to +// SHAKE, but is faster due to it using a more practical round count. +OPENSSL_EXPORT const EVP_MD *EVP_turboshake128(void); +OPENSSL_EXPORT const EVP_MD *EVP_turboshake256(void); + +// EVP_shake* implement SHAKE128 and SHAKE256 extendable-output function. +// +// WARNING: SHAKE is slow. Prefer SHA-2, or TurboSHAKE (`EVP_turboshake*`) if +// an XOF is needed. +OPENSSL_EXPORT const EVP_MD *EVP_shake128(void); +OPENSSL_EXPORT const EVP_MD *EVP_shake256(void); + + +// Digest lookup functions. + // EVP_get_digestbynid returns an `EVP_MD` for the given NID, or NULL if no // such digest is known. OPENSSL_EXPORT const EVP_MD *EVP_get_digestbynid(int nid); @@ -127,7 +157,7 @@ OPENSSL_EXPORT int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, // EVP_MAX_MD_BLOCK_SIZE is the largest digest block size supported, in // bytes. -#define EVP_MAX_MD_BLOCK_SIZE 128 // SHA-512 is the longest so far. +#define EVP_MAX_MD_BLOCK_SIZE 168 // SHAKE128 is the longest so far. // EVP_DigestFinal_ex finishes the digest in `ctx` and writes the output to // `md_out`. `EVP_MD_CTX_size` bytes are written, which is at most @@ -143,6 +173,15 @@ OPENSSL_EXPORT int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, uint8_t *md_out, OPENSSL_EXPORT int EVP_DigestFinal(EVP_MD_CTX *ctx, uint8_t *md_out, unsigned int *out_size); +// EVP_DigestSqueeze writes len bytes of output from `ctx` to `out` and returns +// one. This operation is only implemented if `ctx` was initialized with an +// extendable-output function, which can return arbitrarily long outputs. If +// not, this function returns zero. This function may be repeated to split its +// output over multiple calls. Doing so will give the same output as +// concatenating the calls into a single call. +OPENSSL_EXPORT int EVP_DigestSqueeze(EVP_MD_CTX *ctx, unsigned char *out, + size_t len); + // EVP_Digest performs a complete hashing operation in one call. It hashes `len` // bytes from `data` and writes the digest to `md_out`. `EVP_MD_CTX_size` bytes // are written, which is at most `EVP_MAX_MD_SIZE`. If `out_size` is not NULL @@ -301,8 +340,9 @@ OPENSSL_EXPORT EVP_MD_CTX *EVP_MD_CTX_create(void); // EVP_MD_CTX_destroy calls `EVP_MD_CTX_free`. OPENSSL_EXPORT void EVP_MD_CTX_destroy(EVP_MD_CTX *ctx); -// EVP_DigestFinalXOF returns zero and adds an error to the error queue. -// BoringSSL does not support any XOF digests. +// EVP_DigestFinalXOF behaves like `EVP_DigestSqueeze` but calls +// `EVP_MD_CTX_cleanup` after being called, so it is not possible to call it +// multiple times. OPENSSL_EXPORT int EVP_DigestFinalXOF(EVP_MD_CTX *ctx, uint8_t *out, size_t len); @@ -344,9 +384,9 @@ OPENSSL_EXPORT int EVP_Q_digest(OSSL_LIB_CTX *libctx, const char *name, struct evp_md_pctx_ops; // EVP_MAX_MD_DATA_SIZE is a private constant which specifies the size of the -// largest digest state. SHA-512 and BLAKE2b are joint-largest. Consuming code -// only uses this via the `EVP_MD_CTX` type. -#define EVP_MAX_MD_DATA_SIZE 208 +// largest digest state. SHA3-256 is the largest. Consuming code only uses this +// via the `EVP_MD_CTX` type. +#define EVP_MAX_MD_DATA_SIZE 240 // env_md_ctx_st is typoed ("evp" -> "env"), but the typo comes from OpenSSL // and some consumers forward-declare these structures so we're leaving it diff --git a/third_party/boringssl/src/include/openssl/dsa.h b/third_party/boringssl/src/include/openssl/dsa.h index fff5b76..a77bf91 100644 --- a/third_party/boringssl/src/include/openssl/dsa.h +++ b/third_party/boringssl/src/include/openssl/dsa.h @@ -15,7 +15,7 @@ #ifndef OPENSSL_HEADER_DSA_H #define OPENSSL_HEADER_DSA_H -#include // IWYU pragma: export +#include // IWYU pragma: export #include @@ -51,6 +51,11 @@ OPENSSL_EXPORT void DSA_free(DSA *dsa); // not mutate `dsa` for thread-safety purposes and may be used concurrently. OPENSSL_EXPORT int DSA_up_ref(DSA *dsa); +// DSA_dup_ref increments the reference count of `dsa` and returns the same +// handle. It does not mutate `dsa` for thread-safety purposes and may be used +// concurrently. +OPENSSL_EXPORT DSA *DSA_dup_ref(const DSA *dsa); + // Properties. @@ -370,7 +375,7 @@ extern "C++" { BSSL_NAMESPACE_BEGIN BORINGSSL_MAKE_DELETER(DSA, DSA_free) -BORINGSSL_MAKE_UP_REF(DSA, DSA_up_ref) +BORINGSSL_MAKE_UP_REF(DSA, DSA_dup_ref) BORINGSSL_MAKE_DELETER(DSA_SIG, DSA_SIG_free) BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/include/openssl/ec_key.h b/third_party/boringssl/src/include/openssl/ec_key.h index 1480520..296b7c0 100644 --- a/third_party/boringssl/src/include/openssl/ec_key.h +++ b/third_party/boringssl/src/include/openssl/ec_key.h @@ -60,6 +60,11 @@ OPENSSL_EXPORT EC_KEY *EC_KEY_dup(const EC_KEY *src); // not mutate `key` for thread-safety purposes and may be used concurrently. OPENSSL_EXPORT int EC_KEY_up_ref(EC_KEY *key); +// EC_KEY_dup_ref increases the reference count of `key` and returns the same +// handle. It does not mutate `key` for thread-safety purposes and may be used +// concurrently. +OPENSSL_EXPORT EC_KEY *EC_KEY_dup_ref(const EC_KEY *key); + // EC_KEY_is_opaque returns one if `key` is opaque and doesn't expose its key // material. Otherwise it return zero. OPENSSL_EXPORT int EC_KEY_is_opaque(const EC_KEY *key); @@ -347,7 +352,7 @@ extern "C++" { BSSL_NAMESPACE_BEGIN BORINGSSL_MAKE_DELETER(EC_KEY, EC_KEY_free) -BORINGSSL_MAKE_UP_REF(EC_KEY, EC_KEY_up_ref) +BORINGSSL_MAKE_UP_REF(EC_KEY, EC_KEY_dup_ref) BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/include/openssl/ecdh.h b/third_party/boringssl/src/include/openssl/ecdh.h index a1dff7b..90f1aa0 100644 --- a/third_party/boringssl/src/include/openssl/ecdh.h +++ b/third_party/boringssl/src/include/openssl/ecdh.h @@ -16,7 +16,7 @@ #ifndef OPENSSL_HEADER_ECDH_H #define OPENSSL_HEADER_ECDH_H -#include // IWYU pragma: export +#include // IWYU pragma: export #include @@ -40,7 +40,7 @@ OPENSSL_EXPORT int ECDH_compute_key( // ECDH_compute_key_fips calculates the shared key between `pub_key` and // `priv_key` and hashes it with the appropriate SHA function for `out_len`. The -// only value values for `out_len` are thus 24 (SHA-224), 32 (SHA-256), 48 +// only valid values for `out_len` are thus 28 (SHA-224), 32 (SHA-256), 48 // (SHA-384), and 64 (SHA-512). It returns one on success and zero on error. // // Note that the return value is different to `ECDH_compute_key`: it returns an diff --git a/third_party/boringssl/src/include/openssl/evp.h b/third_party/boringssl/src/include/openssl/evp.h index 8a767ca..bec028c 100644 --- a/third_party/boringssl/src/include/openssl/evp.h +++ b/third_party/boringssl/src/include/openssl/evp.h @@ -17,6 +17,7 @@ #include // IWYU pragma: export +#include #include // IWYU pragma: export // OpenSSL included digest and cipher functions in this header so we include @@ -128,6 +129,9 @@ OPENSSL_EXPORT EVP_PKEY *EVP_PKEY_copy_public(const EVP_PKEY *pkey); #define EVP_PKEY_ML_KEM_768 NID_ML_KEM_768 #define EVP_PKEY_ML_KEM_1024 NID_ML_KEM_1024 #define EVP_PKEY_XWING NID_X_Wing +#define EVP_PKEY_SLH_DSA_SHA2_128S NID_SLH_DSA_SHA2_128s +#define EVP_PKEY_SLH_DSA_SHAKE_256F NID_SLH_DSA_SHAKE_256f +#define EVP_PKEY_SLH_DSA_SHA2_128S_WITH_SHA256 NID_SLH_DSA_SHA2_128s_WITH_SHA256 // EVP_PKEY_id returns the type of `pkey`, which is one of the `EVP_PKEY_*` // values above. These type values generally correspond to the algorithm OID, @@ -199,6 +203,12 @@ OPENSSL_EXPORT const EVP_PKEY_ALG *EVP_pkey_ml_dsa_44(void); OPENSSL_EXPORT const EVP_PKEY_ALG *EVP_pkey_ml_dsa_65(void); OPENSSL_EXPORT const EVP_PKEY_ALG *EVP_pkey_ml_dsa_87(void); +// EVP_pkey_slh_dsa_* implement SLH-DSA and HashSLH-DSA keys, encoded as in +// RFC 9909. The `EVP_PKEY_id` values are `EVP_PKEY_SLH_DSA_*`. +OPENSSL_EXPORT const EVP_PKEY_ALG *EVP_pkey_slh_dsa_sha2_128s(void); +OPENSSL_EXPORT const EVP_PKEY_ALG *EVP_pkey_slh_dsa_sha2_128s_with_sha256(void); +OPENSSL_EXPORT const EVP_PKEY_ALG *EVP_pkey_slh_dsa_shake_256f(void); + // EVP_pkey_ml_kem_* implement ML-KEM keys, encoded as in RFC 9935. The // `EVP_PKEY_id` values are `EVP_PKEY_ML_KEM_*`. In the private key // representation, only the "seed" form is serialized or parsed. @@ -302,22 +312,22 @@ OPENSSL_EXPORT const EVP_PKEY_ALG *EVP_pkey_rsa_pss_sha512(void); // via `EVP_pkey_rsa_pss_sha256`. This differs from upstream OpenSSL, where // callers are exposed to `EVP_PKEY_RSA_PSS` by default. -OPENSSL_EXPORT int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, RSA *key); +OPENSSL_EXPORT int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, const RSA *key); OPENSSL_EXPORT int EVP_PKEY_assign_RSA(EVP_PKEY *pkey, RSA *key); OPENSSL_EXPORT RSA *EVP_PKEY_get0_RSA(const EVP_PKEY *pkey); OPENSSL_EXPORT RSA *EVP_PKEY_get1_RSA(const EVP_PKEY *pkey); -OPENSSL_EXPORT int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, DSA *key); +OPENSSL_EXPORT int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, const DSA *key); OPENSSL_EXPORT int EVP_PKEY_assign_DSA(EVP_PKEY *pkey, DSA *key); OPENSSL_EXPORT DSA *EVP_PKEY_get0_DSA(const EVP_PKEY *pkey); OPENSSL_EXPORT DSA *EVP_PKEY_get1_DSA(const EVP_PKEY *pkey); -OPENSSL_EXPORT int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, EC_KEY *key); +OPENSSL_EXPORT int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, const EC_KEY *key); OPENSSL_EXPORT int EVP_PKEY_assign_EC_KEY(EVP_PKEY *pkey, EC_KEY *key); OPENSSL_EXPORT EC_KEY *EVP_PKEY_get0_EC_KEY(const EVP_PKEY *pkey); OPENSSL_EXPORT EC_KEY *EVP_PKEY_get1_EC_KEY(const EVP_PKEY *pkey); -OPENSSL_EXPORT int EVP_PKEY_set1_DH(EVP_PKEY *pkey, DH *key); +OPENSSL_EXPORT int EVP_PKEY_set1_DH(EVP_PKEY *pkey, const DH *key); OPENSSL_EXPORT int EVP_PKEY_assign_DH(EVP_PKEY *pkey, DH *key); OPENSSL_EXPORT DH *EVP_PKEY_get0_DH(const EVP_PKEY *pkey); OPENSSL_EXPORT DH *EVP_PKEY_get1_DH(const EVP_PKEY *pkey); @@ -423,6 +433,9 @@ OPENSSL_EXPORT int EVP_marshal_private_key(CBB *cbb, const EVP_PKEY *key); // supported by BoringSSL is the 64-byte "seed" resulting from the // concatenation of d||z, as each is defined in FIPS 203. // +// - SLH-DSA, using the 2n-byte public key and 4n-byte private key formats in +// FIPS 205 and RFC 9909. +// // These formats are suitable if serializing a key in a context where the // algorithm is already known and there is no need to encode it. @@ -498,13 +511,10 @@ OPENSSL_EXPORT EVP_PKEY *EVP_PKEY_generate_from_alg(const EVP_PKEY_ALG *alg); // Ed25519, `type` should be NULL. The `EVP_MD_CTX` itself is unused but is // present so the API is uniform. See `EVP_DigestSign`. // -// This function does not mutate `pkey` for thread-safety purposes and may be -// used concurrently with other non-mutating functions on `pkey`. -// // It returns one on success, or zero on error. OPENSSL_EXPORT int EVP_DigestSignInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, const EVP_MD *type, ENGINE *e, - EVP_PKEY *pkey); + const EVP_PKEY *pkey); // EVP_DigestSignUpdate appends `len` bytes from `data` to the data which will // be signed in `EVP_DigestSignFinal`. It returns one. @@ -554,13 +564,10 @@ OPENSSL_EXPORT int EVP_DigestSign(EVP_MD_CTX *ctx, uint8_t *out_sig, // Ed25519, `type` should be NULL. The `EVP_MD_CTX` itself is unused but is // present so the API is uniform. See `EVP_DigestVerify`. // -// This function does not mutate `pkey` for thread-safety purposes and may be -// used concurrently with other non-mutating functions on `pkey`. -// // It returns one on success, or zero on error. OPENSSL_EXPORT int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, const EVP_MD *type, ENGINE *e, - EVP_PKEY *pkey); + const EVP_PKEY *pkey); // EVP_DigestVerifyUpdate appends `len` bytes from `data` to the data which // will be verified by `EVP_DigestVerifyFinal`. It returns one. @@ -615,13 +622,9 @@ OPENSSL_EXPORT int EVP_SignUpdate(EVP_MD_CTX *ctx, const void *data, // actual size of the signature is written to `*out_sig_len`. // // It returns one on success and zero otherwise. -// -// It does not modify `ctx`, thus it's possible to continue to use `ctx` in -// order to sign a longer message. It also does not mutate `pkey` for -// thread-safety purposes and may be used concurrently with other non-mutating -// functions on `pkey`. OPENSSL_EXPORT int EVP_SignFinal(const EVP_MD_CTX *ctx, uint8_t *sig, - unsigned int *out_sig_len, EVP_PKEY *pkey); + unsigned int *out_sig_len, + const EVP_PKEY *pkey); // Verifying (old functions) @@ -650,13 +653,8 @@ OPENSSL_EXPORT int EVP_VerifyUpdate(EVP_MD_CTX *ctx, const void *data, // calls to `EVP_VerifyUpdate`. // // It returns one on success and zero otherwise. -// -// It does not modify `ctx`, thus it's possible to continue to use `ctx` in -// order to verify a longer message. It also does not mutate `pkey` for -// thread-safety purposes and may be used concurrently with other non-mutating -// functions on `pkey`. OPENSSL_EXPORT int EVP_VerifyFinal(EVP_MD_CTX *ctx, const uint8_t *sig, - size_t sig_len, EVP_PKEY *pkey); + size_t sig_len, const EVP_PKEY *pkey); // Printing @@ -752,7 +750,7 @@ OPENSSL_EXPORT int EVP_PBE_scrypt(const char *password, size_t password_len, // EVP_PKEY_CTX_new allocates a fresh `EVP_PKEY_CTX` for use with `pkey`. It // returns the context or NULL on error. -OPENSSL_EXPORT EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e); +OPENSSL_EXPORT EVP_PKEY_CTX *EVP_PKEY_CTX_new(const EVP_PKEY *pkey, ENGINE *e); // EVP_PKEY_CTX_new_id allocates a fresh `EVP_PKEY_CTX` for a key of type `id` // (e.g. `EVP_PKEY_HMAC`). This can be used for key generation where @@ -770,7 +768,7 @@ OPENSSL_EXPORT void EVP_PKEY_CTX_free(EVP_PKEY_CTX *ctx); OPENSSL_EXPORT EVP_PKEY_CTX *EVP_PKEY_CTX_dup(EVP_PKEY_CTX *ctx); // EVP_PKEY_CTX_get0_pkey returns the `EVP_PKEY` associated with `ctx`. -OPENSSL_EXPORT EVP_PKEY *EVP_PKEY_CTX_get0_pkey(EVP_PKEY_CTX *ctx); +OPENSSL_EXPORT EVP_PKEY *EVP_PKEY_CTX_get0_pkey(const EVP_PKEY_CTX *ctx); // EVP_PKEY_sign_init initialises an `EVP_PKEY_CTX` for a signing operation. It // should be called before `EVP_PKEY_sign`. @@ -897,7 +895,8 @@ OPENSSL_EXPORT int EVP_PKEY_derive_init(EVP_PKEY_CTX *ctx); // by `ctx` to `peer`. It should be called after `EVP_PKEY_derive_init`. (For // example, this is used to set the peer's key in (EC)DH.) It returns one on // success and zero on error. -OPENSSL_EXPORT int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer); +OPENSSL_EXPORT int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, + const EVP_PKEY *peer); // EVP_PKEY_derive derives a shared key from `ctx`. If `key` is non-NULL then, // on entry, `out_key_len` must contain the amount of space at `key`. If @@ -1230,6 +1229,13 @@ OPENSSL_EXPORT int EVP_PKEY_get_ec_point_conv_form(const EVP_PKEY *pkey); OPENSSL_EXPORT int EVP_PKEY_CTX_set_ec_paramgen_curve_nid(EVP_PKEY_CTX *ctx, int nid); +// EVP_marshal_public_key_with_ec_point_format marshals key as a DER-encoded +// `SubjectPublicKeyInfo` structure (RFC 5280) and appends the result to `cbb`. +// `key` must be an EC key, and the EC point will be serialized in the format +// specified by `format`. It returns one on success and zero on error. +OPENSSL_EXPORT int EVP_marshal_public_key_with_ec_point_format( + CBB *cbb, const EVP_PKEY *key, point_conversion_form_t format); + // Diffie-Hellman-specific control functions. @@ -1271,7 +1277,7 @@ OPENSSL_EXPORT const EVP_KEM *EVP_kem_ml_kem_1024(void); // defined in draft-irtf-cfrg-concrete-hybrid-kems. OPENSSL_EXPORT const EVP_KEM *EVP_kem_xwing(void); -// TODO(crbug.com/449751916): Add more supported KEMs. +// Additional KEMs are defined in hpke.h: See `EVP_kem_dhkem_*`. // EVP_KEM_ciphertext_len returns the fixed length, in bytes, of a ciphertext // produced and consumed by `kem`. @@ -1633,7 +1639,7 @@ extern "C++" { BSSL_NAMESPACE_BEGIN BORINGSSL_MAKE_DELETER(EVP_PKEY, EVP_PKEY_free) -BORINGSSL_MAKE_UP_REF(EVP_PKEY, EVP_PKEY_up_ref) +BORINGSSL_MAKE_UP_REF(EVP_PKEY, EVP_PKEY_dup_ref) BORINGSSL_MAKE_DELETER(EVP_PKEY_CTX, EVP_PKEY_CTX_free) BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/include/openssl/hpke.h b/third_party/boringssl/src/include/openssl/hpke.h index 9e1a77e..6cc8bbd 100644 --- a/third_party/boringssl/src/include/openssl/hpke.h +++ b/third_party/boringssl/src/include/openssl/hpke.h @@ -55,6 +55,10 @@ OPENSSL_EXPORT const EVP_HPKE_KEM *EVP_hpke_xwing(void); OPENSSL_EXPORT const EVP_HPKE_KEM *EVP_hpke_mlkem768(void); OPENSSL_EXPORT const EVP_HPKE_KEM *EVP_hpke_mlkem1024(void); +// EVP_kem_dhkem_* implement DHKEM variants defined in RFC 9180. +OPENSSL_EXPORT const EVP_KEM *EVP_kem_dhkem_p256_hkdf_sha256(void); +OPENSSL_EXPORT const EVP_KEM *EVP_kem_dhkem_x25519_hkdf_sha256(void); + // EVP_HPKE_KEM_id returns the HPKE KEM identifier for `kem`, which // will be one of the `EVP_HPKE_KEM_*` constants. OPENSSL_EXPORT uint16_t EVP_HPKE_KEM_id(const EVP_HPKE_KEM *kem); @@ -83,6 +87,10 @@ OPENSSL_EXPORT size_t EVP_HPKE_KEM_private_key_len(const EVP_HPKE_KEM *kem); // secret, for `kem`. This value will be at most `EVP_HPKE_MAX_ENC_LENGTH`. OPENSSL_EXPORT size_t EVP_HPKE_KEM_enc_len(const EVP_HPKE_KEM *kem); +// EVP_HPKE_KEM_shared_secret_len returns the length of the shared secret +// produced by `kem`. +OPENSSL_EXPORT size_t EVP_HPKE_KEM_shared_secret_len(const EVP_HPKE_KEM *kem); + // The following constants are KDF identifiers. #define EVP_HPKE_HKDF_SHA256 0x0001 #define EVP_HPKE_HKDF_SHA384 0x0002 @@ -271,6 +279,25 @@ OPENSSL_EXPORT int EVP_HPKE_CTX_setup_recipient( const EVP_HPKE_AEAD *aead, const uint8_t *enc, size_t enc_len, const uint8_t *info, size_t info_len); +// EVP_HPKE_CTX_setup_recipient_with_shared_secret behaves like +// `EVP_HPKE_CTX_setup_recipient`, but takes the shared secret explicitly. +// +// WARNING: `shared_secret` must be the result of decapsulating the sender's +// `enc` value with the recipient's private key. Using the wrong shared secret +// will result in an `EVP_HPKE_CTX` that cannot decrypt the sender's messages. +// Additionally, an attacker with knowledge of `shared_secret` will be able to +// decrypt and forge encrypted messages. +// +// It returns one on success and zero on error. +// +// On success, callers may call `EVP_HPKE_CTX_open` to decrypt messages from the +// sender. Callers must then call `EVP_HPKE_CTX_cleanup` when done. On failure, +// calling `EVP_HPKE_CTX_cleanup` is safe, but not required. +OPENSSL_EXPORT int EVP_HPKE_CTX_setup_recipient_with_shared_secret( + EVP_HPKE_CTX *ctx, const EVP_HPKE_KEM *kem, const EVP_HPKE_KDF *kdf, + const EVP_HPKE_AEAD *aead, const uint8_t *shared_secret, + size_t shared_secret_len, const uint8_t *info, size_t info_len); + // EVP_HPKE_CTX_setup_auth_sender implements the SetupAuthS HPKE operation. It // behaves like `EVP_HPKE_CTX_setup_sender` but authenticates the resulting // context with `key`. @@ -393,14 +420,6 @@ struct evp_hpke_ctx_st { struct evp_hpke_key_st { const EVP_HPKE_KEM *kem; - uint8_t private_key[EVP_HPKE_MAX_PRIVATE_KEY_LENGTH]; - uint8_t public_key[EVP_HPKE_MAX_PUBLIC_KEY_LENGTH]; - - // `pkey`, if non-null, takes precedence over `private_key` and `public_key`, - // which are left unused. Otherwise `private_key` and `public_key` are used - // instead. - // TODO(crbug.com/535883377): Unify EVP_HPKE_KEM and EVP_KEM for all supported - // HPKE KEMs. EVP_PKEY *pkey; }; diff --git a/third_party/boringssl/src/include/openssl/md5.h b/third_party/boringssl/src/include/openssl/md5.h index 373533d..df069dd 100644 --- a/third_party/boringssl/src/include/openssl/md5.h +++ b/third_party/boringssl/src/include/openssl/md5.h @@ -31,6 +31,10 @@ extern "C" { // MD5_DIGEST_LENGTH is the length of an MD5 digest. #define MD5_DIGEST_LENGTH 16 +// MD5_STATE_MAX_BYTES is the maximum length, in bytes, of a marshaled `MD5_CTX` +// state. +#define MD5_STATE_MAX_BYTES (16 + 8 + MD5_CBLOCK - 1) + // MD5_Init initialises `md5` and returns one. OPENSSL_EXPORT int MD5_Init(MD5_CTX *md5); @@ -47,6 +51,22 @@ OPENSSL_EXPORT int MD5_Final(uint8_t out[MD5_DIGEST_LENGTH], MD5_CTX *md5); OPENSSL_EXPORT uint8_t *MD5(const uint8_t *data, size_t len, uint8_t out[MD5_DIGEST_LENGTH]); +// MD5_marshal_state serializes the intermediate hash state in `md5` into `out`, +// sets `*out_len` to the number of bytes written (at most +// `MD5_STATE_MAX_BYTES`), and returns one. `md5` is not modified. The +// serialized format is guaranteed to be backward- and forward-compatible across +// versions of BoringSSL. +OPENSSL_EXPORT int MD5_marshal_state(const MD5_CTX *md5, + uint8_t out[MD5_STATE_MAX_BYTES], + size_t *out_len); + +// MD5_parse_state deserializes `in_len` bytes from `in` (in the format produced +// by `MD5_marshal_state`) into `md5` and returns one. If `in` is malformed, it +// returns zero and leaves `md5` unmodified. The serialized format is guaranteed +// to be backward- and forward-compatible across versions of BoringSSL. +OPENSSL_EXPORT int MD5_parse_state(MD5_CTX *md5, const uint8_t *in, + size_t in_len); + // MD5_Transform is a low-level function that performs a single, MD5 block // transformation using the state from `md5` and 64 bytes from `block`. OPENSSL_EXPORT void MD5_Transform(MD5_CTX *md5, diff --git a/third_party/boringssl/src/include/openssl/nid.h b/third_party/boringssl/src/include/openssl/nid.h index 9ca8e67..aeb315b 100644 --- a/third_party/boringssl/src/include/openssl/nid.h +++ b/third_party/boringssl/src/include/openssl/nid.h @@ -5511,48 +5511,57 @@ extern "C" { #define SN_X_Wing "X-Wing" #define NID_X_Wing 972 -#define SN_alg_mtcProof_draft "alg-mtcProof-draft" -#define NID_alg_mtcProof_draft 976 -#define OBJ_alg_mtcProof_draft 1L, 3L, 6L, 1L, 4L, 1L, 44363L, 47L, 0L -#define OBJ_ENC_alg_mtcProof_draft \ - 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xda, 0x4b, 0x2f, 0x00 - -#define SN_rdna_trustAnchorID_draft "rdna-trustAnchorID-draft" -#define NID_rdna_trustAnchorID_draft 977 -#define OBJ_rdna_trustAnchorID_draft 1L, 3L, 6L, 1L, 4L, 1L, 44363L, 47L, 1L -#define OBJ_ENC_rdna_trustAnchorID_draft \ - 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xda, 0x4b, 0x2f, 0x01 - -#define SN_pe_mtcCertificationAuthority_draft \ - "pe-mtcCertificationAuthority-draft" -#define NID_pe_mtcCertificationAuthority_draft 978 -#define OBJ_pe_mtcCertificationAuthority_draft \ - 1L, 3L, 6L, 1L, 4L, 1L, 44363L, 47L, 2L -#define OBJ_ENC_pe_mtcCertificationAuthority_draft \ - 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xda, 0x4b, 0x2f, 0x02 - #define SN_SLH_DSA_SHA2_128s "id-slh-dsa-sha2-128s" #define LN_SLH_DSA_SHA2_128s "SLH-DSA-SHA2-128s" -#define NID_SLH_DSA_SHA2_128s 979 +#define NID_SLH_DSA_SHA2_128s 973 #define OBJ_SLH_DSA_SHA2_128s 2L, 16L, 840L, 1L, 101L, 3L, 4L, 3L, 20L #define OBJ_ENC_SLH_DSA_SHA2_128s \ 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x14 #define SN_SLH_DSA_SHAKE_256f "id-slh-dsa-shake-256f" #define LN_SLH_DSA_SHAKE_256f "SLH-DSA-SHAKE-256f" -#define NID_SLH_DSA_SHAKE_256f 980 +#define NID_SLH_DSA_SHAKE_256f 974 #define OBJ_SLH_DSA_SHAKE_256f 2L, 16L, 840L, 1L, 101L, 3L, 4L, 3L, 31L #define OBJ_ENC_SLH_DSA_SHAKE_256f \ 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x1f #define SN_SLH_DSA_SHA2_128s_WITH_SHA256 "id-hash-slh-dsa-sha2-128s-with-sha256" #define LN_SLH_DSA_SHA2_128s_WITH_SHA256 "SLH-DSA-SHA2-128s-WITH-SHA256" -#define NID_SLH_DSA_SHA2_128s_WITH_SHA256 981 +#define NID_SLH_DSA_SHA2_128s_WITH_SHA256 975 #define OBJ_SLH_DSA_SHA2_128s_WITH_SHA256 \ 2L, 16L, 840L, 1L, 101L, 3L, 4L, 3L, 35L #define OBJ_ENC_SLH_DSA_SHA2_128s_WITH_SHA256 \ 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x23 +#define SN_alg_mtcProof "alg-mtcProof" +#define NID_alg_mtcProof 976 +#define OBJ_alg_mtcProof 1L, 3L, 6L, 1L, 5L, 5L, 7L, 6L, 67L +#define OBJ_ENC_alg_mtcProof 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x06, 0x43 + +#define SN_rdna_trustAnchorID "rdna-trustAnchorID" +#define NID_rdna_trustAnchorID 977 +#define OBJ_rdna_trustAnchorID 1L, 3L, 6L, 1L, 5L, 5L, 7L, 25L, 3L +#define OBJ_ENC_rdna_trustAnchorID \ + 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x19, 0x03 + +#define SN_pe_mtcCertificationAuthority_SHA256 \ + "pe-mtcCertificationAuthority-SHA256" +#define NID_pe_mtcCertificationAuthority_SHA256 978 +#define OBJ_pe_mtcCertificationAuthority_SHA256 \ + 1L, 3L, 6L, 1L, 5L, 5L, 7L, 1L, 38L +#define OBJ_ENC_pe_mtcCertificationAuthority_SHA256 \ + 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x01, 0x26 + +#define SN_alg_unsigned "alg-unsigned" +#define NID_alg_unsigned 979 +#define OBJ_alg_unsigned 1L, 3L, 6L, 1L, 5L, 5L, 7L, 6L, 36L +#define OBJ_ENC_alg_unsigned 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x06, 0x24 + +#define SN_rdna_unsigned "rdna-unsigned" +#define NID_rdna_unsigned 980 +#define OBJ_rdna_unsigned 1L, 3L, 6L, 1L, 5L, 5L, 7L, 25L, 1L +#define OBJ_ENC_rdna_unsigned 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x19, 0x01 + #if defined(__cplusplus) } /* extern C */ diff --git a/third_party/boringssl/src/include/openssl/pkcs7.h b/third_party/boringssl/src/include/openssl/pkcs7.h index 85c851e..dc36d3d 100644 --- a/third_party/boringssl/src/include/openssl/pkcs7.h +++ b/third_party/boringssl/src/include/openssl/pkcs7.h @@ -15,7 +15,7 @@ #ifndef OPENSSL_HEADER_PKCS7_H #define OPENSSL_HEADER_PKCS7_H -#include // IWYU pragma: export +#include // IWYU pragma: export #include @@ -59,8 +59,8 @@ OPENSSL_EXPORT int PKCS7_bundle_raw_certificates( // PKCS7_bundle_certificates behaves like `PKCS7_bundle_raw_certificates` but // takes `X509` objects as input. -OPENSSL_EXPORT int PKCS7_bundle_certificates( - CBB *out, const STACK_OF(X509) *certs); +OPENSSL_EXPORT int PKCS7_bundle_certificates(CBB *out, + const STACK_OF(X509) *certs); // PKCS7_get_CRLs parses a PKCS#7, SignedData structure from `cbs` and appends // the included CRLs to `out_crls`. It returns one on success and zero on error. @@ -144,8 +144,7 @@ typedef struct { // d2i_PKCS7 parses a BER-encoded, PKCS#7 signed data ContentInfo structure from // `len` bytes at `*inp`, as described in `d2i_SAMPLE`. -OPENSSL_EXPORT PKCS7 *d2i_PKCS7(PKCS7 **out, const uint8_t **inp, - size_t len); +OPENSSL_EXPORT PKCS7 *d2i_PKCS7(PKCS7 **out, const uint8_t **inp, size_t len); // d2i_PKCS7_bio behaves like `d2i_PKCS7` but reads the input from `bio`. If // the length of the object is indefinite the full contents of `bio` are read. @@ -215,8 +214,9 @@ OPENSSL_EXPORT int PKCS7_type_is_signedAndEnveloped(const PKCS7 *p7); // // Note this function only implements a subset of the corresponding OpenSSL // function. It is provided for backwards compatibility only. -OPENSSL_EXPORT PKCS7 *PKCS7_sign(X509 *sign_cert, EVP_PKEY *pkey, - STACK_OF(X509) *certs, BIO *data, int flags); +OPENSSL_EXPORT PKCS7 *PKCS7_sign(const X509 *sign_cert, const EVP_PKEY *pkey, + const STACK_OF(X509) *certs, BIO *data, + int flags); #if defined(__cplusplus) diff --git a/third_party/boringssl/src/include/openssl/pkcs8.h b/third_party/boringssl/src/include/openssl/pkcs8.h index 3abc0c7..2ced285 100644 --- a/third_party/boringssl/src/include/openssl/pkcs8.h +++ b/third_party/boringssl/src/include/openssl/pkcs8.h @@ -204,7 +204,7 @@ OPENSSL_EXPORT int PKCS12_verify_mac(const PKCS12 *p12, const char *password, // an error to specify both an alias on `cert` and a non-NULL `name` // parameter. OPENSSL_EXPORT PKCS12 *PKCS12_create(const char *password, const char *name, - const EVP_PKEY *pkey, X509 *cert, + const EVP_PKEY *pkey, const X509 *cert, const STACK_OF(X509) *chain, int key_nid, int cert_nid, int iterations, int mac_iterations, int key_type); diff --git a/third_party/boringssl/src/include/openssl/pool.h b/third_party/boringssl/src/include/openssl/pool.h index 23f8c44..2c3855b 100644 --- a/third_party/boringssl/src/include/openssl/pool.h +++ b/third_party/boringssl/src/include/openssl/pool.h @@ -59,6 +59,12 @@ OPENSSL_EXPORT void CRYPTO_BUFFER_POOL_free(CRYPTO_BUFFER_POOL *pool); // used concurrently. OPENSSL_EXPORT int CRYPTO_BUFFER_POOL_up_ref(CRYPTO_BUFFER_POOL *pool); +// CRYPTO_BUFFER_POOL_dup_ref increments the reference count of `pool` and +// returns the same handle. It does not mutate `pool` for thread-safety purposes +// and may be used concurrently. +OPENSSL_EXPORT CRYPTO_BUFFER_POOL *CRYPTO_BUFFER_POOL_dup_ref( + const CRYPTO_BUFFER_POOL *pool); + // CRYPTO_BUFFER_new returns a `CRYPTO_BUFFER` containing a copy of `data`, or // else NULL on error. If `pool` is not NULL then the returned value may be a // reference to a previously existing `CRYPTO_BUFFER` that contained the same @@ -124,9 +130,9 @@ extern "C++" { BSSL_NAMESPACE_BEGIN BORINGSSL_MAKE_DELETER(CRYPTO_BUFFER_POOL, CRYPTO_BUFFER_POOL_free) -BORINGSSL_MAKE_UP_REF(CRYPTO_BUFFER_POOL, CRYPTO_BUFFER_POOL_up_ref) +BORINGSSL_MAKE_UP_REF(CRYPTO_BUFFER_POOL, CRYPTO_BUFFER_POOL_dup_ref) BORINGSSL_MAKE_DELETER(CRYPTO_BUFFER, CRYPTO_BUFFER_free) -BORINGSSL_MAKE_UP_REF(CRYPTO_BUFFER, CRYPTO_BUFFER_up_ref) +BORINGSSL_MAKE_UP_REF(CRYPTO_BUFFER, CRYPTO_BUFFER_dup_ref) BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/include/openssl/prefix_symbols.h b/third_party/boringssl/src/include/openssl/prefix_symbols.h index a328dfc..658cc8d 100644 --- a/third_party/boringssl/src/include/openssl/prefix_symbols.h +++ b/third_party/boringssl/src/include/openssl/prefix_symbols.h @@ -130,6 +130,7 @@ #pragma redefine_extname ASN1_STRING_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(ASN1_STRING_free) #pragma redefine_extname ASN1_STRING_get0_data BORINGSSL_ADD_USER_LABEL_AND_PREFIX(ASN1_STRING_get0_data) #pragma redefine_extname ASN1_STRING_get_default_mask BORINGSSL_ADD_USER_LABEL_AND_PREFIX(ASN1_STRING_get_default_mask) +#pragma redefine_extname ASN1_STRING_get_length BORINGSSL_ADD_USER_LABEL_AND_PREFIX(ASN1_STRING_get_length) #pragma redefine_extname ASN1_STRING_length BORINGSSL_ADD_USER_LABEL_AND_PREFIX(ASN1_STRING_length) #pragma redefine_extname ASN1_STRING_new BORINGSSL_ADD_USER_LABEL_AND_PREFIX(ASN1_STRING_new) #pragma redefine_extname ASN1_STRING_print BORINGSSL_ADD_USER_LABEL_AND_PREFIX(ASN1_STRING_print) @@ -137,6 +138,7 @@ #pragma redefine_extname ASN1_STRING_print_ex_fp BORINGSSL_ADD_USER_LABEL_AND_PREFIX(ASN1_STRING_print_ex_fp) #pragma redefine_extname ASN1_STRING_set BORINGSSL_ADD_USER_LABEL_AND_PREFIX(ASN1_STRING_set) #pragma redefine_extname ASN1_STRING_set0 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(ASN1_STRING_set0) +#pragma redefine_extname ASN1_STRING_set1_data BORINGSSL_ADD_USER_LABEL_AND_PREFIX(ASN1_STRING_set1_data) #pragma redefine_extname ASN1_STRING_set_by_NID BORINGSSL_ADD_USER_LABEL_AND_PREFIX(ASN1_STRING_set_by_NID) #pragma redefine_extname ASN1_STRING_set_default_mask BORINGSSL_ADD_USER_LABEL_AND_PREFIX(ASN1_STRING_set_default_mask) #pragma redefine_extname ASN1_STRING_set_default_mask_asc BORINGSSL_ADD_USER_LABEL_AND_PREFIX(ASN1_STRING_set_default_mask_asc) @@ -232,6 +234,7 @@ #pragma redefine_extname BIO_ctrl_get_write_guarantee BORINGSSL_ADD_USER_LABEL_AND_PREFIX(BIO_ctrl_get_write_guarantee) #pragma redefine_extname BIO_ctrl_pending BORINGSSL_ADD_USER_LABEL_AND_PREFIX(BIO_ctrl_pending) #pragma redefine_extname BIO_do_connect BORINGSSL_ADD_USER_LABEL_AND_PREFIX(BIO_do_connect) +#pragma redefine_extname BIO_dup_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(BIO_dup_ref) #pragma redefine_extname BIO_eof BORINGSSL_ADD_USER_LABEL_AND_PREFIX(BIO_eof) #pragma redefine_extname BIO_f_base64 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(BIO_f_base64) #pragma redefine_extname BIO_f_ssl BORINGSSL_ADD_USER_LABEL_AND_PREFIX(BIO_f_ssl) @@ -590,6 +593,7 @@ #pragma redefine_extname CBS_is_valid_asn1_integer BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CBS_is_valid_asn1_integer) #pragma redefine_extname CBS_is_valid_asn1_oid BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CBS_is_valid_asn1_oid) #pragma redefine_extname CBS_is_valid_asn1_relative_oid BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CBS_is_valid_asn1_relative_oid) +#pragma redefine_extname CBS_is_valid_asn1_set_of BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CBS_is_valid_asn1_set_of) #pragma redefine_extname CBS_mem_equal BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CBS_mem_equal) #pragma redefine_extname CBS_parse_generalized_time BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CBS_parse_generalized_time) #pragma redefine_extname CBS_parse_utc_time BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CBS_parse_utc_time) @@ -615,9 +619,14 @@ #pragma redefine_extname CONF_modules_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CONF_modules_free) #pragma redefine_extname CONF_modules_load_file BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CONF_modules_load_file) #pragma redefine_extname CONF_modules_unload BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CONF_modules_unload) +#pragma redefine_extname CPACE_CTX_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CPACE_CTX_free) +#pragma redefine_extname CPACE_CTX_new BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CPACE_CTX_new) +#pragma redefine_extname CPACE_generate_msg BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CPACE_generate_msg) +#pragma redefine_extname CPACE_process_msg BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CPACE_process_msg) #pragma redefine_extname CRL_DIST_POINTS_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CRL_DIST_POINTS_free) #pragma redefine_extname CRL_DIST_POINTS_it BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CRL_DIST_POINTS_it) #pragma redefine_extname CRL_DIST_POINTS_new BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CRL_DIST_POINTS_new) +#pragma redefine_extname CRYPTO_BUFFER_POOL_dup_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CRYPTO_BUFFER_POOL_dup_ref) #pragma redefine_extname CRYPTO_BUFFER_POOL_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CRYPTO_BUFFER_POOL_free) #pragma redefine_extname CRYPTO_BUFFER_POOL_new BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CRYPTO_BUFFER_POOL_new) #pragma redefine_extname CRYPTO_BUFFER_POOL_up_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(CRYPTO_BUFFER_POOL_up_ref) @@ -692,6 +701,7 @@ #pragma redefine_extname DH_compute_key BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DH_compute_key) #pragma redefine_extname DH_compute_key_hashed BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DH_compute_key_hashed) #pragma redefine_extname DH_compute_key_padded BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DH_compute_key_padded) +#pragma redefine_extname DH_dup_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DH_dup_ref) #pragma redefine_extname DH_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DH_free) #pragma redefine_extname DH_generate_key BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DH_generate_key) #pragma redefine_extname DH_generate_parameters BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DH_generate_parameters) @@ -733,6 +743,7 @@ #pragma redefine_extname DSA_do_sign BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DSA_do_sign) #pragma redefine_extname DSA_do_verify BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DSA_do_verify) #pragma redefine_extname DSA_dup_DH BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DSA_dup_DH) +#pragma redefine_extname DSA_dup_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DSA_dup_ref) #pragma redefine_extname DSA_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DSA_free) #pragma redefine_extname DSA_generate_key BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DSA_generate_key) #pragma redefine_extname DSA_generate_parameters BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DSA_generate_parameters) @@ -818,6 +829,7 @@ #pragma redefine_extname EC_KEY_check_key BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EC_KEY_check_key) #pragma redefine_extname EC_KEY_derive_from_secret BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EC_KEY_derive_from_secret) #pragma redefine_extname EC_KEY_dup BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EC_KEY_dup) +#pragma redefine_extname EC_KEY_dup_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EC_KEY_dup_ref) #pragma redefine_extname EC_KEY_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EC_KEY_free) #pragma redefine_extname EC_KEY_generate_key BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EC_KEY_generate_key) #pragma redefine_extname EC_KEY_generate_key_fips BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EC_KEY_generate_key_fips) @@ -1022,6 +1034,7 @@ #pragma redefine_extname EVP_DigestSignFinal BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_DigestSignFinal) #pragma redefine_extname EVP_DigestSignInit BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_DigestSignInit) #pragma redefine_extname EVP_DigestSignUpdate BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_DigestSignUpdate) +#pragma redefine_extname EVP_DigestSqueeze BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_DigestSqueeze) #pragma redefine_extname EVP_DigestUpdate BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_DigestUpdate) #pragma redefine_extname EVP_DigestVerify BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_DigestVerify) #pragma redefine_extname EVP_DigestVerifyFinal BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_DigestVerifyFinal) @@ -1057,6 +1070,7 @@ #pragma redefine_extname EVP_HPKE_CTX_setup_auth_sender BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_HPKE_CTX_setup_auth_sender) #pragma redefine_extname EVP_HPKE_CTX_setup_auth_sender_with_seed_for_testing BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_HPKE_CTX_setup_auth_sender_with_seed_for_testing) #pragma redefine_extname EVP_HPKE_CTX_setup_recipient BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_HPKE_CTX_setup_recipient) +#pragma redefine_extname EVP_HPKE_CTX_setup_recipient_with_shared_secret BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_HPKE_CTX_setup_recipient_with_shared_secret) #pragma redefine_extname EVP_HPKE_CTX_setup_sender BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_HPKE_CTX_setup_sender) #pragma redefine_extname EVP_HPKE_CTX_setup_sender_with_seed_for_testing BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_HPKE_CTX_setup_sender_with_seed_for_testing) #pragma redefine_extname EVP_HPKE_CTX_zero BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_HPKE_CTX_zero) @@ -1066,6 +1080,7 @@ #pragma redefine_extname EVP_HPKE_KEM_id BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_HPKE_KEM_id) #pragma redefine_extname EVP_HPKE_KEM_private_key_len BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_HPKE_KEM_private_key_len) #pragma redefine_extname EVP_HPKE_KEM_public_key_len BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_HPKE_KEM_public_key_len) +#pragma redefine_extname EVP_HPKE_KEM_shared_secret_len BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_HPKE_KEM_shared_secret_len) #pragma redefine_extname EVP_HPKE_KEY_cleanup BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_HPKE_KEY_cleanup) #pragma redefine_extname EVP_HPKE_KEY_copy BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_HPKE_KEY_copy) #pragma redefine_extname EVP_HPKE_KEY_derive BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_HPKE_KEY_derive) @@ -1331,6 +1346,8 @@ #pragma redefine_extname EVP_hpke_p256_hkdf_sha256 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_hpke_p256_hkdf_sha256) #pragma redefine_extname EVP_hpke_x25519_hkdf_sha256 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_hpke_x25519_hkdf_sha256) #pragma redefine_extname EVP_hpke_xwing BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_hpke_xwing) +#pragma redefine_extname EVP_kem_dhkem_p256_hkdf_sha256 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_kem_dhkem_p256_hkdf_sha256) +#pragma redefine_extname EVP_kem_dhkem_x25519_hkdf_sha256 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_kem_dhkem_x25519_hkdf_sha256) #pragma redefine_extname EVP_kem_ml_kem_1024 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_kem_ml_kem_1024) #pragma redefine_extname EVP_kem_ml_kem_768 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_kem_ml_kem_768) #pragma redefine_extname EVP_kem_xwing BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_kem_xwing) @@ -1338,6 +1355,7 @@ #pragma redefine_extname EVP_marshal_digest_algorithm_no_params BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_marshal_digest_algorithm_no_params) #pragma redefine_extname EVP_marshal_private_key BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_marshal_private_key) #pragma redefine_extname EVP_marshal_public_key BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_marshal_public_key) +#pragma redefine_extname EVP_marshal_public_key_with_ec_point_format BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_marshal_public_key_with_ec_point_format) #pragma redefine_extname EVP_md4 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_md4) #pragma redefine_extname EVP_md5 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_md5) #pragma redefine_extname EVP_md5_sha1 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_md5_sha1) @@ -1360,6 +1378,9 @@ #pragma redefine_extname EVP_pkey_rsa_pss_sha256 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_pkey_rsa_pss_sha256) #pragma redefine_extname EVP_pkey_rsa_pss_sha384 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_pkey_rsa_pss_sha384) #pragma redefine_extname EVP_pkey_rsa_pss_sha512 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_pkey_rsa_pss_sha512) +#pragma redefine_extname EVP_pkey_slh_dsa_sha2_128s BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_pkey_slh_dsa_sha2_128s) +#pragma redefine_extname EVP_pkey_slh_dsa_sha2_128s_with_sha256 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_pkey_slh_dsa_sha2_128s_with_sha256) +#pragma redefine_extname EVP_pkey_slh_dsa_shake_256f BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_pkey_slh_dsa_shake_256f) #pragma redefine_extname EVP_pkey_x25519 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_pkey_x25519) #pragma redefine_extname EVP_pkey_xwing BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_pkey_xwing) #pragma redefine_extname EVP_rc2_40_cbc BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_rc2_40_cbc) @@ -1369,8 +1390,15 @@ #pragma redefine_extname EVP_sha224 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_sha224) #pragma redefine_extname EVP_sha256 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_sha256) #pragma redefine_extname EVP_sha384 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_sha384) +#pragma redefine_extname EVP_sha3_256 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_sha3_256) +#pragma redefine_extname EVP_sha3_384 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_sha3_384) +#pragma redefine_extname EVP_sha3_512 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_sha3_512) #pragma redefine_extname EVP_sha512 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_sha512) #pragma redefine_extname EVP_sha512_256 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_sha512_256) +#pragma redefine_extname EVP_shake128 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_shake128) +#pragma redefine_extname EVP_shake256 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_shake256) +#pragma redefine_extname EVP_turboshake128 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_turboshake128) +#pragma redefine_extname EVP_turboshake256 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EVP_turboshake256) #pragma redefine_extname EXTENDED_KEY_USAGE_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EXTENDED_KEY_USAGE_free) #pragma redefine_extname EXTENDED_KEY_USAGE_it BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EXTENDED_KEY_USAGE_it) #pragma redefine_extname EXTENDED_KEY_USAGE_new BORINGSSL_ADD_USER_LABEL_AND_PREFIX(EXTENDED_KEY_USAGE_new) @@ -1429,6 +1457,8 @@ #pragma redefine_extname MD5_Init BORINGSSL_ADD_USER_LABEL_AND_PREFIX(MD5_Init) #pragma redefine_extname MD5_Transform BORINGSSL_ADD_USER_LABEL_AND_PREFIX(MD5_Transform) #pragma redefine_extname MD5_Update BORINGSSL_ADD_USER_LABEL_AND_PREFIX(MD5_Update) +#pragma redefine_extname MD5_marshal_state BORINGSSL_ADD_USER_LABEL_AND_PREFIX(MD5_marshal_state) +#pragma redefine_extname MD5_parse_state BORINGSSL_ADD_USER_LABEL_AND_PREFIX(MD5_parse_state) #pragma redefine_extname METHOD_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(METHOD_ref) #pragma redefine_extname METHOD_unref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(METHOD_unref) #pragma redefine_extname MLDSA44_generate_key BORINGSSL_ADD_USER_LABEL_AND_PREFIX(MLDSA44_generate_key) @@ -1766,6 +1796,7 @@ #pragma redefine_extname RSA_check_fips BORINGSSL_ADD_USER_LABEL_AND_PREFIX(RSA_check_fips) #pragma redefine_extname RSA_check_key BORINGSSL_ADD_USER_LABEL_AND_PREFIX(RSA_check_key) #pragma redefine_extname RSA_decrypt BORINGSSL_ADD_USER_LABEL_AND_PREFIX(RSA_decrypt) +#pragma redefine_extname RSA_dup_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(RSA_dup_ref) #pragma redefine_extname RSA_encrypt BORINGSSL_ADD_USER_LABEL_AND_PREFIX(RSA_encrypt) #pragma redefine_extname RSA_flags BORINGSSL_ADD_USER_LABEL_AND_PREFIX(RSA_flags) #pragma redefine_extname RSA_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(RSA_free) @@ -1828,27 +1859,21 @@ #pragma redefine_extname RSA_verify_PKCS1_PSS_mgf1 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(RSA_verify_PKCS1_PSS_mgf1) #pragma redefine_extname RSA_verify_pss_mgf1 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(RSA_verify_pss_mgf1) #pragma redefine_extname RSA_verify_raw BORINGSSL_ADD_USER_LABEL_AND_PREFIX(RSA_verify_raw) -#pragma redefine_extname SHA1 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA1) #pragma redefine_extname SHA1_Final BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA1_Final) #pragma redefine_extname SHA1_Init BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA1_Init) #pragma redefine_extname SHA1_Transform BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA1_Transform) #pragma redefine_extname SHA1_Update BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA1_Update) -#pragma redefine_extname SHA224 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA224) #pragma redefine_extname SHA224_Final BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA224_Final) #pragma redefine_extname SHA224_Init BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA224_Init) #pragma redefine_extname SHA224_Update BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA224_Update) -#pragma redefine_extname SHA256 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA256) #pragma redefine_extname SHA256_Final BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA256_Final) #pragma redefine_extname SHA256_Init BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA256_Init) #pragma redefine_extname SHA256_Transform BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA256_Transform) #pragma redefine_extname SHA256_TransformBlocks BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA256_TransformBlocks) #pragma redefine_extname SHA256_Update BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA256_Update) -#pragma redefine_extname SHA384 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA384) #pragma redefine_extname SHA384_Final BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA384_Final) #pragma redefine_extname SHA384_Init BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA384_Init) #pragma redefine_extname SHA384_Update BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA384_Update) -#pragma redefine_extname SHA512 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA512) -#pragma redefine_extname SHA512_256 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA512_256) #pragma redefine_extname SHA512_256_Final BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA512_256_Final) #pragma redefine_extname SHA512_256_Init BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA512_256_Init) #pragma redefine_extname SHA512_256_Update BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SHA512_256_Update) @@ -1899,7 +1924,7 @@ #pragma redefine_extname SSL_COMP_get_compression_methods BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_COMP_get_compression_methods) #pragma redefine_extname SSL_COMP_get_id BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_COMP_get_id) #pragma redefine_extname SSL_COMP_get_name BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_COMP_get_name) -#pragma redefine_extname SSL_CREDENTIAL_add1_trust_anchor_group_inclusion BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CREDENTIAL_add1_trust_anchor_group_inclusion) +#pragma redefine_extname SSL_CREDENTIAL_add1_trust_anchor_group BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CREDENTIAL_add1_trust_anchor_group) #pragma redefine_extname SSL_CREDENTIAL_dup_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CREDENTIAL_dup_ref) #pragma redefine_extname SSL_CREDENTIAL_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CREDENTIAL_free) #pragma redefine_extname SSL_CREDENTIAL_get0_pre_shared_key_id BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CREDENTIAL_get0_pre_shared_key_id) @@ -1939,6 +1964,7 @@ #pragma redefine_extname SSL_CTX_clear_extra_chain_certs BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_clear_extra_chain_certs) #pragma redefine_extname SSL_CTX_clear_mode BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_clear_mode) #pragma redefine_extname SSL_CTX_clear_options BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_clear_options) +#pragma redefine_extname SSL_CTX_dup_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_dup_ref) #pragma redefine_extname SSL_CTX_enable_ocsp_stapling BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_enable_ocsp_stapling) #pragma redefine_extname SSL_CTX_enable_signed_cert_timestamps BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_enable_signed_cert_timestamps) #pragma redefine_extname SSL_CTX_enable_tls_channel_id BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_enable_tls_channel_id) @@ -2044,7 +2070,6 @@ #pragma redefine_extname SSL_CTX_set_ex_data BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_set_ex_data) #pragma redefine_extname SSL_CTX_set_false_start_allowed_without_alpn BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_set_false_start_allowed_without_alpn) #pragma redefine_extname SSL_CTX_set_grease_enabled BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_set_grease_enabled) -#pragma redefine_extname SSL_CTX_set_grease_sigalgs_enabled BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_set_grease_sigalgs_enabled) #pragma redefine_extname SSL_CTX_set_info_callback BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_set_info_callback) #pragma redefine_extname SSL_CTX_set_keylog_callback BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_set_keylog_callback) #pragma redefine_extname SSL_CTX_set_max_cert_list BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_set_max_cert_list) @@ -2111,12 +2136,14 @@ #pragma redefine_extname SSL_CTX_use_certificate_file BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_use_certificate_file) #pragma redefine_extname SSL_CTX_use_psk_identity_hint BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_use_psk_identity_hint) #pragma redefine_extname SSL_ECH_KEYS_add BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_ECH_KEYS_add) +#pragma redefine_extname SSL_ECH_KEYS_dup_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_ECH_KEYS_dup_ref) #pragma redefine_extname SSL_ECH_KEYS_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_ECH_KEYS_free) #pragma redefine_extname SSL_ECH_KEYS_has_duplicate_config_id BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_ECH_KEYS_has_duplicate_config_id) #pragma redefine_extname SSL_ECH_KEYS_marshal_retry_configs BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_ECH_KEYS_marshal_retry_configs) #pragma redefine_extname SSL_ECH_KEYS_new BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_ECH_KEYS_new) #pragma redefine_extname SSL_ECH_KEYS_up_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_ECH_KEYS_up_ref) #pragma redefine_extname SSL_SESSION_copy_without_early_data BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_SESSION_copy_without_early_data) +#pragma redefine_extname SSL_SESSION_dup_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_SESSION_dup_ref) #pragma redefine_extname SSL_SESSION_early_data_capable BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_SESSION_early_data_capable) #pragma redefine_extname SSL_SESSION_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_SESSION_free) #pragma redefine_extname SSL_SESSION_from_bytes BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_SESSION_from_bytes) @@ -2567,6 +2594,7 @@ #pragma redefine_extname X509_CRL_delete_ext BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_CRL_delete_ext) #pragma redefine_extname X509_CRL_digest BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_CRL_digest) #pragma redefine_extname X509_CRL_dup BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_CRL_dup) +#pragma redefine_extname X509_CRL_dup_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_CRL_dup_ref) #pragma redefine_extname X509_CRL_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_CRL_free) #pragma redefine_extname X509_CRL_get0_by_cert BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_CRL_get0_by_cert) #pragma redefine_extname X509_CRL_get0_by_serial BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_CRL_get0_by_serial) @@ -2733,7 +2761,6 @@ #pragma redefine_extname X509_STORE_CTX_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_STORE_CTX_free) #pragma redefine_extname X509_STORE_CTX_get0_cert BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_STORE_CTX_get0_cert) #pragma redefine_extname X509_STORE_CTX_get0_chain BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_STORE_CTX_get0_chain) -#pragma redefine_extname X509_STORE_CTX_get0_current_crl BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_STORE_CTX_get0_current_crl) #pragma redefine_extname X509_STORE_CTX_get0_param BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_STORE_CTX_get0_param) #pragma redefine_extname X509_STORE_CTX_get0_parent_ctx BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_STORE_CTX_get0_parent_ctx) #pragma redefine_extname X509_STORE_CTX_get0_store BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_STORE_CTX_get0_store) @@ -2769,6 +2796,7 @@ #pragma redefine_extname X509_STORE_add_cert BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_STORE_add_cert) #pragma redefine_extname X509_STORE_add_crl BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_STORE_add_crl) #pragma redefine_extname X509_STORE_add_lookup BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_STORE_add_lookup) +#pragma redefine_extname X509_STORE_dup_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_STORE_dup_ref) #pragma redefine_extname X509_STORE_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_STORE_free) #pragma redefine_extname X509_STORE_get0_objects BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_STORE_get0_objects) #pragma redefine_extname X509_STORE_get0_param BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_STORE_get0_param) @@ -2907,6 +2935,7 @@ #pragma redefine_extname X509_set_pubkey BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_set_pubkey) #pragma redefine_extname X509_set_serialNumber BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_set_serialNumber) #pragma redefine_extname X509_set_subject_name BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_set_subject_name) +#pragma redefine_extname X509_set_unsigned BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_set_unsigned) #pragma redefine_extname X509_set_version BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_set_version) #pragma redefine_extname X509_sign BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_sign) #pragma redefine_extname X509_sign_ctx BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_sign_ctx) @@ -3280,6 +3309,7 @@ #define ASN1_STRING_free BORINGSSL_ADD_PREFIX(ASN1_STRING_free) #define ASN1_STRING_get0_data BORINGSSL_ADD_PREFIX(ASN1_STRING_get0_data) #define ASN1_STRING_get_default_mask BORINGSSL_ADD_PREFIX(ASN1_STRING_get_default_mask) +#define ASN1_STRING_get_length BORINGSSL_ADD_PREFIX(ASN1_STRING_get_length) #define ASN1_STRING_length BORINGSSL_ADD_PREFIX(ASN1_STRING_length) #define ASN1_STRING_new BORINGSSL_ADD_PREFIX(ASN1_STRING_new) #define ASN1_STRING_print BORINGSSL_ADD_PREFIX(ASN1_STRING_print) @@ -3287,6 +3317,7 @@ #define ASN1_STRING_print_ex_fp BORINGSSL_ADD_PREFIX(ASN1_STRING_print_ex_fp) #define ASN1_STRING_set BORINGSSL_ADD_PREFIX(ASN1_STRING_set) #define ASN1_STRING_set0 BORINGSSL_ADD_PREFIX(ASN1_STRING_set0) +#define ASN1_STRING_set1_data BORINGSSL_ADD_PREFIX(ASN1_STRING_set1_data) #define ASN1_STRING_set_by_NID BORINGSSL_ADD_PREFIX(ASN1_STRING_set_by_NID) #define ASN1_STRING_set_default_mask BORINGSSL_ADD_PREFIX(ASN1_STRING_set_default_mask) #define ASN1_STRING_set_default_mask_asc BORINGSSL_ADD_PREFIX(ASN1_STRING_set_default_mask_asc) @@ -3382,6 +3413,7 @@ #define BIO_ctrl_get_write_guarantee BORINGSSL_ADD_PREFIX(BIO_ctrl_get_write_guarantee) #define BIO_ctrl_pending BORINGSSL_ADD_PREFIX(BIO_ctrl_pending) #define BIO_do_connect BORINGSSL_ADD_PREFIX(BIO_do_connect) +#define BIO_dup_ref BORINGSSL_ADD_PREFIX(BIO_dup_ref) #define BIO_eof BORINGSSL_ADD_PREFIX(BIO_eof) #define BIO_f_base64 BORINGSSL_ADD_PREFIX(BIO_f_base64) #define BIO_f_ssl BORINGSSL_ADD_PREFIX(BIO_f_ssl) @@ -3740,6 +3772,7 @@ #define CBS_is_valid_asn1_integer BORINGSSL_ADD_PREFIX(CBS_is_valid_asn1_integer) #define CBS_is_valid_asn1_oid BORINGSSL_ADD_PREFIX(CBS_is_valid_asn1_oid) #define CBS_is_valid_asn1_relative_oid BORINGSSL_ADD_PREFIX(CBS_is_valid_asn1_relative_oid) +#define CBS_is_valid_asn1_set_of BORINGSSL_ADD_PREFIX(CBS_is_valid_asn1_set_of) #define CBS_mem_equal BORINGSSL_ADD_PREFIX(CBS_mem_equal) #define CBS_parse_generalized_time BORINGSSL_ADD_PREFIX(CBS_parse_generalized_time) #define CBS_parse_utc_time BORINGSSL_ADD_PREFIX(CBS_parse_utc_time) @@ -3765,9 +3798,14 @@ #define CONF_modules_free BORINGSSL_ADD_PREFIX(CONF_modules_free) #define CONF_modules_load_file BORINGSSL_ADD_PREFIX(CONF_modules_load_file) #define CONF_modules_unload BORINGSSL_ADD_PREFIX(CONF_modules_unload) +#define CPACE_CTX_free BORINGSSL_ADD_PREFIX(CPACE_CTX_free) +#define CPACE_CTX_new BORINGSSL_ADD_PREFIX(CPACE_CTX_new) +#define CPACE_generate_msg BORINGSSL_ADD_PREFIX(CPACE_generate_msg) +#define CPACE_process_msg BORINGSSL_ADD_PREFIX(CPACE_process_msg) #define CRL_DIST_POINTS_free BORINGSSL_ADD_PREFIX(CRL_DIST_POINTS_free) #define CRL_DIST_POINTS_it BORINGSSL_ADD_PREFIX(CRL_DIST_POINTS_it) #define CRL_DIST_POINTS_new BORINGSSL_ADD_PREFIX(CRL_DIST_POINTS_new) +#define CRYPTO_BUFFER_POOL_dup_ref BORINGSSL_ADD_PREFIX(CRYPTO_BUFFER_POOL_dup_ref) #define CRYPTO_BUFFER_POOL_free BORINGSSL_ADD_PREFIX(CRYPTO_BUFFER_POOL_free) #define CRYPTO_BUFFER_POOL_new BORINGSSL_ADD_PREFIX(CRYPTO_BUFFER_POOL_new) #define CRYPTO_BUFFER_POOL_up_ref BORINGSSL_ADD_PREFIX(CRYPTO_BUFFER_POOL_up_ref) @@ -3842,6 +3880,7 @@ #define DH_compute_key BORINGSSL_ADD_PREFIX(DH_compute_key) #define DH_compute_key_hashed BORINGSSL_ADD_PREFIX(DH_compute_key_hashed) #define DH_compute_key_padded BORINGSSL_ADD_PREFIX(DH_compute_key_padded) +#define DH_dup_ref BORINGSSL_ADD_PREFIX(DH_dup_ref) #define DH_free BORINGSSL_ADD_PREFIX(DH_free) #define DH_generate_key BORINGSSL_ADD_PREFIX(DH_generate_key) #define DH_generate_parameters BORINGSSL_ADD_PREFIX(DH_generate_parameters) @@ -3883,6 +3922,7 @@ #define DSA_do_sign BORINGSSL_ADD_PREFIX(DSA_do_sign) #define DSA_do_verify BORINGSSL_ADD_PREFIX(DSA_do_verify) #define DSA_dup_DH BORINGSSL_ADD_PREFIX(DSA_dup_DH) +#define DSA_dup_ref BORINGSSL_ADD_PREFIX(DSA_dup_ref) #define DSA_free BORINGSSL_ADD_PREFIX(DSA_free) #define DSA_generate_key BORINGSSL_ADD_PREFIX(DSA_generate_key) #define DSA_generate_parameters BORINGSSL_ADD_PREFIX(DSA_generate_parameters) @@ -3968,6 +4008,7 @@ #define EC_KEY_check_key BORINGSSL_ADD_PREFIX(EC_KEY_check_key) #define EC_KEY_derive_from_secret BORINGSSL_ADD_PREFIX(EC_KEY_derive_from_secret) #define EC_KEY_dup BORINGSSL_ADD_PREFIX(EC_KEY_dup) +#define EC_KEY_dup_ref BORINGSSL_ADD_PREFIX(EC_KEY_dup_ref) #define EC_KEY_free BORINGSSL_ADD_PREFIX(EC_KEY_free) #define EC_KEY_generate_key BORINGSSL_ADD_PREFIX(EC_KEY_generate_key) #define EC_KEY_generate_key_fips BORINGSSL_ADD_PREFIX(EC_KEY_generate_key_fips) @@ -4172,6 +4213,7 @@ #define EVP_DigestSignFinal BORINGSSL_ADD_PREFIX(EVP_DigestSignFinal) #define EVP_DigestSignInit BORINGSSL_ADD_PREFIX(EVP_DigestSignInit) #define EVP_DigestSignUpdate BORINGSSL_ADD_PREFIX(EVP_DigestSignUpdate) +#define EVP_DigestSqueeze BORINGSSL_ADD_PREFIX(EVP_DigestSqueeze) #define EVP_DigestUpdate BORINGSSL_ADD_PREFIX(EVP_DigestUpdate) #define EVP_DigestVerify BORINGSSL_ADD_PREFIX(EVP_DigestVerify) #define EVP_DigestVerifyFinal BORINGSSL_ADD_PREFIX(EVP_DigestVerifyFinal) @@ -4207,6 +4249,7 @@ #define EVP_HPKE_CTX_setup_auth_sender BORINGSSL_ADD_PREFIX(EVP_HPKE_CTX_setup_auth_sender) #define EVP_HPKE_CTX_setup_auth_sender_with_seed_for_testing BORINGSSL_ADD_PREFIX(EVP_HPKE_CTX_setup_auth_sender_with_seed_for_testing) #define EVP_HPKE_CTX_setup_recipient BORINGSSL_ADD_PREFIX(EVP_HPKE_CTX_setup_recipient) +#define EVP_HPKE_CTX_setup_recipient_with_shared_secret BORINGSSL_ADD_PREFIX(EVP_HPKE_CTX_setup_recipient_with_shared_secret) #define EVP_HPKE_CTX_setup_sender BORINGSSL_ADD_PREFIX(EVP_HPKE_CTX_setup_sender) #define EVP_HPKE_CTX_setup_sender_with_seed_for_testing BORINGSSL_ADD_PREFIX(EVP_HPKE_CTX_setup_sender_with_seed_for_testing) #define EVP_HPKE_CTX_zero BORINGSSL_ADD_PREFIX(EVP_HPKE_CTX_zero) @@ -4216,6 +4259,7 @@ #define EVP_HPKE_KEM_id BORINGSSL_ADD_PREFIX(EVP_HPKE_KEM_id) #define EVP_HPKE_KEM_private_key_len BORINGSSL_ADD_PREFIX(EVP_HPKE_KEM_private_key_len) #define EVP_HPKE_KEM_public_key_len BORINGSSL_ADD_PREFIX(EVP_HPKE_KEM_public_key_len) +#define EVP_HPKE_KEM_shared_secret_len BORINGSSL_ADD_PREFIX(EVP_HPKE_KEM_shared_secret_len) #define EVP_HPKE_KEY_cleanup BORINGSSL_ADD_PREFIX(EVP_HPKE_KEY_cleanup) #define EVP_HPKE_KEY_copy BORINGSSL_ADD_PREFIX(EVP_HPKE_KEY_copy) #define EVP_HPKE_KEY_derive BORINGSSL_ADD_PREFIX(EVP_HPKE_KEY_derive) @@ -4481,6 +4525,8 @@ #define EVP_hpke_p256_hkdf_sha256 BORINGSSL_ADD_PREFIX(EVP_hpke_p256_hkdf_sha256) #define EVP_hpke_x25519_hkdf_sha256 BORINGSSL_ADD_PREFIX(EVP_hpke_x25519_hkdf_sha256) #define EVP_hpke_xwing BORINGSSL_ADD_PREFIX(EVP_hpke_xwing) +#define EVP_kem_dhkem_p256_hkdf_sha256 BORINGSSL_ADD_PREFIX(EVP_kem_dhkem_p256_hkdf_sha256) +#define EVP_kem_dhkem_x25519_hkdf_sha256 BORINGSSL_ADD_PREFIX(EVP_kem_dhkem_x25519_hkdf_sha256) #define EVP_kem_ml_kem_1024 BORINGSSL_ADD_PREFIX(EVP_kem_ml_kem_1024) #define EVP_kem_ml_kem_768 BORINGSSL_ADD_PREFIX(EVP_kem_ml_kem_768) #define EVP_kem_xwing BORINGSSL_ADD_PREFIX(EVP_kem_xwing) @@ -4488,6 +4534,7 @@ #define EVP_marshal_digest_algorithm_no_params BORINGSSL_ADD_PREFIX(EVP_marshal_digest_algorithm_no_params) #define EVP_marshal_private_key BORINGSSL_ADD_PREFIX(EVP_marshal_private_key) #define EVP_marshal_public_key BORINGSSL_ADD_PREFIX(EVP_marshal_public_key) +#define EVP_marshal_public_key_with_ec_point_format BORINGSSL_ADD_PREFIX(EVP_marshal_public_key_with_ec_point_format) #define EVP_md4 BORINGSSL_ADD_PREFIX(EVP_md4) #define EVP_md5 BORINGSSL_ADD_PREFIX(EVP_md5) #define EVP_md5_sha1 BORINGSSL_ADD_PREFIX(EVP_md5_sha1) @@ -4510,6 +4557,9 @@ #define EVP_pkey_rsa_pss_sha256 BORINGSSL_ADD_PREFIX(EVP_pkey_rsa_pss_sha256) #define EVP_pkey_rsa_pss_sha384 BORINGSSL_ADD_PREFIX(EVP_pkey_rsa_pss_sha384) #define EVP_pkey_rsa_pss_sha512 BORINGSSL_ADD_PREFIX(EVP_pkey_rsa_pss_sha512) +#define EVP_pkey_slh_dsa_sha2_128s BORINGSSL_ADD_PREFIX(EVP_pkey_slh_dsa_sha2_128s) +#define EVP_pkey_slh_dsa_sha2_128s_with_sha256 BORINGSSL_ADD_PREFIX(EVP_pkey_slh_dsa_sha2_128s_with_sha256) +#define EVP_pkey_slh_dsa_shake_256f BORINGSSL_ADD_PREFIX(EVP_pkey_slh_dsa_shake_256f) #define EVP_pkey_x25519 BORINGSSL_ADD_PREFIX(EVP_pkey_x25519) #define EVP_pkey_xwing BORINGSSL_ADD_PREFIX(EVP_pkey_xwing) #define EVP_rc2_40_cbc BORINGSSL_ADD_PREFIX(EVP_rc2_40_cbc) @@ -4519,8 +4569,15 @@ #define EVP_sha224 BORINGSSL_ADD_PREFIX(EVP_sha224) #define EVP_sha256 BORINGSSL_ADD_PREFIX(EVP_sha256) #define EVP_sha384 BORINGSSL_ADD_PREFIX(EVP_sha384) +#define EVP_sha3_256 BORINGSSL_ADD_PREFIX(EVP_sha3_256) +#define EVP_sha3_384 BORINGSSL_ADD_PREFIX(EVP_sha3_384) +#define EVP_sha3_512 BORINGSSL_ADD_PREFIX(EVP_sha3_512) #define EVP_sha512 BORINGSSL_ADD_PREFIX(EVP_sha512) #define EVP_sha512_256 BORINGSSL_ADD_PREFIX(EVP_sha512_256) +#define EVP_shake128 BORINGSSL_ADD_PREFIX(EVP_shake128) +#define EVP_shake256 BORINGSSL_ADD_PREFIX(EVP_shake256) +#define EVP_turboshake128 BORINGSSL_ADD_PREFIX(EVP_turboshake128) +#define EVP_turboshake256 BORINGSSL_ADD_PREFIX(EVP_turboshake256) #define EXTENDED_KEY_USAGE_free BORINGSSL_ADD_PREFIX(EXTENDED_KEY_USAGE_free) #define EXTENDED_KEY_USAGE_it BORINGSSL_ADD_PREFIX(EXTENDED_KEY_USAGE_it) #define EXTENDED_KEY_USAGE_new BORINGSSL_ADD_PREFIX(EXTENDED_KEY_USAGE_new) @@ -4579,6 +4636,8 @@ #define MD5_Init BORINGSSL_ADD_PREFIX(MD5_Init) #define MD5_Transform BORINGSSL_ADD_PREFIX(MD5_Transform) #define MD5_Update BORINGSSL_ADD_PREFIX(MD5_Update) +#define MD5_marshal_state BORINGSSL_ADD_PREFIX(MD5_marshal_state) +#define MD5_parse_state BORINGSSL_ADD_PREFIX(MD5_parse_state) #define METHOD_ref BORINGSSL_ADD_PREFIX(METHOD_ref) #define METHOD_unref BORINGSSL_ADD_PREFIX(METHOD_unref) #define MLDSA44_generate_key BORINGSSL_ADD_PREFIX(MLDSA44_generate_key) @@ -4916,6 +4975,7 @@ #define RSA_check_fips BORINGSSL_ADD_PREFIX(RSA_check_fips) #define RSA_check_key BORINGSSL_ADD_PREFIX(RSA_check_key) #define RSA_decrypt BORINGSSL_ADD_PREFIX(RSA_decrypt) +#define RSA_dup_ref BORINGSSL_ADD_PREFIX(RSA_dup_ref) #define RSA_encrypt BORINGSSL_ADD_PREFIX(RSA_encrypt) #define RSA_flags BORINGSSL_ADD_PREFIX(RSA_flags) #define RSA_free BORINGSSL_ADD_PREFIX(RSA_free) @@ -4978,27 +5038,21 @@ #define RSA_verify_PKCS1_PSS_mgf1 BORINGSSL_ADD_PREFIX(RSA_verify_PKCS1_PSS_mgf1) #define RSA_verify_pss_mgf1 BORINGSSL_ADD_PREFIX(RSA_verify_pss_mgf1) #define RSA_verify_raw BORINGSSL_ADD_PREFIX(RSA_verify_raw) -#define SHA1 BORINGSSL_ADD_PREFIX(SHA1) #define SHA1_Final BORINGSSL_ADD_PREFIX(SHA1_Final) #define SHA1_Init BORINGSSL_ADD_PREFIX(SHA1_Init) #define SHA1_Transform BORINGSSL_ADD_PREFIX(SHA1_Transform) #define SHA1_Update BORINGSSL_ADD_PREFIX(SHA1_Update) -#define SHA224 BORINGSSL_ADD_PREFIX(SHA224) #define SHA224_Final BORINGSSL_ADD_PREFIX(SHA224_Final) #define SHA224_Init BORINGSSL_ADD_PREFIX(SHA224_Init) #define SHA224_Update BORINGSSL_ADD_PREFIX(SHA224_Update) -#define SHA256 BORINGSSL_ADD_PREFIX(SHA256) #define SHA256_Final BORINGSSL_ADD_PREFIX(SHA256_Final) #define SHA256_Init BORINGSSL_ADD_PREFIX(SHA256_Init) #define SHA256_Transform BORINGSSL_ADD_PREFIX(SHA256_Transform) #define SHA256_TransformBlocks BORINGSSL_ADD_PREFIX(SHA256_TransformBlocks) #define SHA256_Update BORINGSSL_ADD_PREFIX(SHA256_Update) -#define SHA384 BORINGSSL_ADD_PREFIX(SHA384) #define SHA384_Final BORINGSSL_ADD_PREFIX(SHA384_Final) #define SHA384_Init BORINGSSL_ADD_PREFIX(SHA384_Init) #define SHA384_Update BORINGSSL_ADD_PREFIX(SHA384_Update) -#define SHA512 BORINGSSL_ADD_PREFIX(SHA512) -#define SHA512_256 BORINGSSL_ADD_PREFIX(SHA512_256) #define SHA512_256_Final BORINGSSL_ADD_PREFIX(SHA512_256_Final) #define SHA512_256_Init BORINGSSL_ADD_PREFIX(SHA512_256_Init) #define SHA512_256_Update BORINGSSL_ADD_PREFIX(SHA512_256_Update) @@ -5049,7 +5103,7 @@ #define SSL_COMP_get_compression_methods BORINGSSL_ADD_PREFIX(SSL_COMP_get_compression_methods) #define SSL_COMP_get_id BORINGSSL_ADD_PREFIX(SSL_COMP_get_id) #define SSL_COMP_get_name BORINGSSL_ADD_PREFIX(SSL_COMP_get_name) -#define SSL_CREDENTIAL_add1_trust_anchor_group_inclusion BORINGSSL_ADD_PREFIX(SSL_CREDENTIAL_add1_trust_anchor_group_inclusion) +#define SSL_CREDENTIAL_add1_trust_anchor_group BORINGSSL_ADD_PREFIX(SSL_CREDENTIAL_add1_trust_anchor_group) #define SSL_CREDENTIAL_dup_ref BORINGSSL_ADD_PREFIX(SSL_CREDENTIAL_dup_ref) #define SSL_CREDENTIAL_free BORINGSSL_ADD_PREFIX(SSL_CREDENTIAL_free) #define SSL_CREDENTIAL_get0_pre_shared_key_id BORINGSSL_ADD_PREFIX(SSL_CREDENTIAL_get0_pre_shared_key_id) @@ -5089,6 +5143,7 @@ #define SSL_CTX_clear_extra_chain_certs BORINGSSL_ADD_PREFIX(SSL_CTX_clear_extra_chain_certs) #define SSL_CTX_clear_mode BORINGSSL_ADD_PREFIX(SSL_CTX_clear_mode) #define SSL_CTX_clear_options BORINGSSL_ADD_PREFIX(SSL_CTX_clear_options) +#define SSL_CTX_dup_ref BORINGSSL_ADD_PREFIX(SSL_CTX_dup_ref) #define SSL_CTX_enable_ocsp_stapling BORINGSSL_ADD_PREFIX(SSL_CTX_enable_ocsp_stapling) #define SSL_CTX_enable_signed_cert_timestamps BORINGSSL_ADD_PREFIX(SSL_CTX_enable_signed_cert_timestamps) #define SSL_CTX_enable_tls_channel_id BORINGSSL_ADD_PREFIX(SSL_CTX_enable_tls_channel_id) @@ -5194,7 +5249,6 @@ #define SSL_CTX_set_ex_data BORINGSSL_ADD_PREFIX(SSL_CTX_set_ex_data) #define SSL_CTX_set_false_start_allowed_without_alpn BORINGSSL_ADD_PREFIX(SSL_CTX_set_false_start_allowed_without_alpn) #define SSL_CTX_set_grease_enabled BORINGSSL_ADD_PREFIX(SSL_CTX_set_grease_enabled) -#define SSL_CTX_set_grease_sigalgs_enabled BORINGSSL_ADD_PREFIX(SSL_CTX_set_grease_sigalgs_enabled) #define SSL_CTX_set_info_callback BORINGSSL_ADD_PREFIX(SSL_CTX_set_info_callback) #define SSL_CTX_set_keylog_callback BORINGSSL_ADD_PREFIX(SSL_CTX_set_keylog_callback) #define SSL_CTX_set_max_cert_list BORINGSSL_ADD_PREFIX(SSL_CTX_set_max_cert_list) @@ -5261,12 +5315,14 @@ #define SSL_CTX_use_certificate_file BORINGSSL_ADD_PREFIX(SSL_CTX_use_certificate_file) #define SSL_CTX_use_psk_identity_hint BORINGSSL_ADD_PREFIX(SSL_CTX_use_psk_identity_hint) #define SSL_ECH_KEYS_add BORINGSSL_ADD_PREFIX(SSL_ECH_KEYS_add) +#define SSL_ECH_KEYS_dup_ref BORINGSSL_ADD_PREFIX(SSL_ECH_KEYS_dup_ref) #define SSL_ECH_KEYS_free BORINGSSL_ADD_PREFIX(SSL_ECH_KEYS_free) #define SSL_ECH_KEYS_has_duplicate_config_id BORINGSSL_ADD_PREFIX(SSL_ECH_KEYS_has_duplicate_config_id) #define SSL_ECH_KEYS_marshal_retry_configs BORINGSSL_ADD_PREFIX(SSL_ECH_KEYS_marshal_retry_configs) #define SSL_ECH_KEYS_new BORINGSSL_ADD_PREFIX(SSL_ECH_KEYS_new) #define SSL_ECH_KEYS_up_ref BORINGSSL_ADD_PREFIX(SSL_ECH_KEYS_up_ref) #define SSL_SESSION_copy_without_early_data BORINGSSL_ADD_PREFIX(SSL_SESSION_copy_without_early_data) +#define SSL_SESSION_dup_ref BORINGSSL_ADD_PREFIX(SSL_SESSION_dup_ref) #define SSL_SESSION_early_data_capable BORINGSSL_ADD_PREFIX(SSL_SESSION_early_data_capable) #define SSL_SESSION_free BORINGSSL_ADD_PREFIX(SSL_SESSION_free) #define SSL_SESSION_from_bytes BORINGSSL_ADD_PREFIX(SSL_SESSION_from_bytes) @@ -5717,6 +5773,7 @@ #define X509_CRL_delete_ext BORINGSSL_ADD_PREFIX(X509_CRL_delete_ext) #define X509_CRL_digest BORINGSSL_ADD_PREFIX(X509_CRL_digest) #define X509_CRL_dup BORINGSSL_ADD_PREFIX(X509_CRL_dup) +#define X509_CRL_dup_ref BORINGSSL_ADD_PREFIX(X509_CRL_dup_ref) #define X509_CRL_free BORINGSSL_ADD_PREFIX(X509_CRL_free) #define X509_CRL_get0_by_cert BORINGSSL_ADD_PREFIX(X509_CRL_get0_by_cert) #define X509_CRL_get0_by_serial BORINGSSL_ADD_PREFIX(X509_CRL_get0_by_serial) @@ -5883,7 +5940,6 @@ #define X509_STORE_CTX_free BORINGSSL_ADD_PREFIX(X509_STORE_CTX_free) #define X509_STORE_CTX_get0_cert BORINGSSL_ADD_PREFIX(X509_STORE_CTX_get0_cert) #define X509_STORE_CTX_get0_chain BORINGSSL_ADD_PREFIX(X509_STORE_CTX_get0_chain) -#define X509_STORE_CTX_get0_current_crl BORINGSSL_ADD_PREFIX(X509_STORE_CTX_get0_current_crl) #define X509_STORE_CTX_get0_param BORINGSSL_ADD_PREFIX(X509_STORE_CTX_get0_param) #define X509_STORE_CTX_get0_parent_ctx BORINGSSL_ADD_PREFIX(X509_STORE_CTX_get0_parent_ctx) #define X509_STORE_CTX_get0_store BORINGSSL_ADD_PREFIX(X509_STORE_CTX_get0_store) @@ -5919,6 +5975,7 @@ #define X509_STORE_add_cert BORINGSSL_ADD_PREFIX(X509_STORE_add_cert) #define X509_STORE_add_crl BORINGSSL_ADD_PREFIX(X509_STORE_add_crl) #define X509_STORE_add_lookup BORINGSSL_ADD_PREFIX(X509_STORE_add_lookup) +#define X509_STORE_dup_ref BORINGSSL_ADD_PREFIX(X509_STORE_dup_ref) #define X509_STORE_free BORINGSSL_ADD_PREFIX(X509_STORE_free) #define X509_STORE_get0_objects BORINGSSL_ADD_PREFIX(X509_STORE_get0_objects) #define X509_STORE_get0_param BORINGSSL_ADD_PREFIX(X509_STORE_get0_param) @@ -6057,6 +6114,7 @@ #define X509_set_pubkey BORINGSSL_ADD_PREFIX(X509_set_pubkey) #define X509_set_serialNumber BORINGSSL_ADD_PREFIX(X509_set_serialNumber) #define X509_set_subject_name BORINGSSL_ADD_PREFIX(X509_set_subject_name) +#define X509_set_unsigned BORINGSSL_ADD_PREFIX(X509_set_unsigned) #define X509_set_version BORINGSSL_ADD_PREFIX(X509_set_version) #define X509_sign BORINGSSL_ADD_PREFIX(X509_sign) #define X509_sign_ctx BORINGSSL_ADD_PREFIX(X509_sign_ctx) diff --git a/third_party/boringssl/src/include/openssl/rsa.h b/third_party/boringssl/src/include/openssl/rsa.h index 6ff32e9..3e0682d 100644 --- a/third_party/boringssl/src/include/openssl/rsa.h +++ b/third_party/boringssl/src/include/openssl/rsa.h @@ -15,7 +15,7 @@ #ifndef OPENSSL_HEADER_RSA_H #define OPENSSL_HEADER_RSA_H -#include // IWYU pragma: export +#include // IWYU pragma: export #include #include @@ -65,6 +65,11 @@ OPENSSL_EXPORT void RSA_free(RSA *rsa); // not mutate `rsa` for thread-safety purposes and may be used concurrently. OPENSSL_EXPORT int RSA_up_ref(RSA *rsa); +// RSA_dup_ref increments the reference count of `rsa` and returns the same +// handle. It does not mutate `rsa` for thread-safety purposes and may be used +// concurrently. +OPENSSL_EXPORT RSA *RSA_dup_ref(const RSA *rsa); + // Properties. @@ -194,7 +199,7 @@ OPENSSL_EXPORT int RSA_generate_key_ex(RSA *rsa, int bits, const BIGNUM *e, // RSA_generate_key_fips behaves like `RSA_generate_key_ex` but performs // additional checks for FIPS compliance. The public exponent is always 65537 -// and `bits` must be either 2048 or 3072. +// and `bits` must be one of 2048, 3072 and 4096. OPENSSL_EXPORT int RSA_generate_key_fips(RSA *rsa, int bits, BN_GENCB *cb); @@ -832,7 +837,7 @@ extern "C++" { BSSL_NAMESPACE_BEGIN BORINGSSL_MAKE_DELETER(RSA, RSA_free) -BORINGSSL_MAKE_UP_REF(RSA, RSA_up_ref) +BORINGSSL_MAKE_UP_REF(RSA, RSA_dup_ref) BSSL_NAMESPACE_END diff --git a/third_party/boringssl/src/include/openssl/sha.h b/third_party/boringssl/src/include/openssl/sha.h index a09889f..5983ec4 100644 --- a/third_party/boringssl/src/include/openssl/sha.h +++ b/third_party/boringssl/src/include/openssl/sha.h @@ -16,6 +16,7 @@ #define OPENSSL_HEADER_SHA_H #include // IWYU pragma: export +#include // `sha.h` historically included SHA-1 and SHA-2 hash functions. So, for // backward compatibility `sha2.h` is included here. New uses of this header @@ -27,7 +28,7 @@ extern "C" { #endif -// The SHA family of hash functions (SHA-1 and SHA-2). +// The SHA-1 hash function. // SHA-1. @@ -38,29 +39,6 @@ extern "C" { // SHA_DIGEST_LENGTH is the length of a SHA-1 digest. #define SHA_DIGEST_LENGTH 20 -// SHA1_Init initialises `sha` and returns one. -OPENSSL_EXPORT int SHA1_Init(SHA_CTX *sha); - -// SHA1_Update adds `len` bytes from `data` to `sha` and returns one. -OPENSSL_EXPORT int SHA1_Update(SHA_CTX *sha, const void *data, size_t len); - -// SHA1_Final adds the final padding to `sha` and writes the resulting digest to -// `out`, which must have at least `SHA_DIGEST_LENGTH` bytes of space. It -// returns one. -OPENSSL_EXPORT int SHA1_Final(uint8_t out[SHA_DIGEST_LENGTH], SHA_CTX *sha); - -// SHA1 writes the digest of `len` bytes from `data` to `out` and returns -// `out`. There must be at least `SHA_DIGEST_LENGTH` bytes of space in -// `out`. -OPENSSL_EXPORT uint8_t *SHA1(const uint8_t *data, size_t len, - uint8_t out[SHA_DIGEST_LENGTH]); - -// SHA1_Transform is a low-level function that performs a single, SHA-1 block -// transformation using the state from `sha` and `SHA_CBLOCK` bytes from -// `block`. -OPENSSL_EXPORT void SHA1_Transform(SHA_CTX *sha, - const uint8_t block[SHA_CBLOCK]); - struct sha_state_st { #if defined(__cplusplus) || defined(OPENSSL_WINDOWS) uint32_t h[5]; @@ -84,6 +62,38 @@ struct sha_state_st { unsigned num; } /* SHA_CTX */; +// SHA1_Init initialises `sha` and returns one. +OPENSSL_EXPORT int SHA1_Init(SHA_CTX *sha); + +// SHA1_Update adds `len` bytes from `data` to `sha` and returns one. +OPENSSL_EXPORT int SHA1_Update(SHA_CTX *sha, const void *data, size_t len); + +// SHA1_Final adds the final padding to `sha` and writes the resulting digest to +// `out`, which must have at least `SHA_DIGEST_LENGTH` bytes of space. It +// returns one. +OPENSSL_EXPORT int SHA1_Final(uint8_t out[SHA_DIGEST_LENGTH], SHA_CTX *sha); + +// SHA1 writes the digest of `len` bytes from `data` to `out` and returns +// `out`. There must be at least `SHA_DIGEST_LENGTH` bytes of space in +// `out`. +// +// `static inline` to not generate such short-named linker symbols or macros. +static inline uint8_t *SHA1(const uint8_t *data, size_t len, + uint8_t out[SHA_DIGEST_LENGTH]) { + SHA_CTX ctx; + SHA1_Init(&ctx); + SHA1_Update(&ctx, data, len); + SHA1_Final(out, &ctx); + OPENSSL_cleanse(&ctx, sizeof(ctx)); + return out; +} + +// SHA1_Transform is a low-level function that performs a single, SHA-1 block +// transformation using the state from `sha` and `SHA_CBLOCK` bytes from +// `block`. +OPENSSL_EXPORT void SHA1_Transform(SHA_CTX *sha, + const uint8_t block[SHA_CBLOCK]); + // CRYPTO_fips_186_2_prf derives `out_len` bytes from `xkey` using the PRF // defined in FIPS 186-2, Appendix 3.1, with change notice 1 applied. The b // parameter is 160 and seed, XKEY, is also 160 bits. The optional XSEED user diff --git a/third_party/boringssl/src/include/openssl/sha2.h b/third_party/boringssl/src/include/openssl/sha2.h index 349d280..8d204ea 100644 --- a/third_party/boringssl/src/include/openssl/sha2.h +++ b/third_party/boringssl/src/include/openssl/sha2.h @@ -16,6 +16,7 @@ #define OPENSSL_HEADER_SHA2_H #include // IWYU pragma: export +#include #if defined(__cplusplus) extern "C" { @@ -25,7 +26,7 @@ extern "C" { // The SHA-2 family of hash functions. -// SHA-224. +// SHA-256 based hashes. // SHA224_CBLOCK is the block size of SHA-224. #define SHA224_CBLOCK 64 @@ -33,50 +34,80 @@ extern "C" { // SHA224_DIGEST_LENGTH is the length of a SHA-224 digest. #define SHA224_DIGEST_LENGTH 28 -// SHA224_Init initialises `sha` and returns 1. +// SHA256_CBLOCK is the block size of SHA-256. +#define SHA256_CBLOCK 64 + +// SHA256_DIGEST_LENGTH is the length of a SHA-256 digest. +#define SHA256_DIGEST_LENGTH 32 + +struct sha256_state_st { + uint32_t h[8]; + uint32_t Nl, Nh; + uint8_t data[SHA256_CBLOCK]; + unsigned num, md_len; +} /* SHA256_CTX */; + +// SHA224_Init initialises `sha` for SHA-224 and returns 1. OPENSSL_EXPORT int SHA224_Init(SHA256_CTX *sha); // SHA224_Update adds `len` bytes from `data` to `sha` and returns 1. +// +// `sha` must have been initialised for SHA-224. OPENSSL_EXPORT int SHA224_Update(SHA256_CTX *sha, const void *data, size_t len); // SHA224_Final adds the final padding to `sha` and writes the resulting digest // to `out`, which must have at least `SHA224_DIGEST_LENGTH` bytes of space. It // returns 1. +// +// `sha` must have been initialised for SHA-224. OPENSSL_EXPORT int SHA224_Final(uint8_t out[SHA224_DIGEST_LENGTH], SHA256_CTX *sha); // SHA224 writes the digest of `len` bytes from `data` to `out` and returns // `out`. There must be at least `SHA224_DIGEST_LENGTH` bytes of space in // `out`. -OPENSSL_EXPORT uint8_t *SHA224(const uint8_t *data, size_t len, - uint8_t out[SHA224_DIGEST_LENGTH]); - - -// SHA-256. - -// SHA256_CBLOCK is the block size of SHA-256. -#define SHA256_CBLOCK 64 - -// SHA256_DIGEST_LENGTH is the length of a SHA-256 digest. -#define SHA256_DIGEST_LENGTH 32 - -// SHA256_Init initialises `sha` and returns 1. +// +// `static inline` to not generate such short-named linker symbols or macros. +static inline uint8_t *SHA224(const uint8_t *data, size_t len, + uint8_t out[SHA224_DIGEST_LENGTH]) { + SHA256_CTX ctx; + SHA224_Init(&ctx); + SHA224_Update(&ctx, data, len); + SHA224_Final(out, &ctx); + OPENSSL_cleanse(&ctx, sizeof(ctx)); + return out; +} + +// SHA256_Init initialises `sha` for SHA-256 and returns 1. OPENSSL_EXPORT int SHA256_Init(SHA256_CTX *sha); // SHA256_Update adds `len` bytes from `data` to `sha` and returns 1. +// +// `sha` must have been initialised for SHA-256. OPENSSL_EXPORT int SHA256_Update(SHA256_CTX *sha, const void *data, size_t len); // SHA256_Final adds the final padding to `sha` and writes the resulting digest // to `out`, which must have at least `SHA256_DIGEST_LENGTH` bytes of space. It // returns one on success and zero on programmer error. +// +// `sha` must have been initialised for SHA-256. OPENSSL_EXPORT int SHA256_Final(uint8_t out[SHA256_DIGEST_LENGTH], SHA256_CTX *sha); // SHA256 writes the digest of `len` bytes from `data` to `out` and returns // `out`. There must be at least `SHA256_DIGEST_LENGTH` bytes of space in // `out`. -OPENSSL_EXPORT uint8_t *SHA256(const uint8_t *data, size_t len, - uint8_t out[SHA256_DIGEST_LENGTH]); +// +// `static inline` to not generate such short-named linker symbols or macros. +static inline uint8_t *SHA256(const uint8_t *data, size_t len, + uint8_t out[SHA256_DIGEST_LENGTH]) { + SHA256_CTX ctx; + SHA256_Init(&ctx); + SHA256_Update(&ctx, data, len); + SHA256_Final(out, &ctx); + OPENSSL_cleanse(&ctx, sizeof(ctx)); + return out; +} // SHA256_Transform is a low-level function that performs a single, SHA-256 // block transformation using the state from `sha` and `SHA256_CBLOCK` bytes @@ -92,15 +123,8 @@ OPENSSL_EXPORT void SHA256_TransformBlocks(uint32_t state[8], const uint8_t *data, size_t num_blocks); -struct sha256_state_st { - uint32_t h[8]; - uint32_t Nl, Nh; - uint8_t data[SHA256_CBLOCK]; - unsigned num, md_len; -} /* SHA256_CTX */; - -// SHA-384. +// SHA-512 based hashes. // SHA384_CBLOCK is the block size of SHA-384. #define SHA384_CBLOCK 128 @@ -108,50 +132,86 @@ struct sha256_state_st { // SHA384_DIGEST_LENGTH is the length of a SHA-384 digest. #define SHA384_DIGEST_LENGTH 48 -// SHA384_Init initialises `sha` and returns 1. +// SHA512_CBLOCK is the block size of SHA-512. +#define SHA512_CBLOCK 128 + +// SHA512_DIGEST_LENGTH is the length of a SHA-512 digest. +#define SHA512_DIGEST_LENGTH 64 + +// SHA512_256_DIGEST_LENGTH is the length of a SHA-512/256 digest. +// +// See https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf section 5.3.6 +#define SHA512_256_DIGEST_LENGTH 32 + +struct sha512_state_st { + uint64_t h[8]; + uint16_t num, md_len; + uint32_t bytes_so_far_high; + uint64_t bytes_so_far_low; + uint8_t p[SHA512_CBLOCK]; +} /* SHA512_CTX */; + +// SHA384_Init initialises `sha` for SHA-384 and returns 1. OPENSSL_EXPORT int SHA384_Init(SHA512_CTX *sha); // SHA384_Update adds `len` bytes from `data` to `sha` and returns 1. +// +// `sha` must have been initialised for SHA-384. OPENSSL_EXPORT int SHA384_Update(SHA512_CTX *sha, const void *data, size_t len); // SHA384_Final adds the final padding to `sha` and writes the resulting digest // to `out`, which must have at least `SHA384_DIGEST_LENGTH` bytes of space. It // returns one on success and zero on programmer error. +// +// `sha` must have been initialised for SHA-384. OPENSSL_EXPORT int SHA384_Final(uint8_t out[SHA384_DIGEST_LENGTH], SHA512_CTX *sha); // SHA384 writes the digest of `len` bytes from `data` to `out` and returns // `out`. There must be at least `SHA384_DIGEST_LENGTH` bytes of space in // `out`. -OPENSSL_EXPORT uint8_t *SHA384(const uint8_t *data, size_t len, - uint8_t out[SHA384_DIGEST_LENGTH]); - - -// SHA-512. - -// SHA512_CBLOCK is the block size of SHA-512. -#define SHA512_CBLOCK 128 - -// SHA512_DIGEST_LENGTH is the length of a SHA-512 digest. -#define SHA512_DIGEST_LENGTH 64 +// +// `static inline` to not generate such short-named linker symbols or macros. +static inline uint8_t *SHA384(const uint8_t *data, size_t len, + uint8_t out[SHA384_DIGEST_LENGTH]) { + SHA512_CTX ctx; + SHA384_Init(&ctx); + SHA384_Update(&ctx, data, len); + SHA384_Final(out, &ctx); + OPENSSL_cleanse(&ctx, sizeof(ctx)); + return out; +} // SHA512_Init initialises `sha` and returns 1. OPENSSL_EXPORT int SHA512_Init(SHA512_CTX *sha); // SHA512_Update adds `len` bytes from `data` to `sha` and returns 1. +// +// `sha` must have been initialised for SHA-512. OPENSSL_EXPORT int SHA512_Update(SHA512_CTX *sha, const void *data, size_t len); // SHA512_Final adds the final padding to `sha` and writes the resulting digest // to `out`, which must have at least `SHA512_DIGEST_LENGTH` bytes of space. It // returns one on success and zero on programmer error. +// +// `sha` must have been initialised for SHA-512. OPENSSL_EXPORT int SHA512_Final(uint8_t out[SHA512_DIGEST_LENGTH], SHA512_CTX *sha); // SHA512 writes the digest of `len` bytes from `data` to `out` and returns // `out`. There must be at least `SHA512_DIGEST_LENGTH` bytes of space in // `out`. -OPENSSL_EXPORT uint8_t *SHA512(const uint8_t *data, size_t len, - uint8_t out[SHA512_DIGEST_LENGTH]); +// +// `static inline` to not generate such short-named linker symbols or macros. +static inline uint8_t *SHA512(const uint8_t *data, size_t len, + uint8_t out[SHA512_DIGEST_LENGTH]) { + SHA512_CTX ctx; + SHA512_Init(&ctx); + SHA512_Update(&ctx, data, len); + SHA512_Final(out, &ctx); + OPENSSL_cleanse(&ctx, sizeof(ctx)); + return out; +} // SHA512_Transform is a low-level function that performs a single, SHA-512 // block transformation using the state from `sha` and `SHA512_CBLOCK` bytes @@ -159,39 +219,37 @@ OPENSSL_EXPORT uint8_t *SHA512(const uint8_t *data, size_t len, OPENSSL_EXPORT void SHA512_Transform(SHA512_CTX *sha, const uint8_t block[SHA512_CBLOCK]); -struct sha512_state_st { - uint64_t h[8]; - uint16_t num, md_len; - uint32_t bytes_so_far_high; - uint64_t bytes_so_far_low; - uint8_t p[SHA512_CBLOCK]; -} /* SHA512_CTX */; - - -// SHA-512-256 -// -// See https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf section 5.3.6 - -#define SHA512_256_DIGEST_LENGTH 32 - -// SHA512_256_Init initialises `sha` and returns 1. +// SHA512_256_Init initialises `sha` for SHA-512/256 and returns 1. OPENSSL_EXPORT int SHA512_256_Init(SHA512_CTX *sha); // SHA512_256_Update adds `len` bytes from `data` to `sha` and returns 1. +// +// `sha` must have been initialised for SHA-512/256. OPENSSL_EXPORT int SHA512_256_Update(SHA512_CTX *sha, const void *data, size_t len); // SHA512_256_Final adds the final padding to `sha` and writes the resulting // digest to `out`, which must have at least `SHA512_256_DIGEST_LENGTH` bytes of // space. It returns one on success and zero on programmer error. +// +// `sha` must have been initialised for SHA-512/256. OPENSSL_EXPORT int SHA512_256_Final(uint8_t out[SHA512_256_DIGEST_LENGTH], SHA512_CTX *sha); // SHA512_256 writes the digest of `len` bytes from `data` to `out` and returns // `out`. There must be at least `SHA512_256_DIGEST_LENGTH` bytes of space in // `out`. -OPENSSL_EXPORT uint8_t *SHA512_256(const uint8_t *data, size_t len, - uint8_t out[SHA512_256_DIGEST_LENGTH]); +// +// `static inline` to not generate such short-named linker symbols or macros. +static inline uint8_t *SHA512_256(const uint8_t *data, size_t len, + uint8_t out[SHA512_256_DIGEST_LENGTH]) { + SHA512_CTX ctx; + SHA512_256_Init(&ctx); + SHA512_256_Update(&ctx, data, len); + SHA512_256_Final(out, &ctx); + OPENSSL_cleanse(&ctx, sizeof(ctx)); + return out; +} #if defined(__cplusplus) diff --git a/third_party/boringssl/src/include/openssl/span.h b/third_party/boringssl/src/include/openssl/span.h index 5f205b6..72447af 100644 --- a/third_party/boringssl/src/include/openssl/span.h +++ b/third_party/boringssl/src/include/openssl/span.h @@ -15,7 +15,7 @@ #ifndef OPENSSL_HEADER_SSL_SPAN_H #define OPENSSL_HEADER_SSL_SPAN_H -#include // IWYU pragma: export +#include // IWYU pragma: export #if !defined(BORINGSSL_NO_CXX) diff --git a/third_party/boringssl/src/include/openssl/trust_token.h b/third_party/boringssl/src/include/openssl/trust_token.h index cf909ae..e0fbcea 100644 --- a/third_party/boringssl/src/include/openssl/trust_token.h +++ b/third_party/boringssl/src/include/openssl/trust_token.h @@ -15,7 +15,7 @@ #ifndef OPENSSL_HEADER_TRUST_TOKEN_H #define OPENSSL_HEADER_TRUST_TOKEN_H -#include // IWYU pragma: export +#include // IWYU pragma: export #include #if defined(__cplusplus) @@ -152,7 +152,7 @@ OPENSSL_EXPORT int TRUST_TOKEN_CLIENT_add_key(TRUST_TOKEN_CLIENT *ctx, // TRUST_TOKEN_CLIENT_set_srr_key sets the public key used to verify the SRR. It // returns one on success and zero on error. OPENSSL_EXPORT int TRUST_TOKEN_CLIENT_set_srr_key(TRUST_TOKEN_CLIENT *ctx, - EVP_PKEY *key); + const EVP_PKEY *key); // TRUST_TOKEN_CLIENT_begin_issuance produces a request for `count` trust tokens // and serializes the request into a newly-allocated buffer, setting `*out` to @@ -180,11 +180,9 @@ OPENSSL_EXPORT int TRUST_TOKEN_CLIENT_begin_issuance_over_message( // arrives without the specified key present. The caller takes ownership of the // list and must call `sk_TRUST_TOKEN_pop_free` when done. The list is empty if // issuance fails. -OPENSSL_EXPORT STACK_OF(TRUST_TOKEN) * - TRUST_TOKEN_CLIENT_finish_issuance(TRUST_TOKEN_CLIENT *ctx, - size_t *out_key_index, - const uint8_t *response, - size_t response_len); +OPENSSL_EXPORT STACK_OF(TRUST_TOKEN) *TRUST_TOKEN_CLIENT_finish_issuance( + TRUST_TOKEN_CLIENT *ctx, size_t *out_key_index, const uint8_t *response, + size_t response_len); // TRUST_TOKEN_CLIENT_begin_redemption produces a request to redeem a token @@ -243,7 +241,7 @@ OPENSSL_EXPORT int TRUST_TOKEN_ISSUER_add_key(TRUST_TOKEN_ISSUER *ctx, // TRUST_TOKEN_ISSUER_set_srr_key sets the private key used to sign the SRR. It // returns one on success and zero on error. OPENSSL_EXPORT int TRUST_TOKEN_ISSUER_set_srr_key(TRUST_TOKEN_ISSUER *ctx, - EVP_PKEY *key); + const EVP_PKEY *key); // TRUST_TOKEN_ISSUER_issue ingests `request` for token issuance // and generates up to `max_issuance` valid tokens, producing a list of blinded diff --git a/third_party/boringssl/src/include/openssl/x509.h b/third_party/boringssl/src/include/openssl/x509.h index 0ef08e6..19154db 100644 --- a/third_party/boringssl/src/include/openssl/x509.h +++ b/third_party/boringssl/src/include/openssl/x509.h @@ -45,14 +45,31 @@ extern "C" { // Legacy X.509 library. // -// This header is part of OpenSSL's X.509 implementation. It is retained for -// compatibility but should not be used by new code. The functions are difficult -// to use correctly, and have buggy or non-standard behaviors. They are thus -// particularly prone to behavior changes and API removals, as BoringSSL -// iterates on these issues. +// This header is part of an X.509 implementation derived from OpenSSL. Compared +// to other OpenSSL-derived parts of BoringSSL, it is particularly impacted by +// that legacy. Many functions are difficult to use correctly and have a number +// of known bugs or non-standard behaviors. // -// In the future, a replacement library will be available. Meanwhile, minimize -// dependencies on this header where possible. +// As BoringSSL iterates on these issues, this header will be particularly prone +// to behavior changes and API removals. Callers should particularly avoid +// depending on the following: +// +// - Permissive parsing and validation +// - Path building and validation details +// - Obscure features of X.509 that are not well-exercised by the Web PKI +// - Mutating of `X509` objects outside of constructing new certificates +// - Ad-hoc human-readable representations of objects +// - Any other function-specific warnings mentioned in documentation +// +// BoringSSL contains a second X.509 implementation, libpki, found in +// . However, libpki has a more limited API surface and does +// not, e.g., provide APIs for constructing new certificates. For now, BoringSSL +// maintains them as separate, parallel implementations, but we hope to +// eventually converge them. +// +// Note that neither implementation comes with trust anchors (root CAs). The +// calling application is ultimately responsible for managing PKI configuration +// and ensuring, e.g., untrustworthy or compromised CAs are not trusted. // Certificates. @@ -89,7 +106,7 @@ OPENSSL_EXPORT X509 *X509_dup_ref(const X509 *x509); // shallow copy of `chain`, or NULL on error. That is, the return value has the // same contents as `chain`, and each `X509`'s reference count is incremented by // one. -OPENSSL_EXPORT STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *chain); +OPENSSL_EXPORT STACK_OF(X509) *X509_chain_up_ref(const STACK_OF(X509) *chain); // X509_dup returns a newly-allocated copy of `x509`, or NULL on error. This // function works by serializing the structure, so auxiliary properties (see @@ -113,13 +130,13 @@ OPENSSL_EXPORT X509 *d2i_X509(X509 **out, const uint8_t **inp, long len); // Only the `num_algs` algorithms from `algs` will be considered when parsing // the certificate's public key. If the certificate uses a different algorithm, // it will still be parsed, but `X509_get0_pubkey` will return NULL. -OPENSSL_EXPORT X509 *X509_parse_with_algorithms(CRYPTO_BUFFER *buf, +OPENSSL_EXPORT X509 *X509_parse_with_algorithms(const CRYPTO_BUFFER *buf, const EVP_PKEY_ALG *const *algs, size_t num_algs); // X509_parse_from_buffer behaves like `X509_parse_with_algorithms` but uses a // default algorithm list. -OPENSSL_EXPORT X509 *X509_parse_from_buffer(CRYPTO_BUFFER *buf); +OPENSSL_EXPORT X509 *X509_parse_from_buffer(const CRYPTO_BUFFER *buf); // i2d_X509 marshals `x509` as a DER-encoded X.509 Certificate (RFC 5280), as // described in `i2d_SAMPLE`. @@ -223,7 +240,7 @@ OPENSSL_EXPORT void X509_get0_uids(const X509 *x509, // X509_get_extension_flags decodes a set of extensions from `x509` and returns // a collection of `EXFLAG_*` bits which reflect `x509`. If there was an error // in computing this bitmask, the result will include the `EXFLAG_INVALID` bit. -OPENSSL_EXPORT uint32_t X509_get_extension_flags(X509 *x509); +OPENSSL_EXPORT uint32_t X509_get_extension_flags(const X509 *x509); // X509_get_pathlen returns path length constraint from the basic constraints // extension in `x509`. (See RFC 5280, section 4.2.1.9.) It returns -1 if the @@ -232,7 +249,7 @@ OPENSSL_EXPORT uint32_t X509_get_extension_flags(X509 *x509); // TODO(crbug.com/boringssl/381): Decoding an `X509` object will not check for // invalid extensions. To detect the error case, call // `X509_get_extension_flags` and check the `EXFLAG_INVALID` bit. -OPENSSL_EXPORT long X509_get_pathlen(X509 *x509); +OPENSSL_EXPORT long X509_get_pathlen(const X509 *x509); // X509v3_KU_* are key usage bits returned from `X509_get_key_usage`. #define X509v3_KU_DIGITAL_SIGNATURE 0x0080 @@ -258,7 +275,7 @@ OPENSSL_EXPORT long X509_get_pathlen(X509 *x509); // function returns `UINT32_MAX`. If there was an error processing `x509`'s // extensions, or if the first 16 bits in the key usage extension were all zero, // this function returns zero. -OPENSSL_EXPORT uint32_t X509_get_key_usage(X509 *x509); +OPENSSL_EXPORT uint32_t X509_get_key_usage(const X509 *x509); // XKU_* are extended key usage bits returned from // `X509_get_extended_key_usage`. @@ -282,7 +299,7 @@ OPENSSL_EXPORT uint32_t X509_get_key_usage(X509 *x509); // valid and this function returns `UINT32_MAX`. If there was an error // processing `x509`'s extensions, or if `x509`'s extended key usage extension // contained no recognized usages, this function returns zero. -OPENSSL_EXPORT uint32_t X509_get_extended_key_usage(X509 *x509); +OPENSSL_EXPORT uint32_t X509_get_extended_key_usage(const X509 *x509); // X509_get0_subject_key_id returns `x509`'s subject key identifier, if present. // (See RFC 5280, section 4.2.1.2.) It returns NULL if the extension is not @@ -291,7 +308,8 @@ OPENSSL_EXPORT uint32_t X509_get_extended_key_usage(X509 *x509); // TODO(crbug.com/boringssl/381): Decoding an `X509` object will not check for // invalid extensions. To detect the error case, call // `X509_get_extension_flags` and check the `EXFLAG_INVALID` bit. -OPENSSL_EXPORT const ASN1_OCTET_STRING *X509_get0_subject_key_id(X509 *x509); +OPENSSL_EXPORT const ASN1_OCTET_STRING *X509_get0_subject_key_id( + const X509 *x509); // X509_get0_authority_key_id returns keyIdentifier of `x509`'s authority key // identifier, if the extension and field are present. (See RFC 5280, @@ -302,7 +320,8 @@ OPENSSL_EXPORT const ASN1_OCTET_STRING *X509_get0_subject_key_id(X509 *x509); // TODO(crbug.com/boringssl/381): Decoding an `X509` object will not check for // invalid extensions. To detect the error case, call // `X509_get_extension_flags` and check the `EXFLAG_INVALID` bit. -OPENSSL_EXPORT const ASN1_OCTET_STRING *X509_get0_authority_key_id(X509 *x509); +OPENSSL_EXPORT const ASN1_OCTET_STRING *X509_get0_authority_key_id( + const X509 *x509); DEFINE_STACK_OF(GENERAL_NAME) typedef STACK_OF(GENERAL_NAME) GENERAL_NAMES; @@ -316,7 +335,8 @@ typedef STACK_OF(GENERAL_NAME) GENERAL_NAMES; // TODO(crbug.com/boringssl/381): Decoding an `X509` object will not check for // invalid extensions. To detect the error case, call // `X509_get_extension_flags` and check the `EXFLAG_INVALID` bit. -OPENSSL_EXPORT const GENERAL_NAMES *X509_get0_authority_issuer(X509 *x509); +OPENSSL_EXPORT const GENERAL_NAMES *X509_get0_authority_issuer( + const X509 *x509); // X509_get0_authority_serial returns the authorityCertSerialNumber of `x509`'s // authority key identifier, if the extension and field are present. (See @@ -327,7 +347,7 @@ OPENSSL_EXPORT const GENERAL_NAMES *X509_get0_authority_issuer(X509 *x509); // TODO(crbug.com/boringssl/381): Decoding an `X509` object will not check for // invalid extensions. To detect the error case, call // `X509_get_extension_flags` and check the `EXFLAG_INVALID` bit. -OPENSSL_EXPORT const ASN1_INTEGER *X509_get0_authority_serial(X509 *x509); +OPENSSL_EXPORT const ASN1_INTEGER *X509_get0_authority_serial(const X509 *x509); // X509_get0_extensions returns `x509`'s extension list, or NULL if `x509` omits // it. @@ -401,7 +421,7 @@ OPENSSL_EXPORT int i2d_X509_tbs(const X509 *x509, uint8_t **outp); // one if the signature is valid and zero otherwise. Note this function only // checks the signature itself and does not perform a full certificate // validation. -OPENSSL_EXPORT int X509_verify(const X509 *x509, EVP_PKEY *pkey); +OPENSSL_EXPORT int X509_verify(const X509 *x509, const EVP_PKEY *pkey); // X509_get1_email returns a newly-allocated list of NUL-terminated strings // containing all email addresses in `x509`'s subject and all rfc822name names @@ -486,9 +506,8 @@ OPENSSL_EXPORT int X509_set_issuer_name(X509 *x509, const X509_NAME *name); OPENSSL_EXPORT int X509_set_subject_name(X509 *x509, const X509_NAME *name); // X509_set_pubkey sets `x509`'s public key to `pkey`. It returns one on success -// and zero on error. This function does not take ownership of `pkey` and -// internally copies and updates reference counts as needed. -OPENSSL_EXPORT int X509_set_pubkey(X509 *x509, EVP_PKEY *pkey); +// and zero on error. +OPENSSL_EXPORT int X509_set_pubkey(X509 *x509, const EVP_PKEY *pkey); // X509_delete_ext removes the extension in `x` at index `loc` and returns the // removed extension, or NULL if `loc` was out of bounds. If non-NULL, the @@ -518,7 +537,16 @@ OPENSSL_EXPORT int X509_add1_ext_i2d(X509 *x, int nid, void *value, int crit, // on error. This function uses digest algorithm `md`, or `pkey`'s default if // NULL. Other signing parameters use `pkey`'s defaults. To customize them, use // `X509_sign_ctx`. -OPENSSL_EXPORT int X509_sign(X509 *x509, EVP_PKEY *pkey, const EVP_MD *md); +OPENSSL_EXPORT int X509_sign(X509 *x509, const EVP_PKEY *pkey, + const EVP_MD *md); + +// X509_set_unsigned fills in the placeholder fields in `x509` to make an +// unsigned certificate (RFC 9925) and returns one on success or zero on error. +// It sets the signature algorithm to id-alg-unsigned and the signature value to +// the empty string. If the issuer is empty, it additionally sets the issuer to +// the id-rdna-unsigned placeholder value. Otherwise, it retains the existing +// issuer value. +OPENSSL_EXPORT int X509_set_unsigned(X509 *x509); // X509_sign_ctx signs `x509` with `ctx` and replaces the signature algorithm // and signature fields. It returns the length of the signature on success and @@ -682,6 +710,10 @@ DEFINE_STACK_OF(X509_REVOKED) // X509_CRL_up_ref adds one to the reference count of `crl` and returns one. OPENSSL_EXPORT int X509_CRL_up_ref(X509_CRL *crl); +// X509_CRL_dup_ref adds one to the reference count of `crl` and returns the +// same. +OPENSSL_EXPORT X509_CRL *X509_CRL_dup_ref(const X509_CRL *crl); + // X509_CRL_dup returns a newly-allocated copy of `crl`, or NULL on error. This // function works by serializing the structure, so if `crl` is incomplete, it // may fail. @@ -826,7 +858,7 @@ OPENSSL_EXPORT int i2d_X509_CRL_tbs(const X509_CRL *crl, unsigned char **outp); // X509_CRL_verify checks that `crl` has a valid signature by `pkey`. It returns // one if the signature is valid and zero otherwise. -OPENSSL_EXPORT int X509_CRL_verify(const X509_CRL *crl, EVP_PKEY *pkey); +OPENSSL_EXPORT int X509_CRL_verify(const X509_CRL *crl, const EVP_PKEY *pkey); // Issuing certificate revocation lists. @@ -899,7 +931,7 @@ OPENSSL_EXPORT int X509_CRL_add1_ext_i2d(X509_CRL *x, int nid, void *value, // zero on error. This function uses digest algorithm `md`, or `pkey`'s default // if NULL. Other signing parameters use `pkey`'s defaults. To customize them, // use `X509_CRL_sign_ctx`. -OPENSSL_EXPORT int X509_CRL_sign(X509_CRL *crl, EVP_PKEY *pkey, +OPENSSL_EXPORT int X509_CRL_sign(X509_CRL *crl, const EVP_PKEY *pkey, const EVP_MD *md); // X509_CRL_sign_ctx signs `crl` with `ctx` and replaces the signature algorithm @@ -1175,7 +1207,7 @@ OPENSSL_EXPORT int X509_REQ_get_signature_nid(const X509_REQ *req); // X509_REQ_verify checks that `req` has a valid signature by `pkey`. It returns // one if the signature is valid and zero otherwise. -OPENSSL_EXPORT int X509_REQ_verify(const X509_REQ *req, EVP_PKEY *pkey); +OPENSSL_EXPORT int X509_REQ_verify(const X509_REQ *req, const EVP_PKEY *pkey); // X509_REQ_get1_email returns a newly-allocated list of NUL-terminated strings // containing all email addresses in `req`'s subject and all rfc822name names @@ -1209,12 +1241,12 @@ OPENSSL_EXPORT int X509_REQ_set_version(X509_REQ *req, long version); // X509_REQ_set_subject_name sets `req`'s subject to a copy of `name`. It // returns one on success and zero on error. -OPENSSL_EXPORT int X509_REQ_set_subject_name(X509_REQ *req, X509_NAME *name); +OPENSSL_EXPORT int X509_REQ_set_subject_name(X509_REQ *req, + const X509_NAME *name); // X509_REQ_set_pubkey sets `req`'s public key to `pkey`. It returns one on -// success and zero on error. This function does not take ownership of `pkey` -// and internally copies and updates reference counts as needed. -OPENSSL_EXPORT int X509_REQ_set_pubkey(X509_REQ *req, EVP_PKEY *pkey); +// success and zero on error. +OPENSSL_EXPORT int X509_REQ_set_pubkey(X509_REQ *req, const EVP_PKEY *pkey); // X509_REQ_delete_attr removes the attribute at index `loc` in `req`. It // returns the removed attribute to the caller, or NULL if `loc` was out of @@ -1270,7 +1302,7 @@ OPENSSL_EXPORT int X509_REQ_add_extensions( // zero on error. This function uses digest algorithm `md`, or `pkey`'s default // if NULL. Other signing parameters use `pkey`'s defaults. To customize them, // use `X509_REQ_sign_ctx`. -OPENSSL_EXPORT int X509_REQ_sign(X509_REQ *req, EVP_PKEY *pkey, +OPENSSL_EXPORT int X509_REQ_sign(X509_REQ *req, const EVP_PKEY *pkey, const EVP_MD *md); // X509_REQ_sign_ctx signs `req` with `ctx` and replaces the signature algorithm @@ -1563,7 +1595,7 @@ OPENSSL_EXPORT int i2d_X509_PUBKEY(const X509_PUBKEY *key, uint8_t **outp); // X509_PUBKEY_set serializes `pkey` into a newly-allocated `X509_PUBKEY` // structure. On success, it frees `*x` if non-NULL, then sets `*x` to the new // object, and returns one. Otherwise, it returns zero. -OPENSSL_EXPORT int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey); +OPENSSL_EXPORT int X509_PUBKEY_set(X509_PUBKEY **x, const EVP_PKEY *pkey); // X509_PUBKEY_get0 returns `key` as an `EVP_PKEY`, or NULL if `key` either // could not be parsed or is an unrecognized algorithm. The `EVP_PKEY` is cached @@ -2311,8 +2343,6 @@ typedef struct DIST_POINT_NAME_st { GENERAL_NAMES *fullname; STACK_OF(X509_NAME_ENTRY) *relativename; } name; - // If relativename then this contains the full distribution point name - X509_NAME *dpname; } DIST_POINT_NAME; // DIST_POINT_NAME_new returns a newly-allocated, empty `DIST_POINT_NAME` @@ -2626,9 +2656,11 @@ OPENSSL_EXPORT void X509_ALGOR_get0(const ASN1_OBJECT **out_obj, // constructing PSS and move on. OPENSSL_EXPORT int X509_ALGOR_set_md(X509_ALGOR *alg, const EVP_MD *md); -// X509_ALGOR_cmp returns zero if `a` and `b` are equal, and some non-zero value -// otherwise. Note this function can only be used for equality checks, not an -// ordering. +// X509_ALGOR_cmp compares `a` and `b`. It returns zero if they are equal, and a +// negative or positive value if `a` sorts before or after `b`, respectively. +// Values are ordered first by algorithm, then by parameter, with an absent +// parameter sorting before a present one. The order is arbitrary but suitable +// for sorting. Callers should not rely on the exact order. OPENSSL_EXPORT int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b); @@ -2772,6 +2804,10 @@ OPENSSL_EXPORT ASN1_TYPE *X509_ATTRIBUTE_get0_type(X509_ATTRIBUTE *attr, // trusted certificate as a trust anchor. See `X509_VERIFY_PARAM_set_trust` for // details. // +// When this library uses a certificate as a trust anchor, the certificate's +// fields are applied as constraints on the path, similar to RFC 5937. Expiry of +// the trust anchor, via the notBefore and notAfter fields, is also applied. +// // WARNING: Although a trusted certificate which fails the // `X509_VERIFY_PARAM_set_trust` check is functionally an untrusted // intermediate certificate, callers should not rely on this to configure @@ -2802,6 +2838,10 @@ OPENSSL_EXPORT X509_STORE *X509_STORE_new(void); // Although `store` is not const, this function's use of `store` is thread-safe. OPENSSL_EXPORT int X509_STORE_up_ref(X509_STORE *store); +// X509_STORE_dup_ref adds one to the reference count of `store` and returns +// the same handle. +OPENSSL_EXPORT X509_STORE *X509_STORE_dup_ref(const X509_STORE *store); + // X509_STORE_free releases memory associated with `store`. OPENSSL_EXPORT void X509_STORE_free(X509_STORE *store); @@ -2809,15 +2849,16 @@ OPENSSL_EXPORT void X509_STORE_free(X509_STORE *store); // returns one on success and zero on error. This function internally increments // `x509`'s reference count, so the caller retains ownership of `x509`. // -// Certificates configured by this function are still subject to the checks -// described in `X509_VERIFY_PARAM_set_trust`. +// Certificates configured by this function are potential trust anchors, but +// whether they are trust anchors for any given verification depends on the +// checks described in `X509_VERIFY_PARAM_set_trust`. // // Although `store` is not const, this function's use of `store` is thread-safe. // However, if this function is called concurrently with `X509_verify_cert`, it // is a race condition whether `x509` is available for issuer lookups. // Moreover, the result may differ for each issuer lookup performed by a single // `X509_verify_cert` call. -OPENSSL_EXPORT int X509_STORE_add_cert(X509_STORE *store, X509 *x509); +OPENSSL_EXPORT int X509_STORE_add_cert(X509_STORE *store, const X509 *x509); // X509_STORE_add_crl adds `crl` to `store`. It returns one on success and zero // on error. This function internally increments `crl`'s reference count, so the @@ -2834,7 +2875,7 @@ OPENSSL_EXPORT int X509_STORE_add_cert(X509_STORE *store, X509 *x509); // To vary the set of CRLs over time, callers should either create a new // `X509_STORE` or configure CRLs on a per-verification basis with // `X509_STORE_CTX_set0_crls`. -OPENSSL_EXPORT int X509_STORE_add_crl(X509_STORE *store, X509_CRL *crl); +OPENSSL_EXPORT int X509_STORE_add_crl(X509_STORE *store, const X509_CRL *crl); // X509_STORE_get0_param returns `store`'s verification parameters. This object // is mutable and may be modified by the caller. For an individual certificate @@ -3066,11 +3107,6 @@ OPENSSL_EXPORT int X509_STORE_CTX_get_error_depth(const X509_STORE_CTX *ctx); // error returned by `X509_STORE_CTX_get_error`. OPENSSL_EXPORT X509 *X509_STORE_CTX_get_current_cert(const X509_STORE_CTX *ctx); -// X509_STORE_CTX_get0_current_crl returns the CRL which caused the error -// returned by `X509_STORE_CTX_get_error`. -OPENSSL_EXPORT X509_CRL *X509_STORE_CTX_get0_current_crl( - const X509_STORE_CTX *ctx); - // X509_STORE_CTX_get0_store returns the `X509_STORE` that `ctx` uses. OPENSSL_EXPORT X509_STORE *X509_STORE_CTX_get0_store(const X509_STORE_CTX *ctx); @@ -3246,9 +3282,6 @@ OPENSSL_EXPORT int X509_VERIFY_PARAM_set1(X509_VERIFY_PARAM *to, // this option. Critical extensions ensure the verifier does not bypass // unrecognized security restrictions in certificates. #define X509_V_FLAG_IGNORE_CRITICAL 0x10 -// X509_V_FLAG_X509_STRICT does nothing. Its functionality has been enabled by -// default. -#define X509_V_FLAG_X509_STRICT 0x00 // X509_V_FLAG_ALLOW_PROXY_CERTS does nothing. Proxy certificate support has // been removed. #define X509_V_FLAG_ALLOW_PROXY_CERTS 0x40 @@ -3272,26 +3305,35 @@ OPENSSL_EXPORT int X509_VERIFY_PARAM_set1(X509_VERIFY_PARAM *to, // X509_V_FLAG_USE_DELTAS causes all verifications to fail. Delta CRL support // has been removed. #define X509_V_FLAG_USE_DELTAS 0x2000 -// X509_V_FLAG_CHECK_SS_SIGNATURE checks the redundant signature on self-signed -// trust anchors. This check provides no security benefit and only wastes CPU. -#define X509_V_FLAG_CHECK_SS_SIGNATURE 0x4000 -// X509_V_FLAG_TRUSTED_FIRST does nothing. The behavior it controls is always -// enabled. -#define X509_V_FLAG_TRUSTED_FIRST 0x0 // X509_V_FLAG_PARTIAL_CHAIN treats all trusted certificates as trust anchors, // independent of the `X509_VERIFY_PARAM_set_trust` setting. #define X509_V_FLAG_PARTIAL_CHAIN 0x80000 -// X509_V_FLAG_NO_ALT_CHAINS does nothing. -#define X509_V_FLAG_NO_ALT_CHAINS 0x0 // X509_V_FLAG_NO_CHECK_TIME disables all time checks in certificate // verification. #define X509_V_FLAG_NO_CHECK_TIME 0x200000 // X509_V_FLAG_ALLOW_TIMEZONE_OFFSET allows `notBefore` and `notAfter` fields // to contain a time zone offset. #define X509_V_FLAG_ALLOW_TIMEZONE_OFFSET 0x1000000 -// X509_V_FLAG_USE_MTC_DRAFT_PLANTS_05 enables the verification of Merkle Tree -// Certificates as specified in draft-ietf-plants-merkle-tree-certs-05. -#define X509_V_FLAG_USE_MTC_DRAFT_PLANTS_05 0x400000 +// X509_V_FLAG_ALLOW_SHA1 allows certificates and CRLs signed with SHA-1 to be +// accepted during verification. +// This flag is tentatively set by default. Users should add this explicitly if +// they want to allow SHA-1. +#define X509_V_FLAG_ALLOW_SHA1 0x2000000 + +// Deprecated flags. + +// X509_V_FLAG_X509_STRICT does nothing. Its functionality has been enabled by +// default. +#define X509_V_FLAG_X509_STRICT 0x00 +// X509_V_FLAG_CHECK_SS_SIGNATURE does nothing. Historically it would check the +// redundant signature on self-signed trust anchors. This check provided no +// security benefit and only wasted CPU. +#define X509_V_FLAG_CHECK_SS_SIGNATURE 0x0 +// X509_V_FLAG_TRUSTED_FIRST does nothing. The behavior it controls is always +// enabled. +#define X509_V_FLAG_TRUSTED_FIRST 0x0 +// X509_V_FLAG_NO_ALT_CHAINS does nothing. +#define X509_V_FLAG_NO_ALT_CHAINS 0x0 // X509_VERIFY_PARAM_set_flags enables all values in `flags` in `param`'s // verification flags and returns one. `flags` should be a combination of @@ -3750,7 +3792,8 @@ OPENSSL_EXPORT int i2d_NETSCAPE_SPKI(const NETSCAPE_SPKI *spki, uint8_t **outp); // NETSCAPE_SPKI_verify checks that `spki` has a valid signature by `pkey`. It // returns one if the signature is valid and zero otherwise. -OPENSSL_EXPORT int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *spki, EVP_PKEY *pkey); +OPENSSL_EXPORT int NETSCAPE_SPKI_verify(const NETSCAPE_SPKI *spki, + const EVP_PKEY *pkey); // NETSCAPE_SPKI_b64_decode decodes `len` bytes from `str` as a base64-encoded // SignedPublicKeyAndChallenge structure. It returns a newly-allocated @@ -3764,7 +3807,7 @@ OPENSSL_EXPORT NETSCAPE_SPKI *NETSCAPE_SPKI_b64_decode(const char *str, // SignedPublicKeyAndChallenge structure. It returns a newly-allocated // NUL-terminated C string with the result, or NULL on error. The caller must // release the memory with `OPENSSL_free` when done. -OPENSSL_EXPORT char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *spki); +OPENSSL_EXPORT char *NETSCAPE_SPKI_b64_encode(const NETSCAPE_SPKI *spki); // NETSCAPE_SPKI_get_pubkey decodes and returns the public key in `spki` as an // `EVP_PKEY`, or NULL on error. The caller takes ownership of the resulting @@ -3772,16 +3815,15 @@ OPENSSL_EXPORT char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *spki); OPENSSL_EXPORT EVP_PKEY *NETSCAPE_SPKI_get_pubkey(const NETSCAPE_SPKI *spki); // NETSCAPE_SPKI_set_pubkey sets `spki`'s public key to `pkey`. It returns one -// on success or zero on error. This function does not take ownership of `pkey`, -// so the caller may continue to manage its lifetime independently of `spki`. +// on success or zero on error. OPENSSL_EXPORT int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *spki, - EVP_PKEY *pkey); + const EVP_PKEY *pkey); // NETSCAPE_SPKI_sign signs `spki` with `pkey` and replaces the signature // algorithm and signature fields. It returns the length of the signature on // success and zero on error. This function uses digest algorithm `md`, or // `pkey`'s default if NULL. Other signing parameters use `pkey`'s defaults. -OPENSSL_EXPORT int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *spki, EVP_PKEY *pkey, +OPENSSL_EXPORT int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *spki, const EVP_PKEY *pkey, const EVP_MD *md); // A Netscape_spkac_st, or `NETSCAPE_SPKAC`, represents a PublicKeyAndChallenge @@ -4498,7 +4540,7 @@ OPENSSL_EXPORT int ASN1_item_digest(const ASN1_ITEM *it, const EVP_MD *type, OPENSSL_EXPORT int ASN1_item_verify(const ASN1_ITEM *it, const X509_ALGOR *algor1, const ASN1_BIT_STRING *signature, - void *data, EVP_PKEY *pkey); + void *data, const EVP_PKEY *pkey); // ASN1_item_sign serializes `data` with `it` and then signs the result with // the private key `pkey`. It returns the length of the signature on success and @@ -4516,7 +4558,7 @@ OPENSSL_EXPORT int ASN1_item_verify(const ASN1_ITEM *it, OPENSSL_EXPORT int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2, ASN1_BIT_STRING *signature, void *data, - EVP_PKEY *pkey, const EVP_MD *type); + const EVP_PKEY *pkey, const EVP_MD *type); // ASN1_item_sign_ctx behaves like `ASN1_item_sign` except the signature is // signed with `ctx`, `ctx`, which must have been initialized with @@ -4667,7 +4709,7 @@ OPENSSL_EXPORT int X509_STORE_CTX_get1_issuer(X509 **out_issuer, // some extensions in `x509` and may return zero on syntax error. Historically, // callers primarily used this function to trigger this parsing, but this is no // longer necessary. Functions acting on `X509` will internally parse as needed. -OPENSSL_EXPORT int X509_check_purpose(X509 *x509, int purpose, int ca); +OPENSSL_EXPORT int X509_check_purpose(const X509 *x509, int purpose, int ca); #define X509_TRUST_TRUSTED 1 #define X509_TRUST_REJECTED 2 @@ -4679,7 +4721,11 @@ OPENSSL_EXPORT int X509_check_purpose(X509 *x509, int purpose, int ca); // was distrusted, and `X509_TRUST_UNTRUSTED` otherwise. `id` should be one of // the `X509_TRUST_*` constants, or zero to indicate the default behavior. // `flags` should be zero and is ignored. -OPENSSL_EXPORT int X509_check_trust(X509 *x509, int id, int flags); +// +// WARNING: This function assumes `x509` is a trusted certificate, installed in +// an `X509_STORE`. If passed an arbitrary certificate from an untrusted source, +// it may return `X509_TRUST_TRUSTED`. +OPENSSL_EXPORT int X509_check_trust(const X509 *x509, int id, int flags); // X509_STORE_CTX_get1_certs returns a newly-allocated stack containing all // trusted certificates in `ctx`'s `X509_STORE` whose subject matches `name`, or @@ -5316,8 +5362,10 @@ BORINGSSL_MAKE_DELETER(BASIC_CONSTRAINTS, BASIC_CONSTRAINTS_free) // TODO(davidben): Move this to conf.h and rename to CONF_VALUE_free. BORINGSSL_MAKE_DELETER(CONF_VALUE, X509V3_conf_free) BORINGSSL_MAKE_DELETER(DIST_POINT, DIST_POINT_free) +BORINGSSL_MAKE_DELETER(DIST_POINT_NAME, DIST_POINT_NAME_free) BORINGSSL_MAKE_DELETER(GENERAL_NAME, GENERAL_NAME_free) BORINGSSL_MAKE_DELETER(GENERAL_SUBTREE, GENERAL_SUBTREE_free) +BORINGSSL_MAKE_DELETER(ISSUING_DIST_POINT, ISSUING_DIST_POINT_free) BORINGSSL_MAKE_DELETER(NAME_CONSTRAINTS, NAME_CONSTRAINTS_free) BORINGSSL_MAKE_DELETER(NETSCAPE_SPKI, NETSCAPE_SPKI_free) BORINGSSL_MAKE_DELETER(NOTICEREF, NOTICEREF_free) @@ -5328,11 +5376,11 @@ BORINGSSL_MAKE_DELETER(POLICYQUALINFO, POLICYQUALINFO_free) BORINGSSL_MAKE_DELETER(RSA_PSS_PARAMS, RSA_PSS_PARAMS_free) BORINGSSL_MAKE_DELETER(USERNOTICE, USERNOTICE_free) BORINGSSL_MAKE_DELETER(X509, X509_free) -BORINGSSL_MAKE_UP_REF(X509, X509_up_ref) +BORINGSSL_MAKE_UP_REF(X509, X509_dup_ref) BORINGSSL_MAKE_DELETER(X509_ALGOR, X509_ALGOR_free) BORINGSSL_MAKE_DELETER(X509_ATTRIBUTE, X509_ATTRIBUTE_free) BORINGSSL_MAKE_DELETER(X509_CRL, X509_CRL_free) -BORINGSSL_MAKE_UP_REF(X509_CRL, X509_CRL_up_ref) +BORINGSSL_MAKE_UP_REF(X509_CRL, X509_CRL_dup_ref) BORINGSSL_MAKE_DELETER(X509_EXTENSION, X509_EXTENSION_free) BORINGSSL_MAKE_DELETER(X509_INFO, X509_INFO_free) BORINGSSL_MAKE_DELETER(X509_LOOKUP, X509_LOOKUP_free) @@ -5344,13 +5392,13 @@ BORINGSSL_MAKE_DELETER(X509_REQ, X509_REQ_free) BORINGSSL_MAKE_DELETER(X509_REVOKED, X509_REVOKED_free) BORINGSSL_MAKE_DELETER(X509_SIG, X509_SIG_free) BORINGSSL_MAKE_DELETER(X509_STORE, X509_STORE_free) -BORINGSSL_MAKE_UP_REF(X509_STORE, X509_STORE_up_ref) +BORINGSSL_MAKE_UP_REF(X509_STORE, X509_STORE_dup_ref) BORINGSSL_MAKE_DELETER(X509_STORE_CTX, X509_STORE_CTX_free) BORINGSSL_MAKE_DELETER(X509_VERIFY_PARAM, X509_VERIFY_PARAM_free) BSSL_NAMESPACE_END -} // extern C++ +} // extern C++ #endif // !BORINGSSL_NO_CXX #define X509_R_AKID_MISMATCH 100 diff --git a/tool/REVISION b/tool/REVISION index 978305a..a3c9453 100644 --- a/tool/REVISION +++ b/tool/REVISION @@ -1 +1 @@ -e98a6564575520260ef95b2389e5d63a24917093 +289645a450721a7210bf9c69d42bf40a0f1ee730