From 86458a336bf0f647b080c8637515bfefd8ea08b3 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Fri, 9 Oct 2026 18:19:47 +0100 Subject: [PATCH] Update BoringSSL to 8eb25be6fa18d475291122887a7bccd3762ff236 (#607) As a standard pattern, the vendoring script needed some changes, as did our internal code. The biggest change here is that BoringSSL has changed its name mangling scheme. This causes us to no longer need to explicitly write the prefix out anymore: in fact, doing that causes compiler errors. So this patch rewrites the code to resolve that issue. Along the way, I've also added some checks for making sure the name mangling is correct. --- .../6.1/NIOSSLBenchmarks.ManyWrites.p90.json | 2 +- .../NIOSSLBenchmarks.SimpleHandshake.p90.json | 2 +- .../6.2/NIOSSLBenchmarks.ManyWrites.p90.json | 2 +- .../NIOSSLBenchmarks.SimpleHandshake.p90.json | 2 +- .../6.3/NIOSSLBenchmarks.ManyWrites.p90.json | 2 +- .../NIOSSLBenchmarks.SimpleHandshake.p90.json | 2 +- .../NIOSSLBenchmarks.ManyWrites.p90.json | 2 +- .../NIOSSLBenchmarks.SimpleHandshake.p90.json | 2 +- .../NIOSSLBenchmarks.ManyWrites.p90.json | 2 +- .../NIOSSLBenchmarks.SimpleHandshake.p90.json | 2 +- Package.swift | 5 +- Sources/CNIOBoringSSL/crypto/aes/aes.cc | 44 + .../crypto/armv8_feature_parsing.h | 67 + Sources/CNIOBoringSSL/crypto/asn1/a_bitstr.cc | 291 +- Sources/CNIOBoringSSL/crypto/asn1/a_bool.cc | 34 +- Sources/CNIOBoringSSL/crypto/asn1/a_d2i_fp.cc | 27 +- Sources/CNIOBoringSSL/crypto/asn1/a_dup.cc | 33 +- Sources/CNIOBoringSSL/crypto/asn1/a_gentm.cc | 66 +- Sources/CNIOBoringSSL/crypto/asn1/a_i2d_fp.cc | 34 +- Sources/CNIOBoringSSL/crypto/asn1/a_int.cc | 166 +- Sources/CNIOBoringSSL/crypto/asn1/a_mbstr.cc | 32 +- Sources/CNIOBoringSSL/crypto/asn1/a_object.cc | 167 +- Sources/CNIOBoringSSL/crypto/asn1/a_octet.cc | 21 +- Sources/CNIOBoringSSL/crypto/asn1/a_strex.cc | 101 +- Sources/CNIOBoringSSL/crypto/asn1/a_strnid.cc | 101 +- Sources/CNIOBoringSSL/crypto/asn1/a_time.cc | 115 +- Sources/CNIOBoringSSL/crypto/asn1/a_type.cc | 376 +- Sources/CNIOBoringSSL/crypto/asn1/a_utctm.cc | 66 +- Sources/CNIOBoringSSL/crypto/asn1/asn1_lib.cc | 181 +- Sources/CNIOBoringSSL/crypto/asn1/asn1_par.cc | 21 +- Sources/CNIOBoringSSL/crypto/asn1/asn_pack.cc | 41 +- Sources/CNIOBoringSSL/crypto/asn1/f_int.cc | 23 +- Sources/CNIOBoringSSL/crypto/asn1/f_string.cc | 23 +- Sources/CNIOBoringSSL/crypto/asn1/internal.h | 433 +- .../CNIOBoringSSL/crypto/asn1/posix_time.cc | 39 +- Sources/CNIOBoringSSL/crypto/asn1/tasn_dec.cc | 1188 +-- Sources/CNIOBoringSSL/crypto/asn1/tasn_enc.cc | 780 +- Sources/CNIOBoringSSL/crypto/asn1/tasn_fre.cc | 82 +- Sources/CNIOBoringSSL/crypto/asn1/tasn_new.cc | 123 +- Sources/CNIOBoringSSL/crypto/asn1/tasn_typ.cc | 53 +- Sources/CNIOBoringSSL/crypto/asn1/tasn_utl.cc | 158 +- Sources/CNIOBoringSSL/crypto/base64/base64.cc | 50 +- Sources/CNIOBoringSSL/crypto/bcm_support.h | 97 +- Sources/CNIOBoringSSL/crypto/bio/bio.cc | 440 +- Sources/CNIOBoringSSL/crypto/bio/bio_mem.cc | 185 +- Sources/CNIOBoringSSL/crypto/bio/connect.cc | 383 +- Sources/CNIOBoringSSL/crypto/bio/errno.cc | 25 +- Sources/CNIOBoringSSL/crypto/bio/fd.cc | 131 +- Sources/CNIOBoringSSL/crypto/bio/file.cc | 168 +- Sources/CNIOBoringSSL/crypto/bio/hexdump.cc | 31 +- Sources/CNIOBoringSSL/crypto/bio/internal.h | 116 +- Sources/CNIOBoringSSL/crypto/bio/pair.cc | 271 +- Sources/CNIOBoringSSL/crypto/bio/printf.cc | 23 +- Sources/CNIOBoringSSL/crypto/bio/socket.cc | 190 +- .../CNIOBoringSSL/crypto/bio/socket_helper.cc | 86 +- Sources/CNIOBoringSSL/crypto/blake2/blake2.cc | 40 +- Sources/CNIOBoringSSL/crypto/bn/bn_asn1.cc | 30 +- Sources/CNIOBoringSSL/crypto/bn/convert.cc | 147 +- Sources/CNIOBoringSSL/crypto/bn/div.cc | 102 + .../CNIOBoringSSL/crypto/bn/exponentiation.cc | 168 + Sources/CNIOBoringSSL/crypto/bn/sqrt.cc | 93 + Sources/CNIOBoringSSL/crypto/buf/buf.cc | 32 +- .../crypto/bytestring/asn1_compat.cc | 37 +- .../CNIOBoringSSL/crypto/bytestring/ber.cc | 68 +- .../CNIOBoringSSL/crypto/bytestring/cbb.cc | 309 +- .../CNIOBoringSSL/crypto/bytestring/cbs.cc | 203 +- .../crypto/bytestring/internal.h | 140 +- .../crypto/bytestring/unicode.cc | 30 +- Sources/CNIOBoringSSL/crypto/chacha/chacha.cc | 34 +- .../CNIOBoringSSL/crypto/chacha/internal.h | 79 +- .../CNIOBoringSSL/crypto/cipher/derive_key.cc | 53 +- .../crypto/cipher/e_aesctrhmac.cc | 157 +- .../CNIOBoringSSL/crypto/cipher/e_aeseax.cc | 351 + .../crypto/cipher/e_aesgcmsiv.cc | 885 +- .../crypto/cipher/e_chacha20poly1305.cc | 367 +- Sources/CNIOBoringSSL/crypto/cipher/e_des.cc | 95 +- Sources/CNIOBoringSSL/crypto/cipher/e_null.cc | 35 +- Sources/CNIOBoringSSL/crypto/cipher/e_rc2.cc | 92 +- Sources/CNIOBoringSSL/crypto/cipher/e_rc4.cc | 33 +- Sources/CNIOBoringSSL/crypto/cipher/e_tls.cc | 536 +- .../CNIOBoringSSL/crypto/cipher/get_cipher.cc | 45 +- .../CNIOBoringSSL/crypto/cipher/internal.h | 310 +- .../CNIOBoringSSL/crypto/cipher/tls_cbc.cc | 243 +- Sources/CNIOBoringSSL/crypto/cms/cms.cc | 178 + Sources/CNIOBoringSSL/crypto/conf/conf.cc | 153 +- Sources/CNIOBoringSSL/crypto/conf/internal.h | 49 +- .../CNIOBoringSSL/crypto/cpu_aarch64_apple.cc | 39 +- .../crypto/cpu_aarch64_fuchsia.cc | 33 +- .../CNIOBoringSSL/crypto/cpu_aarch64_linux.cc | 34 +- .../crypto/cpu_aarch64_openbsd.cc | 56 +- .../crypto/cpu_aarch64_sysreg.cc | 84 +- .../CNIOBoringSSL/crypto/cpu_aarch64_win.cc | 47 +- .../CNIOBoringSSL/crypto/cpu_arm_freebsd.cc | 33 +- Sources/CNIOBoringSSL/crypto/cpu_arm_linux.cc | 112 +- Sources/CNIOBoringSSL/crypto/cpu_arm_linux.h | 206 +- Sources/CNIOBoringSSL/crypto/cpu_intel.cc | 135 +- Sources/CNIOBoringSSL/crypto/crypto.cc | 109 +- .../crypto/curve25519/asm/x25519-asm-arm.S | 28 +- .../crypto/curve25519/curve25519.cc | 390 +- .../crypto/curve25519/curve25519_64_adx.cc | 26 +- .../crypto/curve25519/curve25519_tables.h | 38 +- .../crypto/curve25519/internal.h | 98 +- .../crypto/curve25519/spake25519.cc | 69 +- Sources/CNIOBoringSSL/crypto/des/des.cc | 67 +- Sources/CNIOBoringSSL/crypto/des/internal.h | 40 +- Sources/CNIOBoringSSL/crypto/dh/dh_asn1.cc | 104 +- Sources/CNIOBoringSSL/crypto/dh/params.cc | 222 +- .../crypto/digest/digest_extra.cc | 172 +- Sources/CNIOBoringSSL/crypto/dsa/dsa.cc | 640 +- Sources/CNIOBoringSSL/crypto/dsa/dsa_asn1.cc | 294 +- Sources/CNIOBoringSSL/crypto/dsa/internal.h | 78 +- Sources/CNIOBoringSSL/crypto/ec/ec_asn1.cc | 411 +- Sources/CNIOBoringSSL/crypto/ec/ec_derive.cc | 80 +- .../CNIOBoringSSL/crypto/ec/hash_to_curve.cc | 689 +- Sources/CNIOBoringSSL/crypto/ec/internal.h | 104 +- Sources/CNIOBoringSSL/crypto/ecdh/ecdh.cc | 35 +- .../CNIOBoringSSL/crypto/ecdsa/ecdsa_asn1.cc | 141 +- .../CNIOBoringSSL/crypto/ecdsa/ecdsa_p1363.cc | 54 + Sources/CNIOBoringSSL/crypto/engine/engine.cc | 40 +- Sources/CNIOBoringSSL/crypto/err/err.cc | 249 +- Sources/CNIOBoringSSL/crypto/err/internal.h | 55 +- Sources/CNIOBoringSSL/crypto/evp/evp.cc | 450 +- Sources/CNIOBoringSSL/crypto/evp/evp_asn1.cc | 475 +- Sources/CNIOBoringSSL/crypto/evp/evp_ctx.cc | 444 +- Sources/CNIOBoringSSL/crypto/evp/evp_kem.cc | 101 + Sources/CNIOBoringSSL/crypto/evp/internal.h | 496 +- Sources/CNIOBoringSSL/crypto/evp/p_dh.cc | 246 +- Sources/CNIOBoringSSL/crypto/evp/p_dh_asn1.cc | 137 - Sources/CNIOBoringSSL/crypto/evp/p_dsa.cc | 333 + .../CNIOBoringSSL/crypto/evp/p_dsa_asn1.cc | 274 - Sources/CNIOBoringSSL/crypto/evp/p_ec.cc | 611 +- Sources/CNIOBoringSSL/crypto/evp/p_ec_asn1.cc | 281 - Sources/CNIOBoringSSL/crypto/evp/p_ed25519.cc | 314 +- .../crypto/evp/p_ed25519_asn1.cc | 225 - Sources/CNIOBoringSSL/crypto/evp/p_hkdf.cc | 196 +- Sources/CNIOBoringSSL/crypto/evp/p_mldsa.cc | 549 ++ Sources/CNIOBoringSSL/crypto/evp/p_mlkem.cc | 510 ++ Sources/CNIOBoringSSL/crypto/evp/p_rsa.cc | 929 +- .../CNIOBoringSSL/crypto/evp/p_rsa_asn1.cc | 193 - Sources/CNIOBoringSSL/crypto/evp/p_x25519.cc | 344 +- .../CNIOBoringSSL/crypto/evp/p_x25519_asn1.cc | 237 - Sources/CNIOBoringSSL/crypto/evp/p_xwing.cc | 300 + Sources/CNIOBoringSSL/crypto/evp/pbkdf.cc | 42 +- Sources/CNIOBoringSSL/crypto/evp/print.cc | 144 +- Sources/CNIOBoringSSL/crypto/evp/scrypt.cc | 65 +- Sources/CNIOBoringSSL/crypto/evp/sign.cc | 86 +- Sources/CNIOBoringSSL/crypto/ex_data.cc | 102 +- .../crypto/fipsmodule/aes/aes.cc.inc | 116 +- .../crypto/fipsmodule/aes/aes_nohw.cc.inc | 268 +- .../crypto/fipsmodule/aes/cbc.cc.inc | 51 +- .../crypto/fipsmodule/aes/cfb.cc.inc | 43 +- .../crypto/fipsmodule/aes/ctr.cc.inc | 33 +- .../crypto/fipsmodule/aes/gcm.cc.inc | 111 +- .../crypto/fipsmodule/aes/gcm_nohw.cc.inc | 54 +- .../crypto/fipsmodule/aes/internal.h | 433 +- .../crypto/fipsmodule/aes/key_wrap.cc.inc | 38 +- .../fipsmodule/aes/mode_wrappers.cc.inc | 50 +- .../crypto/fipsmodule/aes/ofb.cc.inc | 33 +- .../crypto/fipsmodule/aes/polyval.cc.inc | 89 - .../CNIOBoringSSL/crypto/fipsmodule/bcm.cc | 72 +- .../crypto/fipsmodule/bcm_interface.h | 934 +- .../crypto/fipsmodule/bn/add.cc.inc | 46 +- .../fipsmodule/bn/asm/x86_64-gcc.cc.inc | 133 +- .../crypto/fipsmodule/bn/bn.cc.inc | 98 +- .../crypto/fipsmodule/bn/bytes.cc.inc | 118 +- .../crypto/fipsmodule/bn/cmp.cc.inc | 37 +- .../crypto/fipsmodule/bn/ctx.cc.inc | 209 +- .../crypto/fipsmodule/bn/div.cc.inc | 440 +- .../crypto/fipsmodule/bn/div_extra.cc.inc | 53 +- .../fipsmodule/bn/exponentiation.cc.inc | 735 +- .../crypto/fipsmodule/bn/gcd.cc.inc | 186 +- .../crypto/fipsmodule/bn/gcd_extra.cc.inc | 156 +- .../crypto/fipsmodule/bn/generic.cc.inc | 132 +- .../crypto/fipsmodule/bn/internal.h | 621 +- .../crypto/fipsmodule/bn/jacobi.cc.inc | 56 +- .../crypto/fipsmodule/bn/montgomery.cc.inc | 223 +- .../fipsmodule/bn/montgomery_inv.cc.inc | 179 +- .../crypto/fipsmodule/bn/mul.cc.inc | 488 +- .../crypto/fipsmodule/bn/prime.cc.inc | 404 +- .../crypto/fipsmodule/bn/random.cc.inc | 74 +- .../crypto/fipsmodule/bn/rsaz_exp.cc.inc | 65 +- .../crypto/fipsmodule/bn/rsaz_exp.h | 127 +- .../crypto/fipsmodule/bn/shift.cc.inc | 52 +- .../crypto/fipsmodule/bn/sqrt.cc.inc | 190 +- .../crypto/fipsmodule/cipher/aead.cc.inc | 562 +- .../crypto/fipsmodule/cipher/cipher.cc.inc | 634 +- .../crypto/fipsmodule/cipher/e_aes.cc.inc | 521 +- .../crypto/fipsmodule/cipher/e_aesccm.cc.inc | 220 +- .../crypto/fipsmodule/cipher/internal.h | 429 +- .../crypto/fipsmodule/cmac/cmac.cc.inc | 72 +- .../crypto/fipsmodule/delocate.h | 119 +- .../crypto/fipsmodule/dh/check.cc.inc | 168 +- .../crypto/fipsmodule/dh/dh.cc.inc | 381 +- .../crypto/fipsmodule/dh/internal.h | 76 +- .../crypto/fipsmodule/digest/digest.cc.inc | 130 +- .../crypto/fipsmodule/digest/digests.cc.inc | 41 +- .../crypto/fipsmodule/digest/internal.h | 51 +- .../crypto/fipsmodule/digest/md32_common.h | 192 +- .../fipsmodule/digestsign/digestsign.cc.inc | 93 +- .../crypto/fipsmodule/ec/builtin_curves.h | 26 +- .../crypto/fipsmodule/ec/ec.cc.inc | 545 +- .../crypto/fipsmodule/ec/ec_key.cc.inc | 396 +- .../crypto/fipsmodule/ec/ec_montgomery.cc.inc | 239 +- .../crypto/fipsmodule/ec/felem.cc.inc | 182 +- .../crypto/fipsmodule/ec/internal.h | 638 +- .../crypto/fipsmodule/ec/oct.cc.inc | 247 +- .../crypto/fipsmodule/ec/p224-64.cc.inc | 1163 --- .../crypto/fipsmodule/ec/p256-nistz-table.h | 23 +- .../crypto/fipsmodule/ec/p256-nistz.cc.inc | 128 +- .../crypto/fipsmodule/ec/p256-nistz.h | 81 +- .../crypto/fipsmodule/ec/p256.cc.inc | 345 +- .../crypto/fipsmodule/ec/p256_table.h | 26 +- .../crypto/fipsmodule/ec/scalar.cc.inc | 109 +- .../crypto/fipsmodule/ec/simple.cc.inc | 217 +- .../crypto/fipsmodule/ec/simple_mul.cc.inc | 99 +- .../crypto/fipsmodule/ec/util.cc.inc | 35 +- .../crypto/fipsmodule/ec/wnaf.cc.inc | 66 +- .../crypto/fipsmodule/ecdh/ecdh.cc.inc | 32 +- .../crypto/fipsmodule/ecdsa/ecdsa.cc.inc | 107 +- .../crypto/fipsmodule/ecdsa/internal.h | 41 +- .../crypto/fipsmodule/entropy/internal.h | 38 + .../crypto/fipsmodule/entropy/jitter.cc.inc | 463 + .../crypto/fipsmodule/entropy/sha512.cc.inc | 329 + .../crypto/fipsmodule/fips_shared_support.cc | 34 +- .../crypto/fipsmodule/hkdf/hkdf.cc.inc | 40 +- .../crypto/fipsmodule/hmac/hmac.cc.inc | 56 +- .../crypto/fipsmodule/keccak/internal.h | 157 +- .../crypto/fipsmodule/keccak/keccak.cc.inc | 514 +- .../fipsmodule/mldsa/fips_known_values.inc | 1345 +++ .../crypto/fipsmodule/mldsa/mldsa.cc.inc | 2744 ++++-- .../fipsmodule/mlkem/fips_known_values.inc | 411 + .../crypto/fipsmodule/mlkem/mlkem.cc.inc | 1641 +++- .../rand/android_entropy_client.cc.inc | 82 + .../crypto/fipsmodule/rand/ctrdrbg.cc.inc | 323 +- .../crypto/fipsmodule/rand/internal.h | 99 +- .../crypto/fipsmodule/rand/rand.cc.inc | 467 +- .../crypto/fipsmodule/rsa/blinding.cc.inc | 142 - .../crypto/fipsmodule/rsa/internal.h | 156 +- .../crypto/fipsmodule/rsa/padding.cc.inc | 127 +- .../crypto/fipsmodule/rsa/rsa.cc.inc | 508 +- .../crypto/fipsmodule/rsa/rsa_impl.cc.inc | 1117 +-- .../crypto/fipsmodule/self_check/fips.cc.inc | 46 +- .../fipsmodule/self_check/self_check.cc.inc | 957 +- .../fipsmodule/service_indicator/internal.h | 77 +- .../service_indicator.cc.inc | 115 +- .../crypto/fipsmodule/sha/internal.h | 203 +- .../crypto/fipsmodule/sha/sha1.cc.inc | 65 +- .../crypto/fipsmodule/sha/sha256.cc.inc | 97 +- .../crypto/fipsmodule/sha/sha512.cc.inc | 115 +- .../crypto/fipsmodule/slhdsa/address.h | 189 +- .../fipsmodule/slhdsa/fips_known_values.inc | 674 ++ .../crypto/fipsmodule/slhdsa/fors.cc.inc | 230 +- .../crypto/fipsmodule/slhdsa/fors.h | 64 +- .../crypto/fipsmodule/slhdsa/merkle.cc.inc | 207 +- .../crypto/fipsmodule/slhdsa/merkle.h | 76 +- .../crypto/fipsmodule/slhdsa/params.h | 222 +- .../crypto/fipsmodule/slhdsa/slhdsa.cc.inc | 635 +- .../crypto/fipsmodule/slhdsa/thash.cc.inc | 341 +- .../crypto/fipsmodule/slhdsa/thash.h | 80 +- .../crypto/fipsmodule/slhdsa/wots.cc.inc | 211 +- .../crypto/fipsmodule/slhdsa/wots.h | 56 +- .../crypto/fipsmodule/tls/internal.h | 44 +- .../crypto/fipsmodule/tls/kdf.cc.inc | 73 +- Sources/CNIOBoringSSL/crypto/fuzzer_mode.cc | 30 + Sources/CNIOBoringSSL/crypto/hpke/hpke.cc | 623 +- .../crypto/hrss/asm/poly_rq_mul.S | 21 +- Sources/CNIOBoringSSL/crypto/hrss/hrss.cc | 352 +- Sources/CNIOBoringSSL/crypto/hrss/internal.h | 54 +- Sources/CNIOBoringSSL/crypto/internal.h | 1091 ++- Sources/CNIOBoringSSL/crypto/kyber/internal.h | 60 - Sources/CNIOBoringSSL/crypto/kyber/kyber.cc | 869 -- Sources/CNIOBoringSSL/crypto/lhash/internal.h | 102 +- Sources/CNIOBoringSSL/crypto/lhash/lhash.cc | 154 +- Sources/CNIOBoringSSL/crypto/md4/md4.cc | 46 +- Sources/CNIOBoringSSL/crypto/md5/internal.h | 47 +- Sources/CNIOBoringSSL/crypto/md5/md5.cc | 45 +- Sources/CNIOBoringSSL/crypto/mem.cc | 149 +- Sources/CNIOBoringSSL/crypto/mem_internal.h | 706 ++ Sources/CNIOBoringSSL/crypto/mldsa/mldsa.cc | 296 +- Sources/CNIOBoringSSL/crypto/mlkem/mlkem.cc | 112 +- Sources/CNIOBoringSSL/crypto/obj/obj.cc | 310 +- Sources/CNIOBoringSSL/crypto/obj/obj_dat.h | 199 +- Sources/CNIOBoringSSL/crypto/obj/obj_xref.cc | 46 +- .../CNIOBoringSSL/crypto/params_internal.h | 30 + Sources/CNIOBoringSSL/crypto/pem/internal.h | 148 +- Sources/CNIOBoringSSL/crypto/pem/pem_all.cc | 73 +- Sources/CNIOBoringSSL/crypto/pem/pem_info.cc | 169 +- Sources/CNIOBoringSSL/crypto/pem/pem_lib.cc | 539 +- Sources/CNIOBoringSSL/crypto/pem/pem_oth.cc | 33 +- Sources/CNIOBoringSSL/crypto/pem/pem_pk8.cc | 50 +- Sources/CNIOBoringSSL/crypto/pem/pem_pkey.cc | 57 +- Sources/CNIOBoringSSL/crypto/pem/pem_x509.cc | 24 +- Sources/CNIOBoringSSL/crypto/pem/pem_xaux.cc | 24 +- Sources/CNIOBoringSSL/crypto/pkcs7/internal.h | 77 +- Sources/CNIOBoringSSL/crypto/pkcs7/pkcs7.cc | 95 +- .../CNIOBoringSSL/crypto/pkcs7/pkcs7_x509.cc | 385 +- Sources/CNIOBoringSSL/crypto/pkcs8/internal.h | 84 +- .../CNIOBoringSSL/crypto/pkcs8/p5_pbev2.cc | 104 +- Sources/CNIOBoringSSL/crypto/pkcs8/pkcs8.cc | 203 +- .../CNIOBoringSSL/crypto/pkcs8/pkcs8_x509.cc | 387 +- .../CNIOBoringSSL/crypto/poly1305/internal.h | 59 +- .../CNIOBoringSSL/crypto/poly1305/poly1305.cc | 35 +- .../crypto/poly1305/poly1305_arm.cc | 128 +- .../crypto/poly1305/poly1305_vec.cc | 87 +- Sources/CNIOBoringSSL/crypto/pool/internal.h | 116 +- Sources/CNIOBoringSSL/crypto/pool/pool.cc | 366 +- .../crypto/rand/deterministic.cc | 53 +- .../CNIOBoringSSL/crypto/rand/fork_detect.cc | 140 +- .../CNIOBoringSSL/crypto/rand/forkunsafe.cc | 40 +- .../CNIOBoringSSL/crypto/rand/getentropy.cc | 47 +- .../crypto/rand/getrandom_fillin.h | 64 - Sources/CNIOBoringSSL/crypto/rand/internal.h | 67 + Sources/CNIOBoringSSL/crypto/rand/ios.cc | 43 +- Sources/CNIOBoringSSL/crypto/rand/passive.cc | 178 - Sources/CNIOBoringSSL/crypto/rand/rand.cc | 46 +- .../crypto/rand/sysrand_internal.h | 37 - Sources/CNIOBoringSSL/crypto/rand/trusty.cc | 43 +- Sources/CNIOBoringSSL/crypto/rand/urandom.cc | 239 +- Sources/CNIOBoringSSL/crypto/rand/windows.cc | 63 +- Sources/CNIOBoringSSL/crypto/rc4/rc4.cc | 21 +- Sources/CNIOBoringSSL/crypto/refcount.cc | 50 +- Sources/CNIOBoringSSL/crypto/rsa/internal.h | 54 +- Sources/CNIOBoringSSL/crypto/rsa/rsa_asn1.cc | 298 +- Sources/CNIOBoringSSL/crypto/rsa/rsa_crypt.cc | 120 +- Sources/CNIOBoringSSL/crypto/rsa/rsa_extra.cc | 37 +- Sources/CNIOBoringSSL/crypto/rsa/rsa_print.cc | 31 +- Sources/CNIOBoringSSL/crypto/sha/sha1.cc | 29 +- Sources/CNIOBoringSSL/crypto/sha/sha256.cc | 30 +- Sources/CNIOBoringSSL/crypto/sha/sha512.cc | 36 +- .../CNIOBoringSSL/crypto/siphash/siphash.cc | 28 +- Sources/CNIOBoringSSL/crypto/slhdsa/slhdsa.cc | 92 +- .../crypto/spake2plus/internal.h | 94 +- .../crypto/spake2plus/spake2plus.cc | 30 +- Sources/CNIOBoringSSL/crypto/stack/stack.cc | 247 +- Sources/CNIOBoringSSL/crypto/thread.cc | 49 +- Sources/CNIOBoringSSL/crypto/thread_none.cc | 49 +- .../CNIOBoringSSL/crypto/thread_pthread.cc | 87 +- Sources/CNIOBoringSSL/crypto/thread_win.cc | 97 +- .../crypto/trust_token/internal.h | 199 +- .../crypto/trust_token/pmbtoken.cc | 330 +- .../crypto/trust_token/trust_token.cc | 202 +- .../CNIOBoringSSL/crypto/trust_token/voprf.cc | 203 +- Sources/CNIOBoringSSL/crypto/x509/a_digest.cc | 31 +- Sources/CNIOBoringSSL/crypto/x509/a_sign.cc | 130 +- Sources/CNIOBoringSSL/crypto/x509/a_verify.cc | 98 +- .../CNIOBoringSSL/crypto/x509/algorithm.cc | 84 +- Sources/CNIOBoringSSL/crypto/x509/asn1_gen.cc | 105 +- Sources/CNIOBoringSSL/crypto/x509/by_dir.cc | 447 +- Sources/CNIOBoringSSL/crypto/x509/by_file.cc | 80 +- Sources/CNIOBoringSSL/crypto/x509/ext_dat.h | 87 - Sources/CNIOBoringSSL/crypto/x509/i2d_pr.cc | 21 +- Sources/CNIOBoringSSL/crypto/x509/internal.h | 551 +- .../CNIOBoringSSL/crypto/x509/name_print.cc | 49 +- Sources/CNIOBoringSSL/crypto/x509/policy.cc | 1012 +-- Sources/CNIOBoringSSL/crypto/x509/rsa_pss.cc | 390 +- Sources/CNIOBoringSSL/crypto/x509/t_crl.cc | 40 +- Sources/CNIOBoringSSL/crypto/x509/t_req.cc | 70 +- Sources/CNIOBoringSSL/crypto/x509/t_x509.cc | 70 +- Sources/CNIOBoringSSL/crypto/x509/t_x509a.cc | 25 +- Sources/CNIOBoringSSL/crypto/x509/v3_akey.cc | 166 +- Sources/CNIOBoringSSL/crypto/x509/v3_akeya.cc | 25 +- Sources/CNIOBoringSSL/crypto/x509/v3_alt.cc | 202 +- Sources/CNIOBoringSSL/crypto/x509/v3_bcons.cc | 50 +- Sources/CNIOBoringSSL/crypto/x509/v3_bitst.cc | 55 +- Sources/CNIOBoringSSL/crypto/x509/v3_conf.cc | 150 +- Sources/CNIOBoringSSL/crypto/x509/v3_cpols.cc | 334 +- Sources/CNIOBoringSSL/crypto/x509/v3_crld.cc | 315 +- Sources/CNIOBoringSSL/crypto/x509/v3_enum.cc | 46 +- Sources/CNIOBoringSSL/crypto/x509/v3_extku.cc | 72 +- Sources/CNIOBoringSSL/crypto/x509/v3_genn.cc | 51 +- Sources/CNIOBoringSSL/crypto/x509/v3_ia5.cc | 61 +- Sources/CNIOBoringSSL/crypto/x509/v3_info.cc | 113 +- Sources/CNIOBoringSSL/crypto/x509/v3_int.cc | 89 +- Sources/CNIOBoringSSL/crypto/x509/v3_lib.cc | 190 +- Sources/CNIOBoringSSL/crypto/x509/v3_ncons.cc | 1109 ++- Sources/CNIOBoringSSL/crypto/x509/v3_ocsp.cc | 68 +- Sources/CNIOBoringSSL/crypto/x509/v3_pcons.cc | 50 +- Sources/CNIOBoringSSL/crypto/x509/v3_pmaps.cc | 52 +- Sources/CNIOBoringSSL/crypto/x509/v3_prn.cc | 33 +- Sources/CNIOBoringSSL/crypto/x509/v3_purp.cc | 311 +- Sources/CNIOBoringSSL/crypto/x509/v3_skey.cc | 70 +- Sources/CNIOBoringSSL/crypto/x509/v3_utl.cc | 374 +- Sources/CNIOBoringSSL/crypto/x509/x509.cc | 23 +- Sources/CNIOBoringSSL/crypto/x509/x509_att.cc | 83 +- Sources/CNIOBoringSSL/crypto/x509/x509_cmp.cc | 206 +- Sources/CNIOBoringSSL/crypto/x509/x509_d2.cc | 39 +- Sources/CNIOBoringSSL/crypto/x509/x509_def.cc | 35 +- Sources/CNIOBoringSSL/crypto/x509/x509_ext.cc | 91 +- Sources/CNIOBoringSSL/crypto/x509/x509_lu.cc | 427 +- Sources/CNIOBoringSSL/crypto/x509/x509_mtc.cc | 598 ++ Sources/CNIOBoringSSL/crypto/x509/x509_obj.cc | 62 +- Sources/CNIOBoringSSL/crypto/x509/x509_req.cc | 104 +- Sources/CNIOBoringSSL/crypto/x509/x509_set.cc | 169 +- Sources/CNIOBoringSSL/crypto/x509/x509_trs.cc | 52 +- Sources/CNIOBoringSSL/crypto/x509/x509_txt.cc | 21 +- Sources/CNIOBoringSSL/crypto/x509/x509_v3.cc | 87 +- Sources/CNIOBoringSSL/crypto/x509/x509_vfy.cc | 779 +- Sources/CNIOBoringSSL/crypto/x509/x509_vpm.cc | 126 +- Sources/CNIOBoringSSL/crypto/x509/x509cset.cc | 88 +- Sources/CNIOBoringSSL/crypto/x509/x509name.cc | 191 +- Sources/CNIOBoringSSL/crypto/x509/x509rset.cc | 43 +- Sources/CNIOBoringSSL/crypto/x509/x509spki.cc | 47 +- Sources/CNIOBoringSSL/crypto/x509/x_algor.cc | 169 +- Sources/CNIOBoringSSL/crypto/x509/x_all.cc | 133 +- Sources/CNIOBoringSSL/crypto/x509/x_attrib.cc | 35 +- Sources/CNIOBoringSSL/crypto/x509/x_crl.cc | 147 +- Sources/CNIOBoringSSL/crypto/x509/x_exten.cc | 27 +- Sources/CNIOBoringSSL/crypto/x509/x_name.cc | 748 +- Sources/CNIOBoringSSL/crypto/x509/x_pubkey.cc | 220 +- Sources/CNIOBoringSSL/crypto/x509/x_req.cc | 39 +- Sources/CNIOBoringSSL/crypto/x509/x_sig.cc | 29 +- Sources/CNIOBoringSSL/crypto/x509/x_spki.cc | 33 +- Sources/CNIOBoringSSL/crypto/x509/x_val.cc | 23 - Sources/CNIOBoringSSL/crypto/x509/x_x509.cc | 616 +- Sources/CNIOBoringSSL/crypto/x509/x_x509a.cc | 141 +- Sources/CNIOBoringSSL/crypto/xwing/xwing.cc | 257 + .../gen/bcm/aes-gcm-avx10-x86_64-apple.S | 1255 --- .../gen/bcm/aes-gcm-avx10-x86_64-linux.S | 1260 --- .../gen/bcm/aes-gcm-avx2-x86_64-apple.S | 455 +- .../gen/bcm/aes-gcm-avx2-x86_64-linux.S | 451 +- .../gen/bcm/aes-gcm-avx512-x86_64-apple.S | 1257 +++ .../gen/bcm/aes-gcm-avx512-x86_64-linux.S | 1258 +++ .../gen/bcm/aesni-gcm-x86_64-apple.S | 313 +- .../gen/bcm/aesni-gcm-x86_64-linux.S | 310 +- .../CNIOBoringSSL/gen/bcm/aesni-x86-apple.S | 506 +- .../CNIOBoringSSL/gen/bcm/aesni-x86-linux.S | 506 +- .../gen/bcm/aesni-x86_64-apple.S | 1513 ++-- .../gen/bcm/aesni-x86_64-linux.S | 1496 +-- .../CNIOBoringSSL/gen/bcm/aesv8-armv7-linux.S | 4 +- .../CNIOBoringSSL/gen/bcm/aesv8-armv8-apple.S | 10 +- .../CNIOBoringSSL/gen/bcm/aesv8-armv8-linux.S | 4 +- .../CNIOBoringSSL/gen/bcm/aesv8-armv8-win.S | 4 +- .../gen/bcm/aesv8-gcm-armv8-apple.S | 3925 +++++--- .../gen/bcm/aesv8-gcm-armv8-linux.S | 3922 +++++--- .../gen/bcm/aesv8-gcm-armv8-win.S | 3926 +++++--- .../CNIOBoringSSL/gen/bcm/armv4-mont-linux.S | 15 +- .../CNIOBoringSSL/gen/bcm/armv8-mont-apple.S | 63 +- .../CNIOBoringSSL/gen/bcm/armv8-mont-linux.S | 71 +- .../CNIOBoringSSL/gen/bcm/armv8-mont-win.S | 67 +- Sources/CNIOBoringSSL/gen/bcm/bn-586-apple.S | 29 +- Sources/CNIOBoringSSL/gen/bcm/bn-586-linux.S | 35 +- .../CNIOBoringSSL/gen/bcm/bn-armv8-apple.S | 3 +- .../CNIOBoringSSL/gen/bcm/bn-armv8-linux.S | 2 - Sources/CNIOBoringSSL/gen/bcm/bn-armv8-win.S | 2 - .../CNIOBoringSSL/gen/bcm/bsaes-armv7-linux.S | 23 +- .../CNIOBoringSSL/gen/bcm/ghash-armv4-linux.S | 2 - .../gen/bcm/ghash-neon-armv8-apple.S | 6 +- .../gen/bcm/ghash-neon-armv8-linux.S | 4 +- .../gen/bcm/ghash-neon-armv8-win.S | 4 +- .../gen/bcm/ghash-ssse3-x86-apple.S | 46 +- .../gen/bcm/ghash-ssse3-x86-linux.S | 46 +- .../gen/bcm/ghash-ssse3-x86_64-apple.S | 283 +- .../gen/bcm/ghash-ssse3-x86_64-linux.S | 282 +- .../CNIOBoringSSL/gen/bcm/ghash-x86-apple.S | 62 +- .../CNIOBoringSSL/gen/bcm/ghash-x86-linux.S | 62 +- .../gen/bcm/ghash-x86_64-apple.S | 787 +- .../gen/bcm/ghash-x86_64-linux.S | 782 +- .../gen/bcm/ghashv8-armv7-linux.S | 2 - .../gen/bcm/ghashv8-armv8-apple.S | 6 +- .../gen/bcm/ghashv8-armv8-linux.S | 2 - .../CNIOBoringSSL/gen/bcm/ghashv8-armv8-win.S | 2 - .../gen/bcm/p256-armv8-asm-apple.S | 22 +- .../gen/bcm/p256-armv8-asm-linux.S | 3 +- .../gen/bcm/p256-armv8-asm-win.S | 3 +- .../gen/bcm/p256-x86_64-asm-apple.S | 1291 +-- .../gen/bcm/p256-x86_64-asm-linux.S | 1261 +-- .../gen/bcm/p256_beeu-armv8-asm-apple.S | 5 +- .../gen/bcm/p256_beeu-armv8-asm-linux.S | 5 +- .../gen/bcm/p256_beeu-armv8-asm-win.S | 5 +- .../gen/bcm/p256_beeu-x86_64-asm-apple.S | 93 +- .../gen/bcm/p256_beeu-x86_64-asm-linux.S | 93 +- .../gen/bcm/rdrand-x86_64-apple.S | 21 +- .../gen/bcm/rdrand-x86_64-linux.S | 20 +- .../CNIOBoringSSL/gen/bcm/rsaz-avx2-apple.S | 215 +- .../CNIOBoringSSL/gen/bcm/rsaz-avx2-linux.S | 210 +- .../CNIOBoringSSL/gen/bcm/sha1-586-apple.S | 16 +- .../CNIOBoringSSL/gen/bcm/sha1-586-linux.S | 16 +- .../gen/bcm/sha1-armv4-large-linux.S | 2 - .../CNIOBoringSSL/gen/bcm/sha1-armv8-apple.S | 5 +- .../CNIOBoringSSL/gen/bcm/sha1-armv8-linux.S | 4 +- .../CNIOBoringSSL/gen/bcm/sha1-armv8-win.S | 4 +- .../CNIOBoringSSL/gen/bcm/sha1-x86_64-apple.S | 356 +- .../CNIOBoringSSL/gen/bcm/sha1-x86_64-linux.S | 352 +- .../CNIOBoringSSL/gen/bcm/sha256-586-apple.S | 24 +- .../CNIOBoringSSL/gen/bcm/sha256-586-linux.S | 24 +- .../gen/bcm/sha256-armv4-linux.S | 25 +- .../gen/bcm/sha256-armv8-apple.S | 140 +- .../gen/bcm/sha256-armv8-linux.S | 139 +- .../CNIOBoringSSL/gen/bcm/sha256-armv8-win.S | 139 +- .../gen/bcm/sha256-x86_64-apple.S | 1289 +-- .../gen/bcm/sha256-x86_64-linux.S | 1286 +-- .../CNIOBoringSSL/gen/bcm/sha512-586-apple.S | 64 +- .../CNIOBoringSSL/gen/bcm/sha512-586-linux.S | 64 +- .../gen/bcm/sha512-armv4-linux.S | 22 +- .../gen/bcm/sha512-armv8-apple.S | 404 +- .../gen/bcm/sha512-armv8-linux.S | 403 +- .../CNIOBoringSSL/gen/bcm/sha512-armv8-win.S | 403 +- .../gen/bcm/sha512-x86_64-apple.S | 1063 +-- .../gen/bcm/sha512-x86_64-linux.S | 1062 +-- .../CNIOBoringSSL/gen/bcm/vpaes-armv8-apple.S | 28 +- .../CNIOBoringSSL/gen/bcm/vpaes-armv8-linux.S | 12 +- .../CNIOBoringSSL/gen/bcm/vpaes-armv8-win.S | 12 +- .../CNIOBoringSSL/gen/bcm/vpaes-x86-apple.S | 138 +- .../CNIOBoringSSL/gen/bcm/vpaes-x86-linux.S | 138 +- .../gen/bcm/vpaes-x86_64-apple.S | 1097 +-- .../gen/bcm/vpaes-x86_64-linux.S | 1082 +-- .../CNIOBoringSSL/gen/bcm/x86-mont-apple.S | 49 +- .../CNIOBoringSSL/gen/bcm/x86-mont-linux.S | 53 +- .../CNIOBoringSSL/gen/bcm/x86_64-mont-apple.S | 601 +- .../CNIOBoringSSL/gen/bcm/x86_64-mont-linux.S | 598 +- .../gen/bcm/x86_64-mont5-apple.S | 1950 ++-- .../gen/bcm/x86_64-mont5-linux.S | 1934 ++-- .../gen/crypto/aes128gcmsiv-x86_64-apple.S | 370 +- .../gen/crypto/aes128gcmsiv-x86_64-linux.S | 338 +- .../gen/crypto/chacha-armv4-linux.S | 3 +- .../gen/crypto/chacha-armv8-apple.S | 5 +- .../gen/crypto/chacha-armv8-linux.S | 3 +- .../gen/crypto/chacha-armv8-win.S | 3 +- .../gen/crypto/chacha-x86-apple.S | 8 +- .../gen/crypto/chacha-x86-linux.S | 8 +- .../gen/crypto/chacha-x86_64-apple.S | 445 +- .../gen/crypto/chacha-x86_64-linux.S | 442 +- .../crypto/chacha20_poly1305_armv8-apple.S | 9 +- .../crypto/chacha20_poly1305_armv8-linux.S | 7 +- .../gen/crypto/chacha20_poly1305_armv8-win.S | 7 +- .../crypto/chacha20_poly1305_x86_64-apple.S | 1101 +-- .../crypto/chacha20_poly1305_x86_64-linux.S | 1104 +-- Sources/CNIOBoringSSL/gen/crypto/err_data.cc | 1213 +-- .../gen/crypto/md5-x86_64-apple.S | 1230 +-- .../gen/crypto/md5-x86_64-linux.S | 1230 +-- Sources/CNIOBoringSSL/hash.txt | 2 +- Sources/CNIOBoringSSL/include/CNIOBoringSSL.h | 48 +- .../include/CNIOBoringSSL_aead.h | 446 +- .../CNIOBoringSSL/include/CNIOBoringSSL_aes.h | 109 +- .../include/CNIOBoringSSL_arm_arch.h | 49 +- .../include/CNIOBoringSSL_asm_base.h | 73 +- .../include/CNIOBoringSSL_asn1.h | 1337 ++- .../include/CNIOBoringSSL_asn1_mac.h | 26 +- .../include/CNIOBoringSSL_asn1t.h | 39 +- .../include/CNIOBoringSSL_base.h | 176 +- .../include/CNIOBoringSSL_base64.h | 83 +- .../include/CNIOBoringSSL_bcm_public.h | 82 - .../CNIOBoringSSL/include/CNIOBoringSSL_bio.h | 735 +- .../include/CNIOBoringSSL_blake2.h | 52 +- .../include/CNIOBoringSSL_blowfish.h | 36 +- .../CNIOBoringSSL/include/CNIOBoringSSL_bn.h | 629 +- .../CNIOBoringSSL_boringssl_prefix_symbols.h | 4961 ---------- ...IOBoringSSL_boringssl_prefix_symbols_asm.h | 4004 --------- .../CNIOBoringSSL/include/CNIOBoringSSL_buf.h | 51 +- .../include/CNIOBoringSSL_buffer.h | 26 +- .../include/CNIOBoringSSL_bytestring.h | 550 +- .../include/CNIOBoringSSL_cast.h | 76 +- .../include/CNIOBoringSSL_chacha.h | 34 +- .../include/CNIOBoringSSL_cipher.h | 521 +- .../include/CNIOBoringSSL_cmac.h | 54 +- .../CNIOBoringSSL/include/CNIOBoringSSL_cms.h | 147 + .../include/CNIOBoringSSL_conf.h | 52 +- .../include/CNIOBoringSSL_configuration.h | 18 + .../CNIOBoringSSL/include/CNIOBoringSSL_cpu.h | 26 +- .../include/CNIOBoringSSL_crypto.h | 78 +- .../include/CNIOBoringSSL_ctrdrbg.h | 90 +- .../include/CNIOBoringSSL_curve25519.h | 112 +- .../CNIOBoringSSL/include/CNIOBoringSSL_des.h | 61 +- .../CNIOBoringSSL/include/CNIOBoringSSL_dh.h | 213 +- .../include/CNIOBoringSSL_digest.h | 260 +- .../CNIOBoringSSL/include/CNIOBoringSSL_dsa.h | 225 +- .../include/CNIOBoringSSL_dtls1.h | 26 +- .../include/CNIOBoringSSL_e_os2.h | 28 +- .../CNIOBoringSSL/include/CNIOBoringSSL_ec.h | 321 +- .../include/CNIOBoringSSL_ec_key.h | 221 +- .../include/CNIOBoringSSL_ecdh.h | 43 +- .../include/CNIOBoringSSL_ecdsa.h | 158 +- .../include/CNIOBoringSSL_engine.h | 38 +- .../CNIOBoringSSL/include/CNIOBoringSSL_err.h | 168 +- .../CNIOBoringSSL/include/CNIOBoringSSL_evp.h | 1306 ++- .../include/CNIOBoringSSL_evp_errors.h | 33 +- .../include/CNIOBoringSSL_ex_data.h | 80 +- .../include/CNIOBoringSSL_hkdf.h | 40 +- .../include/CNIOBoringSSL_hmac.h | 89 +- .../include/CNIOBoringSSL_hpke.h | 302 +- .../include/CNIOBoringSSL_hrss.h | 50 +- .../include/CNIOBoringSSL_is_boringssl.h | 26 +- .../CNIOBoringSSL/include/CNIOBoringSSL_kdf.h | 67 +- .../include/CNIOBoringSSL_lhash.h | 46 +- .../CNIOBoringSSL/include/CNIOBoringSSL_md4.h | 44 +- .../CNIOBoringSSL/include/CNIOBoringSSL_md5.h | 37 +- .../CNIOBoringSSL/include/CNIOBoringSSL_mem.h | 105 +- .../include/CNIOBoringSSL_mldsa.h | 430 +- .../include/CNIOBoringSSL_mlkem.h | 114 +- .../CNIOBoringSSL/include/CNIOBoringSSL_nid.h | 1386 ++- .../CNIOBoringSSL/include/CNIOBoringSSL_obj.h | 121 +- .../include/CNIOBoringSSL_obj_mac.h | 28 +- .../include/CNIOBoringSSL_objects.h | 26 +- .../include/CNIOBoringSSL_opensslconf.h | 70 +- .../include/CNIOBoringSSL_opensslv.h | 26 +- .../include/CNIOBoringSSL_ossl_typ.h | 26 +- .../include/CNIOBoringSSL_params.h | 42 + .../CNIOBoringSSL/include/CNIOBoringSSL_pem.h | 1045 ++- .../include/CNIOBoringSSL_pkcs12.h | 26 +- .../include/CNIOBoringSSL_pkcs7.h | 108 +- .../include/CNIOBoringSSL_pkcs8.h | 168 +- .../include/CNIOBoringSSL_poly1305.h | 41 +- .../include/CNIOBoringSSL_pool.h | 105 +- .../include/CNIOBoringSSL_posix_time.h | 42 +- .../include/CNIOBoringSSL_prefix_symbols.h | 7988 +++++++++++++++++ .../CNIOBoringSSL_prefix_symbols_internal_S.h | 633 ++ .../CNIOBoringSSL_prefix_symbols_internal_c.h | 329 + .../include/CNIOBoringSSL_rand.h | 66 +- .../CNIOBoringSSL/include/CNIOBoringSSL_rc4.h | 31 +- .../include/CNIOBoringSSL_ripemd.h | 48 +- .../CNIOBoringSSL/include/CNIOBoringSSL_rsa.h | 530 +- .../include/CNIOBoringSSL_safestack.h | 26 +- .../include/CNIOBoringSSL_service_indicator.h | 109 +- .../CNIOBoringSSL/include/CNIOBoringSSL_sha.h | 230 +- .../include/CNIOBoringSSL_sha2.h | 201 + .../include/CNIOBoringSSL_siphash.h | 28 +- .../include/CNIOBoringSSL_slhdsa.h | 200 +- .../include/CNIOBoringSSL_span.h | 311 +- .../include/CNIOBoringSSL_srtp.h | 26 +- .../CNIOBoringSSL/include/CNIOBoringSSL_ssl.h | 4341 +++++---- .../include/CNIOBoringSSL_ssl3.h | 103 +- .../include/CNIOBoringSSL_stack.h | 247 +- .../include/CNIOBoringSSL_target.h | 45 +- .../include/CNIOBoringSSL_thread.h | 33 +- .../include/CNIOBoringSSL_time.h | 26 +- .../include/CNIOBoringSSL_tls1.h | 394 +- .../include/CNIOBoringSSL_tls_prf.h | 47 + .../include/CNIOBoringSSL_trust_token.h | 217 +- .../include/CNIOBoringSSL_type_check.h | 25 +- .../include/CNIOBoringSSL_types.h | 18 + .../include/CNIOBoringSSL_x509.h | 3727 ++++---- .../include/CNIOBoringSSL_x509_vfy.h | 26 +- .../include/CNIOBoringSSL_x509v3.h | 28 +- .../include/CNIOBoringSSL_x509v3_errors.h | 21 +- .../include/CNIOBoringSSL_xwing.h | 115 + .../include/boringssl_prefix_symbols_nasm.inc | 7976 ---------------- .../experimental/CNIOBoringSSL_kyber.h | 146 - .../CNIOBoringSSL/include/module.modulemap | 7 + Sources/CNIOBoringSSL/ssl/bio_ssl.cc | 62 +- Sources/CNIOBoringSSL/ssl/d1_both.cc | 358 +- Sources/CNIOBoringSSL/ssl/d1_lib.cc | 173 +- Sources/CNIOBoringSSL/ssl/d1_pkt.cc | 41 +- Sources/CNIOBoringSSL/ssl/d1_srtp.cc | 52 +- Sources/CNIOBoringSSL/ssl/dtls_method.cc | 51 +- Sources/CNIOBoringSSL/ssl/dtls_record.cc | 116 +- .../ssl/encrypted_client_hello.cc | 325 +- Sources/CNIOBoringSSL/ssl/extensions.cc | 2184 +++-- Sources/CNIOBoringSSL/ssl/handoff.cc | 281 +- Sources/CNIOBoringSSL/ssl/handshake.cc | 159 +- Sources/CNIOBoringSSL/ssl/handshake_client.cc | 380 +- Sources/CNIOBoringSSL/ssl/handshake_server.cc | 447 +- Sources/CNIOBoringSSL/ssl/internal.h | 2949 +++--- Sources/CNIOBoringSSL/ssl/s3_both.cc | 231 +- Sources/CNIOBoringSSL/ssl/s3_lib.cc | 35 +- Sources/CNIOBoringSSL/ssl/s3_pkt.cc | 64 +- Sources/CNIOBoringSSL/ssl/ssl_aead_ctx.cc | 54 +- Sources/CNIOBoringSSL/ssl/ssl_asn1.cc | 229 +- Sources/CNIOBoringSSL/ssl/ssl_buffer.cc | 77 +- Sources/CNIOBoringSSL/ssl/ssl_cert.cc | 263 +- Sources/CNIOBoringSSL/ssl/ssl_cipher.cc | 528 +- Sources/CNIOBoringSSL/ssl/ssl_credential.cc | 614 +- Sources/CNIOBoringSSL/ssl/ssl_file.cc | 380 +- Sources/CNIOBoringSSL/ssl/ssl_key_share.cc | 207 +- Sources/CNIOBoringSSL/ssl/ssl_lib.cc | 2268 +++-- Sources/CNIOBoringSSL/ssl/ssl_privkey.cc | 322 +- Sources/CNIOBoringSSL/ssl/ssl_session.cc | 874 +- Sources/CNIOBoringSSL/ssl/ssl_stat.cc | 32 +- Sources/CNIOBoringSSL/ssl/ssl_transcript.cc | 31 +- Sources/CNIOBoringSSL/ssl/ssl_versions.cc | 114 +- Sources/CNIOBoringSSL/ssl/ssl_x509.cc | 619 +- Sources/CNIOBoringSSL/ssl/t1_enc.cc | 94 +- Sources/CNIOBoringSSL/ssl/tls13_both.cc | 242 +- Sources/CNIOBoringSSL/ssl/tls13_client.cc | 427 +- Sources/CNIOBoringSSL/ssl/tls13_enc.cc | 343 +- Sources/CNIOBoringSSL/ssl/tls13_server.cc | 588 +- Sources/CNIOBoringSSL/ssl/tls_method.cc | 91 +- Sources/CNIOBoringSSL/ssl/tls_record.cc | 102 +- .../fiat/bedrock_polyfill_platform.c.inc | 66 + .../fiat/bedrock_unverified_bareminimum.c.inc | 47 + .../fiat/bedrock_unverified_platform.c.inc | 137 + .../third_party/fiat/curve25519_64_adx.h | 70 +- .../CNIOBoringSSL/third_party/fiat/p256_64.h | 109 +- .../third_party/fiat/p256_64_msvc.h | 75 +- .../third_party/fiat/p256_field.c.inc | 26 + .../third_party/fiat/p256_field_32.br.c.inc | 71 + .../third_party/fiat/p256_field_64.br.c.inc | 84 + .../third_party/fiat/p256_point.br.c.inc | 112 + .../include/CNIOBoringSSLShims.h | 15 + Sources/CNIOBoringSSLShims/shims.c | 44 + Sources/NIOSSL/ByteBufferBIO.swift | 72 +- Sources/NIOSSL/ObjectIdentifier.swift | 18 +- Sources/NIOSSL/SSLCallbacks.swift | 2 +- Sources/NIOSSL/SSLCertificate.swift | 92 +- Sources/NIOSSL/SSLCertificateExtensions.swift | 22 +- Sources/NIOSSL/SSLCertificateName.swift | 18 +- Sources/NIOSSL/SSLConnection.swift | 73 +- Sources/NIOSSL/SSLContext.swift | 72 +- Sources/NIOSSL/SSLErrors.swift | 4 +- Sources/NIOSSL/SSLInit.swift | 2 +- Sources/NIOSSL/SSLPKCS12Bundle.swift | 41 +- Sources/NIOSSL/SSLPrivateKey.swift | 32 +- Sources/NIOSSL/SSLPublicKey.swift | 10 +- Sources/NIOSSL/SubjectAlternativeName.swift | 6 +- Sources/NIOSSL/SwiftCrypto/Zeroization.swift | 2 +- Sources/NIOSSL/TLSConfiguration.swift | 4 +- Sources/NIOSSL/UnsafeKeyAndChainTarget.swift | 28 +- Tests/NIOSSLTests/ByteBufferBIOTest.swift | 96 +- Tests/NIOSSLTests/CustomPrivateKeyTests.swift | 46 +- Tests/NIOSSLTests/NIOSSLIntegrationTest.swift | 14 +- Tests/NIOSSLTests/NIOSSLTestHelpers.swift | 74 +- Tests/NIOSSLTests/ObjectIdentifierTests.swift | 4 +- scripts/boringssl-unprefixed-types.txt | 55 + scripts/check-symbol-prefixing.py | 547 ++ scripts/patch-1-inttypes.patch | 7 +- scripts/patch-2-inttypes.patch | 9 +- scripts/patch-3-more-inttypes.patch | 6 +- scripts/vendor-boringssl.sh | 193 +- 717 files changed, 110173 insertions(+), 91954 deletions(-) create mode 100644 Sources/CNIOBoringSSL/crypto/aes/aes.cc create mode 100644 Sources/CNIOBoringSSL/crypto/armv8_feature_parsing.h create mode 100644 Sources/CNIOBoringSSL/crypto/bn/div.cc create mode 100644 Sources/CNIOBoringSSL/crypto/bn/exponentiation.cc create mode 100644 Sources/CNIOBoringSSL/crypto/bn/sqrt.cc create mode 100644 Sources/CNIOBoringSSL/crypto/cipher/e_aeseax.cc create mode 100644 Sources/CNIOBoringSSL/crypto/cms/cms.cc create mode 100644 Sources/CNIOBoringSSL/crypto/ecdsa/ecdsa_p1363.cc create mode 100644 Sources/CNIOBoringSSL/crypto/evp/evp_kem.cc delete mode 100644 Sources/CNIOBoringSSL/crypto/evp/p_dh_asn1.cc create mode 100644 Sources/CNIOBoringSSL/crypto/evp/p_dsa.cc delete mode 100644 Sources/CNIOBoringSSL/crypto/evp/p_dsa_asn1.cc delete mode 100644 Sources/CNIOBoringSSL/crypto/evp/p_ec_asn1.cc delete mode 100644 Sources/CNIOBoringSSL/crypto/evp/p_ed25519_asn1.cc create mode 100644 Sources/CNIOBoringSSL/crypto/evp/p_mldsa.cc create mode 100644 Sources/CNIOBoringSSL/crypto/evp/p_mlkem.cc delete mode 100644 Sources/CNIOBoringSSL/crypto/evp/p_rsa_asn1.cc delete mode 100644 Sources/CNIOBoringSSL/crypto/evp/p_x25519_asn1.cc create mode 100644 Sources/CNIOBoringSSL/crypto/evp/p_xwing.cc delete mode 100644 Sources/CNIOBoringSSL/crypto/fipsmodule/aes/polyval.cc.inc delete mode 100644 Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p224-64.cc.inc create mode 100644 Sources/CNIOBoringSSL/crypto/fipsmodule/entropy/internal.h create mode 100644 Sources/CNIOBoringSSL/crypto/fipsmodule/entropy/jitter.cc.inc create mode 100644 Sources/CNIOBoringSSL/crypto/fipsmodule/entropy/sha512.cc.inc create mode 100644 Sources/CNIOBoringSSL/crypto/fipsmodule/mldsa/fips_known_values.inc create mode 100644 Sources/CNIOBoringSSL/crypto/fipsmodule/mlkem/fips_known_values.inc create mode 100644 Sources/CNIOBoringSSL/crypto/fipsmodule/rand/android_entropy_client.cc.inc delete mode 100644 Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/blinding.cc.inc create mode 100644 Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/fips_known_values.inc create mode 100644 Sources/CNIOBoringSSL/crypto/fuzzer_mode.cc delete mode 100644 Sources/CNIOBoringSSL/crypto/kyber/internal.h delete mode 100644 Sources/CNIOBoringSSL/crypto/kyber/kyber.cc create mode 100644 Sources/CNIOBoringSSL/crypto/mem_internal.h create mode 100644 Sources/CNIOBoringSSL/crypto/params_internal.h delete mode 100644 Sources/CNIOBoringSSL/crypto/rand/getrandom_fillin.h create mode 100644 Sources/CNIOBoringSSL/crypto/rand/internal.h delete mode 100644 Sources/CNIOBoringSSL/crypto/rand/sysrand_internal.h delete mode 100644 Sources/CNIOBoringSSL/crypto/x509/ext_dat.h create mode 100644 Sources/CNIOBoringSSL/crypto/x509/x509_mtc.cc delete mode 100644 Sources/CNIOBoringSSL/crypto/x509/x_val.cc create mode 100644 Sources/CNIOBoringSSL/crypto/xwing/xwing.cc delete mode 100644 Sources/CNIOBoringSSL/gen/bcm/aes-gcm-avx10-x86_64-apple.S delete mode 100644 Sources/CNIOBoringSSL/gen/bcm/aes-gcm-avx10-x86_64-linux.S create mode 100644 Sources/CNIOBoringSSL/gen/bcm/aes-gcm-avx512-x86_64-apple.S create mode 100644 Sources/CNIOBoringSSL/gen/bcm/aes-gcm-avx512-x86_64-linux.S delete mode 100644 Sources/CNIOBoringSSL/include/CNIOBoringSSL_bcm_public.h delete mode 100644 Sources/CNIOBoringSSL/include/CNIOBoringSSL_boringssl_prefix_symbols.h delete mode 100644 Sources/CNIOBoringSSL/include/CNIOBoringSSL_boringssl_prefix_symbols_asm.h create mode 100644 Sources/CNIOBoringSSL/include/CNIOBoringSSL_cms.h create mode 100644 Sources/CNIOBoringSSL/include/CNIOBoringSSL_configuration.h create mode 100644 Sources/CNIOBoringSSL/include/CNIOBoringSSL_params.h create mode 100644 Sources/CNIOBoringSSL/include/CNIOBoringSSL_prefix_symbols.h create mode 100644 Sources/CNIOBoringSSL/include/CNIOBoringSSL_prefix_symbols_internal_S.h create mode 100644 Sources/CNIOBoringSSL/include/CNIOBoringSSL_prefix_symbols_internal_c.h create mode 100644 Sources/CNIOBoringSSL/include/CNIOBoringSSL_sha2.h create mode 100644 Sources/CNIOBoringSSL/include/CNIOBoringSSL_tls_prf.h create mode 100644 Sources/CNIOBoringSSL/include/CNIOBoringSSL_types.h create mode 100644 Sources/CNIOBoringSSL/include/CNIOBoringSSL_xwing.h delete mode 100644 Sources/CNIOBoringSSL/include/boringssl_prefix_symbols_nasm.inc delete mode 100644 Sources/CNIOBoringSSL/include/experimental/CNIOBoringSSL_kyber.h create mode 100644 Sources/CNIOBoringSSL/third_party/fiat/bedrock_polyfill_platform.c.inc create mode 100644 Sources/CNIOBoringSSL/third_party/fiat/bedrock_unverified_bareminimum.c.inc create mode 100644 Sources/CNIOBoringSSL/third_party/fiat/bedrock_unverified_platform.c.inc create mode 100644 Sources/CNIOBoringSSL/third_party/fiat/p256_field.c.inc create mode 100644 Sources/CNIOBoringSSL/third_party/fiat/p256_field_32.br.c.inc create mode 100644 Sources/CNIOBoringSSL/third_party/fiat/p256_field_64.br.c.inc create mode 100644 Sources/CNIOBoringSSL/third_party/fiat/p256_point.br.c.inc create mode 100644 scripts/boringssl-unprefixed-types.txt create mode 100755 scripts/check-symbol-prefixing.py diff --git a/Benchmarks/Thresholds/6.1/NIOSSLBenchmarks.ManyWrites.p90.json b/Benchmarks/Thresholds/6.1/NIOSSLBenchmarks.ManyWrites.p90.json index 89122218..efeae089 100644 --- a/Benchmarks/Thresholds/6.1/NIOSSLBenchmarks.ManyWrites.p90.json +++ b/Benchmarks/Thresholds/6.1/NIOSSLBenchmarks.ManyWrites.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 201953 + "mallocCountTotal" : 201700 } diff --git a/Benchmarks/Thresholds/6.1/NIOSSLBenchmarks.SimpleHandshake.p90.json b/Benchmarks/Thresholds/6.1/NIOSSLBenchmarks.SimpleHandshake.p90.json index b0f75e64..77a4ee9a 100644 --- a/Benchmarks/Thresholds/6.1/NIOSSLBenchmarks.SimpleHandshake.p90.json +++ b/Benchmarks/Thresholds/6.1/NIOSSLBenchmarks.SimpleHandshake.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 641893 + "mallocCountTotal" : 423833 } diff --git a/Benchmarks/Thresholds/6.2/NIOSSLBenchmarks.ManyWrites.p90.json b/Benchmarks/Thresholds/6.2/NIOSSLBenchmarks.ManyWrites.p90.json index 7904a26c..7a407260 100644 --- a/Benchmarks/Thresholds/6.2/NIOSSLBenchmarks.ManyWrites.p90.json +++ b/Benchmarks/Thresholds/6.2/NIOSSLBenchmarks.ManyWrites.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 201954 + "mallocCountTotal" : 201685 } diff --git a/Benchmarks/Thresholds/6.2/NIOSSLBenchmarks.SimpleHandshake.p90.json b/Benchmarks/Thresholds/6.2/NIOSSLBenchmarks.SimpleHandshake.p90.json index 561e8558..36b5aad6 100644 --- a/Benchmarks/Thresholds/6.2/NIOSSLBenchmarks.SimpleHandshake.p90.json +++ b/Benchmarks/Thresholds/6.2/NIOSSLBenchmarks.SimpleHandshake.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 642876 + "mallocCountTotal" : 424806 } diff --git a/Benchmarks/Thresholds/6.3/NIOSSLBenchmarks.ManyWrites.p90.json b/Benchmarks/Thresholds/6.3/NIOSSLBenchmarks.ManyWrites.p90.json index 7904a26c..9b80de19 100644 --- a/Benchmarks/Thresholds/6.3/NIOSSLBenchmarks.ManyWrites.p90.json +++ b/Benchmarks/Thresholds/6.3/NIOSSLBenchmarks.ManyWrites.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 201954 + "mallocCountTotal" : 201649 } diff --git a/Benchmarks/Thresholds/6.3/NIOSSLBenchmarks.SimpleHandshake.p90.json b/Benchmarks/Thresholds/6.3/NIOSSLBenchmarks.SimpleHandshake.p90.json index 018ee27e..0191641c 100644 --- a/Benchmarks/Thresholds/6.3/NIOSSLBenchmarks.SimpleHandshake.p90.json +++ b/Benchmarks/Thresholds/6.3/NIOSSLBenchmarks.SimpleHandshake.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 641884 + "mallocCountTotal" : 423800 } diff --git a/Benchmarks/Thresholds/nightly-main/NIOSSLBenchmarks.ManyWrites.p90.json b/Benchmarks/Thresholds/nightly-main/NIOSSLBenchmarks.ManyWrites.p90.json index 7904a26c..9b80de19 100644 --- a/Benchmarks/Thresholds/nightly-main/NIOSSLBenchmarks.ManyWrites.p90.json +++ b/Benchmarks/Thresholds/nightly-main/NIOSSLBenchmarks.ManyWrites.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 201954 + "mallocCountTotal" : 201649 } diff --git a/Benchmarks/Thresholds/nightly-main/NIOSSLBenchmarks.SimpleHandshake.p90.json b/Benchmarks/Thresholds/nightly-main/NIOSSLBenchmarks.SimpleHandshake.p90.json index 1bebb06e..8ef309a5 100644 --- a/Benchmarks/Thresholds/nightly-main/NIOSSLBenchmarks.SimpleHandshake.p90.json +++ b/Benchmarks/Thresholds/nightly-main/NIOSSLBenchmarks.SimpleHandshake.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 641871 + "mallocCountTotal" : 423793 } diff --git a/Benchmarks/Thresholds/nightly-next/NIOSSLBenchmarks.ManyWrites.p90.json b/Benchmarks/Thresholds/nightly-next/NIOSSLBenchmarks.ManyWrites.p90.json index 7904a26c..9b80de19 100644 --- a/Benchmarks/Thresholds/nightly-next/NIOSSLBenchmarks.ManyWrites.p90.json +++ b/Benchmarks/Thresholds/nightly-next/NIOSSLBenchmarks.ManyWrites.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 201954 + "mallocCountTotal" : 201649 } diff --git a/Benchmarks/Thresholds/nightly-next/NIOSSLBenchmarks.SimpleHandshake.p90.json b/Benchmarks/Thresholds/nightly-next/NIOSSLBenchmarks.SimpleHandshake.p90.json index d4ba7787..8fd1726e 100644 --- a/Benchmarks/Thresholds/nightly-next/NIOSSLBenchmarks.SimpleHandshake.p90.json +++ b/Benchmarks/Thresholds/nightly-next/NIOSSLBenchmarks.SimpleHandshake.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 641894 + "mallocCountTotal" : 423799 } diff --git a/Package.swift b/Package.swift index c242431c..cc7abe3a 100644 --- a/Package.swift +++ b/Package.swift @@ -22,7 +22,7 @@ import PackageDescription // Sources/CNIOBoringSSL directory. The source repository is at // https://boringssl.googlesource.com/boringssl. // -// BoringSSL Commit: 817ab07ebb53da35afea409ab9328f578492832d +// BoringSSL Commit: 8eb25be6fa18d475291122887a7bccd3762ff236 /// This function generates the dependencies we want to express. /// @@ -73,9 +73,6 @@ let package = Package( .library(name: "NIOSSL", targets: ["NIOSSL"]), .executable(name: "NIOTLSServer", targets: ["NIOTLSServer"]), .executable(name: "NIOSSLHTTP1Client", targets: ["NIOSSLHTTP1Client"]), - /* This target is used only for symbol mangling. It's added and removed automatically because it emits build warnings. MANGLE_START - .library(name: "CNIOBoringSSL", type: .static, targets: ["CNIOBoringSSL"]), - MANGLE_END */ ], dependencies: generateDependencies(), targets: [ diff --git a/Sources/CNIOBoringSSL/crypto/aes/aes.cc b/Sources/CNIOBoringSSL/crypto/aes/aes.cc new file mode 100644 index 00000000..805295c2 --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/aes/aes.cc @@ -0,0 +1,44 @@ +// Copyright 2025 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/bcm_interface.h" + + +using namespace bssl; + +void AES_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { + BCM_aes_encrypt(in, out, key); +} + +void AES_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { + BCM_aes_decrypt(in, out, key); +} + +int AES_set_encrypt_key(const uint8_t *key, unsigned bits, AES_KEY *aeskey) { + if (bits != 128 && bits != 192 && bits != 256) { + return -2; + } + return bcm_success(BCM_aes_set_encrypt_key(key, bits, aeskey)) ? 0 : -1; +} + +int AES_set_decrypt_key(const uint8_t *key, unsigned bits, AES_KEY *aeskey) { + if (bits != 128 && bits != 192 && bits != 256) { + return -2; + } + return bcm_success(BCM_aes_set_decrypt_key(key, bits, aeskey)) ? 0 : -1; +} diff --git a/Sources/CNIOBoringSSL/crypto/armv8_feature_parsing.h b/Sources/CNIOBoringSSL/crypto/armv8_feature_parsing.h new file mode 100644 index 00000000..00f3988e --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/armv8_feature_parsing.h @@ -0,0 +1,67 @@ +#ifndef OPENSSL_CRYPTO_CPU_ARMV8_FEATURE_PARSING_H +#define OPENSSL_CRYPTO_CPU_ARMV8_FEATURE_PARSING_H + +#include +#include + +#include "internal.h" + +#if defined(OPENSSL_AARCH64) + +BSSL_NAMESPACE_BEGIN +namespace armcap { + +// Common field indices based on ARM architecture specification for +// ID_AA64ISAR0_EL1. These are indices (multiplied by 4 for the bit shift). +// Note: SHA3_FIELD_IDX 8 * 4 = 32 (ID_AA64ISAR0_EL1_SHA3_SHIFT value) +#define ID_AA64ISAR0_AES_FIELD_IDX 1 // Bits [7:4] +#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 NBITS_ID_FIELD 4 + +// Helper function to extract a 4-bit field based on its index. +inline unsigned GetIDField(uint64_t reg, unsigned field_idx) { + // We mask with 0xf to ensure only the 4 relevant bits are returned. + return (reg >> (field_idx * NBITS_ID_FIELD)) & 0xf; +} + +// The core function that converts the raw ID_AA64ISAR0 register value +// into the OR'd capability flags (ARMV8_AES, ARMV8_SHA3, etc.). +inline uint32_t ParseISAR0Flags(uint64_t isar0) { + uint32_t armcap = 0; + // AES and PMULL check + unsigned aes = GetIDField(isar0, ID_AA64ISAR0_AES_FIELD_IDX); + if (aes > 0) { + armcap |= ARMV8_AES; + } + if (aes > 1) { + armcap |= ARMV8_PMULL; + } + // SHA1 check + unsigned sha1 = GetIDField(isar0, ID_AA64ISAR0_SHA1_FIELD_IDX); + if (sha1 > 0) { + armcap |= ARMV8_SHA1; + } + // SHA256 and SHA512 check + unsigned sha2 = GetIDField(isar0, ID_AA64ISAR0_SHA2_FIELD_IDX); + if (sha2 > 0) { + armcap |= ARMV8_SHA256; + } + if (sha2 > 1) { + armcap |= ARMV8_SHA512; + } + // SHA3 (EOR3) check + unsigned sha3 = GetIDField(isar0, ID_AA64ISAR0_SHA3_FIELD_IDX); + if (sha3 > 0) { + armcap |= ARMV8_SHA3; + } + return armcap; +} + +} // namespace armcap +BSSL_NAMESPACE_END + +#endif // OPENSSL_AARCH64 + +#endif // OPENSSL_CRYPTO_CPU_ARMV8_FEATURE_PARSING_H diff --git a/Sources/CNIOBoringSSL/crypto/asn1/a_bitstr.cc b/Sources/CNIOBoringSSL/crypto/asn1/a_bitstr.cc index 4f138117..cef21c20 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/a_bitstr.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/a_bitstr.cc @@ -1,80 +1,93 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../internal.h" #include "internal.h" -int ASN1_BIT_STRING_set(ASN1_BIT_STRING *x, const unsigned char *d, - ossl_ssize_t len) { - return ASN1_STRING_set(x, d, len); +using namespace bssl; + +static void set_unused_bits(ASN1_BIT_STRING *str, uint8_t unused_bits) { + assert(unused_bits < 8); + assert(unused_bits == 0 || str->length > 0); + // `ASN1_STRING_FLAG_BITS_LEFT` and the bottom 3 bits encode `padding`. + str->flags &= ~0x07; + str->flags |= ASN1_STRING_FLAG_BITS_LEFT | unused_bits; } -int asn1_bit_string_length(const ASN1_BIT_STRING *str, - uint8_t *out_padding_bits) { - int len = str->length; - if (str->flags & ASN1_STRING_FLAG_BITS_LEFT) { - // If the string is already empty, it cannot have padding bits. - *out_padding_bits = len == 0 ? 0 : str->flags & 0x07; - return len; - } +int ASN1_BIT_STRING_set(ASN1_BIT_STRING *str, const uint8_t *data, + ossl_ssize_t len) { + return ASN1_STRING_set(str, data, len); +} - // TODO(https://crbug.com/boringssl/447): If we move this logic to - // |ASN1_BIT_STRING_set_bit|, can we remove this representation? - while (len > 0 && str->data[len - 1] == 0) { - len--; +int ASN1_BIT_STRING_set1(ASN1_BIT_STRING *str, const uint8_t *data, + size_t length, int unused_bits) { + if (unused_bits < 0 || unused_bits > 7) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BIT_STRING_BITS_LEFT); + return 0; } - uint8_t padding_bits = 0; - if (len > 0) { - uint8_t last = str->data[len - 1]; - assert(last != 0); - for (; padding_bits < 7; padding_bits++) { - if (last & (1 << padding_bits)) { - break; - } - } + const uint8_t unused_bits_mask = (1 << unused_bits) - 1; + if ((length > 0 && (data[length - 1] & unused_bits_mask) != 0) || + (length == 0 && unused_bits != 0)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BIT_STRING_BITS_LEFT); + return 0; } - *out_padding_bits = padding_bits; - return len; + if (!ASN1_STRING_set(str, data, length)) { + return 0; + } + str->type = V_ASN1_BIT_STRING; + set_unused_bits(str, unused_bits); + return 1; +} + +uint8_t ASN1_BIT_STRING_unused_bits(const ASN1_BIT_STRING *str) { + // If the string is already empty, it cannot have padding bits. + return str->length == 0 ? 0 : str->flags & 0x07; } int ASN1_BIT_STRING_num_bytes(const ASN1_BIT_STRING *str, size_t *out) { - uint8_t padding_bits; - int len = asn1_bit_string_length(str, &padding_bits); - if (padding_bits != 0) { + if (ASN1_BIT_STRING_unused_bits(str) != 0) { return 0; } - *out = len; + *out = str->length; return 1; } int i2c_ASN1_BIT_STRING(const ASN1_BIT_STRING *a, unsigned char **pp) { - if (a == NULL) { + if (a == nullptr) { return 0; } - uint8_t bits; - int len = asn1_bit_string_length(a, &bits); + uint8_t bits = ASN1_BIT_STRING_unused_bits(a); + int len = ASN1_STRING_length(a); if (len > INT_MAX - 1) { OPENSSL_PUT_ERROR(ASN1, ERR_R_OVERFLOW); return 0; } int ret = 1 + len; - if (pp == NULL) { + if (pp == nullptr) { return ret; } @@ -89,106 +102,154 @@ int i2c_ASN1_BIT_STRING(const ASN1_BIT_STRING *a, unsigned char **pp) { return ret; } -ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a, - const unsigned char **pp, long len) { - ASN1_BIT_STRING *ret = NULL; - const unsigned char *p; - unsigned char *s; - int padding; - uint8_t padding_mask; +int bssl::asn1_marshal_bit_string(CBB *out, const ASN1_BIT_STRING *in, + CBS_ASN1_TAG tag) { + int len = i2c_ASN1_BIT_STRING(in, nullptr); + if (len <= 0) { + return 0; + } + tag = tag == 0 ? CBS_ASN1_BITSTRING : tag; + CBB child; + uint8_t *ptr; + return CBB_add_asn1(out, &child, tag) && // + CBB_add_space(&child, &ptr, static_cast(len)) && // + i2c_ASN1_BIT_STRING(in, &ptr) == len && // + CBB_flush(out); +} - if (len < 1) { +static int asn1_parse_bit_string_contents(Span in, + ASN1_BIT_STRING *out) { + CBS cbs = in; + uint8_t padding; + if (!CBS_get_u8(&cbs, &padding)) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_SHORT); - goto err; + return 0; } - if (len > INT_MAX) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_LONG); - goto err; - } - - if ((a == NULL) || ((*a) == NULL)) { - if ((ret = ASN1_BIT_STRING_new()) == NULL) { - return NULL; - } - } else { - ret = (*a); - } - - p = *pp; - padding = *(p++); - len--; if (padding > 7) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BIT_STRING_BITS_LEFT); - goto err; + return 0; } // Unused bits in a BIT STRING must be zero. - padding_mask = (1 << padding) - 1; - if (padding != 0 && (len < 1 || (p[len - 1] & padding_mask) != 0)) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BIT_STRING_PADDING); - goto err; - } - - // We do this to preserve the settings. If we modify the settings, via - // the _set_bit function, we will recalculate on output - ret->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); // clear - ret->flags |= (ASN1_STRING_FLAG_BITS_LEFT | padding); // set - - if (len > 0) { - s = reinterpret_cast(OPENSSL_memdup(p, len)); - if (s == NULL) { - goto err; + uint8_t padding_mask = (1 << padding) - 1; + if (padding != 0) { + CBS copy = cbs; + uint8_t last; + if (!CBS_get_last_u8(©, &last) || (last & padding_mask) != 0) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BIT_STRING_PADDING); + return 0; } - p += len; - } else { - s = NULL; } - ret->length = (int)len; - OPENSSL_free(ret->data); - ret->data = s; - ret->type = V_ASN1_BIT_STRING; - if (a != NULL) { - (*a) = ret; + return ASN1_BIT_STRING_set1(out, CBS_data(&cbs), CBS_len(&cbs), padding); +} + +ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a, + const unsigned char **pp, long len) { + if (len < 0) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_SHORT); + return nullptr; } - *pp = p; + + ASN1_BIT_STRING *ret = nullptr; + if (a == nullptr || *a == nullptr) { + if ((ret = ASN1_BIT_STRING_new()) == nullptr) { + return nullptr; + } + } else { + ret = *a; + } + + if (!asn1_parse_bit_string_contents(Span(*pp, len), ret)) { + if (ret != nullptr && (a == nullptr || *a != ret)) { + ASN1_BIT_STRING_free(ret); + } + return nullptr; + } + + if (a != nullptr) { + *a = ret; + } + *pp += len; return ret; -err: - if ((ret != NULL) && ((a == NULL) || (*a != ret))) { - ASN1_BIT_STRING_free(ret); +} + +int bssl::asn1_parse_bit_string(CBS *cbs, ASN1_BIT_STRING *out, + CBS_ASN1_TAG tag) { + tag = tag == 0 ? CBS_ASN1_BITSTRING : tag; + CBS child; + if (!CBS_get_asn1(cbs, &child, tag)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; } - return NULL; + return asn1_parse_bit_string_contents(child, out); +} + +int bssl::asn1_parse_bit_string_with_bad_length(CBS *cbs, + ASN1_BIT_STRING *out) { + CBS child; + CBS_ASN1_TAG tag; + size_t header_len; + int indefinite; + if (!CBS_get_any_ber_asn1_element(cbs, &child, &tag, &header_len, + /*out_ber_found=*/nullptr, + &indefinite) || + tag != CBS_ASN1_BITSTRING || indefinite || // + !CBS_skip(&child, header_len)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; + } + return asn1_parse_bit_string_contents(child, out); +} + +static void trim_trailing_zeros(ASN1_BIT_STRING *a) { + while (a->length > 0 && a->data[a->length - 1] == 0) { + a->length--; + } + uint8_t padding_bits = 0; + if (a->length > 0) { + uint8_t last = a->data[a->length - 1]; + assert(last != 0); + for (; padding_bits < 7; padding_bits++) { + if (last & (1 << padding_bits)) { + break; + } + } + } + set_unused_bits(a, padding_bits); } // These next 2 functions from Goetz Babin-Ebell int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value) { - int w, v, iv; - unsigned char *c; + if (a == nullptr) { + return 0; + } - w = n / 8; - v = 1 << (7 - (n & 0x07)); - iv = ~v; + if (n < 0) { + OPENSSL_PUT_ERROR(ASN1, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return 0; + } + + int w = n / 8; + int v = 1 << (7 - (n & 0x07)); + int iv = ~v; if (!value) { v = 0; } - if (a == NULL) { - return 0; - } - - a->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); // clear, set on write - - if ((a->length < (w + 1)) || (a->data == NULL)) { + if ((a->length < (w + 1)) || (a->data == nullptr)) { if (!value) { + trim_trailing_zeros(a); return 1; // Don't need to set } - if (a->data == NULL) { + unsigned char *c; + if (a->data == nullptr) { c = (unsigned char *)OPENSSL_malloc(w + 1); } else { c = (unsigned char *)OPENSSL_realloc(a->data, w + 1); } - if (c == NULL) { + if (c == nullptr) { return 0; } if (w + 1 - a->length > 0) { @@ -197,10 +258,8 @@ int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value) { a->data = c; a->length = w + 1; } - a->data[w] = ((a->data[w]) & iv) | v; - while ((a->length > 0) && (a->data[a->length - 1] == 0)) { - a->length--; - } + a->data[w] = (a->data[w] & iv) | v; + trim_trailing_zeros(a); return 1; } @@ -209,7 +268,7 @@ int ASN1_BIT_STRING_get_bit(const ASN1_BIT_STRING *a, int n) { w = n / 8; v = 1 << (7 - (n & 0x07)); - if ((a == NULL) || (a->length < (w + 1)) || (a->data == NULL)) { + if ((a == nullptr) || (a->length < (w + 1)) || (a->data == nullptr)) { return 0; } return ((a->data[w] & v) != 0); diff --git a/Sources/CNIOBoringSSL/crypto/asn1/a_bool.cc b/Sources/CNIOBoringSSL/crypto/asn1/a_bool.cc index 26eee2c0..a137bf57 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/a_bool.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/a_bool.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,13 +21,10 @@ int i2d_ASN1_BOOLEAN(ASN1_BOOLEAN a, unsigned char **outp) { - CBB cbb; - if (!CBB_init(&cbb, 3) || // - !CBB_add_asn1_bool(&cbb, a != ASN1_BOOLEAN_FALSE)) { - CBB_cleanup(&cbb); - return -1; - } - return CBB_finish_i2d(&cbb, outp); + return bssl::I2DFromCBB( + /*initial_capacity=*/3, outp, [&](CBB *cbb) -> bool { + return CBB_add_asn1_bool(cbb, a != ASN1_BOOLEAN_FALSE); + }); } ASN1_BOOLEAN d2i_ASN1_BOOLEAN(ASN1_BOOLEAN *out, const unsigned char **inp, @@ -40,7 +42,7 @@ ASN1_BOOLEAN d2i_ASN1_BOOLEAN(ASN1_BOOLEAN *out, const unsigned char **inp, } ASN1_BOOLEAN ret = val ? ASN1_BOOLEAN_TRUE : ASN1_BOOLEAN_FALSE; - if (out != NULL) { + if (out != nullptr) { *out = ret; } *inp = CBS_data(&cbs); diff --git a/Sources/CNIOBoringSSL/crypto/asn1/a_d2i_fp.cc b/Sources/CNIOBoringSSL/crypto/asn1/a_d2i_fp.cc index 1d965f2e..43e75902 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/a_d2i_fp.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/a_d2i_fp.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -22,7 +27,7 @@ void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *x) { // Historically, this function did not impose a limit in OpenSSL and is used // to read CRLs, so we leave this without an external bound. if (!BIO_read_asn1(in, &data, &len, INT_MAX)) { - return NULL; + return nullptr; } const uint8_t *ptr = data; void *ret = ASN1_item_d2i(reinterpret_cast(x), &ptr, len, it); @@ -32,9 +37,9 @@ void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *x) { void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x) { BIO *b = BIO_new_fp(in, BIO_NOCLOSE); - if (b == NULL) { + if (b == nullptr) { OPENSSL_PUT_ERROR(ASN1, ERR_R_BUF_LIB); - return NULL; + return nullptr; } void *ret = ASN1_item_d2i_bio(it, b, x); BIO_free(b); diff --git a/Sources/CNIOBoringSSL/crypto/asn1/a_dup.cc b/Sources/CNIOBoringSSL/crypto/asn1/a_dup.cc index 56e43284..32dd944d 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/a_dup.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/a_dup.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,21 +22,21 @@ // directly dup the underlying structure instead of doing and encode and // decode. void *ASN1_item_dup(const ASN1_ITEM *it, void *x) { - unsigned char *b = NULL; + unsigned char *b = nullptr; const unsigned char *p; long i; void *ret; - if (x == NULL) { - return NULL; + if (x == nullptr) { + return nullptr; } i = ASN1_item_i2d(reinterpret_cast(x), &b, it); - if (b == NULL) { - return NULL; + if (b == nullptr) { + return nullptr; } p = b; - ret = ASN1_item_d2i(NULL, &p, i, it); + ret = ASN1_item_d2i(nullptr, &p, i, it); OPENSSL_free(b); return ret; } diff --git a/Sources/CNIOBoringSSL/crypto/asn1/a_gentm.cc b/Sources/CNIOBoringSSL/crypto/asn1/a_gentm.cc index a181be71..8cd68ddb 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/a_gentm.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/a_gentm.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -19,7 +24,11 @@ #include "internal.h" -int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d) { + +using namespace bssl; + +int bssl::asn1_generalizedtime_to_tm(struct tm *tm, + const ASN1_GENERALIZEDTIME *d) { if (d->type != V_ASN1_GENERALIZEDTIME) { return 0; } @@ -31,19 +40,36 @@ int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d) { return 1; } +int bssl::asn1_parse_generalized_time(CBS *cbs, ASN1_GENERALIZEDTIME *out, + CBS_ASN1_TAG tag) { + tag = tag == 0 ? CBS_ASN1_GENERALIZEDTIME : tag; + CBS child; + if (!CBS_get_asn1(cbs, &child, tag) || + !CBS_parse_generalized_time(&child, nullptr, + /*allow_timezone_offset=*/0)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; + } + if (!ASN1_STRING_set(out, CBS_data(&child), CBS_len(&child))) { + return 0; + } + out->type = V_ASN1_GENERALIZEDTIME; + return 1; +} + int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *d) { - return asn1_generalizedtime_to_tm(NULL, d); + return asn1_generalizedtime_to_tm(nullptr, d); } int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str) { size_t len = strlen(str); CBS cbs; CBS_init(&cbs, (const uint8_t *)str, len); - if (!CBS_parse_generalized_time(&cbs, /*out_tm=*/NULL, + if (!CBS_parse_generalized_time(&cbs, /*out_tm=*/nullptr, /*allow_timezone_offset=*/0)) { return 0; } - if (s != NULL) { + if (s != nullptr) { if (!ASN1_STRING_set(s, str, len)) { return 0; } @@ -63,33 +89,33 @@ ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s, long offset_sec) { struct tm data; if (!OPENSSL_posix_to_tm(posix_time, &data)) { - return NULL; + return nullptr; } if (offset_day || offset_sec) { if (!OPENSSL_gmtime_adj(&data, offset_day, offset_sec)) { - return NULL; + return nullptr; } } if (data.tm_year < 0 - 1900 || data.tm_year > 9999 - 1900) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_TIME_VALUE); - return NULL; + return nullptr; } char buf[16]; int ret = snprintf(buf, sizeof(buf), "%04d%02d%02d%02d%02d%02dZ", data.tm_year + 1900, data.tm_mon + 1, data.tm_mday, data.tm_hour, data.tm_min, data.tm_sec); - // |snprintf| must write exactly 15 bytes (plus the NUL) to the buffer. + // `snprintf` must write exactly 15 bytes (plus the NUL) to the buffer. BSSL_CHECK(ret == static_cast(sizeof(buf) - 1)); int free_s = 0; - if (s == NULL) { + if (s == nullptr) { free_s = 1; s = ASN1_UTCTIME_new(); - if (s == NULL) { - return NULL; + if (s == nullptr) { + return nullptr; } } @@ -97,7 +123,7 @@ ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s, if (free_s) { ASN1_UTCTIME_free(s); } - return NULL; + return nullptr; } s->type = V_ASN1_GENERALIZEDTIME; return s; diff --git a/Sources/CNIOBoringSSL/crypto/asn1/a_i2d_fp.cc b/Sources/CNIOBoringSSL/crypto/asn1/a_i2d_fp.cc index 24f3866e..75d93bd0 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/a_i2d_fp.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/a_i2d_fp.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,9 +19,9 @@ #include -int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, void *x) { +int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, const void *x) { BIO *b = BIO_new_fp(out, BIO_NOCLOSE); - if (b == NULL) { + if (b == nullptr) { OPENSSL_PUT_ERROR(ASN1, ERR_R_BUF_LIB); return 0; } @@ -25,10 +30,11 @@ int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, void *x) { return ret; } -int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, void *x) { - unsigned char *b = NULL; - int n = ASN1_item_i2d(reinterpret_cast(x), &b, it); - if (b == NULL) { +int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, const void *x) { + unsigned char *b = nullptr; + int n = ASN1_item_i2d(reinterpret_cast(const_cast(x)), + &b, it); + if (b == nullptr) { return 0; } diff --git a/Sources/CNIOBoringSSL/crypto/asn1/a_int.cc b/Sources/CNIOBoringSSL/crypto/asn1/a_int.cc index 0276ad4a..bd73c1d0 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/a_int.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/a_int.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,10 +21,14 @@ #include #include #include +#include #include "../internal.h" +#include "internal.h" +using namespace bssl; + ASN1_INTEGER *ASN1_INTEGER_dup(const ASN1_INTEGER *x) { return ASN1_STRING_dup(x); } @@ -33,8 +42,8 @@ int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y) { int ret = ASN1_STRING_cmp(x, y); if (neg) { - // This could be |-ret|, but |ASN1_STRING_cmp| is not forbidden from - // returning |INT_MIN|. + // This could be `-ret`, but `ASN1_STRING_cmp` is not forbidden from + // returning `INT_MIN`. if (ret < 0) { return 1; } else if (ret > 0) { @@ -47,7 +56,7 @@ int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y) { return ret; } -// negate_twos_complement negates |len| bytes from |buf| in-place, interpreted +// negate_twos_complement negates `len` bytes from `buf` in-place, interpreted // as a signed, big-endian two's complement value. static void negate_twos_complement(uint8_t *buf, size_t len) { uint8_t borrow = 0; @@ -67,12 +76,27 @@ static int is_all_zeros(const uint8_t *in, size_t len) { return 1; } +int bssl::asn1_marshal_integer(CBB *out, const ASN1_INTEGER *in, + CBS_ASN1_TAG tag) { + int len = i2c_ASN1_INTEGER(in, nullptr); + if (len <= 0) { + return 0; + } + tag = tag == 0 ? CBS_ASN1_INTEGER : tag; + CBB child; + uint8_t *ptr; + return CBB_add_asn1(out, &child, tag) && // + CBB_add_space(&child, &ptr, static_cast(len)) && // + i2c_ASN1_INTEGER(in, &ptr) == len && // + CBB_flush(out); +} + int i2c_ASN1_INTEGER(const ASN1_INTEGER *in, unsigned char **outp) { - if (in == NULL) { + if (in == nullptr) { return 0; } - // |ASN1_INTEGER|s should be represented minimally, but it is possible to + // `ASN1_INTEGER`s should be represented minimally, but it is possible to // construct invalid ones. Skip leading zeros so this does not produce an // invalid encoding or break invariants. CBS cbs; @@ -108,7 +132,7 @@ int i2c_ASN1_INTEGER(const ASN1_INTEGER *in, unsigned char **outp) { } int len = (int)(pad + CBS_len(&cbs)); assert(len > 0); - if (outp == NULL) { + if (outp == nullptr) { return len; } @@ -126,35 +150,16 @@ int i2c_ASN1_INTEGER(const ASN1_INTEGER *in, unsigned char **outp) { return len; } -ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **out, const unsigned char **inp, - long len) { - // This function can handle lengths up to INT_MAX - 1, but the rest of the - // legacy ASN.1 code mixes integer types, so avoid exposing it to - // ASN1_INTEGERS with larger lengths. - if (len < 0 || len > INT_MAX / 2) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_TOO_LONG); - return NULL; - } - - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); +static int asn1_parse_integer_contents(Span in, + ASN1_INTEGER *out) { + CBS cbs = in; int is_negative; if (!CBS_is_valid_asn1_integer(&cbs, &is_negative)) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_INTEGER); - return NULL; + return 0; } - ASN1_INTEGER *ret = NULL; - if (out == NULL || *out == NULL) { - ret = ASN1_INTEGER_new(); - if (ret == NULL) { - return NULL; - } - } else { - ret = *out; - } - - // Convert to |ASN1_INTEGER|'s sign-and-magnitude representation. First, + // Convert to `ASN1_INTEGER`'s sign-and-magnitude representation. First, // determine the size needed for a minimal result. if (is_negative) { // 0xff00...01 through 0xff7f..ff have a two's complement of 0x00ff...ff @@ -172,33 +177,76 @@ ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **out, const unsigned char **inp, } } - if (!ASN1_STRING_set(ret, CBS_data(&cbs), CBS_len(&cbs))) { - goto err; + if (!ASN1_STRING_set(out, CBS_data(&cbs), CBS_len(&cbs))) { + return 0; } if (is_negative) { - ret->type = V_ASN1_NEG_INTEGER; - negate_twos_complement(ret->data, ret->length); + out->type = V_ASN1_NEG_INTEGER; + negate_twos_complement(out->data, out->length); } else { - ret->type = V_ASN1_INTEGER; + out->type = V_ASN1_INTEGER; } // The value should be minimally-encoded. - assert(ret->length == 0 || ret->data[0] != 0); + assert(out->length == 0 || out->data[0] != 0); // Zero is not negative. - assert(!is_negative || ret->length > 0); + assert(!is_negative || out->length > 0); + return 1; +} + +int bssl::asn1_parse_integer(CBS *cbs, ASN1_INTEGER *out, CBS_ASN1_TAG tag) { + tag = tag == 0 ? CBS_ASN1_INTEGER : tag; + CBS child; + if (!CBS_get_asn1(cbs, &child, tag)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; + } + return asn1_parse_integer_contents(child, out); +} + +int bssl::asn1_parse_enumerated(CBS *cbs, ASN1_ENUMERATED *out, + CBS_ASN1_TAG tag) { + tag = tag == 0 ? CBS_ASN1_ENUMERATED : tag; + if (!asn1_parse_integer(cbs, out, tag)) { + return 0; + } + // Fix the type value. + out->type = + (out->type & V_ASN1_NEG) ? V_ASN1_NEG_ENUMERATED : V_ASN1_ENUMERATED; + return 1; +} + +ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **out, const unsigned char **inp, + long len) { + if (len < 0) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_SHORT); + return nullptr; + } + + ASN1_INTEGER *ret = nullptr; + if (out == nullptr || *out == nullptr) { + ret = ASN1_INTEGER_new(); + if (ret == nullptr) { + return nullptr; + } + } else { + ret = *out; + } + + if (!asn1_parse_integer_contents(Span(*inp, len), ret)) { + if (ret != nullptr && (out == nullptr || *out != ret)) { + ASN1_INTEGER_free(ret); + } + return nullptr; + } *inp += len; - if (out != NULL) { + if (out != nullptr) { *out = ret; } return ret; -err: - if (ret != NULL && (out == NULL || *out != ret)) { - ASN1_INTEGER_free(ret); - } - return NULL; } int ASN1_INTEGER_set_int64(ASN1_INTEGER *a, int64_t v) { @@ -305,7 +353,7 @@ static int asn1_string_get_int64(int64_t *out, const ASN1_STRING *a, int type) { } int64_t i64; int fits_in_i64; - // Check |v != 0| to handle manually-constructed negative zeros. + // Check `v != 0` to handle manually-constructed negative zeros. if ((a->type & V_ASN1_NEG) && v != 0) { i64 = (int64_t)(0u - v); fits_in_i64 = i64 < 0; @@ -330,7 +378,7 @@ int ASN1_ENUMERATED_get_int64(int64_t *out, const ASN1_ENUMERATED *a) { } static long asn1_string_get_long(const ASN1_STRING *a, int type) { - if (a == NULL) { + if (a == nullptr) { return 0; } @@ -356,13 +404,13 @@ long ASN1_ENUMERATED_get(const ASN1_ENUMERATED *a) { static ASN1_STRING *bn_to_asn1_string(const BIGNUM *bn, ASN1_STRING *ai, int type) { ASN1_INTEGER *ret; - if (ai == NULL) { + if (ai == nullptr) { ret = ASN1_STRING_type_new(type); } else { ret = ai; } int len; - if (ret == NULL) { + if (ret == nullptr) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); goto err; } @@ -374,7 +422,7 @@ static ASN1_STRING *bn_to_asn1_string(const BIGNUM *bn, ASN1_STRING *ai, } len = BN_num_bytes(bn); - if (!ASN1_STRING_set(ret, NULL, len) || + if (!ASN1_STRING_set(ret, nullptr, len) || !BN_bn2bin_padded(ret->data, len, bn)) { goto err; } @@ -384,7 +432,7 @@ err: if (ret != ai) { ASN1_STRING_free(ret); } - return NULL; + return nullptr; } ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai) { @@ -398,11 +446,11 @@ ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(const BIGNUM *bn, ASN1_ENUMERATED *ai) { static BIGNUM *asn1_string_to_bn(const ASN1_STRING *ai, BIGNUM *bn, int type) { if ((ai->type & ~V_ASN1_NEG) != type) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_INTEGER_TYPE); - return NULL; + return nullptr; } BIGNUM *ret; - if ((ret = BN_bin2bn(ai->data, ai->length, bn)) == NULL) { + if ((ret = BN_bin2bn(ai->data, ai->length, bn)) == nullptr) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_BN_LIB); } else if (ai->type & V_ASN1_NEG) { BN_set_negative(ret, 1); diff --git a/Sources/CNIOBoringSSL/crypto/asn1/a_mbstr.cc b/Sources/CNIOBoringSSL/crypto/asn1/a_mbstr.cc index 2c13b7c4..743fe3e5 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/a_mbstr.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/a_mbstr.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -19,6 +24,9 @@ #include "../bytestring/internal.h" #include "internal.h" + +using namespace bssl; + // These functions take a string in UTF8, ASCII or multibyte form and a mask // of permissible ASN1 string types. It then works out the minimal type // (using the order Printable < IA5 < T61 < BMP < Universal < UTF8) and @@ -74,7 +82,7 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, return -1; } - // Check |minsize| and |maxsize| and work out the minimal type, if any. + // Check `minsize` and `maxsize` and work out the minimal type, if any. CBS cbs; CBS_init(&cbs, in, len); size_t utf8_len = 0, nchar = 0; @@ -179,7 +187,7 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, CBB cbb; CBB_zero(&cbb); // If both the same type just copy across - uint8_t *data = NULL; + uint8_t *data = nullptr; size_t data_len = 0; if (inform == outform) { if (!ASN1_STRING_set(dest, in, len)) { @@ -201,7 +209,7 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, } } if (/* OpenSSL historically NUL-terminated this value with a single byte, - * even for |MBSTRING_BMP| and |MBSTRING_UNIV|. */ + * even for `MBSTRING_BMP` and `MBSTRING_UNIV`. */ !CBB_add_u8(&cbb, 0) || // !CBB_finish(&cbb, &data, &data_len) || // data_len < 1 || // @@ -223,7 +231,7 @@ err: return -1; } -int asn1_is_printable(uint32_t value) { +int bssl::asn1_is_printable(uint32_t value) { if (value > 0x7f) { return 0; } diff --git a/Sources/CNIOBoringSSL/crypto/asn1/a_object.cc b/Sources/CNIOBoringSSL/crypto/asn1/a_object.cc index 0e2f4aab..0b52d0a9 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/a_object.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/a_object.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -19,29 +24,34 @@ #include "../bytestring/internal.h" #include "../internal.h" +#include "../mem_internal.h" #include "internal.h" -int i2d_ASN1_OBJECT(const ASN1_OBJECT *in, unsigned char **outp) { - if (in == NULL) { +using namespace bssl; + +int bssl::asn1_marshal_object(CBB *out, const ASN1_OBJECT *in, + CBS_ASN1_TAG tag) { + if (in == nullptr) { OPENSSL_PUT_ERROR(ASN1, ERR_R_PASSED_NULL_PARAMETER); - return -1; + return 0; } if (in->length <= 0) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OBJECT); - return -1; + return 0; } - CBB cbb, child; - if (!CBB_init(&cbb, (size_t)in->length + 2) || - !CBB_add_asn1(&cbb, &child, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&child, in->data, in->length)) { - CBB_cleanup(&cbb); - return -1; - } + tag = tag == 0 ? CBS_ASN1_OBJECT : tag; + return CBB_add_asn1_element(out, tag, in->data, in->length); +} - return CBB_finish_i2d(&cbb, outp); +int i2d_ASN1_OBJECT(const ASN1_OBJECT *in, unsigned char **outp) { + return I2DFromCBB( + /*initial_capacity=*/static_cast(in->length) + 2, outp, + [&](CBB *cbb) -> bool { + return asn1_marshal_object(cbb, in, /*tag=*/0); + }); } int i2t_ASN1_OBJECT(char *buf, int buf_len, const ASN1_OBJECT *a) { @@ -58,17 +68,17 @@ static int write_str(BIO *bp, const char *str) { } int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a) { - if (a == NULL || a->data == NULL) { + if (a == nullptr || a->data == nullptr) { return write_str(bp, "NULL"); } - char buf[80], *allocated = NULL; + char buf[80], *allocated = nullptr; const char *str = buf; int len = i2t_ASN1_OBJECT(buf, sizeof(buf), a); if (len > (int)sizeof(buf) - 1) { // The input was truncated. Allocate a buffer that fits. allocated = reinterpret_cast(OPENSSL_malloc(len + 1)); - if (allocated == NULL) { + if (allocated == nullptr) { return -1; } len = i2t_ASN1_OBJECT(allocated, len + 1, a); @@ -85,87 +95,80 @@ int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a) { ASN1_OBJECT *d2i_ASN1_OBJECT(ASN1_OBJECT **out, const unsigned char **inp, long len) { - if (len < 0) { - return NULL; - } - - CBS cbs, child; - CBS_init(&cbs, *inp, (size_t)len); - if (!CBS_get_asn1(&cbs, &child, CBS_ASN1_OBJECT)) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); - return NULL; - } - - const uint8_t *contents = CBS_data(&child); - ASN1_OBJECT *ret = c2i_ASN1_OBJECT(out, &contents, CBS_len(&child)); - if (ret != NULL) { - // |c2i_ASN1_OBJECT| should have consumed the entire input. - assert(CBS_data(&cbs) == contents); - *inp = CBS_data(&cbs); - } - return ret; + return D2IFromCBS(out, inp, len, [](CBS *cbs) -> ASN1_OBJECT * { + CBS child; + if (!CBS_get_asn1(cbs, &child, CBS_ASN1_OBJECT)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return nullptr; + } + const uint8_t *contents = CBS_data(&child); + return c2i_ASN1_OBJECT(nullptr, &contents, CBS_len(&child)); + }); } ASN1_OBJECT *c2i_ASN1_OBJECT(ASN1_OBJECT **out, const unsigned char **inp, long len) { - if (len < 0) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_OBJECT_ENCODING); - return NULL; - } - - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - if (!CBS_is_valid_asn1_oid(&cbs)) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_OBJECT_ENCODING); - return NULL; - } - - ASN1_OBJECT *ret = ASN1_OBJECT_create(NID_undef, *inp, (size_t)len, - /*sn=*/NULL, /*ln=*/NULL); - if (ret == NULL) { - return NULL; - } - - if (out != NULL) { - ASN1_OBJECT_free(*out); - *out = ret; - } - *inp += len; // All bytes were consumed. - return ret; + return D2IFromCBS(out, inp, len, [](CBS *cbs) -> ASN1_OBJECT * { + if (!CBS_is_valid_asn1_oid(cbs)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_OBJECT_ENCODING); + return nullptr; + } + ASN1_OBJECT *ret = + ASN1_OBJECT_create(NID_undef, CBS_data(cbs), CBS_len(cbs), + /*sn=*/nullptr, /*ln=*/nullptr); + if (ret != nullptr) { + // `c2i_ASN1_OBJECT` consumes its whole input on success. + BSSL_CHECK(CBS_skip(cbs, CBS_len(cbs))); + } + return ret; + }); } -ASN1_OBJECT *ASN1_OBJECT_new(void) { - ASN1_OBJECT *ret; +ASN1_OBJECT *bssl::asn1_parse_object(CBS *cbs, CBS_ASN1_TAG tag) { + tag = tag == 0 ? CBS_ASN1_OBJECT : tag; + CBS child; + if (!CBS_get_asn1(cbs, &child, tag)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return nullptr; + } + if (!CBS_is_valid_asn1_oid(&child)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_OBJECT_ENCODING); + return nullptr; + } + return ASN1_OBJECT_create(NID_undef, CBS_data(&child), CBS_len(&child), + /*sn=*/nullptr, /*ln=*/nullptr); +} - ret = (ASN1_OBJECT *)OPENSSL_malloc(sizeof(ASN1_OBJECT)); - if (ret == NULL) { - return NULL; +ASN1_OBJECT *bssl::ASN1_OBJECT_new() { + ASN1_OBJECT *ret = New(); + if (ret == nullptr) { + return nullptr; } ret->length = 0; - ret->data = NULL; + ret->data = nullptr; ret->nid = 0; - ret->sn = NULL; - ret->ln = NULL; + ret->sn = nullptr; + ret->ln = nullptr; ret->flags = ASN1_OBJECT_FLAG_DYNAMIC; return ret; } void ASN1_OBJECT_free(ASN1_OBJECT *a) { - if (a == NULL) { + if (a == nullptr) { return; } if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC_STRINGS) { - OPENSSL_free((void *)a->sn); - OPENSSL_free((void *)a->ln); - a->sn = a->ln = NULL; + OPENSSL_free(const_cast(a->sn)); + OPENSSL_free(const_cast(a->ln)); + a->sn = a->ln = nullptr; } if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC_DATA) { - OPENSSL_free((void *)a->data); - a->data = NULL; + OPENSSL_free(const_cast(a->data)); + a->data = nullptr; a->length = 0; } if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC) { - OPENSSL_free(a); + Delete(a); } } @@ -173,7 +176,7 @@ ASN1_OBJECT *ASN1_OBJECT_create(int nid, const unsigned char *data, size_t len, const char *sn, const char *ln) { if (len > INT_MAX) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_LONG); - return NULL; + return nullptr; } ASN1_OBJECT o; diff --git a/Sources/CNIOBoringSSL/crypto/asn1/a_octet.cc b/Sources/CNIOBoringSSL/crypto/asn1/a_octet.cc index 3e0788f8..65f6bb73 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/a_octet.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/a_octet.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 diff --git a/Sources/CNIOBoringSSL/crypto/asn1/a_strex.cc b/Sources/CNIOBoringSSL/crypto/asn1/a_strex.cc index c1e09fbe..177b0f56 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/a_strex.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/a_strex.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -19,26 +24,29 @@ #include #include #include +#include #include "../bytestring/internal.h" #include "../internal.h" #include "internal.h" +using namespace bssl; + #define ESC_FLAGS \ (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) { - // If |out| is NULL, ignore the output but report the length. - return out == NULL || BIO_write(out, buf, len) == 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; } static 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|, + // `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". unsigned char u8 = (unsigned char)c; @@ -60,7 +68,7 @@ static int do_esc_char(uint32_t c, unsigned long flags, char *do_quotes, (is_last && (c == ' '))) { if (flags & ASN1_STRFLGS_ESC_QUOTE) { // No need to escape, just tell the caller to quote. - if (do_quotes != NULL) { + if (do_quotes != nullptr) { *do_quotes = 1; } return maybe_write(out, &u8, 1) ? 1 : -1; @@ -128,7 +136,7 @@ static int do_buf(const unsigned char *buf, int buflen, int encoding, CBB_init_fixed(&utf8_cbb, utf8_buf, sizeof(utf8_buf)); if (!CBB_add_utf8(&utf8_cbb, c)) { OPENSSL_PUT_ERROR(ASN1, ERR_R_INTERNAL_ERROR); - return 1; + return -1; } size_t utf8_len = CBB_len(&utf8_cbb); for (size_t i = 0; i < utf8_len; i++) { @@ -150,25 +158,22 @@ static int do_buf(const unsigned char *buf, int buflen, int encoding, return outlen; } -// This function hex dumps a buffer of characters - -static int do_hex_dump(BIO *out, unsigned char *buf, int buflen) { - static const char hexdig[] = "0123456789ABCDEF"; - unsigned char *p, *q; - char hextmp[2]; +static int do_hex_dump(BIO *out, Span in) { + if (in.size() > INT_MAX / 2) { + return -1; + } if (out) { - p = buf; - q = buf + buflen; - while (p != q) { - hextmp[0] = hexdig[*p >> 4]; - hextmp[1] = hexdig[*p & 0xf]; + static const char kHexDigit[] = "0123456789ABCDEF"; + for (uint8_t b : in) { + char hextmp[2]; + hextmp[0] = kHexDigit[b >> 4]; + hextmp[1] = kHexDigit[b & 0xf]; if (!maybe_write(out, hextmp, 2)) { return -1; } - p++; } } - return buflen << 1; + return static_cast(in.size() * 2); } // "dump" a string. This is done when the type is unknown, or the flags @@ -182,37 +187,33 @@ static int do_dump(unsigned long flags, BIO *out, const ASN1_STRING *str) { // If we don't dump DER encoding just dump content octets if (!(flags & ASN1_STRFLGS_DUMP_DER)) { - int outlen = do_hex_dump(out, str->data, str->length); + int outlen = do_hex_dump(out, Span(str->data, str->length)); if (outlen < 0) { return -1; } return outlen + 1; } - // Placing the ASN1_STRING in a temporary ASN1_TYPE allows the DER encoding - // to readily obtained. - ASN1_TYPE t; - OPENSSL_memset(&t, 0, sizeof(ASN1_TYPE)); - asn1_type_set0_string(&t, (ASN1_STRING *)str); - unsigned char *der_buf = NULL; - int der_len = i2d_ASN1_TYPE(&t, &der_buf); - if (der_len < 0) { + ScopedCBB cbb; + // Roughly estimate the encoded size with `str->length` to reduce unnecessary + // reallocations. (Tag, length, miscellaneous type-dependent overhead.) + if (!CBB_init(cbb.get(), 4 + str->length) || + !asn1_marshal_any_string(cbb.get(), str)) { return -1; } - int outlen = do_hex_dump(out, der_buf, der_len); - OPENSSL_free(der_buf); + int outlen = do_hex_dump(out, CBBAsSpan(cbb.get())); if (outlen < 0) { return -1; } return outlen + 1; } -// 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 +// 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) { // This function is sometimes passed ASN.1 universal types and sometimes - // passed |ASN1_STRING| type values + // passed `ASN1_STRING` type values switch (type) { case V_ASN1_UTF8STRING: return MBSTRING_UTF8; @@ -223,7 +224,7 @@ static int string_type_to_encoding(int type) { case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: case V_ASN1_ISO64STRING: - // |MBSTRING_ASC| refers to Latin-1, not ASCII. + // `MBSTRING_ASC` refers to Latin-1, not ASCII. return MBSTRING_ASC; case V_ASN1_UNIVERSALSTRING: return MBSTRING_UNIV; @@ -250,7 +251,7 @@ int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str, outlen++; } - // Decide what to do with |str|, either dump the contents or display it. + // Decide what to do with `str`, either dump the contents or display it. int encoding; if (flags & ASN1_STRFLGS_DUMP_ALL) { // Dump everything. @@ -276,7 +277,7 @@ int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str, // Measure the length. char quotes = 0; - int len = do_buf(str->data, str->length, encoding, flags, "es, NULL); + int len = do_buf(str->data, str->length, encoding, flags, "es, nullptr); if (len < 0) { return -1; } @@ -290,7 +291,7 @@ int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str, // Encode the value. if ((quotes && !maybe_write(out, "\"", 1)) || - do_buf(str->data, str->length, encoding, flags, NULL, out) < 0 || + do_buf(str->data, str->length, encoding, flags, nullptr, out) < 0 || (quotes && !maybe_write(out, "\"", 1))) { return -1; } @@ -299,12 +300,12 @@ int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str, int ASN1_STRING_print_ex_fp(FILE *fp, const ASN1_STRING *str, unsigned long flags) { - BIO *bio = NULL; - if (fp != NULL) { - // If |fp| is NULL, this function returns the number of bytes without + BIO *bio = nullptr; + if (fp != nullptr) { + // If `fp` is NULL, this function returns the number of bytes without // writing. bio = BIO_new_fp(fp, BIO_NOCLOSE); - if (bio == NULL) { + if (bio == nullptr) { return -1; } } @@ -323,7 +324,7 @@ int ASN1_STRING_to_UTF8(unsigned char **out, const ASN1_STRING *in) { return -1; } ASN1_STRING stmp, *str = &stmp; - stmp.data = NULL; + stmp.data = nullptr; stmp.length = 0; stmp.flags = 0; int ret = @@ -340,7 +341,7 @@ int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v) { char buf[80]; const char *p; - if (v == NULL) { + if (v == nullptr) { return 0; } n = 0; diff --git a/Sources/CNIOBoringSSL/crypto/asn1/a_strnid.cc b/Sources/CNIOBoringSSL/crypto/asn1/a_strnid.cc index 4bb1c47b..6e93c9ac 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/a_strnid.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/a_strnid.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -13,23 +18,32 @@ #include #include +#include + #include #include #include #include "../internal.h" #include "../lhash/internal.h" +#include "../mem_internal.h" #include "internal.h" +using namespace bssl; + +BSSL_NAMESPACE_BEGIN + DEFINE_LHASH_OF(ASN1_STRING_TABLE) -static LHASH_OF(ASN1_STRING_TABLE) *string_tables = NULL; -static CRYPTO_MUTEX string_tables_lock = CRYPTO_MUTEX_INIT; +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(void) { return B_ASN1_UTF8STRING; } +unsigned long ASN1_STRING_get_default_mask() { return B_ASN1_UTF8STRING; } int ASN1_STRING_set_default_mask_asc(const char *p) { return 1; } @@ -41,13 +55,13 @@ static const ASN1_STRING_TABLE *asn1_string_table_get(int nid); 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 = NULL; + ASN1_STRING *str = nullptr; int ret; if (!out) { out = &str; } const ASN1_STRING_TABLE *tbl = asn1_string_table_get(nid); - if (tbl != NULL) { + if (tbl != nullptr) { unsigned long mask = tbl->mask; if (!(tbl->flags & STABLE_NO_MASK)) { mask &= B_ASN1_UTF8STRING; @@ -58,7 +72,7 @@ ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, const unsigned char *in, ret = ASN1_mbstring_copy(out, in, len, inform, B_ASN1_UTF8STRING); } if (ret <= 0) { - return NULL; + return nullptr; } return *out; } @@ -124,19 +138,19 @@ static const ASN1_STRING_TABLE *asn1_string_table_get(int nid) { ASN1_STRING_TABLE key; key.nid = nid; const ASN1_STRING_TABLE *tbl = reinterpret_cast( - bsearch(&key, tbl_standard, OPENSSL_ARRAY_SIZE(tbl_standard), + bsearch(&key, tbl_standard, std::size(tbl_standard), sizeof(ASN1_STRING_TABLE), table_cmp_void)); - if (tbl != NULL) { + if (tbl != nullptr) { return tbl; } - CRYPTO_MUTEX_lock_read(&string_tables_lock); - if (string_tables != NULL) { + string_tables_lock.LockRead(); + if (string_tables != nullptr) { tbl = lh_ASN1_STRING_TABLE_retrieve(string_tables, &key); } - CRYPTO_MUTEX_unlock_read(&string_tables_lock); - // Note returning |tbl| without the lock is only safe because - // |ASN1_STRING_TABLE_add| cannot modify or delete existing entries. If we + string_tables_lock.UnlockRead(); + // Note returning `tbl` without the lock is only safe because + // `ASN1_STRING_TABLE_add` cannot modify or delete existing entries. If we // wish to support that, this function must copy the result under a lock. return tbl; } @@ -144,35 +158,32 @@ static const ASN1_STRING_TABLE *asn1_string_table_get(int nid) { int ASN1_STRING_TABLE_add(int nid, long minsize, long maxsize, unsigned long mask, unsigned long flags) { // Existing entries cannot be overwritten. - if (asn1_string_table_get(nid) != NULL) { + if (asn1_string_table_get(nid) != nullptr) { OPENSSL_PUT_ERROR(ASN1, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } - int ret = 0; - CRYPTO_MUTEX_lock_write(&string_tables_lock); - - ASN1_STRING_TABLE *tbl = NULL; - if (string_tables == NULL) { + MutexWriteLock lock(&string_tables_lock); + ASN1_STRING_TABLE *tbl = nullptr; + if (string_tables == nullptr) { string_tables = lh_ASN1_STRING_TABLE_new(table_hash, table_cmp); - if (string_tables == NULL) { - goto err; + if (string_tables == nullptr) { + return 0; } } else { // Check again for an existing entry. One may have been added while // unlocked. ASN1_STRING_TABLE key; key.nid = nid; - if (lh_ASN1_STRING_TABLE_retrieve(string_tables, &key) != NULL) { + if (lh_ASN1_STRING_TABLE_retrieve(string_tables, &key) != nullptr) { OPENSSL_PUT_ERROR(ASN1, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); - goto err; + return 0; } } - tbl = reinterpret_cast( - OPENSSL_malloc(sizeof(ASN1_STRING_TABLE))); - if (tbl == NULL) { - goto err; + tbl = New(); + if (tbl == nullptr) { + return 0; } tbl->nid = nid; tbl->flags = flags; @@ -181,21 +192,17 @@ int ASN1_STRING_TABLE_add(int nid, long minsize, long maxsize, tbl->mask = mask; ASN1_STRING_TABLE *old_tbl; if (!lh_ASN1_STRING_TABLE_insert(string_tables, &old_tbl, tbl)) { - OPENSSL_free(tbl); - goto err; + Delete(tbl); + return 0; } - assert(old_tbl == NULL); - ret = 1; - -err: - CRYPTO_MUTEX_unlock_write(&string_tables_lock); - return ret; + assert(old_tbl == nullptr); + return 1; } -void ASN1_STRING_TABLE_cleanup(void) {} +void ASN1_STRING_TABLE_cleanup() {} -void asn1_get_string_table_for_testing(const ASN1_STRING_TABLE **out_ptr, - size_t *out_len) { +void bssl::asn1_get_string_table_for_testing(const ASN1_STRING_TABLE **out_ptr, + size_t *out_len) { *out_ptr = tbl_standard; - *out_len = OPENSSL_ARRAY_SIZE(tbl_standard); + *out_len = std::size(tbl_standard); } diff --git a/Sources/CNIOBoringSSL/crypto/asn1/a_time.cc b/Sources/CNIOBoringSSL/crypto/asn1/a_time.cc index 71f02757..f09d5199 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/a_time.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/a_time.cc @@ -1,15 +1,22 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -20,12 +27,19 @@ #include "internal.h" + +using namespace bssl; + // This is an implementation of the ASN1 Time structure which is: Time ::= // CHOICE { utcTime UTCTime, generalTime GeneralizedTime } written by Steve // Henson. +BSSL_NAMESPACE_BEGIN + IMPLEMENT_ASN1_MSTRING(ASN1_TIME, B_ASN1_TIME) +BSSL_NAMESPACE_END + IMPLEMENT_ASN1_FUNCTIONS_const(ASN1_TIME) ASN1_TIME *ASN1_TIME_set_posix(ASN1_TIME *s, int64_t posix_time) { @@ -46,11 +60,11 @@ ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, int64_t posix_time, int offset_day, if (!OPENSSL_posix_to_tm(posix_time, &tm)) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_ERROR_GETTING_TIME); - return NULL; + return nullptr; } if (offset_day || offset_sec) { if (!OPENSSL_gmtime_adj(&tm, offset_day, offset_sec)) { - return NULL; + return nullptr; } } if (fits_in_utc_time(&tm)) { @@ -72,14 +86,17 @@ int ASN1_TIME_check(const ASN1_TIME *t) { ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *in, ASN1_GENERALIZEDTIME **out) { if (!ASN1_TIME_check(in)) { - return NULL; + return nullptr; } - ASN1_GENERALIZEDTIME *ret = NULL; + UniquePtr tmp; + ASN1_GENERALIZEDTIME *ret = nullptr; if (!out || !*out) { - if (!(ret = ASN1_GENERALIZEDTIME_new())) { - goto err; + tmp.reset(ASN1_GENERALIZEDTIME_new()); + if (tmp == nullptr) { + return nullptr; } + ret = tmp.get(); } else { ret = *out; } @@ -87,40 +104,35 @@ ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *in, // If already GeneralizedTime just copy across if (in->type == V_ASN1_GENERALIZEDTIME) { if (!ASN1_STRING_set(ret, in->data, in->length)) { - goto err; + return nullptr; } - goto done; - } - - // Grow the string to accomodate the two-digit century. - if (!ASN1_STRING_set(ret, NULL, in->length + 2)) { - goto err; - } - - { - char *const out_str = (char *)ret->data; - // |ASN1_STRING_set| also allocates an additional byte for a trailing NUL. - const size_t out_str_capacity = in->length + 2 + 1; - // Work out the century and prepend + } else { + assert(in->type == V_ASN1_UTCTIME); + // `ASN1_TIME_check` implies a bound on the string's lengths. In particular, + // the longest possible UTCTime is "YYMMDDHHMMSS+HHMM", with the (invalid) + // timezone offsets. + static constexpr size_t kMaxUTCTimeLength = 17; + BSSL_CHECK(in->length > 0 && + static_cast(in->length) <= kMaxUTCTimeLength); + char buf[2 /* century */ + kMaxUTCTimeLength + 1 /* NUL */]; + // Work out the century and prepend. if (in->data[0] >= '5') { - OPENSSL_strlcpy(out_str, "19", out_str_capacity); + snprintf(buf, sizeof(buf), "19%.*s", in->length, + reinterpret_cast(in->data)); } else { - OPENSSL_strlcpy(out_str, "20", out_str_capacity); + snprintf(buf, sizeof(buf), "20%.*s", in->length, + reinterpret_cast(in->data)); + } + if (!ASN1_STRING_set(ret, buf, -1 /* use strlen */)) { + return nullptr; } - OPENSSL_strlcat(out_str, (const char *)in->data, out_str_capacity); } -done: - if (out != NULL && *out == NULL) { + if (out != nullptr && *out == nullptr) { *out = ret; } + tmp.release(); // Ownership passed to caller. return ret; - -err: - if (out == NULL || *out != ret) { - ASN1_GENERALIZEDTIME_free(ret); - } - return NULL; } int ASN1_TIME_set_string(ASN1_TIME *s, const char *str) { @@ -133,7 +145,7 @@ int ASN1_TIME_set_string_X509(ASN1_TIME *s, const char *str) { CBS_init(&cbs, (const uint8_t *)str, strlen(str)); int type; struct tm tm; - if (CBS_parse_utc_time(&cbs, /*out_tm=*/NULL, + if (CBS_parse_utc_time(&cbs, /*out_tm=*/nullptr, /*allow_timezone_offset=*/0)) { type = V_ASN1_UTCTIME; } else if (CBS_parse_generalized_time(&cbs, &tm, @@ -147,7 +159,7 @@ int ASN1_TIME_set_string_X509(ASN1_TIME *s, const char *str) { return 0; } - if (s != NULL) { + if (s != nullptr) { if (!ASN1_STRING_set(s, CBS_data(&cbs), CBS_len(&cbs))) { return 0; } @@ -158,8 +170,8 @@ int ASN1_TIME_set_string_X509(ASN1_TIME *s, const char *str) { static int asn1_time_to_tm(struct tm *tm, const ASN1_TIME *t, int allow_timezone_offset) { - if (t == NULL) { - if (OPENSSL_posix_to_tm(time(NULL), tm)) { + if (t == nullptr) { + if (OPENSSL_posix_to_tm(time(nullptr), tm)) { return 1; } return 0; @@ -217,3 +229,20 @@ int ASN1_TIME_to_posix(const ASN1_TIME *t, int64_t *out_time) { } return OPENSSL_tm_to_posix(&tm, out_time); } + +int bssl::asn1_parse_time(CBS *cbs, ASN1_TIME *out, + int allow_utc_timezone_offset) { + if (CBS_peek_asn1_tag(cbs, CBS_ASN1_UTCTIME)) { + return asn1_parse_utc_time(cbs, out, /*tag=*/0, allow_utc_timezone_offset); + } + return asn1_parse_generalized_time(cbs, out, /*tag=*/0); +} + +int bssl::asn1_marshal_time(CBB *cbb, const ASN1_TIME *in) { + if (in->type != V_ASN1_UTCTIME && in->type != V_ASN1_GENERALIZEDTIME) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE); + return 0; + } + return asn1_marshal_octet_string(cbb, in, + static_cast(in->type)); +} diff --git a/Sources/CNIOBoringSSL/crypto/asn1/a_type.cc b/Sources/CNIOBoringSSL/crypto/asn1/a_type.cc index 89defbdd..8e2f1699 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/a_type.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/a_type.cc @@ -1,41 +1,87 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../bytestring/internal.h" +#include "../internal.h" #include "internal.h" +using namespace bssl; + +ASN1_TYPE *ASN1_TYPE_new() { + ASN1_TYPE *ret = New(); + if (ret == nullptr) { + return nullptr; + } + OPENSSL_memset(ret, 0, sizeof(ASN1_TYPE)); + ret->type = -1; + return ret; +} + +static void asn1_type_cleanup(ASN1_TYPE *a) { + switch (a->type) { + case V_ASN1_NULL: + a->value.ptr = nullptr; + break; + case V_ASN1_BOOLEAN: + a->value.boolean = ASN1_BOOLEAN_NONE; + break; + case V_ASN1_OBJECT: + ASN1_OBJECT_free(a->value.object); + a->value.object = nullptr; + break; + default: + ASN1_STRING_free(a->value.asn1_string); + a->value.asn1_string = nullptr; + break; + } +} + +void ASN1_TYPE_free(ASN1_TYPE *a) { + if (a != nullptr) { + asn1_type_cleanup(a); + Delete(a); + } +} + int ASN1_TYPE_get(const ASN1_TYPE *a) { switch (a->type) { case V_ASN1_NULL: case V_ASN1_BOOLEAN: return a->type; case V_ASN1_OBJECT: - return a->value.object != NULL ? a->type : 0; + return a->value.object != nullptr ? a->type : 0; default: - return a->value.asn1_string != NULL ? a->type : 0; + return a->value.asn1_string != nullptr ? a->type : 0; } } -const void *asn1_type_value_as_pointer(const ASN1_TYPE *a) { +const void *bssl::asn1_type_value_as_pointer(const ASN1_TYPE *a) { switch (a->type) { case V_ASN1_NULL: - return NULL; + return nullptr; case V_ASN1_BOOLEAN: - return a->value.boolean ? (void *)0xff : NULL; + return a->value.boolean ? (void *)0xff : nullptr; case V_ASN1_OBJECT: return a->value.object; default: @@ -43,9 +89,9 @@ const void *asn1_type_value_as_pointer(const ASN1_TYPE *a) { } } -void asn1_type_set0_string(ASN1_TYPE *a, ASN1_STRING *str) { - // |ASN1_STRING| types are almost the same as |ASN1_TYPE| types, except that - // the negative flag is not reflected into |ASN1_TYPE|. +void bssl::asn1_type_set0_string(ASN1_TYPE *a, ASN1_STRING *str) { + // `ASN1_STRING` types are almost the same as `ASN1_TYPE` types, except that + // the negative flag is not reflected into `ASN1_TYPE`. int type = str->type; if (type == V_ASN1_NEG_INTEGER) { type = V_ASN1_INTEGER; @@ -53,38 +99,19 @@ void asn1_type_set0_string(ASN1_TYPE *a, ASN1_STRING *str) { type = V_ASN1_ENUMERATED; } - // These types are not |ASN1_STRING| types and use a different - // representation when stored in |ASN1_TYPE|. + // These types are not `ASN1_STRING` types and use a different + // representation when stored in `ASN1_TYPE`. assert(type != V_ASN1_NULL && type != V_ASN1_OBJECT && type != V_ASN1_BOOLEAN); ASN1_TYPE_set(a, type, str); } -void asn1_type_cleanup(ASN1_TYPE *a) { - switch (a->type) { - case V_ASN1_NULL: - a->value.ptr = NULL; - break; - case V_ASN1_BOOLEAN: - a->value.boolean = ASN1_BOOLEAN_NONE; - break; - case V_ASN1_OBJECT: - ASN1_OBJECT_free(a->value.object); - a->value.object = NULL; - break; - default: - ASN1_STRING_free(a->value.asn1_string); - a->value.asn1_string = NULL; - break; - } -} - void ASN1_TYPE_set(ASN1_TYPE *a, int type, void *value) { asn1_type_cleanup(a); a->type = type; switch (type) { case V_ASN1_NULL: - a->value.ptr = NULL; + a->value.ptr = nullptr; break; case V_ASN1_BOOLEAN: a->value.boolean = value ? ASN1_BOOLEAN_TRUE : ASN1_BOOLEAN_FALSE; @@ -165,3 +192,276 @@ int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b) { return result; } + +int bssl::asn1_parse_any(CBS *cbs, ASN1_TYPE *out) { + CBS_ASN1_TAG tag; + CBS elem; + size_t header_len; + if (!CBS_get_any_asn1_element(cbs, &elem, &tag, &header_len)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; + } + + // Handle the non-string types. + if (tag == CBS_ASN1_OBJECT) { + UniquePtr obj(asn1_parse_object(&elem, /*tag=*/0)); + if (obj == nullptr) { + return 0; + } + ASN1_TYPE_set(out, V_ASN1_OBJECT, obj.release()); + return 1; + } + if (tag == CBS_ASN1_NULL) { + if (CBS_len(&elem) != header_len) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; + } + ASN1_TYPE_set(out, V_ASN1_NULL, nullptr); + return 1; + } + if (tag == CBS_ASN1_BOOLEAN) { + int b; + if (!CBS_get_asn1_bool(&elem, &b)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; + } + // V_ASN1_BOOLEAN will interpret the pointer as null for false and any + // arbitrary non-null pointer for true. + ASN1_TYPE_set(out, V_ASN1_BOOLEAN, b ? out : nullptr); + return 1; + } + + // All other cases are handled identically to the string-based ANY parser. + UniquePtr str(ASN1_STRING_new()); + if (str == nullptr || !asn1_parse_any_as_string(&elem, str.get())) { + return 0; + } + asn1_type_set0_string(out, str.release()); + return 1; +} + +int bssl::asn1_parse_any_as_string(CBS *cbs, ASN1_STRING *out) { + CBS_ASN1_TAG tag; + CBS elem; + size_t header_len; + if (!CBS_get_any_asn1_element(cbs, &elem, &tag, &header_len)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; + } + + // Reject unexpectedly constructed or primitive universal types, rather than + // encoding them as an opaque `V_ASN1_OTHER`. As of X.680 (02/2021), tag + // numbers 0-36 have been allocated, except 15. Of these, only 8 (EXTERNAL), + // 11 (EMBEDDED PDV), 16 (SEQUENCE), 17 (SET), and 29 (CHARACTER STRING) are + // constructed. + const CBS_ASN1_TAG tag_class = (tag & CBS_ASN1_CLASS_MASK); + const CBS_ASN1_TAG number = tag & CBS_ASN1_TAG_NUMBER_MASK; + if (tag_class == CBS_ASN1_UNIVERSAL && number <= 36 && number != 15) { + const bool is_constructed = (tag & CBS_ASN1_CONSTRUCTED) != 0; + if (number == V_ASN1_EXTERNAL || number == 11 /* EMBEDDED PDV */ || + number == V_ASN1_SEQUENCE || number == V_ASN1_SET || + number == 29 /* CHARACTER STRING*/) { + if (!is_constructed) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_CONSTRUCTED); + return 0; + } + } else { + if (is_constructed) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_PRIMITIVE); + return 0; + } + } + } + + // Historically, parsing high universal tag numbers made OpenSSL's + // `ASN1_STRING` representation ambiguous. We've since fixed this with + // `V_ASN1_OTHER` but, for now, continue to enforce the limit. + if (tag_class == CBS_ASN1_UNIVERSAL && number > V_ASN1_MAX_UNIVERSAL) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; + } + + // These types are just parsed as `V_ASN1_OTHER` here. Check the contents + // before the generic `V_ASN1_OTHER` path. + CBS body = elem; + BSSL_CHECK(CBS_skip(&body, header_len)); + switch (tag) { + case CBS_ASN1_OBJECT: + if (!CBS_is_valid_asn1_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); + return 0; + } + break; + case CBS_ASN1_BOOLEAN: { + uint8_t v; + if (!CBS_get_u8(&body, &v) || CBS_len(&body) != 0) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_BOOLEAN_IS_WRONG_LENGTH); + return 0; + } + if (v != 0 && v != 0xff) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; + } + break; + } + } + + switch (tag) { + case CBS_ASN1_INTEGER: + return asn1_parse_integer(&elem, out, tag); + case CBS_ASN1_ENUMERATED: + return asn1_parse_enumerated(&elem, out, tag); + case CBS_ASN1_BITSTRING: + return asn1_parse_bit_string(&elem, out, tag); + case CBS_ASN1_UNIVERSALSTRING: + return asn1_parse_universal_string(&elem, out, tag); + case CBS_ASN1_BMPSTRING: + return asn1_parse_bmp_string(&elem, out, tag); + 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); + case CBS_ASN1_GENERALIZEDTIME: + return asn1_parse_generalized_time(&elem, out, tag); + case CBS_ASN1_OCTETSTRING: + return asn1_parse_octet_string(&elem, out, tag); + case CBS_ASN1_T61STRING: + return asn1_parse_t61_string(&elem, out, tag); + case CBS_ASN1_IA5STRING: + case CBS_ASN1_NUMERICSTRING: + case CBS_ASN1_PRINTABLESTRING: + case CBS_ASN1_VIDEOTEXSTRING: + case CBS_ASN1_GRAPHICSTRING: + case CBS_ASN1_VISIBLESTRING: + case CBS_ASN1_GENERALSTRING: + // |CBS_ASN1_*| and |V_ASN1_*| constants match for universal types. + static_assert(CBS_ASN1_IA5STRING == V_ASN1_IA5STRING); + // TODO(crbug.com/42290290): Enforce the encoding of these string types. + return asn1_parse_string_unchecked(&elem, out, static_cast(tag), + tag); + default: + // All unrecognized types, or types that cannot be represented as + // `ASN1_STRING`, are represented as the whole element. + if (!ASN1_STRING_set(out, CBS_data(&elem), CBS_len(&elem))) { + return 0; + } + if (tag == CBS_ASN1_SEQUENCE) { + out->type = V_ASN1_SEQUENCE; + } else if (tag == CBS_ASN1_SET) { + out->type = V_ASN1_SET; + } else { + out->type = V_ASN1_OTHER; + } + return 1; + } +} + +static int asn1_marshal_string_with_type(CBB *out, const ASN1_STRING *in, + int type); + +int bssl::asn1_marshal_any(CBB *out, const ASN1_TYPE *in) { + switch (in->type) { + case V_ASN1_OBJECT: + return asn1_marshal_object(out, in->value.object, /*tag=*/0); + case V_ASN1_NULL: + return CBB_add_asn1_element(out, CBS_ASN1_NULL, nullptr, 0); + case V_ASN1_BOOLEAN: + return CBB_add_asn1_bool(out, in->value.boolean != ASN1_BOOLEAN_FALSE); + case V_ASN1_INTEGER: + case V_ASN1_ENUMERATED: + case V_ASN1_BIT_STRING: + case V_ASN1_OCTET_STRING: + case V_ASN1_NUMERICSTRING: + case V_ASN1_PRINTABLESTRING: + case V_ASN1_T61STRING: + case V_ASN1_VIDEOTEXSTRING: + case V_ASN1_IA5STRING: + case V_ASN1_UTCTIME: + case V_ASN1_GENERALIZEDTIME: + case V_ASN1_GRAPHICSTRING: + case V_ASN1_VISIBLESTRING: + case V_ASN1_GENERALSTRING: + case V_ASN1_UNIVERSALSTRING: + case V_ASN1_BMPSTRING: + case V_ASN1_UTF8STRING: + case V_ASN1_SEQUENCE: + case V_ASN1_SET: + case V_ASN1_OTHER: + // If `in->type` and the underlying `ASN1_STRING` type don't match, use + // `in->type`. See b/446993031. + return asn1_marshal_string_with_type(out, in->value.asn1_string, + in->type); + default: + // `ASN1_TYPE`s can have type -1 when default-constructed. + OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE); + return 0; + } +} + +static int asn1_marshal_string_with_type(CBB *out, const ASN1_STRING *in, + int type) { + switch (type) { + case V_ASN1_INTEGER: + case V_ASN1_NEG_INTEGER: + return asn1_marshal_integer(out, in, CBS_ASN1_INTEGER); + case V_ASN1_ENUMERATED: + case V_ASN1_NEG_ENUMERATED: + return asn1_marshal_integer(out, in, CBS_ASN1_ENUMERATED); + case V_ASN1_BIT_STRING: + return asn1_marshal_bit_string(out, in, /*tag=*/0); + case V_ASN1_OCTET_STRING: + case V_ASN1_NUMERICSTRING: + case V_ASN1_PRINTABLESTRING: + case V_ASN1_T61STRING: + case V_ASN1_VIDEOTEXSTRING: + case V_ASN1_IA5STRING: + case V_ASN1_UTCTIME: + case V_ASN1_GENERALIZEDTIME: + case V_ASN1_GRAPHICSTRING: + case V_ASN1_VISIBLESTRING: + case V_ASN1_GENERALSTRING: + case V_ASN1_UNIVERSALSTRING: + case V_ASN1_BMPSTRING: + case V_ASN1_UTF8STRING: + return asn1_marshal_octet_string(out, in, + static_cast(type)); + case V_ASN1_SEQUENCE: + case V_ASN1_SET: + case V_ASN1_OTHER: + // These three types store the whole TLV as contents. + return CBB_add_bytes(out, ASN1_STRING_get0_data(in), + ASN1_STRING_length(in)); + default: + // `ASN1_TYPE`s can have type -1 when default-constructed. + OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE); + return 0; + } +} + +int bssl::asn1_marshal_any_string(CBB *out, const ASN1_STRING *in) { + return asn1_marshal_string_with_type(out, in, in->type); +} + +ASN1_TYPE *d2i_ASN1_TYPE(ASN1_TYPE **out, const uint8_t **inp, long len) { + return D2IFromCBS(out, inp, len, [](CBS *cbs) -> UniquePtr { + UniquePtr ret(ASN1_TYPE_new()); + if (ret == nullptr || !asn1_parse_any(cbs, ret.get())) { + return nullptr; + } + return ret; + }); +} + +int i2d_ASN1_TYPE(const ASN1_TYPE *in, uint8_t **outp) { + return I2DFromCBB(/*initial_capacity=*/16, outp, [&](CBB *cbb) -> bool { + return asn1_marshal_any(cbb, in); + }); +} diff --git a/Sources/CNIOBoringSSL/crypto/asn1/a_utctm.cc b/Sources/CNIOBoringSSL/crypto/asn1/a_utctm.cc index e4d4cf3f..057373fa 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/a_utctm.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/a_utctm.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -19,8 +24,11 @@ #include "internal.h" -int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d, - int allow_timezone_offset) { + +using namespace bssl; + +int bssl::asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d, + int allow_timezone_offset) { if (d->type != V_ASN1_UTCTIME) { return 0; } @@ -32,8 +40,24 @@ int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d, return 1; } +int bssl::asn1_parse_utc_time(CBS *cbs, ASN1_UTCTIME *out, CBS_ASN1_TAG tag, + int allow_timezone_offset) { + tag = tag == 0 ? CBS_ASN1_UTCTIME : tag; + CBS child; + if (!CBS_get_asn1(cbs, &child, tag) || + !CBS_parse_utc_time(&child, nullptr, allow_timezone_offset)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; + } + if (!ASN1_STRING_set(out, CBS_data(&child), CBS_len(&child))) { + return 0; + } + out->type = V_ASN1_UTCTIME; + return 1; +} + int ASN1_UTCTIME_check(const ASN1_UTCTIME *d) { - return asn1_utctime_to_tm(NULL, d, /*allow_timezone_offset=*/1); + return asn1_utctime_to_tm(nullptr, d, /*allow_timezone_offset=*/1); } int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str) { @@ -43,11 +67,11 @@ int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str) { size_t len = strlen(str); CBS cbs; CBS_init(&cbs, (const uint8_t *)str, len); - if (!CBS_parse_utc_time(&cbs, /*out_tm=*/NULL, + if (!CBS_parse_utc_time(&cbs, /*out_tm=*/nullptr, /*allow_timezone_offset=*/0)) { return 0; } - if (s != NULL) { + if (s != nullptr) { if (!ASN1_STRING_set(s, str, len)) { return 0; } @@ -64,32 +88,32 @@ ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, int64_t posix_time, int offset_day, long offset_sec) { struct tm data; if (!OPENSSL_posix_to_tm(posix_time, &data)) { - return NULL; + return nullptr; } if (offset_day || offset_sec) { if (!OPENSSL_gmtime_adj(&data, offset_day, offset_sec)) { - return NULL; + return nullptr; } } if (data.tm_year < 50 || data.tm_year >= 150) { - return NULL; + return nullptr; } char buf[14]; int ret = snprintf(buf, sizeof(buf), "%02d%02d%02d%02d%02d%02dZ", data.tm_year % 100, data.tm_mon + 1, data.tm_mday, data.tm_hour, data.tm_min, data.tm_sec); - // |snprintf| must write exactly 15 bytes (plus the NUL) to the buffer. + // `snprintf` must write exactly 15 bytes (plus the NUL) to the buffer. BSSL_CHECK(ret == static_cast(sizeof(buf) - 1)); int free_s = 0; - if (s == NULL) { + if (s == nullptr) { free_s = 1; s = ASN1_UTCTIME_new(); - if (s == NULL) { - return NULL; + if (s == nullptr) { + return nullptr; } } @@ -97,7 +121,7 @@ ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, int64_t posix_time, if (free_s) { ASN1_UTCTIME_free(s); } - return NULL; + return nullptr; } s->type = V_ASN1_UTCTIME; return s; diff --git a/Sources/CNIOBoringSSL/crypto/asn1/asn1_lib.cc b/Sources/CNIOBoringSSL/crypto/asn1/asn1_lib.cc index 1ef81ab8..cd23145a 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/asn1_lib.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/asn1_lib.cc @@ -1,14 +1,20 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,9 +23,12 @@ #include #include "../internal.h" +#include "../mem_internal.h" #include "internal.h" +using namespace bssl; + // Cross-module errors from crypto/x509/i2d_pr.c. OPENSSL_DECLARE_ERROR_REASON(ASN1, UNSUPPORTED_PUBLIC_KEY_TYPE) @@ -55,13 +64,13 @@ OPENSSL_DECLARE_ERROR_REASON(ASN1, UNKNOWN_FORMAT) OPENSSL_DECLARE_ERROR_REASON(ASN1, UNKNOWN_TAG) OPENSSL_DECLARE_ERROR_REASON(ASN1, UNSUPPORTED_TYPE) -// Limit |ASN1_STRING|s to 64 MiB of data. Most of this module, as well as +// Limit `ASN1_STRING`s to 64 MiB of data. Most of this module, as well as // downstream code, does not correctly handle overflow. We cap string fields -// more tightly than strictly necessary to fit in |int|. This is not expected to +// more tightly than strictly necessary to fit in `int`. This is not expected to // impact real world uses of this field. // // In particular, this limit is small enough that the bit count of a BIT STRING -// comfortably fits in an |int|, with room for arithmetic. +// comfortably fits in an `int`, with room for arithmetic. #define ASN1_STRING_MAX (64 * 1024 * 1024) static void asn1_put_length(unsigned char **pp, int length); @@ -102,7 +111,7 @@ int ASN1_get_object(const unsigned char **inp, long *out_len, int *out_tag, return constructed; } -// class 0 is constructed constructed == 2 for indefinite length constructed +// class 0 is constructed, constructed == 2 for indefinite length constructed void ASN1_put_object(unsigned char **pp, int constructed, int length, int tag, int xclass) { unsigned char *p = *pp; @@ -196,9 +205,12 @@ int ASN1_object_size(int constructed, int length, int tag) { } int ASN1_STRING_copy(ASN1_STRING *dst, const ASN1_STRING *str) { - if (str == NULL) { + if (str == nullptr) { return 0; } + if (dst == str) { + return 1; + } if (!ASN1_STRING_set(dst, str->data, str->length)) { return 0; } @@ -210,15 +222,15 @@ int ASN1_STRING_copy(ASN1_STRING *dst, const ASN1_STRING *str) { ASN1_STRING *ASN1_STRING_dup(const ASN1_STRING *str) { ASN1_STRING *ret; if (!str) { - return NULL; + return nullptr; } ret = ASN1_STRING_new(); if (!ret) { - return NULL; + return nullptr; } if (!ASN1_STRING_copy(ret, str)) { ASN1_STRING_free(ret); - return NULL; + return nullptr; } return ret; } @@ -227,7 +239,7 @@ int ASN1_STRING_set(ASN1_STRING *str, const void *_data, ossl_ssize_t len_s) { const char *data = reinterpret_cast(_data); size_t len; if (len_s < 0) { - if (data == NULL) { + if (data == nullptr) { return 0; } len = strlen(data); @@ -241,24 +253,25 @@ int ASN1_STRING_set(ASN1_STRING *str, const void *_data, ossl_ssize_t len_s) { return 0; } - if (str->length <= (int)len || str->data == NULL) { + if (str->length <= (int)len || str->data == nullptr) { unsigned char *c = str->data; - if (c == NULL) { + if (c == nullptr) { str->data = reinterpret_cast(OPENSSL_malloc(len + 1)); } else { str->data = reinterpret_cast(OPENSSL_realloc(c, len + 1)); } - if (str->data == NULL) { + if (str->data == nullptr) { str->data = c; return 0; } } str->length = (int)len; - if (data != NULL) { + str->flags &= ~0x07; // Clear unused bits if this is a BIT STRING. + if (data != nullptr) { OPENSSL_memcpy(str->data, data, len); // Historically, OpenSSL would NUL-terminate most (but not all) - // |ASN1_STRING|s, in case anyone accidentally passed |str->data| into a + // `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. str->data[len] = '\0'; @@ -270,49 +283,56 @@ void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len) { OPENSSL_free(str->data); str->data = reinterpret_cast(data); str->length = len; + str->flags &= ~0x07; // Clear unused bits if this is a BIT STRING. } -ASN1_STRING *ASN1_STRING_new(void) { +ASN1_STRING *ASN1_STRING_new() { return (ASN1_STRING_type_new(V_ASN1_OCTET_STRING)); } ASN1_STRING *ASN1_STRING_type_new(int type) { - ASN1_STRING *ret; - - ret = (ASN1_STRING *)OPENSSL_malloc(sizeof(ASN1_STRING)); - if (ret == NULL) { - return NULL; + ASN1_STRING *ret = New(); + if (ret == nullptr) { + return nullptr; } ret->length = 0; ret->type = type; - ret->data = NULL; + ret->data = nullptr; ret->flags = 0; return ret; } +void bssl::asn1_string_init(ASN1_STRING *str, int type) { + OPENSSL_memset(str, 0, sizeof(ASN1_STRING)); + str->type = type; +} + +void bssl::asn1_string_cleanup(ASN1_STRING *str) { + OPENSSL_free(str->data); + str->data = nullptr; +} + void ASN1_STRING_free(ASN1_STRING *str) { - if (str == NULL) { + if (str == nullptr) { return; } - OPENSSL_free(str->data); - OPENSSL_free(str); + asn1_string_cleanup(str); + Delete(str); } int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b) { - // Capture padding bits and implicit truncation in BIT STRINGs. - int a_length = a->length, b_length = b->length; uint8_t a_padding = 0, b_padding = 0; if (a->type == V_ASN1_BIT_STRING) { - a_length = asn1_bit_string_length(a, &a_padding); + a_padding = ASN1_BIT_STRING_unused_bits(a); } if (b->type == V_ASN1_BIT_STRING) { - b_length = asn1_bit_string_length(b, &b_padding); + b_padding = ASN1_BIT_STRING_unused_bits(b); } - if (a_length < b_length) { + if (a->length < b->length) { return -1; } - if (a_length > b_length) { + if (a->length > b->length) { return 1; } // In a BIT STRING, the number of bits is 8 * length - padding. Invert this @@ -324,7 +344,7 @@ int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b) { return 1; } - int ret = OPENSSL_memcmp(a->data, b->data, a_length); + int ret = OPENSSL_memcmp(a->data, b->data, a->length); if (ret != 0) { return ret; } @@ -348,3 +368,86 @@ unsigned char *ASN1_STRING_data(ASN1_STRING *str) { return str->data; } const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *str) { return str->data; } + +int bssl::asn1_parse_string_unchecked(CBS *cbs, ASN1_STRING *out, int str_type, + CBS_ASN1_TAG tag) { + assert(tag != 0); + CBS child; + if (!CBS_get_asn1(cbs, &child, tag)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; + } + if (!ASN1_STRING_set(out, CBS_data(&child), CBS_len(&child))) { + return 0; + } + out->type = str_type; + return 1; +} + +int bssl::asn1_parse_octet_string(CBS *cbs, ASN1_STRING *out, + CBS_ASN1_TAG tag) { + // Nothing to check for OCTET STRING. + tag = tag == 0 ? CBS_ASN1_OCTETSTRING : tag; + return asn1_parse_string_unchecked(cbs, out, V_ASN1_OCTET_STRING, tag); +} + +int bssl::asn1_parse_t61_string(CBS *cbs, ASN1_STRING *out, CBS_ASN1_TAG tag) { + // Nothing to check for T61String. We parse it as Latin-1 and all byte strings + // are valid Latin-1. + tag = tag == 0 ? CBS_ASN1_T61STRING : tag; + return asn1_parse_string_unchecked(cbs, out, V_ASN1_T61STRING, tag); +} + +int bssl::asn1_marshal_octet_string(CBB *out, const ASN1_STRING *in, + CBS_ASN1_TAG tag) { + tag = tag == 0 ? CBS_ASN1_OCTETSTRING : tag; + return CBB_add_asn1_element(out, tag, ASN1_STRING_get0_data(in), + ASN1_STRING_length(in)); +} + +static int asn1_parse_character_string(CBS *cbs, ASN1_STRING *out, + CBS_ASN1_TAG tag, int str_type, + int (*get_char)(CBS *cbs, uint32_t *), + int bad_char_err) { + CBS child; + if (!CBS_get_asn1(cbs, &child, tag)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; + } + CBS copy = child; + while (CBS_len(©) != 0) { + uint32_t c; + if (!get_char(©, &c)) { + OPENSSL_PUT_ERROR(ASN1, bad_char_err); + return 0; + } + } + if (!ASN1_STRING_set(out, CBS_data(&child), CBS_len(&child))) { + return 0; + } + out->type = str_type; + return 1; +} + +int bssl::asn1_parse_bmp_string(CBS *cbs, ASN1_BMPSTRING *out, + CBS_ASN1_TAG tag) { + tag = tag == 0 ? CBS_ASN1_BMPSTRING : tag; + return asn1_parse_character_string(cbs, out, tag, V_ASN1_BMPSTRING, + &CBS_get_ucs2_be, + ASN1_R_INVALID_BMPSTRING); +} + +int bssl::asn1_parse_universal_string(CBS *cbs, ASN1_UNIVERSALSTRING *out, + CBS_ASN1_TAG tag) { + tag = tag == 0 ? CBS_ASN1_UNIVERSALSTRING : tag; + return asn1_parse_character_string(cbs, out, tag, V_ASN1_UNIVERSALSTRING, + &CBS_get_utf32_be, + ASN1_R_INVALID_UNIVERSALSTRING); +} + +int bssl::asn1_parse_utf8_string(CBS *cbs, ASN1_UNIVERSALSTRING *out, + CBS_ASN1_TAG tag) { + tag = tag == 0 ? CBS_ASN1_UTF8STRING : tag; + return asn1_parse_character_string(cbs, out, tag, V_ASN1_UTF8STRING, + &CBS_get_utf8, ASN1_R_INVALID_UTF8STRING); +} diff --git a/Sources/CNIOBoringSSL/crypto/asn1/asn1_par.cc b/Sources/CNIOBoringSSL/crypto/asn1/asn1_par.cc index 8a86c4b3..3b4fa490 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/asn1_par.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/asn1_par.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 diff --git a/Sources/CNIOBoringSSL/crypto/asn1/asn_pack.cc b/Sources/CNIOBoringSSL/crypto/asn1/asn_pack.cc index 6cf84751..e1f96848 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/asn_pack.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/asn_pack.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,26 +19,26 @@ ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, ASN1_STRING **out) { - uint8_t *new_data = NULL; + uint8_t *new_data = nullptr; int len = ASN1_item_i2d(reinterpret_cast(obj), &new_data, it); if (len <= 0) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_ENCODE_ERROR); - return NULL; + return nullptr; } - ASN1_STRING *ret = NULL; - if (out == NULL || *out == NULL) { + ASN1_STRING *ret = nullptr; + if (out == nullptr || *out == nullptr) { ret = ASN1_STRING_new(); - if (ret == NULL) { + if (ret == nullptr) { OPENSSL_free(new_data); - return NULL; + return nullptr; } } else { ret = *out; } ASN1_STRING_set0(ret, new_data, len); - if (out != NULL) { + if (out != nullptr) { *out = ret; } return ret; @@ -41,11 +46,11 @@ ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, ASN1_STRING **out) { void *ASN1_item_unpack(const ASN1_STRING *oct, const ASN1_ITEM *it) { const unsigned char *p = oct->data; - void *ret = ASN1_item_d2i(NULL, &p, oct->length, it); - if (ret == NULL || p != oct->data + oct->length) { + void *ret = ASN1_item_d2i(nullptr, &p, oct->length, it); + if (ret == nullptr || p != oct->data + oct->length) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); ASN1_item_free(reinterpret_cast(ret), it); - return NULL; + return nullptr; } return ret; } diff --git a/Sources/CNIOBoringSSL/crypto/asn1/f_int.cc b/Sources/CNIOBoringSSL/crypto/asn1/f_int.cc index 436414da..a95b73c9 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/f_int.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/f_int.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,7 +21,7 @@ int i2a_ASN1_INTEGER(BIO *bp, const ASN1_INTEGER *a) { static const char *h = "0123456789ABCDEF"; char buf[2]; - if (a == NULL) { + if (a == nullptr) { return 0; } diff --git a/Sources/CNIOBoringSSL/crypto/asn1/f_string.cc b/Sources/CNIOBoringSSL/crypto/asn1/f_string.cc index 14c8f367..31c01269 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/f_string.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/f_string.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,7 +21,7 @@ int i2a_ASN1_STRING(BIO *bp, const ASN1_STRING *a, int type) { static const char *h = "0123456789ABCDEF"; char buf[2]; - if (a == NULL) { + if (a == nullptr) { return 0; } diff --git a/Sources/CNIOBoringSSL/crypto/asn1/internal.h b/Sources/CNIOBoringSSL/crypto/asn1/internal.h index 176ce706..4bf46b7f 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/internal.h +++ b/Sources/CNIOBoringSSL/crypto/asn1/internal.h @@ -1,49 +1,56 @@ -/* - * Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. -#ifndef OPENSSL_HEADER_ASN1_INTERNAL_H -#define OPENSSL_HEADER_ASN1_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_ASN1_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_ASN1_INTERNAL_H #include #include #include +#include -#if defined(__cplusplus) -extern "C" { -#endif +#include "../internal.h" +BSSL_NAMESPACE_BEGIN + // Wrapper functions for time functions. -// OPENSSL_gmtime converts a time_t value in |time| which must be in the range -// of year 0000 to 9999 to a broken out time value in |tm|. On success |tm| is +// OPENSSL_gmtime converts a time_t value in `time` which must be in the range +// of year 0000 to 9999 to a broken out time value in `tm`. On success `tm` is // returned. On failure NULL is returned. OPENSSL_EXPORT struct tm *OPENSSL_gmtime(const time_t *time, struct tm *result); -// OPENSSL_gmtime_adj returns one on success, and updates |tm| by adding -// |offset_day| days and |offset_sec| seconds. It returns zero on failure. |tm| +// OPENSSL_gmtime_adj returns one on success, and updates `tm` by adding +// `offset_day` days and `offset_sec` seconds. It returns zero on failure. `tm` // must be in the range of year 0000 to 9999 both before and after the update or // a failure will be returned. OPENSSL_EXPORT int OPENSSL_gmtime_adj(struct tm *tm, int offset_day, int64_t offset_sec); -// OPENSSL_gmtime_diff calculates the difference between |from| and |to|. It +// OPENSSL_gmtime_diff calculates the difference between `from` and `to`. It // returns one, and outputs the difference as a number of days and seconds in -// |*out_days| and |*out_secs| on success. It returns zero on failure. Both -// |from| and |to| must be in the range of year 0000 to 9999 or a failure will +// `*out_days` and `*out_secs` on success. It returns zero on failure. Both +// `from` and `to` must be in the range of year 0000 to 9999 or a failure will // be returned. OPENSSL_EXPORT int OPENSSL_gmtime_diff(int *out_days, int *out_secs, const struct tm *from, const struct tm *to); -// Internal ASN1 structures and functions: not for application use + +// Object identifiers. // These are used internally in the ASN1_OBJECT to keep track of // whether the names and data need to be free()ed @@ -51,10 +58,12 @@ OPENSSL_EXPORT int OPENSSL_gmtime_diff(int *out_days, int *out_secs, #define ASN1_OBJECT_FLAG_DYNAMIC_STRINGS 0x04 // internal use #define ASN1_OBJECT_FLAG_DYNAMIC_DATA 0x08 // internal use -// An asn1_object_st (aka |ASN1_OBJECT|) represents an ASN.1 OBJECT IDENTIFIER. -// Note: Mutating an |ASN1_OBJECT| is only permitted when initializing it. The -// library maintains a table of static |ASN1_OBJECT|s, which may be referenced -// by non-const |ASN1_OBJECT| pointers. Code which receives an |ASN1_OBJECT| +BSSL_NAMESPACE_END + +// An asn1_object_st (aka `ASN1_OBJECT`) represents an ASN.1 OBJECT IDENTIFIER. +// Note: Mutating an `ASN1_OBJECT` is only permitted when initializing it. The +// library maintains a table of static `ASN1_OBJECT`s, which may be referenced +// by non-const `ASN1_OBJECT` pointers. Code which receives an `ASN1_OBJECT` // pointer externally must assume it is immutable, even if the pointer is not // const. struct asn1_object_st { @@ -65,66 +74,206 @@ struct asn1_object_st { int flags; // Should we free this one }; -ASN1_OBJECT *ASN1_OBJECT_new(void); +BSSL_NAMESPACE_BEGIN -// ASN1_ENCODING is used to save the received encoding of an ASN.1 type. This -// avoids problems with invalid encodings that break signatures. -typedef struct ASN1_ENCODING_st { - // enc is the saved DER encoding. Its ownership is determined by |buf|. - uint8_t *enc; - // len is the length of |enc|. If zero, there is no saved encoding. - size_t len; - // buf, if non-NULL, is the |CRYPTO_BUFFER| that |enc| points into. If NULL, - // |enc| must be released with |OPENSSL_free|. - CRYPTO_BUFFER *buf; -} ASN1_ENCODING; +ASN1_OBJECT *ASN1_OBJECT_new(); + +// asn1_parse_object parses a DER-encoded ASN.1 OBJECT IDENTIFIER from `cbs` and +// write the result to `out`. If `tag` is non-zero, the value is implicitly +// tagged with `tag`. On success, it returns a newly-allocated `ASN1_OBJECT` +// with the result and advances `cbs` past the parsed element. +// +// TODO(crbug.com/boringssl/414361735): This should return a bssl::UniquePtr, +// but cannot until it is made C++ linkage. +ASN1_OBJECT *asn1_parse_object(CBS *cbs, CBS_ASN1_TAG tag); + +// asn1_marshal_object marshals `in` as a DER-encoded, ASN.1 OBJECT IDENTIFIER +// and writes the result to `out`. It returns one on success and zero on error. +// If `tag` is non-zero, the tag is replaced with `tag`. +int asn1_marshal_object(CBB *out, const ASN1_OBJECT *in, CBS_ASN1_TAG tag); + + +// Strings. + +// asn1_is_printable returns one if `value` is a valid Unicode codepoint for an +// ASN.1 PrintableString, and zero otherwise. +int asn1_is_printable(uint32_t value); + +// asn1_string_init initializes `str`, which may be uninitialized, with type +// `type`. +void asn1_string_init(ASN1_STRING *str, int type); + +// asn1_string_cleanup releases memory associated with `str`'s value, without +// freeing `str` itself. +void asn1_string_cleanup(ASN1_STRING *str); + +// A ScopedASN1String is a stack-allocatable `ASN1_STRING` with managed +// lifetime. +// TODO(crbug.com/443769299): Once `ASN1_STRING` is no longer public, this can +// instead use `DECLARE_OPAQUE_STRUCT`. +class ScopedASN1String { + public: + explicit ScopedASN1String(int type) { asn1_string_init(&str_, type); } + ScopedASN1String(const ScopedASN1String &) = delete; + ScopedASN1String &operator=(const ScopedASN1String &) = delete; + ~ScopedASN1String() { asn1_string_cleanup(&str_); } + + ASN1_STRING *get() { return &str_; } + const ASN1_STRING *get() const { return &str_; } + ASN1_STRING *operator->() { return &str_; } + const ASN1_STRING *operator->() const { return &str_; } + + private: + ASN1_STRING str_; +}; + +// asn1_parse_string_unchecked parses a DER-encoded string of type `str_type`, +// tagged with `tag`. It does not check the contents. +int asn1_parse_string_unchecked(CBS *cbs, ASN1_STRING *out, int str_type, + CBS_ASN1_TAG tag); + +// The following functions parse a DER-encoded ASN.1 value of the specified +// type from `cbs` and write the result to `*out`. If `tag` is non-zero, the +// value is implicitly tagged with `tag`. On success, they return one and +// advance `cbs` past the parsed element. On entry, `*out` must contain an +// `ASN1_STRING` in some valid state. +int asn1_parse_bit_string(CBS *cbs, ASN1_BIT_STRING *out, CBS_ASN1_TAG tag); +int asn1_parse_integer(CBS *cbs, ASN1_INTEGER *out, CBS_ASN1_TAG tag); +int asn1_parse_enumerated(CBS *cbs, ASN1_ENUMERATED *out, CBS_ASN1_TAG tag); +int asn1_parse_octet_string(CBS *cbs, ASN1_STRING *out, CBS_ASN1_TAG tag); +int asn1_parse_t61_string(CBS *cbs, ASN1_STRING *out, CBS_ASN1_TAG tag); +int asn1_parse_bmp_string(CBS *cbs, ASN1_BMPSTRING *out, CBS_ASN1_TAG tag); +int asn1_parse_universal_string(CBS *cbs, ASN1_UNIVERSALSTRING *out, + CBS_ASN1_TAG tag); +int asn1_parse_utf8_string(CBS *cbs, ASN1_UNIVERSALSTRING *out, + CBS_ASN1_TAG tag); +int asn1_parse_generalized_time(CBS *cbs, ASN1_GENERALIZEDTIME *out, + CBS_ASN1_TAG tag); +int asn1_parse_utc_time(CBS *cbs, ASN1_UTCTIME *out, CBS_ASN1_TAG tag, + int allow_timezone_offset); + +// asn1_parse_bit_string_with_bad_length behaves like `asn1_parse_bit_string` +// but tolerates BER non-minimal, definite lengths. +int asn1_parse_bit_string_with_bad_length(CBS *cbs, ASN1_BIT_STRING *out); + +// asn1_marshal_bit_string marshals `in` as a DER-encoded, ASN.1 BIT STRING and +// writes the result to `out`. It returns one on success and zero on error. If +// `tag` is non-zero, the tag is replaced with `tag`. +int asn1_marshal_bit_string(CBB *out, const ASN1_BIT_STRING *in, + CBS_ASN1_TAG tag); + +// asn1_marshal_integer marshals `in` as a DER-encoded, ASN.1 INTEGER and writes +// the result to `out`. It returns one on success and zero on error. If `tag` is +// non-zero, the tag is replaced with `tag`. This can also be used to marshal an +// ASN.1 ENUMERATED value by overriding the tag. +int asn1_marshal_integer(CBB *out, const ASN1_INTEGER *in, CBS_ASN1_TAG tag); + +// asn1_marshal_octet_string marshals `in` as a DER-encoded, ASN.1 OCTET STRING +// and writes the result to `out`. It returns one on success and zero on error. +// If `tag` is non-zero, the tag is replaced with `tag`. +// +// This function may be used to marshal other string-based universal types whose +// encoding is that of an implicitly-tagged OCTET STRING, e.g. UTF8String. +int asn1_marshal_octet_string(CBB *out, const ASN1_STRING *in, + CBS_ASN1_TAG tag); OPENSSL_EXPORT int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d, int allow_timezone_offset); OPENSSL_EXPORT int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d); +int asn1_parse_time(CBS *cbs, ASN1_TIME *out, int allow_utc_timezone_offset); +int asn1_marshal_time(CBB *cbb, const ASN1_TIME *in); + + +// The ASN.1 ANY type. + +// asn1_type_value_as_pointer returns `a`'s value in pointer form. This is +// usually the value object but, for BOOLEAN values, is 0 or 0xff cast to +// a pointer. +const void *asn1_type_value_as_pointer(const ASN1_TYPE *a); + +// asn1_type_set0_string sets `a`'s value to the object represented by `str` and +// takes ownership of `str`. +void asn1_type_set0_string(ASN1_TYPE *a, ASN1_STRING *str); + +// asn1_parse_any parses a DER-encoded ASN.1 value of any type from `cbs` and +// writes the result to `*out`. On success, it advances `cbs` past the parsed +// element and returns one. On entry, `*out` must contain an `ASN1_TYPE` in some +// valid state. +int asn1_parse_any(CBS *cbs, ASN1_TYPE *out); + +// asn1_parse_any_as_string behaves like `asn1_parse_any` but represents the +// value as an `ASN1_STRING`. Types which are not represented with +// `ASN1_STRING`, such as `ASN1_OBJECT`, are represented with type +// `V_ASN1_OTHER`. +int asn1_parse_any_as_string(CBS *cbs, ASN1_STRING *out); + +// asn1_marshal_any marshals `in` as a DER-encoded ASN.1 value and writes the +// result to `out`. It returns one on success and zero on error. +int asn1_marshal_any(CBB *out, const ASN1_TYPE *in); + +// asn1_marshal_any_string marshals `in` as a DER-encoded ASN.1 value and writes +// the result to `out`. It returns one on success and zero on error. +int asn1_marshal_any_string(CBB *out, const ASN1_STRING *in); + + +// Support structures for the template-based encoder. + +// ASN1_ENCODING is used to save the received encoding of an ASN.1 type. This +// avoids problems with invalid encodings that break signatures. +typedef struct ASN1_ENCODING_st { + // enc is the saved DER encoding. Its ownership is determined by `buf`. + uint8_t *enc; + // len is the length of `enc`. If zero, there is no saved encoding. + size_t len; +} ASN1_ENCODING; + int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it); void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it); void ASN1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt); -// ASN1_item_ex_d2i parses |len| bytes from |*in| as a structure of type |it| -// and writes the result to |*pval|. If |tag| is non-negative, |it| is -// implicitly tagged with the tag specified by |tag| and |aclass|. If |opt| is -// non-zero, the value is optional. If |buf| is non-NULL, |*in| must point into -// |buf|. -// -// This function returns one and advances |*in| if an object was successfully -// parsed, -1 if an optional value was successfully skipped, and zero on error. -int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, - const ASN1_ITEM *it, int tag, int aclass, char opt, - CRYPTO_BUFFER *buf); - -// ASN1_item_ex_i2d encodes |*pval| as a value of type |it| to |out| under the -// i2d output convention. It returns a non-zero length on success and -1 on -// error. If |tag| is -1. the tag and class come from |it|. Otherwise, the tag -// number is |tag| and the class is |aclass|. This is used for implicit tagging. -// This function treats a missing value as an error, not an optional field. -int ASN1_item_ex_i2d(ASN1_VALUE **pval, unsigned char **out, - const ASN1_ITEM *it, int tag, int aclass); - void ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it); -// asn1_get_choice_selector returns the CHOICE selector value for |*pval|, which -// must of type |it|. +// asn1_load_ptr returns `*pval`, but without asserting `*pval`'s underlying +// type for strict aliasing. This helper must be used when the field's +// underlying type is not known statically. It must not be used for +// `ASN1_BOOLEAN` fields, which are not a pointers. +inline ASN1_VALUE *asn1_load_ptr(ASN1_VALUE **pval) { + ASN1_VALUE *ret; + OPENSSL_memcpy(&ret, pval, sizeof(ASN1_VALUE *)); + return ret; +} + +// asn1_load_ptr_as behaves like `asn1_load_ptr`, but casts the result to `T*`. +template +inline T *asn1_load_ptr_as(ASN1_VALUE **pval) { + return reinterpret_cast(asn1_load_ptr(pval)); +} + +// asn1_store_ptr sets `*pval` to `v`, but without asserting `*pval`'s +// underlying type for strict aliasing. This helper must be used when the +// field's underlying type is not known statically. It must not be used for +// `ASN1_BOOLEAN` fields, which are not a pointers. +inline void asn1_store_ptr(ASN1_VALUE **pval, const void *v) { + OPENSSL_memcpy(pval, &v, sizeof(v)); +} + +// asn1_get_choice_selector returns the CHOICE selector value for `*pval`, which +// must of type `it`. int asn1_get_choice_selector(ASN1_VALUE **pval, const ASN1_ITEM *it); int asn1_set_choice_selector(ASN1_VALUE **pval, int value, const ASN1_ITEM *it); -// asn1_get_field_ptr returns a pointer to the field in |*pval| corresponding to -// |tt|. +// asn1_get_field_ptr returns a pointer to the field in `*pval` corresponding to +// `tt`. ASN1_VALUE **asn1_get_field_ptr(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt); -// asn1_do_adb returns the |ASN1_TEMPLATE| for the ANY DEFINED BY field |tt|, -// based on the selector INTEGER or OID in |*pval|. If |tt| is not an ADB field, -// it returns |tt|. If the selector does not match any value, it returns NULL. -// If |nullerr| is non-zero, it will additionally push an error to the error +// asn1_do_adb returns the `ASN1_TEMPLATE` for the ANY DEFINED BY field `tt`, +// based on the selector INTEGER or OID in `*pval`. If `tt` is not an ADB field, +// it returns `tt`. If the selector does not match any value, it returns NULL. +// If `nullerr` is non-zero, it will additionally push an error to the error // queue when there is no match. const ASN1_TEMPLATE *asn1_do_adb(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt, int nullerr); @@ -135,45 +284,29 @@ int asn1_refcount_dec_and_test_zero(ASN1_VALUE **pval, const ASN1_ITEM *it); void asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it); void asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it); -// asn1_enc_restore, if |*pval| has a saved encoding, writes it to |out| under -// the i2d output convention, sets |*len| to the length, and returns one. If it -// has no saved encoding, it returns zero. -int asn1_enc_restore(int *len, unsigned char **out, ASN1_VALUE **pval, +// asn1_enc_restore, if `*pval` has a saved encoding, sets `*out` to it, and +// returns one. If it has no saved encoding, it returns zero. +int asn1_enc_restore(Span *out, ASN1_VALUE **pval, const ASN1_ITEM *it); -// asn1_enc_save saves |inlen| bytes from |in| as |*pval|'s saved encoding. It -// returns one on success and zero on error. If |buf| is non-NULL, |in| must -// point into |buf|. +// asn1_enc_save saves `inlen` bytes from `in` as `*pval`'s saved encoding. It +// returns one on success and zero on error. If `buf` is non-NULL, `in` must +// point into `buf`. int asn1_enc_save(ASN1_VALUE **pval, const uint8_t *in, size_t inlen, - const ASN1_ITEM *it, CRYPTO_BUFFER *buf); + const ASN1_ITEM *it); -// asn1_encoding_clear clears the cached encoding in |enc|. +// asn1_encoding_clear clears the cached encoding in `enc`. void asn1_encoding_clear(ASN1_ENCODING *enc); -// asn1_type_value_as_pointer returns |a|'s value in pointer form. This is -// usually the value object but, for BOOLEAN values, is 0 or 0xff cast to -// a pointer. -const void *asn1_type_value_as_pointer(const ASN1_TYPE *a); - -// asn1_type_set0_string sets |a|'s value to the object represented by |str| and -// takes ownership of |str|. -void asn1_type_set0_string(ASN1_TYPE *a, ASN1_STRING *str); - -// asn1_type_cleanup releases memory associated with |a|'s value, without -// freeing |a| itself. -void asn1_type_cleanup(ASN1_TYPE *a); - -// asn1_is_printable returns one if |value| is a valid Unicode codepoint for an -// ASN.1 PrintableString, and zero otherwise. -int asn1_is_printable(uint32_t value); - -// asn1_bit_string_length returns the number of bytes in |str| and sets -// |*out_padding_bits| to the number of padding bits. +// asn1_tag_to_cbs converts a tag from this library's representation (the +// `V_ASN1_*` constants) to that of `CBS` and `CBB`. It returns the tag on +// success and zero if the input could not be represented. (Zero would be +// [UNIVERSAL 0], which is a reserved tag value.) // -// This function should be used instead of |ASN1_STRING_length| to correctly -// handle the non-|ASN1_STRING_FLAG_BITS_LEFT| case. -int asn1_bit_string_length(const ASN1_BIT_STRING *str, - uint8_t *out_padding_bits); +// The resulting tag will not have the constructed bit set. The caller must OR +// the result with `CBS_ASN1_CONSTRUCTED` if necessary, before passing to +// `CBS` and `CBB` functions. +CBS_ASN1_TAG asn1_tag_to_cbs(int aclass, int tag); typedef struct { int nid; @@ -183,35 +316,115 @@ typedef struct { unsigned long flags; } ASN1_STRING_TABLE; -// asn1_get_string_table_for_testing sets |*out_ptr| and |*out_len| to the table -// of built-in |ASN1_STRING_TABLE| values. It is exported for testing. +// asn1_get_string_table_for_testing sets `*out_ptr` and `*out_len` to the table +// of built-in `ASN1_STRING_TABLE` values. It is exported for testing. OPENSSL_EXPORT void asn1_get_string_table_for_testing( const ASN1_STRING_TABLE **out_ptr, size_t *out_len); -typedef ASN1_VALUE *ASN1_new_func(void); +typedef ASN1_VALUE *ASN1_new_func(); typedef void ASN1_free_func(ASN1_VALUE *a); typedef ASN1_VALUE *ASN1_d2i_func(ASN1_VALUE **a, const unsigned char **in, long length); typedef int ASN1_i2d_func(ASN1_VALUE *a, unsigned char **in); -typedef int ASN1_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, - const ASN1_ITEM *it, int opt, ASN1_TLC *ctx); +// An ASN1_ex_parse function should parse a value from `cbs` and set `*pval` to +// the result. It should return one on success and zero on failure. If `opt` is +// non-zero, the field may be optional. If an optional element is missing, the +// function should return one and consume zero bytes from `cbs`. +// +// If `opt` is non-zero, the function can assume that `*pval` is nullptr on +// entry. Otherwise, `*pval` may either be nullptr, or the result of +// `ASN1_ex_new_func`. The function may either write into the existing object, +// if any, or unconditionally make a new one. (The existing object comes from +// tasn_new.cc recursively filling in objects before parsing into them.) +typedef int ASN1_ex_parse(ASN1_VALUE **pval, CBS *cbs, const ASN1_ITEM *it, + int opt); + +// An ASN1_ex_marshal function should marshal `*pval`, a value of type `it`, to +// `cbb` and return one on success or zero on error. +typedef int ASN1_ex_marshal(CBB *cbb, ASN1_VALUE **pval, const ASN1_ITEM *it); -typedef int ASN1_ex_i2d(ASN1_VALUE **pval, unsigned char **out, - const ASN1_ITEM *it); typedef int ASN1_ex_new_func(ASN1_VALUE **pval, const ASN1_ITEM *it); typedef void ASN1_ex_free_func(ASN1_VALUE **pval, const ASN1_ITEM *it); typedef struct ASN1_EXTERN_FUNCS_st { ASN1_ex_new_func *asn1_ex_new; ASN1_ex_free_func *asn1_ex_free; - ASN1_ex_d2i *asn1_ex_d2i; - ASN1_ex_i2d *asn1_ex_i2d; + ASN1_ex_parse *asn1_ex_parse; + ASN1_ex_marshal *asn1_ex_marshal; } ASN1_EXTERN_FUNCS; +// 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}; \ + \ + IMPLEMENT_EXTERN_ASN1(name, name##_extern_funcs) -#if defined(__cplusplus) -} // extern C -#endif +// IMPLEMENT_EXTERN_ASN1_PARSE_INTO implements an `ASN1_ITEM` for a type whose +// parse function writes into an existing object. +#define IMPLEMENT_EXTERN_ASN1_PARSE_INTO(name, new_func, free_func, tag, \ + parse_func, marshal_func) \ + \ + static 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) -#endif // OPENSSL_HEADER_ASN1_INTERNAL_H +// ASN1_TIME is an `ASN1_ITEM` whose ASN.1 type is X.509 Time (RFC 5280) and C +// type is `ASN1_TIME*`. +DECLARE_ASN1_ITEM(ASN1_TIME) + +// DIRECTORYSTRING is an `ASN1_ITEM` whose ASN.1 type is X.509 DirectoryString +// (RFC 5280) and C type is `ASN1_STRING*`. +DECLARE_ASN1_ITEM(DIRECTORYSTRING) + +// DISPLAYTEXT is an `ASN1_ITEM` whose ASN.1 type is X.509 DisplayText (RFC +// 5280) and C type is `ASN1_STRING*`. +DECLARE_ASN1_ITEM(DISPLAYTEXT) + +BSSL_NAMESPACE_END + +#endif // OPENSSL_HEADER_CRYPTO_ASN1_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/asn1/posix_time.cc b/Sources/CNIOBoringSSL/crypto/asn1/posix_time.cc index e4401365..dc5ecc91 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/posix_time.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/posix_time.cc @@ -1,16 +1,16 @@ -/* Copyright 2022 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2022 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. // Time conversion to/from POSIX time_t and struct tm, with no support // for time zones other than UTC @@ -29,6 +29,8 @@ #define SECS_PER_DAY (INT64_C(24) * SECS_PER_HOUR) +using namespace bssl; + // Is a year/month/day combination valid, in the range from year 0000 // to 9999? static int is_valid_date(int64_t year, int64_t month, int64_t day) { @@ -183,18 +185,19 @@ int OPENSSL_timegm(const struct tm *tm, time_t *out) { return 1; } -struct tm *OPENSSL_gmtime(const time_t *time, struct tm *out_tm) { +struct tm *bssl::OPENSSL_gmtime(const time_t *time, struct tm *out_tm) { static_assert( sizeof(time_t) == sizeof(int32_t) || sizeof(time_t) == sizeof(int64_t), "time_t is broken"); int64_t posix_time = *time; if (!OPENSSL_posix_to_tm(posix_time, out_tm)) { - return NULL; + return nullptr; } return out_tm; } -int OPENSSL_gmtime_adj(struct tm *tm, int offset_day, int64_t offset_sec) { +int bssl::OPENSSL_gmtime_adj(struct tm *tm, int offset_day, + int64_t offset_sec) { int64_t posix_time; if (!OPENSSL_tm_to_posix(tm, &posix_time)) { return 0; @@ -221,8 +224,8 @@ int OPENSSL_gmtime_adj(struct tm *tm, int offset_day, int64_t offset_sec) { return 1; } -int OPENSSL_gmtime_diff(int *out_days, int *out_secs, const struct tm *from, - const struct tm *to) { +int bssl::OPENSSL_gmtime_diff(int *out_days, int *out_secs, + const struct tm *from, const struct tm *to) { int64_t time_to, time_from; if (!OPENSSL_tm_to_posix(to, &time_to) || !OPENSSL_tm_to_posix(from, &time_from)) { diff --git a/Sources/CNIOBoringSSL/crypto/asn1/tasn_dec.cc b/Sources/CNIOBoringSSL/crypto/asn1/tasn_dec.cc index 9ccec2d5..7c73bd34 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/tasn_dec.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/tasn_dec.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -18,910 +23,589 @@ #include #include -#include "../bytestring/internal.h" +#include + #include "../internal.h" #include "internal.h" -// Constructed types with a recursive definition (such as can be found in PKCS7) -// could eventually exceed the stack given malicious input with excessive -// recursion. Therefore we limit the stack depth. This is the maximum number of -// recursive invocations of asn1_item_embed_d2i(). + +using namespace bssl; + +// Constructed types with a recursive definition could eventually exceed the +// stack given malicious input with excessive recursion. We don't currently +// support such types (our PKCS#7 parser does not use this framework and does +// not implement the full recursive PKCS#7), but limit recursion nonetheless. #define ASN1_MAX_CONSTRUCTED_NEST 30 -static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass, - char *cst, const unsigned char **in, long len, - int exptag, int expclass, char opt); +// The following functions parse a structure of type `it` (or `tt`) from `cbs` +// and write the result to `*pval`. They return one on success and zero on +// error. +// +// If `opt` is true, the field is optional. If an optional element is missing, +// the function returns one and consumes zero bytes from `cbs`. +// +// If `tag` is non-zero, the type is implicitly-tagged with the specified tag. +// `tag` should not have the constructed bit set. If the ASN.1 type is +// constructed, it will be set as appropriate. +// +// On entry, `*pval` may either be null or a default-initialized object, +// according to tasn_new.cc. It, however, may not be an arbitrary object. +// Historically, this code supported arbitrary objects, though not very well, so +// some remnants of more general handling remain. +// +// With the exception of `asn1_parse_item`, there may be a partial object left +// in `*pval` on error. `asn1_parse_item` is the main entrypoint and is +// responsible for recursively freeing objects on error. +static int asn1_parse_item(ASN1_VALUE **pval, CBS *cbs, const ASN1_ITEM *it, + CBS_ASN1_TAG tag, bool opt, int depth); +static int asn1_parse_template(ASN1_VALUE **pval, CBS *cbs, + const ASN1_TEMPLATE *tt, CBS_ASN1_TAG tag, + bool opt, int depth); -static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, - long len, const ASN1_TEMPLATE *tt, char opt, - CRYPTO_BUFFER *buf, int depth); -static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, - long len, const ASN1_TEMPLATE *tt, char opt, - CRYPTO_BUFFER *buf, int depth); -static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, long len, - int utype, const ASN1_ITEM *it); -static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in, - long len, const ASN1_ITEM *it, int tag, - int aclass, char opt); -static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, - long len, const ASN1_ITEM *it, int tag, int aclass, - char opt, CRYPTO_BUFFER *buf, int depth); +// asn1_parse_template_no_explicit behaves like `asn1_parse_template` but +// ignores any explicit tag specified in `tt`. +static int asn1_parse_template_no_explicit(ASN1_VALUE **pval, CBS *cbs, + const ASN1_TEMPLATE *tt, + CBS_ASN1_TAG tag, bool opt, + int depth); -// Table to convert tags to bit values, used for MSTRING type -static const unsigned long tag2bit[31] = { - 0, // (reserved) - 0, // BOOLEAN - 0, // INTEGER - B_ASN1_BIT_STRING, - B_ASN1_OCTET_STRING, - 0, // NULL - 0, // OBJECT IDENTIFIER - B_ASN1_UNKNOWN, // ObjectDescriptor - B_ASN1_UNKNOWN, // EXTERNAL - B_ASN1_UNKNOWN, // REAL - B_ASN1_UNKNOWN, // ENUMERATED - B_ASN1_UNKNOWN, // EMBEDDED PDV - B_ASN1_UTF8STRING, - B_ASN1_UNKNOWN, // RELATIVE-OID - B_ASN1_UNKNOWN, // TIME - B_ASN1_UNKNOWN, // (reserved) - B_ASN1_SEQUENCE, - 0, // SET - B_ASN1_NUMERICSTRING, - B_ASN1_PRINTABLESTRING, - B_ASN1_T61STRING, - B_ASN1_VIDEOTEXSTRING, - B_ASN1_IA5STRING, - B_ASN1_UTCTIME, - B_ASN1_GENERALIZEDTIME, - B_ASN1_GRAPHICSTRING, - B_ASN1_ISO64STRING, - B_ASN1_GENERALSTRING, - B_ASN1_UNIVERSALSTRING, - B_ASN1_UNKNOWN, // CHARACTER STRING - B_ASN1_BMPSTRING, -}; +// asn1_parse_item_primitive behaves like `asn1_parse_item` but only supports +// primitive types. +static int asn1_parse_item_primitive(ASN1_VALUE **pval, CBS *cbs, + const ASN1_ITEM *it, CBS_ASN1_TAG tag, + bool opt, int depth); unsigned long ASN1_tag2bit(int tag) { - if (tag < 0 || tag > 30) { - return 0; + switch (tag) { + case V_ASN1_BIT_STRING: + return B_ASN1_BIT_STRING; + case V_ASN1_OCTET_STRING: + return B_ASN1_OCTET_STRING; + case V_ASN1_UTF8STRING: + return B_ASN1_UTF8STRING; + case V_ASN1_SEQUENCE: + return B_ASN1_SEQUENCE; + case V_ASN1_NUMERICSTRING: + return B_ASN1_NUMERICSTRING; + case V_ASN1_PRINTABLESTRING: + return B_ASN1_PRINTABLESTRING; + case V_ASN1_T61STRING: + return B_ASN1_T61STRING; + case V_ASN1_VIDEOTEXSTRING: + return B_ASN1_VIDEOTEXSTRING; + case V_ASN1_IA5STRING: + return B_ASN1_IA5STRING; + case V_ASN1_UTCTIME: + return B_ASN1_UTCTIME; + case V_ASN1_GENERALIZEDTIME: + return B_ASN1_GENERALIZEDTIME; + case V_ASN1_GRAPHICSTRING: + return B_ASN1_GRAPHICSTRING; + case V_ASN1_ISO64STRING: + return B_ASN1_ISO64STRING; + case V_ASN1_GENERALSTRING: + return B_ASN1_GENERALSTRING; + case V_ASN1_UNIVERSALSTRING: + return B_ASN1_UNIVERSALSTRING; + case V_ASN1_BMPSTRING: + return B_ASN1_BMPSTRING; + default: + return 0; } - return tag2bit[tag]; } -static int is_supported_universal_type(int tag, int aclass) { - if (aclass != V_ASN1_UNIVERSAL) { - return 0; - } - return tag == V_ASN1_OBJECT || tag == V_ASN1_NULL || tag == V_ASN1_BOOLEAN || - tag == V_ASN1_BIT_STRING || tag == V_ASN1_INTEGER || - tag == V_ASN1_ENUMERATED || tag == V_ASN1_OCTET_STRING || - tag == V_ASN1_NUMERICSTRING || tag == V_ASN1_PRINTABLESTRING || - tag == V_ASN1_T61STRING || tag == V_ASN1_VIDEOTEXSTRING || - tag == V_ASN1_IA5STRING || tag == V_ASN1_UTCTIME || - tag == V_ASN1_GENERALIZEDTIME || tag == V_ASN1_GRAPHICSTRING || - tag == V_ASN1_VISIBLESTRING || tag == V_ASN1_GENERALSTRING || - tag == V_ASN1_UNIVERSALSTRING || tag == V_ASN1_BMPSTRING || - tag == V_ASN1_UTF8STRING || tag == V_ASN1_SET || - tag == V_ASN1_SEQUENCE; -} - -// Macro to initialize and invalidate the cache - -// Decode an ASN1 item, this currently behaves just like a standard 'd2i' -// function. 'in' points to a buffer to read the data from, in future we -// will have more advanced versions that can input data a piece at a time and -// this will simply be a special case. - -ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, +ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **pval, const uint8_t **in, long len, const ASN1_ITEM *it) { - ASN1_VALUE *ret = NULL; - if (asn1_item_ex_d2i(&ret, in, len, it, /*tag=*/-1, /*aclass=*/0, /*opt=*/0, - /*buf=*/NULL, /*depth=*/0) <= 0) { - // Clean up, in case the caller left a partial object. - // - // TODO(davidben): I don't think it can leave one, but the codepaths below - // are a bit inconsistent. Revisit this when rewriting this function. - ASN1_item_ex_free(&ret, it); + if (len < 0) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_BUFFER_TOO_SMALL); + return nullptr; + } + + // Bound `len` to comfortably fit in an `int`. Historically, this parser + // routinely mismatched integer types and did not correctly handle overflow. + // This is now largely fixed, but continue to cap the length to be safe. + len = std::min(len, long{INT_MAX / 2}); + + CBS cbs; + CBS_init(&cbs, *in, len); + ASN1_VALUE *ret = nullptr; + if (!asn1_parse_item(&ret, &cbs, it, /*tag=*/0, /*opt=*/false, /*depth=*/0)) { + return nullptr; } // If the caller supplied an output pointer, free the old one and replace it - // with |ret|. This differs from OpenSSL slightly in that we don't support + // with `ret`. This differs from OpenSSL slightly in that we don't support // object reuse. We run this on both success and failure. On failure, even // with object reuse, OpenSSL destroys the previous object. - if (pval != NULL) { + if (pval != nullptr) { ASN1_item_ex_free(pval, it); - *pval = ret; + asn1_store_ptr(pval, ret); } + *in = CBS_data(&cbs); return ret; } -// Decode an item, taking care of IMPLICIT tagging, if any. If 'opt' set and -// tag mismatch return -1 to handle OPTIONAL -// -// TODO(davidben): Historically, all functions in this file had to account for -// |*pval| containing an arbitrary existing value. This is no longer the case -// because |ASN1_item_d2i| now always starts from NULL. As part of rewriting -// this function, take the simplified assumptions into account. Though we must -// still account for the internal calls to |ASN1_item_ex_new|. - -static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, - long len, const ASN1_ITEM *it, int tag, int aclass, - char opt, CRYPTO_BUFFER *buf, int depth) { - const ASN1_TEMPLATE *tt, *errtt = NULL; - const unsigned char *p = NULL, *q; - unsigned char oclass; - char cst, isopt; - int i; - int otag; - int ret = 0; - ASN1_VALUE **pchptr; - if (!pval) { - return 0; +template +static T *ensure_value(ASN1_VALUE **pval) { + T *obj = asn1_load_ptr_as(pval); + if (obj != nullptr) { + return obj; } - - if (buf != NULL) { - assert(CRYPTO_BUFFER_data(buf) <= *in && - *in + len <= CRYPTO_BUFFER_data(buf) + CRYPTO_BUFFER_len(buf)); - } - - // Bound |len| to comfortably fit in an int. Lengths in this module often - // switch between int and long without overflow checks. - if (len > INT_MAX / 2) { - len = INT_MAX / 2; + obj = new_func(); + if (obj == nullptr) { + return nullptr; } + asn1_store_ptr(pval, obj); + return obj; +} +static int asn1_parse_item_no_error_cleanup(ASN1_VALUE **pval, CBS *cbs, + const ASN1_ITEM *it, + CBS_ASN1_TAG tag, bool opt, + int depth, + const ASN1_TEMPLATE **errtt) { if (++depth > ASN1_MAX_CONSTRUCTED_NEST) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_TOO_DEEP); - goto err; + return 0; } switch (it->itype) { case ASN1_ITYPE_PRIMITIVE: if (it->templates) { - // tagging or OPTIONAL is currently illegal on an item template - // because the flags can't get passed down. In practice this - // isn't a problem: we include the relevant flags from the item - // template in the template itself. - if ((tag != -1) || opt) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE); - goto err; + // This is an `ASN1_ITEM_TEMPLATE`, so the underlying template cannot be + // optional. Optionality should be expressed at the layer above. + if (it->templates->flags & ASN1_TFLG_OPTIONAL) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); + return 0; } - return asn1_template_ex_d2i(pval, in, len, it->templates, opt, buf, - depth); + return asn1_parse_template(pval, cbs, it->templates, tag, opt, depth); } - return asn1_d2i_ex_primitive(pval, in, len, it, tag, aclass, opt); - break; + return asn1_parse_item_primitive(pval, cbs, it, tag, opt, depth); - case ASN1_ITYPE_MSTRING: - // It never makes sense for multi-strings to have implicit tagging, so - // if tag != -1, then this looks like an error in the template. - if (tag != -1) { + case ASN1_ITYPE_MSTRING: { + // Multi-strings are CHOICE types and cannot be implicitly tagged. + if (tag != 0) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); - goto err; + return 0; } - p = *in; - // Just read in tag and class - ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, &p, len, -1, 0, 1); - if (!ret) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); - goto err; - } - - // Must be UNIVERSAL class - if (oclass != V_ASN1_UNIVERSAL) { - // If OPTIONAL, assume this is OK + tag = CBS_peek_any_asn1_tag(cbs); + if ((tag & CBS_ASN1_CLASS_MASK) != CBS_ASN1_UNIVERSAL || + (tag & CBS_ASN1_CONSTRUCTED) || + (ASN1_tag2bit(tag & CBS_ASN1_TAG_NUMBER_MASK) & it->utype) == 0) { if (opt) { - return -1; - } - OPENSSL_PUT_ERROR(ASN1, ASN1_R_MSTRING_NOT_UNIVERSAL); - goto err; - } - // Check tag matches bit map - if (!(ASN1_tag2bit(otag) & it->utype)) { - // If OPTIONAL, assume this is OK - if (opt) { - return -1; + ASN1_item_ex_free(pval, it); + return 1; // Omitted optional field. } OPENSSL_PUT_ERROR(ASN1, ASN1_R_MSTRING_WRONG_TAG); - goto err; + return 0; } - return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0); + ASN1_STRING *out = ensure_value(pval); + return out != nullptr && asn1_parse_any_as_string(cbs, out); + } case ASN1_ITYPE_EXTERN: { // We don't support implicit tagging with external types. - if (tag != -1) { + if (tag != 0) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); - goto err; + return 0; } - const ASN1_EXTERN_FUNCS *ef = - reinterpret_cast(it->funcs); - return ef->asn1_ex_d2i(pval, in, len, it, opt, NULL); + auto *ef = reinterpret_cast(it->funcs); + return ef->asn1_ex_parse(pval, cbs, it, opt); } case ASN1_ITYPE_CHOICE: { - // It never makes sense for CHOICE types to have implicit tagging, so if - // tag != -1, then this looks like an error in the template. - if (tag != -1) { + // CHOICE types cannot be implicitly tagged. + if (tag != 0) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); - goto err; + return 0; } const ASN1_AUX *aux = reinterpret_cast(it->funcs); - ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL; - if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) { - goto auxerr; + ASN1_aux_cb *asn1_cb = aux != nullptr ? aux->asn1_cb : nullptr; + if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, nullptr)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_AUX_ERROR); + return 0; } - if (*pval) { - // Free up and zero CHOICE value if initialised - i = asn1_get_choice_selector(pval, it); - if ((i >= 0) && (i < it->tcount)) { - tt = it->templates + i; - pchptr = asn1_get_field_ptr(pval, tt); + if (asn1_load_ptr(pval)) { + // Free up and zero the CHOICE value if initialised. + int idx = asn1_get_choice_selector(pval, it); + if (idx >= 0 && idx < it->tcount) { + const ASN1_TEMPLATE *tt = &it->templates[idx]; + ASN1_VALUE **pchptr = asn1_get_field_ptr(pval, tt); ASN1_template_free(pchptr, tt); asn1_set_choice_selector(pval, -1, it); } } else if (!ASN1_item_ex_new(pval, it)) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); - goto err; - } - // CHOICE type, try each possibility in turn - p = *in; - for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { - pchptr = asn1_get_field_ptr(pval, tt); - // We mark field as OPTIONAL so its absence can be recognised. - ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, buf, depth); - // If field not present, try the next one - if (ret == -1) { - continue; - } - // If positive return, read OK, break loop - if (ret > 0) { - break; - } - // Otherwise must be an ASN1 parsing error - errtt = tt; - OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); - goto err; + return 0; } - // Did we fall off the end without reading anything? - if (i == it->tcount) { - // If OPTIONAL, this is OK + // Parse each possibility as an optional field and find the first one. + size_t orig_len = CBS_len(cbs); + int idx = 0; + for (idx = 0; idx < it->tcount; idx++) { + const ASN1_TEMPLATE *tt = &it->templates[idx]; + ASN1_VALUE **pchptr = asn1_get_field_ptr(pval, tt); + if (!asn1_parse_template(pchptr, cbs, tt, /*tag=*/0, /*opt=*/true, + depth)) { + // Free any partial object left in `pchptr`. `asn1_item_parse` will + // clean up `pval`, but that will not clean up `pchptr` because the + // choice selector has not yet been set below. + ASN1_template_free(pchptr, tt); + *errtt = tt; + OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); + return 0; + } + if (CBS_len(cbs) != orig_len) { + break; // Found a match. + } + } + if (idx == it->tcount) { + // Nothing matched. If the CHOICE is OPTIONAL, this is OK. if (opt) { - // Free and zero it ASN1_item_ex_free(pval, it); - return -1; + return 1; } OPENSSL_PUT_ERROR(ASN1, ASN1_R_NO_MATCHING_CHOICE_TYPE); - goto err; + return 0; } - - asn1_set_choice_selector(pval, i, it); - if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) { - goto auxerr; + asn1_set_choice_selector(pval, idx, it); + if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, nullptr)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_AUX_ERROR); + return 0; } - *in = p; return 1; } case ASN1_ITYPE_SEQUENCE: { - p = *in; - - // If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL - if (tag == -1) { - tag = V_ASN1_SEQUENCE; - aclass = V_ASN1_UNIVERSAL; - } - // Get SEQUENCE length and update len, p - ret = asn1_check_tlen(&len, NULL, NULL, &cst, &p, len, tag, aclass, opt); - if (!ret) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); - goto err; - } else if (ret == -1) { - return -1; - } - if (!cst) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_SEQUENCE_NOT_CONSTRUCTED); - goto err; + tag = tag == 0 ? CBS_ASN1_SEQUENCE : (tag | CBS_ASN1_CONSTRUCTED); + if (opt && !CBS_peek_asn1_tag(cbs, tag)) { + ASN1_item_ex_free(pval, it); + return 1; } - if (!*pval && !ASN1_item_ex_new(pval, it)) { + CBS copy = *cbs, seq; + if (!CBS_get_asn1(cbs, &seq, tag)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; + } + + if (!asn1_load_ptr(pval) && !ASN1_item_ex_new(pval, it)) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); - goto err; + return 0; } const ASN1_AUX *aux = reinterpret_cast(it->funcs); - ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL; - if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) { - goto auxerr; + ASN1_aux_cb *asn1_cb = aux != nullptr ? aux->asn1_cb : nullptr; + if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, nullptr)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_AUX_ERROR); + return 0; } - // Free up and zero any ADB found - for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { + // Free up and zero any ADB found. + for (int i = 0; i < it->tcount; i++) { + const ASN1_TEMPLATE *tt = &it->templates[i]; if (tt->flags & ASN1_TFLG_ADB_MASK) { - const ASN1_TEMPLATE *seqtt; - ASN1_VALUE **pseqval; - seqtt = asn1_do_adb(pval, tt, 0); - if (seqtt == NULL) { + const ASN1_TEMPLATE *seqtt = asn1_do_adb(pval, tt, 0); + if (seqtt == nullptr) { continue; } - pseqval = asn1_get_field_ptr(pval, seqtt); + ASN1_VALUE **pseqval = asn1_get_field_ptr(pval, seqtt); ASN1_template_free(pseqval, seqtt); } } - // Get each field entry - for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { - const ASN1_TEMPLATE *seqtt; - ASN1_VALUE **pseqval; - seqtt = asn1_do_adb(pval, tt, 1); - if (seqtt == NULL) { - goto err; + // Get each field entry. + for (int i = 0; i < it->tcount; i++) { + const ASN1_TEMPLATE *tt = &it->templates[i]; + const ASN1_TEMPLATE *seqtt = asn1_do_adb(pval, tt, /*nullerr=*/1); + if (seqtt == nullptr) { + return 0; } - pseqval = asn1_get_field_ptr(pval, seqtt); - // Have we ran out of data? - if (!len) { - break; + ASN1_VALUE **pseqval = asn1_get_field_ptr(pval, seqtt); + const bool field_opt = (tt->flags & ASN1_TFLG_OPTIONAL) != 0; + if (!asn1_parse_template(pseqval, &seq, seqtt, /*tag=*/0, field_opt, + depth)) { + *errtt = tt; + return 0; } - q = p; - // This determines the OPTIONAL flag value. The field cannot be - // omitted if it is the last of a SEQUENCE and there is still - // data to be read. This isn't strictly necessary but it - // increases efficiency in some cases. - if (i == (it->tcount - 1)) { - isopt = 0; - } else { - isopt = (seqtt->flags & ASN1_TFLG_OPTIONAL) != 0; - } - // attempt to read in field, allowing each to be OPTIONAL - - ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, buf, depth); - if (!ret) { - errtt = seqtt; - goto err; - } else if (ret == -1) { - // OPTIONAL component absent. Free and zero the field. - ASN1_template_free(pseqval, seqtt); - continue; - } - // Update length - len -= p - q; } - - // Check all data read - if (len) { + if (CBS_len(&seq) != 0) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_SEQUENCE_LENGTH_MISMATCH); - goto err; + return 0; } - - // If we get here we've got no more data in the SEQUENCE, however we - // may not have read all fields so check all remaining are OPTIONAL - // and clear any that are. - for (; i < it->tcount; tt++, i++) { - const ASN1_TEMPLATE *seqtt; - seqtt = asn1_do_adb(pval, tt, 1); - if (seqtt == NULL) { - goto err; - } - if (seqtt->flags & ASN1_TFLG_OPTIONAL) { - ASN1_VALUE **pseqval; - pseqval = asn1_get_field_ptr(pval, seqtt); - ASN1_template_free(pseqval, seqtt); - } else { - errtt = seqtt; - OPENSSL_PUT_ERROR(ASN1, ASN1_R_FIELD_MISSING); - goto err; - } + // Save a copy of the bytes consumed. + if (!asn1_enc_save(pval, CBS_data(©), CBS_len(©) - CBS_len(cbs), + it)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_AUX_ERROR); + return 0; } - // Save encoding - if (!asn1_enc_save(pval, *in, p - *in, it, buf)) { - goto auxerr; + if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, nullptr)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_AUX_ERROR); + return 0; } - if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) { - goto auxerr; - } - *in = p; return 1; } default: + OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); return 0; } -auxerr: - OPENSSL_PUT_ERROR(ASN1, ASN1_R_AUX_ERROR); -err: - ASN1_item_ex_free(pval, it); - if (errtt) { - ERR_add_error_data(4, "Field=", errtt->field_name, ", Type=", it->sname); - } else { - ERR_add_error_data(2, "Type=", it->sname); - } - return 0; } -int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, - const ASN1_ITEM *it, int tag, int aclass, char opt, - CRYPTO_BUFFER *buf) { - return asn1_item_ex_d2i(pval, in, len, it, tag, aclass, opt, buf, - /*depth=*/0); -} - -// Templates are handled with two separate functions. One handles any -// EXPLICIT tag and the other handles the rest. - -static int asn1_template_ex_d2i(ASN1_VALUE **val, const unsigned char **in, - long inlen, const ASN1_TEMPLATE *tt, char opt, - CRYPTO_BUFFER *buf, int depth) { - int aclass; - int ret; - long len; - const unsigned char *p, *q; - if (!val) { +static int asn1_parse_item(ASN1_VALUE **pval, CBS *cbs, const ASN1_ITEM *it, + CBS_ASN1_TAG tag, bool opt, int depth) { + const ASN1_TEMPLATE *errtt = nullptr; + if (!asn1_parse_item_no_error_cleanup(pval, cbs, it, tag, opt, depth, + &errtt)) { + ASN1_item_ex_free(pval, it); + if (errtt != nullptr) { + ERR_add_error_data(4, "Field=", errtt->field_name, ", Type=", it->sname); + } else { + ERR_add_error_data(2, "Type=", it->sname); + } return 0; } - uint32_t flags = tt->flags; - aclass = flags & ASN1_TFLG_TAG_CLASS; - - p = *in; - - // Check if EXPLICIT tag expected - if (flags & ASN1_TFLG_EXPTAG) { - char cst; - // Need to work out amount of data available to the inner content and - // where it starts: so read in EXPLICIT header to get the info. - ret = asn1_check_tlen(&len, NULL, NULL, &cst, &p, inlen, tt->tag, aclass, - opt); - q = p; - if (!ret) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); - return 0; - } else if (ret == -1) { - return -1; - } - if (!cst) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED); - return 0; - } - // We've found the field so it can't be OPTIONAL now - ret = asn1_template_noexp_d2i(val, &p, len, tt, /*opt=*/0, buf, depth); - if (!ret) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); - return 0; - } - // We read the field in OK so update length - len -= p - q; - // Check for trailing data. - if (len) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_EXPLICIT_LENGTH_MISMATCH); - goto err; - } - } else { - return asn1_template_noexp_d2i(val, in, inlen, tt, opt, buf, depth); - } - - *in = p; return 1; - -err: - ASN1_template_free(val, tt); - return 0; } -static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, - long len, const ASN1_TEMPLATE *tt, char opt, - CRYPTO_BUFFER *buf, int depth) { - int aclass; - int ret; - const unsigned char *p; - if (!val) { +// Templates are handled with two separate functions. One handles any EXPLICIT +// tag and the other handles the rest. + +static int asn1_parse_template(ASN1_VALUE **pval, CBS *cbs, + const ASN1_TEMPLATE *tt, CBS_ASN1_TAG tag, + bool opt, int depth) { + uint32_t flags = tt->flags; + if ((flags & ASN1_TFLG_EXPTAG) == 0) { + return asn1_parse_template_no_explicit(pval, cbs, tt, tag, opt, depth); + } + + // Determine the tag. + if (tag == 0) { + tag = asn1_tag_to_cbs(flags & ASN1_TFLG_TAG_CLASS, tt->tag); + if (tag == 0) { + return 0; + } + } + tag |= CBS_ASN1_CONSTRUCTED; + + if (opt && !CBS_peek_asn1_tag(cbs, tag)) { + ASN1_template_free(pval, tt); + return 1; + } + + CBS child; + if (!CBS_get_asn1(cbs, &child, tag)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); return 0; } - uint32_t flags = tt->flags; - aclass = flags & ASN1_TFLG_TAG_CLASS; + if (!asn1_parse_template_no_explicit(pval, &child, tt, /*tag=*/0, + /*opt=*/false, depth)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); + return 0; + } + if (CBS_len(&child) != 0) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_EXPLICIT_LENGTH_MISMATCH); + return 0; + } + return 1; +} - p = *in; +static int asn1_parse_template_no_explicit(ASN1_VALUE **pval, CBS *cbs, + const ASN1_TEMPLATE *tt, + CBS_ASN1_TAG tag, bool opt, + int depth) { + // If `tt` provides implicit tagging and the caller did not already override + // the tag, pick up the tag from the template. + uint32_t flags = tt->flags; + if ((flags & ASN1_TFLG_IMPTAG) && tag == 0) { + tag = asn1_tag_to_cbs(flags & ASN1_TFLG_TAG_CLASS, tt->tag); + if (tag == 0) { + return 0; + } + } if (flags & ASN1_TFLG_SK_MASK) { - // SET OF, SEQUENCE OF - int sktag, skaclass; - // First work out expected inner tag value - if (flags & ASN1_TFLG_IMPTAG) { - sktag = tt->tag; - skaclass = aclass; - } else { - skaclass = V_ASN1_UNIVERSAL; - if (flags & ASN1_TFLG_SET_OF) { - sktag = V_ASN1_SET; - } else { - sktag = V_ASN1_SEQUENCE; - } + if (tag == 0) { + tag = (flags & ASN1_TFLG_SET_OF) ? CBS_ASN1_SET : CBS_ASN1_SEQUENCE; } - // Get the tag - ret = - asn1_check_tlen(&len, NULL, NULL, NULL, &p, len, sktag, skaclass, opt); - if (!ret) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); + tag |= CBS_ASN1_CONSTRUCTED; + + if (opt && !CBS_peek_asn1_tag(cbs, tag)) { + ASN1_template_free(pval, tt); + return 1; + } + CBS seq; + if (!CBS_get_asn1(cbs, &seq, tag)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); return 0; - } else if (ret == -1) { - return -1; - } - if (!*val) { - *val = (ASN1_VALUE *)sk_ASN1_VALUE_new_null(); - } else { - // We've got a valid STACK: free up any items present - STACK_OF(ASN1_VALUE) *sktmp = (STACK_OF(ASN1_VALUE) *)*val; - ASN1_VALUE *vtmp; - while (sk_ASN1_VALUE_num(sktmp) > 0) { - vtmp = sk_ASN1_VALUE_pop(sktmp); - ASN1_item_ex_free(&vtmp, ASN1_ITEM_ptr(tt->item)); - } } - if (!*val) { - goto err; + STACK_OF(ASN1_VALUE) *sk = + ensure_value(pval); + if (sk == nullptr) { + return 0; } + assert(sk_ASN1_VALUE_num(sk) == 0); - // Read as many items as we can - while (len > 0) { - ASN1_VALUE *skfield; - const unsigned char *q = p; - skfield = NULL; - if (!asn1_item_ex_d2i(&skfield, &p, len, ASN1_ITEM_ptr(tt->item), - /*tag=*/-1, /*aclass=*/0, /*opt=*/0, buf, depth)) { + while (CBS_len(&seq) != 0) { + ASN1_VALUE *skfield = nullptr; + if (!asn1_parse_item(&skfield, &seq, ASN1_ITEM_ptr(tt->item), /*tag=*/0, + /*opt=*/false, depth)) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); - goto err; - } - len -= p - q; - if (!sk_ASN1_VALUE_push((STACK_OF(ASN1_VALUE) *)*val, skfield)) { ASN1_item_ex_free(&skfield, ASN1_ITEM_ptr(tt->item)); - goto err; + return 0; + } + if (!sk_ASN1_VALUE_push(sk, skfield)) { + ASN1_item_ex_free(&skfield, ASN1_ITEM_ptr(tt->item)); + return 0; } } - } else if (flags & ASN1_TFLG_IMPTAG) { - // IMPLICIT tagging - ret = asn1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), tt->tag, - aclass, opt, buf, depth); - if (!ret) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); - goto err; - } else if (ret == -1) { - return -1; - } - } else { - // Nothing special - ret = asn1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), /*tag=*/-1, - /*aclass=*/0, opt, buf, depth); - if (!ret) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); - goto err; - } else if (ret == -1) { - return -1; - } + return 1; } - *in = p; - return 1; - -err: - ASN1_template_free(val, tt); - return 0; + return asn1_parse_item(pval, cbs, ASN1_ITEM_ptr(tt->item), tag, opt, depth); } -static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in, - long inlen, const ASN1_ITEM *it, int tag, - int aclass, char opt) { - int ret = 0, utype; - long plen; - char cst; - const unsigned char *p; - const unsigned char *cont = NULL; - long len; - if (!pval) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_NULL); - return 0; // Should never happen - } - - if (it->itype == ASN1_ITYPE_MSTRING) { - utype = tag; - tag = -1; - } else { - utype = it->utype; - } +static int asn1_parse_item_primitive(ASN1_VALUE **pval, CBS *cbs, + const ASN1_ITEM *it, CBS_ASN1_TAG tag, + bool opt, int depth) { + assert(it->itype == ASN1_ITYPE_PRIMITIVE); + // `ASN1_ITEM_TEMPLATE` should have been handled by the caller. + assert(it->templates == nullptr); + // Historically, `it->funcs` for primitive types contained an + // `ASN1_PRIMITIVE_FUNCS` table of callbacks. + assert(it->funcs == nullptr); + int utype = it->utype; + // Handle ANY types. if (utype == V_ASN1_ANY) { - // If type is ANY need to figure out type from tag - unsigned char oclass; - if (tag >= 0) { + if (tag != 0) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_TAGGED_ANY); return 0; } - if (opt) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OPTIONAL_ANY); + if (opt && CBS_len(cbs) == 0) { + ASN1_item_ex_free(pval, it); + return 1; // Omitted OPTIONAL value. + } + ASN1_TYPE *typ = ensure_value(pval); + if (typ == nullptr) { return 0; } - p = *in; - ret = asn1_check_tlen(NULL, &utype, &oclass, NULL, &p, inlen, -1, 0, 0); - if (!ret) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); - return 0; - } - if (!is_supported_universal_type(utype, oclass)) { - utype = V_ASN1_OTHER; - } - } - if (tag == -1) { - tag = utype; - aclass = V_ASN1_UNIVERSAL; - } - p = *in; - // Check header - ret = asn1_check_tlen(&plen, NULL, NULL, &cst, &p, inlen, tag, aclass, opt); - if (!ret) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR); - return 0; - } else if (ret == -1) { - return -1; - } - ret = 0; - // SEQUENCE, SET and "OTHER" are left in encoded form - if ((utype == V_ASN1_SEQUENCE) || (utype == V_ASN1_SET) || - (utype == V_ASN1_OTHER)) { - // SEQUENCE and SET must be constructed - if (utype != V_ASN1_OTHER && !cst) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_CONSTRUCTED); - return 0; - } - - cont = *in; - len = p - cont + plen; - p += plen; - } else if (cst) { - // This parser historically supported BER constructed strings. We no - // longer do and will gradually tighten this parser into a DER - // parser. BER types should use |CBS_asn1_ber_to_der|. - OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_PRIMITIVE); - return 0; - } else { - cont = p; - len = plen; - p += plen; + return asn1_parse_any(cbs, typ); } - // We now have content length and type: translate into a structure - if (!asn1_ex_c2i(pval, cont, len, utype, it)) { - goto err; + // Determine the ASN.1 tag. `utype` must be a primitive `ASN1_ITEM`, handled + // by `DECLARE_ASN1_ITEM`. + assert(0 <= utype && utype <= int{CBS_ASN1_TAG_NUMBER_MASK}); + if (tag == 0) { + tag = static_cast(utype); + } + if (utype == V_ASN1_SEQUENCE || utype == V_ASN1_SET) { + tag |= CBS_ASN1_CONSTRUCTED; } - *in = p; - ret = 1; -err: - return ret; -} - -// Translate ASN1 content octets into a structure - -static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, long len, - int utype, const ASN1_ITEM *it) { - ASN1_VALUE **opval = NULL; - ASN1_STRING *stmp; - ASN1_TYPE *typ = NULL; - int ret = 0; - ASN1_INTEGER **tint; - - // Historically, |it->funcs| for primitive types contained an - // |ASN1_PRIMITIVE_FUNCS| table of callbacks. - assert(it->funcs == NULL); - - // If ANY type clear type and set pointer to internal value - if (it->utype == V_ASN1_ANY) { - if (!*pval) { - typ = ASN1_TYPE_new(); - if (typ == NULL) { - goto err; - } - *pval = (ASN1_VALUE *)typ; - } else { - typ = (ASN1_TYPE *)*pval; - } - - if (utype != typ->type) { - ASN1_TYPE_set(typ, utype, NULL); - } - opval = pval; - pval = &typ->value.asn1_value; + if (opt && !CBS_peek_asn1_tag(cbs, tag)) { + ASN1_item_ex_free(pval, it); + return 1; // Omitted OPTIONAL value. } + + // Handle non-`ASN1_STRING` types. switch (utype) { - case V_ASN1_OBJECT: - if (!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len)) { - goto err; + case V_ASN1_OBJECT: { + UniquePtr obj(asn1_parse_object(cbs, tag)); + if (obj == nullptr) { + return 0; } - break; - - case V_ASN1_NULL: - if (len) { + ASN1_OBJECT_free(asn1_load_ptr_as(pval)); + asn1_store_ptr(pval, obj.release()); + return 1; + } + case V_ASN1_NULL: { + CBS null; + if (!CBS_get_asn1(cbs, &null, tag)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; + } + if (CBS_len(&null) != 0) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_NULL_IS_WRONG_LENGTH); - goto err; + return 0; } - *pval = (ASN1_VALUE *)1; - break; - - case V_ASN1_BOOLEAN: - if (len != 1) { + asn1_store_ptr(pval, reinterpret_cast(1)); + return 1; + } + case V_ASN1_BOOLEAN: { + CBS child; + if (!CBS_get_asn1(cbs, &child, tag)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; + } + // TODO(crbug.com/42290221): Reject invalid BOOLEAN encodings and just + // call `CBS_get_asn1_bool`. + if (CBS_len(&child) != 1) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_BOOLEAN_IS_WRONG_LENGTH); - goto err; - } else { - ASN1_BOOLEAN *tbool; - tbool = (ASN1_BOOLEAN *)pval; - *tbool = *cont; + return 0; } - break; + *reinterpret_cast(pval) = + CBS_data(&child)[0] ? ASN1_BOOLEAN_TRUE : ASN1_BOOLEAN_FALSE; + return 1; + } + } + // All other types as an `ASN1_STRING` representation. + ASN1_STRING *str = ensure_value(pval); + if (str == nullptr) { + return 0; + } + + switch (utype) { case V_ASN1_BIT_STRING: - if (!c2i_ASN1_BIT_STRING((ASN1_BIT_STRING **)pval, &cont, len)) { - goto err; - } - break; - + return asn1_parse_bit_string(cbs, str, tag); case V_ASN1_INTEGER: + return asn1_parse_integer(cbs, str, tag); case V_ASN1_ENUMERATED: - tint = (ASN1_INTEGER **)pval; - if (!c2i_ASN1_INTEGER(tint, &cont, len)) { - goto err; - } - // Fixup type to match the expected form - (*tint)->type = utype | ((*tint)->type & V_ASN1_NEG); - break; - + return asn1_parse_enumerated(cbs, str, tag); + case V_ASN1_UNIVERSALSTRING: + return asn1_parse_universal_string(cbs, str, tag); + case V_ASN1_BMPSTRING: + return asn1_parse_bmp_string(cbs, str, tag); + 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); + case V_ASN1_GENERALIZEDTIME: + return asn1_parse_generalized_time(cbs, str, tag); case V_ASN1_OCTET_STRING: + return asn1_parse_octet_string(cbs, str, tag); + case V_ASN1_T61STRING: + return asn1_parse_t61_string(cbs, str, tag); case V_ASN1_NUMERICSTRING: case V_ASN1_PRINTABLESTRING: - case V_ASN1_T61STRING: case V_ASN1_VIDEOTEXSTRING: case V_ASN1_IA5STRING: - case V_ASN1_UTCTIME: - case V_ASN1_GENERALIZEDTIME: case V_ASN1_GRAPHICSTRING: case V_ASN1_VISIBLESTRING: case V_ASN1_GENERALSTRING: - case V_ASN1_UNIVERSALSTRING: - case V_ASN1_BMPSTRING: - case V_ASN1_UTF8STRING: - case V_ASN1_OTHER: - case V_ASN1_SET: - case V_ASN1_SEQUENCE: - // TODO(crbug.com/boringssl/412): This default case should be removed, now - // that we've resolved https://crbug.com/boringssl/561. However, it is still - // needed to support some edge cases in |ASN1_PRINTABLE|. |ASN1_PRINTABLE| - // broadly doesn't tolerate unrecognized universal tags, but except for - // eight values that map to |B_ASN1_UNKNOWN| instead of zero. See the - // X509Test.NameAttributeValues test. - default: { - CBS cbs; - CBS_init(&cbs, cont, (size_t)len); - if (utype == V_ASN1_BMPSTRING) { - while (CBS_len(&cbs) != 0) { - uint32_t c; - if (!CBS_get_ucs2_be(&cbs, &c)) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BMPSTRING); - goto err; - } - } + // TODO(crbug.com/42290290): Enforce the encoding of the other string + // types. + return asn1_parse_string_unchecked(cbs, str, utype, tag); + case V_ASN1_SEQUENCE: { + // Save the entire element in the string. + CBS elem; + if (!CBS_get_asn1_element(cbs, &elem, tag)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR); + return 0; } - if (utype == V_ASN1_UNIVERSALSTRING) { - while (CBS_len(&cbs) != 0) { - uint32_t c; - if (!CBS_get_utf32_be(&cbs, &c)) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_UNIVERSALSTRING); - goto err; - } - } - } - if (utype == V_ASN1_UTF8STRING) { - while (CBS_len(&cbs) != 0) { - uint32_t c; - if (!CBS_get_utf8(&cbs, &c)) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_UTF8STRING); - goto err; - } - } - } - if (utype == V_ASN1_UTCTIME) { - if (!CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/1)) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_TIME_FORMAT); - goto err; - } - } - if (utype == V_ASN1_GENERALIZEDTIME) { - if (!CBS_parse_generalized_time(&cbs, NULL, - /*allow_timezone_offset=*/0)) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_TIME_FORMAT); - goto err; - } - } - // TODO(https://crbug.com/boringssl/427): Check other string types. - - // All based on ASN1_STRING and handled the same - if (!*pval) { - stmp = ASN1_STRING_type_new(utype); - if (!stmp) { - goto err; - } - *pval = (ASN1_VALUE *)stmp; - } else { - stmp = (ASN1_STRING *)*pval; - stmp->type = utype; - } - if (!ASN1_STRING_set(stmp, cont, len)) { - ASN1_STRING_free(stmp); - *pval = NULL; - goto err; - } - break; + str->type = V_ASN1_SEQUENCE; + return ASN1_STRING_set(str, CBS_data(&elem), CBS_len(&elem)); } - } - // If ASN1_ANY and NULL type fix up value - if (typ && (utype == V_ASN1_NULL)) { - typ->value.ptr = NULL; - } - - ret = 1; -err: - if (!ret) { - ASN1_TYPE_free(typ); - if (opval) { - *opval = NULL; - } - } - return ret; -} - -// Check an ASN1 tag and length: a bit like ASN1_get_object but it -// checks the expected tag. - -static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass, - char *cst, const unsigned char **in, long len, - int exptag, int expclass, char opt) { - int i; - int ptag, pclass; - long plen; - const unsigned char *p; - p = *in; - - i = ASN1_get_object(&p, &plen, &ptag, &pclass, len); - if (i & 0x80) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_OBJECT_HEADER); - return 0; - } - if (exptag >= 0) { - if ((exptag != ptag) || (expclass != pclass)) { - // If type is OPTIONAL, not an error: indicate missing type. - if (opt) { - return -1; - } - OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TAG); + default: + OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); return 0; - } } - - if (cst) { - *cst = i & V_ASN1_CONSTRUCTED; - } - - if (olen) { - *olen = plen; - } - - if (oclass) { - *oclass = pclass; - } - - if (otag) { - *otag = ptag; - } - - *in = p; - return 1; } diff --git a/Sources/CNIOBoringSSL/crypto/asn1/tasn_enc.cc b/Sources/CNIOBoringSSL/crypto/asn1/tasn_enc.cc index dc8c0207..0dae44d1 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/tasn_enc.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/tasn_enc.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,616 +21,306 @@ #include #include +#include "../bytestring/internal.h" #include "../internal.h" #include "internal.h" -static int asn1_item_ex_i2d_opt(ASN1_VALUE **pval, unsigned char **out, - const ASN1_ITEM *it, int tag, int aclass, - int optional); -static int asn1_i2d_ex_primitive(ASN1_VALUE **pval, unsigned char **out, - const ASN1_ITEM *it, int tag, int aclass, - int optional); -static int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cont, int *out_omit, - int *putype, const ASN1_ITEM *it); -static int asn1_set_seq_out(STACK_OF(ASN1_VALUE) *sk, unsigned char **out, - int skcontlen, const ASN1_ITEM *item, int do_sort); -static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out, - const ASN1_TEMPLATE *tt, int tag, int aclass, - int optional); +using namespace bssl; -// Top level i2d equivalents +static int asn1_marshal_item(CBB *cbb, ASN1_VALUE **pval, const ASN1_ITEM *it, + CBS_ASN1_TAG tag); +static int asn1_marshal_template(CBB *cbb, ASN1_VALUE **pval, + const ASN1_TEMPLATE *tt, CBS_ASN1_TAG tag); +static int asn1_marshal_template_no_explicit(CBB *cbb, ASN1_VALUE **pval, + const ASN1_TEMPLATE *tt, + CBS_ASN1_TAG tag); +static int asn1_marshal_primitive(CBB *cbb, ASN1_VALUE **pval, + const ASN1_ITEM *it, CBS_ASN1_TAG tag); -int ASN1_item_i2d(ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it) { - if (out && !*out) { - unsigned char *p, *buf; - int len = ASN1_item_ex_i2d(&val, NULL, it, /*tag=*/-1, /*aclass=*/0); - if (len <= 0) { - return len; - } - buf = reinterpret_cast(OPENSSL_malloc(len)); - if (!buf) { - return -1; - } - p = buf; - int len2 = ASN1_item_ex_i2d(&val, &p, it, /*tag=*/-1, /*aclass=*/0); - if (len2 <= 0) { - OPENSSL_free(buf); - return len2; - } - assert(len == len2); - *out = buf; - return len; +static bool asn1_item_has_value(ASN1_VALUE **pval, const ASN1_ITEM *it); +static bool asn1_template_has_value(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt); + +int ASN1_item_i2d(ASN1_VALUE *val, uint8_t **out, const ASN1_ITEM *it) { + return I2DFromCBB(/*initial_capacity=*/64, out, [&](CBB *cbb) -> bool { + return asn1_marshal_item(cbb, &val, it, /*tag=*/0); + }); +} + +// asn1_item_has_value returns whether `pval`, which must have type `it`, +// contains a value. +bool asn1_item_has_value(ASN1_VALUE **pval, const ASN1_ITEM *it) { + // Almost every `ASN1_VALUE` is a pointer, except for types represented as + // `ASN1_BOOLEAN`. + if (it->itype != ASN1_ITYPE_PRIMITIVE) { + // All non-primitive types are pointers. + return asn1_load_ptr(pval) != nullptr; } - - return ASN1_item_ex_i2d(&val, out, it, /*tag=*/-1, /*aclass=*/0); + if (it->templates != nullptr) { + // This is an `ASN1_ITEM_TEMPLATE`. Recurse into the template. + return asn1_template_has_value(pval, it->templates); + } + if (it->utype != V_ASN1_BOOLEAN) { + return asn1_load_ptr(pval) != nullptr; + } + // `ASN1_BOOLEAN` may be omitted in two ways. -1 indicates an omitted + // OPTIONAL BOOLEAN. Additionally, if `it` is `ASN1_FBOOLEAN` or + // `ASN1_TBOOLEAN`, this is DEFAULT FALSE and DEFAULT TRUE, respectively. This + // is stored in `it->size`. + ASN1_BOOLEAN b = *reinterpret_cast(pval); + if (b == ASN1_BOOLEAN_NONE) { + return false; + } + if (it->size > 0) { + // This is DEFAULT TRUE, so only FALSE is present. + return b == ASN1_BOOLEAN_FALSE; + } + if (it->size == 0) { + // This is DEFAULT FALSE, so only TRUE is present. + return b != ASN1_BOOLEAN_FALSE; + } + return true; } -// Encode an item, taking care of IMPLICIT tagging (if any). This function -// performs the normal item handling: it can be used in external types. - -int ASN1_item_ex_i2d(ASN1_VALUE **pval, unsigned char **out, - const ASN1_ITEM *it, int tag, int aclass) { - int ret = asn1_item_ex_i2d_opt(pval, out, it, tag, aclass, /*optional=*/0); - assert(ret != 0); - return ret; +// asn1_template_has_value returns whether `pval`, which must have type `tt`, +// contains a value. +bool asn1_template_has_value(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) { + if (tt->flags & ASN1_TFLG_SK_MASK) { + // If `tt` is a SEQUENCE OF or SET OF type, the C type is `STACK_OF(T)` and + // is a pointer. + return asn1_load_ptr(pval) != nullptr; + } + // Otherwise, `tt`'s representation is the underlying item. + return asn1_item_has_value(pval, ASN1_ITEM_ptr(tt->item)); } -// asn1_item_ex_i2d_opt behaves like |ASN1_item_ex_i2d| but, if |optional| is -// non-zero and |*pval| is omitted, it returns zero and writes no bytes. -int asn1_item_ex_i2d_opt(ASN1_VALUE **pval, unsigned char **out, - const ASN1_ITEM *it, int tag, int aclass, - int optional) { - const ASN1_TEMPLATE *tt = NULL; - int i, seqcontlen, seqlen; - - // Historically, |aclass| was repurposed to pass additional flags into the - // encoding process. - assert((aclass & ASN1_TFLG_TAG_CLASS) == aclass); - // If not overridding the tag, |aclass| is ignored and should be zero. - assert(tag != -1 || aclass == 0); - - // All fields are pointers, except for boolean |ASN1_ITYPE_PRIMITIVE|s. - // Optional primitives are handled later. - if ((it->itype != ASN1_ITYPE_PRIMITIVE) && !*pval) { - if (optional) { - return 0; - } +// asn1_marshal_item marshals `pval`, of type `it`, and writes the result to +// `cbb`. It returns one on success and zero on error. If `tag` is non-zero, the +// value is implicitly tagged with `tag`. +static int asn1_marshal_item(CBB *cbb, ASN1_VALUE **pval, const ASN1_ITEM *it, + CBS_ASN1_TAG tag) { + // All fields are pointers, except for boolean `ASN1_ITYPE_PRIMITIVE`s. Those + // cases will be checked later. + if ((it->itype != ASN1_ITYPE_PRIMITIVE) && !asn1_load_ptr(pval)) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_VALUE); - return -1; + return 0; } switch (it->itype) { case ASN1_ITYPE_PRIMITIVE: if (it->templates) { - // This is an |ASN1_ITEM_TEMPLATE|. + // This is an `ASN1_ITEM_TEMPLATE`, so the underlying template cannot be + // optional. Optionality should be expressed at the layer above. if (it->templates->flags & ASN1_TFLG_OPTIONAL) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); - return -1; + return 0; } - return asn1_template_ex_i2d(pval, out, it->templates, tag, aclass, - optional); + return asn1_marshal_template(cbb, pval, it->templates, tag); } - return asn1_i2d_ex_primitive(pval, out, it, tag, aclass, optional); + return asn1_marshal_primitive(cbb, pval, it, tag); case ASN1_ITYPE_MSTRING: - // It never makes sense for multi-strings to have implicit tagging, so - // if tag != -1, then this looks like an error in the template. - if (tag != -1) { + // CHOICE types cannot be implicitly tagged. + if (tag != 0) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); - return -1; + return 0; } - return asn1_i2d_ex_primitive(pval, out, it, -1, 0, optional); + return asn1_marshal_any_string(cbb, asn1_load_ptr_as(pval)); case ASN1_ITYPE_CHOICE: { - // It never makes sense for CHOICE types to have implicit tagging, so if - // tag != -1, then this looks like an error in the template. - if (tag != -1) { + // CHOICE types cannot be implicitly tagged. + if (tag != 0) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); - return -1; + return 0; } - i = asn1_get_choice_selector(pval, it); + int i = asn1_get_choice_selector(pval, it); if (i < 0 || i >= it->tcount) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_NO_MATCHING_CHOICE_TYPE); - return -1; + return 0; } - const ASN1_TEMPLATE *chtt = it->templates + i; + const ASN1_TEMPLATE *chtt = &it->templates[i]; if (chtt->flags & ASN1_TFLG_OPTIONAL) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); - return -1; + return 0; } ASN1_VALUE **pchval = asn1_get_field_ptr(pval, chtt); - return asn1_template_ex_i2d(pchval, out, chtt, -1, 0, /*optional=*/0); + return asn1_marshal_template(cbb, pchval, chtt, /*tag=*/0); } case ASN1_ITYPE_EXTERN: { // We don't support implicit tagging with external types. - if (tag != -1) { + if (tag != 0) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); - return -1; + return 0; } - const ASN1_EXTERN_FUNCS *ef = - reinterpret_cast(it->funcs); - int ret = ef->asn1_ex_i2d(pval, out, it); - if (ret == 0) { - // |asn1_ex_i2d| should never return zero. We have already checked - // for optional values generically, and |ASN1_ITYPE_EXTERN| fields - // must be pointers. - OPENSSL_PUT_ERROR(ASN1, ERR_R_INTERNAL_ERROR); - return -1; - } - return ret; + auto *ef = static_cast(it->funcs); + return ef->asn1_ex_marshal(cbb, pval, it); } case ASN1_ITYPE_SEQUENCE: { - i = asn1_enc_restore(&seqcontlen, out, pval, it); - // An error occurred - if (i < 0) { - return -1; + Span enc; + if (asn1_enc_restore(&enc, pval, it)) { + return CBB_add_bytes(cbb, enc.data(), enc.size()); } - // We have a valid cached encoding... - if (i > 0) { - return seqcontlen; + tag = tag == 0 ? CBS_ASN1_SEQUENCE : (tag | CBS_ASN1_CONSTRUCTED); + CBB seq; + if (!CBB_add_asn1(cbb, &seq, tag)) { + return 0; } - // Otherwise carry on - seqcontlen = 0; - // If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL - if (tag == -1) { - tag = V_ASN1_SEQUENCE; - aclass = V_ASN1_UNIVERSAL; - } - // First work out sequence content length - for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) { - const ASN1_TEMPLATE *seqtt; - ASN1_VALUE **pseqval; - int tmplen; - seqtt = asn1_do_adb(pval, tt, 1); + for (int i = 0; i < it->tcount; i++) { + const ASN1_TEMPLATE *tt = &it->templates[i]; + const ASN1_TEMPLATE *seqtt = asn1_do_adb(pval, tt, /*nullerr=*/1); if (!seqtt) { - return -1; + return 0; } - pseqval = asn1_get_field_ptr(pval, seqtt); - tmplen = - asn1_template_ex_i2d(pseqval, NULL, seqtt, -1, 0, /*optional=*/0); - if (tmplen == -1 || (tmplen > INT_MAX - seqcontlen)) { - return -1; + ASN1_VALUE **pseqval = asn1_get_field_ptr(pval, seqtt); + if (!asn1_template_has_value(pseqval, seqtt)) { + if ((seqtt->flags & ASN1_TFLG_OPTIONAL) != 0) { + continue; + } + OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_VALUE); + return 0; } - seqcontlen += tmplen; - } - - seqlen = ASN1_object_size(/*constructed=*/1, seqcontlen, tag); - if (!out || seqlen == -1) { - return seqlen; - } - // Output SEQUENCE header - ASN1_put_object(out, /*constructed=*/1, seqcontlen, tag, aclass); - for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) { - const ASN1_TEMPLATE *seqtt; - ASN1_VALUE **pseqval; - seqtt = asn1_do_adb(pval, tt, 1); - if (!seqtt) { - return -1; - } - pseqval = asn1_get_field_ptr(pval, seqtt); - if (asn1_template_ex_i2d(pseqval, out, seqtt, -1, 0, /*optional=*/0) < - 0) { - return -1; + if (!asn1_marshal_template(&seq, pseqval, seqtt, /*tag=*/0)) { + return 0; } } - return seqlen; + return CBB_flush(cbb); } default: OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); - return -1; + return 0; } } -// asn1_template_ex_i2d behaves like |asn1_item_ex_i2d_opt| but uses an -// |ASN1_TEMPLATE| instead of an |ASN1_ITEM|. An |ASN1_TEMPLATE| wraps an -// |ASN1_ITEM| with modifiers such as tagging, SEQUENCE or SET, etc. -static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out, - const ASN1_TEMPLATE *tt, int tag, int iclass, - int optional) { - int i, ret, ttag, tclass; - size_t j; +// asn1_marshal_template marshals `pval`, of type `tt`, and writes the result to +// `cbb`. It returns one on success and zero on error. If `tag` is non-zero, the +// value is implicitly tagged with `tag`. +// +// This function does not look at `ASN1_TFLG_OPTIONAL`. The caller is expected +// to have evaluated it already and, if applicable, skip this function. +static int asn1_marshal_template(CBB *cbb, ASN1_VALUE **pval, + const ASN1_TEMPLATE *tt, CBS_ASN1_TAG tag) { + uint32_t flags = tt->flags; + if (!(flags & ASN1_TFLG_EXPTAG)) { + return asn1_marshal_template_no_explicit(cbb, pval, tt, tag); + } + + // Determine the explicit tag to use. If the caller supplied an implicit tag, + // it overrides this one. Otherwise, use the tag in the template. + if (tag == 0) { + tag = asn1_tag_to_cbs(flags & ASN1_TFLG_TAG_CLASS, tt->tag); + if (tag == 0) { + return 0; + } + } + + CBB child; + return CBB_add_asn1(cbb, &child, tag | CBS_ASN1_CONSTRUCTED) && + asn1_marshal_template_no_explicit(&child, pval, tt, /*tag=*/0) && + CBB_flush(cbb); +} + +// asn1_marshal_template_no_explicit behaves like `asn1_marshal_template` except +// it ignores any explicit tagging specified in `tt`. +static int asn1_marshal_template_no_explicit(CBB *cbb, ASN1_VALUE **pval, + const ASN1_TEMPLATE *tt, + CBS_ASN1_TAG tag) { uint32_t flags = tt->flags; - // Historically, |iclass| was repurposed to pass additional flags into the - // encoding process. - assert((iclass & ASN1_TFLG_TAG_CLASS) == iclass); - // If not overridding the tag, |iclass| is ignored and should be zero. - assert(tag != -1 || iclass == 0); - - // Work out tag and class to use: tagging may come either from the - // template or the arguments, not both because this would create - // ambiguity. - if (flags & ASN1_TFLG_TAG_MASK) { - // Error if argument and template tagging - if (tag != -1) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); - return -1; + // If `tt` provides implicit tagging and the caller did not already override + // the tag, pick up the tag from the template. + if ((flags & ASN1_TFLG_IMPTAG) && tag == 0) { + tag = asn1_tag_to_cbs(flags & ASN1_TFLG_TAG_CLASS, tt->tag); + if (tag == 0) { + return 0; } - // Get tagging from template - ttag = tt->tag; - tclass = flags & ASN1_TFLG_TAG_CLASS; - } else if (tag != -1) { - // No template tagging, get from arguments - ttag = tag; - tclass = iclass & ASN1_TFLG_TAG_CLASS; - } else { - ttag = -1; - tclass = 0; } - // The template may itself by marked as optional, or this may be the template - // of an |ASN1_ITEM_TEMPLATE| type which was contained inside an outer - // optional template. (They cannot both be true because the - // |ASN1_ITEM_TEMPLATE| codepath rejects optional templates.) - assert(!optional || (flags & ASN1_TFLG_OPTIONAL) == 0); - optional = optional || (flags & ASN1_TFLG_OPTIONAL) != 0; - - // At this point 'ttag' contains the outer tag to use, and 'tclass' is the - // class. - if (flags & ASN1_TFLG_SK_MASK) { - // SET OF, SEQUENCE OF - STACK_OF(ASN1_VALUE) *sk = (STACK_OF(ASN1_VALUE) *)*pval; - int isset, sktag, skaclass; - int skcontlen, sklen; - ASN1_VALUE *skitem; - - if (!*pval) { - if (optional) { - return 0; - } + // This is a SET OF or SEQUENCE OF type. + STACK_OF(ASN1_VALUE) *sk = asn1_load_ptr_as(pval); + if (sk == nullptr) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_VALUE); - return -1; + return 0; } - - if (flags & ASN1_TFLG_SET_OF) { - isset = 1; - // Historically, types with both bits set were mutated when - // serialized to apply the sort. We no longer support this. + bool is_set = (flags & ASN1_TFLG_SET_OF) != 0; + if (is_set) { + // Historically, types with both bits set were mutated when serialized to + // apply the sort. We no longer support this. assert((flags & ASN1_TFLG_SEQUENCE_OF) == 0); - } else { - isset = 0; } - - // Work out inner tag value: if EXPLICIT or no tagging use underlying - // type. - if ((ttag != -1) && !(flags & ASN1_TFLG_EXPTAG)) { - sktag = ttag; - skaclass = tclass; - } else { - skaclass = V_ASN1_UNIVERSAL; - if (isset) { - sktag = V_ASN1_SET; - } else { - sktag = V_ASN1_SEQUENCE; - } + if (tag == 0) { + tag = is_set ? CBS_ASN1_SET : CBS_ASN1_SEQUENCE; } - - // Determine total length of items - skcontlen = 0; - for (j = 0; j < sk_ASN1_VALUE_num(sk); j++) { - int tmplen; - skitem = sk_ASN1_VALUE_value(sk, j); - tmplen = ASN1_item_ex_i2d(&skitem, NULL, ASN1_ITEM_ptr(tt->item), -1, 0); - if (tmplen == -1 || (skcontlen > INT_MAX - tmplen)) { - return -1; - } - skcontlen += tmplen; + CBB child; + if (!CBB_add_asn1(cbb, &child, tag | CBS_ASN1_CONSTRUCTED)) { + return 0; } - sklen = ASN1_object_size(/*constructed=*/1, skcontlen, sktag); - if (sklen == -1) { - return -1; - } - // If EXPLICIT need length of surrounding tag - if (flags & ASN1_TFLG_EXPTAG) { - ret = ASN1_object_size(/*constructed=*/1, sklen, ttag); - } else { - ret = sklen; - } - - if (!out || ret == -1) { - return ret; - } - - // Now encode this lot... - // EXPLICIT tag - if (flags & ASN1_TFLG_EXPTAG) { - ASN1_put_object(out, /*constructed=*/1, sklen, ttag, tclass); - } - // SET or SEQUENCE and IMPLICIT tag - ASN1_put_object(out, /*constructed=*/1, skcontlen, sktag, skaclass); - // And the stuff itself - if (!asn1_set_seq_out(sk, out, skcontlen, ASN1_ITEM_ptr(tt->item), isset)) { - return -1; - } - return ret; - } - - if (flags & ASN1_TFLG_EXPTAG) { - // EXPLICIT tagging - // Find length of tagged item - i = asn1_item_ex_i2d_opt(pval, NULL, ASN1_ITEM_ptr(tt->item), -1, 0, - optional); - if (i <= 0) { - return i; - } - // Find length of EXPLICIT tag - ret = ASN1_object_size(/*constructed=*/1, i, ttag); - if (out && ret != -1) { - // Output tag and item - ASN1_put_object(out, /*constructed=*/1, i, ttag, tclass); - if (ASN1_item_ex_i2d(pval, out, ASN1_ITEM_ptr(tt->item), -1, 0) < 0) { - return -1; - } - } - return ret; - } - - // Either normal or IMPLICIT tagging - return asn1_item_ex_i2d_opt(pval, out, ASN1_ITEM_ptr(tt->item), ttag, tclass, - optional); -} - -// Temporary structure used to hold DER encoding of items for SET OF - -typedef struct { - unsigned char *data; - int length; -} DER_ENC; - -static int der_cmp(const void *a, const void *b) { - const DER_ENC *d1 = reinterpret_cast(a), - *d2 = reinterpret_cast(b); - int cmplen, i; - cmplen = (d1->length < d2->length) ? d1->length : d2->length; - i = OPENSSL_memcmp(d1->data, d2->data, cmplen); - if (i) { - return i; - } - return d1->length - d2->length; -} - -// asn1_set_seq_out writes |sk| to |out| under the i2d output convention, -// excluding the tag and length. It returns one on success and zero on error. -// |skcontlen| must be the total encoded size. If |do_sort| is non-zero, the -// elements are sorted for a SET OF type. Each element of |sk| has type -// |item|. -static int asn1_set_seq_out(STACK_OF(ASN1_VALUE) *sk, unsigned char **out, - int skcontlen, const ASN1_ITEM *item, int do_sort) { - // No need to sort if there are fewer than two items. - if (!do_sort || sk_ASN1_VALUE_num(sk) < 2) { for (size_t i = 0; i < sk_ASN1_VALUE_num(sk); i++) { - ASN1_VALUE *skitem = sk_ASN1_VALUE_value(sk, i); - if (ASN1_item_ex_i2d(&skitem, out, item, -1, 0) < 0) { + ASN1_VALUE *elem = sk_ASN1_VALUE_value(sk, i); + if (!asn1_marshal_item(&child, &elem, ASN1_ITEM_ptr(tt->item), + /*tag=*/0)) { return 0; } } - return 1; - } - - int ret = 0; - uint8_t *const buf = reinterpret_cast(OPENSSL_malloc(skcontlen)); - DER_ENC *encoded = reinterpret_cast( - OPENSSL_calloc(sk_ASN1_VALUE_num(sk), sizeof(*encoded))); - uint8_t *p = buf; - if (encoded == NULL || buf == NULL) { - goto err; - } - - // Encode all the elements into |buf| and populate |encoded|. - for (size_t i = 0; i < sk_ASN1_VALUE_num(sk); i++) { - ASN1_VALUE *skitem = sk_ASN1_VALUE_value(sk, i); - encoded[i].data = p; - encoded[i].length = ASN1_item_ex_i2d(&skitem, &p, item, -1, 0); - if (encoded[i].length < 0) { - goto err; + // If this is a SET OF type, sort the encodings when flushing. + if (is_set) { + return CBB_flush_asn1_set_of(&child) && CBB_flush(cbb); } - assert(p - buf <= skcontlen); + return CBB_flush(cbb); } - qsort(encoded, sk_ASN1_VALUE_num(sk), sizeof(*encoded), der_cmp); - - // Output the elements in sorted order. - p = *out; - for (size_t i = 0; i < sk_ASN1_VALUE_num(sk); i++) { - OPENSSL_memcpy(p, encoded[i].data, encoded[i].length); - p += encoded[i].length; - } - *out = p; - - ret = 1; - -err: - OPENSSL_free(encoded); - OPENSSL_free(buf); - return ret; + return asn1_marshal_item(cbb, pval, ASN1_ITEM_ptr(tt->item), tag); } -// asn1_i2d_ex_primitive behaves like |ASN1_item_ex_i2d| but |item| must be a -// a PRIMITIVE or MSTRING type that is not an |ASN1_ITEM_TEMPLATE|. -static int asn1_i2d_ex_primitive(ASN1_VALUE **pval, unsigned char **out, - const ASN1_ITEM *it, int tag, int aclass, - int optional) { - // Get length of content octets and maybe find out the underlying type. - int omit; - int utype = it->utype; - int len = asn1_ex_i2c(pval, NULL, &omit, &utype, it); - if (len < 0) { - return -1; - } - if (omit) { - if (optional) { - return 0; - } +static int asn1_marshal_primitive(CBB *cbb, ASN1_VALUE **pval, + const ASN1_ITEM *it, CBS_ASN1_TAG tag) { + assert(it->itype == ASN1_ITYPE_PRIMITIVE); + // Historically, `it->funcs` for primitive types contained an + // `ASN1_PRIMITIVE_FUNCS` table of callbacks. + assert(it->funcs == nullptr); + if (!asn1_item_has_value(pval, it)) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_VALUE); - return -1; + return 0; } - // If SEQUENCE, SET or OTHER then header is included in pseudo content - // octets so don't include tag+length. We need to check here because the - // call to asn1_ex_i2c() could change utype. - int usetag = - utype != V_ASN1_SEQUENCE && utype != V_ASN1_SET && utype != V_ASN1_OTHER; - - // If not implicitly tagged get tag from underlying type - if (tag == -1) { - tag = utype; - } - - // Output tag+length followed by content octets - if (out) { - if (usetag) { - ASN1_put_object(out, /*constructed=*/0, len, tag, aclass); - } - int len2 = asn1_ex_i2c(pval, *out, &omit, &utype, it); - if (len2 < 0) { - return -1; - } - assert(len == len2); - assert(!omit); - *out += len; - } - - if (usetag) { - return ASN1_object_size(/*constructed=*/0, len, tag); - } - return len; -} - -// asn1_ex_i2c writes the |*pval| to |cout| under the i2d output convention, -// excluding the tag and length. It returns the number of bytes written, -// possibly zero, on success or -1 on error. If |*pval| should be omitted, it -// returns zero and sets |*out_omit| to true. -// -// If |it| is an MSTRING or ANY type, it gets the underlying type from |*pval|, -// which must be an |ASN1_STRING| or |ASN1_TYPE|, respectively. It then updates -// |*putype| with the tag number of type used, or |V_ASN1_OTHER| if it was not a -// universal type. If |*putype| is set to |V_ASN1_SEQUENCE|, |V_ASN1_SET|, or -// |V_ASN1_OTHER|, it additionally outputs the tag and length, so the caller -// must not do so. -// -// Otherwise, |*putype| must contain |it->utype|. -// -// WARNING: Unlike most functions in this file, |asn1_ex_i2c| can return zero -// without omitting the element. ASN.1 values may have empty contents. -static int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *out_omit, - int *putype, const ASN1_ITEM *it) { - ASN1_BOOLEAN *tbool = NULL; - ASN1_STRING *strtmp; - ASN1_OBJECT *otmp; - int utype; - const unsigned char *cont; - unsigned char c; - int len; - - // Historically, |it->funcs| for primitive types contained an - // |ASN1_PRIMITIVE_FUNCS| table of callbacks. - assert(it->funcs == NULL); - - *out_omit = 0; - - // Should type be omitted? - if ((it->itype != ASN1_ITYPE_PRIMITIVE) || (it->utype != V_ASN1_BOOLEAN)) { - if (!*pval) { - *out_omit = 1; - return 0; - } - } - - if (it->itype == ASN1_ITYPE_MSTRING) { - // If MSTRING type set the underlying type - strtmp = (ASN1_STRING *)*pval; - utype = strtmp->type; - if (utype < 0 && utype != V_ASN1_OTHER) { - // MSTRINGs can have type -1 when default-constructed. - OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE); - return -1; - } - // Negative INTEGER and ENUMERATED values use |ASN1_STRING| type values - // that do not match their corresponding utype values. INTEGERs cannot - // participate in MSTRING types, but ENUMERATEDs can. - // - // TODO(davidben): Is this a bug? Although arguably one of the MSTRING - // types should contain more values, rather than less. See - // https://crbug.com/boringssl/412. But it is not possible to fit all - // possible ANY values into an |ASN1_STRING|, so matching the spec here - // is somewhat hopeless. - if (utype == V_ASN1_NEG_INTEGER) { - utype = V_ASN1_INTEGER; - } else if (utype == V_ASN1_NEG_ENUMERATED) { - utype = V_ASN1_ENUMERATED; - } - *putype = utype; - } else if (it->utype == V_ASN1_ANY) { - // If ANY set type and pointer to value - ASN1_TYPE *typ; - typ = (ASN1_TYPE *)*pval; - utype = typ->type; - if (utype < 0 && utype != V_ASN1_OTHER) { - // |ASN1_TYPE|s can have type -1 when default-constructed. - OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE); - return -1; - } - *putype = utype; - pval = &typ->value.asn1_value; - } else { - utype = *putype; - } - - switch (utype) { - case V_ASN1_OBJECT: - otmp = (ASN1_OBJECT *)*pval; - cont = otmp->data; - len = otmp->length; - if (len == 0) { - // Some |ASN1_OBJECT|s do not have OIDs and cannot be serialized. - OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OBJECT); - return -1; - } - break; - - case V_ASN1_NULL: - cont = NULL; - len = 0; - break; - - case V_ASN1_BOOLEAN: - tbool = (ASN1_BOOLEAN *)pval; - if (*tbool == ASN1_BOOLEAN_NONE) { - *out_omit = 1; + // Handle non-string types. + switch (it->utype) { + case V_ASN1_ANY: + // ANY types cannot be implicitly tagged. + if (tag != 0) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); return 0; } - if (it->utype != V_ASN1_ANY) { - // Default handling if value == size field then omit - if ((*tbool && (it->size > 0)) || (!*tbool && !it->size)) { - *out_omit = 1; - return 0; - } - } - c = *tbool ? 0xff : 0x00; - cont = &c; - len = 1; - break; - - case V_ASN1_BIT_STRING: { - int ret = - i2c_ASN1_BIT_STRING((ASN1_BIT_STRING *)*pval, cout ? &cout : NULL); - // |i2c_ASN1_BIT_STRING| returns zero on error instead of -1. - return ret <= 0 ? -1 : ret; + return asn1_marshal_any(cbb, asn1_load_ptr_as(pval)); + case V_ASN1_OBJECT: + return asn1_marshal_object(cbb, asn1_load_ptr_as(pval), tag); + case V_ASN1_NULL: + tag = tag == 0 ? CBS_ASN1_NULL : tag; + return CBB_add_asn1_element(cbb, tag, nullptr, 0); + case V_ASN1_BOOLEAN: { + // `ASN1_BOOLEAN` is not a pointer type. + ASN1_BOOLEAN b = *reinterpret_cast(pval); + tag = tag == 0 ? CBS_ASN1_BOOLEAN : tag; + CBB child; + return CBB_add_asn1(cbb, &child, tag) && + CBB_add_u8(&child, b ? 0xff : 0x00) && // + CBB_flush(cbb); } + } + // All other supported types are represented as strings. + const ASN1_STRING *str = asn1_load_ptr_as(pval); + switch (it->utype) { + case V_ASN1_BIT_STRING: + return asn1_marshal_bit_string(cbb, str, tag); case V_ASN1_INTEGER: - case V_ASN1_ENUMERATED: { - // |i2c_ASN1_INTEGER| also handles ENUMERATED. - int ret = i2c_ASN1_INTEGER((ASN1_INTEGER *)*pval, cout ? &cout : NULL); - // |i2c_ASN1_INTEGER| returns zero on error instead of -1. - return ret <= 0 ? -1 : ret; - } - + return asn1_marshal_integer(cbb, str, tag); + case V_ASN1_ENUMERATED: + tag = tag == 0 ? CBS_ASN1_ENUMERATED : tag; + return asn1_marshal_integer(cbb, str, tag); case V_ASN1_OCTET_STRING: case V_ASN1_NUMERICSTRING: case V_ASN1_PRINTABLESTRING: @@ -640,25 +335,14 @@ static int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *out_omit, case V_ASN1_UNIVERSALSTRING: case V_ASN1_BMPSTRING: case V_ASN1_UTF8STRING: + tag = tag == 0 ? static_cast(it->utype) : tag; + return asn1_marshal_octet_string(cbb, str, tag); case V_ASN1_SEQUENCE: - case V_ASN1_SET: - // This is not a valid |ASN1_ITEM| type, but it appears in |ASN1_TYPE|. - case V_ASN1_OTHER: - // TODO(crbug.com/boringssl/412): This default case should be removed, now - // that we've resolved https://crbug.com/boringssl/561. However, it is still - // needed to support some edge cases in |ASN1_PRINTABLE|. |ASN1_PRINTABLE| - // broadly doesn't tolerate unrecognized universal tags, but except for - // eight values that map to |B_ASN1_UNKNOWN| instead of zero. See the - // X509Test.NameAttributeValues test. + // The `ASN1_SEQUENCE` item stores the entire element. + return CBB_add_bytes(cbb, ASN1_STRING_get0_data(str), + ASN1_STRING_length(str)); default: - // All based on ASN1_STRING and handled the same - strtmp = (ASN1_STRING *)*pval; - cont = strtmp->data; - len = strtmp->length; - break; + OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); + return 0; } - if (cout && len) { - OPENSSL_memcpy(cout, cont, len); - } - return len; } diff --git a/Sources/CNIOBoringSSL/crypto/asn1/tasn_fre.cc b/Sources/CNIOBoringSSL/crypto/asn1/tasn_fre.cc index 9898df3b..e39862d8 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/tasn_fre.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/tasn_fre.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,17 +21,20 @@ #include "internal.h" + +using namespace bssl; + // Free up an ASN1 structure void ASN1_item_free(ASN1_VALUE *val, const ASN1_ITEM *it) { ASN1_item_ex_free(&val, it); } -void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { +void bssl::ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { if (!pval) { return; } - if ((it->itype != ASN1_ITYPE_PRIMITIVE) && !*pval) { + if ((it->itype != ASN1_ITYPE_PRIMITIVE) && !asn1_load_ptr(pval)) { return; } @@ -45,9 +53,9 @@ void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { case ASN1_ITYPE_CHOICE: { const ASN1_AUX *aux = reinterpret_cast(it->funcs); - ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL; + ASN1_aux_cb *asn1_cb = aux != nullptr ? aux->asn1_cb : nullptr; if (asn1_cb) { - if (asn1_cb(ASN1_OP_FREE_PRE, pval, it, NULL) == 2) { + if (asn1_cb(ASN1_OP_FREE_PRE, pval, it, nullptr) == 2) { return; } } @@ -58,10 +66,10 @@ void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { ASN1_template_free(pchval, tt); } if (asn1_cb) { - asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL); + asn1_cb(ASN1_OP_FREE_POST, pval, it, nullptr); } - OPENSSL_free(*pval); - *pval = NULL; + OPENSSL_free(asn1_load_ptr(pval)); + asn1_store_ptr(pval, nullptr); break; } @@ -79,15 +87,15 @@ void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { return; } const ASN1_AUX *aux = reinterpret_cast(it->funcs); - ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL; + ASN1_aux_cb *asn1_cb = aux != nullptr ? aux->asn1_cb : nullptr; if (asn1_cb) { - if (asn1_cb(ASN1_OP_FREE_PRE, pval, it, NULL) == 2) { + if (asn1_cb(ASN1_OP_FREE_PRE, pval, it, nullptr) == 2) { return; } } asn1_enc_free(pval, it); // If we free up as normal we will invalidate any ANY DEFINED BY - // field and we wont be able to determine the type of the field it + // field and we won't be able to determine the type of the field it // defines. So free up in reverse order. for (int i = it->tcount - 1; i >= 0; i--) { const ASN1_TEMPLATE *seqtt = asn1_do_adb(pval, &it->templates[i], 0); @@ -98,45 +106,46 @@ void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { ASN1_template_free(pseqval, seqtt); } if (asn1_cb) { - asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL); + asn1_cb(ASN1_OP_FREE_POST, pval, it, nullptr); } - OPENSSL_free(*pval); - *pval = NULL; + OPENSSL_free(asn1_load_ptr(pval)); + asn1_store_ptr(pval, nullptr); break; } } } -void ASN1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) { +void bssl::ASN1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) { if (tt->flags & ASN1_TFLG_SK_MASK) { - STACK_OF(ASN1_VALUE) *sk = (STACK_OF(ASN1_VALUE) *)*pval; + STACK_OF(ASN1_VALUE) *sk = asn1_load_ptr_as(pval); for (size_t i = 0; i < sk_ASN1_VALUE_num(sk); i++) { ASN1_VALUE *vtmp = sk_ASN1_VALUE_value(sk, i); ASN1_item_ex_free(&vtmp, ASN1_ITEM_ptr(tt->item)); } sk_ASN1_VALUE_free(sk); - *pval = NULL; + asn1_store_ptr(pval, nullptr); } else { ASN1_item_ex_free(pval, ASN1_ITEM_ptr(tt->item)); } } -void ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { - // Historically, |it->funcs| for primitive types contained an - // |ASN1_PRIMITIVE_FUNCS| table of calbacks. - assert(it->funcs == NULL); +void bssl::ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { + // Historically, `it->funcs` for primitive types contained an + // `ASN1_PRIMITIVE_FUNCS` table of callbacks. + assert(it->funcs == nullptr); int utype = it->itype == ASN1_ITYPE_MSTRING ? -1 : it->utype; switch (utype) { case V_ASN1_OBJECT: - ASN1_OBJECT_free((ASN1_OBJECT *)*pval); + ASN1_OBJECT_free(asn1_load_ptr_as(pval)); break; case V_ASN1_BOOLEAN: if (it) { - *(ASN1_BOOLEAN *)pval = (ASN1_BOOLEAN)it->size; + *reinterpret_cast(pval) = + static_cast(it->size); } else { - *(ASN1_BOOLEAN *)pval = ASN1_BOOLEAN_NONE; + *reinterpret_cast(pval) = ASN1_BOOLEAN_NONE; } return; @@ -144,16 +153,11 @@ void ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { break; case V_ASN1_ANY: - if (*pval != NULL) { - asn1_type_cleanup((ASN1_TYPE *)*pval); - OPENSSL_free(*pval); - } + ASN1_TYPE_free(asn1_load_ptr_as(pval)); break; default: - ASN1_STRING_free((ASN1_STRING *)*pval); - *pval = NULL; - break; + ASN1_STRING_free(asn1_load_ptr_as(pval)); } - *pval = NULL; + asn1_store_ptr(pval, nullptr); } diff --git a/Sources/CNIOBoringSSL/crypto/asn1/tasn_new.cc b/Sources/CNIOBoringSSL/crypto/asn1/tasn_new.cc index b1e4ccc8..4713b7f8 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/tasn_new.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/tasn_new.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,9 +22,12 @@ #include #include "../internal.h" +#include "../mem_internal.h" #include "internal.h" +using namespace bssl; + static void asn1_item_clear(ASN1_VALUE **pval, const ASN1_ITEM *it); static int ASN1_template_new(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt); static void asn1_template_clear(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt); @@ -27,17 +35,17 @@ static int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it); static void asn1_primitive_clear(ASN1_VALUE **pval, const ASN1_ITEM *it); ASN1_VALUE *ASN1_item_new(const ASN1_ITEM *it) { - ASN1_VALUE *ret = NULL; + ASN1_VALUE *ret = nullptr; if (ASN1_item_ex_new(&ret, it) > 0) { return ret; } - return NULL; + return nullptr; } // Allocate an ASN1 structure -int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { - const ASN1_TEMPLATE *tt = NULL; +int bssl::ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { + const ASN1_TEMPLATE *tt = nullptr; const ASN1_EXTERN_FUNCS *ef; ASN1_VALUE **pseqval; int i; @@ -70,9 +78,9 @@ int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { case ASN1_ITYPE_CHOICE: { const ASN1_AUX *aux = reinterpret_cast(it->funcs); - ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL; + ASN1_aux_cb *asn1_cb = aux != nullptr ? aux->asn1_cb : nullptr; if (asn1_cb) { - i = asn1_cb(ASN1_OP_NEW_PRE, pval, it, NULL); + i = asn1_cb(ASN1_OP_NEW_PRE, pval, it, nullptr); if (!i) { goto auxerr; } @@ -80,12 +88,13 @@ int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { return 1; } } - *pval = reinterpret_cast(OPENSSL_zalloc(it->size)); - if (!*pval) { + void *obj = OPENSSL_zalloc(it->size); + if (obj == nullptr) { goto memerr; } + asn1_store_ptr(pval, obj); asn1_set_choice_selector(pval, -1, it); - if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, NULL)) { + if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, nullptr)) { goto auxerr2; } break; @@ -93,9 +102,9 @@ int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { case ASN1_ITYPE_SEQUENCE: { const ASN1_AUX *aux = reinterpret_cast(it->funcs); - ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL; + ASN1_aux_cb *asn1_cb = aux != nullptr ? aux->asn1_cb : nullptr; if (asn1_cb) { - i = asn1_cb(ASN1_OP_NEW_PRE, pval, it, NULL); + i = asn1_cb(ASN1_OP_NEW_PRE, pval, it, nullptr); if (!i) { goto auxerr; } @@ -103,10 +112,11 @@ int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { return 1; } } - *pval = reinterpret_cast(OPENSSL_zalloc(it->size)); - if (!*pval) { + void *obj = OPENSSL_zalloc(it->size); + if (obj == nullptr) { goto memerr; } + asn1_store_ptr(pval, obj); asn1_refcount_set_one(pval, it); asn1_enc_init(pval, it); for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) { @@ -115,7 +125,7 @@ int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { goto memerr2; } } - if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, NULL)) { + if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, nullptr)) { goto auxerr2; } break; @@ -138,7 +148,7 @@ auxerr: static void asn1_item_clear(ASN1_VALUE **pval, const ASN1_ITEM *it) { switch (it->itype) { case ASN1_ITYPE_EXTERN: - *pval = NULL; + asn1_store_ptr(pval, nullptr); break; case ASN1_ITYPE_PRIMITIVE: @@ -155,46 +165,39 @@ static void asn1_item_clear(ASN1_VALUE **pval, const ASN1_ITEM *it) { case ASN1_ITYPE_CHOICE: case ASN1_ITYPE_SEQUENCE: - *pval = NULL; + asn1_store_ptr(pval, nullptr); break; } } static int ASN1_template_new(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) { const ASN1_ITEM *it = ASN1_ITEM_ptr(tt->item); - int ret; if (tt->flags & ASN1_TFLG_OPTIONAL) { asn1_template_clear(pval, tt); return 1; } - // If ANY DEFINED BY nothing to do - + // If ANY DEFINED BY, there is nothing to do. if (tt->flags & ASN1_TFLG_ADB_MASK) { - *pval = NULL; + asn1_store_ptr(pval, nullptr); return 1; } - // If SET OF or SEQUENCE OF, its a STACK + // If SET OF or SEQUENCE OF, it's a STACK. if (tt->flags & ASN1_TFLG_SK_MASK) { - STACK_OF(ASN1_VALUE) *skval; - skval = sk_ASN1_VALUE_new_null(); + STACK_OF(ASN1_VALUE) *skval = sk_ASN1_VALUE_new_null(); if (!skval) { - ret = 0; - goto done; + return 0; } - *pval = (ASN1_VALUE *)skval; - ret = 1; - goto done; + asn1_store_ptr(pval, skval); + return 1; } - // Otherwise pass it back to the item routine - ret = ASN1_item_ex_new(pval, it); -done: - return ret; + // Otherwise, pass it back to the item routine. + return ASN1_item_ex_new(pval, it); } static void asn1_template_clear(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) { - // If ADB or STACK just NULL the field + // If ADB or STACK, just NULL the field. if (tt->flags & (ASN1_TFLG_ADB_MASK | ASN1_TFLG_SK_MASK)) { - *pval = NULL; + asn1_store_ptr(pval, nullptr); } else { asn1_item_clear(pval, ASN1_ITEM_ptr(tt->item)); } @@ -208,9 +211,9 @@ static int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { return 0; } - // Historically, |it->funcs| for primitive types contained an - // |ASN1_PRIMITIVE_FUNCS| table of calbacks. - assert(it->funcs == NULL); + // Historically, `it->funcs` for primitive types contained an + // `ASN1_PRIMITIVE_FUNCS` table of callbacks. + assert(it->funcs == nullptr); int utype; if (it->itype == ASN1_ITYPE_MSTRING) { @@ -220,34 +223,32 @@ static int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { } switch (utype) { case V_ASN1_OBJECT: - *pval = (ASN1_VALUE *)OBJ_get_undef(); + asn1_store_ptr(pval, OBJ_get_undef()); return 1; case V_ASN1_BOOLEAN: - *(ASN1_BOOLEAN *)pval = (ASN1_BOOLEAN)it->size; + *reinterpret_cast(pval) = + static_cast(it->size); return 1; case V_ASN1_NULL: - *pval = (ASN1_VALUE *)1; + asn1_store_ptr(pval, reinterpret_cast(1)); return 1; case V_ASN1_ANY: { - ASN1_TYPE *typ = - reinterpret_cast(OPENSSL_malloc(sizeof(ASN1_TYPE))); + ASN1_TYPE *typ = ASN1_TYPE_new(); if (!typ) { return 0; } - typ->value.ptr = NULL; - typ->type = -1; - *pval = (ASN1_VALUE *)typ; + asn1_store_ptr(pval, typ); break; } default: - *pval = (ASN1_VALUE *)ASN1_STRING_type_new(utype); + asn1_store_ptr(pval, ASN1_STRING_type_new(utype)); break; } - if (*pval) { + if (asn1_load_ptr(pval)) { return 1; } return 0; @@ -255,17 +256,19 @@ static int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { static void asn1_primitive_clear(ASN1_VALUE **pval, const ASN1_ITEM *it) { int utype; - // Historically, |it->funcs| for primitive types contained an - // |ASN1_PRIMITIVE_FUNCS| table of calbacks. - assert(it == NULL || it->funcs == NULL); + // Historically, `it->funcs` for primitive types contained an + // `ASN1_PRIMITIVE_FUNCS` table of callbacks. + assert(it == nullptr || it->funcs == nullptr); if (!it || (it->itype == ASN1_ITYPE_MSTRING)) { utype = -1; } else { utype = it->utype; } if (utype == V_ASN1_BOOLEAN) { - *(ASN1_BOOLEAN *)pval = (ASN1_BOOLEAN)it->size; + // `ASN1_BOOLEAN` is not a pointer type. + *reinterpret_cast(pval) = + static_cast(it->size); } else { - *pval = NULL; + asn1_store_ptr(pval, nullptr); } } diff --git a/Sources/CNIOBoringSSL/crypto/asn1/tasn_typ.cc b/Sources/CNIOBoringSSL/crypto/asn1/tasn_typ.cc index 0f3a7c2d..4b564232 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/tasn_typ.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/tasn_typ.cc @@ -1,22 +1,33 @@ -/* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 -// Declarations for string types +#include "internal.h" -#define IMPLEMENT_ASN1_STRING_FUNCTIONS(sname) \ - IMPLEMENT_ASN1_TYPE(sname) \ - IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(sname, sname, sname) \ - sname *sname##_new(void) { return ASN1_STRING_type_new(V_##sname); } \ + +using namespace bssl; + +// TODO(crbug.com/42290417): While we need `ASN1_ITEM`s, the exposed new, free, +// i2d, and d2i functions should call the underlying implementations directly. + +#define IMPLEMENT_ASN1_STRING_FUNCTIONS(sname) \ + IMPLEMENT_ASN1_TYPE(sname) \ + IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(sname, sname, sname) \ + sname *sname##_new() { return ASN1_STRING_type_new(V_##sname); } \ void sname##_free(sname *x) { ASN1_STRING_free(x); } IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_OCTET_STRING) @@ -44,18 +55,20 @@ IMPLEMENT_ASN1_TYPE(ASN1_ANY) // Just swallow an ASN1_SEQUENCE in an ASN1_STRING IMPLEMENT_ASN1_TYPE(ASN1_SEQUENCE) -IMPLEMENT_ASN1_FUNCTIONS_const_fname(ASN1_TYPE, ASN1_ANY, ASN1_TYPE) - -// Multistring types - -IMPLEMENT_ASN1_MSTRING(ASN1_PRINTABLE, B_ASN1_PRINTABLE) -IMPLEMENT_ASN1_FUNCTIONS_const_fname(ASN1_STRING, ASN1_PRINTABLE, - ASN1_PRINTABLE) +BSSL_NAMESPACE_BEGIN IMPLEMENT_ASN1_MSTRING(DISPLAYTEXT, B_ASN1_DISPLAYTEXT) + +BSSL_NAMESPACE_END + IMPLEMENT_ASN1_FUNCTIONS_const_fname(ASN1_STRING, DISPLAYTEXT, DISPLAYTEXT) +BSSL_NAMESPACE_BEGIN + IMPLEMENT_ASN1_MSTRING(DIRECTORYSTRING, B_ASN1_DIRECTORYSTRING) + +BSSL_NAMESPACE_END + IMPLEMENT_ASN1_FUNCTIONS_const_fname(ASN1_STRING, DIRECTORYSTRING, DIRECTORYSTRING) diff --git a/Sources/CNIOBoringSSL/crypto/asn1/tasn_utl.cc b/Sources/CNIOBoringSSL/crypto/asn1/tasn_utl.cc index e2b73805..4c6d7103 100644 --- a/Sources/CNIOBoringSSL/crypto/asn1/tasn_utl.cc +++ b/Sources/CNIOBoringSSL/crypto/asn1/tasn_utl.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,28 +22,30 @@ #include #include #include -#include #include "../internal.h" #include "internal.h" +using namespace bssl; + // Utility functions for manipulating fields and offsets // Add 'offset' to 'addr' #define offset2ptr(addr, offset) (void *)(((char *)(addr)) + (offset)) // Given an ASN1_ITEM CHOICE type return the selector value -int asn1_get_choice_selector(ASN1_VALUE **pval, const ASN1_ITEM *it) { - int *sel = reinterpret_cast(offset2ptr(*pval, it->utype)); +int bssl::asn1_get_choice_selector(ASN1_VALUE **pval, const ASN1_ITEM *it) { + int *sel = + reinterpret_cast(offset2ptr(asn1_load_ptr(pval), it->utype)); return *sel; } // Given an ASN1_ITEM CHOICE type set the selector value, return old value. -int asn1_set_choice_selector(ASN1_VALUE **pval, int value, - const ASN1_ITEM *it) { +int bssl::asn1_set_choice_selector(ASN1_VALUE **pval, int value, + const ASN1_ITEM *it) { int *sel, ret; - sel = reinterpret_cast(offset2ptr(*pval, it->utype)); + sel = reinterpret_cast(offset2ptr(asn1_load_ptr(pval), it->utype)); ret = *sel; *sel = value; return ret; @@ -47,26 +54,27 @@ int asn1_set_choice_selector(ASN1_VALUE **pval, int value, static CRYPTO_refcount_t *asn1_get_references(ASN1_VALUE **pval, const ASN1_ITEM *it) { if (it->itype != ASN1_ITYPE_SEQUENCE) { - return NULL; + return nullptr; } const ASN1_AUX *aux = reinterpret_cast(it->funcs); if (!aux || !(aux->flags & ASN1_AFLG_REFCOUNT)) { - return NULL; + return nullptr; } return reinterpret_cast( - offset2ptr(*pval, aux->ref_offset)); + offset2ptr(asn1_load_ptr(pval), aux->ref_offset)); } -void asn1_refcount_set_one(ASN1_VALUE **pval, const ASN1_ITEM *it) { +void bssl::asn1_refcount_set_one(ASN1_VALUE **pval, const ASN1_ITEM *it) { CRYPTO_refcount_t *references = asn1_get_references(pval, it); - if (references != NULL) { + if (references != nullptr) { *references = 1; } } -int asn1_refcount_dec_and_test_zero(ASN1_VALUE **pval, const ASN1_ITEM *it) { +int bssl::asn1_refcount_dec_and_test_zero(ASN1_VALUE **pval, + const ASN1_ITEM *it) { CRYPTO_refcount_t *references = asn1_get_references(pval, it); - if (references != NULL) { + if (references != nullptr) { return CRYPTO_refcount_dec_and_test_zero(references); } return 1; @@ -75,34 +83,34 @@ int asn1_refcount_dec_and_test_zero(ASN1_VALUE **pval, const ASN1_ITEM *it) { static ASN1_ENCODING *asn1_get_enc_ptr(ASN1_VALUE **pval, const ASN1_ITEM *it) { assert(it->itype == ASN1_ITYPE_SEQUENCE); const ASN1_AUX *aux; - if (!pval || !*pval) { - return NULL; + if (!pval || !asn1_load_ptr(pval)) { + return nullptr; } aux = reinterpret_cast(it->funcs); if (!aux || !(aux->flags & ASN1_AFLG_ENCODING)) { - return NULL; + return nullptr; } - return reinterpret_cast(offset2ptr(*pval, aux->enc_offset)); + return reinterpret_cast( + offset2ptr(asn1_load_ptr(pval), aux->enc_offset)); } -void asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it) { +void bssl::asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it) { ASN1_ENCODING *enc = asn1_get_enc_ptr(pval, it); if (enc) { - enc->enc = NULL; + enc->enc = nullptr; enc->len = 0; - enc->buf = NULL; } } -void asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { +void bssl::asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { ASN1_ENCODING *enc = asn1_get_enc_ptr(pval, it); if (enc) { asn1_encoding_clear(enc); } } -int asn1_enc_save(ASN1_VALUE **pval, const uint8_t *in, size_t in_len, - const ASN1_ITEM *it, CRYPTO_BUFFER *buf) { +int bssl::asn1_enc_save(ASN1_VALUE **pval, const uint8_t *in, size_t in_len, + const ASN1_ITEM *it) { ASN1_ENCODING *enc; enc = asn1_get_enc_ptr(pval, it); if (!enc) { @@ -110,80 +118,55 @@ int asn1_enc_save(ASN1_VALUE **pval, const uint8_t *in, size_t in_len, } asn1_encoding_clear(enc); - if (buf != NULL) { - assert(CRYPTO_BUFFER_data(buf) <= in && - in + in_len <= CRYPTO_BUFFER_data(buf) + CRYPTO_BUFFER_len(buf)); - CRYPTO_BUFFER_up_ref(buf); - enc->buf = buf; - enc->enc = (uint8_t *)in; - } else { - enc->enc = reinterpret_cast(OPENSSL_memdup(in, in_len)); - if (!enc->enc) { - return 0; - } + enc->enc = reinterpret_cast(OPENSSL_memdup(in, in_len)); + if (!enc->enc) { + return 0; } enc->len = in_len; return 1; } -void asn1_encoding_clear(ASN1_ENCODING *enc) { - if (enc->buf != NULL) { - CRYPTO_BUFFER_free(enc->buf); - } else { - OPENSSL_free(enc->enc); - } - enc->enc = NULL; +void bssl::asn1_encoding_clear(ASN1_ENCODING *enc) { + OPENSSL_free(enc->enc); + enc->enc = nullptr; enc->len = 0; - enc->buf = NULL; } -int asn1_enc_restore(int *len, unsigned char **out, ASN1_VALUE **pval, - const ASN1_ITEM *it) { +int bssl::asn1_enc_restore(Span *out, ASN1_VALUE **pval, + const ASN1_ITEM *it) { ASN1_ENCODING *enc = asn1_get_enc_ptr(pval, it); if (!enc || enc->len == 0) { return 0; } - if (out) { - OPENSSL_memcpy(*out, enc->enc, enc->len); - *out += enc->len; - } - if (len) { - *len = enc->len; - } + *out = Span(enc->enc, enc->len); return 1; } // Given an ASN1_TEMPLATE get a pointer to a field -ASN1_VALUE **asn1_get_field_ptr(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) { - ASN1_VALUE **pvaltmp = - reinterpret_cast(offset2ptr(*pval, tt->offset)); - // NOTE for BOOLEAN types the field is just a plain int so we can't return - // int **, so settle for (int *). - return pvaltmp; +ASN1_VALUE **bssl::asn1_get_field_ptr(ASN1_VALUE **pval, + const ASN1_TEMPLATE *tt) { + return reinterpret_cast( + offset2ptr(asn1_load_ptr(pval), tt->offset)); } // Handle ANY DEFINED BY template, find the selector, look up the relevant // ASN1_TEMPLATE in the table and return it. -const ASN1_TEMPLATE *asn1_do_adb(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt, - int nullerr) { - const ASN1_ADB *adb; - const ASN1_ADB_TABLE *atbl; - ASN1_VALUE **sfld; - int i; +const ASN1_TEMPLATE *bssl::asn1_do_adb(ASN1_VALUE **pval, + const ASN1_TEMPLATE *tt, int nullerr) { if (!(tt->flags & ASN1_TFLG_ADB_MASK)) { return tt; } // Else ANY DEFINED BY ... get the table - adb = ASN1_ADB_ptr(tt->item); + const ASN1_ADB *adb = ASN1_ADB_ptr(tt->item); // Get the selector field - sfld = reinterpret_cast(offset2ptr(*pval, adb->offset)); - - // Check if NULL + ASN1_VALUE **sfld = reinterpret_cast( + offset2ptr(asn1_load_ptr(pval), adb->offset)); int selector; - if (*sfld == NULL) { + const ASN1_OBJECT *selector_obj = asn1_load_ptr_as(sfld); + if (selector_obj == nullptr) { if (!adb->null_tt) { goto err; } @@ -194,21 +177,19 @@ const ASN1_TEMPLATE *asn1_do_adb(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt, // NB: don't check for NID_undef here because it // might be a legitimate value in the table assert(tt->flags & ASN1_TFLG_ADB_OID); - selector = OBJ_obj2nid((ASN1_OBJECT *)*sfld); + selector = OBJ_obj2nid(asn1_load_ptr_as(sfld)); // Try to find matching entry in table Maybe should check application types // first to allow application override? Might also be useful to have a flag // which indicates table is sorted and we can do a binary search. For now // stick to a linear search. - - for (atbl = adb->tbl, i = 0; i < adb->tblcount; i++, atbl++) { + for (int i = 0; i < adb->tblcount; i++) { + const ASN1_ADB_TABLE *atbl = &adb->tbl[i]; if (atbl->value == selector) { return &atbl->tt; } } - // FIXME: need to search application table too - // No match, return default type if (!adb->default_tt) { goto err; @@ -220,5 +201,18 @@ err: if (nullerr) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE); } - return NULL; + return nullptr; +} + +CBS_ASN1_TAG bssl::asn1_tag_to_cbs(int aclass, int tag) { + if ((aclass & ASN1_TFLG_TAG_CLASS) != aclass || // + tag < 0 || static_cast(tag) > CBS_ASN1_TAG_NUMBER_MASK || + // Universal tag zero is reserved and should never appear in a template. + // This file treats the zero tag as a sentinel value. + (aclass == 0 && tag == 0)) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE); + return 0; + } + return ((static_cast(aclass)) << CBS_ASN1_TAG_SHIFT) | + static_cast(tag); } diff --git a/Sources/CNIOBoringSSL/crypto/base64/base64.cc b/Sources/CNIOBoringSSL/crypto/base64/base64.cc index 24f26390..fff5bfdd 100644 --- a/Sources/CNIOBoringSSL/crypto/base64/base64.cc +++ b/Sources/CNIOBoringSSL/crypto/base64/base64.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,22 +19,24 @@ #include #include "../internal.h" +#include "../mem_internal.h" -// constant_time_lt_args_8 behaves like |constant_time_lt_8| but takes |uint8_t| +using namespace bssl; + +// constant_time_lt_args_8 behaves like `constant_time_lt_8` but takes `uint8_t` // arguments for a slightly simpler implementation. -static inline uint8_t constant_time_lt_args_8(uint8_t a, uint8_t b) { +static uint8_t constant_time_lt_args_8(uint8_t a, uint8_t b) { crypto_word_t aw = a; crypto_word_t bw = b; - // |crypto_word_t| is larger than |uint8_t|, so |aw| and |bw| have the same - // MSB. |aw| < |bw| iff MSB(|aw| - |bw|) is 1. + // `crypto_word_t` is larger than `uint8_t`, so `aw` and `bw` have the same + // MSB. `aw` < `bw` iff MSB(`aw` - `bw`) is 1. return constant_time_msb_w(aw - bw); } -// constant_time_in_range_8 returns |CONSTTIME_TRUE_8| if |min| <= |a| <= |max| -// and |CONSTTIME_FALSE_8| otherwise. -static inline uint8_t constant_time_in_range_8(uint8_t a, uint8_t min, - uint8_t max) { +// constant_time_in_range_8 returns `CONSTTIME_TRUE_8` if `min` <= `a` <= `max` +// and `CONSTTIME_FALSE_8` otherwise. +static uint8_t constant_time_in_range_8(uint8_t a, uint8_t min, uint8_t max) { a -= min; return constant_time_lt_args_8(a, max - min + 1); } @@ -49,7 +56,7 @@ static uint8_t conv_bin2ascii(uint8_t a) { return ret; } -static_assert(sizeof(((EVP_ENCODE_CTX *)(NULL))->data) % 3 == 0, +static_assert(sizeof(((EVP_ENCODE_CTX *)nullptr)->data) % 3 == 0, "data length must be a multiple of base64 chunk size"); int EVP_EncodedLength(size_t *out_len, size_t len) { @@ -73,12 +80,9 @@ int EVP_EncodedLength(size_t *out_len, size_t len) { return 1; } -EVP_ENCODE_CTX *EVP_ENCODE_CTX_new(void) { - return reinterpret_cast( - OPENSSL_zalloc(sizeof(EVP_ENCODE_CTX))); -} +EVP_ENCODE_CTX *EVP_ENCODE_CTX_new() { return New(); } -void EVP_ENCODE_CTX_free(EVP_ENCODE_CTX *ctx) { OPENSSL_free(ctx); } +void EVP_ENCODE_CTX_free(EVP_ENCODE_CTX *ctx) { Delete(ctx); } void EVP_EncodeInit(EVP_ENCODE_CTX *ctx) { OPENSSL_memset(ctx, 0, sizeof(EVP_ENCODE_CTX)); @@ -238,7 +242,7 @@ static uint8_t base64_ascii_to_bin(uint8_t a) { } // base64_decode_quad decodes a single “quad” (i.e. four characters) of base64 -// data and writes up to three bytes to |out|. It sets |*out_num_bytes| to the +// data and writes up to three bytes to `out`. It sets `*out_num_bytes` to the // number of bytes written, which will be less than three if the quad ended // with padding. It returns one on success or zero on error. static int base64_decode_quad(uint8_t *out, size_t *out_num_bytes, diff --git a/Sources/CNIOBoringSSL/crypto/bcm_support.h b/Sources/CNIOBoringSSL/crypto/bcm_support.h index 7da973da..278318cb 100644 --- a/Sources/CNIOBoringSSL/crypto/bcm_support.h +++ b/Sources/CNIOBoringSSL/crypto/bcm_support.h @@ -1,16 +1,16 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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. #ifndef OPENSSL_HEADER_CRYPTO_BCM_SUPPORT_H #define OPENSSL_HEADER_CRYPTO_BCM_SUPPORT_H @@ -19,73 +19,19 @@ #include -// Provided by libcrypto, called from BCM -#if defined(__cplusplus) -extern "C" { -#endif - -#if defined(OPENSSL_LINUX) -// On linux we use MADVISE instead of pthread_atfork(), due -// to concerns about clone() being used for address space -// duplication. -#define OPENSSL_FORK_DETECTION -#define OPENSSL_FORK_DETECTION_MADVISE -#elif defined(OPENSSL_MACOS) || defined(OPENSSL_IOS) || \ - defined(OPENSSL_OPENBSD) || defined(OPENSSL_FREEBSD) -// These platforms may detect address space duplication with pthread_atfork. -// iOS doesn't normally allow fork in apps, but it's there. -#define OPENSSL_FORK_DETECTION -#define OPENSSL_FORK_DETECTION_PTHREAD_ATFORK -#elif defined(OPENSSL_WINDOWS) || defined(OPENSSL_TRUSTY) || \ - defined(__ZEPHYR__) || defined(CROS_EC) -// These platforms do not fork. -#define OPENSSL_DOES_NOT_FORK -#endif - -#if defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE) -#define OPENSSL_RAND_DETERMINISTIC -#elif defined(OPENSSL_TRUSTY) -#define OPENSSL_RAND_TRUSTY -#elif defined(OPENSSL_WINDOWS) -#define OPENSSL_RAND_WINDOWS -#elif defined(OPENSSL_LINUX) -#define OPENSSL_RAND_URANDOM -#elif defined(OPENSSL_APPLE) && !defined(OPENSSL_MACOS) -// Unlike macOS, iOS and similar hide away getentropy(). -#define OPENSSL_RAND_IOS -#else -// By default if you are integrating BoringSSL we expect you to -// provide getentropy from the header file. -#define OPENSSL_RAND_GETENTROPY -#endif +BSSL_NAMESPACE_BEGIN // Provided by libcrypto, called from BCM // CRYPTO_init_sysrand initializes long-lived resources needed to draw entropy // from the operating system, if the operating system requires initialization. -void CRYPTO_init_sysrand(void); +void CRYPTO_init_sysrand(); -// CRYPTO_sysrand fills |len| bytes at |buf| with entropy from the operating +// CRYPTO_sysrand fills `len` bytes at `buf` with entropy from the operating // system. void CRYPTO_sysrand(uint8_t *buf, size_t len); -// CRYPTO_sysrand_if_available fills |len| bytes at |buf| with entropy from the -// operating system, or early /dev/urandom data, and returns 1, _if_ the entropy -// pool is initialized or if getrandom() is not available and not in FIPS mode. -// Otherwise it will not block and will instead fill |buf| with all zeros and -// return 0. -int CRYPTO_sysrand_if_available(uint8_t *buf, size_t len); - -// CRYPTO_sysrand_for_seed fills |len| bytes at |buf| with entropy from the -// operating system. It may draw from the |GRND_RANDOM| pool on Android, -// depending on the vendor's configuration. -void CRYPTO_sysrand_for_seed(uint8_t *buf, size_t len); - -// RAND_need_entropy is called whenever the BCM module has stopped because it -// has run out of entropy. -void RAND_need_entropy(size_t bytes_needed); - // crypto_get_fork_generation returns the fork generation number for the current // process, or zero if not supported on the platform. The fork generation number // is a non-zero, strictly-monotonic counter with the property that, if queried @@ -98,9 +44,9 @@ void RAND_need_entropy(size_t bytes_needed); // the save fork generation. Note this logic transparently handles platforms // which always return zero. // -// This is not reliably supported on all platforms which implement |fork|, so it +// This is not reliably supported on all platforms which implement `fork`, so it // should only be used as a hardening measure. -OPENSSL_EXPORT uint64_t CRYPTO_get_fork_generation(void); +OPENSSL_EXPORT uint64_t CRYPTO_get_fork_generation(); // CRYPTO_fork_detect_force_madv_wipeonfork_for_testing is an internal detail // used for testing purposes. @@ -109,11 +55,8 @@ OPENSSL_EXPORT void CRYPTO_fork_detect_force_madv_wipeonfork_for_testing( // CRYPTO_get_stderr returns stderr. This function exists to avoid BCM needing // a data dependency on libc. -FILE *CRYPTO_get_stderr(void); +FILE *CRYPTO_get_stderr(); - -#if defined(__cplusplus) -} // extern C -#endif +BSSL_NAMESPACE_END #endif // OPENSSL_HEADER_CRYPTO_BCM_SUPPORT_H diff --git a/Sources/CNIOBoringSSL/crypto/bio/bio.cc b/Sources/CNIOBoringSSL/crypto/bio/bio.cc index 86c3fc46..5b148a1c 100644 --- a/Sources/CNIOBoringSSL/crypto/bio/bio.cc +++ b/Sources/CNIOBoringSSL/crypto/bio/bio.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,58 +19,58 @@ #include #include +#include +#include + #include #include #include -#include +#include #include "../internal.h" +#include "../mem_internal.h" +#include "internal.h" -static CRYPTO_EX_DATA_CLASS g_ex_data_class = - CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA; +using namespace bssl; + +static ExDataClass g_ex_data_class(/*with_app_data=*/true); + +Bio::Bio(const BIO_METHOD *m) : RefCounted(CheckSubClass()), method(m) { + CRYPTO_new_ex_data(&ex_data); +} BIO *BIO_new(const BIO_METHOD *method) { - BIO *ret = reinterpret_cast(OPENSSL_zalloc(sizeof(BIO))); - if (ret == NULL) { - return NULL; + UniquePtr ret(New(method)); + if (ret == nullptr) { + return nullptr; } - ret->method = method; - ret->shutdown = 1; - ret->references = 1; - CRYPTO_new_ex_data(&ret->ex_data); - - if (method->create != NULL && !method->create(ret)) { - OPENSSL_free(ret); - return NULL; + if (method->create != nullptr && !method->create(ret.get())) { + return nullptr; } - return ret; + return ret.release(); +} + +Bio::~Bio() { + BIO *next = BIO_pop(this); + if (method->destroy != nullptr) { + method->destroy(this); + } + CRYPTO_free_ex_data(&g_ex_data_class, &ex_data); + BIO_free(next); } int BIO_free(BIO *bio) { - BIO *next_bio; - - for (; bio != NULL; bio = next_bio) { - if (!CRYPTO_refcount_dec_and_test_zero(&bio->references)) { - return 0; - } - - next_bio = BIO_pop(bio); - - if (bio->method != NULL && bio->method->destroy != NULL) { - bio->method->destroy(bio); - } - - CRYPTO_free_ex_data(&g_ex_data_class, bio, &bio->ex_data); - OPENSSL_free(bio); + if (bio == nullptr) { + return 1; } - return 1; + return FromOpaque(bio)->DecRefInternal(); } int BIO_up_ref(BIO *bio) { - CRYPTO_refcount_inc(&bio->references); + FromOpaque(bio)->UpRefInternal(); return 1; } @@ -74,71 +79,108 @@ void BIO_vfree(BIO *bio) { BIO_free(bio); } void BIO_free_all(BIO *bio) { BIO_free(bio); } int BIO_read(BIO *bio, void *buf, int len) { - if (bio == NULL || bio->method == NULL || bio->method->bread == NULL) { + auto *impl = FromOpaque(bio); + if (impl == nullptr || impl->method->bread == nullptr) { OPENSSL_PUT_ERROR(BIO, BIO_R_UNSUPPORTED_METHOD); - return -2; + return -1; } - if (!bio->init) { + if (!impl->init) { OPENSSL_PUT_ERROR(BIO, BIO_R_UNINITIALIZED); - return -2; + return -1; } if (len <= 0) { return 0; } - int ret = bio->method->bread(bio, reinterpret_cast(buf), len); + int ret = impl->method->bread(impl, reinterpret_cast(buf), len); if (ret > 0) { - bio->num_read += ret; + impl->num_read += ret; + } else if (ret < 0) { + // In preparation for |BIO_read_ex|, canonicalize error returns to -1. + ret = -1; } return ret; } int BIO_gets(BIO *bio, char *buf, int len) { - if (bio == NULL || bio->method == NULL || bio->method->bgets == NULL) { + auto *impl = FromOpaque(bio); + if (impl == nullptr || impl->method->bgets == nullptr) { OPENSSL_PUT_ERROR(BIO, BIO_R_UNSUPPORTED_METHOD); - return -2; + return -1; } - if (!bio->init) { + if (!impl->init) { OPENSSL_PUT_ERROR(BIO, BIO_R_UNINITIALIZED); - return -2; + return -1; } if (len <= 0) { return 0; } - int ret = bio->method->bgets(bio, buf, len); + int ret = impl->method->bgets(impl, buf, len); if (ret > 0) { - bio->num_read += ret; + impl->num_read += ret; } return ret; } -int BIO_write(BIO *bio, const void *in, int inl) { - if (bio == NULL || bio->method == NULL || bio->method->bwrite == NULL) { +int BIO_write_ex(BIO *bio, const void *data, size_t len, size_t *out_written) { + if (out_written != nullptr) { + *out_written = 0; + } + auto *impl = FromOpaque(bio); + if (impl == nullptr || + (impl->method->bwrite == nullptr && impl->method->bwrite_ex == nullptr)) { OPENSSL_PUT_ERROR(BIO, BIO_R_UNSUPPORTED_METHOD); - return -2; - } - if (!bio->init) { - OPENSSL_PUT_ERROR(BIO, BIO_R_UNINITIALIZED); - return -2; - } - if (inl <= 0) { return 0; } - int ret = bio->method->bwrite(bio, reinterpret_cast(in), inl); - if (ret > 0) { - bio->num_write += ret; + if (!impl->init) { + OPENSSL_PUT_ERROR(BIO, BIO_R_UNINITIALIZED); + return 0; } - return ret; -} - -int BIO_write_all(BIO *bio, const void *data, size_t len) { - const uint8_t *data_u8 = reinterpret_cast(data); - while (len > 0) { - int ret = BIO_write(bio, data_u8, len > INT_MAX ? INT_MAX : (int)len); + // Matching OpenSSL, writing zero bytes should "successfully" write no bytes. + if (len == 0) { + return 1; + } + // Support `BIO_METHOD`s using either the old or new API. + size_t written; + if (impl->method->bwrite_ex != nullptr) { + if (!impl->method->bwrite_ex(bio, static_cast(data), len, + &written)) { + return 0; + } + } else { + int ret = + impl->method->bwrite(impl, static_cast(data), + static_cast(std::min(len, size_t{INT_MAX}))); if (ret <= 0) { return 0; } - data_u8 += ret; - len -= ret; + written = static_cast(ret); + } + impl->num_write += written; + if (out_written != nullptr) { + *out_written = written; + } + return 1; +} + +int BIO_write(BIO *bio, const void *in, int inl) { + // Matching OpenSSL, `inl <= 0` returns zero, i.e. a "successful" write of + // zero bytes. + inl = std::max(inl, 0); + size_t written; + if (!BIO_write_ex(bio, in, static_cast(inl), &written)) { + return -1; + } + return static_cast(written); +} + +int BIO_write_all(BIO *bio, const void *data, size_t len) { + auto span = Span(reinterpret_cast(data), len); + while (!span.empty()) { + size_t written; + if (!BIO_write_ex(bio, span.data(), span.size(), &written)) { + return 0; + } + span = span.subspan(written); } return 1; } @@ -146,33 +188,36 @@ int BIO_write_all(BIO *bio, const void *data, size_t len) { int BIO_puts(BIO *bio, const char *in) { size_t len = strlen(in); if (len > INT_MAX) { - // |BIO_write| and the return value both assume the string fits in |int|. + // `BIO_write` and the return value both assume the string fits in `int`. OPENSSL_PUT_ERROR(BIO, ERR_R_OVERFLOW); return -1; } return BIO_write(bio, in, (int)len); } -int BIO_flush(BIO *bio) { return (int)BIO_ctrl(bio, BIO_CTRL_FLUSH, 0, NULL); } +int BIO_flush(BIO *bio) { + return (int)BIO_ctrl(bio, BIO_CTRL_FLUSH, 0, nullptr); +} long BIO_ctrl(BIO *bio, int cmd, long larg, void *parg) { - if (bio == NULL) { + auto *impl = FromOpaque(bio); + if (impl == nullptr) { return 0; } - if (bio->method == NULL || bio->method->ctrl == NULL) { + if (impl->method->ctrl == nullptr) { OPENSSL_PUT_ERROR(BIO, BIO_R_UNSUPPORTED_METHOD); - return -2; + return -1; } - return bio->method->ctrl(bio, cmd, larg, parg); + return impl->method->ctrl(impl, cmd, larg, parg); } char *BIO_ptr_ctrl(BIO *b, int cmd, long larg) { - char *p = NULL; + char *p = nullptr; if (BIO_ctrl(b, cmd, larg, (void *)&p) <= 0) { - return NULL; + return nullptr; } return p; @@ -184,13 +229,17 @@ long BIO_int_ctrl(BIO *b, int cmd, long larg, int iarg) { return BIO_ctrl(b, cmd, larg, (void *)&i); } -int BIO_reset(BIO *bio) { return (int)BIO_ctrl(bio, BIO_CTRL_RESET, 0, NULL); } +int BIO_reset(BIO *bio) { + return (int)BIO_ctrl(bio, BIO_CTRL_RESET, 0, nullptr); +} -int BIO_eof(BIO *bio) { return (int)BIO_ctrl(bio, BIO_CTRL_EOF, 0, NULL); } +int BIO_eof(BIO *bio) { return (int)BIO_ctrl(bio, BIO_CTRL_EOF, 0, nullptr); } -void BIO_set_flags(BIO *bio, int flags) { bio->flags |= flags; } +void BIO_set_flags(BIO *bio, int flags) { FromOpaque(bio)->flags |= flags; } -int BIO_test_flags(const BIO *bio, int flags) { return bio->flags & flags; } +int BIO_test_flags(const BIO *bio, int flags) { + return FromOpaque(bio)->flags & flags; +} int BIO_should_read(const BIO *bio) { return BIO_test_flags(bio, BIO_FLAGS_READ); @@ -208,52 +257,67 @@ int BIO_should_io_special(const BIO *bio) { return BIO_test_flags(bio, BIO_FLAGS_IO_SPECIAL); } -int BIO_get_retry_reason(const BIO *bio) { return bio->retry_reason; } +int BIO_get_retry_reason(const BIO *bio) { + return FromOpaque(bio)->retry_reason; +} -void BIO_set_retry_reason(BIO *bio, int reason) { bio->retry_reason = reason; } +void BIO_set_retry_reason(BIO *bio, int reason) { + FromOpaque(bio)->retry_reason = reason; +} -void BIO_clear_flags(BIO *bio, int flags) { bio->flags &= ~flags; } +void BIO_clear_flags(BIO *bio, int flags) { FromOpaque(bio)->flags &= ~flags; } void BIO_set_retry_read(BIO *bio) { - bio->flags |= BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY; + FromOpaque(bio)->flags |= BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY; } void BIO_set_retry_write(BIO *bio) { - bio->flags |= BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY; + FromOpaque(bio)->flags |= BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY; +} + +void BIO_set_retry_special(BIO *bio) { + FromOpaque(bio)->flags |= BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY; } static const int kRetryFlags = BIO_FLAGS_RWS | BIO_FLAGS_SHOULD_RETRY; -int BIO_get_retry_flags(BIO *bio) { return bio->flags & kRetryFlags; } +int BIO_get_retry_flags(BIO *bio) { + return FromOpaque(bio)->flags & kRetryFlags; +} void BIO_clear_retry_flags(BIO *bio) { - bio->flags &= ~kRetryFlags; - bio->retry_reason = 0; + auto *impl = FromOpaque(bio); + impl->flags &= ~kRetryFlags; + impl->retry_reason = 0; } -int BIO_method_type(const BIO *bio) { return bio->method->type; } +int BIO_method_type(const BIO *bio) { + return FromOpaque(bio)->method->type; +} void BIO_copy_next_retry(BIO *bio) { - BIO_clear_retry_flags(bio); - BIO_set_flags(bio, BIO_get_retry_flags(bio->next_bio)); - bio->retry_reason = bio->next_bio->retry_reason; + auto *impl = FromOpaque(bio); + BIO_clear_retry_flags(impl); + BIO_set_flags(impl, BIO_get_retry_flags(impl->next_bio)); + impl->retry_reason = impl->next_bio->retry_reason; } -long BIO_callback_ctrl(BIO *bio, int cmd, bio_info_cb fp) { - if (bio == NULL) { +long BIO_callback_ctrl(BIO *bio, int cmd, BIO_info_cb *fp) { + auto *impl = FromOpaque(bio); + if (impl == nullptr) { return 0; } - if (bio->method == NULL || bio->method->callback_ctrl == NULL) { + if (impl->method->callback_ctrl == nullptr) { OPENSSL_PUT_ERROR(BIO, BIO_R_UNSUPPORTED_METHOD); return 0; } - return bio->method->callback_ctrl(bio, cmd, fp); + return impl->method->callback_ctrl(impl, cmd, fp); } size_t BIO_pending(const BIO *bio) { - const long r = BIO_ctrl((BIO *)bio, BIO_CTRL_PENDING, 0, NULL); + const long r = BIO_ctrl(const_cast(bio), BIO_CTRL_PENDING, 0, nullptr); assert(r >= 0); if (r < 0) { @@ -265,7 +329,8 @@ size_t BIO_pending(const BIO *bio) { size_t BIO_ctrl_pending(const BIO *bio) { return BIO_pending(bio); } size_t BIO_wpending(const BIO *bio) { - const long r = BIO_ctrl((BIO *)bio, BIO_CTRL_WPENDING, 0, NULL); + const long r = + BIO_ctrl(const_cast(bio), BIO_CTRL_WPENDING, 0, nullptr); assert(r >= 0); if (r < 0) { @@ -275,75 +340,62 @@ size_t BIO_wpending(const BIO *bio) { } int BIO_set_close(BIO *bio, int close_flag) { - return (int)BIO_ctrl(bio, BIO_CTRL_SET_CLOSE, close_flag, NULL); + return (int)BIO_ctrl(bio, BIO_CTRL_SET_CLOSE, close_flag, nullptr); } -OPENSSL_EXPORT uint64_t BIO_number_read(const BIO *bio) { - return bio->num_read; -} +uint64_t BIO_number_read(const BIO *bio) { return FromOpaque(bio)->num_read; } -OPENSSL_EXPORT uint64_t BIO_number_written(const BIO *bio) { - return bio->num_write; +uint64_t BIO_number_written(const BIO *bio) { + return FromOpaque(bio)->num_write; } BIO *BIO_push(BIO *bio, BIO *appended_bio) { - BIO *last_bio; - - if (bio == NULL) { + if (bio == nullptr) { return bio; } - last_bio = bio; - while (last_bio->next_bio != NULL) { + Bio *last_bio = FromOpaque(bio); + while (last_bio->next_bio != nullptr) { last_bio = last_bio->next_bio; } - last_bio->next_bio = appended_bio; + last_bio->next_bio = FromOpaque(appended_bio); return bio; } BIO *BIO_pop(BIO *bio) { - BIO *ret; - - if (bio == NULL) { - return NULL; + if (bio == nullptr) { + return nullptr; } - ret = bio->next_bio; - bio->next_bio = NULL; - return ret; + return std::exchange(FromOpaque(bio)->next_bio, nullptr); } BIO *BIO_next(BIO *bio) { if (!bio) { - return NULL; + return nullptr; } - return bio->next_bio; + return FromOpaque(bio)->next_bio; } BIO *BIO_find_type(BIO *bio, int type) { - int method_type, mask; - if (!bio) { - return NULL; + return nullptr; } - mask = type & 0xff; + int mask = type & 0xff; do { - if (bio->method != NULL) { - method_type = bio->method->type; - - if (!mask) { - if (method_type & type) { - return bio; - } - } else if (method_type == type) { + int method_type = BIO_method_type(bio); + if (!mask) { + if (method_type & type) { return bio; } + } else if (method_type == type) { + return bio; } - bio = bio->next_bio; - } while (bio != NULL); + bio = BIO_next(bio); + } while (bio != nullptr); - return NULL; + return nullptr; } int BIO_indent(BIO *bio, unsigned indent, unsigned max_indent) { @@ -365,15 +417,15 @@ static int print_bio(const char *str, size_t len, void *bio) { void ERR_print_errors(BIO *bio) { ERR_print_errors_cb(print_bio, bio); } -// bio_read_all reads everything from |bio| and prepends |prefix| to it. On -// success, |*out| is set to an allocated buffer (which should be freed with -// |OPENSSL_free|), |*out_len| is set to its length and one is returned. The -// buffer will contain |prefix| followed by the contents of |bio|. On failure, +// bio_read_all reads everything from `bio` and prepends `prefix` to it. On +// success, `*out` is set to an allocated buffer (which should be freed with +// `OPENSSL_free`), `*out_len` is set to its length and one is returned. The +// buffer will contain `prefix` followed by the contents of `bio`. On failure, // zero is returned. // // The function will fail if the size of the output would equal or exceed -// |max_len|. -static int bio_read_all(BIO *bio, uint8_t **out, size_t *out_len, +// `max_len`. +static int bio_read_all(Bio *bio, uint8_t **out, size_t *out_len, const uint8_t *prefix, size_t prefix_len, size_t max_len) { static const size_t kChunkSize = 4096; @@ -386,7 +438,7 @@ static int bio_read_all(BIO *bio, uint8_t **out, size_t *out_len, return 0; } *out = reinterpret_cast(OPENSSL_malloc(len)); - if (*out == NULL) { + if (*out == nullptr) { return 0; } OPENSSL_memcpy(*out, prefix, prefix_len); @@ -405,7 +457,7 @@ static int bio_read_all(BIO *bio, uint8_t **out, size_t *out_len, if (n == 0) { *out_len = done; return 1; - } else if (n == -1) { + } else if (n < 0) { OPENSSL_free(*out); return 0; } @@ -418,7 +470,7 @@ static int bio_read_all(BIO *bio, uint8_t **out, size_t *out_len, } uint8_t *new_buf = reinterpret_cast(OPENSSL_realloc(*out, len)); - if (new_buf == NULL) { + if (new_buf == nullptr) { OPENSSL_free(*out); return 0; } @@ -427,19 +479,19 @@ static int bio_read_all(BIO *bio, uint8_t **out, size_t *out_len, } } -// bio_read_full reads |len| bytes |bio| and writes them into |out|. It -// tolerates partial reads from |bio| and returns one on success or zero if a -// read fails before |len| bytes are read. On failure, it additionally sets -// |*out_eof_on_first_read| to whether the error was due to |bio| returning zero -// on the first read. |out_eof_on_first_read| may be NULL to discard the value. -static int bio_read_full(BIO *bio, uint8_t *out, int *out_eof_on_first_read, +// bio_read_full reads `len` bytes `bio` and writes them into `out`. It +// tolerates partial reads from `bio` and returns one on success or zero if a +// read fails before `len` bytes are read. On failure, it additionally sets +// `*out_eof_on_first_read` to whether the error was due to `bio` returning zero +// on the first read. `out_eof_on_first_read` may be NULL to discard the value. +static int bio_read_full(Bio *bio, uint8_t *out, int *out_eof_on_first_read, size_t len) { int first_read = 1; while (len > 0) { int todo = len <= INT_MAX ? (int)len : INT_MAX; int ret = BIO_read(bio, out, todo); if (ret <= 0) { - if (out_eof_on_first_read != NULL) { + if (out_eof_on_first_read != nullptr) { *out_eof_on_first_read = first_read && ret == 0; } return 0; @@ -452,8 +504,8 @@ static int bio_read_full(BIO *bio, uint8_t *out, int *out_eof_on_first_read, return 1; } -// For compatibility with existing |d2i_*_bio| callers, |BIO_read_asn1| uses -// |ERR_LIB_ASN1| errors. +// For compatibility with existing `d2i_*_bio` callers, `BIO_read_asn1` uses +// `ERR_LIB_ASN1` errors. OPENSSL_DECLARE_ERROR_REASON(ASN1, ASN1_R_DECODE_ERROR) OPENSSL_DECLARE_ERROR_REASON(ASN1, ASN1_R_HEADER_TOO_LONG) OPENSSL_DECLARE_ERROR_REASON(ASN1, ASN1_R_NOT_ENOUGH_DATA) @@ -464,11 +516,12 @@ int BIO_read_asn1(BIO *bio, uint8_t **out, size_t *out_len, size_t max_len) { static const size_t kInitialHeaderLen = 2; int eof_on_first_read; - if (!bio_read_full(bio, header, &eof_on_first_read, kInitialHeaderLen)) { + auto *impl = FromOpaque(bio); + if (!bio_read_full(impl, header, &eof_on_first_read, kInitialHeaderLen)) { if (eof_on_first_read) { - // Historically, OpenSSL returned |ASN1_R_HEADER_TOO_LONG| when - // |d2i_*_bio| could not read anything. CPython conditions on this to - // determine if |bio| was empty. + // Historically, OpenSSL returned `ASN1_R_HEADER_TOO_LONG` when + // `d2i_*_bio` could not read anything. CPython conditions on this to + // determine if `bio` was empty. OPENSSL_PUT_ERROR(ASN1, ASN1_R_HEADER_TOO_LONG); } else { OPENSSL_PUT_ERROR(ASN1, ASN1_R_NOT_ENOUGH_DATA); @@ -495,7 +548,7 @@ int BIO_read_asn1(BIO *bio, uint8_t **out, size_t *out_len, size_t max_len) { if ((tag & 0x20 /* constructed */) != 0 && num_bytes == 0) { // indefinite length. - if (!bio_read_all(bio, out, out_len, header, kInitialHeaderLen, + if (!bio_read_all(impl, out, out_len, header, kInitialHeaderLen, max_len)) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_NOT_ENOUGH_DATA); return 0; @@ -508,7 +561,7 @@ int BIO_read_asn1(BIO *bio, uint8_t **out, size_t *out_len, size_t max_len) { return 0; } - if (!bio_read_full(bio, header + kInitialHeaderLen, NULL, num_bytes)) { + if (!bio_read_full(impl, header + kInitialHeaderLen, nullptr, num_bytes)) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_NOT_ENOUGH_DATA); return 0; } @@ -543,11 +596,11 @@ int BIO_read_asn1(BIO *bio, uint8_t **out, size_t *out_len, size_t max_len) { *out_len = len; *out = reinterpret_cast(OPENSSL_malloc(len)); - if (*out == NULL) { + if (*out == nullptr) { return 0; } OPENSSL_memcpy(*out, header, header_len); - if (!bio_read_full(bio, (*out) + header_len, NULL, len - header_len)) { + if (!bio_read_full(impl, (*out) + header_len, nullptr, len - header_len)) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_NOT_ENOUGH_DATA); OPENSSL_free(*out); return 0; @@ -556,35 +609,28 @@ int BIO_read_asn1(BIO *bio, uint8_t **out, size_t *out_len, size_t max_len) { return 1; } -void BIO_set_retry_special(BIO *bio) { - bio->flags |= BIO_FLAGS_READ | BIO_FLAGS_IO_SPECIAL; -} - int BIO_set_write_buffer_size(BIO *bio, int buffer_size) { return 0; } -static CRYPTO_MUTEX g_index_lock = CRYPTO_MUTEX_INIT; +static StaticMutex g_index_lock; static int g_index = BIO_TYPE_START; -int BIO_get_new_index(void) { - CRYPTO_MUTEX_lock_write(&g_index_lock); - // If |g_index| exceeds 255, it will collide with the flags bits. +int BIO_get_new_index() { + MutexWriteLock lock(&g_index_lock); + // If `g_index` exceeds 255, it will collide with the flags bits. int ret = g_index > 255 ? -1 : g_index++; - CRYPTO_MUTEX_unlock_write(&g_index_lock); return ret; } BIO_METHOD *BIO_meth_new(int type, const char *name) { - BIO_METHOD *method = - reinterpret_cast(OPENSSL_zalloc(sizeof(BIO_METHOD))); - if (method == NULL) { - return NULL; + BIO_METHOD *method = New(); + if (method == nullptr) { + return nullptr; } method->type = type; - method->name = name; return method; } -void BIO_meth_free(BIO_METHOD *method) { OPENSSL_free(method); } +void BIO_meth_free(BIO_METHOD *method) { Delete(method); } int BIO_meth_set_create(BIO_METHOD *method, int (*create_func)(BIO *)) { method->create = create_func; @@ -596,6 +642,13 @@ int BIO_meth_set_destroy(BIO_METHOD *method, int (*destroy_func)(BIO *)) { return 1; } +int BIO_meth_set_write_ex(BIO_METHOD *method, + int (*write_ex_func)(BIO *, const char *, size_t, + size_t *)) { + method->bwrite_ex = write_ex_func; + return 1; +} + int BIO_meth_set_write(BIO_METHOD *method, int (*write_func)(BIO *, const char *, int)) { method->bwrite = write_func; @@ -620,20 +673,29 @@ int BIO_meth_set_ctrl(BIO_METHOD *method, return 1; } -void BIO_set_data(BIO *bio, void *ptr) { bio->ptr = ptr; } +int BIO_meth_set_callback_ctrl(BIO_METHOD *method, + long (*callback_ctrl_func)(BIO *, int, + BIO_info_cb *)) { + method->callback_ctrl = callback_ctrl_func; + return 1; +} -void *BIO_get_data(BIO *bio) { return bio->ptr; } +void BIO_set_data(BIO *bio, void *ptr) { FromOpaque(bio)->ptr = ptr; } -void BIO_set_init(BIO *bio, int init) { bio->init = init; } +void *BIO_get_data(BIO *bio) { return FromOpaque(bio)->ptr; } -int BIO_get_init(BIO *bio) { return bio->init; } +void BIO_set_init(BIO *bio, int init) { FromOpaque(bio)->init = init; } -void BIO_set_shutdown(BIO *bio, int shutdown) { bio->shutdown = shutdown; } +int BIO_get_init(BIO *bio) { return FromOpaque(bio)->init; } -int BIO_get_shutdown(BIO *bio) { return bio->shutdown; } +void BIO_set_shutdown(BIO *bio, int shutdown) { + FromOpaque(bio)->shutdown = shutdown; +} + +int BIO_get_shutdown(BIO *bio) { return FromOpaque(bio)->shutdown; } int BIO_meth_set_puts(BIO_METHOD *method, int (*puts)(BIO *, const char *)) { - // Ignore the parameter. We implement |BIO_puts| using |BIO_write|. + // Ignore the parameter. We implement `BIO_puts` using `BIO_write`. return 1; } @@ -645,9 +707,9 @@ int BIO_get_ex_new_index(long argl, void *argp, // } int BIO_set_ex_data(BIO *bio, int idx, void *data) { - return CRYPTO_set_ex_data(&bio->ex_data, idx, data); + return CRYPTO_set_ex_data(&FromOpaque(bio)->ex_data, idx, data); } void *BIO_get_ex_data(const BIO *bio, int idx) { - return CRYPTO_get_ex_data(&bio->ex_data, idx); + return CRYPTO_get_ex_data(&FromOpaque(bio)->ex_data, idx); } diff --git a/Sources/CNIOBoringSSL/crypto/bio/bio_mem.cc b/Sources/CNIOBoringSSL/crypto/bio/bio_mem.cc index 9632715c..694a853b 100644 --- a/Sources/CNIOBoringSSL/crypto/bio/bio_mem.cc +++ b/Sources/CNIOBoringSSL/crypto/bio/bio_mem.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,8 +22,11 @@ #include #include "../internal.h" +#include "internal.h" +using namespace bssl; + BIO *BIO_new_mem_buf(const void *buf, ossl_ssize_t len) { BIO *ret; BUF_MEM *b; @@ -26,26 +34,26 @@ BIO *BIO_new_mem_buf(const void *buf, ossl_ssize_t len) { if (!buf && len != 0) { OPENSSL_PUT_ERROR(BIO, BIO_R_NULL_PARAMETER); - return NULL; + return nullptr; } ret = BIO_new(BIO_s_mem()); - if (ret == NULL) { - return NULL; + if (ret == nullptr) { + return nullptr; } - b = (BUF_MEM *)ret->ptr; - // BIO_FLAGS_MEM_RDONLY ensures |b->data| is not written to. + b = (BUF_MEM *)BIO_get_data(ret); + // BIO_FLAGS_MEM_RDONLY ensures `b->data` is not written to. b->data = reinterpret_cast(const_cast(buf)); b->length = size; b->max = size; - ret->flags |= BIO_FLAGS_MEM_RDONLY; + BIO_set_flags(ret, BIO_FLAGS_MEM_RDONLY); - // |num| is used to store the value that this BIO will return when it runs + // `num` is used to store the value that this BIO will return when it runs // out of data. If it's negative then the retry flags will also be set. Since - // this is static data, retrying wont help - ret->num = 0; + // this is static data, retrying won't help + FromOpaque(ret)->num = 0; return ret; } @@ -54,41 +62,38 @@ static int mem_new(BIO *bio) { BUF_MEM *b; b = BUF_MEM_new(); - if (b == NULL) { + if (b == nullptr) { return 0; } - // |shutdown| is used to store the close flag: whether the BIO has ownership + // `shutdown` is used to store the close flag: whether the BIO has ownership // of the BUF_MEM. - bio->shutdown = 1; - bio->init = 1; - bio->num = -1; - bio->ptr = (char *)b; + BIO_set_shutdown(bio, 1); + BIO_set_init(bio, 1); + FromOpaque(bio)->num = -1; + BIO_set_data(bio, (char *)b); return 1; } static int mem_free(BIO *bio) { - if (!bio->shutdown || !bio->init || bio->ptr == NULL) { + if (!BIO_get_shutdown(bio) || !BIO_get_init(bio) || + BIO_get_data(bio) == nullptr) { return 1; } - BUF_MEM *b = (BUF_MEM *)bio->ptr; - if (bio->flags & BIO_FLAGS_MEM_RDONLY) { - b->data = NULL; + BUF_MEM *b = (BUF_MEM *)BIO_get_data(bio); + if (BIO_test_flags(bio, BIO_FLAGS_MEM_RDONLY)) { + b->data = nullptr; } BUF_MEM_free(b); - bio->ptr = NULL; + BIO_set_data(bio, nullptr); return 1; } static int mem_read(BIO *bio, char *out, int outl) { BIO_clear_retry_flags(bio); - if (outl <= 0) { - return 0; - } - - BUF_MEM *b = reinterpret_cast(bio->ptr); + BUF_MEM *b = reinterpret_cast(BIO_get_data(bio)); int ret = outl; if ((size_t)ret > b->length) { ret = (int)b->length; @@ -97,13 +102,13 @@ static int mem_read(BIO *bio, char *out, int outl) { if (ret > 0) { OPENSSL_memcpy(out, b->data, ret); b->length -= ret; - if (bio->flags & BIO_FLAGS_MEM_RDONLY) { + if (BIO_test_flags(bio, BIO_FLAGS_MEM_RDONLY)) { b->data += ret; } else { OPENSSL_memmove(b->data, &b->data[ret], b->length); } } else if (b->length == 0) { - ret = bio->num; + ret = FromOpaque(bio)->num; if (ret != 0) { BIO_set_retry_read(bio); } @@ -111,23 +116,20 @@ static int mem_read(BIO *bio, char *out, int outl) { return ret; } -static int mem_write(BIO *bio, const char *in, int inl) { +static int mem_write_ex(BIO *bio, const char *in, size_t inl, + size_t *out_written) { BIO_clear_retry_flags(bio); - if (inl <= 0) { - return 0; // Successfully write zero bytes. - } - - if (bio->flags & BIO_FLAGS_MEM_RDONLY) { + if (BIO_test_flags(bio, BIO_FLAGS_MEM_RDONLY)) { OPENSSL_PUT_ERROR(BIO, BIO_R_WRITE_TO_READ_ONLY_BIO); - return -1; + return 0; } - BUF_MEM *b = reinterpret_cast(bio->ptr); + BUF_MEM *b = reinterpret_cast(BIO_get_data(bio)); if (!BUF_MEM_append(b, in, inl)) { - return -1; + return 0; } - - return inl; + *out_written = inl; + return 1; } static int mem_gets(BIO *bio, char *buf, int size) { @@ -138,7 +140,7 @@ static int mem_gets(BIO *bio, char *buf, int size) { // The buffer size includes space for the trailing NUL, so we can read at most // one fewer byte. - BUF_MEM *b = reinterpret_cast(bio->ptr); + BUF_MEM *b = reinterpret_cast(BIO_get_data(bio)); int ret = size - 1; if ((size_t)ret > b->length) { ret = (int)b->length; @@ -147,7 +149,7 @@ static int mem_gets(BIO *bio, char *buf, int size) { // Stop at the first newline. const char *newline = reinterpret_cast(OPENSSL_memchr(b->data, '\n', ret)); - if (newline != NULL) { + if (newline != nullptr) { ret = (int)(newline - b->data + 1); } @@ -159,15 +161,12 @@ static int mem_gets(BIO *bio, char *buf, int size) { } static long mem_ctrl(BIO *bio, int cmd, long num, void *ptr) { - long ret = 1; - - BUF_MEM *b = (BUF_MEM *)bio->ptr; - + BUF_MEM *b = static_cast(BIO_get_data(bio)); switch (cmd) { case BIO_CTRL_RESET: - if (b->data != NULL) { + if (b->data != nullptr) { // For read only case reset to the start again - if (bio->flags & BIO_FLAGS_MEM_RDONLY) { + if (BIO_test_flags(bio, BIO_FLAGS_MEM_RDONLY)) { b->data -= b->max - b->length; b->length = b->max; } else { @@ -175,72 +174,70 @@ static long mem_ctrl(BIO *bio, int cmd, long num, void *ptr) { b->length = 0; } } - break; + return 1; case BIO_CTRL_EOF: - ret = (long)(b->length == 0); - break; + return b->length == 0; case BIO_C_SET_BUF_MEM_EOF_RETURN: - bio->num = (int)num; - break; + FromOpaque(bio)->num = static_cast(num); + return 1; case BIO_CTRL_INFO: - ret = (long)b->length; - if (ptr != NULL) { - char **pptr = reinterpret_cast(ptr); - *pptr = b->data; + if (ptr != nullptr) { + char **out = reinterpret_cast(ptr); + *out = b->data; } - break; + // This API can overflow on 64-bit Windows, where `long` is smaller than + // `ptrdiff_t`. `BIO_mem_contents` is the overflow-safe API. + return static_cast(b->length); case BIO_C_SET_BUF_MEM: mem_free(bio); - bio->shutdown = (int)num; - bio->ptr = ptr; - break; + BIO_set_shutdown(bio, static_cast(num)); + BIO_set_data(bio, ptr); + return 1; case BIO_C_GET_BUF_MEM_PTR: - if (ptr != NULL) { - BUF_MEM **pptr = reinterpret_cast(ptr); - *pptr = b; + if (ptr != nullptr) { + BUF_MEM **out = reinterpret_cast(ptr); + *out = b; } - break; + return 1; case BIO_CTRL_GET_CLOSE: - ret = (long)bio->shutdown; - break; + return BIO_get_shutdown(bio); case BIO_CTRL_SET_CLOSE: - bio->shutdown = (int)num; - break; - + BIO_set_shutdown(bio, static_cast(num)); + return 1; case BIO_CTRL_WPENDING: - ret = 0L; - break; + return 0; case BIO_CTRL_PENDING: - ret = (long)b->length; - break; + // TODO(crbug.com/412584975): This can overflow on 64-bit Windows. + return static_cast(b->length); case BIO_CTRL_FLUSH: - ret = 1; - break; + return 1; default: - ret = 0; - break; + return 0; } - return ret; } static const BIO_METHOD mem_method = { - BIO_TYPE_MEM, "memory buffer", - mem_write, mem_read, - NULL /* puts */, mem_gets, - mem_ctrl, mem_new, - mem_free, NULL /* callback_ctrl */, + BIO_TYPE_MEM, + /*bwrite=*/nullptr, + mem_write_ex, + mem_read, + mem_gets, + mem_ctrl, + mem_new, + mem_free, + /*callback_ctrl=*/nullptr, }; -const BIO_METHOD *BIO_s_mem(void) { return &mem_method; } +const BIO_METHOD *BIO_s_mem() { return &mem_method; } int BIO_mem_contents(const BIO *bio, const uint8_t **out_contents, size_t *out_len) { const BUF_MEM *b; - if (bio->method != &mem_method) { + if (FromOpaque(bio)->method != &mem_method) { return 0; } - b = (BUF_MEM *)bio->ptr; + b = (BUF_MEM *)BIO_get_data((BIO *)bio); *out_contents = (uint8_t *)b->data; *out_len = b->length; return 1; @@ -259,5 +256,5 @@ int BIO_set_mem_buf(BIO *bio, BUF_MEM *b, int take_ownership) { } int BIO_set_mem_eof_return(BIO *bio, int eof_value) { - return (int)BIO_ctrl(bio, BIO_C_SET_BUF_MEM_EOF_RETURN, eof_value, NULL); + return (int)BIO_ctrl(bio, BIO_C_SET_BUF_MEM_EOF_RETURN, eof_value, nullptr); } diff --git a/Sources/CNIOBoringSSL/crypto/bio/connect.cc b/Sources/CNIOBoringSSL/crypto/bio/connect.cc index bf27293e..b01705c8 100644 --- a/Sources/CNIOBoringSSL/crypto/bio/connect.cc +++ b/Sources/CNIOBoringSSL/crypto/bio/connect.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -13,6 +18,7 @@ #include #include +#include #include #if !defined(OPENSSL_WINDOWS) @@ -21,19 +27,23 @@ #include #include #else -OPENSSL_MSVC_PRAGMA(warning(push, 3)) #include #include -OPENSSL_MSVC_PRAGMA(warning(pop)) #endif +#include +#include + #include #include #include "../internal.h" +#include "../mem_internal.h" #include "internal.h" +using namespace bssl; + enum { BIO_CONN_S_BEFORE, BIO_CONN_S_BLOCKED_CONNECT, @@ -41,46 +51,45 @@ enum { }; namespace { -typedef struct bio_connect_st { - int state; +struct BIO_CONNECT { + int state = BIO_CONN_S_BEFORE; - char *param_hostname; - char *param_port; - int nbio; + UniquePtr param_hostname; + UniquePtr param_port; + int nbio = 0; - unsigned short port; + unsigned short port = 0; - struct sockaddr_storage them; - socklen_t them_length; + sockaddr_storage them; + socklen_t them_length = 0; - // the file descriptor is kept in bio->num in order to match the socket - // BIO. + // The file descriptor is kept in bio->num in order to match the socket BIO. // info_callback is called when the connection is initially made // callback(BIO,state,ret); The callback should return 'ret', state is for // compatibility with the SSL info_callback. - int (*info_callback)(const BIO *bio, int state, int ret); -} BIO_CONNECT; + int (*info_callback)(BIO *bio, int state, int ret) = nullptr; +}; } // namespace #if !defined(OPENSSL_WINDOWS) static int closesocket(int sock) { return close(sock); } #endif -// split_host_and_port sets |*out_host| and |*out_port| to the host and port -// parsed from |name|. It returns one on success or zero on error. Even when -// successful, |*out_port| may be NULL on return if no port was specified. -static int split_host_and_port(char **out_host, char **out_port, - const char *name) { - const char *host, *port = NULL; +// split_host_and_port sets `*out_host` and `*out_port` to the host and port +// parsed from `name`. It returns one on success or zero on error. Even when +// successful, `*out_port` may be NULL on return if no port was specified. +static int split_host_and_port(UniquePtr *out_host, + UniquePtr *out_port, const char *name) { + const char *host, *port = nullptr; size_t host_len = 0; - *out_host = NULL; - *out_port = NULL; + *out_host = nullptr; + *out_port = nullptr; if (name[0] == '[') { // bracketed IPv6 address const char *close = strchr(name, ']'); - if (close == NULL) { + if (close == nullptr) { return 0; } host = name + 1; @@ -92,7 +101,8 @@ static int split_host_and_port(char **out_host, char **out_port, } } else { const char *colon = strchr(name, ':'); - if (colon == NULL || strchr(colon + 1, ':') != NULL) { // IPv6 address + if (colon == nullptr || + strchr(colon + 1, ':') != nullptr) { // IPv6 address host = name; host_len = strlen(name); } else { // host:port @@ -102,18 +112,17 @@ static int split_host_and_port(char **out_host, char **out_port, } } - *out_host = OPENSSL_strndup(host, host_len); - if (*out_host == NULL) { + out_host->reset(OPENSSL_strndup(host, host_len)); + if (*out_host == nullptr) { return 0; } - if (port == NULL) { - *out_port = NULL; + if (port == nullptr) { + *out_port = nullptr; return 1; } - *out_port = OPENSSL_strdup(port); - if (*out_port == NULL) { - OPENSSL_free(*out_host); - *out_host = NULL; + out_port->reset(OPENSSL_strdup(port)); + if (*out_port == nullptr) { + *out_host = nullptr; return 0; } return 1; @@ -121,9 +130,9 @@ static int split_host_and_port(char **out_host, char **out_port, static int conn_state(BIO *bio, BIO_CONNECT *c) { int ret = -1, i; - int (*cb)(const BIO *, int, int) = NULL; + int (*cb)(BIO *, int, int) = nullptr; - if (c->info_callback != NULL) { + if (c->info_callback != nullptr) { cb = c->info_callback; } @@ -134,67 +143,66 @@ static int conn_state(BIO *bio, BIO_CONNECT *c) { // exactly what they say. If there is only a hostname, try // (just once) to split it into a hostname and port. - if (c->param_hostname == NULL) { + if (c->param_hostname == nullptr) { OPENSSL_PUT_ERROR(BIO, BIO_R_NO_HOSTNAME_SPECIFIED); goto exit_loop; } - if (c->param_port == NULL) { - char *host, *port; - if (!split_host_and_port(&host, &port, c->param_hostname) || - port == NULL) { - OPENSSL_free(host); - OPENSSL_free(port); + if (c->param_port == nullptr) { + UniquePtr host, port; + if (!split_host_and_port(&host, &port, c->param_hostname.get()) || + port == nullptr) { OPENSSL_PUT_ERROR(BIO, BIO_R_NO_PORT_SPECIFIED); - ERR_add_error_data(2, "host=", c->param_hostname); + ERR_add_error_data(2, "host=", c->param_hostname.get()); goto exit_loop; } - OPENSSL_free(c->param_port); - c->param_port = port; - OPENSSL_free(c->param_hostname); - c->param_hostname = host; + c->param_port = std::move(port); + c->param_hostname = std::move(host); } if (!bio_ip_and_port_to_socket_and_addr( - &bio->num, &c->them, &c->them_length, c->param_hostname, - c->param_port)) { + &FromOpaque(bio)->num, &c->them, &c->them_length, + c->param_hostname.get(), c->param_port.get())) { OPENSSL_PUT_ERROR(BIO, BIO_R_UNABLE_TO_CREATE_SOCKET); - ERR_add_error_data(4, "host=", c->param_hostname, ":", c->param_port); + ERR_add_error_data(4, "host=", c->param_hostname.get(), ":", + c->param_port.get()); goto exit_loop; } if (c->nbio) { - if (!bio_socket_nbio(bio->num, 1)) { + if (!bio_socket_nbio(FromOpaque(bio)->num, 1)) { OPENSSL_PUT_ERROR(BIO, BIO_R_ERROR_SETTING_NBIO); - ERR_add_error_data(4, "host=", c->param_hostname, ":", - c->param_port); + ERR_add_error_data(4, "host=", c->param_hostname.get(), ":", + c->param_port.get()); goto exit_loop; } } i = 1; - ret = setsockopt(bio->num, SOL_SOCKET, SO_KEEPALIVE, (char *)&i, - sizeof(i)); + ret = setsockopt(FromOpaque(bio)->num, SOL_SOCKET, SO_KEEPALIVE, + (char *)&i, sizeof(i)); if (ret < 0) { OPENSSL_PUT_SYSTEM_ERROR(); OPENSSL_PUT_ERROR(BIO, BIO_R_KEEPALIVE); - ERR_add_error_data(4, "host=", c->param_hostname, ":", c->param_port); + ERR_add_error_data(4, "host=", c->param_hostname.get(), ":", + c->param_port.get()); goto exit_loop; } BIO_clear_retry_flags(bio); - ret = connect(bio->num, (struct sockaddr *)&c->them, c->them_length); + ret = connect(FromOpaque(bio)->num, (struct sockaddr *)&c->them, + c->them_length); if (ret < 0) { if (bio_socket_should_retry(ret)) { - BIO_set_flags(bio, (BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY)); + BIO_set_retry_special(bio); c->state = BIO_CONN_S_BLOCKED_CONNECT; - bio->retry_reason = BIO_RR_CONNECT; + BIO_set_retry_reason(bio, BIO_RR_CONNECT); } else { OPENSSL_PUT_SYSTEM_ERROR(); OPENSSL_PUT_ERROR(BIO, BIO_R_CONNECT_ERROR); - ERR_add_error_data(4, "host=", c->param_hostname, ":", - c->param_port); + ERR_add_error_data(4, "host=", c->param_hostname.get(), ":", + c->param_port.get()); } goto exit_loop; } else { @@ -203,21 +211,19 @@ static int conn_state(BIO *bio, BIO_CONNECT *c) { break; case BIO_CONN_S_BLOCKED_CONNECT: - i = bio_sock_error(bio->num); - if (i) { - if (bio_socket_should_retry(ret)) { - BIO_set_flags(bio, (BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY)); + if (!bio_socket_finish_connect(FromOpaque(bio)->num)) { + if (bio_socket_should_retry(-1)) { + BIO_set_retry_special(bio); c->state = BIO_CONN_S_BLOCKED_CONNECT; - bio->retry_reason = BIO_RR_CONNECT; - ret = -1; + BIO_set_retry_reason(bio, BIO_RR_CONNECT); } else { BIO_clear_retry_flags(bio); OPENSSL_PUT_SYSTEM_ERROR(); OPENSSL_PUT_ERROR(BIO, BIO_R_NBIO_CONNECT_ERROR); - ERR_add_error_data(4, "host=", c->param_hostname, ":", - c->param_port); - ret = 0; + ERR_add_error_data(4, "host=", c->param_hostname.get(), ":", + c->param_port.get()); } + ret = -1; goto exit_loop; } else { c->state = BIO_CONN_S_OK; @@ -232,7 +238,7 @@ static int conn_state(BIO *bio, BIO_CONNECT *c) { goto exit_loop; } - if (cb != NULL) { + if (cb != nullptr) { ret = cb((BIO *)bio, c->state, ret); if (ret == 0) { goto end; @@ -241,7 +247,7 @@ static int conn_state(BIO *bio, BIO_CONNECT *c) { } exit_loop: - if (cb != NULL) { + if (cb != nullptr) { ret = cb((BIO *)bio, c->state, ret); } @@ -249,55 +255,35 @@ end: return ret; } -static BIO_CONNECT *BIO_CONNECT_new(void) { - BIO_CONNECT *ret = - reinterpret_cast(OPENSSL_zalloc(sizeof(BIO_CONNECT))); - if (ret == NULL) { - return NULL; - } - ret->state = BIO_CONN_S_BEFORE; - return ret; -} - -static void BIO_CONNECT_free(BIO_CONNECT *c) { - if (c == nullptr) { - return; - } - OPENSSL_free(c->param_hostname); - OPENSSL_free(c->param_port); - OPENSSL_free(c); -} - static int conn_new(BIO *bio) { - bio->init = 0; - bio->num = -1; - bio->flags = 0; - bio->ptr = BIO_CONNECT_new(); - return bio->ptr != NULL; + BIO_set_init(bio, 0); + FromOpaque(bio)->num = -1; + FromOpaque(bio)->flags = 0; + BIO_set_data(bio, New()); + return BIO_get_data(bio) != nullptr; } static void conn_close_socket(BIO *bio) { - BIO_CONNECT *c = (BIO_CONNECT *)bio->ptr; + BIO_CONNECT *c = (BIO_CONNECT *)BIO_get_data(bio); - if (bio->num == -1) { + if (FromOpaque(bio)->num == -1) { return; } // Only do a shutdown if things were established if (c->state == BIO_CONN_S_OK) { - shutdown(bio->num, 2); + shutdown(FromOpaque(bio)->num, 2); } - closesocket(bio->num); - bio->num = -1; + closesocket(FromOpaque(bio)->num); + FromOpaque(bio)->num = -1; } static int conn_free(BIO *bio) { - if (bio->shutdown) { + if (BIO_get_shutdown(bio)) { conn_close_socket(bio); } - BIO_CONNECT_free((BIO_CONNECT *)bio->ptr); - + Delete(static_cast(BIO_get_data(bio))); return 1; } @@ -305,7 +291,7 @@ static int conn_read(BIO *bio, char *out, int out_len) { int ret = 0; BIO_CONNECT *data; - data = (BIO_CONNECT *)bio->ptr; + data = (BIO_CONNECT *)BIO_get_data(bio); if (data->state != BIO_CONN_S_OK) { ret = conn_state(bio, data); if (ret <= 0) { @@ -314,7 +300,7 @@ static int conn_read(BIO *bio, char *out, int out_len) { } bio_clear_socket_error(); - ret = (int)recv(bio->num, out, out_len, 0); + ret = (int)recv(FromOpaque(bio)->num, out, out_len, 0); BIO_clear_retry_flags(bio); if (ret <= 0) { if (bio_socket_should_retry(ret)) { @@ -325,161 +311,132 @@ static int conn_read(BIO *bio, char *out, int out_len) { return ret; } -static int conn_write(BIO *bio, const char *in, int in_len) { - int ret; - BIO_CONNECT *data; - - data = (BIO_CONNECT *)bio->ptr; +static int conn_write_ex(BIO *bio, const char *in, size_t in_len, + size_t *out_written) { + BIO_CONNECT *data = (BIO_CONNECT *)BIO_get_data(bio); if (data->state != BIO_CONN_S_OK) { - ret = conn_state(bio, data); - if (ret <= 0) { - return ret; + if (conn_state(bio, data) <= 0) { + return 0; } } bio_clear_socket_error(); - ret = (int)send(bio->num, in, in_len, 0); +#if defined(OPENSSL_WINDOWS) + in_len = std::min(in_len, size_t{INT_MAX}); + int ret = send(FromOpaque(bio)->num, in, static_cast(in_len), 0); +#else + ssize_t ret = send(FromOpaque(bio)->num, in, in_len, 0); +#endif BIO_clear_retry_flags(bio); if (ret <= 0) { if (bio_socket_should_retry(ret)) { BIO_set_retry_write(bio); } + return 0; } - return ret; + *out_written = ret; + return 1; } static long conn_ctrl(BIO *bio, int cmd, long num, void *ptr) { - int *ip; - long ret = 1; - BIO_CONNECT *data; - - data = (BIO_CONNECT *)bio->ptr; - + BIO_CONNECT *data = static_cast(BIO_get_data(bio)); switch (cmd) { case BIO_CTRL_RESET: - ret = 0; data->state = BIO_CONN_S_BEFORE; conn_close_socket(bio); - bio->flags = 0; - break; + FromOpaque(bio)->flags = 0; + return 0; case BIO_C_DO_STATE_MACHINE: // use this one to start the connection if (data->state != BIO_CONN_S_OK) { - ret = (long)conn_state(bio, data); + return conn_state(bio, data); } else { - ret = 1; + return 1; } - break; case BIO_C_SET_CONNECT: - if (ptr != NULL) { - bio->init = 1; - if (num == 0) { - OPENSSL_free(data->param_hostname); - data->param_hostname = - OPENSSL_strdup(reinterpret_cast(ptr)); - if (data->param_hostname == NULL) { - ret = 0; - } - } else if (num == 1) { - OPENSSL_free(data->param_port); - data->param_port = - OPENSSL_strdup(reinterpret_cast(ptr)); - if (data->param_port == NULL) { - ret = 0; - } - } else { - ret = 0; - } + if (ptr == nullptr) { + return 0; } - break; - case BIO_C_SET_NBIO: - data->nbio = (int)num; - break; - case BIO_C_GET_FD: - if (bio->init) { - ip = (int *)ptr; - if (ip != NULL) { - *ip = bio->num; + BIO_set_init(bio, 1); + if (num == 0) { + data->param_hostname.reset( + OPENSSL_strdup(reinterpret_cast(ptr))); + if (data->param_hostname == nullptr) { + return 0; + } + } else if (num == 1) { + data->param_port.reset( + OPENSSL_strdup(reinterpret_cast(ptr))); + if (data->param_port == nullptr) { + return 0; } - ret = bio->num; } else { - ret = -1; + return 0; + } + return 1; + case BIO_C_SET_NBIO: + data->nbio = static_cast(num); + return 1; + case BIO_C_GET_FD: + if (BIO_get_init(bio)) { + int *out = static_cast(ptr); + if (out != nullptr) { + *out = FromOpaque(bio)->num; + } + return FromOpaque(bio)->num; + } else { + return -1; } - break; case BIO_CTRL_GET_CLOSE: - ret = bio->shutdown; - break; + return BIO_get_shutdown(bio); case BIO_CTRL_SET_CLOSE: - bio->shutdown = (int)num; - break; - case BIO_CTRL_PENDING: - case BIO_CTRL_WPENDING: - ret = 0; - break; + BIO_set_shutdown(bio, static_cast(num)); + return 1; case BIO_CTRL_FLUSH: - break; + return 1; case BIO_CTRL_GET_CALLBACK: { - int (**fptr)(const BIO *bio, int state, int xret); - fptr = reinterpret_cast(ptr); - *fptr = data->info_callback; - } break; + auto out = reinterpret_cast(ptr); + *out = data->info_callback; + return 1; + } default: - ret = 0; - break; + return 0; } - return ret; } -static long conn_callback_ctrl(BIO *bio, int cmd, bio_info_cb fp) { - long ret = 1; - BIO_CONNECT *data; - - data = (BIO_CONNECT *)bio->ptr; - +static long conn_callback_ctrl(BIO *bio, int cmd, BIO_info_cb *fp) { + BIO_CONNECT *data = static_cast(BIO_get_data(bio)); switch (cmd) { case BIO_CTRL_SET_CALLBACK: - // This is the actual type signature of |fp|. The caller is expected to - // cast it to |bio_info_cb| due to the |BIO_callback_ctrl| calling - // convention. - OPENSSL_MSVC_PRAGMA(warning(push)) - OPENSSL_MSVC_PRAGMA(warning(disable : 4191)) - OPENSSL_CLANG_PRAGMA("clang diagnostic push") - OPENSSL_CLANG_PRAGMA( - "clang diagnostic ignored \"-Wunknown-warning-option\"") - OPENSSL_CLANG_PRAGMA("clang diagnostic ignored \"-Wcast-function-type\"") - data->info_callback = (int (*)(const struct bio_st *, int, int))fp; - OPENSSL_CLANG_PRAGMA("clang diagnostic pop") - OPENSSL_MSVC_PRAGMA(warning(pop)) - break; + data->info_callback = fp; + return 1; default: - ret = 0; - break; + return 0; } - return ret; } BIO *BIO_new_connect(const char *hostname) { BIO *ret; ret = BIO_new(BIO_s_connect()); - if (ret == NULL) { - return NULL; + if (ret == nullptr) { + return nullptr; } if (!BIO_set_conn_hostname(ret, hostname)) { BIO_free(ret); - return NULL; + return nullptr; } return ret; } static const BIO_METHOD methods_connectp = { - BIO_TYPE_CONNECT, "socket connect", conn_write, conn_read, - NULL /* puts */, NULL /* gets */, conn_ctrl, conn_new, - conn_free, conn_callback_ctrl, + BIO_TYPE_CONNECT, /*bwrite=*/nullptr, conn_write_ex, + conn_read, /*gets=*/nullptr, conn_ctrl, + conn_new, conn_free, conn_callback_ctrl, }; -const BIO_METHOD *BIO_s_connect(void) { return &methods_connectp; } +const BIO_METHOD *BIO_s_connect() { return &methods_connectp; } int BIO_set_conn_hostname(BIO *bio, const char *name) { return (int)BIO_ctrl(bio, BIO_C_SET_CONNECT, 0, (void *)name); @@ -496,11 +453,11 @@ int BIO_set_conn_int_port(BIO *bio, const int *port) { } int BIO_set_nbio(BIO *bio, int on) { - return (int)BIO_ctrl(bio, BIO_C_SET_NBIO, on, NULL); + return (int)BIO_ctrl(bio, BIO_C_SET_NBIO, on, nullptr); } int BIO_do_connect(BIO *bio) { - return (int)BIO_ctrl(bio, BIO_C_DO_STATE_MACHINE, 0, NULL); + return (int)BIO_ctrl(bio, BIO_C_DO_STATE_MACHINE, 0, nullptr); } #endif // OPENSSL_NO_SOCK diff --git a/Sources/CNIOBoringSSL/crypto/bio/errno.cc b/Sources/CNIOBoringSSL/crypto/bio/errno.cc index efceb72c..d41c6fbc 100644 --- a/Sources/CNIOBoringSSL/crypto/bio/errno.cc +++ b/Sources/CNIOBoringSSL/crypto/bio/errno.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,7 +19,9 @@ #include "internal.h" -int bio_errno_should_retry(int return_value) { +using namespace bssl; + +int bssl::bio_errno_should_retry(int return_value) { if (return_value != -1) { return 0; } diff --git a/Sources/CNIOBoringSSL/crypto/bio/fd.cc b/Sources/CNIOBoringSSL/crypto/bio/fd.cc index 2e9546dc..0c387188 100644 --- a/Sources/CNIOBoringSSL/crypto/bio/fd.cc +++ b/Sources/CNIOBoringSSL/crypto/bio/fd.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -18,6 +23,8 @@ #include #else #include +#include +#include #endif #include @@ -31,18 +38,18 @@ #define BORINGSSL_CLOSE _close #define BORINGSSL_LSEEK _lseek #define BORINGSSL_READ _read - #define BORINGSSL_WRITE _write #else #define BORINGSSL_CLOSE close #define BORINGSSL_LSEEK lseek #define BORINGSSL_READ read - #define BORINGSSL_WRITE write #endif +using namespace bssl; + BIO *BIO_new_fd(int fd, int close_flag) { BIO *ret = BIO_new(BIO_s_fd()); - if (ret == NULL) { - return NULL; + if (ret == nullptr) { + return nullptr; } BIO_set_fd(ret, fd, close_flag); return ret; @@ -50,24 +57,22 @@ BIO *BIO_new_fd(int fd, int close_flag) { static int fd_new(BIO *bio) { // num is used to store the file descriptor. - bio->num = -1; + FromOpaque(bio)->num = -1; return 1; } static int fd_free(BIO *bio) { - if (bio->shutdown) { - if (bio->init) { - BORINGSSL_CLOSE(bio->num); + if (BIO_get_shutdown(bio)) { + if (BIO_get_init(bio)) { + BORINGSSL_CLOSE(FromOpaque(bio)->num); } - bio->init = 0; + BIO_set_init(bio, 0); } return 1; } static int fd_read(BIO *b, char *out, int outl) { - int ret = 0; - - ret = (int)BORINGSSL_READ(b->num, out, outl); + int ret = (int)BORINGSSL_READ(FromOpaque(b)->num, out, outl); BIO_clear_retry_flags(b); if (ret <= 0) { if (bio_errno_should_retry(ret)) { @@ -78,75 +83,68 @@ static int fd_read(BIO *b, char *out, int outl) { return ret; } -static int fd_write(BIO *b, const char *in, int inl) { - int ret = (int)BORINGSSL_WRITE(b->num, in, inl); +static int fd_write_ex(BIO *b, const char *in, size_t inl, + size_t *out_written) { +#if defined(OPENSSL_WINDOWS) + inl = std::min(inl, size_t{UINT_MAX}); + int ret = _write(FromOpaque(b)->num, in, static_cast(inl)); +#else + ssize_t ret = write(FromOpaque(b)->num, in, inl); +#endif BIO_clear_retry_flags(b); if (ret <= 0) { if (bio_errno_should_retry(ret)) { BIO_set_retry_write(b); } + return 0; } - return ret; + *out_written = ret; + return 1; } static long fd_ctrl(BIO *b, int cmd, long num, void *ptr) { - long ret = 1; - int *ip; - switch (cmd) { case BIO_CTRL_RESET: num = 0; [[fallthrough]]; case BIO_C_FILE_SEEK: - ret = 0; - if (b->init) { - ret = (long)BORINGSSL_LSEEK(b->num, num, SEEK_SET); + if (BIO_get_init(b)) { + return (long)BORINGSSL_LSEEK(FromOpaque(b)->num, num, SEEK_SET); } - break; + return 0; case BIO_C_FILE_TELL: case BIO_CTRL_INFO: - ret = 0; - if (b->init) { - ret = (long)BORINGSSL_LSEEK(b->num, 0, SEEK_CUR); + if (BIO_get_init(b)) { + return (long)BORINGSSL_LSEEK(FromOpaque(b)->num, 0, SEEK_CUR); } - break; + return 0; case BIO_C_SET_FD: fd_free(b); - b->num = *((int *)ptr); - b->shutdown = (int)num; - b->init = 1; - break; + FromOpaque(b)->num = *static_cast(ptr); + BIO_set_shutdown(b, static_cast(num)); + BIO_set_init(b, 1); + return 1; case BIO_C_GET_FD: - if (b->init) { - ip = (int *)ptr; - if (ip != NULL) { - *ip = b->num; + if (BIO_get_init(b)) { + int *out = static_cast(ptr); + if (out != nullptr) { + *out = FromOpaque(b)->num; } - return b->num; + return FromOpaque(b)->num; } else { - ret = -1; + return -1; } - break; case BIO_CTRL_GET_CLOSE: - ret = b->shutdown; - break; + return BIO_get_shutdown(b); case BIO_CTRL_SET_CLOSE: - b->shutdown = (int)num; - break; - case BIO_CTRL_PENDING: - case BIO_CTRL_WPENDING: - ret = 0; - break; + BIO_set_shutdown(b, static_cast(num)); + return 1; case BIO_CTRL_FLUSH: - ret = 1; - break; + return 1; default: - ret = 0; - break; + return 0; } - - return ret; } static int fd_gets(BIO *bp, char *buf, int size) { @@ -166,16 +164,23 @@ static int fd_gets(BIO *bp, char *buf, int size) { ptr[0] = '\0'; - // The output length is bounded by |size|. + // The output length is bounded by `size`. return (int)(ptr - buf); } static const BIO_METHOD methods_fdp = { - BIO_TYPE_FD, "file descriptor", fd_write, fd_read, NULL /* puts */, - fd_gets, fd_ctrl, fd_new, fd_free, NULL /* callback_ctrl */, + BIO_TYPE_FD, + /*bwrite=*/nullptr, + fd_write_ex, + fd_read, + fd_gets, + fd_ctrl, + fd_new, + fd_free, + /*callback_ctrl=*/nullptr, }; -const BIO_METHOD *BIO_s_fd(void) { return &methods_fdp; } +const BIO_METHOD *BIO_s_fd() { return &methods_fdp; } #endif // OPENSSL_NO_POSIX_IO diff --git a/Sources/CNIOBoringSSL/crypto/bio/file.cc b/Sources/CNIOBoringSSL/crypto/bio/file.cc index efe6d645..9d450a66 100644 --- a/Sources/CNIOBoringSSL/crypto/bio/file.cc +++ b/Sources/CNIOBoringSSL/crypto/bio/file.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. #if defined(__linux) || defined(__sun) || defined(__hpux) // Following definition aliases fopen to fopen64 on above mentioned @@ -35,6 +40,7 @@ #include #include "../internal.h" +#include "internal.h" #if defined(OPENSSL_WINDOWS) #include @@ -50,7 +56,7 @@ #else static FILE *fopen_if_available(const char *path, const char *mode) { errno = ENOENT; - return NULL; + return nullptr; } #endif @@ -59,7 +65,7 @@ BIO *BIO_new_file(const char *filename, const char *mode) { FILE *file; file = fopen_if_available(filename, mode); - if (file == NULL) { + if (file == nullptr) { OPENSSL_PUT_SYSTEM_ERROR(); ERR_add_error_data(5, "fopen('", filename, "','", mode, "')"); @@ -68,13 +74,13 @@ BIO *BIO_new_file(const char *filename, const char *mode) { } else { OPENSSL_PUT_ERROR(BIO, BIO_R_SYS_LIB); } - return NULL; + return nullptr; } ret = BIO_new_fp(file, BIO_CLOSE); - if (ret == NULL) { + if (ret == nullptr) { fclose(file); - return NULL; + return nullptr; } return ret; @@ -82,8 +88,8 @@ BIO *BIO_new_file(const char *filename, const char *mode) { BIO *BIO_new_fp(FILE *stream, int flags) { BIO *ret = BIO_new(BIO_s_file()); - if (ret == NULL) { - return NULL; + if (ret == nullptr) { + return nullptr; } BIO_set_fp(ret, stream, flags); @@ -91,86 +97,80 @@ BIO *BIO_new_fp(FILE *stream, int flags) { } static int file_free(BIO *bio) { - if (!bio->shutdown) { + if (!BIO_get_shutdown(bio)) { return 1; } - if (bio->init && bio->ptr != NULL) { - fclose(reinterpret_cast(bio->ptr)); - bio->ptr = NULL; + if (BIO_get_init(bio) && BIO_get_data(bio) != nullptr) { + fclose(reinterpret_cast(BIO_get_data(bio))); + BIO_set_data(bio, nullptr); } - bio->init = 0; + BIO_set_init(bio, 0); return 1; } static int file_read(BIO *b, char *out, int outl) { - if (!b->init) { - return 0; - } - - size_t ret = fread(out, 1, outl, (FILE *)b->ptr); - if (ret == 0 && ferror((FILE *)b->ptr)) { + size_t ret = fread(out, 1, outl, (FILE *)BIO_get_data(b)); + if (ret == 0 && ferror((FILE *)BIO_get_data(b))) { OPENSSL_PUT_SYSTEM_ERROR(); OPENSSL_PUT_ERROR(BIO, ERR_R_SYS_LIB); return -1; } - // fread reads at most |outl| bytes, so |ret| fits in an int. + // fread reads at most `outl` bytes, so `ret` fits in an int. return (int)ret; } -static int file_write(BIO *b, const char *in, int inl) { - if (!b->init) { +static int file_write_ex(BIO *b, const char *in, size_t inl, + size_t *out_written) { + if (fwrite(in, inl, 1, (FILE *)BIO_get_data(b)) == 0) { return 0; } - - int ret = (int)fwrite(in, inl, 1, (FILE *)b->ptr); - if (ret > 0) { - ret = inl; - } - return ret; + // We currently ask |fwrite| to write one "object" of size |inl|, rather than + // |inl| objects of size 1. |fwrite| will only succeed if it wrote the whole + // input. + // + // TODO(crbug.com/518854940): This also means we discard information about + // partial writes. + *out_written = inl; + return 1; } static long file_ctrl(BIO *b, int cmd, long num, void *ptr) { - long ret = 1; - FILE *fp = (FILE *)b->ptr; - FILE **fpp; - + FILE *fp = static_cast(BIO_get_data(b)); switch (cmd) { case BIO_CTRL_RESET: num = 0; [[fallthrough]]; case BIO_C_FILE_SEEK: - ret = (long)fseek(fp, num, 0); - break; + return fseek(fp, num, 0); case BIO_CTRL_EOF: - ret = (long)feof(fp); - break; + // feof may return any non-zero value for EOF, but we must return 1. + return feof(fp) != 0; case BIO_C_FILE_TELL: case BIO_CTRL_INFO: - ret = ftell(fp); - break; + return ftell(fp); case BIO_C_SET_FILE_PTR: file_free(b); static_assert((BIO_CLOSE & BIO_FP_TEXT) == 0, "BIO_CLOSE and BIO_FP_TEXT must not collide"); #if defined(OPENSSL_WINDOWS) - // If |BIO_FP_TEXT| is not set, OpenSSL will switch the file to binary + // If `BIO_FP_TEXT` is not set, OpenSSL will switch the file to binary // mode. BoringSSL intentionally diverges here because it means code - // tested under POSIX will inadvertently change the state of |FILE| - // objects when wrapping them in a |BIO|. + // tested under POSIX will inadvertently change the state of `FILE` + // objects when wrapping them in a `BIO`. if (num & BIO_FP_TEXT) { _setmode(_fileno(reinterpret_cast(ptr)), _O_TEXT); } #endif - b->shutdown = (int)num & BIO_CLOSE; - b->ptr = ptr; - b->init = 1; - break; + BIO_set_shutdown(b, static_cast(num) & BIO_CLOSE); + BIO_set_data(b, ptr); + BIO_set_init(b, 1); + return 1; case BIO_C_SET_FILENAME: file_free(b); - b->shutdown = (int)num & BIO_CLOSE; + BIO_set_shutdown(b, static_cast(num) & BIO_CLOSE); const char *mode; if (num & BIO_FP_APPEND) { if (num & BIO_FP_READ) { @@ -186,43 +186,35 @@ static long file_ctrl(BIO *b, int cmd, long num, void *ptr) { mode = "rb"; } else { OPENSSL_PUT_ERROR(BIO, BIO_R_BAD_FOPEN_MODE); - ret = 0; - break; + return 0; } fp = fopen_if_available(reinterpret_cast(ptr), mode); - if (fp == NULL) { + if (fp == nullptr) { OPENSSL_PUT_SYSTEM_ERROR(); ERR_add_error_data(5, "fopen('", ptr, "','", mode, "')"); OPENSSL_PUT_ERROR(BIO, ERR_R_SYS_LIB); - ret = 0; - break; + return 0; } - b->ptr = fp; - b->init = 1; - break; + BIO_set_data(b, fp); + BIO_set_init(b, 1); + return 1; case BIO_C_GET_FILE_PTR: // the ptr parameter is actually a FILE ** in this case. - if (ptr != NULL) { - fpp = (FILE **)ptr; - *fpp = (FILE *)b->ptr; + if (ptr != nullptr) { + FILE **out = static_cast(ptr); + *out = fp; } - break; + return 1; case BIO_CTRL_GET_CLOSE: - ret = (long)b->shutdown; - break; + return BIO_get_shutdown(b); case BIO_CTRL_SET_CLOSE: - b->shutdown = (int)num; - break; + BIO_set_shutdown(b, static_cast(num)); + return 1; case BIO_CTRL_FLUSH: - ret = 0 == fflush((FILE *)b->ptr); - break; - case BIO_CTRL_WPENDING: - case BIO_CTRL_PENDING: + return fflush(fp) == 0; default: - ret = 0; - break; + return 0; } - return ret; } static int file_gets(BIO *bp, char *buf, int size) { @@ -230,10 +222,10 @@ static int file_gets(BIO *bp, char *buf, int size) { return 0; } - if (!fgets(buf, size, (FILE *)bp->ptr)) { + if (!fgets(buf, size, (FILE *)BIO_get_data(bp))) { buf[0] = 0; // TODO(davidben): This doesn't distinguish error and EOF. This should check - // |ferror| as in |file_read|. + // `ferror` as in `file_read`. return 0; } @@ -241,14 +233,18 @@ static int file_gets(BIO *bp, char *buf, int size) { } static const BIO_METHOD methods_filep = { - BIO_TYPE_FILE, "FILE pointer", - file_write, file_read, - NULL /* puts */, file_gets, - file_ctrl, NULL /* create */, - file_free, NULL /* callback_ctrl */, + BIO_TYPE_FILE, + /*bwrite=*/nullptr, + file_write_ex, + file_read, + file_gets, + file_ctrl, + /*create=*/nullptr, + file_free, + /*callback_ctrl=*/nullptr, }; -const BIO_METHOD *BIO_s_file(void) { return &methods_filep; } +const BIO_METHOD *BIO_s_file() { return &methods_filep; } int BIO_get_fp(BIO *bio, FILE **out_file) { @@ -280,8 +276,8 @@ int BIO_rw_filename(BIO *bio, const char *filename) { (char *)filename); } -long BIO_tell(BIO *bio) { return BIO_ctrl(bio, BIO_C_FILE_TELL, 0, NULL); } +long BIO_tell(BIO *bio) { return BIO_ctrl(bio, BIO_C_FILE_TELL, 0, nullptr); } long BIO_seek(BIO *bio, long offset) { - return BIO_ctrl(bio, BIO_C_FILE_SEEK, offset, NULL); + return BIO_ctrl(bio, BIO_C_FILE_SEEK, offset, nullptr); } diff --git a/Sources/CNIOBoringSSL/crypto/bio/hexdump.cc b/Sources/CNIOBoringSSL/crypto/bio/hexdump.cc index 00163fb5..d964e67d 100644 --- a/Sources/CNIOBoringSSL/crypto/bio/hexdump.cc +++ b/Sources/CNIOBoringSSL/crypto/bio/hexdump.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -15,6 +20,8 @@ #include "../internal.h" +using namespace bssl; + namespace { // hexdump_ctx contains the state of a hexdump. struct hexdump_ctx { @@ -39,8 +46,8 @@ static char to_char(uint8_t b) { return b; } -// hexdump_write adds |len| bytes of |data| to the current hex dump described by -// |ctx|. +// hexdump_write adds `len` bytes of `data` to the current hex dump described by +// `ctx`. static int hexdump_write(struct hexdump_ctx *ctx, const uint8_t *data, size_t len) { char buf[10]; @@ -99,9 +106,9 @@ static int hexdump_write(struct hexdump_ctx *ctx, const uint8_t *data, return 1; } -// finish flushes any buffered data in |ctx|. +// finish flushes any buffered data in `ctx`. static int finish(struct hexdump_ctx *ctx) { - // See the comments in |hexdump| for the details of this format. + // See the comments in `hexdump` for the details of this format. const unsigned n_bytes = ctx->used; unsigned l; char buf[5]; diff --git a/Sources/CNIOBoringSSL/crypto/bio/internal.h b/Sources/CNIOBoringSSL/crypto/bio/internal.h index 467ab3b6..4d9387c7 100644 --- a/Sources/CNIOBoringSSL/crypto/bio/internal.h +++ b/Sources/CNIOBoringSSL/crypto/bio/internal.h @@ -1,16 +1,26 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. -#ifndef OPENSSL_HEADER_BIO_INTERNAL_H -#define OPENSSL_HEADER_BIO_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_BIO_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_BIO_INTERNAL_H -#include +#include + +#include + +#include "../internal.h" +#include "../mem_internal.h" #if !defined(OPENSSL_NO_SOCK) #if !defined(OPENSSL_WINDOWS) @@ -18,57 +28,101 @@ // newlib uses u_short in socket.h without defining it. typedef unsigned short u_short; #endif -#include #include +#include #else -OPENSSL_MSVC_PRAGMA(warning(push, 3)) #include -OPENSSL_MSVC_PRAGMA(warning(pop)) typedef int socklen_t; #endif #endif // !OPENSSL_NO_SOCK -#if defined(__cplusplus) -extern "C" { -#endif +DECLARE_OPAQUE_STRUCT(bio_st, Bio) + +struct bio_method_st { + int type; + int (*bwrite)(BIO *, const char *, int); + int (*bwrite_ex)(BIO *, const char *, size_t, size_t *); + int (*bread)(BIO *, char *, int); + int (*bgets)(BIO *, char *, int); + long (*ctrl)(BIO *, int, long, void *); + int (*create)(BIO *); + int (*destroy)(BIO *); + long (*callback_ctrl)(BIO *, int, BIO_info_cb *); +}; + +BSSL_NAMESPACE_BEGIN + +class Bio : public bio_st, public RefCounted { + public: + explicit Bio(const BIO_METHOD *m); + + const BIO_METHOD *method; + CRYPTO_EX_DATA ex_data; + + // TODO(crbug.com/412269080): `init` and `shutdown` could be bitfields, or + // integrated into `flags`, to save memory. + + // init is non-zero if this `BIO` has been initialised. + int init = 0; + // shutdown is often used by specific `BIO_METHOD`s to determine whether + // they own some underlying resource. This flag can often be controlled by + // `BIO_set_close`. For example, whether an fd BIO closes the underlying fd + // when it, itself, is closed. + int shutdown = 1; + int flags = 0; + int retry_reason = 0; + // num is a BIO-specific value. For example, in fd BIOs it's used to store a + // file descriptor. + int num = 0; + void *ptr = nullptr; + // next_bio points to the next `BIO` in a chain. This `BIO` owns a reference + // to `next_bio`. + Bio *next_bio = nullptr; // used by filter BIOs + uint64_t num_read = 0, num_write = 0; + + private: + friend RefCounted; + ~Bio(); +}; #if !defined(OPENSSL_NO_SOCK) -// bio_ip_and_port_to_socket_and_addr creates a socket and fills in |*out_addr| -// and |*out_addr_length| with the correct values for connecting to |hostname| -// on |port_str|. It returns one on success or zero on error. +// bio_ip_and_port_to_socket_and_addr creates a socket and fills in `*out_addr` +// and `*out_addr_length` with the correct values for connecting to `hostname` +// on `port_str`. It returns one on success or zero on error. int bio_ip_and_port_to_socket_and_addr(int *out_sock, struct sockaddr_storage *out_addr, socklen_t *out_addr_length, const char *hostname, const char *port_str); -// bio_socket_nbio sets whether |sock| is non-blocking. It returns one on +// bio_socket_nbio sets whether `sock` is non-blocking. It returns one on // success and zero otherwise. int bio_socket_nbio(int sock, int on); // bio_clear_socket_error clears the last system socket error. // // TODO(fork): remove all callers of this. -void bio_clear_socket_error(void); +void bio_clear_socket_error(); -// bio_sock_error returns the last socket error on |sock|. -int bio_sock_error(int sock); +// bio_socket_finish_connect attempts to complete an in-progress, non-blocking +// connect operation on `sock`. It returns one if the connect operation +// succeeded. Otherwise, it returns zero and sets the last socket error to the +// reason it failed. +int bio_socket_finish_connect(int sock); -// bio_socket_should_retry returns non-zero if |return_value| indicates an error +// bio_socket_should_retry returns non-zero if `return_value` indicates an error // and the last socket error indicates that it's non-fatal. int bio_socket_should_retry(int return_value); #endif // !OPENSSL_NO_SOCK -// bio_errno_should_retry returns non-zero if |return_value| indicates an error -// and |errno| indicates that it's non-fatal. +// bio_errno_should_retry returns non-zero if `return_value` indicates an error +// and `errno` indicates that it's non-fatal. int bio_errno_should_retry(int return_value); +BSSL_NAMESPACE_END -#if defined(__cplusplus) -} // extern C -#endif -#endif // OPENSSL_HEADER_BIO_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_BIO_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/bio/pair.cc b/Sources/CNIOBoringSSL/crypto/bio/pair.cc index 7eee095a..d2b7da14 100644 --- a/Sources/CNIOBoringSSL/crypto/bio/pair.cc +++ b/Sources/CNIOBoringSSL/crypto/bio/pair.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,112 +21,105 @@ #include #include "../internal.h" +#include "../mem_internal.h" +#include "internal.h" +using namespace bssl; + namespace { struct bio_bio_st { - BIO *peer; // NULL if buf == NULL. - // If peer != NULL, then peer->ptr is also a bio_bio_st, - // and its "peer" member points back to us. - // peer != NULL iff init != 0 in the BIO. + BIO *peer = nullptr; // NULL if buf == NULL. + // If peer != NULL, then BIO_get_data(peer) is also a + // bio_bio_st, and its "peer" member points back to us. + // peer != NULL iff init != 0 in the BIO. // This is for what we write (i.e. reading uses peer's struct): - int closed; // valid iff peer != NULL - size_t len; // valid iff buf != NULL; 0 if peer == NULL - size_t offset; // valid iff buf != NULL; 0 if len == 0 - size_t size; - uint8_t *buf; // "size" elements (if != NULL) + int closed = 0; // valid iff peer != NULL + size_t len = 0; // valid iff buf != NULL; 0 if peer == NULL + size_t offset = 0; // valid iff buf != NULL; 0 if len == 0 + size_t size = 0; + uint8_t *buf = nullptr; // "size" elements (if != NULL) - size_t request; // valid iff peer != NULL; 0 if len != 0, - // otherwise set by peer to number of bytes - // it (unsuccessfully) tried to read, - // never more than buffer space (size-len) warrants. + size_t request = 0; // valid iff peer != NULL; 0 if len != 0, + // otherwise set by peer to number of bytes + // it (unsuccessfully) tried to read, + // never more than buffer space (size-len) warrants. }; } // namespace static int bio_new(BIO *bio) { - struct bio_bio_st *b = - reinterpret_cast(OPENSSL_zalloc(sizeof *b)); - if (b == NULL) { + struct bio_bio_st *b = New(); + if (b == nullptr) { return 0; } b->size = 17 * 1024; // enough for one TLS record (just a default) - bio->ptr = b; + BIO_set_data(bio, b); return 1; } static void bio_destroy_pair(BIO *bio) { - struct bio_bio_st *b = reinterpret_cast(bio->ptr); + struct bio_bio_st *b = reinterpret_cast(BIO_get_data(bio)); BIO *peer_bio; struct bio_bio_st *peer_b; - if (b == NULL) { + if (b == nullptr) { return; } peer_bio = b->peer; - if (peer_bio == NULL) { + if (peer_bio == nullptr) { return; } - peer_b = reinterpret_cast(peer_bio->ptr); + peer_b = reinterpret_cast(BIO_get_data(peer_bio)); - assert(peer_b != NULL); + assert(peer_b != nullptr); assert(peer_b->peer == bio); - peer_b->peer = NULL; - peer_bio->init = 0; - assert(peer_b->buf != NULL); + peer_b->peer = nullptr; + BIO_set_init(peer_bio, 0); + assert(peer_b->buf != nullptr); peer_b->len = 0; peer_b->offset = 0; - b->peer = NULL; - bio->init = 0; - assert(b->buf != NULL); + b->peer = nullptr; + BIO_set_init(bio, 0); + assert(b->buf != nullptr); b->len = 0; b->offset = 0; } static int bio_free(BIO *bio) { - struct bio_bio_st *b = reinterpret_cast(bio->ptr); + struct bio_bio_st *b = reinterpret_cast(BIO_get_data(bio)); - assert(b != NULL); + assert(b != nullptr); if (b->peer) { bio_destroy_pair(bio); } OPENSSL_free(b->buf); - OPENSSL_free(b); + Delete(b); return 1; } static int bio_read(BIO *bio, char *buf, int size_) { size_t size = size_; - size_t rest; - struct bio_bio_st *b, *peer_b; BIO_clear_retry_flags(bio); - if (!bio->init) { - return 0; - } - - b = reinterpret_cast(bio->ptr); - assert(b != NULL); - assert(b->peer != NULL); - peer_b = reinterpret_cast(b->peer->ptr); - assert(peer_b != NULL); - assert(peer_b->buf != NULL); + bio_bio_st *b = reinterpret_cast(BIO_get_data(bio)); + assert(b != nullptr); + assert(b->peer != nullptr); + bio_bio_st *peer_b = reinterpret_cast(BIO_get_data(b->peer)); + assert(peer_b != nullptr); + assert(peer_b->buf != nullptr); peer_b->request = 0; // will be set in "retry_read" situation - if (buf == NULL || size == 0) { - return 0; - } - if (peer_b->len == 0) { if (peer_b->closed) { return 0; // writer has closed, and no data is left @@ -144,7 +142,7 @@ static int bio_read(BIO *bio, char *buf, int size_) { } // now read "size" bytes - rest = size; + size_t rest = size; assert(rest > 0); // one or two iterations @@ -178,38 +176,31 @@ static int bio_read(BIO *bio, char *buf, int size_) { rest -= chunk; } while (rest); - // |size| is bounded by the buffer size, which fits in |int|. + // `size` is bounded by the buffer size, which fits in `int`. return (int)size; } -static int bio_write(BIO *bio, const char *buf, int num_) { - size_t num = num_; - size_t rest; - struct bio_bio_st *b; - +static int bio_write_ex(BIO *bio, const char *buf, size_t num, + size_t *out_written) { BIO_clear_retry_flags(bio); - if (!bio->init || buf == NULL || num == 0) { - return 0; - } - - b = reinterpret_cast(bio->ptr); - assert(b != NULL); - assert(b->peer != NULL); - assert(b->buf != NULL); + struct bio_bio_st *b = reinterpret_cast(BIO_get_data(bio)); + assert(b != nullptr); + assert(b->peer != nullptr); + assert(b->buf != nullptr); b->request = 0; if (b->closed) { // we already closed OPENSSL_PUT_ERROR(BIO, BIO_R_BROKEN_PIPE); - return -1; + return 0; } assert(b->len <= b->size); if (b->len == b->size) { BIO_set_retry_write(bio); // buffer is full - return -1; + return 0; } // we can write @@ -218,7 +209,7 @@ static int bio_write(BIO *bio, const char *buf, int num_) { } // now write "num" bytes - rest = num; + size_t rest = num; assert(rest > 0); // one or two iterations @@ -251,43 +242,43 @@ static int bio_write(BIO *bio, const char *buf, int num_) { buf += chunk; } while (rest); - // |num| is bounded by the buffer size, which fits in |int|. - return (int)num; + *out_written = num; + return 1; } static int bio_make_pair(BIO *bio1, BIO *bio2, size_t writebuf1_len, size_t writebuf2_len) { struct bio_bio_st *b1, *b2; - assert(bio1 != NULL); - assert(bio2 != NULL); + assert(bio1 != nullptr); + assert(bio2 != nullptr); - b1 = reinterpret_cast(bio1->ptr); - b2 = reinterpret_cast(bio2->ptr); + b1 = reinterpret_cast(BIO_get_data(bio1)); + b2 = reinterpret_cast(BIO_get_data(bio2)); - if (b1->peer != NULL || b2->peer != NULL) { + if (b1->peer != nullptr || b2->peer != nullptr) { OPENSSL_PUT_ERROR(BIO, BIO_R_IN_USE); return 0; } - if (b1->buf == NULL) { + if (b1->buf == nullptr) { if (writebuf1_len) { b1->size = writebuf1_len; } b1->buf = reinterpret_cast(OPENSSL_malloc(b1->size)); - if (b1->buf == NULL) { + if (b1->buf == nullptr) { return 0; } b1->len = 0; b1->offset = 0; } - if (b2->buf == NULL) { + if (b2->buf == nullptr) { if (writebuf2_len) { b2->size = writebuf2_len; } b2->buf = reinterpret_cast(OPENSSL_malloc(b2->size)); - if (b2->buf == NULL) { + if (b2->buf == nullptr) { return 0; } b2->len = 0; @@ -301,40 +292,39 @@ static int bio_make_pair(BIO *bio1, BIO *bio2, size_t writebuf1_len, b2->closed = 0; b2->request = 0; - bio1->init = 1; - bio2->init = 1; + BIO_set_init(bio1, 1); + BIO_set_init(bio2, 1); return 1; } static long bio_ctrl(BIO *bio, int cmd, long num, void *ptr) { - long ret; - struct bio_bio_st *b = reinterpret_cast(bio->ptr); - - assert(b != NULL); - + struct bio_bio_st *b = reinterpret_cast(BIO_get_data(bio)); + assert(b != nullptr); switch (cmd) { // Specific control codes first: case BIO_C_GET_WRITE_BUF_SIZE: - ret = (long)b->size; - break; + // TODO(crbug.com/412584975): This can overflow on 64-bit Windows. Do we + // need it? It implements `BIO_get_write_buf_size`, but we don't have the + // wrapper. + return static_cast(b->size); case BIO_C_GET_WRITE_GUARANTEE: // How many bytes can the caller feed to the next write // without having to keep any? - if (b->peer == NULL || b->closed) { - ret = 0; - } else { - ret = (long)b->size - b->len; + if (b->peer == nullptr || b->closed) { + return 0; } - break; + // TODO(crbug.com/412584975): This can overflow on 64-bit Windows. + return static_cast(b->size - b->len); case BIO_C_GET_READ_REQUEST: // If the peer unsuccessfully tried to read, how many bytes // were requested? (As with BIO_CTRL_PENDING, that number // can usually be treated as boolean.) - ret = (long)b->request; - break; + // + // TODO(crbug.com/412584975): This can overflow on 64-bit Windows. + return static_cast(b->request); case BIO_C_RESET_READ_REQUEST: // Reset request. (Can be useful after read attempts @@ -342,84 +332,79 @@ static long bio_ctrl(BIO *bio, int cmd, long num, void *ptr) { // e.g. when probing SSL_read to see if any data is // available.) b->request = 0; - ret = 1; - break; + return 1; case BIO_C_SHUTDOWN_WR: // similar to shutdown(..., SHUT_WR) b->closed = 1; - ret = 1; - break; - + return 1; // Standard control codes: case BIO_CTRL_GET_CLOSE: - ret = bio->shutdown; - break; + return BIO_get_shutdown(bio); case BIO_CTRL_SET_CLOSE: - bio->shutdown = (int)num; - ret = 1; - break; + BIO_set_shutdown(bio, static_cast(num)); + return 1; case BIO_CTRL_PENDING: - if (b->peer != NULL) { + if (b->peer != nullptr) { struct bio_bio_st *peer_b = - reinterpret_cast(b->peer->ptr); - ret = (long)peer_b->len; - } else { - ret = 0; + reinterpret_cast(BIO_get_data(b->peer)); + // TODO(crbug.com/412584975): This can overflow on 64-bit Windows. + return static_cast(peer_b->len); } - break; + return 0; case BIO_CTRL_WPENDING: - ret = 0; - if (b->buf != NULL) { - ret = (long)b->len; + if (b->buf == nullptr) { + return 0; } - break; + // TODO(crbug.com/412584975): This can overflow on 64-bit Windows. + return static_cast(b->len); case BIO_CTRL_FLUSH: - ret = 1; - break; + return 1; case BIO_CTRL_EOF: { - BIO *other_bio = reinterpret_cast(ptr); - - if (other_bio) { - struct bio_bio_st *other_b = - reinterpret_cast(other_bio->ptr); - assert(other_b != NULL); - ret = other_b->len == 0 && other_b->closed; - } else { - ret = 1; + if (b->peer) { + auto *peer_b = reinterpret_cast(BIO_get_data(b->peer)); + assert(peer_b != nullptr); + return peer_b->len == 0 && peer_b->closed; } - } break; + return 1; + } default: - ret = 0; + return 0; } - return ret; } static const BIO_METHOD methods_biop = { - BIO_TYPE_BIO, "BIO pair", bio_write, bio_read, NULL /* puts */, - NULL /* gets */, bio_ctrl, bio_new, bio_free, NULL /* callback_ctrl */, + BIO_TYPE_BIO, + /*bwrite=*/nullptr, + bio_write_ex, + bio_read, + /*gets=*/nullptr, + bio_ctrl, + bio_new, + bio_free, + /*callback_ctrl=*/nullptr, }; -static const BIO_METHOD *bio_s_bio(void) { return &methods_biop; } +static const BIO_METHOD *bio_s_bio() { return &methods_biop; } int BIO_new_bio_pair(BIO **bio1_p, size_t writebuf1_len, BIO **bio2_p, size_t writebuf2_len) { BIO *bio1 = BIO_new(bio_s_bio()); BIO *bio2 = BIO_new(bio_s_bio()); - if (bio1 == NULL || bio2 == NULL || + if (bio1 == nullptr || bio2 == nullptr || !bio_make_pair(bio1, bio2, writebuf1_len, writebuf2_len)) { BIO_free(bio1); BIO_free(bio2); - *bio1_p = NULL; - *bio2_p = NULL; + *bio1_p = nullptr; + *bio2_p = nullptr; return 0; } @@ -429,13 +414,13 @@ int BIO_new_bio_pair(BIO **bio1_p, size_t writebuf1_len, BIO **bio2_p, } size_t BIO_ctrl_get_read_request(BIO *bio) { - return BIO_ctrl(bio, BIO_C_GET_READ_REQUEST, 0, NULL); + return BIO_ctrl(bio, BIO_C_GET_READ_REQUEST, 0, nullptr); } size_t BIO_ctrl_get_write_guarantee(BIO *bio) { - return BIO_ctrl(bio, BIO_C_GET_WRITE_GUARANTEE, 0, NULL); + return BIO_ctrl(bio, BIO_C_GET_WRITE_GUARANTEE, 0, nullptr); } int BIO_shutdown_wr(BIO *bio) { - return (int)BIO_ctrl(bio, BIO_C_SHUTDOWN_WR, 0, NULL); + return (int)BIO_ctrl(bio, BIO_C_SHUTDOWN_WR, 0, nullptr); } diff --git a/Sources/CNIOBoringSSL/crypto/bio/printf.cc b/Sources/CNIOBoringSSL/crypto/bio/printf.cc index 5def8fc5..676d9198 100644 --- a/Sources/CNIOBoringSSL/crypto/bio/printf.cc +++ b/Sources/CNIOBoringSSL/crypto/bio/printf.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -34,7 +39,7 @@ int BIO_printf(BIO *bio, const char *format, ...) { // include a trailing NUL, but the buffer must be sized for it. out = reinterpret_cast(OPENSSL_malloc(requested_len + 1)); out_malloced = 1; - if (out == NULL) { + if (out == nullptr) { return -1; } va_start(args, format); diff --git a/Sources/CNIOBoringSSL/crypto/bio/socket.cc b/Sources/CNIOBoringSSL/crypto/bio/socket.cc index cce7ed6a..44b8cdf3 100644 --- a/Sources/CNIOBoringSSL/crypto/bio/socket.cc +++ b/Sources/CNIOBoringSSL/crypto/bio/socket.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -13,47 +18,43 @@ #include #include +#include + +#include #if !defined(OPENSSL_WINDOWS) #include #else -OPENSSL_MSVC_PRAGMA(warning(push, 3)) #include -OPENSSL_MSVC_PRAGMA(warning(pop)) - OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib")) #endif #include "internal.h" +using namespace bssl; + #if !defined(OPENSSL_WINDOWS) -static int closesocket(int sock) { - return close(sock); -} +static int closesocket(int sock) { return close(sock); } #endif static int sock_free(BIO *bio) { - if (bio->shutdown) { - if (bio->init) { - closesocket(bio->num); + if (BIO_get_shutdown(bio)) { + if (BIO_get_init(bio)) { + closesocket(FromOpaque(bio)->num); } - bio->init = 0; - bio->flags = 0; + BIO_set_init(bio, 0); + BIO_clear_retry_flags(bio); } return 1; } static int sock_read(BIO *b, char *out, int outl) { - if (out == NULL) { - return 0; - } - bio_clear_socket_error(); #if defined(OPENSSL_WINDOWS) - int ret = recv(b->num, out, outl, 0); + int ret = recv(FromOpaque(b)->num, out, outl, 0); #else - int ret = (int)read(b->num, out, outl); + int ret = (int)read(FromOpaque(b)->num, out, outl); #endif BIO_clear_retry_flags(b); if (ret <= 0) { @@ -64,79 +65,146 @@ static int sock_read(BIO *b, char *out, int outl) { return ret; } -static int sock_write(BIO *b, const char *in, int inl) { +static int sock_write_ex(BIO *b, const char *in, size_t inl, + size_t *out_written) { bio_clear_socket_error(); #if defined(OPENSSL_WINDOWS) - int ret = send(b->num, in, inl, 0); + inl = std::min(inl, size_t{INT_MAX}); + int ret = send(FromOpaque(b)->num, in, static_cast(inl), 0); #else - int ret = (int)write(b->num, in, inl); + ssize_t ret = write(FromOpaque(b)->num, in, inl); #endif BIO_clear_retry_flags(b); if (ret <= 0) { if (bio_socket_should_retry(ret)) { BIO_set_retry_write(b); } + return 0; } - return ret; + + *out_written = ret; + return 1; } static long sock_ctrl(BIO *b, int cmd, long num, void *ptr) { - long ret = 1; - int *ip; - switch (cmd) { case BIO_C_SET_FD: sock_free(b); - b->num = *((int *)ptr); - b->shutdown = (int)num; - b->init = 1; - break; + FromOpaque(b)->num = *static_cast(ptr); + BIO_set_shutdown(b, static_cast(num)); + BIO_set_init(b, 1); + return 1; case BIO_C_GET_FD: - if (b->init) { - ip = (int *)ptr; - if (ip != NULL) { - *ip = b->num; + if (BIO_get_init(b)) { + int *out = static_cast(ptr); + if (out != nullptr) { + *out = FromOpaque(b)->num; } - ret = b->num; - } else { - ret = -1; + return FromOpaque(b)->num; } - break; + return -1; case BIO_CTRL_GET_CLOSE: - ret = b->shutdown; - break; + return BIO_get_shutdown(b); case BIO_CTRL_SET_CLOSE: - b->shutdown = (int)num; - break; + BIO_set_shutdown(b, static_cast(num)); + return 1; case BIO_CTRL_FLUSH: - ret = 1; - break; + return 1; default: - ret = 0; - break; + return 0; } - return ret; } static const BIO_METHOD methods_sockp = { - BIO_TYPE_SOCKET, "socket", - sock_write, sock_read, - NULL /* puts */, NULL /* gets, */, - sock_ctrl, NULL /* create */, - sock_free, NULL /* callback_ctrl */, + BIO_TYPE_SOCKET, + /*bwrite=*/nullptr, sock_write_ex, + sock_read, nullptr /* gets, */, + sock_ctrl, nullptr /* create */, + sock_free, nullptr /* callback_ctrl */, }; -const BIO_METHOD *BIO_s_socket(void) { return &methods_sockp; } +const BIO_METHOD *BIO_s_socket() { return &methods_sockp; } BIO *BIO_new_socket(int fd, int close_flag) { BIO *ret; ret = BIO_new(BIO_s_socket()); - if (ret == NULL) { - return NULL; + if (ret == nullptr) { + return nullptr; } BIO_set_fd(ret, fd, close_flag); return ret; } +// These functions are provided solely for compatibility with software that +// tries to copy and then modify `BIO_s_socket`. See bio.h for details. +// PostgreSQL's use makes several fragile assumptions on `BIO_s_socket`: +// +// - We do not store anything in `BIO_set_data`. (Broken in upstream OpenSSL, +// which broke PostgreSQL.) +// - We do not store anything in `BIO_set_app_data`. +// - `BIO_s_socket` is implemented internally using the non-`size_t`-clean +// I/O functions rather than the `size_t`-clean ones. +// - `BIO_METHOD` never gains another function pointer that is used in concert +// with any of the functions here. +// +// Some other projects doing similar things use `BIO_meth_get_read` and +// `BIO_meth_get_write` and in turn assume that `BIO_s_socket` has not been +// ported to the `size_t`-clean `BIO_read_ex` and `BIO_write_ex`. (Not yet +// implemented in BoringSSL.) +// +// This is hopelessly fragile. PostgreSQL 18 will include a fix to stop using +// these APIs, but older versions and other software remain impacted, so we +// implement these functions, but only support `BIO_s_socket`. For now they just +// return the underlying functions, but if we ever need to break the above +// assumptions, we can return an older, frozen version of `BIO_s_socket`. +// Limiting to exactly one allowed `BIO_METHOD` lets us do this. +// +// These functions are also deprecated in upstream OpenSSL. See +// https://github.com/openssl/openssl/issues/26047 +// +// TODO(davidben): Once Folly and all versions of PostgreSQL we care about are +// updated or patched, remove these functions. + +int (*BIO_meth_get_write(const BIO_METHOD *method))(BIO *, const char *, int) { + BSSL_CHECK(method == BIO_s_socket()); + return method->bwrite; +} + +int (*BIO_meth_get_read(const BIO_METHOD *method))(BIO *, char *, int) { + BSSL_CHECK(method == BIO_s_socket()); + return method->bread; +} + +int (*BIO_meth_get_gets(const BIO_METHOD *method))(BIO *, char *, int) { + BSSL_CHECK(method == BIO_s_socket()); + return method->bgets; +} + +int (*BIO_meth_get_puts(const BIO_METHOD *method))(BIO *, const char *) { + BSSL_CHECK(method == BIO_s_socket()); + return nullptr; +} + +long (*BIO_meth_get_ctrl(const BIO_METHOD *method))(BIO *, int, long, void *) { + BSSL_CHECK(method == BIO_s_socket()); + return method->ctrl; +} + +int (*BIO_meth_get_create(const BIO_METHOD *method))(BIO *) { + BSSL_CHECK(method == BIO_s_socket()); + return method->create; +} + +int (*BIO_meth_get_destroy(const BIO_METHOD *method))(BIO *) { + BSSL_CHECK(method == BIO_s_socket()); + return method->destroy; +} + +long (*BIO_meth_get_callback_ctrl(const BIO_METHOD *method))(BIO *, int, + bio_info_cb) { + BSSL_CHECK(method == BIO_s_socket()); + return method->callback_ctrl; +} + #endif // OPENSSL_NO_SOCK diff --git a/Sources/CNIOBoringSSL/crypto/bio/socket_helper.cc b/Sources/CNIOBoringSSL/crypto/bio/socket_helper.cc index fe699e16..5adaa3a2 100644 --- a/Sources/CNIOBoringSSL/crypto/bio/socket_helper.cc +++ b/Sources/CNIOBoringSSL/crypto/bio/socket_helper.cc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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. #if defined(__linux__) #undef _POSIX_C_SOURCE @@ -27,19 +27,21 @@ #include #if !defined(OPENSSL_WINDOWS) +#include #include +#include #include #else -OPENSSL_MSVC_PRAGMA(warning(push, 3)) #include #include -OPENSSL_MSVC_PRAGMA(warning(pop)) #endif #include "internal.h" #include "../internal.h" +BSSL_NAMESPACE_BEGIN + int bio_ip_and_port_to_socket_and_addr(int *out_sock, struct sockaddr_storage *out_addr, socklen_t *out_addr_length, @@ -109,16 +111,58 @@ int bio_socket_nbio(int sock, int on) { #endif } -void bio_clear_socket_error(void) {} +void bio_clear_socket_error() {} -int bio_sock_error(int sock) { +int bio_socket_finish_connect(int sock) { + // A blocked connect signals whether it is ready based on whether it is + // writable. (SO_ERROR is not filled in before it is writable.) +#if defined(OPENSSL_WINDOWS) + fd_set write_set, except_set; + FD_ZERO(&write_set); + FD_SET(static_cast(sock), &write_set); + FD_ZERO(&except_set); + FD_SET(static_cast(sock), &except_set); + timeval timeout = {0, 0}; + if (select(0 /* unused on Windows */, /*readfds=*/nullptr, &write_set, + &except_set, &timeout) == SOCKET_ERROR) { + return 0; + } + if (!FD_ISSET(sock, &write_set) && !FD_ISSET(sock, &except_set)) { + // The connect has not completed. Set the error that |connect| would return. + WSASetLastError(WSAEWOULDBLOCK); + return 0; + } +#else + pollfd pfd; + pfd.fd = sock; + // poll implicitly listens for POLLERR and POLLHUP. + pfd.events = POLLOUT; + pfd.revents = 0; + if (poll(&pfd, 1, /*timeout=*/0) < 0) { + return 0; + } + if (pfd.revents == 0) { + // The connect has not completed. Set the error that |connect| would return. + errno = EINPROGRESS; + return 0; + } +#endif + + // Check if the connection succeeded. int error; socklen_t error_size = sizeof(error); - if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *)&error, &error_size) < 0) { - return 1; + return 0; } - return error; + if (error != 0) { +#if defined(OPENSSL_WINDOWS) + WSASetLastError(error); +#else + errno = error; +#endif + return 0; + } + return 1; } int bio_socket_should_retry(int return_value) { @@ -130,4 +174,6 @@ int bio_socket_should_retry(int return_value) { #endif } +BSSL_NAMESPACE_END + #endif // OPENSSL_NO_SOCK diff --git a/Sources/CNIOBoringSSL/crypto/blake2/blake2.cc b/Sources/CNIOBoringSSL/crypto/blake2/blake2.cc index 21ea0ba6..cbdb8b12 100644 --- a/Sources/CNIOBoringSSL/crypto/blake2/blake2.cc +++ b/Sources/CNIOBoringSSL/crypto/blake2/blake2.cc @@ -1,23 +1,27 @@ -/* Copyright 2021 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2021 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 "../internal.h" +using namespace bssl; + // https://tools.ietf.org/html/rfc7693#section-2.6 static const uint64_t kIV[8] = { UINT64_C(0x6a09e667f3bcc908), UINT64_C(0xbb67ae8584caa73b), @@ -64,7 +68,7 @@ static void blake2b_transform(BLAKE2B_CTX *b2b, 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), ""); + static_assert(sizeof(v) == sizeof(b2b->h) + sizeof(kIV)); OPENSSL_memcpy(v, b2b->h, sizeof(b2b->h)); OPENSSL_memcpy(&v[8], kIV, sizeof(kIV)); @@ -99,7 +103,7 @@ static void blake2b_transform(BLAKE2B_CTX *b2b, blake2b_load(block, s[15])); } - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(b2b->h); i++) { + for (size_t i = 0; i < std::size(b2b->h); i++) { b2b->h[i] ^= v[i]; b2b->h[i] ^= v[i + 8]; } @@ -108,7 +112,7 @@ static void blake2b_transform(BLAKE2B_CTX *b2b, void BLAKE2B256_Init(BLAKE2B_CTX *b2b) { OPENSSL_memset(b2b, 0, sizeof(BLAKE2B_CTX)); - static_assert(sizeof(kIV) == sizeof(b2b->h), ""); + static_assert(sizeof(kIV) == sizeof(b2b->h)); OPENSSL_memcpy(&b2b->h, kIV, sizeof(kIV)); // https://tools.ietf.org/html/rfc7693#section-2.5 @@ -135,7 +139,7 @@ void BLAKE2B256_Update(BLAKE2B_CTX *b2b, const void *in_data, size_t len) { return; } - // More input remains therefore we must have filled |b2b->block|. + // More input remains therefore we must have filled `b2b->block`. assert(b2b->block_used == BLAKE2B_CBLOCK); blake2b_transform(b2b, b2b->block, BLAKE2B_CBLOCK, /*is_final_block=*/0); @@ -156,7 +160,7 @@ void BLAKE2B256_Final(uint8_t out[BLAKE2B256_DIGEST_LENGTH], BLAKE2B_CTX *b2b) { sizeof(b2b->block) - b2b->block_used); blake2b_transform(b2b, b2b->block, b2b->block_used, /*is_final_block=*/1); - static_assert(BLAKE2B256_DIGEST_LENGTH <= sizeof(b2b->h), ""); + static_assert(BLAKE2B256_DIGEST_LENGTH <= sizeof(b2b->h)); memcpy(out, b2b->h, BLAKE2B256_DIGEST_LENGTH); } diff --git a/Sources/CNIOBoringSSL/crypto/bn/bn_asn1.cc b/Sources/CNIOBoringSSL/crypto/bn/bn_asn1.cc index b0dbf19f..173f7b5f 100644 --- a/Sources/CNIOBoringSSL/crypto/bn/bn_asn1.cc +++ b/Sources/CNIOBoringSSL/crypto/bn/bn_asn1.cc @@ -1,16 +1,16 @@ -/* Copyright 2015 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2015 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 @@ -32,7 +32,7 @@ int BN_parse_asn1_unsigned(CBS *cbs, BIGNUM *ret) { return 0; } - return BN_bin2bn(CBS_data(&child), CBS_len(&child), ret) != NULL; + return BN_bin2bn(CBS_data(&child), CBS_len(&child), ret) != nullptr; } int BN_marshal_asn1(CBB *cbb, const BIGNUM *bn) { @@ -45,7 +45,7 @@ int BN_marshal_asn1(CBB *cbb, const BIGNUM *bn) { CBB child; if (!CBB_add_asn1(cbb, &child, CBS_ASN1_INTEGER) || // The number must be padded with a leading zero if the high bit would - // otherwise be set or if |bn| is zero. + // otherwise be set or if `bn` is zero. (BN_num_bits(bn) % 8 == 0 && !CBB_add_u8(&child, 0x00)) || !BN_bn2cbb_padded(&child, BN_num_bytes(bn), bn) || !CBB_flush(cbb)) { diff --git a/Sources/CNIOBoringSSL/crypto/bn/convert.cc b/Sources/CNIOBoringSSL/crypto/bn/convert.cc index 30b9ae7f..11e4d4ea 100644 --- a/Sources/CNIOBoringSSL/crypto/bn/convert.cc +++ b/Sources/CNIOBoringSSL/crypto/bn/convert.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,6 +19,8 @@ #include #include +#include + #include #include #include @@ -22,6 +29,8 @@ #include "../fipsmodule/bn/internal.h" +using namespace bssl; + int BN_bn2cbb_padded(CBB *out, size_t len, const BIGNUM *in) { uint8_t *ptr; return CBB_add_space(out, &ptr, len) && BN_bn2bin_padded(ptr, len, in); @@ -34,8 +43,8 @@ char *BN_bn2hex(const BIGNUM *bn) { char *buf = reinterpret_cast( OPENSSL_malloc(1 /* leading '-' */ + 1 /* zero is non-empty */ + width * BN_BYTES * 2 + 1 /* trailing NUL */)); - if (buf == NULL) { - return NULL; + if (buf == nullptr) { + return nullptr; } char *p = buf; @@ -64,20 +73,20 @@ char *BN_bn2hex(const BIGNUM *bn) { return buf; } -// decode_hex decodes |in_len| bytes of hex data from |in| and updates |bn|. +// decode_hex decodes `in_len` bytes of hex data from `in` and updates `bn`. static int decode_hex(BIGNUM *bn, const char *in, int in_len) { if (in_len > INT_MAX / 4) { OPENSSL_PUT_ERROR(BN, BN_R_BIGNUM_TOO_LONG); return 0; } - // |in_len| is the number of hex digits. + // `in_len` is the number of hex digits. if (!bn_expand(bn, in_len * 4)) { return 0; } int i = 0; while (in_len > 0) { - // Decode one |BN_ULONG| at a time. + // Decode one `BN_ULONG` at a time. int todo = BN_BYTES * 2; if (todo > in_len) { todo = in_len; @@ -88,7 +97,7 @@ static int decode_hex(BIGNUM *bn, const char *in, int in_len) { for (j = todo; j > 0; j--) { uint8_t hex = 0; if (!OPENSSL_fromxdigit(&hex, in[in_len - j])) { - // This shouldn't happen. The caller checks |OPENSSL_isxdigit|. + // This shouldn't happen. The caller checks `OPENSSL_isxdigit`. assert(0); } word = (word << 4) | hex; @@ -102,12 +111,12 @@ static int decode_hex(BIGNUM *bn, const char *in, int in_len) { return 1; } -// decode_dec decodes |in_len| bytes of decimal data from |in| and updates |bn|. +// decode_dec decodes `in_len` bytes of decimal data from `in` and updates `bn`. static int decode_dec(BIGNUM *bn, const char *in, int in_len) { int i, j; BN_ULONG l = 0; - // Decode |BN_DEC_NUM| digits at a time. + // Decode `BN_DEC_NUM` digits at a time. j = BN_DEC_NUM - (in_len % BN_DEC_NUM); if (j == BN_DEC_NUM) { j = 0; @@ -132,11 +141,11 @@ typedef int (*char_test_func)(int c); static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode, char_test_func want_char) { - BIGNUM *ret = NULL; + BIGNUM *ret = nullptr; int neg = 0, i; int num; - if (in == NULL || *in == 0) { + if (in == nullptr || *in == 0) { return 0; } @@ -149,14 +158,14 @@ static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode, } num = i + neg; - if (outp == NULL) { + if (outp == nullptr) { return num; } // in is the start of the hex digits, and it is 'i' long - if (*outp == NULL) { + if (*outp == nullptr) { ret = BN_new(); - if (ret == NULL) { + if (ret == nullptr) { return 0; } } else { @@ -177,7 +186,7 @@ static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode, return num; err: - if (*outp == NULL) { + if (*outp == nullptr) { BN_free(ret); } @@ -191,33 +200,32 @@ int BN_hex2bn(BIGNUM **outp, const char *in) { char *BN_bn2dec(const BIGNUM *a) { // It is easier to print strings little-endian, so we assemble it in reverse // and fix at the end. - BIGNUM *copy = NULL; - CBB cbb; - if (!CBB_init(&cbb, 16) || // - !CBB_add_u8(&cbb, 0 /* trailing NUL */)) { - goto err; + ScopedCBB cbb; + if (!CBB_init(cbb.get(), 16) || // + !CBB_add_u8(cbb.get(), 0 /* trailing NUL */)) { + return nullptr; } if (BN_is_zero(a)) { - if (!CBB_add_u8(&cbb, '0')) { - goto err; + if (!CBB_add_u8(cbb.get(), '0')) { + return nullptr; } } else { - copy = BN_dup(a); - if (copy == NULL) { - goto err; + UniquePtr copy(BN_dup(a)); + if (copy == nullptr) { + return nullptr; } - while (!BN_is_zero(copy)) { - BN_ULONG word = BN_div_word(copy, BN_DEC_CONV); + while (!BN_is_zero(copy.get())) { + BN_ULONG word = BN_div_word(copy.get(), BN_DEC_CONV); if (word == (BN_ULONG)-1) { - goto err; + return nullptr; } - const int add_leading_zeros = !BN_is_zero(copy); + const int add_leading_zeros = !BN_is_zero(copy.get()); for (int i = 0; i < BN_DEC_NUM && (add_leading_zeros || word != 0); i++) { - if (!CBB_add_u8(&cbb, '0' + word % 10)) { - goto err; + if (!CBB_add_u8(cbb.get(), '0' + word % 10)) { + return nullptr; } word /= 10; } @@ -226,30 +234,18 @@ char *BN_bn2dec(const BIGNUM *a) { } if (BN_is_negative(a) && // - !CBB_add_u8(&cbb, '-')) { - goto err; + !CBB_add_u8(cbb.get(), '-')) { + return nullptr; } uint8_t *data; size_t len; - if (!CBB_finish(&cbb, &data, &len)) { - goto err; + if (!CBB_finish(cbb.get(), &data, &len)) { + return nullptr; } - // Reverse the buffer. - for (size_t i = 0; i < len / 2; i++) { - uint8_t tmp = data[i]; - data[i] = data[len - 1 - i]; - data[len - 1 - i] = tmp; - } - - BN_free(copy); - return (char *)data; - -err: - BN_free(copy); - CBB_cleanup(&cbb); - return NULL; + std::reverse(data, data + len); + return reinterpret_cast(data); } int BN_dec2bn(BIGNUM **outp, const char *in) { @@ -280,38 +276,33 @@ int BN_asc2bn(BIGNUM **outp, const char *in) { } int BN_print(BIO *bp, const BIGNUM *a) { - int i, j, v, z = 0; - int ret = 0; - if (a->neg && BIO_write(bp, "-", 1) != 1) { - goto end; + return 0; } if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1) { - goto end; + return 0; } - for (i = bn_minimal_width(a) - 1; i >= 0; i--) { - for (j = BN_BITS2 - 4; j >= 0; j -= 4) { + int z = 0; + for (int i = bn_minimal_width(a) - 1; i >= 0; i--) { + for (int j = BN_BITS2 - 4; j >= 0; j -= 4) { // strip leading zeros - v = ((int)(a->d[i] >> (long)j)) & 0x0f; + int v = ((int)(a->d[i] >> (long)j)) & 0x0f; if (z || v != 0) { if (BIO_write(bp, &hextable[v], 1) != 1) { - goto end; + return 0; } z = 1; } } } - ret = 1; - -end: - return ret; + return 1; } int BN_print_fp(FILE *fp, const BIGNUM *a) { BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); - if (b == NULL) { + if (b == nullptr) { return 0; } @@ -341,7 +332,7 @@ size_t BN_bn2mpi(const BIGNUM *in, uint8_t *out) { return 4; } - if (out == NULL) { + if (out == nullptr) { return 4 + len; } @@ -362,7 +353,7 @@ size_t BN_bn2mpi(const BIGNUM *in, uint8_t *out) { BIGNUM *BN_mpi2bn(const uint8_t *in, size_t len, BIGNUM *out) { if (len < 4) { OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING); - return NULL; + return nullptr; } const size_t in_len = ((size_t)in[0] << 24) | // ((size_t)in[1] << 16) | // @@ -370,14 +361,14 @@ BIGNUM *BN_mpi2bn(const uint8_t *in, size_t len, BIGNUM *out) { ((size_t)in[3]); if (in_len != len - 4) { OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING); - return NULL; + return nullptr; } int out_is_alloced = 0; - if (out == NULL) { + if (out == nullptr) { out = BN_new(); - if (out == NULL) { - return NULL; + if (out == nullptr) { + return nullptr; } out_is_alloced = 1; } @@ -388,11 +379,11 @@ BIGNUM *BN_mpi2bn(const uint8_t *in, size_t len, BIGNUM *out) { } in += 4; - if (BN_bin2bn(in, in_len, out) == NULL) { + if (BN_bin2bn(in, in_len, out) == nullptr) { if (out_is_alloced) { BN_free(out); } - return NULL; + return nullptr; } out->neg = ((*in) & 0x80) != 0; if (out->neg) { diff --git a/Sources/CNIOBoringSSL/crypto/bn/div.cc b/Sources/CNIOBoringSSL/crypto/bn/div.cc new file mode 100644 index 00000000..d1980c8a --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/bn/div.cc @@ -0,0 +1,102 @@ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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/bn/internal.h" +#include "../internal.h" + + +using namespace bssl; + +int BN_mod_pow2(BIGNUM *r, const BIGNUM *a, size_t e) { + if (e == 0 || a->width == 0) { + BN_zero(r); + return 1; + } + + size_t num_words = 1 + ((e - 1) / BN_BITS2); + + // If `a` definitely has less than `e` bits, just BN_copy. + if ((size_t)a->width < num_words) { + return BN_copy(r, a) != nullptr; + } + + // Otherwise, first make sure we have enough space in `r`. + // Note that this will fail if num_words > INT_MAX. + if (!bn_wexpand(r, num_words)) { + return 0; + } + + // Copy the content of `a` into `r`. + OPENSSL_memcpy(r->d, a->d, num_words * sizeof(BN_ULONG)); + + // If `e` isn't word-aligned, we have to mask off some of our bits. + size_t top_word_exponent = e % (sizeof(BN_ULONG) * 8); + if (top_word_exponent != 0) { + r->d[num_words - 1] &= (((BN_ULONG)1) << top_word_exponent) - 1; + } + + // Fill in the remaining fields of `r`. + r->neg = a->neg; + r->width = (int)num_words; + bn_set_minimal_width(r); + return 1; +} + +int BN_nnmod_pow2(BIGNUM *r, const BIGNUM *a, size_t e) { + if (!BN_mod_pow2(r, a, e)) { + return 0; + } + + // If the returned value was non-negative, we're done. + if (BN_is_zero(r) || !r->neg) { + return 1; + } + + size_t num_words = 1 + (e - 1) / BN_BITS2; + + // Expand `r` to the size of our modulus. + if (!bn_wexpand(r, num_words)) { + return 0; + } + + // Clear the upper words of `r`. + OPENSSL_memset(&r->d[r->width], 0, (num_words - r->width) * BN_BYTES); + + // Set parameters of `r`. + r->neg = 0; + r->width = (int)num_words; + + // Now, invert every word. The idea here is that we want to compute 2^e-`x`, + // which is actually equivalent to the twos-complement representation of `x` + // in `e` bits, which is -x = ~x + 1. + for (int i = 0; i < r->width; i++) { + r->d[i] = ~r->d[i]; + } + + // If our exponent doesn't span the top word, we have to mask the rest. + size_t top_word_exponent = e % BN_BITS2; + if (top_word_exponent != 0) { + r->d[r->width - 1] &= (((BN_ULONG)1) << top_word_exponent) - 1; + } + + // Keep the minimal-width invariant for `BIGNUM`. + bn_set_minimal_width(r); + + // Finally, add one, for the reason described above. + return BN_add(r, r, BN_value_one()); +} diff --git a/Sources/CNIOBoringSSL/crypto/bn/exponentiation.cc b/Sources/CNIOBoringSSL/crypto/bn/exponentiation.cc new file mode 100644 index 00000000..2d937a07 --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/bn/exponentiation.cc @@ -0,0 +1,168 @@ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../fipsmodule/bn/internal.h" + + +using namespace bssl; + +int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { + BN_CTXScope scope(ctx); + BIGNUM *rr; + if (r == a || r == p) { + rr = BN_CTX_get(ctx); + } else { + rr = r; + } + + BIGNUM *v = BN_CTX_get(ctx); + if (rr == nullptr || v == nullptr) { + return 0; + } + + if (BN_copy(v, a) == nullptr) { + return 0; + } + int bits = BN_num_bits(p); + + if (BN_is_odd(p)) { + if (BN_copy(rr, a) == nullptr) { + return 0; + } + } else { + if (!BN_one(rr)) { + return 0; + } + } + + for (int i = 1; i < bits; i++) { + if (!BN_sqr(v, v, ctx)) { + return 0; + } + if (BN_is_bit_set(p, i)) { + if (!BN_mul(rr, rr, v, ctx)) { + return 0; + } + } + } + + if (r != rr && !BN_copy(r, rr)) { + return 0; + } + return 1; +} + +static int mod_exp_even(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx) { + // No cryptographic operations require modular exponentiation with an even + // modulus. We support it for backwards compatibility with any applications + // that may have relied on the operation, but optimize for simplicity over + // performance with straightforward square-and-multiply routine. + int bits = BN_num_bits(p); + if (bits == 0) { + return BN_one(r); + } + + // Make a copy of `a`, in case it aliases `r`. + BN_CTXScope scope(ctx); + BIGNUM *tmp = BN_CTX_get(ctx); + if (tmp == nullptr || !BN_copy(tmp, a)) { + return 0; + } + + assert(BN_is_bit_set(p, bits - 1)); + if (!BN_copy(r, tmp)) { + return 0; + } + + for (int i = bits - 2; i >= 0; i--) { + if (!BN_mod_sqr(r, r, m, ctx) || + (BN_is_bit_set(p, i) && !BN_mod_mul(r, r, tmp, m, ctx))) { + return 0; + } + } + + return 1; +} + +int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, + BN_CTX *ctx) { + if (m->neg) { + OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER); + return 0; + } + if (a->neg || BN_ucmp(a, m) >= 0) { + if (!BN_nnmod(r, a, m, ctx)) { + return 0; + } + a = r; + } + + if (BN_is_odd(m)) { + return BN_mod_exp_mont(r, a, p, m, ctx, nullptr); + } + + return mod_exp_even(r, a, p, m, ctx); +} + +int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, + const BN_MONT_CTX *mont) { + // BN_mod_exp_mont requires reduced inputs. + if (bn_minimal_width(m) == 1) { + a %= m->d[0]; + } + + UniquePtr a_bignum(BN_new()); + if (a_bignum == nullptr || !BN_set_word(a_bignum.get(), a)) { + OPENSSL_PUT_ERROR(BN, ERR_R_INTERNAL_ERROR); + return 0; + } + + return BN_mod_exp_mont(rr, a_bignum.get(), p, m, ctx, mont); +} + +int BN_mod_exp2_mont(BIGNUM *rr, const BIGNUM *a1, const BIGNUM *p1, + const BIGNUM *a2, const BIGNUM *p2, const BIGNUM *m, + BN_CTX *ctx, const BN_MONT_CTX *mont) { + // Allocate a montgomery context if it was not supplied by the caller. + UniquePtr new_mont; + if (mont == nullptr) { + new_mont.reset(BN_MONT_CTX_new_for_modulus(m, ctx)); + if (new_mont == nullptr) { + return 0; + } + mont = new_mont.get(); + } + + // BN_mod_mul_montgomery removes one Montgomery factor, so passing one + // Montgomery-encoded and one non-Montgomery-encoded value gives a + // non-Montgomery-encoded result. + UniquePtr tmp(BN_new()); + if (tmp == nullptr || // + !BN_mod_exp_mont(rr, a1, p1, m, ctx, mont) || + !BN_mod_exp_mont(tmp.get(), a2, p2, m, ctx, mont) || + !BN_to_montgomery(rr, rr, mont, ctx) || + !BN_mod_mul_montgomery(rr, rr, tmp.get(), mont, ctx)) { + return 0; + } + + return 1; +} diff --git a/Sources/CNIOBoringSSL/crypto/bn/sqrt.cc b/Sources/CNIOBoringSSL/crypto/bn/sqrt.cc new file mode 100644 index 00000000..1c41be47 --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/bn/sqrt.cc @@ -0,0 +1,93 @@ +// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 + + +int BN_sqrt(BIGNUM *out_sqrt, const BIGNUM *in, BN_CTX *ctx) { + BIGNUM *estimate, *tmp, *delta, *last_delta, *tmp2; + int ok = 0, last_delta_valid = 0; + + if (in->neg) { + OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER); + return 0; + } + if (BN_is_zero(in)) { + BN_zero(out_sqrt); + return 1; + } + + bssl::BN_CTXScope scope(ctx); + if (out_sqrt == in) { + estimate = BN_CTX_get(ctx); + } else { + estimate = out_sqrt; + } + tmp = BN_CTX_get(ctx); + last_delta = BN_CTX_get(ctx); + delta = BN_CTX_get(ctx); + if (estimate == nullptr || tmp == nullptr || last_delta == nullptr || + delta == nullptr) { + goto err; + } + + // We estimate that the square root of an n-bit number is 2^{n/2}. + if (!BN_lshift(estimate, BN_value_one(), BN_num_bits(in)/2)) { + goto err; + } + + // This is Newton's method for finding a root of the equation `estimate`^2 - + // `in` = 0. + for (;;) { + // `estimate` = 1/2 * (`estimate` + `in`/`estimate`) + if (!BN_div(tmp, nullptr, in, estimate, ctx) || + !BN_add(tmp, tmp, estimate) || !BN_rshift1(estimate, tmp) || + // `tmp` = `estimate`^2 + !BN_sqr(tmp, estimate, ctx) || + // `delta` = `in` - `tmp` + !BN_sub(delta, in, tmp)) { + OPENSSL_PUT_ERROR(BN, ERR_R_BN_LIB); + goto err; + } + + delta->neg = 0; + // The difference between `in` and `estimate` squared is required to always + // decrease. This ensures that the loop always terminates, but I don't have + // a proof that it always finds the square root for a given square. + if (last_delta_valid && BN_cmp(delta, last_delta) >= 0) { + break; + } + + last_delta_valid = 1; + + tmp2 = last_delta; + last_delta = delta; + delta = tmp2; + } + + if (BN_cmp(tmp, in) != 0) { + OPENSSL_PUT_ERROR(BN, BN_R_NOT_A_SQUARE); + goto err; + } + + ok = 1; + +err: + if (ok && out_sqrt == in && !BN_copy(out_sqrt, estimate)) { + ok = 0; + } + return ok; +} diff --git a/Sources/CNIOBoringSSL/crypto/buf/buf.cc b/Sources/CNIOBoringSSL/crypto/buf/buf.cc index 5f53955a..518bef45 100644 --- a/Sources/CNIOBoringSSL/crypto/buf/buf.cc +++ b/Sources/CNIOBoringSSL/crypto/buf/buf.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -15,18 +20,19 @@ #include #include "../internal.h" +#include "../mem_internal.h" -BUF_MEM *BUF_MEM_new(void) { - return reinterpret_cast(OPENSSL_zalloc(sizeof(BUF_MEM))); -} +using namespace bssl; + +BUF_MEM *BUF_MEM_new() { return New(); } void BUF_MEM_free(BUF_MEM *buf) { if (buf == nullptr) { return; } OPENSSL_free(buf->data); - OPENSSL_free(buf); + Delete(buf); } int BUF_MEM_reserve(BUF_MEM *buf, size_t cap) { @@ -48,7 +54,7 @@ int BUF_MEM_reserve(BUF_MEM *buf, size_t cap) { char *new_buf = reinterpret_cast(OPENSSL_realloc(buf->data, alloc_size)); - if (new_buf == NULL) { + if (new_buf == nullptr) { return 0; } diff --git a/Sources/CNIOBoringSSL/crypto/bytestring/asn1_compat.cc b/Sources/CNIOBoringSSL/crypto/bytestring/asn1_compat.cc index 5e6821b4..e9222ceb 100644 --- a/Sources/CNIOBoringSSL/crypto/bytestring/asn1_compat.cc +++ b/Sources/CNIOBoringSSL/crypto/bytestring/asn1_compat.cc @@ -1,16 +1,16 @@ -/* Copyright 2016 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2016 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 @@ -25,24 +25,25 @@ #include "../internal.h" -int CBB_finish_i2d(CBB *cbb, uint8_t **outp) { +using namespace bssl; + +int bssl::CBB_finish_i2d(CBB *cbb, uint8_t **outp) { assert(!cbb->is_child); assert(cbb->u.base.can_resize); uint8_t *der; size_t der_len; if (!CBB_finish(cbb, &der, &der_len)) { - CBB_cleanup(cbb); return -1; } if (der_len > INT_MAX) { OPENSSL_free(der); return -1; } - if (outp != NULL) { - if (*outp == NULL) { + if (outp != nullptr) { + if (*outp == nullptr) { *outp = der; - der = NULL; + der = nullptr; } else { OPENSSL_memcpy(*outp, der, der_len); *outp += der_len; diff --git a/Sources/CNIOBoringSSL/crypto/bytestring/ber.cc b/Sources/CNIOBoringSSL/crypto/bytestring/ber.cc index f18e8f94..1d0072da 100644 --- a/Sources/CNIOBoringSSL/crypto/bytestring/ber.cc +++ b/Sources/CNIOBoringSSL/crypto/bytestring/ber.cc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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 @@ -20,10 +20,12 @@ #include "internal.h" +using namespace bssl; + // kMaxDepth limits the recursion depth to avoid overflowing the stack. static const uint32_t kMaxDepth = 128; -// is_string_type returns one if |tag| is a string type and zero otherwise. It +// is_string_type returns one if `tag` is a string type and zero otherwise. It // ignores the constructed bit. static int is_string_type(CBS_ASN1_TAG tag) { // While BER supports constructed BIT STRINGS, OpenSSL misparses them. To @@ -48,10 +50,10 @@ static int is_string_type(CBS_ASN1_TAG tag) { } } -// cbs_find_ber walks an ASN.1 structure in |orig_in| and sets |*ber_found| +// cbs_find_ber walks an ASN.1 structure in `orig_in` and sets `*ber_found` // depending on whether an indefinite length element or constructed string was -// found. The value of |orig_in| is not changed. It returns one on success (i.e. -// |*ber_found| was set) and zero on error. +// found. The value of `orig_in` is not changed. It returns one on success (i.e. +// `*ber_found` was set) and zero on error. static int cbs_find_ber(const CBS *orig_in, int *ber_found, uint32_t depth) { if (depth > kMaxDepth) { return 0; @@ -92,8 +94,8 @@ static int cbs_find_ber(const CBS *orig_in, int *ber_found, uint32_t depth) { return 1; } -// cbs_get_eoc returns one if |cbs| begins with an "end of contents" (EOC) value -// and zero otherwise. If an EOC was found, it advances |cbs| past it. +// cbs_get_eoc returns one if `cbs` begins with an "end of contents" (EOC) value +// and zero otherwise. If an EOC was found, it advances `cbs` past it. static int cbs_get_eoc(CBS *cbs) { if (CBS_len(cbs) >= 2 && CBS_data(cbs)[0] == 0 && CBS_data(cbs)[1] == 0) { @@ -102,11 +104,11 @@ static int cbs_get_eoc(CBS *cbs) { return 0; } -// cbs_convert_ber reads BER data from |in| and writes DER data to |out|. If -// |string_tag| is non-zero, then all elements must match |string_tag| up to the -// constructed bit and primitive element bodies are written to |out| without +// cbs_convert_ber reads BER data from `in` and writes DER data to `out`. If +// `string_tag` is non-zero, then all elements must match `string_tag` up to the +// constructed bit and primitive element bodies are written to `out` without // element headers. This is used when concatenating the fragments of a -// constructed string. If |looking_for_eoc| is set then any EOC elements found +// constructed string. If `looking_for_eoc` is set then any EOC elements found // will cause the function to return after consuming it. It returns one on // success and zero on error. static int cbs_convert_ber(CBS *in, CBB *out, CBS_ASN1_TAG string_tag, @@ -128,13 +130,13 @@ static int cbs_convert_ber(CBS *in, CBB *out, CBS_ASN1_TAG string_tag, int indefinite; CBB *out_contents, out_contents_storage; if (!CBS_get_any_ber_asn1_element(in, &contents, &tag, &header_len, - /*out_ber_found=*/NULL, &indefinite)) { + /*out_ber_found=*/nullptr, &indefinite)) { return 0; } if (string_tag != 0) { // This is part of a constructed string. All elements must match - // |string_tag| up to the constructed bit and get appended to |out| + // `string_tag` up to the constructed bit and get appended to `out` // without a child element. if ((tag & ~CBS_ASN1_CONSTRUCTED) != string_tag) { return 0; @@ -189,7 +191,7 @@ static int cbs_convert_ber(CBS *in, CBB *out, CBS_ASN1_TAG string_tag, return looking_for_eoc == 0; } -int CBS_asn1_ber_to_der(CBS *in, CBS *out, uint8_t **out_storage) { +int bssl::CBS_asn1_ber_to_der(CBS *in, CBS *out, uint8_t **out_storage) { CBB cbb; // First, do a quick walk to find any indefinite-length elements. Most of the @@ -200,10 +202,10 @@ int CBS_asn1_ber_to_der(CBS *in, CBS *out, uint8_t **out_storage) { } if (!conversion_needed) { - if (!CBS_get_any_asn1_element(in, out, NULL, NULL)) { + if (!CBS_get_any_asn1_element(in, out, nullptr, nullptr)) { return 0; } - *out_storage = NULL; + *out_storage = nullptr; return 1; } @@ -219,21 +221,21 @@ int CBS_asn1_ber_to_der(CBS *in, CBS *out, uint8_t **out_storage) { return 1; } -int CBS_get_asn1_implicit_string(CBS *in, CBS *out, uint8_t **out_storage, - CBS_ASN1_TAG outer_tag, - CBS_ASN1_TAG inner_tag) { +int bssl::CBS_get_asn1_implicit_string(CBS *in, CBS *out, uint8_t **out_storage, + CBS_ASN1_TAG outer_tag, + CBS_ASN1_TAG inner_tag) { assert(!(outer_tag & CBS_ASN1_CONSTRUCTED)); assert(!(inner_tag & CBS_ASN1_CONSTRUCTED)); assert(is_string_type(inner_tag)); if (CBS_peek_asn1_tag(in, outer_tag)) { // Normal implicitly-tagged string. - *out_storage = NULL; + *out_storage = nullptr; return CBS_get_asn1(in, out, outer_tag); } // Otherwise, try to parse an implicitly-tagged constructed string. - // |CBS_asn1_ber_to_der| is assumed to have run, so only allow one level deep + // `CBS_asn1_ber_to_der` is assumed to have run, so only allow one level deep // of nesting. CBB result; CBS child; diff --git a/Sources/CNIOBoringSSL/crypto/bytestring/cbb.cc b/Sources/CNIOBoringSSL/crypto/bytestring/cbb.cc index 0cef36aa..93ac35cd 100644 --- a/Sources/CNIOBoringSSL/crypto/bytestring/cbb.cc +++ b/Sources/CNIOBoringSSL/crypto/bytestring/cbb.cc @@ -1,34 +1,42 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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 "../internal.h" +#include "../mem_internal.h" +#include "internal.h" +using namespace bssl; + void CBB_zero(CBB *cbb) { OPENSSL_memset(cbb, 0, sizeof(CBB)); } static void cbb_init(CBB *cbb, uint8_t *buf, size_t cap, int can_resize) { cbb->is_child = 0; - cbb->child = NULL; + cbb->child = nullptr; cbb->u.base.buf = buf; cbb->u.base.len = 0; cbb->u.base.cap = cap; @@ -40,7 +48,7 @@ int CBB_init(CBB *cbb, size_t initial_capacity) { CBB_zero(cbb); uint8_t *buf = reinterpret_cast(OPENSSL_malloc(initial_capacity)); - if (initial_capacity > 0 && buf == NULL) { + if (initial_capacity > 0 && buf == nullptr) { return 0; } @@ -55,8 +63,8 @@ int CBB_init_fixed(CBB *cbb, uint8_t *buf, size_t len) { } void CBB_cleanup(CBB *cbb) { - // Child |CBB|s are non-owning. They are implicitly discarded and should not - // be used with |CBB_cleanup| or |ScopedCBB|. + // Child `CBB`s are non-owning. They are implicitly discarded and should not + // be used with `CBB_cleanup` or `ScopedCBB`. assert(!cbb->is_child); if (cbb->is_child) { return; @@ -64,12 +72,14 @@ void CBB_cleanup(CBB *cbb) { if (cbb->u.base.can_resize) { OPENSSL_free(cbb->u.base.buf); + cbb->u.base.buf = nullptr; } } static int cbb_buffer_reserve(struct cbb_buffer_st *base, uint8_t **out, size_t len) { - if (base == NULL) { + if (base == nullptr) { + OPENSSL_PUT_ERROR(CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } @@ -92,7 +102,7 @@ static int cbb_buffer_reserve(struct cbb_buffer_st *base, uint8_t **out, } uint8_t *newbuf = reinterpret_cast(OPENSSL_realloc(base->buf, newcap)); - if (newbuf == NULL) { + if (newbuf == nullptr) { goto err; } @@ -116,7 +126,7 @@ static int cbb_buffer_add(struct cbb_buffer_st *base, uint8_t **out, if (!cbb_buffer_reserve(base, out, len)) { return 0; } - // This will not overflow or |cbb_buffer_reserve| would have failed. + // This will not overflow or `cbb_buffer_reserve` would have failed. base->len += len; return 1; } @@ -131,18 +141,19 @@ int CBB_finish(CBB *cbb, uint8_t **out_data, size_t *out_len) { return 0; } - if (cbb->u.base.can_resize && (out_data == NULL || out_len == NULL)) { - // |out_data| and |out_len| can only be NULL if the CBB is fixed. + if (cbb->u.base.can_resize && (out_data == nullptr || out_len == nullptr)) { + // `out_data` and `out_len` can only be NULL if the CBB is fixed. + OPENSSL_PUT_ERROR(CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } - if (out_data != NULL) { + if (out_data != nullptr) { *out_data = cbb->u.base.buf; } - if (out_len != NULL) { + if (out_len != nullptr) { *out_len = cbb->u.base.len; } - cbb->u.base.buf = NULL; + cbb->u.base.buf = nullptr; CBB_cleanup(cbb); return 1; } @@ -155,41 +166,42 @@ static struct cbb_buffer_st *cbb_get_base(CBB *cbb) { } static void cbb_on_error(CBB *cbb) { - // Due to C's lack of destructors and |CBB|'s auto-flushing API, a failing - // |CBB|-taking function may leave a dangling pointer to a child |CBB|. As a - // result, the convention is callers may not write to |CBB|s that have failed. - // But, as a safety measure, we lock the |CBB| into an error state. Once the - // error bit is set, |cbb->child| will not be read. + // Due to C's lack of destructors and `CBB`'s auto-flushing API, a failing + // `CBB`-taking function may leave a dangling pointer to a child `CBB`. As a + // result, the convention is callers may not write to `CBB`s that have failed. + // But, as a safety measure, we lock the `CBB` into an error state. Once the + // error bit is set, `cbb->child` will not be read. // - // TODO(davidben): This still isn't quite ideal. A |CBB| function *outside* - // this file may originate an error while the |CBB| points to a local child. + // TODO(davidben): This still isn't quite ideal. A `CBB` function *outside* + // this file may originate an error while the `CBB` points to a local child. // In that case we don't set the error bit and are reliant on the error - // convention. Perhaps we allow |CBB_cleanup| on child |CBB|s and make every - // child's |CBB_cleanup| set the error bit if unflushed. That will be + // convention. Perhaps we allow `CBB_cleanup` on child `CBB`s and make every + // child's `CBB_cleanup` set the error bit if unflushed. That will be // convenient for C++ callers, but very tedious for C callers. So C callers - // perhaps should get a |CBB_on_error| function that can be, less tediously, - // stuck in a |goto err| block. + // perhaps should get a `CBB_on_error` function that can be, less tediously, + // stuck in a `goto err` block. cbb_get_base(cbb)->error = 1; // Clearing the pointer is not strictly necessary, but GCC's dangling pointer - // warning does not know |cbb->child| will not be read once |error| is set + // warning does not know `cbb->child` will not be read once `error` is set // above. - cbb->child = NULL; + cbb->child = nullptr; } // CBB_flush recurses and then writes out any pending length prefix. The // current length of the underlying base is taken to be the length of the // length-prefixed data. int CBB_flush(CBB *cbb) { - // If |base| has hit an error, the buffer is in an undefined state, so - // fail all following calls. In particular, |cbb->child| may point to invalid + // If `base` has hit an error, the buffer is in an undefined state, so + // fail all following calls. In particular, `cbb->child` may point to invalid // memory. struct cbb_buffer_st *base = cbb_get_base(cbb); - if (base == NULL || base->error) { + if (base == nullptr || base->error) { + OPENSSL_PUT_ERROR(CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } - if (cbb->child == NULL) { + if (cbb->child == nullptr) { // Nothing to flush. return 1; } @@ -200,8 +212,11 @@ int CBB_flush(CBB *cbb) { size_t child_start = child->offset + child->pending_len_len; size_t len; - if (!CBB_flush(cbb->child) || child_start < child->offset || - base->len < child_start) { + if (!CBB_flush(cbb->child)) { + goto err; + } + if (child_start < child->offset || base->len < child_start) { + OPENSSL_PUT_ERROR(CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } @@ -241,7 +256,7 @@ int CBB_flush(CBB *cbb) { if (len_len != 1) { // We need to move the contents along in order to make space. size_t extra_bytes = len_len - 1; - if (!cbb_buffer_add(base, NULL, extra_bytes)) { + if (!cbb_buffer_add(base, nullptr, extra_bytes)) { goto err; } OPENSSL_memmove(base->buf + child_start + extra_bytes, @@ -260,8 +275,8 @@ int CBB_flush(CBB *cbb) { goto err; } - child->base = NULL; - cbb->child = NULL; + child->base = nullptr; + cbb->child = nullptr; return 1; @@ -270,8 +285,8 @@ err: return 0; } -const uint8_t *CBB_data(const CBB *cbb) { - assert(cbb->child == NULL); +uint8_t *CBB_data(const CBB *cbb) { + assert(cbb->child == nullptr); if (cbb->is_child) { return cbb->u.child.base->buf + cbb->u.child.offset + cbb->u.child.pending_len_len; @@ -280,7 +295,7 @@ const uint8_t *CBB_data(const CBB *cbb) { } size_t CBB_len(const CBB *cbb) { - assert(cbb->child == NULL); + assert(cbb->child == nullptr); if (cbb->is_child) { assert(cbb->u.child.offset + cbb->u.child.pending_len_len <= cbb->u.child.base->len); @@ -292,7 +307,7 @@ size_t CBB_len(const CBB *cbb) { static int cbb_add_child(CBB *cbb, CBB *out_child, uint8_t len_len, int is_asn1) { - assert(cbb->child == NULL); + assert(cbb->child == nullptr); assert(!is_asn1 || len_len == 1); struct cbb_buffer_st *base = cbb_get_base(cbb); size_t offset = base->len; @@ -335,7 +350,7 @@ int CBB_add_u24_length_prefixed(CBB *cbb, CBB *out_contents) { return cbb_add_length_prefixed(cbb, out_contents, 3); } -// add_base128_integer encodes |v| as a big-endian base-128 integer where the +// add_base128_integer encodes `v` as a big-endian base-128 integer where the // high bit of each byte indicates where there is more data. This is the // encoding used in DER for both high tag number form and OID components. static int add_base128_integer(CBB *cbb, uint64_t v) { @@ -361,6 +376,13 @@ static int add_base128_integer(CBB *cbb, uint64_t v) { return 1; } +int bssl::cbb_add_decimal_ascii(CBB *out, uint64_t v) { + char buf[DECIMAL_SIZE(uint64_t) + 1]; + snprintf(buf, sizeof(buf), "%" PRIu64, v); + return CBB_add_bytes(out, reinterpret_cast(buf), + strlen(buf)); +} + int CBB_add_asn1(CBB *cbb, CBB *out_contents, CBS_ASN1_TAG tag) { if (!CBB_flush(cbb)) { return 0; @@ -379,7 +401,7 @@ int CBB_add_asn1(CBB *cbb, CBB *out_contents, CBS_ASN1_TAG tag) { return 0; } - // Reserve one byte of length prefix. |CBB_flush| will finish it later. + // Reserve one byte of length prefix. `CBB_flush` will finish it later. return cbb_add_child(cbb, out_contents, /*len_len=*/1, /*is_asn1=*/1); } @@ -419,7 +441,8 @@ int CBB_reserve(CBB *cbb, uint8_t **out_data, size_t len) { int CBB_did_write(CBB *cbb, size_t len) { struct cbb_buffer_st *base = cbb_get_base(cbb); size_t newlen = base->len + len; - if (cbb->child != NULL || newlen < base->len || newlen > base->cap) { + if (cbb->child != nullptr || newlen < base->len || newlen > base->cap) { + OPENSSL_PUT_ERROR(CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } base->len = newlen; @@ -437,8 +460,9 @@ static int cbb_add_u(CBB *cbb, uint64_t v, size_t len_len) { v >>= 8; } - // |v| must fit in |len_len| bytes. + // `v` must fit in `len_len` bytes. if (v != 0) { + OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW); cbb_on_error(cbb); return 0; } @@ -462,14 +486,23 @@ int CBB_add_u32le(CBB *cbb, uint32_t value) { return CBB_add_u32(cbb, CRYPTO_bswap4(value)); } +int CBB_add_u48(CBB *cbb, uint64_t value) { return cbb_add_u(cbb, value, 6); } + int CBB_add_u64(CBB *cbb, uint64_t value) { return cbb_add_u(cbb, value, 8); } int CBB_add_u64le(CBB *cbb, uint64_t value) { return CBB_add_u64(cbb, CRYPTO_bswap8(value)); } +void CBB_discard(CBB *cbb, size_t len) { + BSSL_CHECK(cbb->child == nullptr); + BSSL_CHECK(len <= CBB_len(cbb)); + struct cbb_buffer_st *base = cbb_get_base(cbb); + base->len -= len; +} + void CBB_discard_child(CBB *cbb) { - if (cbb->child == NULL) { + if (cbb->child == nullptr) { return; } @@ -477,8 +510,21 @@ void CBB_discard_child(CBB *cbb) { assert(cbb->child->is_child); base->len = cbb->child->u.child.offset; - cbb->child->u.child.base = NULL; - cbb->child = NULL; + cbb->child->u.child.base = nullptr; + cbb->child = nullptr; +} + +int CBB_add_asn1_element(CBB *cbb, CBS_ASN1_TAG tag, const uint8_t *data, + size_t data_len) { + CBB child; + if (!CBB_add_asn1(cbb, &child, tag) || + !CBB_add_bytes(&child, data, data_len) || // + !CBB_flush(cbb)) { + cbb_on_error(cbb); + return 0; + } + + return 1; } int CBB_add_asn1_uint64(CBB *cbb, uint64_t value) { @@ -557,14 +603,7 @@ err: } int CBB_add_asn1_octet_string(CBB *cbb, const uint8_t *data, size_t data_len) { - CBB child; - if (!CBB_add_asn1(cbb, &child, CBS_ASN1_OCTETSTRING) || - !CBB_add_bytes(&child, data, data_len) || !CBB_flush(cbb)) { - cbb_on_error(cbb); - return 0; - } - - return 1; + return CBB_add_asn1_element(cbb, CBS_ASN1_OCTETSTRING, data, data_len); } int CBB_add_asn1_bool(CBB *cbb, int value) { @@ -578,9 +617,9 @@ int CBB_add_asn1_bool(CBB *cbb, int value) { return 1; } -// parse_dotted_decimal parses one decimal component from |cbs|, where |cbs| is +// parse_dotted_decimal parses one decimal component from `cbs`, where `cbs` is // an OID literal, e.g., "1.2.840.113554.4.1.72585". It consumes both the -// component and the dot, so |cbs| may be passed into the function again for the +// component and the dot, so `cbs` may be passed into the function again for the // next value. static int parse_dotted_decimal(CBS *cbs, uint64_t *out) { if (!CBS_get_u64_decimal(cbs, out)) { @@ -608,8 +647,8 @@ int CBB_add_asn1_oid_from_text(CBB *cbb, const char *text, size_t len) { return 0; } - // The first component is encoded as 40 * |a| + |b|. This assumes that |a| is - // 0, 1, or 2 and that, when it is 0 or 1, |b| is at most 39. + // The first component is encoded as 40 * `a` + `b`. This assumes that `a` is + // 0, 1, or 2 and that, when it is 0 or 1, `b` is at most 39. if (a > 2 || (a < 2 && b > 39) || b > UINT64_MAX - 80 || !add_base128_integer(cbb, 40u * a + b)) { return 0; @@ -625,23 +664,56 @@ int CBB_add_asn1_oid_from_text(CBB *cbb, const char *text, size_t len) { return 1; } -static int compare_set_of_element(const void *a_ptr, const void *b_ptr) { - // See X.690, section 11.6 for the ordering. They are sorted in ascending - // order by their DER encoding. - const CBS *a = reinterpret_cast(a_ptr), - *b = reinterpret_cast(b_ptr); - size_t a_len = CBS_len(a), b_len = CBS_len(b); - size_t min_len = a_len < b_len ? a_len : b_len; - int ret = OPENSSL_memcmp(CBS_data(a), CBS_data(b), min_len); - if (ret != 0) { - return ret; - } - if (a_len == b_len) { +int CBB_add_asn1_relative_oid_from_text(CBB *cbb, const char *text, + size_t len) { + if (!CBB_flush(cbb)) { return 0; } - // If one is a prefix of the other, the shorter one sorts first. (This is not - // actually reachable. No DER encoding is a prefix of another DER encoding.) - return a_len < b_len ? -1 : 1; + + // Relative OIDs must have at least one component. + if (!len) { + return 0; + } + + CBS cbs; + CBS_init(&cbs, reinterpret_cast(text), len); + + while (CBS_len(&cbs) > 0) { + uint64_t a; + if (!parse_dotted_decimal(&cbs, &a) || !add_base128_integer(cbb, a)) { + return 0; + } + } + + return 1; +} + +int CBB_add_asn1_relative_oid_from_der_to_text(CBB *cbb, const uint8_t *data, + size_t data_len) { + CBS der; + CBS_init(&der, data, data_len); + // Relative OIDs must have at least one component. + uint64_t v; + if (!CBS_get_asn1_oid_component(&der, &v) || !cbb_add_decimal_ascii(cbb, v)) { + return 0; + } + + while (CBS_len(&der) != 0) { + if (!CBS_get_asn1_oid_component(&der, &v) || !CBB_add_u8(cbb, '.') || + !cbb_add_decimal_ascii(cbb, v)) { + return 0; + } + } + + return 1; +} + +int CBB_add_asn1_oid_component(CBB *cbb, uint64_t value) { + if (!CBB_flush(cbb)) { + return 0; + } + + return add_base128_integer(cbb, value); } int CBB_flush_asn1_set_of(CBB *cbb) { @@ -649,11 +721,10 @@ int CBB_flush_asn1_set_of(CBB *cbb) { return 0; } - CBS cbs; size_t num_children = 0; - CBS_init(&cbs, CBB_data(cbb), CBB_len(cbb)); + CBS cbs(CBBAsSpan(cbb)); while (CBS_len(&cbs) != 0) { - if (!CBS_get_any_asn1_element(&cbs, NULL, NULL, NULL)) { + if (!CBS_get_any_asn1_element(&cbs, nullptr, nullptr, nullptr)) { OPENSSL_PUT_ERROR(CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } @@ -665,38 +736,52 @@ int CBB_flush_asn1_set_of(CBB *cbb) { } // Parse out the children and sort. We alias them into a copy of so they - // remain valid as we rewrite |cbb|. - int ret = 0; - size_t buf_len = CBB_len(cbb); - uint8_t *buf = - reinterpret_cast(OPENSSL_memdup(CBB_data(cbb), buf_len)); - CBS *children = - reinterpret_cast(OPENSSL_calloc(num_children, sizeof(CBS))); - uint8_t *out; - size_t offset = 0; - if (buf == NULL || children == NULL) { - goto err; + // remain valid as we rewrite `cbb`. + Array copy; + Array children; + if (!copy.CopyFrom(CBBAsSpan(cbb)) || // + !children.Init(num_children)) { + return 0; } - CBS_init(&cbs, buf, buf_len); + cbs = CBS(copy); for (size_t i = 0; i < num_children; i++) { - if (!CBS_get_any_asn1_element(&cbs, &children[i], NULL, NULL)) { - goto err; + if (!CBS_get_any_asn1_element(&cbs, &children[i], nullptr, nullptr)) { + OPENSSL_PUT_ERROR(CRYPTO, ERR_R_INTERNAL_ERROR); + return 0; } } - qsort(children, num_children, sizeof(CBS), compare_set_of_element); + 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; + }); // Write the contents back in the new order. - out = (uint8_t *)CBB_data(cbb); + uint8_t *out = const_cast(CBB_data(cbb)); + size_t offset = 0; for (size_t i = 0; i < num_children; i++) { OPENSSL_memcpy(out + offset, CBS_data(&children[i]), CBS_len(&children[i])); offset += CBS_len(&children[i]); } - assert(offset == buf_len); - - ret = 1; - -err: - OPENSSL_free(buf); - OPENSSL_free(children); - return ret; + assert(offset == copy.size()); + return 1; +} + +bool bssl::CBBFinishArray(CBB *cbb, Array *out) { + uint8_t *ptr; + size_t len; + if (!CBB_finish(cbb, &ptr, &len)) { + OPENSSL_PUT_ERROR(CRYPTO, ERR_R_INTERNAL_ERROR); + return false; + } + out->Reset(ptr, len); + return true; } diff --git a/Sources/CNIOBoringSSL/crypto/bytestring/cbs.cc b/Sources/CNIOBoringSSL/crypto/bytestring/cbs.cc index 5a2bfc93..2ff0659c 100644 --- a/Sources/CNIOBoringSSL/crypto/bytestring/cbs.cc +++ b/Sources/CNIOBoringSSL/crypto/bytestring/cbs.cc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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 @@ -18,7 +18,6 @@ #include #include -#include #include #include "../asn1/internal.h" @@ -26,6 +25,8 @@ #include "internal.h" +using namespace bssl; + static int cbs_get(CBS *cbs, const uint8_t **p, size_t n) { if (cbs->len < n) { return 0; @@ -44,14 +45,14 @@ int CBS_skip(CBS *cbs, size_t len) { int CBS_stow(const CBS *cbs, uint8_t **out_ptr, size_t *out_len) { OPENSSL_free(*out_ptr); - *out_ptr = NULL; + *out_ptr = nullptr; *out_len = 0; if (cbs->len == 0) { return 1; } *out_ptr = reinterpret_cast(OPENSSL_memdup(cbs->data, cbs->len)); - if (*out_ptr == NULL) { + if (*out_ptr == nullptr) { return 0; } *out_len = cbs->len; @@ -59,15 +60,15 @@ int CBS_stow(const CBS *cbs, uint8_t **out_ptr, size_t *out_len) { } int CBS_strdup(const CBS *cbs, char **out_ptr) { - if (*out_ptr != NULL) { + if (*out_ptr != nullptr) { OPENSSL_free(*out_ptr); } *out_ptr = OPENSSL_strndup((const char *)cbs->data, cbs->len); - return (*out_ptr != NULL); + return (*out_ptr != nullptr); } int CBS_contains_zero_byte(const CBS *cbs) { - return OPENSSL_memchr(cbs->data, 0, cbs->len) != NULL; + return OPENSSL_memchr(cbs->data, 0, cbs->len) != nullptr; } int CBS_mem_equal(const CBS *cbs, const uint8_t *data, size_t len) { @@ -144,6 +145,8 @@ int CBS_get_u32le(CBS *cbs, uint32_t *out) { return 1; } +int CBS_get_u48(CBS *cbs, uint64_t *out) { return cbs_get_u(cbs, out, 6); } + int CBS_get_u64(CBS *cbs, uint64_t *out) { return cbs_get_u(cbs, out, 8); } int CBS_get_u64le(CBS *cbs, uint64_t *out) { @@ -186,7 +189,7 @@ static int cbs_get_length_prefixed(CBS *cbs, CBS *out, size_t len_len) { if (!cbs_get_u(cbs, &len, len_len)) { return 0; } - // If |len_len| <= 3 then we know that |len| will fit into a |size_t|, even on + // If `len_len` <= 3 then we know that `len` will fit into a `size_t`, even on // 32-bit systems. assert(len_len <= 3); return CBS_get_bytes(cbs, out, len); @@ -207,12 +210,48 @@ int CBS_get_u24_length_prefixed(CBS *cbs, CBS *out) { int CBS_get_until_first(CBS *cbs, CBS *out, uint8_t c) { const uint8_t *split = reinterpret_cast( OPENSSL_memchr(CBS_data(cbs), c, CBS_len(cbs))); - if (split == NULL) { + if (split == nullptr) { return 0; } return CBS_get_bytes(cbs, out, split - CBS_data(cbs)); } +int CBS_get_until_first_of(CBS *cbs, CBS *out, const char *chars) { + size_t pos = 0; + while (pos < CBS_len(cbs)) { + uint8_t c = CBS_data(cbs)[pos]; + // Special-case for \0 characters. We don't want to match on a null byte, + // even though strchr will happily return the \0 at the end of `chars`. + if (!c || !strchr(chars, c)) { + pos++; + } else { + break; + } + } + if (pos == CBS_len(cbs)) { + return 0; + } + return CBS_get_bytes(cbs, out, pos); +} + +int CBS_get_until_first_not_of(CBS *cbs, CBS *out, const char *chars) { + size_t pos = 0; + while (pos < CBS_len(cbs)) { + uint8_t c = CBS_data(cbs)[pos]; + // Special-case for \0 characters. We don't want to match on a null byte, + // even though strchr will happily return the \0 at the end of `chars`. + if (c && strchr(chars, c)) { + pos++; + } else { + break; + } + } + if (pos == CBS_len(cbs)) { + return 0; + } + return CBS_get_bytes(cbs, out, pos); +} + int CBS_get_u64_decimal(CBS *cbs, uint64_t *out) { uint64_t v = 0; int seen_digit = 0; @@ -237,10 +276,7 @@ int CBS_get_u64_decimal(CBS *cbs, uint64_t *out) { return seen_digit; } -// parse_base128_integer reads a big-endian base-128 integer from |cbs| and sets -// |*out| to the result. This is the encoding used in DER for both high tag -// number form and OID components. -static int parse_base128_integer(CBS *cbs, uint64_t *out) { +int CBS_get_asn1_oid_component(CBS *cbs, uint64_t *out) { uint64_t v = 0; uint8_t b; do { @@ -279,8 +315,9 @@ static int parse_asn1_tag(CBS *cbs, CBS_ASN1_TAG *out) { CBS_ASN1_TAG tag = ((CBS_ASN1_TAG)tag_byte & 0xe0) << CBS_ASN1_TAG_SHIFT; CBS_ASN1_TAG tag_number = tag_byte & 0x1f; if (tag_number == 0x1f) { + // High tag numbers are encoded in the same format as OID components. uint64_t v; - if (!parse_base128_integer(cbs, &v) || + if (!CBS_get_asn1_oid_component(cbs, &v) || // Check the tag number is within our supported bounds. v > CBS_ASN1_TAG_NUMBER_MASK || // Small tag numbers should have used low tag number form, even in BER. @@ -309,22 +346,22 @@ static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag, CBS header = *cbs; CBS throwaway; - if (out == NULL) { + if (out == nullptr) { out = &throwaway; } if (ber_ok) { *out_ber_found = 0; *out_indefinite = 0; } else { - assert(out_ber_found == NULL); - assert(out_indefinite == NULL); + assert(out_ber_found == nullptr); + assert(out_indefinite == nullptr); } CBS_ASN1_TAG tag; if (!parse_asn1_tag(&header, &tag)) { return 0; } - if (out_tag != NULL) { + if (out_tag != nullptr) { *out_tag = tag; } @@ -341,7 +378,7 @@ static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag, if ((length_byte & 0x80) == 0) { // Short form length. len = ((size_t)length_byte) + header_len; - if (out_header_len != NULL) { + if (out_header_len != nullptr) { *out_header_len = header_len; } } else { @@ -353,7 +390,7 @@ static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag, if (ber_ok && (tag & CBS_ASN1_CONSTRUCTED) != 0 && num_bytes == 0) { // indefinite length - if (out_header_len != NULL) { + if (out_header_len != nullptr) { *out_header_len = header_len; } *out_ber_found = 1; @@ -373,7 +410,7 @@ static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag, // ITU-T X.690 section 10.1 (DER length forms) requires encoding the // length with the minimum number of octets. BER could, technically, have // 125 superfluous zero bytes. We do not attempt to handle that and still - // require that the length fit in a |uint32_t| for BER. + // require that the length fit in a `uint32_t` for BER. if (len64 < 128) { // Length should have used short-form encoding. if (ber_ok) { @@ -396,7 +433,7 @@ static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag, return 0; } len += header_len + num_bytes; - if (out_header_len != NULL) { + if (out_header_len != nullptr) { *out_header_len = header_len + num_bytes; } } @@ -410,7 +447,7 @@ int CBS_get_any_asn1(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag) { return 0; } - if (!CBS_skip(out, header_len)) { + if (out && !CBS_skip(out, header_len)) { assert(0); return 0; } @@ -420,7 +457,8 @@ int CBS_get_any_asn1(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag) { int CBS_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag, size_t *out_header_len) { - return cbs_get_any_asn1_element(cbs, out, out_tag, out_header_len, NULL, NULL, + return cbs_get_any_asn1_element(cbs, out, out_tag, out_header_len, nullptr, + nullptr, /*ber_ok=*/0); } @@ -440,7 +478,7 @@ static int cbs_get_asn1(CBS *cbs, CBS *out, CBS_ASN1_TAG tag_value, CBS_ASN1_TAG tag; CBS throwaway; - if (out == NULL) { + if (out == nullptr) { out = &throwaway; } @@ -465,15 +503,29 @@ int CBS_get_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG tag_value) { return cbs_get_asn1(cbs, out, tag_value, 0 /* include header */); } -int CBS_peek_asn1_tag(const CBS *cbs, CBS_ASN1_TAG tag_value) { +CBS_ASN1_TAG CBS_peek_any_asn1_tag(const CBS *cbs) { CBS copy = *cbs; - CBS_ASN1_TAG actual_tag; - return parse_asn1_tag(©, &actual_tag) && tag_value == actual_tag; + CBS_ASN1_TAG tag; + if (!parse_asn1_tag(©, &tag)) { + return 0; + } + return tag; +} + +int CBS_peek_asn1_tag(const CBS *cbs, CBS_ASN1_TAG tag_value) { + CBS_ASN1_TAG actual_tag = CBS_peek_any_asn1_tag(cbs); + // The caller should never pass zero as |tag_value|, but return zero if they + // did. + return actual_tag != 0 && actual_tag == tag_value; } int CBS_get_asn1_uint64(CBS *cbs, uint64_t *out) { + return CBS_get_asn1_uint64_with_tag(cbs, out, CBS_ASN1_INTEGER); +} + +int CBS_get_asn1_uint64_with_tag(CBS *cbs, uint64_t *out, CBS_ASN1_TAG tag) { CBS bytes; - if (!CBS_get_asn1(cbs, &bytes, CBS_ASN1_INTEGER) || + if (!CBS_get_asn1(cbs, &bytes, tag) || !CBS_is_unsigned_asn1_integer(&bytes)) { return 0; } @@ -494,9 +546,13 @@ int CBS_get_asn1_uint64(CBS *cbs, uint64_t *out) { } int CBS_get_asn1_int64(CBS *cbs, int64_t *out) { + return CBS_get_asn1_int64_with_tag(cbs, out, CBS_ASN1_INTEGER); +} + +int CBS_get_asn1_int64_with_tag(CBS *cbs, int64_t *out, CBS_ASN1_TAG tag) { int is_negative; CBS bytes; - if (!CBS_get_asn1(cbs, &bytes, CBS_ASN1_INTEGER) || + if (!CBS_get_asn1(cbs, &bytes, tag) || !CBS_is_valid_asn1_integer(&bytes, &is_negative)) { return 0; } @@ -538,7 +594,7 @@ int CBS_get_optional_asn1(CBS *cbs, CBS *out, int *out_present, present = 1; } - if (out_present != NULL) { + if (out_present != nullptr) { *out_present = present; } @@ -559,7 +615,7 @@ int CBS_get_optional_asn1_octet_string(CBS *cbs, CBS *out, int *out_present, return 0; } } else { - CBS_init(out, NULL, 0); + CBS_init(out, nullptr, 0); } if (out_present) { *out_present = present; @@ -655,7 +711,7 @@ int CBS_is_valid_asn1_integer(const CBS *cbs, int *out_is_negative) { if (!CBS_get_u8(©, &first_byte)) { return 0; // INTEGERs may not be empty. } - if (out_is_negative != NULL) { + if (out_is_negative != nullptr) { *out_is_negative = (first_byte & 0x80) != 0; } if (!CBS_get_u8(©, &second_byte)) { @@ -673,12 +729,6 @@ int CBS_is_unsigned_asn1_integer(const CBS *cbs) { return CBS_is_valid_asn1_integer(cbs, &is_negative) && !is_negative; } -static int add_decimal(CBB *out, uint64_t v) { - char buf[DECIMAL_SIZE(uint64_t) + 1]; - snprintf(buf, sizeof(buf), "%" PRIu64, v); - return CBB_add_bytes(out, (const uint8_t *)buf, strlen(buf)); -} - int CBS_is_valid_asn1_oid(const CBS *cbs) { if (CBS_len(cbs) == 0) { return 0; // OID encodings cannot be empty. @@ -688,9 +738,9 @@ int CBS_is_valid_asn1_oid(const CBS *cbs) { uint8_t v, prev = 0; while (CBS_get_u8(©, &v)) { // OID encodings are a sequence of minimally-encoded base-128 integers (see - // |parse_base128_integer|). If |prev|'s MSB was clear, it was the last byte - // of an integer (or |v| is the first byte). |v| is then the first byte of - // the next integer. If first byte of an integer is 0x80, it is not + // `CBS_get_asn1_oid_component`). If `prev`'s MSB was clear, it was the last + // byte of an integer (or `v` is the first byte). `v` is then the first byte + // of the next integer. If first byte of an integer is 0x80, it is not // minimally-encoded. if ((prev & 0x80) == 0 && v == 0x80) { return 0; @@ -711,23 +761,23 @@ char *CBS_asn1_oid_to_text(const CBS *cbs) { // The first component is 40 * value1 + value2, where value1 is 0, 1, or 2. uint64_t v; - if (!parse_base128_integer(©, &v)) { + if (!CBS_get_asn1_oid_component(©, &v)) { goto err; } if (v >= 80) { if (!CBB_add_bytes(&cbb, (const uint8_t *)"2.", 2) || - !add_decimal(&cbb, v - 80)) { + !cbb_add_decimal_ascii(&cbb, v - 80)) { goto err; } - } else if (!add_decimal(&cbb, v / 40) || !CBB_add_u8(&cbb, '.') || - !add_decimal(&cbb, v % 40)) { + } else if (!cbb_add_decimal_ascii(&cbb, v / 40) || !CBB_add_u8(&cbb, '.') || + !cbb_add_decimal_ascii(&cbb, v % 40)) { goto err; } while (CBS_len(©) != 0) { - if (!parse_base128_integer(©, &v) || !CBB_add_u8(&cbb, '.') || - !add_decimal(&cbb, v)) { + if (!CBS_get_asn1_oid_component(©, &v) || !CBB_add_u8(&cbb, '.') || + !cbb_add_decimal_ascii(&cbb, v)) { goto err; } } @@ -742,7 +792,30 @@ char *CBS_asn1_oid_to_text(const CBS *cbs) { err: CBB_cleanup(&cbb); - return NULL; + return nullptr; +} + +int CBS_is_valid_asn1_relative_oid(const CBS *cbs) { + return CBS_is_valid_asn1_oid(cbs); +} + +char *CBS_asn1_relative_oid_to_text(const CBS *cbs) { + ScopedCBB cbb; + if (!CBB_init(cbb.get(), 32)) { + return nullptr; + } + if (!CBB_add_asn1_relative_oid_from_der_to_text(cbb.get(), CBS_data(cbs), + CBS_len(cbs))) { + return nullptr; + } + + uint8_t *txt; + size_t txt_len; + if (!CBB_add_u8(cbb.get(), '\0') || !CBB_finish(cbb.get(), &txt, &txt_len)) { + return nullptr; + } + + return reinterpret_cast(txt); } static int cbs_get_two_digits(CBS *cbs, int *out) { @@ -838,10 +911,10 @@ static int CBS_parse_rfc5280_time_internal(const CBS *cbs, int is_gentime, case 'Z': break; // We correctly have 'Z' on the end as per spec. case '+': - offset_sign = 1; + offset_sign = -1; break; // Should not be allowed per RFC 5280. case '-': - offset_sign = -1; + offset_sign = 1; break; // Should not be allowed per RFC 5280. default: return 0; // Reject anything else after the time. @@ -850,7 +923,7 @@ static int CBS_parse_rfc5280_time_internal(const CBS *cbs, int is_gentime, // If allow_timezone_offset is non-zero, allow for a four digit timezone // offset to be specified even though this is not allowed by RFC 5280. We are // permissive of this for UTCTimes due to the unfortunate existence of - // artisinally rolled long lived certificates that were baked into places that + // artisanally rolled long lived certificates that were baked into places that // are now difficult to change. These certificates were generated with the // 'openssl' command that permissively allowed the creation of certificates // with notBefore and notAfter times specified as strings for direct @@ -878,7 +951,7 @@ static int CBS_parse_rfc5280_time_internal(const CBS *cbs, int is_gentime, return 0; // Reject invalid lengths. } - if (out_tm != NULL) { + if (out_tm != nullptr) { // Fill in the tm fields corresponding to what we validated. out_tm->tm_year = year - 1900; out_tm->tm_mon = month - 1; diff --git a/Sources/CNIOBoringSSL/crypto/bytestring/internal.h b/Sources/CNIOBoringSSL/crypto/bytestring/internal.h index 03d8064c..6f646318 100644 --- a/Sources/CNIOBoringSSL/crypto/bytestring/internal.h +++ b/Sources/CNIOBoringSSL/crypto/bytestring/internal.h @@ -1,39 +1,43 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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. -#ifndef OPENSSL_HEADER_BYTESTRING_INTERNAL_H -#define OPENSSL_HEADER_BYTESTRING_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_BYTESTRING_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_BYTESTRING_INTERNAL_H -#include +#include +#include +#include -#if defined(__cplusplus) -extern "C" { -#endif +#include + +#include "../mem_internal.h" -// CBS_asn1_ber_to_der reads a BER element from |in|. If it finds +BSSL_NAMESPACE_BEGIN + +// CBS_asn1_ber_to_der reads a BER element from `in`. If it finds // indefinite-length elements or constructed strings then it converts the BER -// data to DER, sets |out| to the converted contents and |*out_storage| to a -// buffer which the caller must release with |OPENSSL_free|. Otherwise, it sets -// |out| to the original BER element in |in| and |*out_storage| to NULL. -// Additionally, |*in| will be advanced over the BER element. +// data to DER, sets `out` to the converted contents and `*out_storage` to a +// buffer which the caller must release with `OPENSSL_free`. Otherwise, it sets +// `out` to the original BER element in `in` and `*out_storage` to NULL. +// Additionally, `*in` will be advanced over the BER element. // // This function should successfully process any valid BER input, however it // will not convert all of BER's deviations from DER. BER is ambiguous between // implicitly-tagged SEQUENCEs of strings and implicitly-tagged constructed // strings. Implicitly-tagged strings must be parsed with -// |CBS_get_ber_implicitly_tagged_string| instead of |CBS_get_asn1|. The caller +// `CBS_get_ber_implicitly_tagged_string` instead of `CBS_get_asn1`. The caller // must also account for BER variations in the contents of a primitive. // // It returns one on success and zero otherwise. @@ -41,15 +45,15 @@ OPENSSL_EXPORT int CBS_asn1_ber_to_der(CBS *in, CBS *out, uint8_t **out_storage); // CBS_get_asn1_implicit_string parses a BER string of primitive type -// |inner_tag| implicitly-tagged with |outer_tag|. It sets |out| to the -// contents. If concatenation was needed, it sets |*out_storage| to a buffer -// which the caller must release with |OPENSSL_free|. Otherwise, it sets -// |*out_storage| to NULL. +// `inner_tag` implicitly-tagged with `outer_tag`. It sets `out` to the +// contents. If concatenation was needed, it sets `*out_storage` to a buffer +// which the caller must release with `OPENSSL_free`. Otherwise, it sets +// `*out_storage` to NULL. // // This function does not parse all of BER. It requires the string be // definite-length. Constructed strings are allowed, but all children of the // outermost element must be primitive. The caller should use -// |CBS_asn1_ber_to_der| before running this function. +// `CBS_asn1_ber_to_der` before running this function. // // It returns one on success and zero otherwise. OPENSSL_EXPORT int CBS_get_asn1_implicit_string(CBS *in, CBS *out, @@ -57,18 +61,74 @@ OPENSSL_EXPORT int CBS_get_asn1_implicit_string(CBS *in, CBS *out, CBS_ASN1_TAG outer_tag, CBS_ASN1_TAG inner_tag); -// CBB_finish_i2d calls |CBB_finish| on |cbb| which must have been initialized -// with |CBB_init|. If |outp| is not NULL then the result is written to |*outp| -// and |*outp| is advanced just past the output. It returns the number of bytes -// in the result, whether written or not, or a negative value on error. On -// error, it calls |CBB_cleanup| on |cbb|. +// CBB_finish_i2d calls `CBB_finish` on `cbb` which must have been initialized +// with `CBB_init`. If `outp` is not NULL then the result is written to `*outp` +// and `*outp` is advanced just past the output. It returns the number of bytes +// in the result, whether written or not, or a negative value on error. // // This function may be used to help implement legacy i2d ASN.1 functions. -int CBB_finish_i2d(CBB *cbb, uint8_t **outp); +OPENSSL_EXPORT int CBB_finish_i2d(CBB *cbb, uint8_t **outp); +// CBBAsSpan returns a span containing `cbb`'s contents. It does not flush +// `cbb`. The span is valid until the next operation to `cbb`. +// +// To avoid unfinalized length prefixes, it is a fatal error to call this on a +// CBB with any active children. +inline Span CBBAsSpan(const CBB *cbb) { + return Span(CBB_data(cbb), CBB_len(cbb)); +} -#if defined(__cplusplus) -} // extern C -#endif +// CBBFinishArray behaves like `CBB_finish` but stores the result in an Array. +OPENSSL_EXPORT bool CBBFinishArray(CBB *cbb, Array *out); -#endif // OPENSSL_HEADER_BYTESTRING_INTERNAL_H +// D2IFromCBS takes a functor of type `Unique(CBS*)` and implements the d2i +// calling convention. For compatibility with functions that don't tag their +// return value (e.g. public APIs), `T*(CBS)` is also accepted. The callback can +// assume that the `CBS`'s length fits in `long`. The callback should not access +// `out`, `inp`, or `len` directly. +template +inline T *D2IFromCBS(T **out, const uint8_t **inp, long len, CBSFunc func) { + static_assert(std::is_invocable_v); + static_assert( + std::is_same_v, UniquePtr> || + std::is_same_v, T *>); + if (len < 0) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_BUFFER_TOO_SMALL); + return nullptr; + } + CBS cbs; + CBS_init(&cbs, *inp, len); + UniquePtr ret(func(&cbs)); + if (ret == nullptr) { + return nullptr; + } + if (out != nullptr) { + UniquePtr free_out(*out); + *out = ret.get(); + } + *inp = CBS_data(&cbs); + return ret.release(); +} + +// I2DFromCBB takes a functor of type `bool(CBB*)` and implements the i2d +// calling convention. It internally makes a `CBB` with the specified initial +// capacity. The callback should not access `outp` directly. +template +inline int I2DFromCBB(size_t initial_capacity, uint8_t **outp, CBBFunc func) { + static_assert(std::is_invocable_v); + static_assert(std::is_same_v, bool>); + ScopedCBB cbb; + if (!CBB_init(cbb.get(), initial_capacity) || !func(cbb.get())) { + return -1; + } + return CBB_finish_i2d(cbb.get(), outp); +} + +// cbb_add_decimal_ascii adds the characters of an ASCII string representation +// of `v` as a decimal value to `out` (without a terminating NUL byte). It +// returns one on success and zero on error. +int cbb_add_decimal_ascii(CBB *out, uint64_t v); + +BSSL_NAMESPACE_END + +#endif // OPENSSL_HEADER_CRYPTO_BYTESTRING_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/bytestring/unicode.cc b/Sources/CNIOBoringSSL/crypto/bytestring/unicode.cc index e78400f1..6ea832dd 100644 --- a/Sources/CNIOBoringSSL/crypto/bytestring/unicode.cc +++ b/Sources/CNIOBoringSSL/crypto/bytestring/unicode.cc @@ -1,16 +1,16 @@ -/* Copyright 2018 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2018 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 @@ -33,10 +33,10 @@ static int is_valid_code_point(uint32_t v) { return 1; } -// BOTTOM_BITS returns a byte with the bottom |n| bits set. +// BOTTOM_BITS returns a byte with the bottom `n` bits set. #define BOTTOM_BITS(n) (uint8_t)((1u << (n)) - 1) -// TOP_BITS returns a byte with the top |n| bits set. +// TOP_BITS returns a byte with the top `n` bits set. #define TOP_BITS(n) ((uint8_t)~BOTTOM_BITS(8 - (n))) int CBS_get_utf8(CBS *cbs, uint32_t *out) { diff --git a/Sources/CNIOBoringSSL/crypto/chacha/chacha.cc b/Sources/CNIOBoringSSL/crypto/chacha/chacha.cc index c5b63a26..ce9155b0 100644 --- a/Sources/CNIOBoringSSL/crypto/chacha/chacha.cc +++ b/Sources/CNIOBoringSSL/crypto/chacha/chacha.cc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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. // Adapted from the public domain, estream code by D. Bernstein. @@ -24,6 +24,8 @@ // sigma contains the ChaCha constants, which happen to be an ASCII string. +using namespace bssl; + static const uint8_t sigma[16] = { 'e', 'x', 'p', 'a', 'n', 'd', ' ', '3', '2', '-', 'b', 'y', 't', 'e', ' ', 'k' }; @@ -38,8 +40,8 @@ static const uint8_t sigma[16] = { 'e', 'x', 'p', 'a', 'n', 'd', ' ', '3', x[c] += x[d]; \ x[b] = CRYPTO_rotl_u32(x[b] ^ x[c], 7); -void CRYPTO_hchacha20(uint8_t out[32], const uint8_t key[32], - const uint8_t nonce[16]) { +void bssl::CRYPTO_hchacha20(uint8_t out[32], const uint8_t key[32], + const uint8_t nonce[16]) { uint32_t x[16]; OPENSSL_memcpy(x, sigma, sizeof(sigma)); OPENSSL_memcpy(&x[4], key, 32); @@ -148,7 +150,7 @@ void CRYPTO_chacha_20(uint8_t *out, const uint8_t *in, size_t in_len, #else // chacha_core performs 20 rounds of ChaCha on the input words in -// |input| and writes the 64 output bytes to |output|. +// `input` and writes the 64 output bytes to `output`. static void chacha_core(uint8_t output[64], const uint32_t input[16]) { uint32_t x[16]; int i; diff --git a/Sources/CNIOBoringSSL/crypto/chacha/internal.h b/Sources/CNIOBoringSSL/crypto/chacha/internal.h index 8d290d79..3f86a9a5 100644 --- a/Sources/CNIOBoringSSL/crypto/chacha/internal.h +++ b/Sources/CNIOBoringSSL/crypto/chacha/internal.h @@ -1,28 +1,26 @@ -/* Copyright 2018 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2018 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. -#ifndef OPENSSL_HEADER_CHACHA_INTERNAL -#define OPENSSL_HEADER_CHACHA_INTERNAL +#ifndef OPENSSL_HEADER_CRYPTO_CHACHA_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_CHACHA_INTERNAL_H #include #include "../internal.h" -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN // CRYPTO_hchacha20 computes the HChaCha20 function, which should only be used // as part of XChaCha20. @@ -37,10 +35,11 @@ void CRYPTO_hchacha20(uint8_t out[32], const uint8_t key[32], inline int ChaCha20_ctr32_ssse3_capable(size_t len) { // Unlike the x86_64 version, the x86 SSSE3 routine runs for all non-zero // lengths. - return len > 0 && CRYPTO_is_SSSE3_capable() && CRYPTO_is_FXSR_capable(); + return len > 0 && CRYPTO_is_SSSE3_capable(); } -void ChaCha20_ctr32_ssse3(uint8_t *out, const uint8_t *in, size_t in_len, - const uint32_t key[8], const uint32_t counter[4]); +extern "C" void ChaCha20_ctr32_ssse3(uint8_t *out, const uint8_t *in, + size_t in_len, const uint32_t key[8], + const uint32_t counter[4]); #elif !defined(OPENSSL_NO_ASM) && \ (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) @@ -51,8 +50,9 @@ void ChaCha20_ctr32_ssse3(uint8_t *out, const uint8_t *in, size_t in_len, inline int ChaCha20_ctr32_neon_capable(size_t len) { return len >= 192 && CRYPTO_is_NEON_capable(); } -void ChaCha20_ctr32_neon(uint8_t *out, const uint8_t *in, size_t in_len, - const uint32_t key[8], const uint32_t counter[4]); +extern "C" void ChaCha20_ctr32_neon(uint8_t *out, const uint8_t *in, + size_t in_len, const uint32_t key[8], + const uint32_t counter[4]); #elif !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) #define CHACHA20_ASM_NOHW @@ -60,8 +60,9 @@ void ChaCha20_ctr32_neon(uint8_t *out, const uint8_t *in, size_t in_len, inline int ChaCha20_ctr32_avx2_capable(size_t len) { return len > 128 && CRYPTO_is_AVX2_capable(); } -void ChaCha20_ctr32_avx2(uint8_t *out, const uint8_t *in, size_t in_len, - const uint32_t key[8], const uint32_t counter[4]); +extern "C" void ChaCha20_ctr32_avx2(uint8_t *out, const uint8_t *in, + size_t in_len, const uint32_t key[8], + const uint32_t counter[4]); #define CHACHA20_ASM_SSSE3_4X inline int ChaCha20_ctr32_ssse3_4x_capable(size_t len) { @@ -69,34 +70,34 @@ inline int ChaCha20_ctr32_ssse3_4x_capable(size_t len) { int faster = len > 192 || !CRYPTO_cpu_perf_is_like_silvermont(); return capable && faster; } -void ChaCha20_ctr32_ssse3_4x(uint8_t *out, const uint8_t *in, size_t in_len, - const uint32_t key[8], const uint32_t counter[4]); +extern "C" void ChaCha20_ctr32_ssse3_4x(uint8_t *out, const uint8_t *in, + size_t in_len, const uint32_t key[8], + const uint32_t counter[4]); #define CHACHA20_ASM_SSSE3 inline int ChaCha20_ctr32_ssse3_capable(size_t len) { return len > 128 && CRYPTO_is_SSSE3_capable(); } -void ChaCha20_ctr32_ssse3(uint8_t *out, const uint8_t *in, size_t in_len, - const uint32_t key[8], const uint32_t counter[4]); +extern "C" void ChaCha20_ctr32_ssse3(uint8_t *out, const uint8_t *in, + size_t in_len, const uint32_t key[8], + const uint32_t counter[4]); #endif #if defined(CHACHA20_ASM_NOHW) -// ChaCha20_ctr32_nohw encrypts |in_len| bytes from |in| and writes the result -// to |out|. If |in| and |out| alias, they must be equal. |in_len| may not be +// ChaCha20_ctr32_nohw encrypts `in_len` bytes from `in` and writes the result +// to `out`. If `in` and `out` alias, they must be equal. `in_len` may not be // zero. // -// |counter[0]| is the initial 32-bit block counter, and the remainder is the +// `counter[0]` is the initial 32-bit block counter, and the remainder is the // 96-bit nonce. If the counter overflows, the output is undefined. The function // will produce output, but the output may vary by machine and may not be // self-consistent. (On some architectures, the assembly implements a mix of // 64-bit and 32-bit counters.) -void ChaCha20_ctr32_nohw(uint8_t *out, const uint8_t *in, size_t in_len, - const uint32_t key[8], const uint32_t counter[4]); +extern "C" void ChaCha20_ctr32_nohw(uint8_t *out, const uint8_t *in, + size_t in_len, const uint32_t key[8], + const uint32_t counter[4]); #endif +BSSL_NAMESPACE_END -#if defined(__cplusplus) -} // extern C -#endif - -#endif // OPENSSL_HEADER_CHACHA_INTERNAL +#endif // OPENSSL_HEADER_CRYPTO_CHACHA_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/cipher/derive_key.cc b/Sources/CNIOBoringSSL/crypto/cipher/derive_key.cc index 48ec4038..0a780a73 100644 --- a/Sources/CNIOBoringSSL/crypto/cipher/derive_key.cc +++ b/Sources/CNIOBoringSSL/crypto/cipher/derive_key.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -15,12 +20,9 @@ #include -#define PKCS5_SALT_LEN 8 - int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md, - const uint8_t *salt, const uint8_t *data, size_t data_len, + const uint8_t salt[8], const uint8_t *data, size_t data_len, unsigned count, uint8_t *key, uint8_t *iv) { - EVP_MD_CTX c; uint8_t md_buf[EVP_MAX_MD_SIZE]; unsigned addmd = 0; unsigned mds = 0, i; @@ -32,36 +34,36 @@ int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md, assert(nkey <= EVP_MAX_KEY_LENGTH); assert(niv <= EVP_MAX_IV_LENGTH); - if (data == NULL) { + if (data == nullptr) { return nkey; } - EVP_MD_CTX_init(&c); + bssl::ScopedEVP_MD_CTX c; for (;;) { - if (!EVP_DigestInit_ex(&c, md, NULL)) { + if (!EVP_DigestInit_ex(c.get(), md, nullptr)) { goto err; } if (addmd++) { - if (!EVP_DigestUpdate(&c, md_buf, mds)) { + if (!EVP_DigestUpdate(c.get(), md_buf, mds)) { goto err; } } - if (!EVP_DigestUpdate(&c, data, data_len)) { + if (!EVP_DigestUpdate(c.get(), data, data_len)) { goto err; } - if (salt != NULL) { - if (!EVP_DigestUpdate(&c, salt, PKCS5_SALT_LEN)) { + if (salt != nullptr) { + if (!EVP_DigestUpdate(c.get(), salt, 8)) { goto err; } } - if (!EVP_DigestFinal_ex(&c, md_buf, &mds)) { + if (!EVP_DigestFinal_ex(c.get(), md_buf, &mds)) { goto err; } for (i = 1; i < count; i++) { - if (!EVP_DigestInit_ex(&c, md, NULL) || - !EVP_DigestUpdate(&c, md_buf, mds) || - !EVP_DigestFinal_ex(&c, md_buf, &mds)) { + if (!EVP_DigestInit_ex(c.get(), md, nullptr) || + !EVP_DigestUpdate(c.get(), md_buf, mds) || + !EVP_DigestFinal_ex(c.get(), md_buf, &mds)) { goto err; } } @@ -72,7 +74,7 @@ int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md, if (nkey == 0 || i == mds) { break; } - if (key != NULL) { + if (key != nullptr) { *(key++) = md_buf[i]; } nkey--; @@ -85,7 +87,7 @@ int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md, if (niv == 0 || i == mds) { break; } - if (iv != NULL) { + if (iv != nullptr) { *(iv++) = md_buf[i]; } niv--; @@ -99,7 +101,6 @@ int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md, rv = EVP_CIPHER_key_length(type); err: - EVP_MD_CTX_cleanup(&c); OPENSSL_cleanse(md_buf, EVP_MAX_MD_SIZE); return rv; } diff --git a/Sources/CNIOBoringSSL/crypto/cipher/e_aesctrhmac.cc b/Sources/CNIOBoringSSL/crypto/cipher/e_aesctrhmac.cc index 1fd9edb7..ea7bc779 100644 --- a/Sources/CNIOBoringSSL/crypto/cipher/e_aesctrhmac.cc +++ b/Sources/CNIOBoringSSL/crypto/cipher/e_aesctrhmac.cc @@ -1,16 +1,16 @@ -/* Copyright 2017 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2017 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 @@ -19,12 +19,15 @@ #include #include #include -#include +#include +#include #include "../fipsmodule/aes/internal.h" #include "../fipsmodule/cipher/internal.h" +using namespace bssl; + #define EVP_AEAD_AES_CTR_HMAC_SHA256_TAG_LEN SHA256_DIGEST_LENGTH #define EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN 12 @@ -39,7 +42,7 @@ struct aead_aes_ctr_hmac_sha256_ctx { SHA256_CTX outer_init_state; }; -static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) >= +static_assert(sizeof(((EVP_AEAD_CTX *)nullptr)->state) >= sizeof(struct aead_aes_ctr_hmac_sha256_ctx), "AEAD state is too small"); static_assert(alignof(union evp_aead_ctx_st_state) >= @@ -96,8 +99,8 @@ static int aead_aes_ctr_hmac_sha256_init(EVP_AEAD_CTX *ctx, const uint8_t *key, return 0; } - aes_ctx->ctr = - aes_ctr_set_key(&aes_ctx->ks.ks, NULL, &aes_ctx->block, key, aes_key_len); + aes_ctx->ctr = aes_ctr_set_key(&aes_ctx->ks.ks, nullptr, &aes_ctx->block, key, + aes_key_len); ctx->tag_len = tag_len; hmac_init(&aes_ctx->inner_init_state, &aes_ctx->outer_init_state, key + aes_key_len); @@ -121,19 +124,22 @@ static void hmac_update_uint64(SHA256_CTX *sha256, uint64_t value) { static void hmac_calculate(uint8_t out[SHA256_DIGEST_LENGTH], const SHA256_CTX *inner_init_state, const SHA256_CTX *outer_init_state, - const uint8_t *ad, size_t ad_len, - const uint8_t *nonce, const uint8_t *ciphertext, - size_t ciphertext_len) { + Span aadvecs, + const uint8_t *nonce, + Span iovecs, bool encrypt) { + size_t ad_len = bssl::iovec::TotalLength(aadvecs); SHA256_CTX sha256; OPENSSL_memcpy(&sha256, inner_init_state, sizeof(sha256)); hmac_update_uint64(&sha256, ad_len); - hmac_update_uint64(&sha256, ciphertext_len); + hmac_update_uint64(&sha256, bssl::iovec::TotalLength(iovecs)); SHA256_Update(&sha256, nonce, EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN); - SHA256_Update(&sha256, ad, ad_len); + for (const CRYPTO_IVEC &aadvec : aadvecs) { + SHA256_Update(&sha256, aadvec.in, aadvec.len); + } // Pad with zeros to the end of the SHA-256 block. const unsigned num_padding = - (SHA256_CBLOCK - ((sizeof(uint64_t)*2 + + (SHA256_CBLOCK - ((sizeof(uint64_t) * 2 + EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN + ad_len) % SHA256_CBLOCK)) % SHA256_CBLOCK; @@ -141,7 +147,9 @@ static void hmac_calculate(uint8_t out[SHA256_DIGEST_LENGTH], OPENSSL_memset(padding, 0, num_padding); SHA256_Update(&sha256, padding, num_padding); - SHA256_Update(&sha256, ciphertext, ciphertext_len); + for (const CRYPTO_IOVEC &iovec : iovecs) { + SHA256_Update(&sha256, encrypt ? iovec.out : iovec.in, iovec.len); + } uint8_t inner_digest[SHA256_DIGEST_LENGTH]; SHA256_Final(inner_digest, &sha256); @@ -152,10 +160,8 @@ static void hmac_calculate(uint8_t out[SHA256_DIGEST_LENGTH], } static void aead_aes_ctr_hmac_sha256_crypt( - const struct aead_aes_ctr_hmac_sha256_ctx *aes_ctx, uint8_t *out, - const uint8_t *in, size_t len, const uint8_t *nonce) { - // Since the AEAD operation is one-shot, keeping a buffer of unused keystream - // bytes is pointless. However, |CRYPTO_ctr128_encrypt_ctr32| requires it. + const struct aead_aes_ctr_hmac_sha256_ctx *aes_ctx, + Span iovecs, const uint8_t *nonce) { uint8_t partial_block_buffer[AES_BLOCK_SIZE]; unsigned partial_block_offset = 0; OPENSSL_memset(partial_block_buffer, 0, sizeof(partial_block_buffer)); @@ -164,74 +170,85 @@ static void aead_aes_ctr_hmac_sha256_crypt( OPENSSL_memcpy(counter, nonce, EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN); OPENSSL_memset(counter + EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN, 0, 4); - CRYPTO_ctr128_encrypt_ctr32(in, out, len, &aes_ctx->ks.ks, counter, - partial_block_buffer, &partial_block_offset, - aes_ctx->ctr); + for (const CRYPTO_IOVEC &iovec : iovecs) { + CRYPTO_ctr128_encrypt_ctr32(iovec.in, iovec.out, iovec.len, &aes_ctx->ks.ks, + counter, partial_block_buffer, + &partial_block_offset, aes_ctx->ctr); + } } -static int aead_aes_ctr_hmac_sha256_seal_scatter( - const EVP_AEAD_CTX *ctx, uint8_t *out, uint8_t *out_tag, - size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *extra_in, - size_t extra_in_len, const uint8_t *ad, size_t ad_len) { +static int aead_aes_ctr_hmac_sha256_sealv(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span out_tag, + size_t *out_tag_len, + Span nonce, + Span aadvecs) { const struct aead_aes_ctr_hmac_sha256_ctx *aes_ctx = - (struct aead_aes_ctr_hmac_sha256_ctx *) &ctx->state; - const uint64_t in_len_64 = in_len; + (struct aead_aes_ctr_hmac_sha256_ctx *)&ctx->state; + const uint64_t in_len_64 = bssl::iovec::TotalLength(iovecs); if (in_len_64 >= (UINT64_C(1) << 32) * AES_BLOCK_SIZE) { - // This input is so large it would overflow the 32-bit block counter. + // This input is so large it would overflow the 32-bit block counter. OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); return 0; } - if (max_out_tag_len < ctx->tag_len) { + if (out_tag.size() < ctx->tag_len) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); return 0; } - if (nonce_len != EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN) { + if (nonce.size() != EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE); return 0; } - aead_aes_ctr_hmac_sha256_crypt(aes_ctx, out, in, in_len, nonce); + aead_aes_ctr_hmac_sha256_crypt(aes_ctx, iovecs, nonce.data()); uint8_t hmac_result[SHA256_DIGEST_LENGTH]; hmac_calculate(hmac_result, &aes_ctx->inner_init_state, - &aes_ctx->outer_init_state, ad, ad_len, nonce, out, in_len); - OPENSSL_memcpy(out_tag, hmac_result, ctx->tag_len); + &aes_ctx->outer_init_state, aadvecs, nonce.data(), iovecs, + /*encrypt=*/true); + CopyToPrefix(Span(hmac_result).first(ctx->tag_len), out_tag); *out_tag_len = ctx->tag_len; return 1; } -static int aead_aes_ctr_hmac_sha256_open_gather( - const EVP_AEAD_CTX *ctx, uint8_t *out, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *in_tag, - size_t in_tag_len, const uint8_t *ad, size_t ad_len) { +static int aead_aes_ctr_hmac_sha256_openv_detached( + const EVP_AEAD_CTX *ctx, Span iovecs, + Span nonce, Span in_tag, + Span aadvecs) { const struct aead_aes_ctr_hmac_sha256_ctx *aes_ctx = - (struct aead_aes_ctr_hmac_sha256_ctx *) &ctx->state; + (struct aead_aes_ctr_hmac_sha256_ctx *)&ctx->state; + const uint64_t in_len_64 = bssl::iovec::TotalLength(iovecs); - if (in_tag_len != ctx->tag_len) { + if (in_len_64 >= (UINT64_C(1) << 32) * AES_BLOCK_SIZE) { + // This input is so large it would overflow the 32-bit block counter. OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } - if (nonce_len != EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN) { + if (in_tag.size() != ctx->tag_len) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); + return 0; + } + + if (nonce.size() != EVP_AEAD_AES_CTR_HMAC_SHA256_NONCE_LEN) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE); return 0; } uint8_t hmac_result[SHA256_DIGEST_LENGTH]; hmac_calculate(hmac_result, &aes_ctx->inner_init_state, - &aes_ctx->outer_init_state, ad, ad_len, nonce, in, - in_len); - if (CRYPTO_memcmp(hmac_result, in_tag, ctx->tag_len) != 0) { + &aes_ctx->outer_init_state, aadvecs, nonce.data(), iovecs, + /*encrypt=*/false); + if (CRYPTO_memcmp(hmac_result, in_tag.data(), ctx->tag_len) != 0) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } - aead_aes_ctr_hmac_sha256_crypt(aes_ctx, out, in, in_len, nonce); + aead_aes_ctr_hmac_sha256_crypt(aes_ctx, iovecs, nonce.data()); return 1; } @@ -241,16 +258,15 @@ static const EVP_AEAD aead_aes_128_ctr_hmac_sha256 = { 12, // nonce length EVP_AEAD_AES_CTR_HMAC_SHA256_TAG_LEN, // overhead EVP_AEAD_AES_CTR_HMAC_SHA256_TAG_LEN, // max tag length - 0, // seal_scatter_supports_extra_in aead_aes_ctr_hmac_sha256_init, - NULL /* init_with_direction */, + nullptr /* init_with_direction */, aead_aes_ctr_hmac_sha256_cleanup, - NULL /* open */, - aead_aes_ctr_hmac_sha256_seal_scatter, - aead_aes_ctr_hmac_sha256_open_gather, - NULL /* get_iv */, - NULL /* tag_len */, + nullptr /* openv */, + aead_aes_ctr_hmac_sha256_sealv, + aead_aes_ctr_hmac_sha256_openv_detached, + nullptr /* get_iv */, + nullptr /* tag_len */, }; static const EVP_AEAD aead_aes_256_ctr_hmac_sha256 = { @@ -258,22 +274,21 @@ static const EVP_AEAD aead_aes_256_ctr_hmac_sha256 = { 12, // nonce length EVP_AEAD_AES_CTR_HMAC_SHA256_TAG_LEN, // overhead EVP_AEAD_AES_CTR_HMAC_SHA256_TAG_LEN, // max tag length - 0, // seal_scatter_supports_extra_in aead_aes_ctr_hmac_sha256_init, - NULL /* init_with_direction */, + nullptr /* init_with_direction */, aead_aes_ctr_hmac_sha256_cleanup, - NULL /* open */, - aead_aes_ctr_hmac_sha256_seal_scatter, - aead_aes_ctr_hmac_sha256_open_gather, - NULL /* get_iv */, - NULL /* tag_len */, + nullptr /* openv */, + aead_aes_ctr_hmac_sha256_sealv, + aead_aes_ctr_hmac_sha256_openv_detached, + nullptr /* get_iv */, + nullptr /* tag_len */, }; -const EVP_AEAD *EVP_aead_aes_128_ctr_hmac_sha256(void) { +const EVP_AEAD *EVP_aead_aes_128_ctr_hmac_sha256() { return &aead_aes_128_ctr_hmac_sha256; } -const EVP_AEAD *EVP_aead_aes_256_ctr_hmac_sha256(void) { +const EVP_AEAD *EVP_aead_aes_256_ctr_hmac_sha256() { return &aead_aes_256_ctr_hmac_sha256; } diff --git a/Sources/CNIOBoringSSL/crypto/cipher/e_aeseax.cc b/Sources/CNIOBoringSSL/crypto/cipher/e_aeseax.cc new file mode 100644 index 00000000..536c6aec --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/cipher/e_aeseax.cc @@ -0,0 +1,351 @@ +// Copyright 2025 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 "../fipsmodule/cipher/internal.h" +#include "../internal.h" + + +using namespace bssl; + +// Implementation of AES-EAX defined in +// https://www.iacr.org/archive/fse2004/30170391/30170391.pdf. + +#define EVP_AEAD_AES_EAX_TAG_LEN AES_BLOCK_SIZE + +struct aead_aes_eax_ctx { + union { + double align; + AES_KEY ks; + } ks; + uint8_t b[AES_BLOCK_SIZE]; + uint8_t p[AES_BLOCK_SIZE]; +}; + +static void mult_by_X(uint8_t out[AES_BLOCK_SIZE], + const uint8_t in[AES_BLOCK_SIZE]) { + const crypto_word_t in_hi = CRYPTO_load_word_be(in); + for (size_t i = 0; i < AES_BLOCK_SIZE - 1; ++i) { + out[i] = (in[i] << 1) | (in[i + 1] >> 7); + } + // Carry over 0x87 if msb is 1, 0x00 if msb is 0. + out[AES_BLOCK_SIZE - 1] = in[AES_BLOCK_SIZE - 1] << 1; + const uint8_t p = 0x87; + constant_time_conditional_memxor(out + AES_BLOCK_SIZE - 1, &p, /*n=*/1, + constant_time_msb_w(in_hi)); +} + +static int aead_aes_eax_init(EVP_AEAD_CTX *ctx, const uint8_t *key, + size_t key_len, size_t tag_len) { + struct aead_aes_eax_ctx *aes_ctx = (struct aead_aes_eax_ctx *)&ctx->state; + + if (key_len != 16 && key_len != 32) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_KEY_LENGTH); + return 0; + } + + if (tag_len == EVP_AEAD_DEFAULT_TAG_LENGTH) { + tag_len = EVP_AEAD_AES_EAX_TAG_LEN; + } + + if (tag_len != EVP_AEAD_AES_EAX_TAG_LEN) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_TAG_SIZE); + return 0; + } + + if (AES_set_encrypt_key(key, /*bits=*/key_len * 8, &aes_ctx->ks.ks) != 0) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_AES_KEY_SETUP_FAILED); + return 0; + } + ctx->tag_len = tag_len; + + // L <- Ek(0^n). + OPENSSL_memset(aes_ctx->b, 0, sizeof(aes_ctx->b)); + AES_encrypt(aes_ctx->b, aes_ctx->b, &aes_ctx->ks.ks); + // B <- 2L. + mult_by_X(aes_ctx->b, aes_ctx->b); + // P <- 4L = 2B. + mult_by_X(aes_ctx->p, aes_ctx->b); + return 1; +} + +static void aead_aes_eax_cleanup(EVP_AEAD_CTX *ctx) {} + +// Implements the CBK function in the paper. +static void cbk_block(const struct aead_aes_eax_ctx *aes_ctx, + const uint8_t in[AES_BLOCK_SIZE], + uint8_t out[AES_BLOCK_SIZE]) { + CRYPTO_xor16(out, in, out); + AES_encrypt(out, out, &aes_ctx->ks.ks); +} + +// Precondition: in_len <= AES_BLOCK_SIZE. +static void pad(const struct aead_aes_eax_ctx *aes_ctx, + uint8_t out[AES_BLOCK_SIZE], const uint8_t *in, size_t in_len) { + assert(in_len <= AES_BLOCK_SIZE); + if (in_len == AES_BLOCK_SIZE) { + CRYPTO_xor16(out, aes_ctx->b, in); + return; + } + OPENSSL_memset(out, 0, AES_BLOCK_SIZE); + OPENSSL_memcpy(out, in, in_len); + out[in_len] = 0x80; + CRYPTO_xor16(out, aes_ctx->p, out); +} + +template +static void omac_with_tag(const struct aead_aes_eax_ctx *aes_ctx, + uint8_t out[AES_BLOCK_SIZE], Span ivecs, + uint8_t tag) { + OPENSSL_memset(out, 0, AES_BLOCK_SIZE); + out[AES_BLOCK_SIZE - 1] = tag; + size_t in_len = bssl::iovec::TotalLength(ivecs); + if (in_len == 0) { + // CBK(pad(M;B,P)) = CBK(B). Avoiding padding to skip a copy. + cbk_block(aes_ctx, aes_ctx->b, out); + return; + } + // CBK(M1) = Ek(M1 ^ 0^n) + AES_encrypt(out, out, &aes_ctx->ks.ks); + bssl::iovec::ForEachBlockRange( + ivecs, + [&](const uint8_t *in, size_t len) { + while (len >= AES_BLOCK_SIZE) { + // Full blocks, no padding needed. + cbk_block(aes_ctx, in, out); + in += AES_BLOCK_SIZE; + len -= AES_BLOCK_SIZE; + } + BSSL_CHECK(len == 0); + return true; + }, + [&](const uint8_t *in, size_t len) { + // Remaining blocks. + while (len > AES_BLOCK_SIZE) { + // Full blocks, no padding needed. + cbk_block(aes_ctx, in, out); + in += AES_BLOCK_SIZE; + len -= AES_BLOCK_SIZE; + } + // Last partial block. + uint8_t padded_block[AES_BLOCK_SIZE]; + pad(aes_ctx, padded_block, in, len); + cbk_block(aes_ctx, padded_block, out); + return true; + }); +} + +static void omac_with_tag_iovec_out(const struct aead_aes_eax_ctx *aes_ctx, + uint8_t out[AES_BLOCK_SIZE], + Span iovecs, + uint8_t tag) { + OPENSSL_memset(out, 0, AES_BLOCK_SIZE); + out[AES_BLOCK_SIZE - 1] = tag; + size_t in_len = bssl::iovec::TotalLength(iovecs); + if (in_len == 0) { + // CBK(pad(M;B,P)) = CBK(B). Avoiding padding to skip a copy. + cbk_block(aes_ctx, aes_ctx->b, out); + return; + } + // CBK(M1) = Ek(M1 ^ 0^n) + AES_encrypt(out, out, &aes_ctx->ks.ks); + bssl::iovec::ForEachOutBlockRange( + iovecs, + [&](const uint8_t *in, size_t len) { + while (len >= AES_BLOCK_SIZE) { + // Full blocks, no padding needed. + cbk_block(aes_ctx, in, out); + in += AES_BLOCK_SIZE; + len -= AES_BLOCK_SIZE; + } + BSSL_CHECK(len == 0); + return true; + }, + [&](const uint8_t *in, size_t len) { + while (len > AES_BLOCK_SIZE) { + // Full blocks, no padding needed. + cbk_block(aes_ctx, in, out); + in += AES_BLOCK_SIZE; + len -= AES_BLOCK_SIZE; + } + // Last partial block. + uint8_t padded_block[AES_BLOCK_SIZE]; + pad(aes_ctx, padded_block, in, len); + cbk_block(aes_ctx, padded_block, out); + return true; + }); +} + +// Encrypts/decrypts `in_len` bytes from `in` to `out` using AES-CTR with `n` as +// the IV. +static void aes_ctr(const struct aead_aes_eax_ctx *aes_ctx, + Span iovecs, + const uint8_t n[AES_BLOCK_SIZE]) { + uint8_t ivec[AES_BLOCK_SIZE]; + OPENSSL_memcpy(ivec, n, AES_BLOCK_SIZE); + + uint8_t ecount_buf[AES_BLOCK_SIZE]; + unsigned int num = 0; + + for (const CRYPTO_IOVEC &iovec : iovecs) { + AES_ctr128_encrypt(iovec.in, iovec.out, iovec.len, &aes_ctx->ks.ks, ivec, + ecount_buf, &num); + } +} + +static int aead_aes_eax_sealv(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span out_tag, size_t *out_tag_len, + Span nonce, + Span aadvecs) { + // We use the full 128 bits of the nonce as counter, so no need to check the + // plaintext size. + + if (out_tag.size() < ctx->tag_len) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); + return 0; + } + + if (nonce.size() != 12 && nonce.size() != 16) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE); + return 0; + } + + const struct aead_aes_eax_ctx *aes_ctx = + (struct aead_aes_eax_ctx *)&ctx->state; + + // N <- OMAC(0 || nonce) + uint8_t n[AES_BLOCK_SIZE]; + CRYPTO_IVEC noncevec[1]; + noncevec[0].in = nonce.data(); + noncevec[0].len = nonce.size(); + omac_with_tag(aes_ctx, n, Span(noncevec), /*tag=*/0); + // H <- OMAC(1 || ad) + uint8_t h[AES_BLOCK_SIZE]; + omac_with_tag(aes_ctx, h, aadvecs, /*tag=*/1); + + // C <- CTR^{N}_{K}(M) + aes_ctr(aes_ctx, iovecs, n); + + // MAC <- OMAC(2 || C) + omac_with_tag_iovec_out(aes_ctx, out_tag.data(), iovecs, /*tag=*/2); + // MAC <- N ^ C ^ H + CRYPTO_xor16(out_tag.data(), n, out_tag.data()); + CRYPTO_xor16(out_tag.data(), h, out_tag.data()); + + *out_tag_len = ctx->tag_len; + return 1; +} + +static int aead_aes_eax_openv_detached(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span nonce, + Span in_tag, + Span aadvecs) { + const uint64_t ad_len_64 = bssl::iovec::TotalLength(aadvecs); + if (ad_len_64 >= (UINT64_C(1) << 61)) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); + return 0; + } + + if (in_tag.size() != EVP_AEAD_AES_EAX_TAG_LEN) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); + return 0; + } + + if (nonce.size() != 12 && nonce.size() != 16) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE); + return 0; + } + + const struct aead_aes_eax_ctx *aes_ctx = + (struct aead_aes_eax_ctx *)&ctx->state; + + // N <- OMAC(0 || nonce) + uint8_t n[AES_BLOCK_SIZE]; + CRYPTO_IVEC noncevec[1]; + noncevec[0].in = nonce.data(); + noncevec[0].len = nonce.size(); + omac_with_tag(aes_ctx, n, Span(noncevec), + /*tag=*/0); + // H <- OMAC(1 || ad) + uint8_t h[AES_BLOCK_SIZE]; + omac_with_tag(aes_ctx, h, aadvecs, /*tag=*/1); + + // MAC <- OMAC(2 || C) + uint8_t mac[AES_BLOCK_SIZE]; + omac_with_tag(aes_ctx, mac, iovecs, /*tag=*/2); + // MAC <- N ^ C ^ H + CRYPTO_xor16(mac, n, mac); + CRYPTO_xor16(mac, h, mac); + + if (CRYPTO_memcmp(mac, in_tag.data(), in_tag.size()) != 0) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); + return 0; + } + + // M <- CTR^{N}_{K}(C) + aes_ctr(aes_ctx, iovecs, n); + return 1; +} + +static const EVP_AEAD aead_aes_128_eax = { + 16, // AES key size + 16, // nonce length + EVP_AEAD_AES_EAX_TAG_LEN, // overhead + EVP_AEAD_AES_EAX_TAG_LEN, // max tag length + + aead_aes_eax_init, + nullptr, // init_with_direction + aead_aes_eax_cleanup, + nullptr, // openv + aead_aes_eax_sealv, + aead_aes_eax_openv_detached, + nullptr, // get_iv + nullptr, // tag_len +}; + +static const EVP_AEAD aead_aes_256_eax = { + 32, // AES key size + 16, // nonce length + EVP_AEAD_AES_EAX_TAG_LEN, // overhead + EVP_AEAD_AES_EAX_TAG_LEN, // max tag length + + aead_aes_eax_init, + nullptr, // init_with_direction + aead_aes_eax_cleanup, + nullptr, // openv + aead_aes_eax_sealv, + aead_aes_eax_openv_detached, + nullptr, // get_iv + nullptr, // tag_len +}; + +const EVP_AEAD *EVP_aead_aes_128_eax() { return &aead_aes_128_eax; } + +const EVP_AEAD *EVP_aead_aes_256_eax() { return &aead_aes_256_eax; } diff --git a/Sources/CNIOBoringSSL/crypto/cipher/e_aesgcmsiv.cc b/Sources/CNIOBoringSSL/crypto/cipher/e_aesgcmsiv.cc index c02b2ea8..b892791a 100644 --- a/Sources/CNIOBoringSSL/crypto/cipher/e_aesgcmsiv.cc +++ b/Sources/CNIOBoringSSL/crypto/cipher/e_aesgcmsiv.cc @@ -1,16 +1,16 @@ -/* Copyright 2017 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2017 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 @@ -19,61 +19,44 @@ #include #include #include +#include #include "../fipsmodule/aes/internal.h" #include "../fipsmodule/cipher/internal.h" #include "../internal.h" +#include "internal.h" +using namespace bssl; + #define EVP_AEAD_AES_GCM_SIV_NONCE_LEN 12 #define EVP_AEAD_AES_GCM_SIV_TAG_LEN 16 -// TODO(davidben): AES-GCM-SIV assembly is not correct for Windows. It must save -// and restore xmm6 through xmm15. -#if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM) && \ - !defined(OPENSSL_WINDOWS) -#define AES_GCM_SIV_ASM - -// Optimised AES-GCM-SIV - namespace { -struct aead_aes_gcm_siv_asm_ctx { - alignas(16) uint8_t key[16 * 15]; - int is_128_bit; -}; -} // namespace +void inc_counter(uint8_t tag[16], uint32_t by) { + CRYPTO_store_u32_le(tag, CRYPTO_load_u32_le(tag) + by); +} + +#if defined(AES_GCM_SIV_ASM) // The assembly code assumes 8-byte alignment of the EVP_AEAD_CTX's state, and // aligns to 16 bytes itself. -static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) + 8 >= - sizeof(struct aead_aes_gcm_siv_asm_ctx), +static_assert(sizeof(((EVP_AEAD_CTX *)nullptr)->state) >= + sizeof(struct aead_aes_gcm_siv_asm_ctx) + 8, "AEAD state is too small"); static_assert(alignof(union evp_aead_ctx_st_state) >= 8, "AEAD state has insufficient alignment"); -// asm_ctx_from_ctx returns a 16-byte aligned context pointer from |ctx|. -static struct aead_aes_gcm_siv_asm_ctx *asm_ctx_from_ctx( - const EVP_AEAD_CTX *ctx) { +// asm_ctx_from_ctx returns a 16-byte aligned context pointer from `ctx`. +struct aead_aes_gcm_siv_asm_ctx *asm_ctx_from_ctx(const EVP_AEAD_CTX *ctx) { // ctx->state must already be 8-byte aligned. Thus, at most, we may need to // add eight to align it to 16 bytes. const uintptr_t offset = ((uintptr_t)&ctx->state) & 8; return (struct aead_aes_gcm_siv_asm_ctx *)(&ctx->state.opaque[offset]); } -extern "C" { -// aes128gcmsiv_aes_ks writes an AES-128 key schedule for |key| to -// |out_expanded_key|. -extern void aes128gcmsiv_aes_ks(const uint8_t key[16], - uint8_t out_expanded_key[16 * 15]); - -// aes256gcmsiv_aes_ks writes an AES-256 key schedule for |key| to -// |out_expanded_key|. -extern void aes256gcmsiv_aes_ks(const uint8_t key[32], - uint8_t out_expanded_key[16 * 15]); -} - -static int aead_aes_gcm_siv_asm_init(EVP_AEAD_CTX *ctx, const uint8_t *key, - size_t key_len, size_t tag_len) { +int aead_aes_gcm_siv_asm_init(EVP_AEAD_CTX *ctx, const uint8_t *key, + size_t key_len, size_t tag_len) { const size_t key_bits = key_len * 8; if (key_bits != 128 && key_bits != 256) { @@ -106,133 +89,17 @@ static int aead_aes_gcm_siv_asm_init(EVP_AEAD_CTX *ctx, const uint8_t *key, return 1; } -static void aead_aes_gcm_siv_asm_cleanup(EVP_AEAD_CTX *ctx) {} +void aead_aes_gcm_siv_asm_cleanup(EVP_AEAD_CTX *ctx) {} -extern "C" { -// aesgcmsiv_polyval_horner updates the POLYVAL value in |in_out_poly| to -// include a number (|in_blocks|) of 16-byte blocks of data from |in|, given -// the POLYVAL key in |key|. -extern void aesgcmsiv_polyval_horner(const uint8_t in_out_poly[16], - const uint8_t key[16], const uint8_t *in, - size_t in_blocks); - -// aesgcmsiv_htable_init writes powers 1..8 of |auth_key| to |out_htable|. -extern void aesgcmsiv_htable_init(uint8_t out_htable[16 * 8], - const uint8_t auth_key[16]); - -// aesgcmsiv_htable6_init writes powers 1..6 of |auth_key| to |out_htable|. -extern void aesgcmsiv_htable6_init(uint8_t out_htable[16 * 6], - const uint8_t auth_key[16]); - -// aesgcmsiv_htable_polyval updates the POLYVAL value in |in_out_poly| to -// include |in_len| bytes of data from |in|. (Where |in_len| must be a multiple -// of 16.) It uses the precomputed powers of the key given in |htable|. -extern void aesgcmsiv_htable_polyval(const uint8_t htable[16 * 8], - const uint8_t *in, size_t in_len, - uint8_t in_out_poly[16]); - -// aes128gcmsiv_dec decrypts |in_len| & ~15 bytes from |out| and writes them to -// |in|. |in| and |out| may be equal, but must not otherwise alias. -// -// |in_out_calculated_tag_and_scratch|, on entry, must contain: -// 1. The current value of the calculated tag, which will be updated during -// decryption and written back to the beginning of this buffer on exit. -// 2. The claimed tag, which is needed to derive counter values. -// -// While decrypting, the whole of |in_out_calculated_tag_and_scratch| may be -// used for other purposes. In order to decrypt and update the POLYVAL value, it -// uses the expanded key from |key| and the table of powers in |htable|. -extern void aes128gcmsiv_dec(const uint8_t *in, uint8_t *out, - uint8_t in_out_calculated_tag_and_scratch[16 * 8], - const uint8_t htable[16 * 6], - const struct aead_aes_gcm_siv_asm_ctx *key, - size_t in_len); - -// aes256gcmsiv_dec acts like |aes128gcmsiv_dec|, but for AES-256. -extern void aes256gcmsiv_dec(const uint8_t *in, uint8_t *out, - uint8_t in_out_calculated_tag_and_scratch[16 * 8], - const uint8_t htable[16 * 6], - const struct aead_aes_gcm_siv_asm_ctx *key, - size_t in_len); - -// aes128gcmsiv_kdf performs the AES-GCM-SIV KDF given the expanded key from -// |key_schedule| and the nonce in |nonce|. Note that, while only 12 bytes of -// the nonce are used, 16 bytes are read and so the value must be -// right-padded. -extern void aes128gcmsiv_kdf(const uint8_t nonce[16], - uint64_t out_key_material[8], - const uint8_t *key_schedule); - -// aes256gcmsiv_kdf acts like |aes128gcmsiv_kdf|, but for AES-256. -extern void aes256gcmsiv_kdf(const uint8_t nonce[16], - uint64_t out_key_material[12], - const uint8_t *key_schedule); - -// aes128gcmsiv_aes_ks_enc_x1 performs a key expansion of the AES-128 key in -// |key|, writes the expanded key to |out_expanded_key| and encrypts a single -// block from |in| to |out|. -extern void aes128gcmsiv_aes_ks_enc_x1(const uint8_t in[16], uint8_t out[16], - uint8_t out_expanded_key[16 * 15], - const uint64_t key[2]); - -// aes256gcmsiv_aes_ks_enc_x1 acts like |aes128gcmsiv_aes_ks_enc_x1|, but for -// AES-256. -extern void aes256gcmsiv_aes_ks_enc_x1(const uint8_t in[16], uint8_t out[16], - uint8_t out_expanded_key[16 * 15], - const uint64_t key[4]); - -// aes128gcmsiv_ecb_enc_block encrypts a single block from |in| to |out| using -// the expanded key in |expanded_key|. -extern void aes128gcmsiv_ecb_enc_block( - const uint8_t in[16], uint8_t out[16], - const struct aead_aes_gcm_siv_asm_ctx *expanded_key); - -// aes256gcmsiv_ecb_enc_block acts like |aes128gcmsiv_ecb_enc_block|, but for -// AES-256. -extern void aes256gcmsiv_ecb_enc_block( - const uint8_t in[16], uint8_t out[16], - const struct aead_aes_gcm_siv_asm_ctx *expanded_key); - -// aes128gcmsiv_enc_msg_x4 encrypts |in_len| bytes from |in| to |out| using the -// expanded key from |key|. (The value of |in_len| must be a multiple of 16.) -// The |in| and |out| buffers may be equal but must not otherwise overlap. The -// initial counter is constructed from the given |tag| as required by -// AES-GCM-SIV. -extern void aes128gcmsiv_enc_msg_x4(const uint8_t *in, uint8_t *out, - const uint8_t *tag, - const struct aead_aes_gcm_siv_asm_ctx *key, - size_t in_len); - -// aes256gcmsiv_enc_msg_x4 acts like |aes128gcmsiv_enc_msg_x4|, but for -// AES-256. -extern void aes256gcmsiv_enc_msg_x4(const uint8_t *in, uint8_t *out, - const uint8_t *tag, - const struct aead_aes_gcm_siv_asm_ctx *key, - size_t in_len); - -// aes128gcmsiv_enc_msg_x8 acts like |aes128gcmsiv_enc_msg_x4|, but is -// optimised for longer messages. -extern void aes128gcmsiv_enc_msg_x8(const uint8_t *in, uint8_t *out, - const uint8_t *tag, - const struct aead_aes_gcm_siv_asm_ctx *key, - size_t in_len); - -// aes256gcmsiv_enc_msg_x8 acts like |aes256gcmsiv_enc_msg_x4|, but is -// optimised for longer messages. -extern void aes256gcmsiv_enc_msg_x8(const uint8_t *in, uint8_t *out, - const uint8_t *tag, - const struct aead_aes_gcm_siv_asm_ctx *key, - size_t in_len); -} - -// gcm_siv_asm_polyval evaluates POLYVAL at |auth_key| on the given plaintext -// and AD. The result is written to |out_tag|. -static void gcm_siv_asm_polyval(uint8_t out_tag[16], const uint8_t *in, - size_t in_len, const uint8_t *ad, size_t ad_len, - const uint8_t auth_key[16], - const uint8_t nonce[12]) { +// gcm_siv_asm_polyval evaluates POLYVAL at `auth_key` on the given plaintext +// and AD. The result is written to `out_tag`, which must be 16-byte aligned. +void gcm_siv_asm_polyval(uint8_t out_tag[16], Span iovecs, + Span aadvecs, + const uint8_t auth_key[16], const uint8_t nonce[12]) { OPENSSL_memset(out_tag, 0, 16); + const size_t ad_len = bssl::iovec::TotalLength(aadvecs); const size_t ad_blocks = ad_len / 16; + const size_t in_len = bssl::iovec::TotalLength(iovecs); const size_t in_blocks = in_len / 16; int htable_init = 0; alignas(16) uint8_t htable[16 * 8]; @@ -242,30 +109,36 @@ static void gcm_siv_asm_polyval(uint8_t out_tag[16], const uint8_t *in, aesgcmsiv_htable_init(htable, auth_key); } - if (htable_init) { - aesgcmsiv_htable_polyval(htable, ad, ad_len & ~15, out_tag); - } else { - aesgcmsiv_polyval_horner(out_tag, auth_key, ad, ad_blocks); - } + auto f_whole = [&](const uint8_t *in, size_t len) { + if (htable_init) { + aesgcmsiv_htable_polyval(htable, in, len, out_tag); + } else { + aesgcmsiv_polyval_horner(out_tag, auth_key, in, len / AES_BLOCK_SIZE); + } + return true; + }; - uint8_t scratch[16]; - if (ad_len & 15) { - OPENSSL_memset(scratch, 0, sizeof(scratch)); - OPENSSL_memcpy(scratch, &ad[ad_len & ~15], ad_len & 15); - aesgcmsiv_polyval_horner(out_tag, auth_key, scratch, 1); - } + auto f_final = [&](const uint8_t *in, size_t len) { + size_t len_whole = (len / AES_BLOCK_SIZE) * AES_BLOCK_SIZE; + if (len_whole != 0) { + f_whole(in, len_whole); + in += len_whole; + len -= len_whole; + } + if (len != 0) { + uint8_t pad_buf[AES_BLOCK_SIZE]; + OPENSSL_memcpy(pad_buf, in, len); + OPENSSL_memset(pad_buf + len, 0, AES_BLOCK_SIZE - len); + aesgcmsiv_polyval_horner(out_tag, auth_key, pad_buf, 1); + } + return true; + }; - if (htable_init) { - aesgcmsiv_htable_polyval(htable, in, in_len & ~15, out_tag); - } else { - aesgcmsiv_polyval_horner(out_tag, auth_key, in, in_blocks); - } + bssl::iovec::ForEachBlockRange( + aadvecs, f_whole, f_final); - if (in_len & 15) { - OPENSSL_memset(scratch, 0, sizeof(scratch)); - OPENSSL_memcpy(scratch, &in[in_len & ~15], in_len & 15); - aesgcmsiv_polyval_horner(out_tag, auth_key, scratch, 1); - } + bssl::iovec::ForEachBlockRange( + iovecs, f_whole, f_final); uint8_t length_block[16]; CRYPTO_store_u64_le(length_block, ad_len * 8); @@ -281,16 +154,16 @@ static void gcm_siv_asm_polyval(uint8_t out_tag[16], const uint8_t *in, // aead_aes_gcm_siv_asm_crypt_last_block handles the encryption/decryption // (same thing in CTR mode) of the final block of a plaintext/ciphertext. It -// writes |in_len| & 15 bytes to |out| + |in_len|, based on an initial counter -// derived from |tag|. -static void aead_aes_gcm_siv_asm_crypt_last_block( - int is_128_bit, uint8_t *out, const uint8_t *in, size_t in_len, - const uint8_t tag[16], +// writes `total_in_len` & 15 bytes to `out_last_block`, based on an initial +// counter derived from `tag`. +void aead_aes_gcm_siv_asm_crypt_last_block( + int is_128_bit, uint8_t *out_last_block, const uint8_t *in_last_block, + size_t total_in_len, const uint8_t tag[16], const struct aead_aes_gcm_siv_asm_ctx *enc_key_expanded) { alignas(16) uint8_t counter[16]; OPENSSL_memcpy(&counter, tag, sizeof(counter)); counter[15] |= 0x80; - CRYPTO_store_u32_le(counter, CRYPTO_load_u32_le(counter) + in_len / 16); + inc_counter(counter, static_cast(total_in_len / 16)); if (is_128_bit) { aes128gcmsiv_ecb_enc_block(counter, counter, enc_key_expanded); @@ -298,22 +171,20 @@ static void aead_aes_gcm_siv_asm_crypt_last_block( aes256gcmsiv_ecb_enc_block(counter, counter, enc_key_expanded); } - const size_t last_bytes_offset = in_len & ~15; - const size_t last_bytes_len = in_len & 15; - uint8_t *last_bytes_out = &out[last_bytes_offset]; - const uint8_t *last_bytes_in = &in[last_bytes_offset]; + const size_t last_bytes_len = total_in_len & 15; for (size_t i = 0; i < last_bytes_len; i++) { - last_bytes_out[i] = last_bytes_in[i] ^ counter[i]; + out_last_block[i] = in_last_block[i] ^ counter[i]; } } // aead_aes_gcm_siv_kdf calculates the record encryption and authentication -// keys given the |nonce|. -static void aead_aes_gcm_siv_kdf( - int is_128_bit, const struct aead_aes_gcm_siv_asm_ctx *gcm_siv_ctx, - uint64_t out_record_auth_key[2], uint64_t out_record_enc_key[4], - const uint8_t nonce[12]) { - alignas(16) uint8_t padded_nonce[16]; +// keys given the `nonce`. +void aead_aes_gcm_siv_kdf(int is_128_bit, + const struct aead_aes_gcm_siv_asm_ctx *gcm_siv_ctx, + uint64_t out_record_auth_key[2], + uint64_t out_record_enc_key[4], + const uint8_t nonce[12]) { + alignas(16) uint8_t padded_nonce[16] = {0}; OPENSSL_memcpy(padded_nonce, nonce, 12); alignas(16) uint64_t key_material[12]; @@ -333,13 +204,15 @@ static void aead_aes_gcm_siv_kdf( out_record_auth_key[1] = key_material[2]; } -static int aead_aes_gcm_siv_asm_seal_scatter( - const EVP_AEAD_CTX *ctx, uint8_t *out, uint8_t *out_tag, - size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *extra_in, - size_t extra_in_len, const uint8_t *ad, size_t ad_len) { +int aead_aes_gcm_siv_asm_sealv(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span out_tag, size_t *out_tag_len, + Span nonce, + Span aadvecs) { const struct aead_aes_gcm_siv_asm_ctx *gcm_siv_ctx = asm_ctx_from_ctx(ctx); + const size_t in_len = bssl::iovec::TotalLength(iovecs); const uint64_t in_len_64 = in_len; + const size_t ad_len = bssl::iovec::TotalLength(aadvecs); const uint64_t ad_len_64 = ad_len; if (in_len_64 > (UINT64_C(1) << 36) || ad_len_64 >= (UINT64_C(1) << 61)) { @@ -347,12 +220,12 @@ static int aead_aes_gcm_siv_asm_seal_scatter( return 0; } - if (max_out_tag_len < EVP_AEAD_AES_GCM_SIV_TAG_LEN) { + if (out_tag.size() < EVP_AEAD_AES_GCM_SIV_TAG_LEN) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); return 0; } - if (nonce_len != EVP_AEAD_AES_GCM_SIV_NONCE_LEN) { + if (nonce.size() != EVP_AEAD_AES_GCM_SIV_NONCE_LEN) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE); return 0; } @@ -360,63 +233,121 @@ static int aead_aes_gcm_siv_asm_seal_scatter( alignas(16) uint64_t record_auth_key[2]; alignas(16) uint64_t record_enc_key[4]; aead_aes_gcm_siv_kdf(gcm_siv_ctx->is_128_bit, gcm_siv_ctx, record_auth_key, - record_enc_key, nonce); + record_enc_key, nonce.data()); alignas(16) uint8_t tag[16] = {0}; - gcm_siv_asm_polyval(tag, in, in_len, ad, ad_len, - (const uint8_t *)record_auth_key, nonce); + gcm_siv_asm_polyval(tag, iovecs, aadvecs, (const uint8_t *)record_auth_key, + nonce.data()); struct aead_aes_gcm_siv_asm_ctx enc_key_expanded; if (gcm_siv_ctx->is_128_bit) { aes128gcmsiv_aes_ks_enc_x1(tag, tag, &enc_key_expanded.key[0], record_enc_key); - - if (in_len < 128) { - aes128gcmsiv_enc_msg_x4(in, out, tag, &enc_key_expanded, in_len & ~15); - } else { - aes128gcmsiv_enc_msg_x8(in, out, tag, &enc_key_expanded, in_len & ~15); - } + // Maintain a counter across calls to assembly. The functions internally set + // the MSB of the last byte, so we only need to update the counter. + alignas(16) uint8_t counter[16]; + OPENSSL_memcpy(counter, tag, 16); + bssl::iovec::ForEachBlockRange( + iovecs, + [&](const uint8_t *in, uint8_t *out, size_t len) { + if (len >= 128) { + aes128gcmsiv_enc_msg_x8(in, out, counter, &enc_key_expanded, len); + } else { + aes128gcmsiv_enc_msg_x4(in, out, counter, &enc_key_expanded, len); + } + inc_counter(counter, static_cast(len / AES_BLOCK_SIZE)); + return true; + }, + [&](const uint8_t *in, uint8_t *out, size_t len) { + size_t len_whole = (len / AES_BLOCK_SIZE) * AES_BLOCK_SIZE; + if (len_whole != 0) { + if (len_whole >= 128) { + aes128gcmsiv_enc_msg_x8(in, out, counter, &enc_key_expanded, + len_whole); + } else { + aes128gcmsiv_enc_msg_x4(in, out, counter, &enc_key_expanded, + len_whole); + } + in += len_whole; + out += len_whole; + len -= len_whole; + } + if (len != 0) { + aead_aes_gcm_siv_asm_crypt_last_block( + /*is_128_bit=*/true, /*out_last_block=*/out, + /*in_last_block=*/in, /*total_in_len=*/in_len, tag, + &enc_key_expanded); + } + return true; + }); } else { aes256gcmsiv_aes_ks_enc_x1(tag, tag, &enc_key_expanded.key[0], record_enc_key); - - if (in_len < 128) { - aes256gcmsiv_enc_msg_x4(in, out, tag, &enc_key_expanded, in_len & ~15); - } else { - aes256gcmsiv_enc_msg_x8(in, out, tag, &enc_key_expanded, in_len & ~15); - } + alignas(16) uint8_t counter[16]; + OPENSSL_memcpy(counter, tag, 16); + bssl::iovec::ForEachBlockRange( + iovecs, + [&](const uint8_t *in, uint8_t *out, size_t len) { + if (len >= 128) { + aes256gcmsiv_enc_msg_x8(in, out, counter, &enc_key_expanded, len); + } else { + aes256gcmsiv_enc_msg_x4(in, out, counter, &enc_key_expanded, len); + } + inc_counter(counter, static_cast(len / AES_BLOCK_SIZE)); + return true; + }, + [&](const uint8_t *in, uint8_t *out, size_t len) { + size_t len_whole = (len / AES_BLOCK_SIZE) * AES_BLOCK_SIZE; + if (len_whole != 0) { + if (len_whole >= 128) { + aes256gcmsiv_enc_msg_x8(in, out, counter, &enc_key_expanded, + len_whole); + } else { + aes256gcmsiv_enc_msg_x4(in, out, counter, &enc_key_expanded, + len_whole); + } + in += len_whole; + out += len_whole; + len -= len_whole; + } + if (len != 0) { + aead_aes_gcm_siv_asm_crypt_last_block( + /*is_128_bit=*/false, /*out_last_block=*/out, + /*in_last_block=*/in, /*total_in_len=*/in_len, tag, + &enc_key_expanded); + } + return true; + }); } - if (in_len & 15) { - aead_aes_gcm_siv_asm_crypt_last_block(gcm_siv_ctx->is_128_bit, out, in, - in_len, tag, &enc_key_expanded); - } - - OPENSSL_memcpy(out_tag, tag, sizeof(tag)); + CopyToPrefix(tag, out_tag); *out_tag_len = EVP_AEAD_AES_GCM_SIV_TAG_LEN; return 1; } -static int aead_aes_gcm_siv_asm_open_gather( - const EVP_AEAD_CTX *ctx, uint8_t *out, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *in_tag, - size_t in_tag_len, const uint8_t *ad, size_t ad_len) { +int aead_aes_gcm_siv_asm_openv_detached(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span nonce, + Span in_tag, + Span aadvecs) { + const size_t ad_len = bssl::iovec::TotalLength(aadvecs); const uint64_t ad_len_64 = ad_len; if (ad_len_64 >= (UINT64_C(1) << 61)) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); return 0; } + const size_t in_len = bssl::iovec::TotalLength(iovecs); const uint64_t in_len_64 = in_len; if (in_len_64 > UINT64_C(1) << 36 || - in_tag_len != EVP_AEAD_AES_GCM_SIV_TAG_LEN) { + in_tag.size() != EVP_AEAD_AES_GCM_SIV_TAG_LEN) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } - if (nonce_len != EVP_AEAD_AES_GCM_SIV_NONCE_LEN) { + if (nonce.size() != EVP_AEAD_AES_GCM_SIV_NONCE_LEN) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE); return 0; } @@ -426,7 +357,7 @@ static int aead_aes_gcm_siv_asm_open_gather( alignas(16) uint64_t record_auth_key[2]; alignas(16) uint64_t record_enc_key[4]; aead_aes_gcm_siv_kdf(gcm_siv_ctx->is_128_bit, gcm_siv_ctx, record_auth_key, - record_enc_key, nonce); + record_enc_key, nonce.data()); struct aead_aes_gcm_siv_asm_ctx expanded_key; if (gcm_siv_ctx->is_128_bit) { @@ -439,38 +370,87 @@ static int aead_aes_gcm_siv_asm_open_gather( alignas(16) uint8_t calculated_tag[16 * 8] = {0}; OPENSSL_memset(calculated_tag, 0, EVP_AEAD_AES_GCM_SIV_TAG_LEN); - const size_t ad_blocks = ad_len / 16; - aesgcmsiv_polyval_horner(calculated_tag, (const uint8_t *)record_auth_key, ad, - ad_blocks); - - uint8_t scratch[16]; - if (ad_len & 15) { - OPENSSL_memset(scratch, 0, sizeof(scratch)); - OPENSSL_memcpy(scratch, &ad[ad_len & ~15], ad_len & 15); - aesgcmsiv_polyval_horner(calculated_tag, (const uint8_t *)record_auth_key, - scratch, 1); - } + bssl::iovec::ForEachBlockRange( + aadvecs, + [&](const uint8_t *in, size_t len) { + aesgcmsiv_polyval_horner(calculated_tag, + (const uint8_t *)record_auth_key, in, + len / AES_BLOCK_SIZE); + return true; + }, + [&](const uint8_t *in, size_t len) { + size_t len_whole = (len / AES_BLOCK_SIZE) * AES_BLOCK_SIZE; + if (len_whole != 0) { + aesgcmsiv_polyval_horner(calculated_tag, + (const uint8_t *)record_auth_key, in, + len_whole / AES_BLOCK_SIZE); + in += len_whole; + len -= len_whole; + } + if (len != 0) { + uint8_t pad_buf[AES_BLOCK_SIZE]; + OPENSSL_memcpy(pad_buf, in, len); + OPENSSL_memset(pad_buf + len, 0, AES_BLOCK_SIZE - len); + aesgcmsiv_polyval_horner( + calculated_tag, (const uint8_t *)record_auth_key, pad_buf, 1); + } + return true; + }); alignas(16) uint8_t htable[16 * 6]; aesgcmsiv_htable6_init(htable, (const uint8_t *)record_auth_key); - // aes[128|256]gcmsiv_dec needs access to the claimed tag. So it's put into - // its scratch space. - memcpy(calculated_tag + 16, in_tag, EVP_AEAD_AES_GCM_SIV_TAG_LEN); - if (gcm_siv_ctx->is_128_bit) { - aes128gcmsiv_dec(in, out, calculated_tag, htable, &expanded_key, in_len); - } else { - aes256gcmsiv_dec(in, out, calculated_tag, htable, &expanded_key, in_len); - } - - if (in_len & 15) { - aead_aes_gcm_siv_asm_crypt_last_block(gcm_siv_ctx->is_128_bit, out, in, - in_len, in_tag, &expanded_key); - OPENSSL_memset(scratch, 0, sizeof(scratch)); - OPENSSL_memcpy(scratch, out + (in_len & ~15), in_len & 15); - aesgcmsiv_polyval_horner(calculated_tag, (const uint8_t *)record_auth_key, - scratch, 1); - } + size_t blocks = 0; + bssl::iovec::ForEachBlockRange( + iovecs, + [&](const uint8_t *in, uint8_t *out, size_t len) { + // aes[128|256]gcmsiv_dec needs access to the claimed tag. So it's put + // into its scratch space. The function may clobber the claimed tag, so + // this is copied before each call. + OPENSSL_memcpy(calculated_tag + 16, in_tag.data(), + EVP_AEAD_AES_GCM_SIV_TAG_LEN); + inc_counter(calculated_tag + 16, static_cast(blocks)); + if (gcm_siv_ctx->is_128_bit) { + aes128gcmsiv_dec(in, out, calculated_tag, htable, &expanded_key, len); + } else { + aes256gcmsiv_dec(in, out, calculated_tag, htable, &expanded_key, len); + } + blocks += len / AES_BLOCK_SIZE; + return true; + }, + [&](const uint8_t *in, uint8_t *out, size_t len) { + size_t len_whole = (len / AES_BLOCK_SIZE) * AES_BLOCK_SIZE; + if (len_whole != 0) { + // aes[128|256]gcmsiv_dec needs access to the claimed tag. So it's put + // into its scratch space. The function may clobber the claimed tag, + // so this is copied before each call. + OPENSSL_memcpy(calculated_tag + 16, in_tag.data(), + EVP_AEAD_AES_GCM_SIV_TAG_LEN); + inc_counter(calculated_tag + 16, static_cast(blocks)); + if (gcm_siv_ctx->is_128_bit) { + aes128gcmsiv_dec(in, out, calculated_tag, htable, &expanded_key, + len_whole); + } else { + aes256gcmsiv_dec(in, out, calculated_tag, htable, &expanded_key, + len_whole); + } + in += len_whole; + out += len_whole; + len -= len_whole; + } + if (len != 0) { + aead_aes_gcm_siv_asm_crypt_last_block( + gcm_siv_ctx->is_128_bit, /*out_last_block=*/out, + /*in_last_block=*/in, /*total_in_len=*/in_len, in_tag.data(), + &expanded_key); + uint8_t pad_buf[AES_BLOCK_SIZE]; + OPENSSL_memcpy(pad_buf, out, len); + OPENSSL_memset(pad_buf + len, 0, AES_BLOCK_SIZE - len); + aesgcmsiv_polyval_horner( + calculated_tag, (const uint8_t *)record_auth_key, pad_buf, 1); + } + return true; + }); uint8_t length_block[16]; CRYPTO_store_u64_le(length_block, ad_len * 8); @@ -490,8 +470,8 @@ static int aead_aes_gcm_siv_asm_open_gather( aes256gcmsiv_ecb_enc_block(calculated_tag, calculated_tag, &expanded_key); } - if (CRYPTO_memcmp(calculated_tag, in_tag, EVP_AEAD_AES_GCM_SIV_TAG_LEN) != - 0) { + if (CRYPTO_memcmp(calculated_tag, in_tag.data(), + EVP_AEAD_AES_GCM_SIV_TAG_LEN) != 0) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } @@ -499,43 +479,41 @@ static int aead_aes_gcm_siv_asm_open_gather( return 1; } -static const EVP_AEAD aead_aes_128_gcm_siv_asm = { +const EVP_AEAD aead_aes_128_gcm_siv_asm = { 16, // key length EVP_AEAD_AES_GCM_SIV_NONCE_LEN, // nonce length EVP_AEAD_AES_GCM_SIV_TAG_LEN, // overhead EVP_AEAD_AES_GCM_SIV_TAG_LEN, // max tag length - 0, // seal_scatter_supports_extra_in aead_aes_gcm_siv_asm_init, - NULL /* init_with_direction */, + nullptr /* init_with_direction */, aead_aes_gcm_siv_asm_cleanup, - NULL /* open */, - aead_aes_gcm_siv_asm_seal_scatter, - aead_aes_gcm_siv_asm_open_gather, - NULL /* get_iv */, - NULL /* tag_len */, + nullptr /* openv */, + aead_aes_gcm_siv_asm_sealv, + aead_aes_gcm_siv_asm_openv_detached, + nullptr /* get_iv */, + nullptr /* tag_len */, }; -static const EVP_AEAD aead_aes_256_gcm_siv_asm = { +const EVP_AEAD aead_aes_256_gcm_siv_asm = { 32, // key length EVP_AEAD_AES_GCM_SIV_NONCE_LEN, // nonce length EVP_AEAD_AES_GCM_SIV_TAG_LEN, // overhead EVP_AEAD_AES_GCM_SIV_TAG_LEN, // max tag length - 0, // seal_scatter_supports_extra_in aead_aes_gcm_siv_asm_init, - NULL /* init_with_direction */, + nullptr /* init_with_direction */, aead_aes_gcm_siv_asm_cleanup, - NULL /* open */, - aead_aes_gcm_siv_asm_seal_scatter, - aead_aes_gcm_siv_asm_open_gather, - NULL /* get_iv */, - NULL /* tag_len */, + nullptr /* openv */, + aead_aes_gcm_siv_asm_sealv, + aead_aes_gcm_siv_asm_openv_detached, + nullptr /* get_iv */, + nullptr /* tag_len */, }; -#endif // X86_64 && !NO_ASM && !WINDOWS +#endif // AES_GCM_SIV_ASM + -namespace { struct aead_aes_gcm_siv_ctx { union { double align; @@ -544,17 +522,16 @@ struct aead_aes_gcm_siv_ctx { block128_f kgk_block; unsigned is_256 : 1; }; -} // namespace -static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) >= +static_assert(sizeof(((EVP_AEAD_CTX *)nullptr)->state) >= sizeof(struct aead_aes_gcm_siv_ctx), "AEAD state is too small"); static_assert(alignof(union evp_aead_ctx_st_state) >= alignof(struct aead_aes_gcm_siv_ctx), "AEAD state has insufficient alignment"); -static int aead_aes_gcm_siv_init(EVP_AEAD_CTX *ctx, const uint8_t *key, - size_t key_len, size_t tag_len) { +int aead_aes_gcm_siv_init(EVP_AEAD_CTX *ctx, const uint8_t *key, size_t key_len, + size_t tag_len) { const size_t key_bits = key_len * 8; if (key_bits != 128 && key_bits != 256) { @@ -574,7 +551,7 @@ static int aead_aes_gcm_siv_init(EVP_AEAD_CTX *ctx, const uint8_t *key, (struct aead_aes_gcm_siv_ctx *)&ctx->state; OPENSSL_memset(gcm_siv_ctx, 0, sizeof(struct aead_aes_gcm_siv_ctx)); - aes_ctr_set_key(&gcm_siv_ctx->ks.ks, NULL, &gcm_siv_ctx->kgk_block, key, + aes_ctr_set_key(&gcm_siv_ctx->ks.ks, nullptr, &gcm_siv_ctx->kgk_block, key, key_len); gcm_siv_ctx->is_256 = (key_len == 32); ctx->tag_len = tag_len; @@ -582,80 +559,182 @@ static int aead_aes_gcm_siv_init(EVP_AEAD_CTX *ctx, const uint8_t *key, return 1; } -static void aead_aes_gcm_siv_cleanup(EVP_AEAD_CTX *ctx) {} +void aead_aes_gcm_siv_cleanup(EVP_AEAD_CTX *ctx) {} -// gcm_siv_crypt encrypts (or decrypts—it's the same thing) |in_len| bytes from -// |in| to |out|, using the block function |enc_block| with |key| in counter -// mode, starting at |initial_counter|. This differs from the traditional -// counter mode code in that the counter is handled little-endian, only the -// first four bytes are used and the GCM-SIV tweak to the final byte is -// applied. The |in| and |out| pointers may be equal but otherwise must not +// gcm_siv_crypt encrypts (or decrypts—it's the same thing) bytes from `in` to +// `out` in the `iovec`, using the block function `enc_block` with `key` in +// counter mode, starting at `initial_counter`. This differs from the +// traditional counter mode code in that the counter is handled little-endian, +// only the first four bytes are used and the GCM-SIV tweak to the final byte +// is applied. The `in` and `out` pointers may be equal but otherwise must not // alias. -static void gcm_siv_crypt(uint8_t *out, const uint8_t *in, size_t in_len, - const uint8_t initial_counter[AES_BLOCK_SIZE], - block128_f enc_block, const AES_KEY *key) { +void gcm_siv_crypt(Span iovecs, + const uint8_t initial_counter[AES_BLOCK_SIZE], + block128_f enc_block, const AES_KEY *key) { uint8_t counter[16]; OPENSSL_memcpy(counter, initial_counter, AES_BLOCK_SIZE); counter[15] |= 0x80; - for (size_t done = 0; done < in_len;) { - uint8_t keystream[AES_BLOCK_SIZE]; - enc_block(counter, keystream, key); - CRYPTO_store_u32_le(counter, CRYPTO_load_u32_le(counter) + 1); + auto crypt_bytes = [&](const uint8_t *in, uint8_t *out, size_t len) { + for (size_t done = 0; done < len;) { + uint8_t keystream[AES_BLOCK_SIZE]; + enc_block(counter, keystream, key); + inc_counter(counter, 1); - size_t todo = AES_BLOCK_SIZE; - if (in_len - done < todo) { - todo = in_len - done; + size_t todo = AES_BLOCK_SIZE; + if (len - done < todo) { + todo = len - done; + } + + for (size_t i = 0; i < todo; i++) { + out[done + i] = keystream[i] ^ in[done + i]; + } + + done += todo; + } + return true; + }; + + bssl::iovec::ForEachBlockRange( + iovecs, crypt_bytes, crypt_bytes); +} + + +// POLYVAL. +// +// POLYVAL is a polynomial authenticator that operates over a field very +// similar to the one that GHASH uses. See +// https://www.rfc-editor.org/rfc/rfc8452.html#section-3. + +// POLYVAL(H, X₁, ..., Xₙ) = +// ByteReverse(GHASH(mulX_GHASH(ByteReverse(H)), ByteReverse(X₁), ..., +// ByteReverse(Xₙ))). +// +// See https://www.rfc-editor.org/rfc/rfc8452.html#appendix-A. + +struct polyval_ctx { + uint8_t S[16]; + u128 Htable[16]; + gmult_func gmult; + ghash_func ghash; +}; + +// byte_reverse reverses the order of the bytes in `b->c`. +void byte_reverse(uint8_t b[16]) { + uint64_t hi = CRYPTO_load_u64_le(b); + uint64_t lo = CRYPTO_load_u64_le(b + 8); + CRYPTO_store_u64_le(b, CRYPTO_bswap8(lo)); + CRYPTO_store_u64_le(b + 8, CRYPTO_bswap8(hi)); +} + +// reverse_and_mulX_ghash interprets `b` as a reversed element of the GHASH +// field, multiplies that by 'x' and serialises the result back into `b`, but +// with GHASH's backwards bit ordering. +void reverse_and_mulX_ghash(uint8_t b[16]) { + uint64_t hi = CRYPTO_load_u64_le(b); + uint64_t lo = CRYPTO_load_u64_le(b + 8); + const crypto_word_t carry = constant_time_eq_w(hi & 1, 1); + hi >>= 1; + hi |= lo << 63; + lo >>= 1; + lo ^= ((uint64_t)constant_time_select_w(carry, 0xe1, 0)) << 56; + + CRYPTO_store_u64_le(b, CRYPTO_bswap8(lo)); + CRYPTO_store_u64_le(b + 8, CRYPTO_bswap8(hi)); +} + +void crypto_polyval_init(struct polyval_ctx *ctx, const uint8_t key[16]) { + alignas(8) uint8_t H[16]; + OPENSSL_memcpy(H, key, 16); + reverse_and_mulX_ghash(H); + + CRYPTO_ghash_init(&ctx->gmult, &ctx->ghash, ctx->Htable, H); + OPENSSL_memset(&ctx->S, 0, sizeof(ctx->S)); +} + +void crypto_polyval_update_blocks(struct polyval_ctx *ctx, const uint8_t *in, + size_t in_len) { + assert((in_len & 15) == 0); + alignas(8) uint8_t buf[32 * 16]; + + while (in_len > 0) { + size_t todo = in_len; + if (todo > sizeof(buf)) { + todo = sizeof(buf); + } + OPENSSL_memcpy(buf, in, todo); + in += todo; + in_len -= todo; + + size_t blocks = todo / 16; + for (size_t i = 0; i < blocks; i++) { + byte_reverse(buf + 16 * i); } - for (size_t i = 0; i < todo; i++) { - out[done + i] = keystream[i] ^ in[done + i]; - } - - done += todo; + ctx->ghash(ctx->S, ctx->Htable, buf, todo); } } -// gcm_siv_polyval evaluates POLYVAL at |auth_key| on the given plaintext and -// AD. The result is written to |out_tag|. -static void gcm_siv_polyval( - uint8_t out_tag[16], const uint8_t *in, size_t in_len, const uint8_t *ad, - size_t ad_len, const uint8_t auth_key[16], - const uint8_t nonce[EVP_AEAD_AES_GCM_SIV_NONCE_LEN]) { +void crypto_polyval_finish(const struct polyval_ctx *ctx, uint8_t out[16]) { + OPENSSL_memcpy(out, &ctx->S, 16); + byte_reverse(out); +} + +// gcm_siv_polyval evaluates POLYVAL at `auth_key` on the given plaintext and +// AD. The result is written to `out_tag`. +void gcm_siv_polyval(uint8_t out_tag[16], Span iovecs, + bool encrypt, Span aadvecs, + const uint8_t auth_key[16], + const uint8_t nonce[EVP_AEAD_AES_GCM_SIV_NONCE_LEN]) { struct polyval_ctx polyval_ctx; - CRYPTO_POLYVAL_init(&polyval_ctx, auth_key); + crypto_polyval_init(&polyval_ctx, auth_key); - CRYPTO_POLYVAL_update_blocks(&polyval_ctx, ad, ad_len & ~15); + auto f_whole = [&](const uint8_t *in, size_t len) { + crypto_polyval_update_blocks(&polyval_ctx, in, len); + return true; + }; + auto f_final = [&](const uint8_t *in, size_t len) { + size_t len_whole = (len / AES_BLOCK_SIZE) * AES_BLOCK_SIZE; + if (len_whole != 0) { + crypto_polyval_update_blocks(&polyval_ctx, in, len_whole); + in += len_whole; + len -= len_whole; + } + if (len != 0) { + uint8_t pad_buf[AES_BLOCK_SIZE]; + OPENSSL_memcpy(pad_buf, in, len); + OPENSSL_memset(pad_buf + len, 0, AES_BLOCK_SIZE - len); + crypto_polyval_update_blocks(&polyval_ctx, pad_buf, AES_BLOCK_SIZE); + } + return true; + }; - uint8_t scratch[16]; - if (ad_len & 15) { - OPENSSL_memset(scratch, 0, sizeof(scratch)); - OPENSSL_memcpy(scratch, &ad[ad_len & ~15], ad_len & 15); - CRYPTO_POLYVAL_update_blocks(&polyval_ctx, scratch, sizeof(scratch)); - } + bssl::iovec::ForEachBlockRange( + aadvecs, f_whole, f_final); - CRYPTO_POLYVAL_update_blocks(&polyval_ctx, in, in_len & ~15); - if (in_len & 15) { - OPENSSL_memset(scratch, 0, sizeof(scratch)); - OPENSSL_memcpy(scratch, &in[in_len & ~15], in_len & 15); - CRYPTO_POLYVAL_update_blocks(&polyval_ctx, scratch, sizeof(scratch)); + if (encrypt) { + bssl::iovec::ForEachBlockRange( + iovecs, f_whole, f_final); + } else { + bssl::iovec::ForEachOutBlockRange(iovecs, f_whole, f_final); } uint8_t length_block[16]; - CRYPTO_store_u64_le(length_block, ((uint64_t)ad_len) * 8); - CRYPTO_store_u64_le(length_block + 8, ((uint64_t)in_len) * 8); - CRYPTO_POLYVAL_update_blocks(&polyval_ctx, length_block, + CRYPTO_store_u64_le(length_block, + ((uint64_t)bssl::iovec::TotalLength(aadvecs)) * 8); + CRYPTO_store_u64_le(length_block + 8, + ((uint64_t)bssl::iovec::TotalLength(iovecs)) * 8); + crypto_polyval_update_blocks(&polyval_ctx, length_block, sizeof(length_block)); - CRYPTO_POLYVAL_finish(&polyval_ctx, out_tag); + crypto_polyval_finish(&polyval_ctx, out_tag); for (size_t i = 0; i < EVP_AEAD_AES_GCM_SIV_NONCE_LEN; i++) { out_tag[i] ^= nonce[i]; } out_tag[15] &= 0x7f; } -namespace { // gcm_siv_record_keys contains the keys used for a specific GCM-SIV record. struct gcm_siv_record_keys { uint8_t auth_key[16]; @@ -665,13 +744,12 @@ struct gcm_siv_record_keys { } enc_key; block128_f enc_block; }; -} // namespace // gcm_siv_keys calculates the keys for a specific GCM-SIV record with the -// given nonce and writes them to |*out_keys|. -static void gcm_siv_keys(const struct aead_aes_gcm_siv_ctx *gcm_siv_ctx, - struct gcm_siv_record_keys *out_keys, - const uint8_t nonce[EVP_AEAD_AES_GCM_SIV_NONCE_LEN]) { +// given nonce and writes them to `*out_keys`. +void gcm_siv_keys(const struct aead_aes_gcm_siv_ctx *gcm_siv_ctx, + struct gcm_siv_record_keys *out_keys, + const uint8_t nonce[EVP_AEAD_AES_GCM_SIV_NONCE_LEN]) { const AES_KEY *const key = &gcm_siv_ctx->ks.ks; uint8_t key_material[(128 /* POLYVAL key */ + 256 /* max AES key */) / 8]; const size_t blocks_needed = gcm_siv_ctx->is_256 ? 6 : 4; @@ -689,25 +767,27 @@ static void gcm_siv_keys(const struct aead_aes_gcm_siv_ctx *gcm_siv_ctx, } OPENSSL_memcpy(out_keys->auth_key, key_material, 16); - // Note the |ctr128_f| function uses a big-endian couner, while AES-GCM-SIV + // Note the `ctr128_f` function uses a big-endian counter, while AES-GCM-SIV // uses a little-endian counter. We ignore the return value and only use - // |block128_f|. This has a significant performance cost for the fallback + // `block128_f`. This has a significant performance cost for the fallback // bitsliced AES implementations (bsaes and aes_nohw). // // We currently do not consider AES-GCM-SIV to be performance-sensitive on - // client hardware. If this changes, we can write little-endian |ctr128_f| + // client hardware. If this changes, we can write little-endian `ctr128_f` // functions. - aes_ctr_set_key(&out_keys->enc_key.ks, NULL, &out_keys->enc_block, + aes_ctr_set_key(&out_keys->enc_key.ks, nullptr, &out_keys->enc_block, key_material + 16, gcm_siv_ctx->is_256 ? 32 : 16); } -static int aead_aes_gcm_siv_seal_scatter( - const EVP_AEAD_CTX *ctx, uint8_t *out, uint8_t *out_tag, - size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *extra_in, - size_t extra_in_len, const uint8_t *ad, size_t ad_len) { +int aead_aes_gcm_siv_sealv(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span out_tag, size_t *out_tag_len, + Span nonce, + Span aadvecs) { const struct aead_aes_gcm_siv_ctx *gcm_siv_ctx = (struct aead_aes_gcm_siv_ctx *)&ctx->state; + size_t in_len = bssl::iovec::TotalLength(iovecs); + size_t ad_len = bssl::iovec::TotalLength(aadvecs); const uint64_t in_len_64 = in_len; const uint64_t ad_len_64 = ad_len; @@ -717,51 +797,50 @@ static int aead_aes_gcm_siv_seal_scatter( return 0; } - if (max_out_tag_len < EVP_AEAD_AES_GCM_SIV_TAG_LEN) { + if (out_tag.size() < EVP_AEAD_AES_GCM_SIV_TAG_LEN) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); return 0; } - if (nonce_len != EVP_AEAD_AES_GCM_SIV_NONCE_LEN) { + if (nonce.size() != EVP_AEAD_AES_GCM_SIV_NONCE_LEN) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE); return 0; } struct gcm_siv_record_keys keys; - gcm_siv_keys(gcm_siv_ctx, &keys, nonce); + gcm_siv_keys(gcm_siv_ctx, &keys, nonce.data()); - uint8_t tag[16]; - gcm_siv_polyval(tag, in, in_len, ad, ad_len, keys.auth_key, nonce); + uint8_t tag[EVP_AEAD_AES_GCM_SIV_TAG_LEN]; + gcm_siv_polyval(tag, iovecs, true, aadvecs, keys.auth_key, nonce.data()); keys.enc_block(tag, tag, &keys.enc_key.ks); - gcm_siv_crypt(out, in, in_len, tag, keys.enc_block, &keys.enc_key.ks); + gcm_siv_crypt(iovecs, tag, keys.enc_block, &keys.enc_key.ks); - OPENSSL_memcpy(out_tag, tag, EVP_AEAD_AES_GCM_SIV_TAG_LEN); + CopyToPrefix(tag, out_tag); *out_tag_len = EVP_AEAD_AES_GCM_SIV_TAG_LEN; return 1; } -static int aead_aes_gcm_siv_open_gather(const EVP_AEAD_CTX *ctx, uint8_t *out, - const uint8_t *nonce, size_t nonce_len, - const uint8_t *in, size_t in_len, - const uint8_t *in_tag, - size_t in_tag_len, const uint8_t *ad, - size_t ad_len) { - const uint64_t ad_len_64 = ad_len; +int aead_aes_gcm_siv_openv_detached(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span nonce, + Span in_tag, + Span aadvecs) { + const uint64_t ad_len_64 = bssl::iovec::TotalLength(aadvecs); if (ad_len_64 >= (UINT64_C(1) << 61)) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); return 0; } - const uint64_t in_len_64 = in_len; - if (in_tag_len != EVP_AEAD_AES_GCM_SIV_TAG_LEN || - in_len_64 > (UINT64_C(1) << 36) + AES_BLOCK_SIZE) { + const uint64_t in_len_64 = bssl::iovec::TotalLength(iovecs); + if (in_tag.size() != EVP_AEAD_AES_GCM_SIV_TAG_LEN || + in_len_64 > (UINT64_C(1) << 36)) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } - if (nonce_len != EVP_AEAD_AES_GCM_SIV_NONCE_LEN) { + if (nonce.size() != EVP_AEAD_AES_GCM_SIV_NONCE_LEN) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE); return 0; } @@ -770,15 +849,16 @@ static int aead_aes_gcm_siv_open_gather(const EVP_AEAD_CTX *ctx, uint8_t *out, (struct aead_aes_gcm_siv_ctx *)&ctx->state; struct gcm_siv_record_keys keys; - gcm_siv_keys(gcm_siv_ctx, &keys, nonce); + gcm_siv_keys(gcm_siv_ctx, &keys, nonce.data()); - gcm_siv_crypt(out, in, in_len, in_tag, keys.enc_block, &keys.enc_key.ks); + gcm_siv_crypt(iovecs, in_tag.data(), keys.enc_block, &keys.enc_key.ks); uint8_t expected_tag[EVP_AEAD_AES_GCM_SIV_TAG_LEN]; - gcm_siv_polyval(expected_tag, out, in_len, ad, ad_len, keys.auth_key, nonce); + gcm_siv_polyval(expected_tag, iovecs, false, aadvecs, keys.auth_key, + nonce.data()); keys.enc_block(expected_tag, expected_tag, &keys.enc_key.ks); - if (CRYPTO_memcmp(expected_tag, in_tag, sizeof(expected_tag)) != 0) { + if (CRYPTO_memcmp(expected_tag, in_tag.data(), sizeof(expected_tag)) != 0) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } @@ -786,60 +866,53 @@ static int aead_aes_gcm_siv_open_gather(const EVP_AEAD_CTX *ctx, uint8_t *out, return 1; } -static const EVP_AEAD aead_aes_128_gcm_siv = { +const EVP_AEAD aead_aes_128_gcm_siv = { 16, // key length EVP_AEAD_AES_GCM_SIV_NONCE_LEN, // nonce length EVP_AEAD_AES_GCM_SIV_TAG_LEN, // overhead EVP_AEAD_AES_GCM_SIV_TAG_LEN, // max tag length - 0, // seal_scatter_supports_extra_in aead_aes_gcm_siv_init, - NULL /* init_with_direction */, + nullptr /* init_with_direction */, aead_aes_gcm_siv_cleanup, - NULL /* open */, - aead_aes_gcm_siv_seal_scatter, - aead_aes_gcm_siv_open_gather, - NULL /* get_iv */, - NULL /* tag_len */, + nullptr /* openv */, + aead_aes_gcm_siv_sealv, + aead_aes_gcm_siv_openv_detached, + nullptr /* get_iv */, + nullptr /* tag_len */, }; -static const EVP_AEAD aead_aes_256_gcm_siv = { +const EVP_AEAD aead_aes_256_gcm_siv = { 32, // key length EVP_AEAD_AES_GCM_SIV_NONCE_LEN, // nonce length EVP_AEAD_AES_GCM_SIV_TAG_LEN, // overhead EVP_AEAD_AES_GCM_SIV_TAG_LEN, // max tag length - 0, // seal_scatter_supports_extra_in aead_aes_gcm_siv_init, - NULL /* init_with_direction */, + nullptr /* init_with_direction */, aead_aes_gcm_siv_cleanup, - NULL /* open */, - aead_aes_gcm_siv_seal_scatter, - aead_aes_gcm_siv_open_gather, - NULL /* get_iv */, - NULL /* tag_len */, + nullptr /* openv */, + aead_aes_gcm_siv_sealv, + aead_aes_gcm_siv_openv_detached, + nullptr /* get_iv */, + nullptr /* tag_len */, }; +} // namespace +const EVP_AEAD *EVP_aead_aes_128_gcm_siv() { #if defined(AES_GCM_SIV_ASM) - -const EVP_AEAD *EVP_aead_aes_128_gcm_siv(void) { - if (CRYPTO_is_AVX_capable() && CRYPTO_is_AESNI_capable()) { + if (aes_gcm_siv_asm_capable()) { return &aead_aes_128_gcm_siv_asm; } +#endif return &aead_aes_128_gcm_siv; } -const EVP_AEAD *EVP_aead_aes_256_gcm_siv(void) { - if (CRYPTO_is_AVX_capable() && CRYPTO_is_AESNI_capable()) { +const EVP_AEAD *EVP_aead_aes_256_gcm_siv() { +#if defined(AES_GCM_SIV_ASM) + if (aes_gcm_siv_asm_capable()) { return &aead_aes_256_gcm_siv_asm; } +#endif return &aead_aes_256_gcm_siv; } - -#else - -const EVP_AEAD *EVP_aead_aes_128_gcm_siv(void) { return &aead_aes_128_gcm_siv; } - -const EVP_AEAD *EVP_aead_aes_256_gcm_siv(void) { return &aead_aes_256_gcm_siv; } - -#endif // AES_GCM_SIV_ASM diff --git a/Sources/CNIOBoringSSL/crypto/cipher/e_chacha20poly1305.cc b/Sources/CNIOBoringSSL/crypto/cipher/e_chacha20poly1305.cc index d31da63f..845ee733 100644 --- a/Sources/CNIOBoringSSL/crypto/cipher/e_chacha20poly1305.cc +++ b/Sources/CNIOBoringSSL/crypto/cipher/e_chacha20poly1305.cc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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 @@ -22,17 +22,20 @@ #include #include #include +#include -#include "internal.h" #include "../chacha/internal.h" #include "../fipsmodule/cipher/internal.h" #include "../internal.h" +#include "internal.h" + +using namespace bssl; struct aead_chacha20_poly1305_ctx { uint8_t key[32]; }; -static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) >= +static_assert(sizeof(((EVP_AEAD_CTX *)nullptr)->state) >= sizeof(struct aead_chacha20_poly1305_ctx), "AEAD state is too small"); static_assert(alignof(union evp_aead_ctx_st_state) >= @@ -76,186 +79,252 @@ static void poly1305_update_length(poly1305_state *poly1305, size_t data_len) { CRYPTO_poly1305_update(poly1305, length_bytes, sizeof(length_bytes)); } -// calc_tag fills |tag| with the authentication tag for the given inputs. -static void calc_tag(uint8_t tag[POLY1305_TAG_LEN], const uint8_t *key, - const uint8_t nonce[12], const uint8_t *ad, size_t ad_len, - const uint8_t *ciphertext, size_t ciphertext_len, - const uint8_t *ciphertext_extra, - size_t ciphertext_extra_len) { +// calc_tag_pre prepares filling `tag` with the authentication tag for the given +// inputs. +static size_t calc_tag_pre(poly1305_state *ctx, const uint8_t key[32], + const uint8_t nonce[12], + Span aadvecs) { alignas(16) uint8_t poly1305_key[32]; OPENSSL_memset(poly1305_key, 0, sizeof(poly1305_key)); CRYPTO_chacha_20(poly1305_key, poly1305_key, sizeof(poly1305_key), key, nonce, 0); - static const uint8_t padding[16] = { 0 }; // Padding is all zeros. - poly1305_state ctx; - CRYPTO_poly1305_init(&ctx, poly1305_key); - CRYPTO_poly1305_update(&ctx, ad, ad_len); + static const uint8_t padding[16] = {0}; // Padding is all zeros. + CRYPTO_poly1305_init(ctx, poly1305_key); + size_t ad_len = 0; + for (const CRYPTO_IVEC &aadvec : aadvecs) { + CRYPTO_poly1305_update(ctx, aadvec.in, aadvec.len); + ad_len += aadvec.len; + } if (ad_len % 16 != 0) { - CRYPTO_poly1305_update(&ctx, padding, sizeof(padding) - (ad_len % 16)); + CRYPTO_poly1305_update(ctx, padding, sizeof(padding) - (ad_len % 16)); } - CRYPTO_poly1305_update(&ctx, ciphertext, ciphertext_len); - CRYPTO_poly1305_update(&ctx, ciphertext_extra, ciphertext_extra_len); - const size_t ciphertext_total = ciphertext_len + ciphertext_extra_len; - if (ciphertext_total % 16 != 0) { - CRYPTO_poly1305_update(&ctx, padding, - sizeof(padding) - (ciphertext_total % 16)); - } - poly1305_update_length(&ctx, ad_len); - poly1305_update_length(&ctx, ciphertext_total); - CRYPTO_poly1305_finish(&ctx, tag); + return ad_len; } -static int chacha20_poly1305_seal_scatter( - const uint8_t *key, uint8_t *out, uint8_t *out_tag, - size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *extra_in, - size_t extra_in_len, const uint8_t *ad, size_t ad_len, size_t tag_len) { - if (extra_in_len + tag_len < tag_len) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); - return 0; +static void calc_tag_post(poly1305_state *ctx, uint8_t tag[POLY1305_TAG_LEN], + size_t ciphertext_total, size_t ad_len) { + static const uint8_t padding[16] = {0}; // Padding is all zeros. + if (ciphertext_total % 16 != 0) { + CRYPTO_poly1305_update(ctx, padding, + sizeof(padding) - (ciphertext_total % 16)); } - if (max_out_tag_len < tag_len + extra_in_len) { + poly1305_update_length(ctx, ad_len); + poly1305_update_length(ctx, ciphertext_total); + CRYPTO_poly1305_finish(ctx, tag); +} + +static int chacha20_poly1305_sealv(const uint8_t *key, + Span iovecs, + Span out_tag, size_t *out_tag_len, + Span nonce, + Span aadvecs, + size_t tag_len) { + if (out_tag.size() < tag_len) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); return 0; } - if (nonce_len != 12) { + if (nonce.size() != 12) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE); return 0; } - // |CRYPTO_chacha_20| uses a 32-bit block counter. Therefore we disallow + // `CRYPTO_chacha_20` uses a 32-bit block counter. Therefore we disallow // individual operations that work on more than 256GB at a time. - // |in_len_64| is needed because, on 32-bit platforms, size_t is only + // `in_len_64` is needed because, on 32-bit platforms, size_t is only // 32-bits and this produces a warning because it's always false. // Casting to uint64_t inside the conditional is not sufficient to stop // the warning. - const uint64_t in_len_64 = in_len; + const uint64_t in_len_64 = bssl::iovec::TotalLength(iovecs); if (in_len_64 >= (UINT64_C(1) << 32) * 64 - 64) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); return 0; } - if (max_out_tag_len < tag_len) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); - return 0; - } - - // The the extra input is given, it is expected to be very short and so is - // encrypted byte-by-byte first. - if (extra_in_len) { - static const size_t kChaChaBlockSize = 64; - uint32_t block_counter = (uint32_t)(1 + (in_len / kChaChaBlockSize)); - size_t offset = in_len % kChaChaBlockSize; - uint8_t block[64 /* kChaChaBlockSize */]; - - for (size_t done = 0; done < extra_in_len; block_counter++) { - memset(block, 0, sizeof(block)); - CRYPTO_chacha_20(block, block, sizeof(block), key, nonce, - block_counter); - for (size_t i = offset; i < sizeof(block) && done < extra_in_len; - i++, done++) { - out_tag[done] = extra_in[done] ^ block[i]; - } - offset = 0; - } - } - union chacha20_poly1305_seal_data data; - if (chacha20_poly1305_asm_capable()) { + if (chacha20_poly1305_asm_capable() && iovecs.size() <= 2 && + aadvecs.size() <= 1) { OPENSSL_memcpy(data.in.key, key, 32); data.in.counter = 0; - OPENSSL_memcpy(data.in.nonce, nonce, 12); - data.in.extra_ciphertext = out_tag; - data.in.extra_ciphertext_len = extra_in_len; - chacha20_poly1305_seal(out, in, in_len, ad, ad_len, &data); + CopySpan(nonce, data.in.nonce); + if (iovecs.size() >= 2) { + // `chacha20_poly1305_seal` only supports one extra input and expects it + // to have been encrypted ahead of time. (Historically it was only used + // for very short inputs.) + constexpr size_t kChaChaBlockSize = 64; + uint32_t block_counter = + (uint32_t)(1 + (iovecs[0].len / kChaChaBlockSize)); + size_t offset = iovecs[0].len % kChaChaBlockSize; + size_t done = 0; + if (offset != 0) { + uint8_t block[kChaChaBlockSize]; + memset(block, 0, sizeof(block)); + CRYPTO_chacha_20(block, block, sizeof(block), key, nonce.data(), + block_counter); + for (size_t i = offset; i < sizeof(block) && done < iovecs[1].len; + i++, done++) { + iovecs[1].out[done] = iovecs[1].in[done] ^ block[i]; + } + ++block_counter; + } + if (done < iovecs[1].len) { + CRYPTO_chacha_20(iovecs[1].out + done, iovecs[1].in + done, + iovecs[1].len - done, key, nonce.data(), + block_counter); + } + // TODO(crbug.com/473454967): Support more than 1 extra ciphertext. + data.in.extra_ciphertext = iovecs[1].out; + data.in.extra_ciphertext_len = iovecs[1].len; + } else { + data.in.extra_ciphertext = nullptr; + data.in.extra_ciphertext_len = 0; + } + chacha20_poly1305_seal(iovecs.size() >= 1 ? iovecs[0].out : nullptr, + iovecs.size() >= 1 ? iovecs[0].in : nullptr, + iovecs.size() >= 1 ? iovecs[0].len : 0, + aadvecs.size() >= 1 ? aadvecs[0].in : nullptr, + aadvecs.size() >= 1 ? aadvecs[0].len : 0, &data); } else { - CRYPTO_chacha_20(out, in, in_len, key, nonce, 1); - calc_tag(data.out.tag, key, nonce, ad, ad_len, out, in_len, out_tag, - extra_in_len); + poly1305_state ctx; + size_t ad_len = calc_tag_pre(&ctx, key, nonce.data(), aadvecs); + + size_t ciphertext_total = 0; + size_t block = 1; + bssl::iovec::ForEachBlockRange<64, /*WriteOut=*/true>( + iovecs, + [&](const uint8_t *in, uint8_t *out, size_t len) { + // TODO(crbug.com/473454967): Maybe just provide asm version of this? + // Here, len is always a multiple of 64. + CRYPTO_chacha_20(out, in, len, key, nonce.data(), block); + CRYPTO_poly1305_update(&ctx, out, len); + ciphertext_total += len; + block += len / 64; + return true; + }, + [&](const uint8_t *in, uint8_t *out, size_t len) { + // Here, len may be anything. If an asm version can't handle that, + // it will be worth splitting off multiples of 64 here. + CRYPTO_chacha_20(out, in, len, key, nonce.data(), block); + CRYPTO_poly1305_update(&ctx, out, len); + ciphertext_total += len; + return true; + }); + + calc_tag_post(&ctx, data.out.tag, ciphertext_total, ad_len); } - OPENSSL_memcpy(out_tag + extra_in_len, data.out.tag, tag_len); - *out_tag_len = extra_in_len + tag_len; + CopyToPrefix(Span(data.out.tag).first(tag_len), out_tag); + *out_tag_len = tag_len; return 1; } -static int aead_chacha20_poly1305_seal_scatter( - const EVP_AEAD_CTX *ctx, uint8_t *out, uint8_t *out_tag, - size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *extra_in, - size_t extra_in_len, const uint8_t *ad, size_t ad_len) { +static int aead_chacha20_poly1305_sealv(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span out_tag, + size_t *out_tag_len, + Span nonce, + Span aadvecs) { const struct aead_chacha20_poly1305_ctx *c20_ctx = (struct aead_chacha20_poly1305_ctx *)&ctx->state; - return chacha20_poly1305_seal_scatter( - c20_ctx->key, out, out_tag, out_tag_len, max_out_tag_len, nonce, - nonce_len, in, in_len, extra_in, extra_in_len, ad, ad_len, ctx->tag_len); + return chacha20_poly1305_sealv(c20_ctx->key, iovecs, out_tag, out_tag_len, + nonce, aadvecs, ctx->tag_len); } -static int aead_xchacha20_poly1305_seal_scatter( - const EVP_AEAD_CTX *ctx, uint8_t *out, uint8_t *out_tag, - size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *extra_in, - size_t extra_in_len, const uint8_t *ad, size_t ad_len) { +static int aead_xchacha20_poly1305_sealv(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span out_tag, + size_t *out_tag_len, + Span nonce, + Span aadvecs) { const struct aead_chacha20_poly1305_ctx *c20_ctx = (struct aead_chacha20_poly1305_ctx *)&ctx->state; - if (nonce_len != 24) { + if (nonce.size() != 24) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE); return 0; } alignas(4) uint8_t derived_key[32]; alignas(4) uint8_t derived_nonce[12]; - CRYPTO_hchacha20(derived_key, c20_ctx->key, nonce); + CRYPTO_hchacha20(derived_key, c20_ctx->key, nonce.data()); OPENSSL_memset(derived_nonce, 0, 4); OPENSSL_memcpy(&derived_nonce[4], &nonce[16], 8); - return chacha20_poly1305_seal_scatter( - derived_key, out, out_tag, out_tag_len, max_out_tag_len, - derived_nonce, sizeof(derived_nonce), in, in_len, extra_in, extra_in_len, - ad, ad_len, ctx->tag_len); + return chacha20_poly1305_sealv(derived_key, iovecs, out_tag, out_tag_len, + derived_nonce, aadvecs, ctx->tag_len); } -static int chacha20_poly1305_open_gather( - const uint8_t *key, uint8_t *out, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *in_tag, - size_t in_tag_len, const uint8_t *ad, size_t ad_len, size_t tag_len) { - if (nonce_len != 12) { +static int chacha20_poly1305_openv_detached(const uint8_t *key, + Span iovecs, + Span nonce, + Span in_tag, + Span aadvecs, + size_t tag_len) { + if (nonce.size() != 12) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE); return 0; } - if (in_tag_len != tag_len) { + if (in_tag.size() != tag_len) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } - // |CRYPTO_chacha_20| uses a 32-bit block counter. Therefore we disallow + // `CRYPTO_chacha_20` uses a 32-bit block counter. Therefore we disallow // individual operations that work on more than 256GB at a time. - // |in_len_64| is needed because, on 32-bit platforms, size_t is only + // `in_len_64` is needed because, on 32-bit platforms, size_t is only // 32-bits and this produces a warning because it's always false. // Casting to uint64_t inside the conditional is not sufficient to stop // the warning. - const uint64_t in_len_64 = in_len; + const uint64_t in_len_64 = bssl::iovec::TotalLength(iovecs); if (in_len_64 >= (UINT64_C(1) << 32) * 64 - 64) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); return 0; } union chacha20_poly1305_open_data data; - if (chacha20_poly1305_asm_capable()) { + if (chacha20_poly1305_asm_capable() && iovecs.size() <= 1 && + aadvecs.size() <= 1) { + // TODO(crbug.com/473454967): Support more than 1 ciphertext segment. OPENSSL_memcpy(data.in.key, key, 32); data.in.counter = 0; - OPENSSL_memcpy(data.in.nonce, nonce, 12); - chacha20_poly1305_open(out, in, in_len, ad, ad_len, &data); + CopySpan(nonce, data.in.nonce); + chacha20_poly1305_open(iovecs.size() >= 1 ? iovecs[0].out : nullptr, + iovecs.size() >= 1 ? iovecs[0].in : nullptr, + iovecs.size() >= 1 ? iovecs[0].len : 0, + aadvecs.size() >= 1 ? aadvecs[0].in : nullptr, + aadvecs.size() >= 1 ? aadvecs[0].len : 0, &data); } else { - calc_tag(data.out.tag, key, nonce, ad, ad_len, in, in_len, NULL, 0); - CRYPTO_chacha_20(out, in, in_len, key, nonce, 1); + poly1305_state ctx; + size_t ad_len = calc_tag_pre(&ctx, key, nonce.data(), aadvecs); + + size_t ciphertext_total = 0; + size_t block = 1; + bssl::iovec::ForEachBlockRange<64, /*WriteOut=*/true>( + iovecs, + [&](const uint8_t *in, uint8_t *out, size_t len) { + // TODO(crbug.com/473454967): Maybe just provide asm version of this? + // Here, len is always a multiple of 64. + CRYPTO_poly1305_update(&ctx, in, len); + CRYPTO_chacha_20(out, in, len, key, nonce.data(), block); + ciphertext_total += len; + block += len / 64; + return true; + }, + [&](const uint8_t *in, uint8_t *out, size_t len) { + // Here, len may be anything. If an asm version can't handle that, + // it will be worth splitting off multiples of 64 here. + CRYPTO_poly1305_update(&ctx, in, len); + CRYPTO_chacha_20(out, in, len, key, nonce.data(), block); + ciphertext_total += len; + return true; + }); + + calc_tag_post(&ctx, data.out.tag, ciphertext_total, ad_len); } - if (CRYPTO_memcmp(data.out.tag, in_tag, tag_len) != 0) { + if (CRYPTO_memcmp(data.out.tag, in_tag.data(), tag_len) != 0) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } @@ -263,39 +332,37 @@ static int chacha20_poly1305_open_gather( return 1; } -static int aead_chacha20_poly1305_open_gather( - const EVP_AEAD_CTX *ctx, uint8_t *out, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *in_tag, - size_t in_tag_len, const uint8_t *ad, size_t ad_len) { +static int aead_chacha20_poly1305_openv_detached( + const EVP_AEAD_CTX *ctx, Span iovecs, + Span nonce, Span in_tag, + Span aadvecs) { const struct aead_chacha20_poly1305_ctx *c20_ctx = (struct aead_chacha20_poly1305_ctx *)&ctx->state; - return chacha20_poly1305_open_gather(c20_ctx->key, out, nonce, nonce_len, in, - in_len, in_tag, in_tag_len, ad, ad_len, - ctx->tag_len); + return chacha20_poly1305_openv_detached(c20_ctx->key, iovecs, nonce, in_tag, + aadvecs, ctx->tag_len); } -static int aead_xchacha20_poly1305_open_gather( - const EVP_AEAD_CTX *ctx, uint8_t *out, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *in_tag, - size_t in_tag_len, const uint8_t *ad, size_t ad_len) { +static int aead_xchacha20_poly1305_openv_detached( + const EVP_AEAD_CTX *ctx, Span iovecs, + Span nonce, Span in_tag, + Span aadvecs) { const struct aead_chacha20_poly1305_ctx *c20_ctx = (struct aead_chacha20_poly1305_ctx *)&ctx->state; - if (nonce_len != 24) { + if (nonce.size() != 24) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE); return 0; } alignas(4) uint8_t derived_key[32]; alignas(4) uint8_t derived_nonce[12]; - CRYPTO_hchacha20(derived_key, c20_ctx->key, nonce); + CRYPTO_hchacha20(derived_key, c20_ctx->key, nonce.data()); OPENSSL_memset(derived_nonce, 0, 4); OPENSSL_memcpy(&derived_nonce[4], &nonce[16], 8); - return chacha20_poly1305_open_gather( - derived_key, out, derived_nonce, sizeof(derived_nonce), in, in_len, - in_tag, in_tag_len, ad, ad_len, ctx->tag_len); + return chacha20_poly1305_openv_detached(derived_key, iovecs, derived_nonce, + in_tag, aadvecs, ctx->tag_len); } static const EVP_AEAD aead_chacha20_poly1305 = { @@ -303,16 +370,15 @@ static const EVP_AEAD aead_chacha20_poly1305 = { 12, // nonce len POLY1305_TAG_LEN, // overhead POLY1305_TAG_LEN, // max tag length - 1, // seal_scatter_supports_extra_in aead_chacha20_poly1305_init, - NULL, // init_with_direction + nullptr, // init_with_direction aead_chacha20_poly1305_cleanup, - NULL /* open */, - aead_chacha20_poly1305_seal_scatter, - aead_chacha20_poly1305_open_gather, - NULL, // get_iv - NULL, // tag_len + nullptr, // openv + aead_chacha20_poly1305_sealv, + aead_chacha20_poly1305_openv_detached, + nullptr, // get_iv + nullptr, // tag_len }; static const EVP_AEAD aead_xchacha20_poly1305 = { @@ -320,22 +386,19 @@ static const EVP_AEAD aead_xchacha20_poly1305 = { 24, // nonce len POLY1305_TAG_LEN, // overhead POLY1305_TAG_LEN, // max tag length - 1, // seal_scatter_supports_extra_in aead_chacha20_poly1305_init, - NULL, // init_with_direction + nullptr, // init_with_direction aead_chacha20_poly1305_cleanup, - NULL /* open */, - aead_xchacha20_poly1305_seal_scatter, - aead_xchacha20_poly1305_open_gather, - NULL, // get_iv - NULL, // tag_len + nullptr, // openv + aead_xchacha20_poly1305_sealv, + aead_xchacha20_poly1305_openv_detached, + nullptr, // get_iv + nullptr, // tag_len }; -const EVP_AEAD *EVP_aead_chacha20_poly1305(void) { - return &aead_chacha20_poly1305; -} +const EVP_AEAD *EVP_aead_chacha20_poly1305() { return &aead_chacha20_poly1305; } -const EVP_AEAD *EVP_aead_xchacha20_poly1305(void) { +const EVP_AEAD *EVP_aead_xchacha20_poly1305() { return &aead_xchacha20_poly1305; } diff --git a/Sources/CNIOBoringSSL/crypto/cipher/e_des.cc b/Sources/CNIOBoringSSL/crypto/cipher/e_des.cc index 03e5609c..688d9e37 100644 --- a/Sources/CNIOBoringSSL/crypto/cipher/e_des.cc +++ b/Sources/CNIOBoringSSL/crypto/cipher/e_des.cc @@ -1,11 +1,18 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,6 +23,8 @@ #include "internal.h" +using namespace bssl; + typedef struct { union { double align; @@ -30,10 +39,10 @@ static int des_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, return 1; } -static int des_cbc_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, - size_t in_len) { +static int des_cbc_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out, + const uint8_t *in, size_t len) { EVP_DES_KEY *dat = (EVP_DES_KEY *)ctx->cipher_data; - DES_ncbc_encrypt_ex(in, out, in_len, &dat->ks.ks, ctx->iv, ctx->encrypt); + DES_ncbc_encrypt_ex(in, out, len, &dat->ks.ks, ctx->iv, ctx->encrypt); return 1; } @@ -45,22 +54,24 @@ static const EVP_CIPHER evp_des_cbc = { /*ctx_size=*/sizeof(EVP_DES_KEY), /*flags=*/EVP_CIPH_CBC_MODE, /*init=*/des_init_key, - /*cipher=*/des_cbc_cipher, + /*cipher_update=*/des_cbc_cipher_update, + /*cipher_final=*/nullptr, + /*update_aad=*/nullptr, /*cleanup=*/nullptr, /*ctrl=*/nullptr, }; -const EVP_CIPHER *EVP_des_cbc(void) { return &evp_des_cbc; } +const EVP_CIPHER *EVP_des_cbc() { return &evp_des_cbc; } -static int des_ecb_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, - size_t in_len) { - if (in_len < ctx->cipher->block_size) { +static int des_ecb_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out, + const uint8_t *in, size_t len) { + if (len < ctx->cipher->block_size) { return 1; } - in_len -= ctx->cipher->block_size; + len -= ctx->cipher->block_size; EVP_DES_KEY *dat = (EVP_DES_KEY *)ctx->cipher_data; - for (size_t i = 0; i <= in_len; i += ctx->cipher->block_size) { + for (size_t i = 0; i <= len; i += ctx->cipher->block_size) { DES_ecb_encrypt_ex(in + i, out + i, &dat->ks.ks, ctx->encrypt); } return 1; @@ -74,12 +85,14 @@ static const EVP_CIPHER evp_des_ecb = { /*ctx_size=*/sizeof(EVP_DES_KEY), /*flags=*/EVP_CIPH_ECB_MODE, /*init=*/des_init_key, - /*cipher=*/des_ecb_cipher, + /*cipher_update=*/des_ecb_cipher_update, + /*cipher_final=*/nullptr, + /*update_aad=*/nullptr, /*cleanup=*/nullptr, /*ctrl=*/nullptr, }; -const EVP_CIPHER *EVP_des_ecb(void) { return &evp_des_ecb; } +const EVP_CIPHER *EVP_des_ecb() { return &evp_des_ecb; } typedef struct { union { @@ -97,10 +110,10 @@ static int des_ede3_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, return 1; } -static int des_ede3_cbc_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, - const uint8_t *in, size_t in_len) { +static int des_ede3_cbc_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out, + const uint8_t *in, size_t len) { DES_EDE_KEY *dat = (DES_EDE_KEY *)ctx->cipher_data; - DES_ede3_cbc_encrypt_ex(in, out, in_len, &dat->ks.ks[0], &dat->ks.ks[1], + DES_ede3_cbc_encrypt_ex(in, out, len, &dat->ks.ks[0], &dat->ks.ks[1], &dat->ks.ks[2], ctx->iv, ctx->encrypt); return 1; } @@ -113,12 +126,14 @@ static const EVP_CIPHER evp_des_ede3_cbc = { /*ctx_size=*/sizeof(DES_EDE_KEY), /*flags=*/EVP_CIPH_CBC_MODE, /*init=*/des_ede3_init_key, - /*cipher=*/des_ede3_cbc_cipher, + /*cipher_update=*/des_ede3_cbc_cipher_update, + /*cipher_final=*/nullptr, + /*update_aad=*/nullptr, /*cleanup=*/nullptr, /*ctrl=*/nullptr, }; -const EVP_CIPHER *EVP_des_ede3_cbc(void) { return &evp_des_ede3_cbc; } +const EVP_CIPHER *EVP_des_ede3_cbc() { return &evp_des_ede3_cbc; } static int des_ede_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, const uint8_t *iv, int enc) { @@ -138,22 +153,24 @@ static const EVP_CIPHER evp_des_ede_cbc = { /*ctx_size=*/sizeof(DES_EDE_KEY), /*flags=*/EVP_CIPH_CBC_MODE, /*init=*/des_ede_init_key, - /*cipher=*/des_ede3_cbc_cipher, + /*cipher_update=*/des_ede3_cbc_cipher_update, + /*cipher_final=*/nullptr, + /*update_aad=*/nullptr, /*cleanup=*/nullptr, /*ctrl=*/nullptr, }; -const EVP_CIPHER *EVP_des_ede_cbc(void) { return &evp_des_ede_cbc; } +const EVP_CIPHER *EVP_des_ede_cbc() { return &evp_des_ede_cbc; } -static int des_ede_ecb_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, - const uint8_t *in, size_t in_len) { - if (in_len < ctx->cipher->block_size) { +static int des_ede_ecb_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out, + const uint8_t *in, size_t len) { + if (len < ctx->cipher->block_size) { return 1; } - in_len -= ctx->cipher->block_size; + len -= ctx->cipher->block_size; DES_EDE_KEY *dat = (DES_EDE_KEY *)ctx->cipher_data; - for (size_t i = 0; i <= in_len; i += ctx->cipher->block_size) { + for (size_t i = 0; i <= len; i += ctx->cipher->block_size) { DES_ecb3_encrypt_ex(in + i, out + i, &dat->ks.ks[0], &dat->ks.ks[1], &dat->ks.ks[2], ctx->encrypt); } @@ -168,12 +185,14 @@ static const EVP_CIPHER evp_des_ede = { /*ctx_size=*/sizeof(DES_EDE_KEY), /*flags=*/EVP_CIPH_ECB_MODE, /*init=*/des_ede_init_key, - /*cipher=*/des_ede_ecb_cipher, + /*cipher_update=*/des_ede_ecb_cipher_update, + /*cipher_final=*/nullptr, + /*update_aad=*/nullptr, /*cleanup=*/nullptr, /*ctrl=*/nullptr, }; -const EVP_CIPHER *EVP_des_ede(void) { return &evp_des_ede; } +const EVP_CIPHER *EVP_des_ede() { return &evp_des_ede; } static const EVP_CIPHER evp_des_ede3 = { /*nid=*/NID_des_ede3_ecb, @@ -183,11 +202,13 @@ static const EVP_CIPHER evp_des_ede3 = { /*ctx_size=*/sizeof(DES_EDE_KEY), /*flags=*/EVP_CIPH_ECB_MODE, /*init=*/des_ede3_init_key, - /*cipher=*/des_ede_ecb_cipher, + /*cipher_update=*/des_ede_ecb_cipher_update, + /*cipher_final=*/nullptr, + /*update_aad=*/nullptr, /*cleanup=*/nullptr, /*ctrl=*/nullptr, }; -const EVP_CIPHER *EVP_des_ede3(void) { return &evp_des_ede3; } +const EVP_CIPHER *EVP_des_ede3() { return &evp_des_ede3; } -const EVP_CIPHER *EVP_des_ede3_ecb(void) { return EVP_des_ede3(); } +const EVP_CIPHER *EVP_des_ede3_ecb() { return EVP_des_ede3(); } diff --git a/Sources/CNIOBoringSSL/crypto/cipher/e_null.cc b/Sources/CNIOBoringSSL/crypto/cipher/e_null.cc index ab6deb8f..cb2ef316 100644 --- a/Sources/CNIOBoringSSL/crypto/cipher/e_null.cc +++ b/Sources/CNIOBoringSSL/crypto/cipher/e_null.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,15 +22,17 @@ #include "../internal.h" +using namespace bssl; + static int null_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, const uint8_t *iv, int enc) { return 1; } -static int null_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, - size_t in_len) { +static int null_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out, + const uint8_t *in, size_t len) { if (in != out) { - OPENSSL_memcpy(out, in, in_len); + OPENSSL_memcpy(out, in, len); } return 1; } @@ -38,9 +45,11 @@ static const EVP_CIPHER n_cipher = { /*ctx_size=*/0, /*flags=*/0, /*init=*/null_init_key, - /*cipher=*/null_cipher, + /*cipher_update=*/null_cipher_update, + /*cipher_final=*/nullptr, + /*update_aad=*/nullptr, /*cleanup=*/nullptr, /*ctrl=*/nullptr, }; -const EVP_CIPHER *EVP_enc_null(void) { return &n_cipher; } +const EVP_CIPHER *EVP_enc_null() { return &n_cipher; } diff --git a/Sources/CNIOBoringSSL/crypto/cipher/e_rc2.cc b/Sources/CNIOBoringSSL/crypto/cipher/e_rc2.cc index f755b582..3ffef243 100644 --- a/Sources/CNIOBoringSSL/crypto/cipher/e_rc2.cc +++ b/Sources/CNIOBoringSSL/crypto/cipher/e_rc2.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -95,7 +100,7 @@ typedef struct rc2_key_st { uint16_t data[64]; } RC2_KEY; -static void RC2_encrypt(uint32_t *d, RC2_KEY *key) { +static void rc2_encrypt(uint32_t *d, RC2_KEY *key) { int i, n; uint16_t *p0, *p1; uint16_t x0, x1, x2, x3, t; @@ -139,7 +144,7 @@ static void RC2_encrypt(uint32_t *d, RC2_KEY *key) { d[1] = (uint32_t)(x2 & 0xffff) | ((uint32_t)(x3 & 0xffff) << 16L); } -static void RC2_decrypt(uint32_t *d, RC2_KEY *key) { +static void rc2_decrypt(uint32_t *d, RC2_KEY *key) { int i, n; uint16_t *p0, *p1; uint16_t x0, x1, x2, x3, t; @@ -184,7 +189,7 @@ static void RC2_decrypt(uint32_t *d, RC2_KEY *key) { d[1] = (uint32_t)(x2 & 0xffff) | ((uint32_t)(x3 & 0xffff) << 16L); } -static void RC2_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, +static void rc2_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, RC2_KEY *ks, uint8_t *iv, int encrypt) { uint32_t tin0, tin1; uint32_t tout0, tout1, xor0, xor1; @@ -202,7 +207,7 @@ static void RC2_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; - RC2_encrypt(tin, ks); + rc2_encrypt(tin, ks); tout0 = tin[0]; l2c(tout0, out); tout1 = tin[1]; @@ -214,7 +219,7 @@ static void RC2_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; - RC2_encrypt(tin, ks); + rc2_encrypt(tin, ks); tout0 = tin[0]; l2c(tout0, out); tout1 = tin[1]; @@ -231,7 +236,7 @@ static void RC2_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, tin[0] = tin0; c2l(in, tin1); tin[1] = tin1; - RC2_decrypt(tin, ks); + rc2_decrypt(tin, ks); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2c(tout0, out); @@ -244,7 +249,7 @@ static void RC2_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, tin[0] = tin0; c2l(in, tin1); tin[1] = tin1; - RC2_decrypt(tin, ks); + rc2_decrypt(tin, ks); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2cn(tout0, tout1, out, l + 8); @@ -282,18 +287,23 @@ static const uint8_t key_table[256] = { 0xfe, 0x7f, 0xc1, 0xad, }; -static void RC2_set_key(RC2_KEY *key, int len, const uint8_t *data, int bits) { - int i, j; +static int rc2_set_key(RC2_KEY *key, size_t len, const uint8_t *data, + int bits) { + size_t i, j; uint8_t *k; - uint16_t *ki; unsigned int c, d; k = (uint8_t *)&key->data[0]; *k = 0; // for if there is a zero length key + if (len == 0) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_KEY_LENGTH); + return 0; + } if (len > 128) { len = 128; } + if (bits <= 0) { bits = 1024; } @@ -321,16 +331,20 @@ static void RC2_set_key(RC2_KEY *key, int len, const uint8_t *data, int bits) { d = key_table[k[i] & c]; k[i] = d; - while (i--) { + + while (i > 0) { + --i; d = key_table[k[i + j] ^ d]; k[i] = d; } // copy from bytes into uint16_t's - ki = &(key->data[63]); - for (i = 127; i >= 0; i -= 2) { - *(ki--) = ((k[i] << 8) | k[i - 1]) & 0xffff; + for (i = 0; i < 64; ++i) { + j = 63 - i; + key->data[j] = ((k[2 * j + 1] << 8) | k[2 * j]) & 0xffff; } + + return 1; } typedef struct { @@ -341,24 +355,26 @@ typedef struct { static int rc2_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, const uint8_t *iv, int enc) { EVP_RC2_KEY *rc2_key = (EVP_RC2_KEY *)ctx->cipher_data; - RC2_set_key(&rc2_key->ks, EVP_CIPHER_CTX_key_length(ctx), key, - rc2_key->key_bits); + if (!rc2_set_key(&rc2_key->ks, EVP_CIPHER_CTX_key_length(ctx), key, + rc2_key->key_bits)) { + return 0; + } return 1; } -static int rc2_cbc_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, - size_t inl) { +static int rc2_cbc_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out, + const uint8_t *in, size_t len) { EVP_RC2_KEY *key = (EVP_RC2_KEY *)ctx->cipher_data; static const size_t kChunkSize = 0x10000; - while (inl >= kChunkSize) { - RC2_cbc_encrypt(in, out, kChunkSize, &key->ks, ctx->iv, ctx->encrypt); - inl -= kChunkSize; + while (len >= kChunkSize) { + rc2_cbc_encrypt(in, out, kChunkSize, &key->ks, ctx->iv, ctx->encrypt); + len -= kChunkSize; in += kChunkSize; out += kChunkSize; } - if (inl) { - RC2_cbc_encrypt(in, out, inl, &key->ks, ctx->iv, ctx->encrypt); + if (len) { + rc2_cbc_encrypt(in, out, len, &key->ks, ctx->iv, ctx->encrypt); } return 1; } @@ -371,7 +387,7 @@ static int rc2_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { key->key_bits = EVP_CIPHER_CTX_key_length(ctx) * 8; return 1; case EVP_CTRL_SET_RC2_KEY_BITS: - // Should be overridden by later call to |EVP_CTRL_INIT|, but + // Should be overridden by later call to `EVP_CTRL_INIT`, but // people call it, so it may as well work. key->key_bits = arg; return 1; @@ -389,12 +405,14 @@ static const EVP_CIPHER rc2_40_cbc = { /*ctx_size=*/sizeof(EVP_RC2_KEY), /*flags=*/EVP_CIPH_CBC_MODE | EVP_CIPH_VARIABLE_LENGTH | EVP_CIPH_CTRL_INIT, /*init=*/rc2_init_key, - /*cipher=*/rc2_cbc_cipher, + /*cipher_update=*/rc2_cbc_cipher_update, + /*cipher_final=*/nullptr, + /*update_aad=*/nullptr, /*cleanup=*/nullptr, /*ctrl=*/rc2_ctrl, }; -const EVP_CIPHER *EVP_rc2_40_cbc(void) { return &rc2_40_cbc; } +const EVP_CIPHER *EVP_rc2_40_cbc() { return &rc2_40_cbc; } static const EVP_CIPHER rc2_cbc = { /*nid=*/NID_rc2_cbc, @@ -404,9 +422,11 @@ static const EVP_CIPHER rc2_cbc = { /*ctx_size=*/sizeof(EVP_RC2_KEY), /*flags=*/EVP_CIPH_CBC_MODE | EVP_CIPH_VARIABLE_LENGTH | EVP_CIPH_CTRL_INIT, /*init=*/rc2_init_key, - /*cipher=*/rc2_cbc_cipher, + /*cipher_update=*/rc2_cbc_cipher_update, + /*cipher_final=*/nullptr, + /*update_aad=*/nullptr, /*cleanup=*/nullptr, /*ctrl=*/rc2_ctrl, }; -const EVP_CIPHER *EVP_rc2_cbc(void) { return &rc2_cbc; } +const EVP_CIPHER *EVP_rc2_cbc() { return &rc2_cbc; } diff --git a/Sources/CNIOBoringSSL/crypto/cipher/e_rc4.cc b/Sources/CNIOBoringSSL/crypto/cipher/e_rc4.cc index ae42fff6..7a23cee0 100644 --- a/Sources/CNIOBoringSSL/crypto/cipher/e_rc4.cc +++ b/Sources/CNIOBoringSSL/crypto/cipher/e_rc4.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -25,11 +30,11 @@ static int rc4_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, return 1; } -static int rc4_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, - size_t in_len) { +static int rc4_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out, + const uint8_t *in, size_t len) { RC4_KEY *rc4key = (RC4_KEY *)ctx->cipher_data; - RC4(rc4key, in_len, in, out); + RC4(rc4key, len, in, out); return 1; } @@ -41,9 +46,11 @@ static const EVP_CIPHER rc4 = { /*ctx_size=*/sizeof(RC4_KEY), /*flags=*/EVP_CIPH_VARIABLE_LENGTH, /*init=*/rc4_init_key, - /*cipher=*/rc4_cipher, + /*cipher_update=*/rc4_cipher_update, + /*cipher_final=*/nullptr, + /*update_aad=*/nullptr, /*cleanup=*/nullptr, /*ctrl=*/nullptr, }; -const EVP_CIPHER *EVP_rc4(void) { return &rc4; } +const EVP_CIPHER *EVP_rc4() { return &rc4; } diff --git a/Sources/CNIOBoringSSL/crypto/cipher/e_tls.cc b/Sources/CNIOBoringSSL/crypto/cipher/e_tls.cc index fc518ee0..97fd9502 100644 --- a/Sources/CNIOBoringSSL/crypto/cipher/e_tls.cc +++ b/Sources/CNIOBoringSSL/crypto/cipher/e_tls.cc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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 @@ -23,15 +23,19 @@ #include #include #include +#include #include "../fipsmodule/cipher/internal.h" #include "../internal.h" +#include "../mem_internal.h" #include "internal.h" +using namespace bssl; + typedef struct { EVP_CIPHER_CTX cipher_ctx; - HMAC_CTX hmac_ctx; + HMAC_CTX *hmac_ctx; // mac_key is the portion of the key used for the MAC. It is retained // separately for the constant-time CBC code. uint8_t mac_key[EVP_MAX_MD_SIZE]; @@ -43,7 +47,7 @@ typedef struct { static_assert(EVP_MAX_MD_SIZE < 256, "mac_key_len does not fit in uint8_t"); -static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) >= sizeof(AEAD_TLS_CTX), +static_assert(sizeof(((EVP_AEAD_CTX *)nullptr)->state) >= sizeof(AEAD_TLS_CTX), "AEAD state is too small"); static_assert(alignof(union evp_aead_ctx_st_state) >= alignof(AEAD_TLS_CTX), "AEAD state has insufficient alignment"); @@ -51,15 +55,14 @@ static_assert(alignof(union evp_aead_ctx_st_state) >= alignof(AEAD_TLS_CTX), static void aead_tls_cleanup(EVP_AEAD_CTX *ctx) { AEAD_TLS_CTX *tls_ctx = (AEAD_TLS_CTX *)&ctx->state; EVP_CIPHER_CTX_cleanup(&tls_ctx->cipher_ctx); - HMAC_CTX_cleanup(&tls_ctx->hmac_ctx); + HMAC_CTX_free(tls_ctx->hmac_ctx); } static int aead_tls_init(EVP_AEAD_CTX *ctx, const uint8_t *key, size_t key_len, size_t tag_len, enum evp_aead_direction_t dir, const EVP_CIPHER *cipher, const EVP_MD *md, char implicit_iv) { - if (tag_len != EVP_AEAD_DEFAULT_TAG_LENGTH && - tag_len != EVP_MD_size(md)) { + if (tag_len != EVP_AEAD_DEFAULT_TAG_LENGTH && tag_len != EVP_MD_size(md)) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_TAG_SIZE); return 0; } @@ -72,20 +75,25 @@ static int aead_tls_init(EVP_AEAD_CTX *ctx, const uint8_t *key, size_t key_len, size_t mac_key_len = EVP_MD_size(md); size_t enc_key_len = EVP_CIPHER_key_length(cipher); assert(mac_key_len + enc_key_len + - (implicit_iv ? EVP_CIPHER_iv_length(cipher) : 0) == key_len); + (implicit_iv ? EVP_CIPHER_iv_length(cipher) : 0) == + key_len); AEAD_TLS_CTX *tls_ctx = (AEAD_TLS_CTX *)&ctx->state; + tls_ctx->hmac_ctx = HMAC_CTX_new(); + if (!tls_ctx->hmac_ctx) { + return 0; + } EVP_CIPHER_CTX_init(&tls_ctx->cipher_ctx); - HMAC_CTX_init(&tls_ctx->hmac_ctx); assert(mac_key_len <= EVP_MAX_MD_SIZE); OPENSSL_memcpy(tls_ctx->mac_key, key, mac_key_len); tls_ctx->mac_key_len = (uint8_t)mac_key_len; tls_ctx->implicit_iv = implicit_iv; - if (!EVP_CipherInit_ex(&tls_ctx->cipher_ctx, cipher, NULL, &key[mac_key_len], - implicit_iv ? &key[mac_key_len + enc_key_len] : NULL, - dir == evp_aead_seal) || - !HMAC_Init_ex(&tls_ctx->hmac_ctx, key, mac_key_len, md, NULL)) { + if (!EVP_CipherInit_ex( + &tls_ctx->cipher_ctx, cipher, nullptr, &key[mac_key_len], + implicit_iv ? &key[mac_key_len + enc_key_len] : nullptr, + dir == evp_aead_seal) || + !HMAC_Init_ex(tls_ctx->hmac_ctx, key, mac_key_len, md, nullptr)) { aead_tls_cleanup(ctx); return 0; } @@ -94,33 +102,24 @@ static int aead_tls_init(EVP_AEAD_CTX *ctx, const uint8_t *key, size_t key_len, return 1; } -static size_t aead_tls_tag_len(const EVP_AEAD_CTX *ctx, const size_t in_len, - const size_t extra_in_len) { - assert(extra_in_len == 0); +static size_t aead_tls_tag_len(const EVP_AEAD_CTX *ctx, const size_t in_len) { const AEAD_TLS_CTX *tls_ctx = (AEAD_TLS_CTX *)&ctx->state; + assert(EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE); - const size_t hmac_len = HMAC_size(&tls_ctx->hmac_ctx); - if (EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) != EVP_CIPH_CBC_MODE) { - // The NULL cipher. - return hmac_len; - } - + const size_t hmac_len = HMAC_size(tls_ctx->hmac_ctx); const size_t block_size = EVP_CIPHER_CTX_block_size(&tls_ctx->cipher_ctx); - // An overflow of |in_len + hmac_len| doesn't affect the result mod - // |block_size|, provided that |block_size| is a smaller power of two. - assert(block_size != 0 && (block_size & (block_size - 1)) == 0); - const size_t pad_len = block_size - (in_len + hmac_len) % block_size; + // An overflow of `in_len + hmac_len` doesn't affect the result mod + // `block_size`, provided that `block_size` is a smaller power of two. + assert(block_size == 8 /*3DES*/ || block_size == 16 /*AES*/); + const size_t pad_len = block_size - ((in_len + hmac_len) & (block_size - 1)); return hmac_len + pad_len; } -static int aead_tls_seal_scatter(const EVP_AEAD_CTX *ctx, uint8_t *out, - uint8_t *out_tag, size_t *out_tag_len, - const size_t max_out_tag_len, - const uint8_t *nonce, const size_t nonce_len, - const uint8_t *in, const size_t in_len, - const uint8_t *extra_in, - const size_t extra_in_len, const uint8_t *ad, - const size_t ad_len) { +static int aead_tls_sealv(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span out_tag, size_t *out_tag_len, + Span nonce, + Span aadvecs) { AEAD_TLS_CTX *tls_ctx = (AEAD_TLS_CTX *)&ctx->state; if (!tls_ctx->cipher_ctx.encrypt) { @@ -129,114 +128,147 @@ static int aead_tls_seal_scatter(const EVP_AEAD_CTX *ctx, uint8_t *out, return 0; } - if (in_len > INT_MAX) { - // EVP_CIPHER takes int as input. - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); - return 0; - } - - if (max_out_tag_len < aead_tls_tag_len(ctx, in_len, extra_in_len)) { + size_t in_len = bssl::iovec::TotalLength(iovecs); + if (out_tag.size() < aead_tls_tag_len(ctx, in_len)) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); return 0; } - if (nonce_len != EVP_AEAD_nonce_length(ctx->aead)) { + if (nonce.size() != EVP_AEAD_nonce_length(ctx->aead)) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE_SIZE); return 0; } + size_t ad_len = bssl::iovec::TotalLength(aadvecs); if (ad_len != 13 - 2 /* length bytes */) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_AD_SIZE); return 0; } - // To allow for CBC mode which changes cipher length, |ad| doesn't include the + // To allow for CBC mode which changes cipher length, `ad` doesn't include the // length for legacy ciphers. uint8_t ad_extra[2]; - ad_extra[0] = (uint8_t)(in_len >> 8); - ad_extra[1] = (uint8_t)(in_len & 0xff); + CRYPTO_store_u16_be(ad_extra, static_cast(in_len)); // Compute the MAC. This must be first in case the operation is being done // in-place. uint8_t mac[EVP_MAX_MD_SIZE]; + if (!HMAC_Init_ex(tls_ctx->hmac_ctx, nullptr, 0, nullptr, nullptr)) { + return 0; + } + for (const CRYPTO_IVEC &aadvec : aadvecs) { + if (!HMAC_Update(tls_ctx->hmac_ctx, aadvec.in, aadvec.len)) { + return 0; + } + } + if (!HMAC_Update(tls_ctx->hmac_ctx, ad_extra, sizeof(ad_extra))) { + return 0; + } + for (const CRYPTO_IOVEC &iovec : iovecs) { + if (!HMAC_Update(tls_ctx->hmac_ctx, iovec.in, iovec.len)) { + return 0; + } + } unsigned mac_len; - if (!HMAC_Init_ex(&tls_ctx->hmac_ctx, NULL, 0, NULL, NULL) || - !HMAC_Update(&tls_ctx->hmac_ctx, ad, ad_len) || - !HMAC_Update(&tls_ctx->hmac_ctx, ad_extra, sizeof(ad_extra)) || - !HMAC_Update(&tls_ctx->hmac_ctx, in, in_len) || - !HMAC_Final(&tls_ctx->hmac_ctx, mac, &mac_len)) { + if (!HMAC_Final(tls_ctx->hmac_ctx, mac, &mac_len)) { return 0; } // Configure the explicit IV. - if (EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE && - !tls_ctx->implicit_iv && - !EVP_EncryptInit_ex(&tls_ctx->cipher_ctx, NULL, NULL, NULL, nonce)) { + assert(EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE); + if (!tls_ctx->implicit_iv && + !EVP_EncryptInit_ex(&tls_ctx->cipher_ctx, nullptr, nullptr, nullptr, + nonce.data())) { return 0; } + size_t block_size = EVP_CIPHER_CTX_block_size(&tls_ctx->cipher_ctx); + assert(block_size == 8 /*3DES*/ || block_size == 16 /*AES*/); + // Encrypt the input. - int len; - if (!EVP_EncryptUpdate(&tls_ctx->cipher_ctx, out, &len, in, (int)in_len)) { + size_t len = 0; + size_t tag_len = 0; + if (!bssl::iovec::ForEachBlockRange_Dynamic( + block_size, iovecs, + [&](const uint8_t *in, uint8_t *out, size_t chunk_len) { + // Complete block(s). + size_t out_len; + if (!EVP_EncryptUpdate_ex(&tls_ctx->cipher_ctx, out, &out_len, + chunk_len, in, chunk_len)) { + return false; + } + assert(out_len == chunk_len); + len += out_len; + return true; + }, + [&](const uint8_t *in, uint8_t *out, size_t chunk_len) { + // Final chunk, possibly with a partial block. + size_t out_len; + if (!EVP_EncryptUpdate_ex(&tls_ctx->cipher_ctx, out, &out_len, + chunk_len, in, chunk_len)) { + return false; + } + len += out_len; + size_t remaining = chunk_len - out_len; + assert(remaining < block_size); + if (remaining == 0) { + return true; + } + + // Feed the MAC into the cipher in two steps. First complete the + // final partial block from encrypting the input and split the + // result between `out` and `out_tag`. Then feed the rest. + const size_t early_mac_len = block_size - remaining; + assert(early_mac_len < block_size); + assert(len + block_size - early_mac_len == in_len); + uint8_t buf[EVP_MAX_BLOCK_LENGTH]; + size_t buf_len; + if (!EVP_EncryptUpdate_ex(&tls_ctx->cipher_ctx, buf, &buf_len, + sizeof(buf), mac, early_mac_len)) { + return false; + } + assert(buf_len == block_size); + OPENSSL_memcpy(out + out_len, buf, remaining); + OPENSSL_memcpy(out_tag.data(), buf + remaining, early_mac_len); + tag_len = early_mac_len; + return true; + })) { return 0; } - unsigned block_size = EVP_CIPHER_CTX_block_size(&tls_ctx->cipher_ctx); - - // Feed the MAC into the cipher in two steps. First complete the final partial - // block from encrypting the input and split the result between |out| and - // |out_tag|. Then feed the rest. - - const size_t early_mac_len = (block_size - (in_len % block_size)) % block_size; - if (early_mac_len != 0) { - assert(len + block_size - early_mac_len == in_len); - uint8_t buf[EVP_MAX_BLOCK_LENGTH]; - int buf_len; - if (!EVP_EncryptUpdate(&tls_ctx->cipher_ctx, buf, &buf_len, mac, - (int)early_mac_len)) { - return 0; - } - assert(buf_len == (int)block_size); - OPENSSL_memcpy(out + len, buf, block_size - early_mac_len); - OPENSSL_memcpy(out_tag, buf + block_size - early_mac_len, early_mac_len); - } - size_t tag_len = early_mac_len; - - if (!EVP_EncryptUpdate(&tls_ctx->cipher_ctx, out_tag + tag_len, &len, - mac + tag_len, mac_len - tag_len)) { + if (!EVP_EncryptUpdate_ex(&tls_ctx->cipher_ctx, out_tag.data() + tag_len, + &len, out_tag.size() - tag_len, mac + tag_len, + mac_len - tag_len)) { return 0; } tag_len += len; - if (block_size > 1) { - assert(block_size <= 256); - assert(EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE); - - // Compute padding and feed that into the cipher. - uint8_t padding[256]; - unsigned padding_len = block_size - ((in_len + mac_len) % block_size); - OPENSSL_memset(padding, padding_len - 1, padding_len); - if (!EVP_EncryptUpdate(&tls_ctx->cipher_ctx, out_tag + tag_len, &len, - padding, (int)padding_len)) { - return 0; - } - tag_len += len; + // Compute padding and feed that into the cipher. + uint8_t padding[256]; + unsigned padding_len = block_size - ((in_len + mac_len) & (block_size - 1)); + OPENSSL_memset(padding, padding_len - 1, padding_len); + if (!EVP_EncryptUpdate_ex(&tls_ctx->cipher_ctx, out_tag.data() + tag_len, + &len, out_tag.size() - tag_len, padding, + padding_len)) { + return 0; } + tag_len += len; - if (!EVP_EncryptFinal_ex(&tls_ctx->cipher_ctx, out_tag + tag_len, &len)) { + if (!EVP_EncryptFinal_ex2(&tls_ctx->cipher_ctx, out_tag.data() + tag_len, + &len, out_tag.size() - tag_len)) { return 0; } assert(len == 0); // Padding is explicit. - assert(tag_len == aead_tls_tag_len(ctx, in_len, extra_in_len)); + assert(tag_len == aead_tls_tag_len(ctx, in_len)); *out_tag_len = tag_len; return 1; } -static int aead_tls_open(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len, - size_t max_out_len, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, - const uint8_t *ad, size_t ad_len) { +static int aead_tls_openv(const EVP_AEAD_CTX *ctx, + Span iovecs, + size_t *out_total_bytes, Span nonce, + Span aadvecs) { AEAD_TLS_CTX *tls_ctx = (AEAD_TLS_CTX *)&ctx->state; if (tls_ctx->cipher_ctx.encrypt) { @@ -245,144 +277,135 @@ static int aead_tls_open(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len, return 0; } - if (in_len < HMAC_size(&tls_ctx->hmac_ctx)) { + size_t in_len = bssl::iovec::TotalLength(iovecs); + if (in_len < HMAC_size(tls_ctx->hmac_ctx)) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } - if (max_out_len < in_len) { - // This requires that the caller provide space for the MAC, even though it - // will always be removed on return. - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); - return 0; - } - - if (nonce_len != EVP_AEAD_nonce_length(ctx->aead)) { + if (nonce.size() != EVP_AEAD_nonce_length(ctx->aead)) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE_SIZE); return 0; } + size_t ad_len = bssl::iovec::TotalLength(aadvecs); if (ad_len != 13 - 2 /* length bytes */) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_AD_SIZE); return 0; } - if (in_len > INT_MAX) { - // EVP_CIPHER takes int as input. - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); - return 0; - } - // Configure the explicit IV. - if (EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE && - !tls_ctx->implicit_iv && - !EVP_DecryptInit_ex(&tls_ctx->cipher_ctx, NULL, NULL, NULL, nonce)) { + assert(EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE); + if (!tls_ctx->implicit_iv && + !EVP_DecryptInit_ex(&tls_ctx->cipher_ctx, nullptr, nullptr, nullptr, + nonce.data())) { return 0; } // Decrypt to get the plaintext + MAC + padding. size_t total = 0; - int len; - if (!EVP_DecryptUpdate(&tls_ctx->cipher_ctx, out, &len, in, (int)in_len)) { - return 0; + size_t block_size = EVP_CIPHER_CTX_block_size(&tls_ctx->cipher_ctx); + auto decrypt_update = [&](const uint8_t *in, uint8_t *out, size_t len) { + size_t out_len; + if (!EVP_DecryptUpdate_ex(&tls_ctx->cipher_ctx, out, &out_len, len, in, + len)) { + return false; + } + CONSTTIME_SECRET(out, out_len); + if (out_len != len) { + // A byte sequence that was not a multiple of the block size was provided + // as ciphertext. This is generally invalid and thus should be rejected. + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); + return false; + } + total += len; + return true; + }; + if (!bssl::iovec::ForEachBlockRange_Dynamic( + block_size, iovecs, decrypt_update, decrypt_update)) { + return false; } - total += len; - if (!EVP_DecryptFinal_ex(&tls_ctx->cipher_ctx, out + total, &len)) { - return 0; - } - total += len; assert(total == in_len); - CONSTTIME_SECRET(out, total); + const size_t mac_len = HMAC_size(tls_ctx->hmac_ctx); + + // Split the decrypted record into `iovecs_without_trailer` and `trailer`, + // based on the public lower bound of where the plaintext ends. The plaintext + // is followed by `mac_len` and then at most 256 bytes of padding. + bssl::iovec::MaybeInplaceArray iovecs_without_trailer; + if (!iovecs_without_trailer.CopyFrom(iovecs)) { + return 0; + } + uint8_t trailer_buf[EVP_MAX_MD_SIZE + 256]; + const size_t trailer_len = std::min(in_len, mac_len + 256); + std::optional> trailer = + bssl::iovec::GetAndRemoveOutSuffix(Span(trailer_buf).first(trailer_len), + Span(iovecs_without_trailer)); + BSSL_CHECK(trailer.has_value()); // Remove CBC padding. Code from here on is timing-sensitive with respect to - // |padding_ok| and |data_plus_mac_len| for CBC ciphers. - size_t data_plus_mac_len; + // `padding_ok`, `trailer_minus_padding`, and derived values. crypto_word_t padding_ok; - if (EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE) { - if (!EVP_tls_cbc_remove_padding( - &padding_ok, &data_plus_mac_len, out, total, - EVP_CIPHER_CTX_block_size(&tls_ctx->cipher_ctx), - HMAC_size(&tls_ctx->hmac_ctx))) { - // Publicly invalid. This can be rejected in non-constant time. - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); - return 0; - } - } else { - padding_ok = CONSTTIME_TRUE_W; - data_plus_mac_len = total; - // |data_plus_mac_len| = |total| = |in_len| at this point. |in_len| has - // already been checked against the MAC size at the top of the function. - assert(data_plus_mac_len >= HMAC_size(&tls_ctx->hmac_ctx)); - } - size_t data_len = data_plus_mac_len - HMAC_size(&tls_ctx->hmac_ctx); - - // At this point, if the padding is valid, the first |data_plus_mac_len| bytes - // after |out| are the plaintext and MAC. Otherwise, |data_plus_mac_len| is - // still large enough to extract a MAC, but it will be irrelevant. - - // To allow for CBC mode which changes cipher length, |ad| doesn't include the - // length for legacy ciphers. - uint8_t ad_fixed[13]; - OPENSSL_memcpy(ad_fixed, ad, 11); - ad_fixed[11] = (uint8_t)(data_len >> 8); - ad_fixed[12] = (uint8_t)(data_len & 0xff); - ad_len += 2; - - // Compute the MAC and extract the one in the record. - uint8_t mac[EVP_MAX_MD_SIZE]; - size_t mac_len; - uint8_t record_mac_tmp[EVP_MAX_MD_SIZE]; - uint8_t *record_mac; - if (EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE && - EVP_tls_cbc_record_digest_supported(tls_ctx->hmac_ctx.md)) { - if (!EVP_tls_cbc_digest_record(tls_ctx->hmac_ctx.md, mac, &mac_len, - ad_fixed, out, data_len, total, - tls_ctx->mac_key, tls_ctx->mac_key_len)) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); - return 0; - } - assert(mac_len == HMAC_size(&tls_ctx->hmac_ctx)); - - record_mac = record_mac_tmp; - EVP_tls_cbc_copy_mac(record_mac, mac_len, out, data_plus_mac_len, total); - } else { - // We should support the constant-time path for all CBC-mode ciphers - // implemented. - assert(EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) != EVP_CIPH_CBC_MODE); - - unsigned mac_len_u; - if (!HMAC_Init_ex(&tls_ctx->hmac_ctx, NULL, 0, NULL, NULL) || - !HMAC_Update(&tls_ctx->hmac_ctx, ad_fixed, ad_len) || - !HMAC_Update(&tls_ctx->hmac_ctx, out, data_len) || - !HMAC_Final(&tls_ctx->hmac_ctx, mac, &mac_len_u)) { - return 0; - } - mac_len = mac_len_u; - - assert(mac_len == HMAC_size(&tls_ctx->hmac_ctx)); - record_mac = &out[data_len]; - } - - // Perform the MAC check and the padding check in constant-time. It should be - // safe to simply perform the padding check first, but it would not be under a - // different choice of MAC location on padding failure. See - // EVP_tls_cbc_remove_padding. - crypto_word_t good = - constant_time_eq_int(CRYPTO_memcmp(record_mac, mac, mac_len), 0); - good &= padding_ok; - CONSTTIME_DECLASSIFY(&good, sizeof(good)); - if (!good) { + size_t trailer_minus_padding; + if (!EVP_tls_cbc_remove_padding(&padding_ok, &trailer_minus_padding, + trailer->data(), trailer->size(), block_size, + mac_len)) { + // Publicly invalid. This can be rejected in non-constant time. OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } - CONSTTIME_DECLASSIFY(&data_len, sizeof(data_len)); - CONSTTIME_DECLASSIFY(out, data_len); + // If the padding is valid, `trailer->first(trailer_minus_padding)` is the + // last bytes of plaintext and the MAC. Otherwise, it is still large enough to + // extract a MAC, but it will be irrelevant. Note that `trailer_minus_padding` + // is secret. + declassify_assert(trailer_minus_padding >= mac_len); + size_t data_in_trailer_len = trailer_minus_padding - mac_len; + size_t max_data_in_trailer_len = trailer->size() - mac_len; + size_t data_len = total - trailer->size() + data_in_trailer_len; + + // To allow for CBC mode which changes cipher length, `ad_len` doesn't + // include the length for legacy ciphers. + uint8_t ad_extra[2]; + CRYPTO_store_u16_be(ad_extra, static_cast(data_len)); + + // Compute the MAC and extract the one in the record. + uint8_t mac[EVP_MAX_MD_SIZE]; + size_t got_mac_len; + assert(EVP_tls_cbc_record_digest_supported(tls_ctx->hmac_ctx->md)); + if (!EVP_tls_cbc_digest_record( + tls_ctx->hmac_ctx->md, mac, &got_mac_len, ad_extra, aadvecs, + iovecs_without_trailer, trailer->first(max_data_in_trailer_len), + data_in_trailer_len, tls_ctx->mac_key, tls_ctx->mac_key_len)) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); + return 0; + } + assert(got_mac_len == mac_len); + + uint8_t record_mac[EVP_MAX_MD_SIZE]; + EVP_tls_cbc_copy_mac(record_mac, mac_len, trailer->data(), + trailer_minus_padding, trailer->size()); + + // Perform the MAC check and the padding check in constant-time. It should be + // safe to simply perform the padding check first, but it would not be under a + // different choice of MAC location on padding failure. See + // EVP_tls_cbc_remove_padding. The value barrier seems to be necessary to + // prevent a branch in Clang. + crypto_word_t good = value_barrier_w( + constant_time_eq_int(CRYPTO_memcmp(record_mac, mac, mac_len), 0)); + good &= padding_ok; + if (!constant_time_declassify_w(good)) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); + return 0; + } // End of timing-sensitive code. + CONSTTIME_DECLASSIFY(&data_len, sizeof(data_len)); + for (const CRYPTO_IOVEC &iovec : iovecs) { + CONSTTIME_DECLASSIFY(iovec.out, iovec.len); + } - *out_len = data_len; + *out_total_bytes = data_len; return 1; } @@ -456,15 +479,14 @@ static const EVP_AEAD aead_aes_128_cbc_sha1_tls = { 16, // nonce len (IV) 16 + SHA_DIGEST_LENGTH, // overhead (padding + SHA1) SHA_DIGEST_LENGTH, // max tag length - 0, // seal_scatter_supports_extra_in - NULL, // init + nullptr, // init aead_aes_128_cbc_sha1_tls_init, aead_tls_cleanup, - aead_tls_open, - aead_tls_seal_scatter, - NULL, // open_gather - NULL, // get_iv + aead_tls_openv, + aead_tls_sealv, + nullptr, // openv_detached + nullptr, // get_iv aead_tls_tag_len, }; @@ -473,14 +495,13 @@ static const EVP_AEAD aead_aes_128_cbc_sha1_tls_implicit_iv = { 0, // nonce len 16 + SHA_DIGEST_LENGTH, // overhead (padding + SHA1) SHA_DIGEST_LENGTH, // max tag length - 0, // seal_scatter_supports_extra_in - NULL, // init + nullptr, // init aead_aes_128_cbc_sha1_tls_implicit_iv_init, aead_tls_cleanup, - aead_tls_open, - aead_tls_seal_scatter, - NULL, // open_gather + aead_tls_openv, + aead_tls_sealv, + nullptr, // openv_detached aead_tls_get_iv, // get_iv aead_tls_tag_len, }; @@ -490,15 +511,14 @@ static const EVP_AEAD aead_aes_128_cbc_sha256_tls = { 16, // nonce len (IV) 16 + SHA256_DIGEST_LENGTH, // overhead (padding + SHA256) SHA256_DIGEST_LENGTH, // max tag length - 0, // seal_scatter_supports_extra_in - NULL, // init + nullptr, // init aead_aes_128_cbc_sha256_tls_init, aead_tls_cleanup, - aead_tls_open, - aead_tls_seal_scatter, - NULL, // open_gather - NULL, // get_iv + aead_tls_openv, + aead_tls_sealv, + nullptr, // openv_detached + nullptr, // get_iv aead_tls_tag_len, }; @@ -507,15 +527,14 @@ static const EVP_AEAD aead_aes_256_cbc_sha1_tls = { 16, // nonce len (IV) 16 + SHA_DIGEST_LENGTH, // overhead (padding + SHA1) SHA_DIGEST_LENGTH, // max tag length - 0, // seal_scatter_supports_extra_in - NULL, // init + nullptr, // init aead_aes_256_cbc_sha1_tls_init, aead_tls_cleanup, - aead_tls_open, - aead_tls_seal_scatter, - NULL, // open_gather - NULL, // get_iv + aead_tls_openv, + aead_tls_sealv, + nullptr, // openv_detached + nullptr, // get_iv aead_tls_tag_len, }; @@ -524,14 +543,13 @@ static const EVP_AEAD aead_aes_256_cbc_sha1_tls_implicit_iv = { 0, // nonce len 16 + SHA_DIGEST_LENGTH, // overhead (padding + SHA1) SHA_DIGEST_LENGTH, // max tag length - 0, // seal_scatter_supports_extra_in - NULL, // init + nullptr, // init aead_aes_256_cbc_sha1_tls_implicit_iv_init, aead_tls_cleanup, - aead_tls_open, - aead_tls_seal_scatter, - NULL, // open_gather + aead_tls_openv, + aead_tls_sealv, + nullptr, // openv_detached aead_tls_get_iv, // get_iv aead_tls_tag_len, }; @@ -541,15 +559,14 @@ static const EVP_AEAD aead_des_ede3_cbc_sha1_tls = { 8, // nonce len (IV) 8 + SHA_DIGEST_LENGTH, // overhead (padding + SHA1) SHA_DIGEST_LENGTH, // max tag length - 0, // seal_scatter_supports_extra_in - NULL, // init + nullptr, // init aead_des_ede3_cbc_sha1_tls_init, aead_tls_cleanup, - aead_tls_open, - aead_tls_seal_scatter, - NULL, // open_gather - NULL, // get_iv + aead_tls_openv, + aead_tls_sealv, + nullptr, // openv_detached + nullptr, // get_iv aead_tls_tag_len, }; @@ -558,42 +575,41 @@ static const EVP_AEAD aead_des_ede3_cbc_sha1_tls_implicit_iv = { 0, // nonce len 8 + SHA_DIGEST_LENGTH, // overhead (padding + SHA1) SHA_DIGEST_LENGTH, // max tag length - 0, // seal_scatter_supports_extra_in - NULL, // init + nullptr, // init aead_des_ede3_cbc_sha1_tls_implicit_iv_init, aead_tls_cleanup, - aead_tls_open, - aead_tls_seal_scatter, - NULL, // open_gather + aead_tls_openv, + aead_tls_sealv, + nullptr, // openv_detached aead_tls_get_iv, // get_iv aead_tls_tag_len, }; -const EVP_AEAD *EVP_aead_aes_128_cbc_sha1_tls(void) { +const EVP_AEAD *EVP_aead_aes_128_cbc_sha1_tls() { return &aead_aes_128_cbc_sha1_tls; } -const EVP_AEAD *EVP_aead_aes_128_cbc_sha1_tls_implicit_iv(void) { +const EVP_AEAD *EVP_aead_aes_128_cbc_sha1_tls_implicit_iv() { return &aead_aes_128_cbc_sha1_tls_implicit_iv; } -const EVP_AEAD *EVP_aead_aes_128_cbc_sha256_tls(void) { +const EVP_AEAD *EVP_aead_aes_128_cbc_sha256_tls() { return &aead_aes_128_cbc_sha256_tls; } -const EVP_AEAD *EVP_aead_aes_256_cbc_sha1_tls(void) { +const EVP_AEAD *EVP_aead_aes_256_cbc_sha1_tls() { return &aead_aes_256_cbc_sha1_tls; } -const EVP_AEAD *EVP_aead_aes_256_cbc_sha1_tls_implicit_iv(void) { +const EVP_AEAD *EVP_aead_aes_256_cbc_sha1_tls_implicit_iv() { return &aead_aes_256_cbc_sha1_tls_implicit_iv; } -const EVP_AEAD *EVP_aead_des_ede3_cbc_sha1_tls(void) { +const EVP_AEAD *EVP_aead_des_ede3_cbc_sha1_tls() { return &aead_des_ede3_cbc_sha1_tls; } -const EVP_AEAD *EVP_aead_des_ede3_cbc_sha1_tls_implicit_iv(void) { +const EVP_AEAD *EVP_aead_des_ede3_cbc_sha1_tls_implicit_iv() { return &aead_des_ede3_cbc_sha1_tls_implicit_iv; } diff --git a/Sources/CNIOBoringSSL/crypto/cipher/get_cipher.cc b/Sources/CNIOBoringSSL/crypto/cipher/get_cipher.cc index 2ab7394e..32b55bcb 100644 --- a/Sources/CNIOBoringSSL/crypto/cipher/get_cipher.cc +++ b/Sources/CNIOBoringSSL/crypto/cipher/get_cipher.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -23,7 +28,7 @@ static const struct { int nid; const char *name; - const EVP_CIPHER *(*func)(void); + const EVP_CIPHER *(*func)(); } kCiphers[] = { {NID_aes_128_cbc, "aes-128-cbc", EVP_aes_128_cbc}, {NID_aes_128_ctr, "aes-128-ctr", EVP_aes_128_ctr}, @@ -50,31 +55,31 @@ static const struct { }; const EVP_CIPHER *EVP_get_cipherbynid(int nid) { - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kCiphers); i++) { - if (kCiphers[i].nid == nid) { - return kCiphers[i].func(); + for (const auto &cipher : kCiphers) { + if (cipher.nid == nid) { + return cipher.func(); } } - return NULL; + return nullptr; } const EVP_CIPHER *EVP_get_cipherbyname(const char *name) { - if (name == NULL) { - return NULL; + if (name == nullptr) { + return nullptr; } // This is not a name used by OpenSSL, but tcpdump registers it with - // |EVP_add_cipher_alias|. Our |EVP_add_cipher_alias| is a no-op, so we + // `EVP_add_cipher_alias`. Our `EVP_add_cipher_alias` is a no-op, so we // support the name here. if (OPENSSL_strcasecmp(name, "3des") == 0) { name = "des-ede3-cbc"; } - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kCiphers); i++) { - if (OPENSSL_strcasecmp(kCiphers[i].name, name) == 0) { - return kCiphers[i].func(); + for (const auto &cipher : kCiphers) { + if (OPENSSL_strcasecmp(cipher.name, name) == 0) { + return cipher.func(); } } - return NULL; + return nullptr; } diff --git a/Sources/CNIOBoringSSL/crypto/cipher/internal.h b/Sources/CNIOBoringSSL/crypto/cipher/internal.h index ba8bb1e3..ce73a6c1 100644 --- a/Sources/CNIOBoringSSL/crypto/cipher/internal.h +++ b/Sources/CNIOBoringSSL/crypto/cipher/internal.h @@ -1,45 +1,51 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. -#ifndef OPENSSL_HEADER_CIPHER_EXTRA_INTERNAL_H -#define OPENSSL_HEADER_CIPHER_EXTRA_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_CIPHER_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_CIPHER_INTERNAL_H #include #include +#include #include +#include +#include #include "../internal.h" -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN // EVP_tls_cbc_get_padding determines the padding from the decrypted, TLS, CBC -// record in |in|. This decrypted record should not include any "decrypted" +// record in `in`. This decrypted record should not include any "decrypted" // explicit IV. If the record is publicly invalid, it returns zero. Otherwise, -// it returns one and sets |*out_padding_ok| to all ones (0xfff..f) if the -// padding is valid and zero otherwise. It then sets |*out_len| to the length -// with the padding removed or |in_len| if invalid. +// it returns one and sets `*out_padding_ok` to all ones (0xfff..f) if the +// padding is valid and zero otherwise. It then sets `*out_len` to the length +// with the padding removed or `in_len` if invalid. // // If the function returns one, it runs in time independent of the contents of -// |in|. It is also guaranteed that |*out_len| >= |mac_size|, satisfying -// |EVP_tls_cbc_copy_mac|'s precondition. +// `in`. It is also guaranteed that, independent of `*out_padding_ok`, `mac_len` +// <= `*out_len` <= `in_len`, satisfying `EVP_tls_cbc_copy_mac`'s precondition. int EVP_tls_cbc_remove_padding(crypto_word_t *out_padding_ok, size_t *out_len, const uint8_t *in, size_t in_len, size_t block_size, size_t mac_size); -// EVP_tls_cbc_copy_mac copies |md_size| bytes from the end of the first -// |in_len| bytes of |in| to |out| in constant time (independent of the concrete -// value of |in_len|, which may vary within a 256-byte window). |in| must point -// to a buffer of |orig_len| bytes. +// EVP_tls_cbc_copy_mac copies `md_size` bytes from the end of the first +// `in_len` bytes of `in` to `out` in constant time (independent of the concrete +// value of `in_len`, which may vary within a 256-byte window). `in` must point +// to a buffer of `orig_len` bytes. // // On entry: // orig_len >= in_len >= md_size @@ -47,14 +53,14 @@ int EVP_tls_cbc_remove_padding(crypto_word_t *out_padding_ok, size_t *out_len, void EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in, size_t in_len, size_t orig_len); -// EVP_tls_cbc_record_digest_supported returns 1 iff |md| is a hash function +// EVP_tls_cbc_record_digest_supported returns 1 iff `md` is a hash function // which EVP_tls_cbc_digest_record supports. int EVP_tls_cbc_record_digest_supported(const EVP_MD *md); -// EVP_sha1_final_with_secret_suffix computes the result of hashing |len| bytes -// from |in| to |ctx| and writes the resulting hash to |out|. |len| is treated -// as secret and must be at most |max_len|, which is treated as public. |in| -// must point to a buffer of at least |max_len| bytes. It returns one on success +// EVP_sha1_final_with_secret_suffix computes the result of hashing `len` bytes +// from `in` to `ctx` and writes the resulting hash to `out`. `len` is treated +// as secret and must be at most `max_len`, which is treated as public. `in` +// must point to a buffer of at least `max_len` bytes. It returns one on success // and zero if inputs are too long. // // This function is exported for unit tests. @@ -63,7 +69,7 @@ OPENSSL_EXPORT int EVP_sha1_final_with_secret_suffix( size_t max_len); // EVP_sha256_final_with_secret_suffix acts like -// |EVP_sha1_final_with_secret_suffix|, but for SHA-256. +// `EVP_sha1_final_with_secret_suffix`, but for SHA-256. // // This function is exported for unit tests. OPENSSL_EXPORT int EVP_sha256_final_with_secret_suffix( @@ -77,23 +83,29 @@ OPENSSL_EXPORT int EVP_sha256_final_with_secret_suffix( // EVP_tls_cbc_record_digest_supported must return true for this hash. // md_out: the digest output. At most EVP_MAX_MD_SIZE bytes will be written. // md_out_size: the number of output bytes is written here. -// header: the 13-byte, TLS record header. -// data: the record data itself -// data_size: the secret, reported length of the data once the padding and MAC -// have been removed. -// data_plus_mac_plus_padding_size: the public length of the whole -// record, including padding. +// len_header: the two length bytes of the TLS record header. +// aadvecs: the 11-byte TLS record header as it was provided by the caller. +// iovecs_without_trailer: the section of the plaintext that does not include +// the trailer whose length is secret (typically the entire plaintext with +// an upper bound of padding and MAC size removed) +// trailer: a buffer, of public length, containing the remainder of the +// plaintext as a prefix. +// data_in_trailer_size: the secret, reported length of the data portion in +// `trailer` once the padding and MAC have been removed. // // On entry: by virtue of having been through one of the remove_padding // functions, above, we know that data_plus_mac_size is large enough to contain // a padding byte and MAC. (If the padding was invalid, it might contain the // padding too. ) -int EVP_tls_cbc_digest_record(const EVP_MD *md, uint8_t *md_out, - size_t *md_out_size, const uint8_t header[13], - const uint8_t *data, size_t data_size, - size_t data_plus_mac_plus_padding_size, - const uint8_t *mac_secret, - unsigned mac_secret_length); +int EVP_tls_cbc_digest_record( + const EVP_MD *md, uint8_t *md_out, size_t *md_out_size, + const uint8_t len_header[2], bssl::Span aadvecs, + bssl::Span iovecs_without_trailer, + bssl::Span trailer, size_t data_in_trailer_size, + const uint8_t *mac_secret, unsigned mac_secret_length); + + +// ChaCha20-Poly1305 Assembly. #define POLY1305_TAG_LEN 16 @@ -124,7 +136,7 @@ union chacha20_poly1305_seal_data { } out; }; -#if (defined(OPENSSL_X86_64) || defined(OPENSSL_AARCH64)) && \ +#if (defined(OPENSSL_X86_64) || defined(OPENSSL_AARCH64)) && \ !defined(OPENSSL_NO_ASM) static_assert(sizeof(union chacha20_poly1305_open_data) == 48, @@ -132,7 +144,7 @@ static_assert(sizeof(union chacha20_poly1305_open_data) == 48, static_assert(sizeof(union chacha20_poly1305_seal_data) == 48 + 8 + 8, "wrong chacha20_poly1305_seal_data size"); -inline int chacha20_poly1305_asm_capable(void) { +inline int chacha20_poly1305_asm_capable() { #if defined(OPENSSL_X86_64) return CRYPTO_is_SSE4_1_capable(); #elif defined(OPENSSL_AARCH64) @@ -141,15 +153,15 @@ inline int chacha20_poly1305_asm_capable(void) { } // chacha20_poly1305_open is defined in chacha20_poly1305_*.pl. It decrypts -// |plaintext_len| bytes from |ciphertext| and writes them to |out_plaintext|. -// Additional input parameters are passed in |aead_data->in|. On exit, it will -// write calculated tag value to |aead_data->out.tag|, which the caller must +// `plaintext_len` bytes from `ciphertext` and writes them to `out_plaintext`. +// Additional input parameters are passed in `aead_data->in`. On exit, it will +// write calculated tag value to `aead_data->out.tag`, which the caller must // check. #if defined(OPENSSL_X86_64) -extern void chacha20_poly1305_open_nohw( +extern "C" void chacha20_poly1305_open_sse41( uint8_t *out_plaintext, const uint8_t *ciphertext, size_t plaintext_len, const uint8_t *ad, size_t ad_len, union chacha20_poly1305_open_data *data); -extern void chacha20_poly1305_open_avx2( +extern "C" void chacha20_poly1305_open_avx2( uint8_t *out_plaintext, const uint8_t *ciphertext, size_t plaintext_len, const uint8_t *ad, size_t ad_len, union chacha20_poly1305_open_data *data); inline void chacha20_poly1305_open(uint8_t *out_plaintext, @@ -161,28 +173,28 @@ inline void chacha20_poly1305_open(uint8_t *out_plaintext, chacha20_poly1305_open_avx2(out_plaintext, ciphertext, plaintext_len, ad, ad_len, data); } else { - chacha20_poly1305_open_nohw(out_plaintext, ciphertext, plaintext_len, ad, - ad_len, data); + chacha20_poly1305_open_sse41(out_plaintext, ciphertext, plaintext_len, ad, + ad_len, data); } } #else -extern void chacha20_poly1305_open(uint8_t *out_plaintext, - const uint8_t *ciphertext, - size_t plaintext_len, const uint8_t *ad, - size_t ad_len, - union chacha20_poly1305_open_data *data); +extern "C" void chacha20_poly1305_open(uint8_t *out_plaintext, + const uint8_t *ciphertext, + size_t plaintext_len, const uint8_t *ad, + size_t ad_len, + union chacha20_poly1305_open_data *data); #endif // chacha20_poly1305_open is defined in chacha20_poly1305_*.pl. It encrypts -// |plaintext_len| bytes from |plaintext| and writes them to |out_ciphertext|. -// Additional input parameters are passed in |aead_data->in|. The calculated tag -// value is over the computed ciphertext concatenated with |extra_ciphertext| -// and written to |aead_data->out.tag|. +// `plaintext_len` bytes from `plaintext` and writes them to `out_ciphertext`. +// Additional input parameters are passed in `aead_data->in`. The calculated tag +// value is over the computed ciphertext concatenated with `extra_ciphertext` +// and written to `aead_data->out.tag`. #if defined(OPENSSL_X86_64) -extern void chacha20_poly1305_seal_nohw( +extern "C" void chacha20_poly1305_seal_sse41( uint8_t *out_ciphertext, const uint8_t *plaintext, size_t plaintext_len, const uint8_t *ad, size_t ad_len, union chacha20_poly1305_seal_data *data); -extern void chacha20_poly1305_seal_avx2( +extern "C" void chacha20_poly1305_seal_avx2( uint8_t *out_ciphertext, const uint8_t *plaintext, size_t plaintext_len, const uint8_t *ad, size_t ad_len, union chacha20_poly1305_seal_data *data); inline void chacha20_poly1305_seal(uint8_t *out_ciphertext, @@ -194,21 +206,21 @@ inline void chacha20_poly1305_seal(uint8_t *out_ciphertext, chacha20_poly1305_seal_avx2(out_ciphertext, plaintext, plaintext_len, ad, ad_len, data); } else { - chacha20_poly1305_seal_nohw(out_ciphertext, plaintext, plaintext_len, ad, - ad_len, data); + chacha20_poly1305_seal_sse41(out_ciphertext, plaintext, plaintext_len, ad, + ad_len, data); } } #else -extern void chacha20_poly1305_seal(uint8_t *out_ciphertext, - const uint8_t *plaintext, - size_t plaintext_len, const uint8_t *ad, - size_t ad_len, - union chacha20_poly1305_seal_data *data); +extern "C" void chacha20_poly1305_seal(uint8_t *out_ciphertext, + const uint8_t *plaintext, + size_t plaintext_len, const uint8_t *ad, + size_t ad_len, + union chacha20_poly1305_seal_data *data); #endif #else -inline int chacha20_poly1305_asm_capable(void) { return 0; } +inline int chacha20_poly1305_asm_capable() { return 0; } inline void chacha20_poly1305_open(uint8_t *out_plaintext, const uint8_t *ciphertext, @@ -228,8 +240,160 @@ inline void chacha20_poly1305_seal(uint8_t *out_ciphertext, #endif -#if defined(__cplusplus) -} // extern C -#endif +// AES-GCM-SIV Assembly. -#endif // OPENSSL_HEADER_CIPHER_EXTRA_INTERNAL_H +// TODO(davidben): AES-GCM-SIV assembly is not correct for Windows. It must save +// and restore xmm6 through xmm15. +#if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM) && \ + !defined(OPENSSL_WINDOWS) +#define AES_GCM_SIV_ASM + +struct aead_aes_gcm_siv_asm_ctx { + alignas(16) uint8_t key[16 * 15]; + int is_128_bit; +}; + +inline int aes_gcm_siv_asm_capable() { + return CRYPTO_is_AVX_capable() && CRYPTO_is_AESNI_capable() && + CRYPTO_is_PCLMUL_capable(); +} + +extern "C" { +// aes128gcmsiv_aes_ks writes an AES-128 key schedule for `key` to +// `out_expanded_key`. `out_expanded_key` must be 16-byte aligned. +extern void aes128gcmsiv_aes_ks(const uint8_t key[16], + uint8_t out_expanded_key[16 * 15]); + +// aes256gcmsiv_aes_ks writes an AES-256 key schedule for `key` to +// `out_expanded_key`. `out_expanded_key` must be 16-byte aligned. +extern void aes256gcmsiv_aes_ks(const uint8_t key[32], + uint8_t out_expanded_key[16 * 15]); + +// aesgcmsiv_polyval_horner updates the POLYVAL value in `in_out_poly` to +// include a number (`in_blocks`) of 16-byte blocks of data from `in`, given +// the POLYVAL key in `key`. `in_out_poly` and `key` must be 16-byte aligned. +extern void aesgcmsiv_polyval_horner(const uint8_t in_out_poly[16], + const uint8_t key[16], const uint8_t *in, + size_t in_blocks); + +// aesgcmsiv_htable_init writes powers 1..8 of `auth_key` to `out_htable`. +// `out_htable` and `auth_key` must be 16-byte aligned. +extern void aesgcmsiv_htable_init(uint8_t out_htable[16 * 8], + const uint8_t auth_key[16]); + +// aesgcmsiv_htable6_init writes powers 1..6 of `auth_key` to `out_htable`. +// `out_htable` and `auth_key` must be 16-byte aligned. +extern void aesgcmsiv_htable6_init(uint8_t out_htable[16 * 6], + const uint8_t auth_key[16]); + +// aesgcmsiv_htable_polyval updates the POLYVAL value in `in_out_poly` to +// include `in_len` bytes of data from `in`. (Where `in_len` must be a multiple +// of 16.) It uses the precomputed powers of the key given in `htable`. +// `in_out_poly` and `htable` must be 16-byte aligned. +extern void aesgcmsiv_htable_polyval(const uint8_t htable[16 * 8], + const uint8_t *in, size_t in_len, + uint8_t in_out_poly[16]); + +// aes128gcmsiv_dec decrypts `in_len` & ~15 bytes from `out` and writes them to +// `in`. `in` and `out` may be equal, but must not otherwise alias. +// +// `in_out_calculated_tag_and_scratch`, on entry, must contain: +// 1. The current value of the calculated tag, which will be updated during +// decryption and written back to the beginning of this buffer on exit. +// 2. The claimed tag, which is needed to derive counter values. +// +// While decrypting, the whole of `in_out_calculated_tag_and_scratch` may be +// used for other purposes. `in_out_calculated_tag_and_scratch` and `htable` +// must be 16-byte aligned. In order to decrypt and update the POLYVAL value, it +// uses the expanded key from `key` and the table of powers in `htable`. +extern void aes128gcmsiv_dec(const uint8_t *in, uint8_t *out, + uint8_t in_out_calculated_tag_and_scratch[16 * 8], + const uint8_t htable[16 * 6], + const struct aead_aes_gcm_siv_asm_ctx *key, + size_t in_len); + +// aes256gcmsiv_dec acts like `aes128gcmsiv_dec`, but for AES-256. +// `in_out_calculated_tag_and_scratch` and `htable` must be 16-byte aligned. +extern void aes256gcmsiv_dec(const uint8_t *in, uint8_t *out, + uint8_t in_out_calculated_tag_and_scratch[16 * 8], + const uint8_t htable[16 * 6], + const struct aead_aes_gcm_siv_asm_ctx *key, + size_t in_len); + +// aes128gcmsiv_kdf performs the AES-GCM-SIV KDF given the expanded key from +// `key_schedule` and the nonce in `nonce`. Note that, while only 12 bytes of +// the nonce are used, 16 bytes are read and so the value must be +// right-padded. `nonce`, `out_key_material`, and `key_schedule` must be +// 16-byte aligned. +extern void aes128gcmsiv_kdf(const uint8_t nonce[16], + uint64_t out_key_material[8], + const uint8_t *key_schedule); + +// aes256gcmsiv_kdf acts like `aes128gcmsiv_kdf`, but for AES-256. `nonce`, +// `out_key_material`, and `key_schedule` must be 16-byte aligned. +extern void aes256gcmsiv_kdf(const uint8_t nonce[16], + uint64_t out_key_material[12], + const uint8_t *key_schedule); + +// aes128gcmsiv_aes_ks_enc_x1 performs a key expansion of the AES-128 key in +// `key`, writes the expanded key to `out_expanded_key` and encrypts a single +// block from `in` to `out`. `in`, `out`, `out_expanded_key`, and `key` must be +// 16-byte aligned. +extern void aes128gcmsiv_aes_ks_enc_x1(const uint8_t in[16], uint8_t out[16], + uint8_t out_expanded_key[16 * 15], + const uint64_t key[2]); + +// aes256gcmsiv_aes_ks_enc_x1 acts like `aes128gcmsiv_aes_ks_enc_x1`, but for +// AES-256. `in`, `out`, `out_expanded_key`, and `key` must be 16-byte aligned. +extern void aes256gcmsiv_aes_ks_enc_x1(const uint8_t in[16], uint8_t out[16], + uint8_t out_expanded_key[16 * 15], + const uint64_t key[4]); + +// aes128gcmsiv_ecb_enc_block encrypts a single block from `in` to `out` using +// the expanded key in `expanded_key`. `in` and `out` must be 16-byte aligned. +extern void aes128gcmsiv_ecb_enc_block( + const uint8_t in[16], uint8_t out[16], + const struct aead_aes_gcm_siv_asm_ctx *expanded_key); + +// aes256gcmsiv_ecb_enc_block acts like `aes128gcmsiv_ecb_enc_block`, but for +// AES-256. `in` and `out` must be 16-byte aligned. +extern void aes256gcmsiv_ecb_enc_block( + const uint8_t in[16], uint8_t out[16], + const struct aead_aes_gcm_siv_asm_ctx *expanded_key); + +// aes128gcmsiv_enc_msg_x4 encrypts `in_len` bytes from `in` to `out` using the +// expanded key from `key`. (The value of `in_len` must be a multiple of 16.) +// The `in` and `out` buffers may be equal but must not otherwise overlap. The +// initial counter is constructed from the given `tag` as required by +// AES-GCM-SIV. `tag` must be 16-byte aligned. +extern void aes128gcmsiv_enc_msg_x4(const uint8_t *in, uint8_t *out, + const uint8_t *tag, + const struct aead_aes_gcm_siv_asm_ctx *key, + size_t in_len); + +// aes256gcmsiv_enc_msg_x4 acts like `aes128gcmsiv_enc_msg_x4`, but for +// AES-256. `tag` must be 16-byte aligned. +extern void aes256gcmsiv_enc_msg_x4(const uint8_t *in, uint8_t *out, + const uint8_t *tag, + const struct aead_aes_gcm_siv_asm_ctx *key, + size_t in_len); + +// aes128gcmsiv_enc_msg_x8 acts like `aes128gcmsiv_enc_msg_x4`, but is +// optimised for longer messages. +extern void aes128gcmsiv_enc_msg_x8(const uint8_t *in, uint8_t *out, + const uint8_t *tag, + const struct aead_aes_gcm_siv_asm_ctx *key, + size_t in_len); + +// aes256gcmsiv_enc_msg_x8 acts like `aes256gcmsiv_enc_msg_x4`, but is +// optimised for longer messages. +extern void aes256gcmsiv_enc_msg_x8(const uint8_t *in, uint8_t *out, + const uint8_t *tag, + const struct aead_aes_gcm_siv_asm_ctx *key, + size_t in_len); +} +#endif // OPENSSL_X86_64 && !OPENSSL_NO_ASM && !OPENSSL_WINDOWS + +BSSL_NAMESPACE_END + +#endif // OPENSSL_HEADER_CRYPTO_CIPHER_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/cipher/tls_cbc.cc b/Sources/CNIOBoringSSL/crypto/cipher/tls_cbc.cc index a43b1812..235b6fba 100644 --- a/Sources/CNIOBoringSSL/crypto/cipher/tls_cbc.cc +++ b/Sources/CNIOBoringSSL/crypto/cipher/tls_cbc.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2012-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2012-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -13,15 +18,19 @@ #include #include #include +#include +#include "../fipsmodule/cipher/internal.h" #include "../internal.h" #include "internal.h" -#include "../fipsmodule/cipher/internal.h" -int EVP_tls_cbc_remove_padding(crypto_word_t *out_padding_ok, size_t *out_len, - const uint8_t *in, size_t in_len, - size_t block_size, size_t mac_size) { +using namespace bssl; + +int bssl::EVP_tls_cbc_remove_padding(crypto_word_t *out_padding_ok, + size_t *out_len, const uint8_t *in, + size_t in_len, size_t block_size, + size_t mac_size) { const size_t overhead = 1 /* padding length byte */ + mac_size; // These lengths are all public so we can test them in non-constant time. @@ -37,7 +46,7 @@ int EVP_tls_cbc_remove_padding(crypto_word_t *out_padding_ok, size_t *out_len, // length byte. Thus, with the length byte included, there are i+1 // bytes of padding. // - // We can't check just |padding_length+1| bytes because that leaks + // We can't check just `padding_length+1` bytes because that leaks // decrypted information. Therefore we always have to check the maximum // amount of padding possible. (Again, the length of the record is // public information so we can use it.) @@ -48,18 +57,21 @@ int EVP_tls_cbc_remove_padding(crypto_word_t *out_padding_ok, size_t *out_len, for (size_t i = 0; i < to_check; i++) { uint8_t mask = constant_time_ge_8(padding_length, i); - uint8_t b = in[in_len - 1 - i]; - // The final |padding_length+1| bytes should all have the value - // |padding_length|. Therefore the XOR should be zero. + // The value barrier on `(in_len - 1 - i)` isn't needed to enforce + // constant-time. It is just there to prevent a false positive in + // constant-time checks by valgrind. + uint8_t b = in[value_barrier_w(in_len - 1 - i)]; + // The final `padding_length+1` bytes should all have the value + // `padding_length`. Therefore the XOR should be zero. good &= ~(mask & (padding_length ^ b)); } - // If any of the final |padding_length+1| bytes had the wrong value, - // one or more of the lower eight bits of |good| will be cleared. + // If any of the final `padding_length+1` bytes had the wrong value, + // one or more of the lower eight bits of `good` will be cleared. good = constant_time_eq_w(0xff, good & 0xff); - // Always treat |padding_length| as zero on error. If, assuming block size of - // 16, a padding of [<15 arbitrary bytes> 15] treated |padding_length| as 16 + // Always treat `padding_length` as zero on error. If, assuming block size of + // 16, a padding of [<15 arbitrary bytes> 15] treated `padding_length` as 16 // and returned -1, distinguishing good MAC and bad padding from bad MAC and // bad padding would give POODLE's padding oracle. padding_length = good & (padding_length + 1); @@ -68,13 +80,13 @@ int EVP_tls_cbc_remove_padding(crypto_word_t *out_padding_ok, size_t *out_len, return 1; } -void EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in, - size_t in_len, size_t orig_len) { +void bssl::EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in, + size_t in_len, size_t orig_len) { uint8_t rotated_mac1[EVP_MAX_MD_SIZE], rotated_mac2[EVP_MAX_MD_SIZE]; uint8_t *rotated_mac = rotated_mac1; uint8_t *rotated_mac_tmp = rotated_mac2; - // mac_end is the index of |in| just after the end of the MAC. + // mac_end is the index of `in` just after the end of the MAC. size_t mac_end = in_len; size_t mac_start = mac_end - md_size; @@ -102,15 +114,15 @@ void EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in, mac_started |= is_mac_start; uint8_t mac_ended = constant_time_ge_8(i, mac_end); rotated_mac[j] |= in[i] & mac_started & ~mac_ended; - // Save the offset that |mac_start| is mapped to. + // Save the offset that `mac_start` is mapped to. rotate_offset |= j & is_mac_start; } // Now rotate the MAC. We rotate in log(md_size) steps, one for each bit // position. for (size_t offset = 1; offset < md_size; offset <<= 1, rotate_offset >>= 1) { - // Rotate by |offset| iff the corresponding bit is set in - // |rotate_offset|, placing the result in |rotated_mac_tmp|. + // Rotate by `offset` iff the corresponding bit is set in + // `rotate_offset`, placing the result in `rotated_mac_tmp`. const uint8_t skip_rotate = (rotate_offset & 1) - 1; for (size_t i = 0, j = offset; i < md_size; i++, j++) { if (j >= md_size) { @@ -120,7 +132,7 @@ void EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in, constant_time_select_8(skip_rotate, rotated_mac[i], rotated_mac[j]); } - // Swap pointers so |rotated_mac| contains the (possibly) rotated value. + // Swap pointers so `rotated_mac` contains the (possibly) rotated value. // Note the number of iterations and thus the identity of these pointers is // public information. uint8_t *tmp = rotated_mac; @@ -131,12 +143,12 @@ void EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in, OPENSSL_memcpy(out, rotated_mac, md_size); } -int EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx, - uint8_t out[SHA_DIGEST_LENGTH], - const uint8_t *in, size_t len, - size_t max_len) { - // Bound the input length so |total_bits| below fits in four bytes. This is - // redundant with TLS record size limits. This also ensures |input_idx| below +int bssl::EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx, + uint8_t out[SHA_DIGEST_LENGTH], + const uint8_t *in, size_t len, + size_t max_len) { + // Bound the input length so `total_bits` below fits in four bytes. This is + // redundant with TLS record size limits. This also ensures `input_idx` below // does not overflow. size_t max_len_bits = max_len << 3; if (ctx->Nh != 0 || @@ -146,7 +158,7 @@ int EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx, return 0; } - // We need to hash the following into |ctx|: + // We need to hash the following into `ctx`: // // - ctx->data[:ctx->num] // - in[:len] @@ -157,24 +169,21 @@ int EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx, size_t last_block = num_blocks - 1; size_t max_blocks = (ctx->num + max_len + 1 + 8 + SHA_CBLOCK - 1) >> 6; - // The bounds above imply |total_bits| fits in four bytes. + // The bounds above imply `total_bits` fits in four bytes. size_t total_bits = ctx->Nl + (len << 3); uint8_t length_bytes[4]; - length_bytes[0] = (uint8_t)(total_bits >> 24); - length_bytes[1] = (uint8_t)(total_bits >> 16); - length_bytes[2] = (uint8_t)(total_bits >> 8); - length_bytes[3] = (uint8_t)total_bits; + CRYPTO_store_u32_be(length_bytes, total_bits); // We now construct and process each expected block in constant-time. uint8_t block[SHA_CBLOCK] = {0}; uint32_t result[5] = {0}; - // input_idx is the index into |in| corresponding to the current block. - // However, we allow this index to overflow beyond |max_len|, to simplify the + // input_idx is the index into `in` corresponding to the current block. + // However, we allow this index to overflow beyond `max_len`, to simplify the // 0x80 byte. size_t input_idx = 0; for (size_t i = 0; i < max_blocks; i++) { - // Fill |block| with data from the partial block in |ctx| and |in|. We copy - // as if we were hashing up to |max_len| and then zero the excess later. + // Fill `block` with data from the partial block in `ctx` and `in`. We copy + // as if we were hashing up to `max_len` and then zero the excess later. size_t block_start = 0; if (i == 0) { OPENSSL_memcpy(block, ctx->data, ctx->num); @@ -188,12 +197,12 @@ int EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx, OPENSSL_memcpy(block + block_start, in + input_idx, to_copy); } - // Zero any bytes beyond |len| and add the 0x80 byte. + // Zero any bytes beyond `len` and add the 0x80 byte. for (size_t j = block_start; j < SHA_CBLOCK; j++) { // input[idx] corresponds to block[j]. size_t idx = input_idx + j - block_start; - // The barriers on |len| are not strictly necessary. However, without - // them, GCC compiles this code by incorporating |len| into the loop + // The barriers on `len` are not strictly necessary. However, without + // them, GCC compiles this code by incorporating `len` into the loop // counter and subtracting it out later. This is still constant-time, but // it frustrates attempts to validate this. uint8_t is_in_bounds = constant_time_lt_8(idx, value_barrier_w(len)); @@ -204,8 +213,10 @@ int EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx, input_idx += SHA_CBLOCK - block_start; - // Fill in the length if this is the last block. - crypto_word_t is_last_block = constant_time_eq_w(i, last_block); + // Fill in the length if this is the last block. Use a value barrier to + // prevent Clang from compiling the conditional select as a jump. + crypto_word_t is_last_block = + value_barrier_w(constant_time_eq_w(i, last_block)); for (size_t j = 0; j < 4; j++) { block[SHA_CBLOCK - 4 + j] |= is_last_block & length_bytes[j]; } @@ -224,12 +235,12 @@ int EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx, return 1; } -int EVP_sha256_final_with_secret_suffix(SHA256_CTX *ctx, - uint8_t out[SHA256_DIGEST_LENGTH], - const uint8_t *in, size_t len, - size_t max_len) { - // Bound the input length so |total_bits| below fits in four bytes. This is - // redundant with TLS record size limits. This also ensures |input_idx| below +int bssl::EVP_sha256_final_with_secret_suffix(SHA256_CTX *ctx, + uint8_t out[SHA256_DIGEST_LENGTH], + const uint8_t *in, size_t len, + size_t max_len) { + // Bound the input length so `total_bits` below fits in four bytes. This is + // redundant with TLS record size limits. This also ensures `input_idx` below // does not overflow. size_t max_len_bits = max_len << 3; if (ctx->Nh != 0 || @@ -239,7 +250,7 @@ int EVP_sha256_final_with_secret_suffix(SHA256_CTX *ctx, return 0; } - // We need to hash the following into |ctx|: + // We need to hash the following into `ctx`: // // - ctx->data[:ctx->num] // - in[:len] @@ -250,24 +261,21 @@ int EVP_sha256_final_with_secret_suffix(SHA256_CTX *ctx, size_t last_block = num_blocks - 1; size_t max_blocks = (ctx->num + max_len + 1 + 8 + SHA256_CBLOCK - 1) >> 6; - // The bounds above imply |total_bits| fits in four bytes. + // The bounds above imply `total_bits` fits in four bytes. size_t total_bits = ctx->Nl + (len << 3); uint8_t length_bytes[4]; - length_bytes[0] = (uint8_t)(total_bits >> 24); - length_bytes[1] = (uint8_t)(total_bits >> 16); - length_bytes[2] = (uint8_t)(total_bits >> 8); - length_bytes[3] = (uint8_t)total_bits; + CRYPTO_store_u32_be(length_bytes, total_bits); // We now construct and process each expected block in constant-time. uint8_t block[SHA256_CBLOCK] = {0}; uint32_t result[8] = {0}; - // input_idx is the index into |in| corresponding to the current block. - // However, we allow this index to overflow beyond |max_len|, to simplify the + // input_idx is the index into `in` corresponding to the current block. + // However, we allow this index to overflow beyond `max_len`, to simplify the // 0x80 byte. size_t input_idx = 0; for (size_t i = 0; i < max_blocks; i++) { - // Fill |block| with data from the partial block in |ctx| and |in|. We copy - // as if we were hashing up to |max_len| and then zero the excess later. + // Fill `block` with data from the partial block in `ctx` and `in`. We copy + // as if we were hashing up to `max_len` and then zero the excess later. size_t block_start = 0; if (i == 0) { OPENSSL_memcpy(block, ctx->data, ctx->num); @@ -281,12 +289,12 @@ int EVP_sha256_final_with_secret_suffix(SHA256_CTX *ctx, OPENSSL_memcpy(block + block_start, in + input_idx, to_copy); } - // Zero any bytes beyond |len| and add the 0x80 byte. + // Zero any bytes beyond `len` and add the 0x80 byte. for (size_t j = block_start; j < SHA256_CBLOCK; j++) { // input[idx] corresponds to block[j]. size_t idx = input_idx + j - block_start; - // The barriers on |len| are not strictly necessary. However, without - // them, GCC compiles this code by incorporating |len| into the loop + // The barriers on `len` are not strictly necessary. However, without + // them, GCC compiles this code by incorporating `len` into the loop // counter and subtracting it out later. This is still constant-time, but // it frustrates attempts to validate this. uint8_t is_in_bounds = constant_time_lt_8(idx, value_barrier_w(len)); @@ -297,8 +305,10 @@ int EVP_sha256_final_with_secret_suffix(SHA256_CTX *ctx, input_idx += SHA256_CBLOCK - block_start; - // Fill in the length if this is the last block. - crypto_word_t is_last_block = constant_time_eq_w(i, last_block); + // Fill in the length if this is the last block. Use a value barrier to + // prevent Clang from compiling the conditional select as a jump. + crypto_word_t is_last_block = + value_barrier_w(constant_time_eq_w(i, last_block)); for (size_t j = 0; j < 4; j++) { block[SHA256_CBLOCK - 4 + j] |= is_last_block & length_bytes[j]; } @@ -317,7 +327,7 @@ int EVP_sha256_final_with_secret_suffix(SHA256_CTX *ctx, return 1; } -int EVP_tls_cbc_record_digest_supported(const EVP_MD *md) { +int bssl::EVP_tls_cbc_record_digest_supported(const EVP_MD *md) { switch (EVP_MD_type(md)) { case NID_sha1: case NID_sha256: @@ -327,12 +337,12 @@ int EVP_tls_cbc_record_digest_supported(const EVP_MD *md) { } } -static int tls_cbc_digest_record_sha1(uint8_t *md_out, size_t *md_out_size, - const uint8_t header[13], - const uint8_t *data, size_t data_size, - size_t data_plus_mac_plus_padding_size, - const uint8_t *mac_secret, - unsigned mac_secret_length) { +static int tls_cbc_digest_record_sha1( + uint8_t *md_out, size_t *md_out_size, const uint8_t len_header[2], + Span aadvecs, + Span iovecs_without_trailer, + Span trailer, size_t data_in_trailer_size, + const uint8_t *mac_secret, unsigned mac_secret_length) { if (mac_secret_length > SHA_CBLOCK) { // HMAC pads small keys with zeros and hashes large keys down. This function // should never reach the large key case. @@ -351,24 +361,22 @@ static int tls_cbc_digest_record_sha1(uint8_t *md_out, size_t *md_out_size, SHA_CTX ctx; SHA1_Init(&ctx); SHA1_Update(&ctx, hmac_pad, SHA_CBLOCK); - SHA1_Update(&ctx, header, 13); - - // There are at most 256 bytes of padding, so we can compute the public - // minimum length for |data_size|. - size_t min_data_size = 0; - if (data_plus_mac_plus_padding_size > SHA_DIGEST_LENGTH + 256) { - min_data_size = data_plus_mac_plus_padding_size - SHA_DIGEST_LENGTH - 256; + for (const CRYPTO_IVEC &aadvec : aadvecs) { + SHA1_Update(&ctx, aadvec.in, aadvec.len); } + SHA1_Update(&ctx, len_header, 2); // Hash the public minimum length directly. This reduces the number of blocks // that must be computed in constant-time. - SHA1_Update(&ctx, data, min_data_size); + for (const CRYPTO_IOVEC &iovec : iovecs_without_trailer) { + SHA1_Update(&ctx, iovec.out, iovec.len); + } - // Hash the remaining data without leaking |data_size|. + // Hash the remaining data without leaking `data_in_trailer_size`. uint8_t mac_out[SHA_DIGEST_LENGTH]; - if (!EVP_sha1_final_with_secret_suffix( - &ctx, mac_out, data + min_data_size, data_size - min_data_size, - data_plus_mac_plus_padding_size - min_data_size)) { + if (!EVP_sha1_final_with_secret_suffix(&ctx, mac_out, trailer.data(), + data_in_trailer_size, + trailer.size())) { return 0; } @@ -385,12 +393,12 @@ static int tls_cbc_digest_record_sha1(uint8_t *md_out, size_t *md_out_size, return 1; } -static int tls_cbc_digest_record_sha256(uint8_t *md_out, size_t *md_out_size, - const uint8_t header[13], - const uint8_t *data, size_t data_size, - size_t data_plus_mac_plus_padding_size, - const uint8_t *mac_secret, - unsigned mac_secret_length) { +static int tls_cbc_digest_record_sha256( + uint8_t *md_out, size_t *md_out_size, const uint8_t len_header[2], + Span aadvecs, + Span iovecs_without_trailer, + Span trailer, size_t data_in_trailer_size, + const uint8_t *mac_secret, unsigned mac_secret_length) { if (mac_secret_length > SHA256_CBLOCK) { // HMAC pads small keys with zeros and hashes large keys down. This function // should never reach the large key case. @@ -409,25 +417,22 @@ static int tls_cbc_digest_record_sha256(uint8_t *md_out, size_t *md_out_size, SHA256_CTX ctx; SHA256_Init(&ctx); SHA256_Update(&ctx, hmac_pad, SHA256_CBLOCK); - SHA256_Update(&ctx, header, 13); - - // There are at most 256 bytes of padding, so we can compute the public - // minimum length for |data_size|. - size_t min_data_size = 0; - if (data_plus_mac_plus_padding_size > SHA256_DIGEST_LENGTH + 256) { - min_data_size = - data_plus_mac_plus_padding_size - SHA256_DIGEST_LENGTH - 256; + for (const CRYPTO_IVEC &aadvec : aadvecs) { + SHA256_Update(&ctx, aadvec.in, aadvec.len); } + SHA256_Update(&ctx, len_header, 2); // Hash the public minimum length directly. This reduces the number of blocks // that must be computed in constant-time. - SHA256_Update(&ctx, data, min_data_size); + for (const CRYPTO_IOVEC &iovec : iovecs_without_trailer) { + SHA256_Update(&ctx, iovec.out, iovec.len); + } - // Hash the remaining data without leaking |data_size|. + // Hash the remaining data without leaking `data_in_trailer_size`. uint8_t mac_out[SHA256_DIGEST_LENGTH]; - if (!EVP_sha256_final_with_secret_suffix( - &ctx, mac_out, data + min_data_size, data_size - min_data_size, - data_plus_mac_plus_padding_size - min_data_size)) { + if (!EVP_sha256_final_with_secret_suffix(&ctx, mac_out, trailer.data(), + data_in_trailer_size, + trailer.size())) { return 0; } @@ -444,22 +449,22 @@ static int tls_cbc_digest_record_sha256(uint8_t *md_out, size_t *md_out_size, return 1; } -int EVP_tls_cbc_digest_record(const EVP_MD *md, uint8_t *md_out, - size_t *md_out_size, const uint8_t header[13], - const uint8_t *data, size_t data_size, - size_t data_plus_mac_plus_padding_size, - const uint8_t *mac_secret, - unsigned mac_secret_length) { +int bssl::EVP_tls_cbc_digest_record( + const EVP_MD *md, uint8_t *md_out, size_t *md_out_size, + const uint8_t len_header[2], Span aadvecs, + Span iovecs_without_trailer, + Span trailer, size_t data_in_trailer_size, + const uint8_t *mac_secret, unsigned mac_secret_length) { switch (EVP_MD_type(md)) { case NID_sha1: - return tls_cbc_digest_record_sha1( - md_out, md_out_size, header, data, data_size, - data_plus_mac_plus_padding_size, mac_secret, mac_secret_length); + return tls_cbc_digest_record_sha1( // + md_out, md_out_size, len_header, aadvecs, iovecs_without_trailer, + trailer, data_in_trailer_size, mac_secret, mac_secret_length); case NID_sha256: - return tls_cbc_digest_record_sha256( - md_out, md_out_size, header, data, data_size, - data_plus_mac_plus_padding_size, mac_secret, mac_secret_length); + return tls_cbc_digest_record_sha256( // + md_out, md_out_size, len_header, aadvecs, iovecs_without_trailer, + trailer, data_in_trailer_size, mac_secret, mac_secret_length); default: // EVP_tls_cbc_record_digest_supported should have been called first to diff --git a/Sources/CNIOBoringSSL/crypto/cms/cms.cc b/Sources/CNIOBoringSSL/crypto/cms/cms.cc new file mode 100644 index 00000000..6299b6cc --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/cms/cms.cc @@ -0,0 +1,178 @@ +// Copyright 2025 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 "../bytestring/internal.h" +#include "../internal.h" +#include "../mem_internal.h" +#include "../pkcs7/internal.h" + + +using namespace bssl; + +// TODO(davidben): Should we move the core PKCS#7 / CMS implementation into +// crypto/cms instead of crypto/pkcs7? CMS is getting new features while PKCS#7 +// is not. +OPENSSL_DECLARE_ERROR_REASON(CMS, CERTIFICATE_HAS_NO_KEYID) + +DECLARE_OPAQUE_STRUCT(CMS_SignerInfo_st, CMSSignerInfo) +DECLARE_OPAQUE_STRUCT(CMS_ContentInfo_st, CMSContentInfo) + +BSSL_NAMESPACE_BEGIN + +class CMSSignerInfo : public CMS_SignerInfo_st { + public: + UniquePtr signcert; + UniquePtr pkey; + const EVP_MD *md = nullptr; + bool use_key_id = false; +}; + +class CMSContentInfo : public CMS_ContentInfo_st { + public: + static constexpr bool kAllowUniquePtr = true; + bool has_signer_info = false; + CMSSignerInfo signer_info; + Array der; +}; + +BSSL_NAMESPACE_END + +CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, 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) { + OPENSSL_PUT_ERROR(CMS, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return nullptr; + } + + UniquePtr cms = MakeUnique(); + if (cms == nullptr) { + return nullptr; + } + + if (pkey != nullptr && + !CMS_add1_signer(cms.get(), signcert, pkey, /*md=*/nullptr, flags)) { + return nullptr; + } + + // We don't actually use streaming mode, but Linux passes `CMS_STREAM` to + // `CMS_sign` and OpenSSL interprets it as an alias for `CMS_PARTIAL` in this + // context. + if ((flags & (CMS_PARTIAL | CMS_STREAM)) == 0 && + !CMS_final(cms.get(), data, nullptr, flags)) { + return nullptr; + } + + return cms.release(); +} + +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, + uint32_t flags) { + auto *impl = FromOpaque(cms); + if ( // Already finalized. + !impl->der.empty() || + // We only support one signer. + impl->has_signer_info || + // We do not support embedding certificates in SignedData. + (flags & CMS_NOCERTS) == 0 || + // We do not support attributes in SignedData. + (flags & CMS_NOATTR) == 0) { + OPENSSL_PUT_ERROR(CMS, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return nullptr; + } + + if (signcert == nullptr || pkey == nullptr) { + OPENSSL_PUT_ERROR(CMS, ERR_R_PASSED_NULL_PARAMETER); + return nullptr; + } + + if (!X509_check_private_key(signcert, pkey)) { + OPENSSL_PUT_ERROR(CMS, CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE); + return nullptr; + } + + // Default to SHA-256. + if (md == nullptr) { + md = EVP_sha256(); + } + + // Save information for later. + impl->has_signer_info = true; + impl->signer_info.signcert = UpRef(signcert); + impl->signer_info.pkey = UpRef(pkey); + impl->signer_info.md = md; + impl->signer_info.use_key_id = (flags & CMS_USE_KEYID) != 0; + return &impl->signer_info; +} + +int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont, uint32_t flags) { + auto *impl = FromOpaque(cms); + if ( // Already finalized. + !impl->der.empty() || + // Require a SignerInfo. We do not support signature-less SignedDatas. + !impl->has_signer_info || + // We only support the straightforward passthrough mode, without S/MIME + // translations. + (flags & CMS_BINARY) == 0 || + // We do not support `dcont`. It is unclear what it does. + dcont != nullptr) { + OPENSSL_PUT_ERROR(CMS, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return 0; + } + + ScopedCBB cbb; + if (!CBB_init(cbb.get(), 2048) || + !pkcs7_add_external_signature(cbb.get(), impl->signer_info.signcert.get(), + impl->signer_info.pkey.get(), + impl->signer_info.md, data, + impl->signer_info.use_key_id) || + !CBBFinishArray(cbb.get(), &impl->der)) { + return 0; + } + + return 1; +} + +int i2d_CMS_bio(BIO *out, CMS_ContentInfo *cms) { + auto *impl = FromOpaque(cms); + if (impl->der.empty()) { + // Not yet finalized. + OPENSSL_PUT_ERROR(CMS, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return 0; + } + + return BIO_write_all(out, impl->der.data(), impl->der.size()); +} + +int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags) { + // We do not support streaming mode. + if ((flags & CMS_STREAM) != 0 || in != nullptr) { + OPENSSL_PUT_ERROR(CMS, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return 0; + } + + return i2d_CMS_bio(out, cms); +} diff --git a/Sources/CNIOBoringSSL/crypto/conf/conf.cc b/Sources/CNIOBoringSSL/crypto/conf/conf.cc index 85cc2072..31fe146a 100644 --- a/Sources/CNIOBoringSSL/crypto/conf/conf.cc +++ b/Sources/CNIOBoringSSL/crypto/conf/conf.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,19 +21,25 @@ #include #include #include -#include #include #include "../internal.h" +#include "../mem_internal.h" #include "internal.h" +using namespace bssl; + +BSSL_NAMESPACE_BEGIN + struct conf_section_st { char *name; // values contains non-owning pointers to the values in the section. STACK_OF(CONF_VALUE) *values; }; +BSSL_NAMESPACE_END + static const char kDefaultSectionName[] = "default"; static uint32_t conf_section_hash(const CONF_SECTION *s) { @@ -55,46 +66,44 @@ static int conf_value_cmp(const CONF_VALUE *a, const CONF_VALUE *b) { } CONF *NCONF_new(void *method) { - if (method != NULL) { - return NULL; + if (method != nullptr) { + return nullptr; } - CONF *conf = reinterpret_cast(OPENSSL_malloc(sizeof(CONF))); - if (conf == NULL) { - return NULL; + CONF *conf = New(); + if (conf == nullptr) { + return nullptr; } conf->sections = lh_CONF_SECTION_new(conf_section_hash, conf_section_cmp); conf->values = lh_CONF_VALUE_new(conf_value_hash, conf_value_cmp); - if (conf->sections == NULL || conf->values == NULL) { + if (conf->sections == nullptr || conf->values == nullptr) { NCONF_free(conf); - return NULL; + return nullptr; } return conf; } -CONF_VALUE *CONF_VALUE_new(void) { - return reinterpret_cast(OPENSSL_zalloc(sizeof(CONF_VALUE))); -} +CONF_VALUE *bssl::CONF_VALUE_new() { return New(); } static void value_free(CONF_VALUE *value) { - if (value == NULL) { + if (value == nullptr) { return; } OPENSSL_free(value->section); OPENSSL_free(value->name); OPENSSL_free(value->value); - OPENSSL_free(value); + Delete(value); } static void section_free(CONF_SECTION *section) { - if (section == NULL) { + if (section == nullptr) { return; } OPENSSL_free(section->name); sk_CONF_VALUE_free(section->values); - OPENSSL_free(section); + Delete(section); } static void value_free_arg(CONF_VALUE *value, void *arg) { value_free(value); } @@ -104,26 +113,25 @@ static void section_free_arg(CONF_SECTION *section, void *arg) { } void NCONF_free(CONF *conf) { - if (conf == NULL) { + if (conf == nullptr) { return; } - lh_CONF_SECTION_doall_arg(conf->sections, section_free_arg, NULL); + lh_CONF_SECTION_doall_arg(conf->sections, section_free_arg, nullptr); lh_CONF_SECTION_free(conf->sections); - lh_CONF_VALUE_doall_arg(conf->values, value_free_arg, NULL); + lh_CONF_VALUE_doall_arg(conf->values, value_free_arg, nullptr); lh_CONF_VALUE_free(conf->values); - OPENSSL_free(conf); + Delete(conf); } static CONF_SECTION *NCONF_new_section(const CONF *conf, const char *section) { - CONF_SECTION *s = - reinterpret_cast(OPENSSL_malloc(sizeof(CONF_SECTION))); + CONF_SECTION *s = New(); if (!s) { - return NULL; + return nullptr; } s->name = OPENSSL_strdup(section); s->values = sk_CONF_VALUE_new_null(); - if (s->name == NULL || s->values == NULL) { + if (s->name == nullptr || s->values == nullptr) { goto err; } @@ -136,7 +144,7 @@ static CONF_SECTION *NCONF_new_section(const CONF *conf, const char *section) { err: section_free(s); - return NULL; + return nullptr; } static int is_comment(char c) { return c == '#'; } @@ -146,7 +154,7 @@ static int is_quote(char c) { return c == '"' || c == '\'' || c == '`'; } static int is_esc(char c) { return c == '\\'; } static int is_conf_ws(char c) { - // This differs from |OPENSSL_isspace| in that CONF does not accept '\v' and + // This differs from `OPENSSL_isspace` in that CONF does not accept '\v' and // '\f' as whitespace. return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } @@ -165,7 +173,7 @@ static int str_copy(CONF *conf, char *section, char **pto, char *from) { BUF_MEM *buf; buf = BUF_MEM_new(); - if (buf == NULL) { + if (buf == nullptr) { return 0; } @@ -240,8 +248,8 @@ static CONF_SECTION *get_section(const CONF *conf, const char *section) { const STACK_OF(CONF_VALUE) *NCONF_get_section(const CONF *conf, const char *section) { const CONF_SECTION *section_obj = get_section(conf, section); - if (section_obj == NULL) { - return NULL; + if (section_obj == nullptr) { + return nullptr; } return section_obj->values; } @@ -250,7 +258,7 @@ const char *NCONF_get_string(const CONF *conf, const char *section, const char *name) { CONF_VALUE templ, *value; - if (section == NULL) { + if (section == nullptr) { section = kDefaultSectionName; } @@ -258,8 +266,8 @@ const char *NCONF_get_string(const CONF *conf, const char *section, templ.section = (char *)section; templ.name = (char *)name; value = lh_CONF_VALUE_retrieve(conf->values, &templ); - if (value == NULL) { - return NULL; + if (value == nullptr) { + return nullptr; } return value->value; } @@ -267,7 +275,7 @@ const char *NCONF_get_string(const CONF *conf, const char *section, static int add_string(const CONF *conf, CONF_SECTION *section, CONF_VALUE *value) { value->section = OPENSSL_strdup(section->name); - if (value->section == NULL) { + if (value->section == nullptr) { return 0; } @@ -277,12 +285,12 @@ static int add_string(const CONF *conf, CONF_SECTION *section, CONF_VALUE *old_value; if (!lh_CONF_VALUE_insert(conf->values, &old_value, value)) { - // Remove |value| from |section->values|, so we do not leave a dangling + // Remove `value` from `section->values`, so we do not leave a dangling // pointer. sk_CONF_VALUE_pop(section->values); return 0; } - if (old_value != NULL) { + if (old_value != nullptr) { (void)sk_CONF_VALUE_delete_ptr(section->values, old_value); value_free(old_value); } @@ -366,27 +374,27 @@ static void clear_comments(char *p) { int NCONF_load_bio(CONF *conf, BIO *in, long *out_error_line) { static const size_t CONFBUFSIZE = 512; int bufnum = 0, i, ii; - BUF_MEM *buff = NULL; + BUF_MEM *buff = nullptr; char *s, *p, *end; int again; long eline = 0; - CONF_VALUE *v = NULL; - CONF_SECTION *sv = NULL; - char *section = NULL, *buf; + CONF_VALUE *v = nullptr; + CONF_SECTION *sv = nullptr; + char *section = nullptr, *buf; char *start, *psection, *pname; - if ((buff = BUF_MEM_new()) == NULL) { + if ((buff = BUF_MEM_new()) == nullptr) { OPENSSL_PUT_ERROR(CONF, ERR_R_BUF_LIB); goto err; } section = OPENSSL_strdup(kDefaultSectionName); - if (section == NULL) { + if (section == nullptr) { goto err; } sv = NCONF_new_section(conf, section); - if (sv == NULL) { + if (sv == nullptr) { OPENSSL_PUT_ERROR(CONF, CONF_R_UNABLE_TO_CREATE_NEW_SECTION); goto err; } @@ -428,7 +436,7 @@ int NCONF_load_bio(CONF *conf, BIO *in, long *out_error_line) { // i is the number of bytes bufnum += i; - v = NULL; + v = nullptr; // check for line continuation if (bufnum >= 1) { // If we have bytes and the last char '\\' and @@ -468,20 +476,20 @@ int NCONF_load_bio(CONF *conf, BIO *in, long *out_error_line) { goto err; } *end = '\0'; - if (!str_copy(conf, NULL, §ion, start)) { + if (!str_copy(conf, nullptr, §ion, start)) { goto err; } - if ((sv = get_section(conf, section)) == NULL) { + if ((sv = get_section(conf, section)) == nullptr) { sv = NCONF_new_section(conf, section); } - if (sv == NULL) { + if (sv == nullptr) { OPENSSL_PUT_ERROR(CONF, CONF_R_UNABLE_TO_CREATE_NEW_SECTION); goto err; } continue; } else { pname = s; - psection = NULL; + psection = nullptr; end = eat_name(s); if ((end[0] == ':') && (end[1] == ':')) { *end = '\0'; @@ -511,11 +519,11 @@ int NCONF_load_bio(CONF *conf, BIO *in, long *out_error_line) { if (!(v = CONF_VALUE_new())) { goto err; } - if (psection == NULL) { + if (psection == nullptr) { psection = section; } v->name = OPENSSL_strdup(pname); - if (v->name == NULL) { + if (v->name == nullptr) { goto err; } if (!str_copy(conf, psection, &(v->value), start)) { @@ -524,10 +532,10 @@ int NCONF_load_bio(CONF *conf, BIO *in, long *out_error_line) { CONF_SECTION *tv; if (strcmp(psection, section) != 0) { - if ((tv = get_section(conf, psection)) == NULL) { + if ((tv = get_section(conf, psection)) == nullptr) { tv = NCONF_new_section(conf, psection); } - if (tv == NULL) { + if (tv == nullptr) { OPENSSL_PUT_ERROR(CONF, CONF_R_UNABLE_TO_CREATE_NEW_SECTION); goto err; } @@ -537,17 +545,17 @@ int NCONF_load_bio(CONF *conf, BIO *in, long *out_error_line) { if (add_string(conf, tv, v) == 0) { goto err; } - v = NULL; + v = nullptr; } } BUF_MEM_free(buff); - OPENSSL_free(section); + Delete(section); return 1; err: BUF_MEM_free(buff); - OPENSSL_free(section); - if (out_error_line != NULL) { + Delete(section); + if (out_error_line != nullptr) { *out_error_line = eline; } ERR_add_error_dataf("line %ld", eline); @@ -559,7 +567,7 @@ int NCONF_load(CONF *conf, const char *filename, long *out_error_line) { BIO *in = BIO_new_file(filename, "rb"); int ret; - if (in == NULL) { + if (in == nullptr) { OPENSSL_PUT_ERROR(CONF, ERR_R_SYS_LIB); return 0; } @@ -570,13 +578,14 @@ int NCONF_load(CONF *conf, const char *filename, long *out_error_line) { return ret; } -int CONF_parse_list(const char *list, char sep, int remove_whitespace, - int (*list_cb)(const char *elem, size_t len, void *usr), - void *arg) { +int bssl::CONF_parse_list(const char *list, char sep, int remove_whitespace, + int (*list_cb)(const char *elem, size_t len, + void *usr), + void *arg) { int ret; const char *lstart, *tmpend, *p; - if (list == NULL) { + if (list == nullptr) { OPENSSL_PUT_ERROR(CONF, CONF_R_LIST_CANNOT_BE_NULL); return 0; } @@ -590,7 +599,7 @@ int CONF_parse_list(const char *list, char sep, int remove_whitespace, } p = strchr(lstart, sep); if (p == lstart || !*lstart) { - ret = list_cb(NULL, 0, arg); + ret = list_cb(nullptr, 0, arg); } else { if (p) { tmpend = p - 1; @@ -607,7 +616,7 @@ int CONF_parse_list(const char *list, char sep, int remove_whitespace, if (ret <= 0) { return ret; } - if (p == NULL) { + if (p == nullptr) { return 1; } lstart = p + 1; @@ -619,8 +628,10 @@ int CONF_modules_load_file(const char *filename, const char *appname, return 1; } -void CONF_modules_free(void) {} +void CONF_modules_unload(int all) {} + +void CONF_modules_free() {} void OPENSSL_config(const char *config_name) {} -void OPENSSL_no_config(void) {} +void OPENSSL_no_config() {} diff --git a/Sources/CNIOBoringSSL/crypto/conf/internal.h b/Sources/CNIOBoringSSL/crypto/conf/internal.h index 7efaaaf7..c867905b 100644 --- a/Sources/CNIOBoringSSL/crypto/conf/internal.h +++ b/Sources/CNIOBoringSSL/crypto/conf/internal.h @@ -1,16 +1,16 @@ -/* Copyright 2015 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2015 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. #ifndef OPENSSL_HEADER_CRYPTO_CONF_INTERNAL_H #define OPENSSL_HEADER_CRYPTO_CONF_INTERNAL_H @@ -19,37 +19,36 @@ #include "../lhash/internal.h" -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN typedef struct conf_section_st CONF_SECTION; DEFINE_LHASH_OF(CONF_SECTION) DEFINE_LHASH_OF(CONF_VALUE) +BSSL_NAMESPACE_END + struct conf_st { LHASH_OF(CONF_VALUE) *values; LHASH_OF(CONF_SECTION) *sections; }; -// CONF_VALUE_new returns a freshly allocated and zeroed |CONF_VALUE|. -CONF_VALUE *CONF_VALUE_new(void); +BSSL_NAMESPACE_BEGIN -// CONF_parse_list takes a list separated by 'sep' and calls |list_cb| giving +// CONF_VALUE_new returns a freshly allocated and zeroed `CONF_VALUE`. +CONF_VALUE *CONF_VALUE_new(); + +// CONF_parse_list takes a list separated by 'sep' and calls `list_cb` giving // the start and length of each member, optionally stripping leading and // trailing whitespace. This can be used to parse comma separated lists for -// example. If |list_cb| returns <= 0, then the iteration is halted and that -// value is returned immediately. Otherwise it returns one. Note that |list_cb| +// example. If `list_cb` returns <= 0, then the iteration is halted and that +// value is returned immediately. Otherwise it returns one. Note that `list_cb` // may be called on an empty member. OPENSSL_EXPORT int CONF_parse_list( const char *list, char sep, int remove_whitespace, int (*list_cb)(const char *elem, size_t len, void *usr), void *arg); - -#if defined(__cplusplus) -} // extern C -#endif +BSSL_NAMESPACE_END #endif // OPENSSL_HEADER_CRYPTO_CONF_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/cpu_aarch64_apple.cc b/Sources/CNIOBoringSSL/crypto/cpu_aarch64_apple.cc index f5fcad69..c25b5ac0 100644 --- a/Sources/CNIOBoringSSL/crypto/cpu_aarch64_apple.cc +++ b/Sources/CNIOBoringSSL/crypto/cpu_aarch64_apple.cc @@ -1,16 +1,16 @@ -/* Copyright 2021 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2021 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 "internal.h" @@ -20,13 +20,13 @@ #include #include -#include +using namespace bssl; static int has_hw_feature(const char *name) { int value; size_t len = sizeof(value); - if (sysctlbyname(name, &value, &len, NULL, 0) != 0) { + if (sysctlbyname(name, &value, &len, nullptr, 0) != 0) { return 0; } if (len != sizeof(int)) { @@ -45,7 +45,7 @@ static int has_hw_feature(const char *name) { return value != 0; } -void OPENSSL_cpuid_setup(void) { +void bssl::OPENSSL_cpuid_setup() { // Apple ARM64 platforms have NEON and cryptography extensions available // statically, so we do not need to query them. In particular, there sometimes // are no sysctls corresponding to such features. See below. @@ -63,13 +63,14 @@ void OPENSSL_cpuid_setup(void) { // available in macOS 12. For compatibility with macOS 11, we also support // the old names. The old names don't have values for features like FEAT_AES, // so instead we detect them statically above. - // - // If querying new sysctls, update the Chromium sandbox definition. See - // https://crrev.com/c/4415225. if (has_hw_feature("hw.optional.arm.FEAT_SHA512") || has_hw_feature("hw.optional.armv8_2_sha512")) { OPENSSL_armcap_P |= ARMV8_SHA512; } + if (has_hw_feature("hw.optional.arm.FEAT_SHA3") || + has_hw_feature("hw.optional.armv8_2_sha3")) { + OPENSSL_armcap_P |= ARMV8_SHA3; + } } #endif // OPENSSL_AARCH64 && OPENSSL_APPLE && !OPENSSL_STATIC_ARMCAP diff --git a/Sources/CNIOBoringSSL/crypto/cpu_aarch64_fuchsia.cc b/Sources/CNIOBoringSSL/crypto/cpu_aarch64_fuchsia.cc index b9c30f9f..88db3b2d 100644 --- a/Sources/CNIOBoringSSL/crypto/cpu_aarch64_fuchsia.cc +++ b/Sources/CNIOBoringSSL/crypto/cpu_aarch64_fuchsia.cc @@ -1,16 +1,16 @@ -/* Copyright 2018 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2018 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 "internal.h" @@ -21,10 +21,10 @@ #include #include -#include +using namespace bssl; -void OPENSSL_cpuid_setup(void) { +void bssl::OPENSSL_cpuid_setup() { uint32_t hwcap; zx_status_t rc = zx_system_get_features(ZX_FEATURE_KIND_CPU, &hwcap); if (rc != ZX_OK || (hwcap & ZX_ARM64_FEATURE_ISA_ASIMD) == 0) { @@ -50,6 +50,9 @@ void OPENSSL_cpuid_setup(void) { if (hwcap & ZX_ARM64_FEATURE_ISA_SHA512) { OPENSSL_armcap_P |= ARMV8_SHA512; } + if (hwcap & ZX_ARM64_FEATURE_ISA_SHA3) { + OPENSSL_armcap_P |= ARMV8_SHA3; + } } #endif // OPENSSL_AARCH64 && OPENSSL_FUCHSIA && !OPENSSL_STATIC_ARMCAP diff --git a/Sources/CNIOBoringSSL/crypto/cpu_aarch64_linux.cc b/Sources/CNIOBoringSSL/crypto/cpu_aarch64_linux.cc index c7eebc62..527c7f03 100644 --- a/Sources/CNIOBoringSSL/crypto/cpu_aarch64_linux.cc +++ b/Sources/CNIOBoringSSL/crypto/cpu_aarch64_linux.cc @@ -1,16 +1,16 @@ -/* Copyright 2016 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2016 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 "internal.h" @@ -19,10 +19,10 @@ #include -#include +using namespace bssl; -void OPENSSL_cpuid_setup(void) { +void bssl::OPENSSL_cpuid_setup() { unsigned long hwcap = getauxval(AT_HWCAP); // See /usr/include/asm/hwcap.h on an aarch64 installation for the source of @@ -32,6 +32,7 @@ void OPENSSL_cpuid_setup(void) { static const unsigned long kPMULL = 1 << 4; static const unsigned long kSHA1 = 1 << 5; static const unsigned long kSHA256 = 1 << 6; + static const unsigned long kSHA3 = 1 << 17; static const unsigned long kSHA512 = 1 << 21; if ((hwcap & kNEON) == 0) { @@ -57,6 +58,9 @@ void OPENSSL_cpuid_setup(void) { if (hwcap & kSHA512) { OPENSSL_armcap_P |= ARMV8_SHA512; } + if (hwcap & kSHA3) { + OPENSSL_armcap_P |= ARMV8_SHA3; + } } #endif // OPENSSL_AARCH64 && OPENSSL_LINUX && !OPENSSL_STATIC_ARMCAP diff --git a/Sources/CNIOBoringSSL/crypto/cpu_aarch64_openbsd.cc b/Sources/CNIOBoringSSL/crypto/cpu_aarch64_openbsd.cc index 2a269271..f3192f94 100644 --- a/Sources/CNIOBoringSSL/crypto/cpu_aarch64_openbsd.cc +++ b/Sources/CNIOBoringSSL/crypto/cpu_aarch64_openbsd.cc @@ -1,16 +1,16 @@ -/* Copyright (c) 2022, Robert Nagy - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright (c) 2022, Robert Nagy +// +// 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 @@ -21,41 +21,25 @@ #include #include -#include - +#include "armv8_feature_parsing.h" #include "internal.h" -void OPENSSL_cpuid_setup(void) { +using namespace bssl; + +void bssl::OPENSSL_cpuid_setup() { int isar0_mib[] = {CTL_MACHDEP, CPU_ID_AA64ISAR0}; uint64_t cpu_id = 0; size_t len = sizeof(cpu_id); - if (sysctl(isar0_mib, 2, &cpu_id, &len, NULL, 0) < 0) { + if (sysctl(isar0_mib, 2, &cpu_id, &len, nullptr, 0) < 0) { return; } OPENSSL_armcap_P |= ARMV7_NEON; - if (ID_AA64ISAR0_AES(cpu_id) >= ID_AA64ISAR0_AES_BASE) { - OPENSSL_armcap_P |= ARMV8_AES; - } - - if (ID_AA64ISAR0_AES(cpu_id) >= ID_AA64ISAR0_AES_PMULL) { - OPENSSL_armcap_P |= ARMV8_PMULL; - } - - if (ID_AA64ISAR0_SHA1(cpu_id) >= ID_AA64ISAR0_SHA1_BASE) { - OPENSSL_armcap_P |= ARMV8_SHA1; - } - - if (ID_AA64ISAR0_SHA2(cpu_id) >= ID_AA64ISAR0_SHA2_BASE) { - OPENSSL_armcap_P |= ARMV8_SHA256; - } - - if (ID_AA64ISAR0_SHA2(cpu_id) >= ID_AA64ISAR0_SHA2_512) { - OPENSSL_armcap_P |= ARMV8_SHA512; - } + // Use the common parsing function to check other features. + OPENSSL_armcap_P |= armcap::ParseISAR0Flags(cpu_id); } #endif // OPENSSL_AARCH64 && OPENSSL_OPENBSD && !OPENSSL_STATIC_ARMCAP diff --git a/Sources/CNIOBoringSSL/crypto/cpu_aarch64_sysreg.cc b/Sources/CNIOBoringSSL/crypto/cpu_aarch64_sysreg.cc index 466850df..80fa0689 100644 --- a/Sources/CNIOBoringSSL/crypto/cpu_aarch64_sysreg.cc +++ b/Sources/CNIOBoringSSL/crypto/cpu_aarch64_sysreg.cc @@ -1,16 +1,18 @@ -/* Copyright 2023 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2023 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 "internal.h" @@ -21,16 +23,12 @@ (defined(ANDROID_BAREMETAL) || defined(OPENSSL_FREEBSD)) && \ !defined(OPENSSL_NO_ASM) -#include +#include "./armv8_feature_parsing.h" + +BSSL_NAMESPACE_BEGIN #define ID_AA64PFR0_EL1_ADVSIMD 5 -#define ID_AA64ISAR0_EL1_AES 1 -#define ID_AA64ISAR0_EL1_SHA1 2 -#define ID_AA64ISAR0_EL1_SHA2 3 - -#define NBITS_ID_FIELD 4 - #define READ_SYSREG(name) \ ({ \ uint64_t _r; \ @@ -38,12 +36,10 @@ _r; \ }) -static unsigned get_id_field(uint64_t reg, unsigned field) { - return (reg >> (field * NBITS_ID_FIELD)) & ((1 << NBITS_ID_FIELD) - 1); -} - -static int get_signed_id_field(uint64_t reg, unsigned field) { - unsigned value = get_id_field(reg, field); +// We use the common GetIDField helper now, but need a signed variant +// for the NEON check using ID_AA64PFR0_EL1. +static int GetSignedIDField(uint64_t reg, unsigned field) { + unsigned value = armcap::GetIDField(reg, field); if (value & (1 << (NBITS_ID_FIELD - 1))) { return (int)(value | (UINT64_MAX << NBITS_ID_FIELD)); } else { @@ -51,44 +47,20 @@ static int get_signed_id_field(uint64_t reg, unsigned field) { } } -static uint32_t read_armcap(void) { - uint32_t armcap = ARMV7_NEON; - +void OPENSSL_cpuid_setup() { uint64_t id_aa64pfr0_el1 = READ_SYSREG("id_aa64pfr0_el1"); - - if (get_signed_id_field(id_aa64pfr0_el1, ID_AA64PFR0_EL1_ADVSIMD) < 0) { + if (GetSignedIDField(id_aa64pfr0_el1, ID_AA64PFR0_EL1_ADVSIMD) < 0) { // If AdvSIMD ("NEON") is missing, don't report other features either. // This matches OpenSSL. - return 0; + return; } + // Use the common parsing function to check all cryptographic features. uint64_t id_aa64isar0_el1 = READ_SYSREG("id_aa64isar0_el1"); - - unsigned aes = get_id_field(id_aa64isar0_el1, ID_AA64ISAR0_EL1_AES); - if (aes > 0) { - armcap |= ARMV8_AES; - } - if (aes > 1) { - armcap |= ARMV8_PMULL; - } - - unsigned sha1 = get_id_field(id_aa64isar0_el1, ID_AA64ISAR0_EL1_SHA1); - if (sha1 > 0) { - armcap |= ARMV8_SHA1; - } - - unsigned sha2 = get_id_field(id_aa64isar0_el1, ID_AA64ISAR0_EL1_SHA2); - if (sha2 > 0) { - armcap |= ARMV8_SHA256; - } - if (sha2 > 1) { - armcap |= ARMV8_SHA512; - } - - return armcap; + OPENSSL_armcap_P |= ARMV7_NEON | armcap::ParseISAR0Flags(id_aa64isar0_el1); } -void OPENSSL_cpuid_setup(void) { OPENSSL_armcap_P |= read_armcap(); } +BSSL_NAMESPACE_END #endif // OPENSSL_AARCH64 && !OPENSSL_STATIC_ARMCAP && // (ANDROID_BAREMETAL || OPENSSL_FREEBSD) diff --git a/Sources/CNIOBoringSSL/crypto/cpu_aarch64_win.cc b/Sources/CNIOBoringSSL/crypto/cpu_aarch64_win.cc index 5f18fc7a..4d51bbda 100644 --- a/Sources/CNIOBoringSSL/crypto/cpu_aarch64_win.cc +++ b/Sources/CNIOBoringSSL/crypto/cpu_aarch64_win.cc @@ -1,17 +1,17 @@ -/* Copyright 2018 The BoringSSL Authors - * Copyright (c) 2020, Arm Ltd. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2018 The BoringSSL Authors +// Copyright (c) 2020, Arm Ltd. +// +// 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 "internal.h" @@ -20,10 +20,17 @@ #include -#include +#if !defined(PF_ARM_SHA3_INSTRUCTIONS_AVAILABLE) +#define PF_ARM_SHA3_INSTRUCTIONS_AVAILABLE 64 +#endif +#if !defined(PF_ARM_SHA512_INSTRUCTIONS_AVAILABLE) +#define PF_ARM_SHA512_INSTRUCTIONS_AVAILABLE 65 +#endif -void OPENSSL_cpuid_setup(void) { +using namespace bssl; + +void bssl::OPENSSL_cpuid_setup() { // We do not need to check for the presence of NEON, as Armv8-A always has it OPENSSL_armcap_P |= ARMV7_NEON; @@ -34,8 +41,12 @@ void OPENSSL_cpuid_setup(void) { OPENSSL_armcap_P |= ARMV8_SHA1; OPENSSL_armcap_P |= ARMV8_SHA256; } - // As of writing, Windows does not have a |PF_*| value for ARMv8.2 SHA-512 - // extensions. When it does, add it here. + if (IsProcessorFeaturePresent(PF_ARM_SHA512_INSTRUCTIONS_AVAILABLE)) { + OPENSSL_armcap_P |= ARMV8_SHA512; + } + if (IsProcessorFeaturePresent(PF_ARM_SHA3_INSTRUCTIONS_AVAILABLE)) { + OPENSSL_armcap_P |= ARMV8_SHA3; + } } #endif // OPENSSL_AARCH64 && OPENSSL_WINDOWS && !OPENSSL_STATIC_ARMCAP diff --git a/Sources/CNIOBoringSSL/crypto/cpu_arm_freebsd.cc b/Sources/CNIOBoringSSL/crypto/cpu_arm_freebsd.cc index 1ae99d0f..af10fd95 100644 --- a/Sources/CNIOBoringSSL/crypto/cpu_arm_freebsd.cc +++ b/Sources/CNIOBoringSSL/crypto/cpu_arm_freebsd.cc @@ -1,16 +1,16 @@ -/* Copyright 2022 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2022 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 "internal.h" @@ -19,14 +19,15 @@ #include #include -#include #include -void OPENSSL_cpuid_setup(void) { +using namespace bssl; + +void bssl::OPENSSL_cpuid_setup() { unsigned long hwcap = 0, hwcap2 = 0; - // |elf_aux_info| may fail, in which case |hwcap| and |hwcap2| will be + // `elf_aux_info` may fail, in which case `hwcap` and `hwcap2` will be // left at zero. The rest of this function will then gracefully report // the features are absent. elf_aux_info(AT_HWCAP, &hwcap, sizeof(hwcap)); diff --git a/Sources/CNIOBoringSSL/crypto/cpu_arm_linux.cc b/Sources/CNIOBoringSSL/crypto/cpu_arm_linux.cc index c107df77..a07337f1 100644 --- a/Sources/CNIOBoringSSL/crypto/cpu_arm_linux.cc +++ b/Sources/CNIOBoringSSL/crypto/cpu_arm_linux.cc @@ -1,16 +1,16 @@ -/* Copyright 2016 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2016 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 "internal.h" @@ -22,11 +22,14 @@ #include #include -#include +#include + #include #include "cpu_arm_linux.h" +using namespace bssl; + static int open_eintr(const char *path, int flags) { int ret; do { @@ -43,8 +46,8 @@ static ssize_t read_eintr(int fd, void *out, size_t len) { return ret; } -// read_file opens |path| and reads until end-of-file. On success, it returns -// one and sets |*out_ptr| and |*out_len| to a newly-allocated buffer with the +// read_file opens `path` and reads until end-of-file. On success, it returns +// one and sets `*out_ptr` and `*out_len` to a newly-allocated buffer with the // contents. Otherwise, it returns zero. static int read_file(char **out_ptr, size_t *out_len, const char *path) { int fd = open_eintr(path, O_RDONLY); @@ -56,7 +59,7 @@ static int read_file(char **out_ptr, size_t *out_len, const char *path) { int ret = 0; size_t cap = kReadSize, len = 0; char *buf = reinterpret_cast(OPENSSL_malloc(cap)); - if (buf == NULL) { + if (buf == nullptr) { goto err; } @@ -67,7 +70,7 @@ static int read_file(char **out_ptr, size_t *out_len, const char *path) { goto err; } char *new_buf = reinterpret_cast(OPENSSL_realloc(buf, new_cap)); - if (new_buf == NULL) { + if (new_buf == nullptr) { goto err; } buf = new_buf; @@ -87,7 +90,7 @@ static int read_file(char **out_ptr, size_t *out_len, const char *path) { *out_ptr = buf; *out_len = len; ret = 1; - buf = NULL; + buf = nullptr; err: OPENSSL_free(buf); @@ -97,53 +100,72 @@ err: static int g_needs_hwcap2_workaround; -void OPENSSL_cpuid_setup(void) { - // We ignore the return value of |read_file| and proceed with an empty - // /proc/cpuinfo on error. If |getauxval| works, we will still detect - // capabilities. - char *cpuinfo_data = NULL; - size_t cpuinfo_len = 0; - read_file(&cpuinfo_data, &cpuinfo_len, "/proc/cpuinfo"); - STRING_PIECE cpuinfo; - cpuinfo.data = cpuinfo_data; - cpuinfo.len = cpuinfo_len; - +void bssl::OPENSSL_cpuid_setup() { // Matching OpenSSL, only report other features if NEON is present. unsigned long hwcap = getauxval(AT_HWCAP); - if (hwcap & HWCAP_NEON) { + if (hwcap & CRYPTO_HWCAP_NEON) { +#if defined(HWCAP_ARM_NEON) + static_assert(HWCAP_ARM_NEON == CRYPTO_HWCAP_NEON, + "CRYPTO_HWCAP values must match Linux"); +#endif OPENSSL_armcap_P |= ARMV7_NEON; // Some ARMv8 Android devices don't expose AT_HWCAP2. Fall back to - // /proc/cpuinfo. See https://crbug.com/boringssl/46. As of February 2021, - // this is now rare (see Chrome's Net.NeedsHWCAP2Workaround metric), but AES - // and PMULL extensions are very useful, so we still carry the workaround - // for now. + // /proc/cpuinfo. See https://crbug.com/40644934. The fix was added to + // Android CTS in N, so, after Net.NeedsHWCAP2Workaround confirms this, we + // should be able to disable this when __ANDROID_MIN_SDK_VERSION__ is high + // enough. (It may not be worth carrying the workaround at all at that + // point. Then again, AES and PMULL extensions are crucial for performance + // when available.) unsigned long hwcap2 = getauxval(AT_HWCAP2); if (hwcap2 == 0) { - hwcap2 = crypto_get_arm_hwcap2_from_cpuinfo(&cpuinfo); - g_needs_hwcap2_workaround = hwcap2 != 0; + char *cpuinfo_data = nullptr; + size_t cpuinfo_len = 0; + if (read_file(&cpuinfo_data, &cpuinfo_len, "/proc/cpuinfo")) { + hwcap2 = armcap::GetHWCAP2FromCpuinfo( + std::string_view(cpuinfo_data, cpuinfo_len)); + g_needs_hwcap2_workaround = hwcap2 != 0; + OPENSSL_free(cpuinfo_data); + } } - if (hwcap2 & HWCAP2_AES) { + // HWCAP2_* values, without the "CRYPTO_" prefix, are exposed through + // in some versions of glibc(>= 2.41). Assert that we don't + // diverge from those values. + if (hwcap2 & CRYPTO_HWCAP2_AES) { +#if defined(HWCAP2_AES) + static_assert(HWCAP2_AES == CRYPTO_HWCAP2_AES, + "CRYPTO_HWCAP2 values must match Linux"); +#endif OPENSSL_armcap_P |= ARMV8_AES; } - if (hwcap2 & HWCAP2_PMULL) { + if (hwcap2 & CRYPTO_HWCAP2_PMULL) { +#if defined(HWCAP2_PMULL) + static_assert(HWCAP2_PMULL == CRYPTO_HWCAP2_PMULL, + "CRYPTO_HWCAP2 values must match Linux"); +#endif OPENSSL_armcap_P |= ARMV8_PMULL; } - if (hwcap2 & HWCAP2_SHA1) { + if (hwcap2 & CRYPTO_HWCAP2_SHA1) { +#if defined(HWCAP2_SHA1) + static_assert(HWCAP2_SHA1 == CRYPTO_HWCAP2_SHA1, + "CRYPTO_HWCAP2 values must match Linux"); +#endif OPENSSL_armcap_P |= ARMV8_SHA1; } - if (hwcap2 & HWCAP2_SHA2) { + if (hwcap2 & CRYPTO_HWCAP2_SHA2) { +#if defined(HWCAP2_SHA2) + static_assert(HWCAP2_SHA2 == CRYPTO_HWCAP2_SHA2, + "CRYPTO_HWCAP2 values must match Linux"); +#endif OPENSSL_armcap_P |= ARMV8_SHA256; } } - - OPENSSL_free(cpuinfo_data); } -int CRYPTO_has_broken_NEON(void) { return 0; } +int CRYPTO_has_broken_NEON() { return 0; } -int CRYPTO_needs_hwcap2_workaround(void) { +int CRYPTO_needs_hwcap2_workaround() { OPENSSL_init_cpuid(); return g_needs_hwcap2_workaround; } diff --git a/Sources/CNIOBoringSSL/crypto/cpu_arm_linux.h b/Sources/CNIOBoringSSL/crypto/cpu_arm_linux.h index c5943583..4bccf700 100644 --- a/Sources/CNIOBoringSSL/crypto/cpu_arm_linux.h +++ b/Sources/CNIOBoringSSL/crypto/cpu_arm_linux.h @@ -1,163 +1,141 @@ -/* Copyright 2018 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2018 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. #ifndef OPENSSL_HEADER_CRYPTO_CPU_ARM_LINUX_H #define OPENSSL_HEADER_CRYPTO_CPU_ARM_LINUX_H #include -#include +#include + +#include #include "internal.h" -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN +namespace armcap { // The cpuinfo parser lives in a header file so it may be accessible from // cross-platform fuzzers without adding code to those platforms normally. -#define HWCAP_NEON (1 << 12) +#define CRYPTO_HWCAP_NEON (1 << 12) // See /usr/include/asm/hwcap.h on an ARM installation for the source of // these values. -#define HWCAP2_AES (1 << 0) -#define HWCAP2_PMULL (1 << 1) -#define HWCAP2_SHA1 (1 << 2) -#define HWCAP2_SHA2 (1 << 3) +// We add the prefix "CRYPTO_" to the definitions so as not to collide with +// some versions of glibc (>= 2.41) that expose them through . +#define CRYPTO_HWCAP2_AES (1 << 0) +#define CRYPTO_HWCAP2_PMULL (1 << 1) +#define CRYPTO_HWCAP2_SHA1 (1 << 2) +#define CRYPTO_HWCAP2_SHA2 (1 << 3) -typedef struct { - const char *data; - size_t len; -} STRING_PIECE; - -static int STRING_PIECE_equals(const STRING_PIECE *a, const char *b) { - size_t b_len = strlen(b); - return a->len == b_len && OPENSSL_memcmp(a->data, b, b_len) == 0; +// SplitStringView finds the first occurrence of `sep` in `in` and, if found, +// sets `*out_left` and `*out_right` to `in` split before and after `sep`, and +// returns true. If not found, it returns false. +inline bool SplitStringView(std::string_view *out_left, + std::string_view *out_right, std::string_view in, + char sep) { + auto pos = in.find(sep); + if (pos == std::string_view::npos) { + return false; + } + *out_left = in.substr(0, pos); + *out_right = in.substr(pos + 1); + return true; } -// STRING_PIECE_split finds the first occurence of |sep| in |in| and, if found, -// sets |*out_left| and |*out_right| to |in| split before and after it. It -// returns one if |sep| was found and zero otherwise. -static int STRING_PIECE_split(STRING_PIECE *out_left, STRING_PIECE *out_right, - const STRING_PIECE *in, char sep) { - const char *p = (const char *)OPENSSL_memchr(in->data, sep, in->len); - if (p == NULL) { - return 0; +// GetDelimited reads a `sep`-delimited entry from `s`, writing it to `out` and +// updating `s` to point beyond it. It returns true on success and false if `s` +// is empty. If `s` has no copies of `sep` and is non-empty, it reads the entire +// string to `out`. +inline bool GetDelimited(std::string_view *s, std::string_view *out, char sep) { + if (s->empty()) { + return false; } - // |out_left| or |out_right| may alias |in|, so make a copy. - STRING_PIECE in_copy = *in; - out_left->data = in_copy.data; - out_left->len = p - in_copy.data; - out_right->data = in_copy.data + out_left->len + 1; - out_right->len = in_copy.len - out_left->len - 1; - return 1; -} - -// STRING_PIECE_get_delimited reads a |sep|-delimited entry from |s|, writing it -// to |out| and updating |s| to point beyond it. It returns one on success and -// zero if |s| is empty. If |s| is has no copies of |sep| and is non-empty, it -// reads the entire string to |out|. -static int STRING_PIECE_get_delimited(STRING_PIECE *s, STRING_PIECE *out, char sep) { - if (s->len == 0) { - return 0; - } - if (!STRING_PIECE_split(out, s, s, sep)) { - // |s| had no instances of |sep|. Return the entire string. + if (!SplitStringView(out, s, *s, sep)) { + // `s` had no instances of `sep`. Return the entire string. *out = *s; - s->data += s->len; - s->len = 0; + *s = std::string_view(); } - return 1; + return true; } -// STRING_PIECE_trim removes leading and trailing whitespace from |s|. -static void STRING_PIECE_trim(STRING_PIECE *s) { - while (s->len != 0 && (s->data[0] == ' ' || s->data[0] == '\t')) { - s->data++; - s->len--; - } - while (s->len != 0 && - (s->data[s->len - 1] == ' ' || s->data[s->len - 1] == '\t')) { - s->len--; +// TrimStringView removes leading and trailing whitespace from `s`. +inline std::string_view TrimStringView(std::string_view s) { + size_t pos = s.find_first_not_of(" \t"); + if (pos == std::string_view::npos) { + return {}; } + s = s.substr(pos); + pos = s.find_last_not_of(" \t"); + assert(pos != std::string_view::npos); + return s.substr(0, pos + 1); } -// extract_cpuinfo_field extracts a /proc/cpuinfo field named |field| from -// |in|. If found, it sets |*out| to the value and returns one. Otherwise, it -// returns zero. -static int extract_cpuinfo_field(STRING_PIECE *out, const STRING_PIECE *in, - const char *field) { - // Process |in| one line at a time. - STRING_PIECE remaining = *in, line; - while (STRING_PIECE_get_delimited(&remaining, &line, '\n')) { - STRING_PIECE key, value; - if (!STRING_PIECE_split(&key, &value, &line, ':')) { +// ExtractCpuinfoField extracts a /proc/cpuinfo field named `field` from `in`. +// If found, it returns the value. Otherwise, it returns the empty string. +inline std::string_view ExtractCpuinfoField(std::string_view in, + std::string_view field) { + // Process `in` one line at a time. + std::string_view line; + while (GetDelimited(&in, &line, '\n')) { + std::string_view key, value; + if (!SplitStringView(&key, &value, line, ':')) { continue; } - STRING_PIECE_trim(&key); - if (STRING_PIECE_equals(&key, field)) { - STRING_PIECE_trim(&value); - *out = value; - return 1; + if (TrimStringView(key) == field) { + return TrimStringView(value); } } - return 0; + return {}; } -// has_list_item treats |list| as a space-separated list of items and returns -// one if |item| is contained in |list| and zero otherwise. -static int has_list_item(const STRING_PIECE *list, const char *item) { - STRING_PIECE remaining = *list, feature; - while (STRING_PIECE_get_delimited(&remaining, &feature, ' ')) { - if (STRING_PIECE_equals(&feature, item)) { - return 1; +// HasListItem treats `list` as a space-separated list of items and returns +// whether `item` is contained in `list`. +inline bool HasListItem(std::string_view list, std::string_view item) { + std::string_view feature; + while (GetDelimited(&list, &feature, ' ')) { + if (feature == item) { + return true; } } - return 0; + return false; } -// crypto_get_arm_hwcap2_from_cpuinfo returns an equivalent ARM |AT_HWCAP2| -// value from |cpuinfo|. -static unsigned long crypto_get_arm_hwcap2_from_cpuinfo( - const STRING_PIECE *cpuinfo) { - STRING_PIECE features; - if (!extract_cpuinfo_field(&features, cpuinfo, "Features")) { - return 0; - } - +// GetHWCAP2FromCpuinfo returns an equivalent ARM `AT_HWCAP2` value from +// `cpuinfo`. +inline unsigned long GetHWCAP2FromCpuinfo(std::string_view cpuinfo) { + std::string_view features = ExtractCpuinfoField(cpuinfo, "Features"); unsigned long ret = 0; - if (has_list_item(&features, "aes")) { - ret |= HWCAP2_AES; + if (HasListItem(features, "aes")) { + ret |= CRYPTO_HWCAP2_AES; } - if (has_list_item(&features, "pmull")) { - ret |= HWCAP2_PMULL; + if (HasListItem(features, "pmull")) { + ret |= CRYPTO_HWCAP2_PMULL; } - if (has_list_item(&features, "sha1")) { - ret |= HWCAP2_SHA1; + if (HasListItem(features, "sha1")) { + ret |= CRYPTO_HWCAP2_SHA1; } - if (has_list_item(&features, "sha2")) { - ret |= HWCAP2_SHA2; + if (HasListItem(features, "sha2")) { + ret |= CRYPTO_HWCAP2_SHA2; } return ret; } - -#if defined(__cplusplus) -} // extern C -#endif +} // namespace armcap +BSSL_NAMESPACE_END #endif // OPENSSL_HEADER_CRYPTO_CPU_ARM_LINUX_H diff --git a/Sources/CNIOBoringSSL/crypto/cpu_intel.cc b/Sources/CNIOBoringSSL/crypto/cpu_intel.cc index 7d0c6b88..f08348e6 100644 --- a/Sources/CNIOBoringSSL/crypto/cpu_intel.cc +++ b/Sources/CNIOBoringSSL/crypto/cpu_intel.cc @@ -1,35 +1,41 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 #if !defined(OPENSSL_NO_ASM) && \ (defined(OPENSSL_X86) || defined(OPENSSL_X86_64)) +#include #include -#include +#include #include #include #if defined(_MSC_VER) -OPENSSL_MSVC_PRAGMA(warning(push, 3)) #include #include -OPENSSL_MSVC_PRAGMA(warning(pop)) #endif #include "internal.h" -// OPENSSL_cpuid runs the cpuid instruction. |leaf| is passed in as EAX and ECX -// is set to zero. It writes EAX, EBX, ECX, and EDX to |*out_eax| through -// |*out_edx|. +using namespace bssl; + +// OPENSSL_cpuid runs the cpuid instruction. `leaf` is passed in as EAX and ECX +// is set to zero. It writes EAX, EBX, ECX, and EDX to `*out_eax` through +// `*out_edx`. static void OPENSSL_cpuid(uint32_t *out_eax, uint32_t *out_ebx, uint32_t *out_ecx, uint32_t *out_edx, uint32_t leaf) { #if defined(_MSC_VER) @@ -59,7 +65,7 @@ static void OPENSSL_cpuid(uint32_t *out_eax, uint32_t *out_ebx, } // OPENSSL_xgetbv returns the value of an Intel Extended Control Register (XCR). -// Currently only XCR0 is defined by Intel so |xcr| should always be zero. +// Currently only XCR0 is defined by Intel so `xcr` should always be zero. static uint64_t OPENSSL_xgetbv(uint32_t xcr) { #if defined(_MSC_VER) return (uint64_t)_xgetbv(xcr); @@ -86,23 +92,26 @@ static bool os_supports_avx512(uint64_t xcr0) { #endif } -// handle_cpu_env applies the value from |in| to the CPUID values in |out[0]| -// and |out[1]|. See the comment in |OPENSSL_cpuid_setup| about this. -static void handle_cpu_env(uint32_t *out, const char *in) { +// handle_cpu_env applies the value from `in` to the CPUID values in `out[0]` +// and `out[1]`. See the comment in `OPENSSL_cpuid_setup` about this. The +// `is_last` argument specifies whether the value is at the end of the string. +// Otherwise it may be followed by a colon. +static void handle_cpu_env(uint32_t out[2], const char *in, bool is_last) { const int invert_op = in[0] == '~'; const int or_op = in[0] == '|'; const int skip_first_byte = invert_op || or_op; const int hex = in[skip_first_byte] == '0' && in[skip_first_byte + 1] == 'x'; + const int base = hex ? 16 : 10; - int sscanf_result; - uint64_t v; - if (hex) { - sscanf_result = sscanf(in + invert_op + 2, "%" PRIx64, &v); - } else { - sscanf_result = sscanf(in + invert_op, "%" PRIu64, &v); - } + const char *start = in + skip_first_byte; + char *end; + errno = 0; + // We need to parse 64-bit values with `strtoull`. + static_assert(sizeof(unsigned long long) == sizeof(uint64_t)); + unsigned long long v = strtoull(start, &end, base); - if (!sscanf_result) { + if (end == start || (*end != '\0' && (is_last || *end != ':')) || + (v == ULLONG_MAX && errno == ERANGE)) { return; } @@ -118,18 +127,39 @@ static void handle_cpu_env(uint32_t *out, const char *in) { } } -void OPENSSL_cpuid_setup(void) { +void bssl::OPENSSL_adjust_ia32cap(uint32_t cap[4], const char *env) { + // OPENSSL_ia32cap can contain zero, one or two values, separated with a ':'. + // Each value is a 64-bit, unsigned value which may start with "0x" to + // indicate a hex value. Prior to the 64-bit value, a '~' or '|' may be given. + // + // If the '~' prefix is present: + // the value is inverted and ANDed with the probed CPUID result + // If the '|' prefix is present: + // the value is ORed with the probed CPUID result + // Otherwise: + // the value is taken as the result of the CPUID + // + // The first value determines OPENSSL_ia32cap_P[0] and [1]. The second [2] + // and [3]. + handle_cpu_env(cap, env, /*is_last=*/false); + env = strchr(env, ':'); + if (env != nullptr) { + handle_cpu_env(cap + 2, env + 1, /*is_last=*/true); + } +} + +void bssl::OPENSSL_cpuid_setup() { // Determine the vendor and maximum input value. uint32_t eax, ebx, ecx, edx; OPENSSL_cpuid(&eax, &ebx, &ecx, &edx, 0); uint32_t num_ids = eax; - int is_intel = ebx == 0x756e6547 /* Genu */ && // - edx == 0x49656e69 /* ineI */ && // + int is_intel = ebx == 0x756e6547 /* Genu */ && // + edx == 0x49656e69 /* ineI */ && // ecx == 0x6c65746e /* ntel */; - int is_amd = ebx == 0x68747541 /* Auth */ && // - edx == 0x69746e65 /* enti */ && // + int is_amd = ebx == 0x68747541 /* Auth */ && // + edx == 0x69746e65 /* enti */ && // ecx == 0x444d4163 /* cAMD */; uint32_t extended_features[2] = {0}; @@ -166,14 +196,6 @@ void OPENSSL_cpuid_setup(void) { } } - // Force the hyper-threading bit so that the more conservative path is always - // chosen. - edx |= 1u << 28; - - // Reserved bit #20 was historically repurposed to control the in-memory - // representation of RC4 state. Always set it to zero. - edx &= ~(1u << 20); - // Reserved bit #30 is repurposed to signal an Intel CPU. if (is_intel) { edx |= (1u << 30); @@ -181,10 +203,6 @@ void OPENSSL_cpuid_setup(void) { edx &= ~(1u << 30); } - // The SDBG bit is repurposed to denote AMD XOP support. Don't ever use AMD - // XOP code paths. - ecx &= ~(1u << 11); - uint64_t xcr0 = 0; if (ecx & (1u << 27)) { // XCR0 may only be queried if the OSXSAVE bit is set. @@ -214,10 +232,6 @@ void OPENSSL_cpuid_setup(void) { // 128-bit or 256-bit vectors, and also volume 2a section 2.7.11 ("#UD // Equations for EVEX") which says that all EVEX-coded instructions raise an // undefined-instruction exception if any of these XCR0 bits is zero. - // - // AVX10 fixes this by reorganizing the features that used to be part of - // "AVX512" and allowing them to be used independently of 512-bit support. - // TODO: add AVX10 detection. extended_features[0] &= ~(1u << 16); // AVX512F extended_features[0] &= ~(1u << 17); // AVX512DQ extended_features[0] &= ~(1u << 21); // AVX512IFMA @@ -264,30 +278,9 @@ void OPENSSL_cpuid_setup(void) { OPENSSL_ia32cap_P[2] = extended_features[0]; OPENSSL_ia32cap_P[3] = extended_features[1]; - const char *env1, *env2; - env1 = getenv("OPENSSL_ia32cap"); - if (env1 == NULL) { - return; - } - - // OPENSSL_ia32cap can contain zero, one or two values, separated with a ':'. - // Each value is a 64-bit, unsigned value which may start with "0x" to - // indicate a hex value. Prior to the 64-bit value, a '~' or '|' may be given. - // - // If the '~' prefix is present: - // the value is inverted and ANDed with the probed CPUID result - // If the '|' prefix is present: - // the value is ORed with the probed CPUID result - // Otherwise: - // the value is taken as the result of the CPUID - // - // The first value determines OPENSSL_ia32cap_P[0] and [1]. The second [2] - // and [3]. - - handle_cpu_env(&OPENSSL_ia32cap_P[0], env1); - env2 = strchr(env1, ':'); - if (env2 != NULL) { - handle_cpu_env(&OPENSSL_ia32cap_P[2], env2 + 1); + const char *env = getenv("OPENSSL_ia32cap"); + if (env != nullptr) { + OPENSSL_adjust_ia32cap(OPENSSL_ia32cap_P, env); } } diff --git a/Sources/CNIOBoringSSL/crypto/crypto.cc b/Sources/CNIOBoringSSL/crypto/crypto.cc index a582297e..b86f376b 100644 --- a/Sources/CNIOBoringSSL/crypto/crypto.cc +++ b/Sources/CNIOBoringSSL/crypto/crypto.cc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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 @@ -22,6 +22,8 @@ #include "internal.h" +using namespace bssl; + static_assert(sizeof(ossl_ssize_t) == sizeof(size_t), "ossl_ssize_t should be the same size as size_t"); @@ -54,77 +56,42 @@ static_assert(sizeof(ossl_ssize_t) == sizeof(size_t), // archive, linking on OS X will fail to resolve common symbols. By // initialising it to zero, it becomes a "data symbol", which isn't so // affected. -HIDDEN uint8_t BORINGSSL_function_hit[9] = {0}; +HIDDEN uint8_t bssl::BORINGSSL_function_hit[8] = {0}; #endif #if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) // This value must be explicitly initialized to zero. See similar comment above. -HIDDEN uint32_t OPENSSL_ia32cap_P[4] = {0}; +HIDDEN uint32_t bssl::OPENSSL_ia32cap_P[4] = {0}; -uint32_t OPENSSL_get_ia32cap(int idx) { +uint32_t bssl::OPENSSL_get_ia32cap(int idx) { OPENSSL_init_cpuid(); return OPENSSL_ia32cap_P[idx]; } -#elif defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64) +#elif (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) && \ + !defined(OPENSSL_STATIC_ARMCAP) +HIDDEN uint32_t bssl::OPENSSL_armcap_P = 0; -#include - -#if defined(OPENSSL_STATIC_ARMCAP) - -// See ARM ACLE for the definitions of these macros. Note |__ARM_FEATURE_AES| -// covers both AES and PMULL and |__ARM_FEATURE_SHA2| covers SHA-1 and SHA-256. -// https://developer.arm.com/architectures/system-architectures/software-standards/acle -// https://github.com/ARM-software/acle/issues/152 -// -// TODO(davidben): Do we still need |OPENSSL_STATIC_ARMCAP_*| or are the -// standard flags and -march sufficient? -HIDDEN uint32_t OPENSSL_armcap_P = -#if defined(OPENSSL_STATIC_ARMCAP_NEON) || defined(__ARM_NEON) - ARMV7_NEON | -#endif -#if defined(OPENSSL_STATIC_ARMCAP_AES) || defined(__ARM_FEATURE_AES) - ARMV8_AES | -#endif -#if defined(OPENSSL_STATIC_ARMCAP_PMULL) || defined(__ARM_FEATURE_AES) - ARMV8_PMULL | -#endif -#if defined(OPENSSL_STATIC_ARMCAP_SHA1) || defined(__ARM_FEATURE_SHA2) - ARMV8_SHA1 | -#endif -#if defined(OPENSSL_STATIC_ARMCAP_SHA256) || defined(__ARM_FEATURE_SHA2) - ARMV8_SHA256 | -#endif -#if defined(__ARM_FEATURE_SHA512) - ARMV8_SHA512 | -#endif - 0; - -#else -HIDDEN uint32_t OPENSSL_armcap_P = 0; - -uint32_t *OPENSSL_get_armcap_pointer_for_test(void) { +uint32_t *bssl::OPENSSL_get_armcap_pointer_for_test() { OPENSSL_init_cpuid(); return &OPENSSL_armcap_P; } -#endif -uint32_t OPENSSL_get_armcap(void) { +uint32_t bssl::OPENSSL_get_armcap() { OPENSSL_init_cpuid(); return OPENSSL_armcap_P; } - #endif #if defined(NEED_CPUID) -static CRYPTO_once_t once = CRYPTO_ONCE_INIT; -void OPENSSL_init_cpuid(void) { CRYPTO_once(&once, OPENSSL_cpuid_setup); } +static bssl::CRYPTO_once_t once = CRYPTO_ONCE_INIT; +void bssl::OPENSSL_init_cpuid() { CRYPTO_once(&once, OPENSSL_cpuid_setup); } #endif -void CRYPTO_library_init(void) {} +void CRYPTO_library_init() {} -int CRYPTO_is_confidential_build(void) { +int CRYPTO_is_confidential_build() { #if defined(BORINGSSL_CONFIDENTIAL) return 1; #else @@ -132,7 +99,7 @@ int CRYPTO_is_confidential_build(void) { #endif } -void CRYPTO_pre_sandbox_init(void) { +void CRYPTO_pre_sandbox_init() { // Read from /proc/cpuinfo if needed. OPENSSL_init_cpuid(); // Open /dev/urandom if needed. @@ -160,24 +127,26 @@ const char *OpenSSL_version(int which) { } } -unsigned long SSLeay(void) { return OPENSSL_VERSION_NUMBER; } +unsigned long SSLeay() { return OPENSSL_VERSION_NUMBER; } -unsigned long OpenSSL_version_num(void) { return OPENSSL_VERSION_NUMBER; } +unsigned long OpenSSL_version_num() { return OPENSSL_VERSION_NUMBER; } -int CRYPTO_malloc_init(void) { return 1; } +int CRYPTO_malloc_init() { return 1; } -int OPENSSL_malloc_init(void) { return 1; } +int OPENSSL_malloc_init() { return 1; } -void ENGINE_load_builtin_engines(void) {} +void ENGINE_load_builtin_engines() {} -int ENGINE_register_all_complete(void) { return 1; } +int ENGINE_register_all_complete() { return 1; } -void OPENSSL_load_builtin_modules(void) {} +void ENGINE_cleanup() {} + +void OPENSSL_load_builtin_modules() {} int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings) { return 1; } -void OPENSSL_cleanup(void) {} +void OPENSSL_cleanup() {} -FILE *CRYPTO_get_stderr(void) { return stderr; } +FILE *bssl::CRYPTO_get_stderr() { return stderr; } diff --git a/Sources/CNIOBoringSSL/crypto/curve25519/asm/x25519-asm-arm.S b/Sources/CNIOBoringSSL/crypto/curve25519/asm/x25519-asm-arm.S index 78a13e1f..650a75f6 100644 --- a/Sources/CNIOBoringSSL/crypto/curve25519/asm/x25519-asm-arm.S +++ b/Sources/CNIOBoringSSL/crypto/curve25519/asm/x25519-asm-arm.S @@ -1,22 +1,22 @@ #define BORINGSSL_PREFIX CNIOBoringSSL #if defined(__arm__) && defined(__linux__) -/* Copyright 2015 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2015 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. /* This file is taken from crypto_scalarmult/curve25519/neon2/scalarmult.s in * SUPERCOP 20141124 (http://bench.cr.yp.to/supercop.html). That code is public - * domain licensed but the standard ISC license is included above to keep + * domain licensed but the standard Apache 2.0 license is included above to keep * licensing simple. */ #include diff --git a/Sources/CNIOBoringSSL/crypto/curve25519/curve25519.cc b/Sources/CNIOBoringSSL/crypto/curve25519/curve25519.cc index f37d479e..edae66f9 100644 --- a/Sources/CNIOBoringSSL/crypto/curve25519/curve25519.cc +++ b/Sources/CNIOBoringSSL/crypto/curve25519/curve25519.cc @@ -1,16 +1,16 @@ -/* Copyright 2020 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2020 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. // Some of this code is taken from the ref10 version of Ed25519 in SUPERCOP // 20141124 (http://bench.cr.yp.to/supercop.html). That code is released as @@ -22,9 +22,10 @@ #include #include +#include #include #include -#include +#include #include "../internal.h" #include "internal.h" @@ -41,6 +42,8 @@ #endif +using namespace bssl; + // Low-level intrinsic operations static uint64_t load_3(const uint8_t *in) { @@ -68,7 +71,7 @@ static uint64_t load_4(const uint8_t *in) { typedef uint64_t fe_limb_t; #define FE_NUM_LIMBS 5 -// assert_fe asserts that |f| satisfies bounds: +// assert_fe asserts that `f` satisfies bounds: // // [[0x0 ~> 0x8cccccccccccc], // [0x0 ~> 0x8cccccccccccc], @@ -85,7 +88,7 @@ typedef uint64_t fe_limb_t; } \ } while (0) -// assert_fe_loose asserts that |f| satisfies bounds: +// assert_fe_loose asserts that `f` satisfies bounds: // // [[0x0 ~> 0x1a666666666664], // [0x0 ~> 0x1a666666666664], @@ -107,7 +110,7 @@ typedef uint64_t fe_limb_t; typedef uint32_t fe_limb_t; #define FE_NUM_LIMBS 10 -// assert_fe asserts that |f| satisfies bounds: +// assert_fe asserts that `f` satisfies bounds: // // [[0x0 ~> 0x4666666], [0x0 ~> 0x2333333], // [0x0 ~> 0x4666666], [0x0 ~> 0x2333333], @@ -125,7 +128,7 @@ typedef uint32_t fe_limb_t; } \ } while (0) -// assert_fe_loose asserts that |f| satisfies bounds: +// assert_fe_loose asserts that `f` satisfies bounds: // // [[0x0 ~> 0xd333332], [0x0 ~> 0x6999999], // [0x0 ~> 0xd333332], [0x0 ~> 0x6999999], @@ -149,12 +152,14 @@ 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]) { - // |fiat_25519_from_bytes| requires the top-most bit be clear. + // `fiat_25519_from_bytes` requires the top-most bit be clear. declassify_assert((s[31] & 0x80) == 0); fiat_25519_from_bytes(h->v, s); assert_fe(h->v); } +// 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]) { uint8_t s_copy[32]; OPENSSL_memcpy(s_copy, s, 32); @@ -284,7 +289,7 @@ static void fe_neg(fe_loose *h, const fe *f) { // // Preconditions: b in {0,1}. static 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 + // 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. // // TODO(davidben): Switch to fiat's calling convention, or ask fiat to emit a @@ -298,6 +303,19 @@ static void fe_cmov(fe_loose *f, const fe_loose *g, fe_limb_t b) { } } +// Replace (f,g) with (g,g) if b == 1; +// 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) { + b = 0 - b; + for (unsigned i = 0; i < FE_NUM_LIMBS; i++) { + fe_limb_t x = f->v[i] ^ g->v[i]; + x &= b; + f->v[i] ^= x; + } +} + // h = f static void fe_copy(fe *h, const fe *f) { OPENSSL_memmove(h, f, sizeof(fe)); } @@ -372,16 +390,22 @@ 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_loose *f) { - fe tight; - fe_carry(&tight, f); +static int fe_isnonzero(const fe *f) { uint8_t s[32]; - fe_tobytes(s, &tight); + fe_tobytes(s, f); static const uint8_t zero[32] = {0}; return CRYPTO_memcmp(s, zero, sizeof(zero)) != 0; } +// return 0 if f == 0 +// return 1 if f != 0 +static int fe_isnonzero(const fe_loose *f) { + fe tight; + fe_carry(&tight, f); + return fe_isnonzero(&tight); +} + // 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) { @@ -391,7 +415,7 @@ static int fe_isnegative(const fe *f) { } static void fe_sq2_tt(fe *h, const fe *f) { - // h = f^2 + // h = f² fe_sq_tt(h, f); // h = h + h @@ -460,7 +484,7 @@ static void fe_pow22523(fe *out, const fe *z) { // Group operations. -void x25519_ge_tobytes(uint8_t s[32], const ge_p2 *h) { +void bssl::x25519_ge_tobytes(uint8_t s[32], const ge_p2 *h) { fe recip; fe x; fe y; @@ -484,7 +508,7 @@ static void ge_p3_tobytes(uint8_t s[32], const ge_p3 *h) { s[31] ^= fe_isnegative(&x) << 7; } -int x25519_ge_frombytes_vartime(ge_p3 *h, const uint8_t s[32]) { +int bssl::x25519_ge_frombytes_vartime(ge_p3 *h, const uint8_t s[32]) { fe u; fe_loose v; fe w; @@ -495,9 +519,9 @@ int x25519_ge_frombytes_vartime(ge_p3 *h, const uint8_t s[32]) { fe_1(&h->Z); fe_sq_tt(&w, &h->Y); fe_mul_ttt(&vxx, &w, &d); - fe_sub(&v, &w, &h->Z); // u = y^2-1 + fe_sub(&v, &w, &h->Z); // u = y² - 1 fe_carry(&u, &v); - fe_add(&v, &vxx, &h->Z); // v = dy^2+1 + fe_add(&v, &vxx, &h->Z); // v = dy² + 1 fe_mul_ttl(&w, &u, &v); // w = u*v fe_pow22523(&h->X, &w); // x = w^((q-5)/8) @@ -558,7 +582,7 @@ static void ge_p3_to_p2(ge_p2 *r, const ge_p3 *p) { } // r = p -void x25519_ge_p3_to_cached(ge_cached *r, const ge_p3 *p) { +void bssl::x25519_ge_p3_to_cached(ge_cached *r, const ge_p3 *p) { fe_add(&r->YplusX, &p->Y, &p->X); fe_sub(&r->YminusX, &p->Y, &p->X); fe_copy_lt(&r->Z, &p->Z); @@ -566,14 +590,14 @@ void x25519_ge_p3_to_cached(ge_cached *r, const ge_p3 *p) { } // r = p -void x25519_ge_p1p1_to_p2(ge_p2 *r, const ge_p1p1 *p) { +void bssl::x25519_ge_p1p1_to_p2(ge_p2 *r, const ge_p1p1 *p) { fe_mul_tll(&r->X, &p->X, &p->T); fe_mul_tll(&r->Y, &p->Y, &p->Z); fe_mul_tll(&r->Z, &p->Z, &p->T); } // r = p -void x25519_ge_p1p1_to_p3(ge_p3 *r, const ge_p1p1 *p) { +void bssl::x25519_ge_p1p1_to_p3(ge_p3 *r, const ge_p1p1 *p) { fe_mul_tll(&r->X, &p->X, &p->T); fe_mul_tll(&r->Y, &p->Y, &p->Z); fe_mul_tll(&r->Z, &p->Z, &p->T); @@ -648,7 +672,7 @@ static void ge_msub(ge_p1p1 *r, const ge_p3 *p, const ge_precomp *q) { } // r = p + q -void x25519_ge_add(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) { +void bssl::x25519_ge_add(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) { fe trX, trY, trZ, trT; fe_add(&r->X, &p->Y, &p->X); @@ -666,7 +690,7 @@ void x25519_ge_add(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) { } // r = p - q -void x25519_ge_sub(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) { +void bssl::x25519_ge_sub(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) { fe trX, trY, trZ, trT; fe_add(&r->X, &p->Y, &p->X); @@ -689,16 +713,16 @@ static void cmov(ge_precomp *t, const ge_precomp *u, uint8_t b) { fe_cmov(&t->xy2d, &u->xy2d, b); } -void x25519_ge_scalarmult_small_precomp( +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| + // precomp_table is first expanded into matching `ge_precomp` // elements. ge_precomp multiples[15]; unsigned i; for (i = 0; i < 15; i++) { // The precomputed table is assumed to already clear the top bit, so - // |fe_frombytes_strict| may be used directly. + // `fe_frombytes_strict` may be used directly. const uint8_t *bytes = &precomp_table[i * (2 * 32)]; fe x, y; fe_frombytes_strict(&x, bytes); @@ -711,7 +735,7 @@ void x25519_ge_scalarmult_small_precomp( fe_mul_llt(&out->xy2d, &out->xy2d, &d2); } - // See the comment above |k25519SmallPrecomp| about the structure of the + // See the comment above `k25519SmallPrecomp` about the structure of the // precomputed elements. This loop does 64 additions and 64 doublings to // calculate the result. ge_p3_0(h); @@ -745,7 +769,7 @@ void x25519_ge_scalarmult_small_precomp( #if defined(OPENSSL_SMALL) -void x25519_ge_scalarmult_base(ge_p3 *h, const uint8_t a[32]) { +void bssl::x25519_ge_scalarmult_base(ge_p3 *h, const uint8_t a[32]) { x25519_ge_scalarmult_small_precomp(h, a, k25519SmallPrecomp); } @@ -762,7 +786,7 @@ static void table_select(ge_precomp *t, const int pos, const signed char b) { #if defined(__clang__) // materialize for vectorization, 6% speedup __asm__("" : "+m"(t_bytes) : /*no inputs*/); #endif - static_assert(sizeof(t_bytes) == sizeof(k25519Precomp[pos][0]), ""); + static_assert(sizeof(t_bytes) == sizeof(k25519Precomp[pos][0])); for (int i = 0; i < 8; i++) { constant_time_conditional_memxor(t_bytes, k25519Precomp[pos][i], sizeof(t_bytes), @@ -791,7 +815,7 @@ static void table_select(ge_precomp *t, const int pos, const signed char b) { // // Preconditions: // a[31] <= 127 -void x25519_ge_scalarmult_base(ge_p3 *h, const uint8_t a[32]) { +void bssl::x25519_ge_scalarmult_base(ge_p3 *h, const uint8_t a[32]) { #if defined(BORINGSSL_FE25519_ADX) if (CRYPTO_is_BMI1_capable() && CRYPTO_is_BMI2_capable() && CRYPTO_is_ADX_capable()) { @@ -862,7 +886,8 @@ static void cmov_cached(ge_cached *t, ge_cached *u, uint8_t b) { // r = scalar * A. // where a = a[0]+256*a[1]+...+256^31 a[31]. -void x25519_ge_scalarmult(ge_p2 *r, const uint8_t *scalar, const ge_p3 *A) { +void bssl::x25519_ge_scalarmult(ge_p2 *r, const uint8_t *scalar, + const ge_p3 *A) { ge_p2 Ai_p2[8]; ge_cached Ai[16]; ge_p1p1 t; @@ -1021,9 +1046,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 +// int64_lshift21 returns `a << 21` but is defined when shifting bits into the // sign bit. This works around a language flaw in C. -static inline int64_t int64_lshift21(int64_t a) { +static int64_t int64_lshift21(int64_t a) { return (int64_t)((uint64_t)a << 21); } @@ -1037,7 +1062,7 @@ static inline int64_t int64_lshift21(int64_t a) { // s[0]+256*s[1]+...+256^31*s[31] = s mod l // where l = 2^252 + 27742317777372353535851937790883648493. // Overwrites s in place. -void x25519_sc_reduce(uint8_t s[64]) { +void bssl::x25519_sc_reduce(uint8_t s[64]) { int64_t s0 = 2097151 & load_3(s); int64_t s1 = 2097151 & (load_4(s + 2) >> 5); int64_t s2 = 2097151 & (load_3(s + 5) >> 2); @@ -1865,13 +1890,9 @@ void ED25519_keypair(uint8_t out_public_key[32], uint8_t out_private_key[64]) { ED25519_keypair_from_seed(out_public_key, out_private_key, seed); } -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 - // allocation failure. While that can't happen with the current - // implementation, we want to reserve the ability to allocate in this - // implementation in the future. - +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]) { uint8_t az[SHA512_DIGEST_LENGTH]; SHA512(private_key, 32, az); @@ -1881,6 +1902,7 @@ int ED25519_sign(uint8_t out_sig[64], const uint8_t *message, SHA512_CTX hash_ctx; SHA512_Init(&hash_ctx); + SHA512_Update(&hash_ctx, hash_prefix, hash_prefix_len); SHA512_Update(&hash_ctx, az + 32, 32); SHA512_Update(&hash_ctx, message, message_len); uint8_t nonce[SHA512_DIGEST_LENGTH]; @@ -1892,6 +1914,7 @@ int ED25519_sign(uint8_t out_sig[64], const uint8_t *message, ge_p3_tobytes(out_sig, &R); SHA512_Init(&hash_ctx); + SHA512_Update(&hash_ctx, hash_prefix, hash_prefix_len); SHA512_Update(&hash_ctx, out_sig, 32); SHA512_Update(&hash_ctx, private_key + 32, 32); SHA512_Update(&hash_ctx, message, message_len); @@ -1906,8 +1929,10 @@ int ED25519_sign(uint8_t out_sig[64], const uint8_t *message, return 1; } -int ED25519_verify(const uint8_t *message, size_t message_len, - const uint8_t signature[64], const uint8_t public_key[32]) { +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]) { ge_p3 A; if ((signature[63] & 224) != 0 || !x25519_ge_frombytes_vartime(&A, public_key)) { @@ -1950,6 +1975,7 @@ int ED25519_verify(const uint8_t *message, size_t message_len, SHA512_CTX hash_ctx; SHA512_Init(&hash_ctx); + SHA512_Update(&hash_ctx, hash_prefix, hash_prefix_len); SHA512_Update(&hash_ctx, signature, 32); SHA512_Update(&hash_ctx, public_key, 32); SHA512_Update(&hash_ctx, message, message_len); @@ -1967,6 +1993,78 @@ int ED25519_verify(const uint8_t *message, size_t message_len, return CRYPTO_memcmp(rcheck, rcopy, sizeof(rcheck)) == 0; } +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 + // allocation failure. While that can't happen with the current + // implementation, we want to reserve the ability to allocate in this + // implementation in the future. + + return ed25519_sign(out_sig, nullptr, 0, message, message_len, private_key); +} + +int ED25519_verify(const uint8_t *message, size_t message_len, + const uint8_t signature[64], const uint8_t public_key[32]) { + return ed25519_verify(nullptr, 0, message, message_len, signature, + public_key); +} + +// ED25519_MAX_CONTEXT is the longest context permitted by RFC 8032. +#define ED25519_MAX_CONTEXT 255 +#define ED25519_MAX_HASH_PREFIX (32 + 1 + 1 + ED25519_MAX_CONTEXT) + +// 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) { + if (context_len > ED25519_MAX_CONTEXT) { + return 0; + } + + OPENSSL_memcpy(out_hash_prefix, "SigEd25519 no Ed25519 collisions", 32); + out_hash_prefix[32] = 1; + out_hash_prefix[33] = static_cast(context_len); + OPENSSL_memcpy(&out_hash_prefix[34], context, context_len); + *out_hash_prefix_len = 32 + 1 + 1 + context_len; + return 1; +} + +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], + const uint8_t private_key[64]) { + // NOTE: The documentation on this function says that it returns zero on + // allocation failure. While that can't happen with the current + // implementation, we want to reserve the ability to allocate in this + // implementation in the future. + + uint8_t hash_prefix[ED25519_MAX_HASH_PREFIX]; + size_t hash_prefix_len; + if (!ed25519_build_hash_prefix(hash_prefix, &hash_prefix_len, context, + context_len)) { + return 0; + } + + return ed25519_sign(out_sig, hash_prefix, hash_prefix_len, sha512_digest, + SHA512_DIGEST_LENGTH, private_key); +} + +int ED25519_verify_prehashed(const uint8_t *context, size_t context_len, + const uint8_t sha512_digest[SHA512_DIGEST_LENGTH], + const uint8_t signature[64], + const uint8_t public_key[32]) { + uint8_t hash_prefix[ED25519_MAX_HASH_PREFIX]; + size_t hash_prefix_len; + if (!ed25519_build_hash_prefix(hash_prefix, &hash_prefix_len, context, + context_len)) { + return 0; + } + + return ed25519_verify(hash_prefix, hash_prefix_len, sha512_digest, + SHA512_DIGEST_LENGTH, signature, public_key); +} + void ED25519_keypair_from_seed(uint8_t out_public_key[32], uint8_t out_private_key[64], const uint8_t seed[32]) { @@ -2152,3 +2250,187 @@ void X25519_public_from_private(uint8_t out_public_value[32], fe_tobytes(out_public_value, &zminusy_inv); CONSTTIME_DECLASSIFY(out_public_value, 32); } + +static void fe_from_limb(fe *h, fe_limb_t val) { + fe_0(h); + h->v[0] = val; + assert_fe(h->v); +} + +// map_to_curve_elligator2 implements the straight-line Elligator 2 mapping +// for Curve25519 from RFC 9380, Appendix G.2.1. +// +// 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) { + fe one, J_fe, c2_fe; + fe_1(&one); + fe_from_limb(&J_fe, 486662); + // c2 = 2^((p + 3) / 8) mod (2^255 - 19) in little-endian. + constexpr static uint8_t kC2[32] = { + 0xb1, 0xa0, 0x0e, 0x4a, 0x27, 0x1b, 0xee, 0xc4, 0x78, 0xe4, 0x2f, + 0xad, 0x06, 0x18, 0x43, 0x2f, 0xa7, 0xd7, 0xfb, 0x3d, 0x99, 0x00, + 0x4d, 0x2b, 0x0b, 0xdf, 0xc1, 0x4f, 0x80, 0x24, 0x83, 0x2b}; + fe_frombytes(&c2_fe, kC2); + + // 1-2. tv1 = 2 * u^2 + fe tv1; + fe_sq2_tt(&tv1, u); + + // 3. xd = tv1 + 1 + fe_loose xd_loose; + fe_add(&xd_loose, &tv1, &one); + + // 4. x1n = -J + fe_loose x1n_loose; + fe_neg(&x1n_loose, &J_fe); + + // 5. tv2 = xd^2 + fe tv2; + fe_sq_tl(&tv2, &xd_loose); + + // 6. gxd = xd^3 + fe gxd; + fe_mul_ttl(&gxd, &tv2, &xd_loose); + + fe gx1; + { + fe_loose l_tmp; + // 7. gx1 = J * tv1 + fe_mul_ltt(&l_tmp, &J_fe, &tv1); + // 8. gx1 = gx1 * x1n + fe_mul_tll(&gx1, &l_tmp, &x1n_loose); + // 9. gx1 = gx1 + tv2 + fe_add(&l_tmp, &gx1, &tv2); + // 10. gx1 = gx1 * x1n + fe_mul_tll(&gx1, &l_tmp, &x1n_loose); + } + + fe tv3; + // 11. tv3 = gxd^2 + fe_sq_tt(&tv3, &gxd); + // 12. tv2 = tv3^2 + fe_sq_tt(&tv2, &tv3); + // 13. tv3 = tv3 * gxd + fe_mul_ttt(&tv3, &tv3, &gxd); + // 14. tv3 = tv3 * gx1 + fe_mul_ttt(&tv3, &tv3, &gx1); + // 15. tv2 = tv2 * tv3 + fe_mul_ttt(&tv2, &tv2, &tv3); + + // 16. y11 = tv2^c4 = (gx1 * gxd^7)^((p - 5) / 8) + fe y11; + fe_pow22523(&y11, &tv2); + // 17. y11 = y11 * tv3 + fe_mul_ttt(&y11, &y11, &tv3); + + // 18. y12 = y11 * c3 + fe y12; + fe_mul_ttt(&y12, &y11, &sqrtm1); + + // 19. tv2 = y11 ^ 2 + fe_sq_tt(&tv2, &y11); + // 20. tv2 = tv2 * gxd + fe_mul_ttt(&tv2, &tv2, &gxd); + // 21. e1 = tv2 == gx1 + fe_limb_t e1; + { + fe_loose l_tmp; + fe_sub(&l_tmp, &tv2, &gx1); + e1 = 1 - fe_isnonzero(&l_tmp); + } + + // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt + fe y1; + fe_copy(&y1, &y12); + fe_cmov(&y1, &y11, e1); + + // 23. x2n = x1n * tv1 + fe x2n; + fe_mul_ttl(&x2n, &tv1, &x1n_loose); + + // 24. y21 = y11 * u + fe y21; + fe_mul_ttt(&y21, &y11, u); + // 25. y21 = y21 * c2 + fe_mul_ttt(&y21, &y21, &c2_fe); + + // 26. y22 = y21 * c3 + fe y22; + fe_mul_ttt(&y22, &y21, &sqrtm1); + + // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1) + fe gx2; + fe_mul_ttt(&gx2, &gx1, &tv1); + + // 28. tv2 = y21^2 + fe_sq_tt(&tv2, &y21); + // 29. tv2 = tv2 * gxd + fe_mul_ttt(&tv2, &tv2, &gxd); + // 30. e2 = tv2 == gx2 + fe_limb_t e2; + { + fe_loose l_tmp; + fe_sub(&l_tmp, &tv2, &gx2); + e2 = 1 - fe_isnonzero(&l_tmp); + } + + // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt + fe y2; + fe_copy(&y2, &y22); + fe_cmov(&y2, &y21, e2); + + // 32. tv2 = y1^2 + fe_sq_tt(&tv2, &y1); + // 33. tv2 = tv2 * gxd + fe_mul_ttt(&tv2, &tv2, &gxd); + // 34. e3 = tv2 == gx1 + fe_limb_t e3; + { + fe_loose l_tmp; + fe_sub(&l_tmp, &tv2, &gx1); + e3 = 1 - fe_isnonzero(&l_tmp); + } + + fe xn, y; + // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2 + // or xn = CMOV(x1n, x2n, 1 - e3) + fe_carry(&xn, &x1n_loose); + fe_cmov(&xn, &x2n, 1 - e3); + // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2 + fe_copy(&y, &y2); + fe_cmov(&y, &y1, e3); + + // 37. e4 = sgn0(y) == 1 # Fix sign of y + fe_limb_t e4 = fe_isnegative(&y); + fe negy; + { + fe_loose l_tmp; + fe_neg(&l_tmp, &y); + fe_carry(&negy, &l_tmp); + } + // 38. y = CMOV(y, -y, e3 XOR e4) + fe_cmov(&y, &negy, e3 ^ e4); + + // 39. return (xn, xd, y, /* 1 */) + fe_copy(out_xMn, &xn); + fe_carry(out_xMd, &xd_loose); + fe_copy(out_yMn, &y); +} + +void bssl::map_to_curve_curve25519_elligator2(uint8_t out_qx[32], + uint8_t out_qy[32], + const uint8_t u[32]) { + fe u_fe; + fe_frombytes(&u_fe, u); + + fe xMn, xMd, yMn; + map_to_curve_elligator2(&xMn, &xMd, &yMn, &u_fe); + + fe xMd_inv, qx; + fe_invert(&xMd_inv, &xMd); + fe_mul_ttt(&qx, &xMn, &xMd_inv); + fe_tobytes(out_qx, &qx); + fe_tobytes(out_qy, &yMn); +} diff --git a/Sources/CNIOBoringSSL/crypto/curve25519/curve25519_64_adx.cc b/Sources/CNIOBoringSSL/crypto/curve25519/curve25519_64_adx.cc index 63e50dc2..da270c22 100644 --- a/Sources/CNIOBoringSSL/crypto/curve25519/curve25519_64_adx.cc +++ b/Sources/CNIOBoringSSL/crypto/curve25519/curve25519_64_adx.cc @@ -1,16 +1,16 @@ -/* Copyright 2023 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2023 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 "internal.h" #if defined(BORINGSSL_FE25519_ADX) diff --git a/Sources/CNIOBoringSSL/crypto/curve25519/curve25519_tables.h b/Sources/CNIOBoringSSL/crypto/curve25519/curve25519_tables.h index f459ed33..0869238b 100644 --- a/Sources/CNIOBoringSSL/crypto/curve25519/curve25519_tables.h +++ b/Sources/CNIOBoringSSL/crypto/curve25519/curve25519_tables.h @@ -1,22 +1,22 @@ -/* Copyright 2020 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2020 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. // This file is generated from // ./make_curve25519_tables.py > curve25519_tables.h -static const fe d = {{ +static const bssl::fe d = {{ #if defined(OPENSSL_64_BIT) 929955233495203, 466365720129213, 1662059464998953, 2033849074728123, 1442794654840575 @@ -26,7 +26,7 @@ static const fe d = {{ #endif }}; -static const fe sqrtm1 = {{ +static const bssl::fe sqrtm1 = {{ #if defined(OPENSSL_64_BIT) 1718705420411056, 234908883556509, 2233514472574048, 2117202627021982, 765476049583133 @@ -36,7 +36,7 @@ static const fe sqrtm1 = {{ #endif }}; -static const fe d2 = {{ +static const bssl::fe d2 = {{ #if defined(OPENSSL_64_BIT) 1859910466990425, 932731440258426, 1072319116312658, 1815898335770999, 633789495995903 @@ -52,7 +52,7 @@ static const fe d2 = {{ // 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 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: // (i₀×2^192 + i₁×2^128 + i₂×2^64 + i₃)G, where G is the generator. @@ -142,7 +142,7 @@ static const uint8_t k25519SmallPrecomp[15 * 2 * 32] = { #else // k25519Precomp[i][j] = (j+1)*256^i*B -const uint8_t k25519Precomp[32][8][3][32] = { +const uint8_t bssl::k25519Precomp[32][8][3][32] = { { { {0x85, 0x3b, 0x8c, 0xf5, 0xc6, 0x93, 0xbc, 0x2f, 0x19, 0xe, 0x8c, @@ -3028,7 +3028,7 @@ const uint8_t k25519Precomp[32][8][3][32] = { #endif // OPENSSL_SMALL // Bi[i] = (2*i+1)*B -static const ge_precomp Bi[8] = { +static const bssl::ge_precomp Bi[8] = { { {{ #if defined(OPENSSL_64_BIT) diff --git a/Sources/CNIOBoringSSL/crypto/curve25519/internal.h b/Sources/CNIOBoringSSL/crypto/curve25519/internal.h index 8386757b..f0dab096 100644 --- a/Sources/CNIOBoringSSL/crypto/curve25519/internal.h +++ b/Sources/CNIOBoringSSL/crypto/curve25519/internal.h @@ -1,85 +1,91 @@ -/* Copyright 2020 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2020 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. -#ifndef OPENSSL_HEADER_CURVE25519_INTERNAL_H -#define OPENSSL_HEADER_CURVE25519_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_CURVE25519_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_CURVE25519_INTERNAL_H #include #include "../internal.h" -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN #if defined(OPENSSL_ARM) && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_APPLE) #define BORINGSSL_X25519_NEON // x25519_NEON is defined in asm/x25519-arm.S. -void x25519_NEON(uint8_t out[32], const uint8_t scalar[32], - const uint8_t point[32]); +extern "C" void x25519_NEON(uint8_t out[32], const uint8_t scalar[32], + const uint8_t point[32]); #endif #if !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_SMALL) && \ - defined(__GNUC__) && defined(__x86_64__) && !defined(OPENSSL_WINDOWS) + (defined(__APPLE__) || defined(__ELF__)) && defined(OPENSSL_X86_64) #define BORINGSSL_FE25519_ADX // fiat_curve25519_adx_mul is defined in // third_party/fiat/asm/fiat_curve25519_adx_mul.S -void __attribute__((sysv_abi)) -fiat_curve25519_adx_mul(uint64_t out[4], const uint64_t in1[4], - const uint64_t in2[4]); +extern "C" void __attribute__((sysv_abi)) fiat_curve25519_adx_mul( + uint64_t out[4], const uint64_t in1[4], const uint64_t in2[4]); // fiat_curve25519_adx_square is defined in // third_party/fiat/asm/fiat_curve25519_adx_square.S -void __attribute__((sysv_abi)) -fiat_curve25519_adx_square(uint64_t out[4], const uint64_t in[4]); +extern "C" void __attribute__((sysv_abi)) fiat_curve25519_adx_square( + uint64_t out[4], const uint64_t in[4]); // x25519_scalar_mult_adx is defined in third_party/fiat/curve25519_64_adx.h void x25519_scalar_mult_adx(uint8_t out[32], const uint8_t scalar[32], const uint8_t point[32]); void x25519_ge_scalarmult_base_adx(uint8_t h[4][32], const uint8_t a[32]); + #endif #if defined(OPENSSL_64_BIT) -// fe means field element. Here the field is \Z/(2^255-19). An element t, -// entries t[0]...t[4], represents the integer t[0]+2^51 t[1]+2^102 t[2]+2^153 -// t[3]+2^204 t[4]. +// fe means field element. Here the field is ℤ/(2^255-19). An element t, +// entries t[0]...t[4], represents the integer +// t[0] + 2^51 t[1] + 2^102 t[2] + 2^153 t[3] + 2^204 t[4]. // fe limbs are bounded by 1.125*2^51. // Multiplication and carrying produce fe from fe_loose. -typedef struct fe { uint64_t v[5]; } fe; +typedef struct fe { + uint64_t v[5]; +} fe; // fe_loose limbs are bounded by 3.375*2^51. // Addition and subtraction produce fe_loose from (fe, fe). -typedef struct fe_loose { uint64_t v[5]; } fe_loose; +typedef struct fe_loose { + uint64_t v[5]; +} fe_loose; #else -// fe means field element. Here the field is \Z/(2^255-19). An element t, -// entries t[0]...t[9], represents the integer t[0]+2^26 t[1]+2^51 t[2]+2^77 -// t[3]+2^102 t[4]+...+2^230 t[9]. +// fe means field element. Here the field is ℤ/(2^255-19). +// An element t, entries t[0]...t[9], represents the integer +// t[0] + 2^26 t[1] + 2^51 t[2] + 2^77 t[3] + 2^102 t[4] + ... + 2^230 t[9]. // fe limbs are bounded by 1.125*2^26,1.125*2^25,1.125*2^26,1.125*2^25,etc. // Multiplication and carrying produce fe from fe_loose. -typedef struct fe { uint32_t v[10]; } fe; +typedef struct fe { + uint32_t v[10]; +} fe; -// fe_loose limbs are bounded by 3.375*2^26,3.375*2^25,3.375*2^26,3.375*2^25,etc. -// Addition and subtraction produce fe_loose from (fe, fe). -typedef struct fe_loose { uint32_t v[10]; } fe_loose; +// fe_loose limbs are bounded by 3.375*2^26, 3.375*2^25, 3.375*2^26, 3.375*2^25, +// etc. Addition and subtraction produce fe_loose from (fe, fe). +typedef struct fe_loose { + uint32_t v[10]; +} fe_loose; #endif // ge means group element. // // Here the group is the set of pairs (x,y) of field elements (see fe.h) -// satisfying -x^2 + y^2 = 1 + d x^2y^2 +// satisfying -x² + y² = 1 + d x²y² // where d = -121665/121666. // // Representations: @@ -140,6 +146,11 @@ enum spake2_state_t { spake2_state_key_generated, }; +void map_to_curve_curve25519_elligator2(uint8_t out_qx[32], uint8_t out_qy[32], + const uint8_t u[32]); + +BSSL_NAMESPACE_END + struct spake2_ctx_st { uint8_t private_key[32]; uint8_t my_msg[32]; @@ -150,15 +161,14 @@ struct spake2_ctx_st { uint8_t *their_name; size_t their_name_len; enum spake2_role_t my_role; - enum spake2_state_t state; + enum bssl::spake2_state_t state; char disable_password_scalar_hack; }; +BSSL_NAMESPACE_BEGIN extern const uint8_t k25519Precomp[32][8][3][32]; -#if defined(__cplusplus) -} // extern C -#endif +BSSL_NAMESPACE_END -#endif // OPENSSL_HEADER_CURVE25519_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_CURVE25519_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/curve25519/spake25519.cc b/Sources/CNIOBoringSSL/crypto/curve25519/spake25519.cc index 2aeeca4c..bc556133 100644 --- a/Sources/CNIOBoringSSL/crypto/curve25519/spake25519.cc +++ b/Sources/CNIOBoringSSL/crypto/curve25519/spake25519.cc @@ -1,32 +1,37 @@ -/* Copyright 2016 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2016 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 "../fipsmodule/bn/internal.h" #include "../internal.h" +#include "../mem_internal.h" #include "./internal.h" +using namespace bssl; + // The following precomputation tables are for the following // points used in the SPAKE2 protocol. // @@ -276,10 +281,9 @@ static const uint8_t kSpakeMSmallPrecomp[15 * 2 * 32] = { 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 *ctx = - reinterpret_cast(OPENSSL_zalloc(sizeof(SPAKE2_CTX))); - if (ctx == NULL) { - return NULL; + SPAKE2_CTX *ctx = New(); + if (ctx == nullptr) { + return nullptr; } ctx->my_role = my_role; @@ -290,23 +294,23 @@ SPAKE2_CTX *SPAKE2_CTX_new(enum spake2_role_t my_role, const uint8_t *my_name, if (!CBS_stow(&my_name_cbs, &ctx->my_name, &ctx->my_name_len) || !CBS_stow(&their_name_cbs, &ctx->their_name, &ctx->their_name_len)) { SPAKE2_CTX_free(ctx); - return NULL; + return nullptr; } return ctx; } void SPAKE2_CTX_free(SPAKE2_CTX *ctx) { - if (ctx == NULL) { + if (ctx == nullptr) { return; } OPENSSL_free(ctx->my_name); OPENSSL_free(ctx->their_name); - OPENSSL_free(ctx); + Delete(ctx); } -// left_shift_3 sets |n| to |n|*8, where |n| is represented in little-endian +// 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]) { uint8_t carry = 0; @@ -330,21 +334,20 @@ static 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. +// scalar_cmov copies `src` to `dest` if `mask` is all ones. static void scalar_cmov(scalar *dest, const scalar *src, crypto_word_t mask) { bn_select_words(dest->words, mask, src->words, dest->words, - OPENSSL_ARRAY_SIZE(dest->words)); + std::size(dest->words)); } -// scalar_double sets |s| to |2×s|. +// scalar_double sets `s` to `2×s`. static void scalar_double(scalar *s) { - bn_add_words(s->words, s->words, s->words, OPENSSL_ARRAY_SIZE(s->words)); + bn_add_words(s->words, s->words, s->words, std::size(s->words)); } -// scalar_add sets |dest| to |dest| plus |src|. +// scalar_add sets `dest` to `dest` plus `src`. static void scalar_add(scalar *dest, const scalar *src) { - bn_add_words(dest->words, dest->words, src->words, - OPENSSL_ARRAY_SIZE(dest->words)); + bn_add_words(dest->words, dest->words, src->words, std::size(dest->words)); } int SPAKE2_generate_msg(SPAKE2_CTX *ctx, uint8_t *out, size_t *out_len, @@ -375,8 +378,8 @@ int SPAKE2_generate_msg(SPAKE2_CTX *ctx, uint8_t *out, size_t *out_len, OPENSSL_memcpy(ctx->password_hash, password_tmp, sizeof(ctx->password_hash)); x25519_sc_reduce(password_tmp); - // Due to a copy-paste error, the call to |left_shift_3| was omitted after - // the |x25519_sc_reduce|, just above. This meant that |ctx->password_scalar| + // Due to a copy-paste error, the call to `left_shift_3` was omitted after + // the `x25519_sc_reduce`, just above. This meant that `ctx->password_scalar` // was not a multiple of eight to clear the cofactor and thus three bits of // the password hash would leak. In order to fix this in a unilateral way, // points of small order are added to the mask point such that it is in the @@ -392,8 +395,8 @@ int SPAKE2_generate_msg(SPAKE2_CTX *ctx, uint8_t *out, size_t *out_len, scalar password_scalar; OPENSSL_memcpy(&password_scalar, password_tmp, sizeof(password_scalar)); - // |password_scalar| is the result of |x25519_sc_reduce| and thus is, at - // most, $l-1$ (where $l$ is |kOrder|, the order of the prime-order subgroup + // `password_scalar` is the result of `x25519_sc_reduce` and thus is, at + // most, $l-1$ (where $l$ is `kOrder`, the order of the prime-order subgroup // of Ed25519). In the following, we may add $l + 2×l + 4×l$ for a max value // of $8×l-1$. That is < 2**256, as required. diff --git a/Sources/CNIOBoringSSL/crypto/des/des.cc b/Sources/CNIOBoringSSL/crypto/des/des.cc index ddaf48e5..d99dfe11 100644 --- a/Sources/CNIOBoringSSL/crypto/des/des.cc +++ b/Sources/CNIOBoringSSL/crypto/des/des.cc @@ -1,19 +1,27 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "internal.h" +using namespace bssl; + /* IP and FP * The problem is more of a geometric problem that random bit fiddling. 0 1 2 3 4 5 6 7 62 54 46 38 30 22 14 6 @@ -335,7 +343,7 @@ void DES_set_key(const DES_cblock *key, DES_key_schedule *schedule) { DES_set_key_ex(key->bytes, schedule); } -void DES_set_key_ex(const uint8_t key[8], DES_key_schedule *schedule) { +void bssl::DES_set_key_ex(const uint8_t key[8], DES_key_schedule *schedule) { static const int shifts2[16] = {0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0}; uint32_t c, d, t, s, t2; @@ -543,8 +551,9 @@ static void DES_encrypt2(uint32_t data[2], const DES_key_schedule *ks, data[1] = CRYPTO_rotr_u32(r, 3); } -void DES_encrypt3(uint32_t data[2], const DES_key_schedule *ks1, - const DES_key_schedule *ks2, const DES_key_schedule *ks3) { +void bssl::DES_encrypt3(uint32_t data[2], const DES_key_schedule *ks1, + const DES_key_schedule *ks2, + const DES_key_schedule *ks3) { uint32_t l, r; l = data[0]; @@ -562,8 +571,9 @@ void DES_encrypt3(uint32_t data[2], const DES_key_schedule *ks1, data[1] = r; } -void DES_decrypt3(uint32_t data[2], const DES_key_schedule *ks1, - const DES_key_schedule *ks2, const DES_key_schedule *ks3) { +void bssl::DES_decrypt3(uint32_t data[2], const DES_key_schedule *ks1, + const DES_key_schedule *ks2, + const DES_key_schedule *ks3) { uint32_t l, r; l = data[0]; @@ -586,8 +596,9 @@ void DES_ecb_encrypt(const DES_cblock *in_block, DES_cblock *out_block, DES_ecb_encrypt_ex(in_block->bytes, out_block->bytes, schedule, is_encrypt); } -void DES_ecb_encrypt_ex(const uint8_t in[8], uint8_t out[8], - const DES_key_schedule *schedule, int is_encrypt) { +void bssl::DES_ecb_encrypt_ex(const uint8_t in[8], uint8_t out[8], + const DES_key_schedule *schedule, + int is_encrypt) { uint32_t ll[2]; ll[0] = CRYPTO_load_u32_le(in); ll[1] = CRYPTO_load_u32_le(in + 4); @@ -602,13 +613,14 @@ void DES_ncbc_encrypt(const uint8_t *in, uint8_t *out, size_t len, DES_ncbc_encrypt_ex(in, out, len, schedule, ivec->bytes, enc); } -void DES_ncbc_encrypt_ex(const uint8_t *in, uint8_t *out, size_t len, - const DES_key_schedule *schedule, uint8_t ivec[8], - int enc) { +void bssl::DES_ncbc_encrypt_ex(const uint8_t *in, uint8_t *out, size_t len, + const DES_key_schedule *schedule, + uint8_t ivec[8], int enc) { uint32_t tin0, tin1; uint32_t tout0, tout1, xor0, xor1; uint32_t tin[2]; unsigned char *iv; + assert(len % 8 == 0); iv = ivec; @@ -684,10 +696,10 @@ void DES_ecb3_encrypt(const DES_cblock *input, DES_cblock *output, DES_ecb3_encrypt_ex(input->bytes, output->bytes, ks1, ks2, ks3, enc); } -void DES_ecb3_encrypt_ex(const uint8_t in[8], uint8_t out[8], - const DES_key_schedule *ks1, - const DES_key_schedule *ks2, - const DES_key_schedule *ks3, int enc) { +void bssl::DES_ecb3_encrypt_ex(const uint8_t in[8], uint8_t out[8], + const DES_key_schedule *ks1, + const DES_key_schedule *ks2, + const DES_key_schedule *ks3, int enc) { uint32_t ll[2]; ll[0] = CRYPTO_load_u32_le(in); ll[1] = CRYPTO_load_u32_le(in + 4); @@ -708,15 +720,16 @@ void DES_ede3_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len, DES_ede3_cbc_encrypt_ex(in, out, len, ks1, ks2, ks3, ivec->bytes, enc); } -void DES_ede3_cbc_encrypt_ex(const uint8_t *in, uint8_t *out, size_t len, - const DES_key_schedule *ks1, - const DES_key_schedule *ks2, - const DES_key_schedule *ks3, uint8_t ivec[8], - int enc) { +void bssl::DES_ede3_cbc_encrypt_ex(const uint8_t *in, uint8_t *out, size_t len, + const DES_key_schedule *ks1, + const DES_key_schedule *ks2, + const DES_key_schedule *ks3, uint8_t ivec[8], + int enc) { uint32_t tin0, tin1; uint32_t tout0, tout1, xor0, xor1; uint32_t tin[2]; uint8_t *iv; + assert(len % 8 == 0); iv = ivec; diff --git a/Sources/CNIOBoringSSL/crypto/des/internal.h b/Sources/CNIOBoringSSL/crypto/des/internal.h index 8c31ef66..b78cde4c 100644 --- a/Sources/CNIOBoringSSL/crypto/des/internal.h +++ b/Sources/CNIOBoringSSL/crypto/des/internal.h @@ -1,27 +1,30 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. -#ifndef OPENSSL_HEADER_DES_INTERNAL_H -#define OPENSSL_HEADER_DES_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_DES_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_DES_INTERNAL_H #include #include #include "../internal.h" -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN // TODO(davidben): Ideally these macros would be replaced with -// |CRYPTO_load_u32_le| and |CRYPTO_store_u32_le|. +// `CRYPTO_load_u32_le` and `CRYPTO_store_u32_le`. #define c2l(c, l) \ do { \ @@ -126,7 +129,7 @@ void DES_ede3_cbc_encrypt_ex(const uint8_t *in, uint8_t *out, size_t len, // Private functions. // -// These functions are only exported for use in |decrepit|. +// These functions are only exported for use in `decrepit`. OPENSSL_EXPORT void DES_decrypt3(uint32_t data[2], const DES_key_schedule *ks1, const DES_key_schedule *ks2, @@ -136,9 +139,6 @@ OPENSSL_EXPORT void DES_encrypt3(uint32_t data[2], const DES_key_schedule *ks1, const DES_key_schedule *ks2, const DES_key_schedule *ks3); +BSSL_NAMESPACE_END -#if defined(__cplusplus) -} // extern C -#endif - -#endif // OPENSSL_HEADER_DES_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_DES_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/dh/dh_asn1.cc b/Sources/CNIOBoringSSL/crypto/dh/dh_asn1.cc index 22660619..97d8f281 100644 --- a/Sources/CNIOBoringSSL/crypto/dh/dh_asn1.cc +++ b/Sources/CNIOBoringSSL/crypto/dh/dh_asn1.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -20,17 +25,19 @@ #include "../fipsmodule/dh/internal.h" -static int parse_integer(CBS *cbs, BIGNUM **out) { - assert(*out == NULL); - *out = BN_new(); - if (*out == NULL) { +using namespace bssl; + +static int parse_integer(CBS *cbs, UniquePtr *out) { + assert(*out == nullptr); + out->reset(BN_new()); + if (*out == nullptr) { return 0; } - return BN_parse_asn1_unsigned(cbs, *out); + return BN_parse_asn1_unsigned(cbs, out->get()); } static int marshal_integer(CBB *cbb, BIGNUM *bn) { - if (bn == NULL) { + if (bn == nullptr) { // A DH object may be missing some components. OPENSSL_PUT_ERROR(DH, ERR_R_PASSED_NULL_PARAMETER); return 0; @@ -39,50 +46,51 @@ static int marshal_integer(CBB *cbb, BIGNUM *bn) { } DH *DH_parse_parameters(CBS *cbs) { - DH *ret = DH_new(); - if (ret == NULL) { - return NULL; + UniquePtr ret(DH_new()); + if (ret == nullptr) { + return nullptr; } CBS child; + auto *impl = FromOpaque(ret.get()); if (!CBS_get_asn1(cbs, &child, CBS_ASN1_SEQUENCE) || - !parse_integer(&child, &ret->p) || - !parse_integer(&child, &ret->g)) { - goto err; + !parse_integer(&child, &impl->p) || // + !parse_integer(&child, &impl->g)) { + OPENSSL_PUT_ERROR(DH, DH_R_DECODE_ERROR); + return nullptr; } uint64_t priv_length; if (CBS_len(&child) != 0) { if (!CBS_get_asn1_uint64(&child, &priv_length) || priv_length > UINT_MAX) { - goto err; + OPENSSL_PUT_ERROR(DH, DH_R_DECODE_ERROR); + return nullptr; } - ret->priv_length = (unsigned)priv_length; + impl->priv_length = (unsigned)priv_length; } if (CBS_len(&child) != 0) { - goto err; + OPENSSL_PUT_ERROR(DH, DH_R_DECODE_ERROR); + return nullptr; } - if (!dh_check_params_fast(ret)) { - goto err; + if (!dh_check_params_fast(ret.get())) { + OPENSSL_PUT_ERROR(DH, DH_R_DECODE_ERROR); + return nullptr; } - return ret; - -err: - OPENSSL_PUT_ERROR(DH, DH_R_DECODE_ERROR); - DH_free(ret); - return NULL; + return ret.release(); } int DH_marshal_parameters(CBB *cbb, const DH *dh) { CBB child; + auto *impl = FromOpaque(dh); if (!CBB_add_asn1(cbb, &child, CBS_ASN1_SEQUENCE) || - !marshal_integer(&child, dh->p) || - !marshal_integer(&child, dh->g) || - (dh->priv_length != 0 && - !CBB_add_asn1_uint64(&child, dh->priv_length)) || + !marshal_integer(&child, impl->p.get()) || + !marshal_integer(&child, impl->g.get()) || + (impl->priv_length != 0 && + !CBB_add_asn1_uint64(&child, impl->priv_length)) || !CBB_flush(cbb)) { OPENSSL_PUT_ERROR(DH, DH_R_ENCODE_ERROR); return 0; @@ -91,29 +99,11 @@ int DH_marshal_parameters(CBB *cbb, const DH *dh) { } DH *d2i_DHparams(DH **out, const uint8_t **inp, long len) { - if (len < 0) { - return NULL; - } - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - DH *ret = DH_parse_parameters(&cbs); - if (ret == NULL) { - return NULL; - } - if (out != NULL) { - DH_free(*out); - *out = ret; - } - *inp = CBS_data(&cbs); - return ret; + return D2IFromCBS(out, inp, len, DH_parse_parameters); } int i2d_DHparams(const DH *in, uint8_t **outp) { - CBB cbb; - if (!CBB_init(&cbb, 0) || - !DH_marshal_parameters(&cbb, in)) { - CBB_cleanup(&cbb); - return -1; - } - return CBB_finish_i2d(&cbb, outp); + return I2DFromCBB( + /*initial_capacity=*/256, outp, + [&](CBB *cbb) -> bool { return DH_marshal_parameters(cbb, in); }); } diff --git a/Sources/CNIOBoringSSL/crypto/dh/params.cc b/Sources/CNIOBoringSSL/crypto/dh/params.cc index e3be73ef..04012250 100644 --- a/Sources/CNIOBoringSSL/crypto/dh/params.cc +++ b/Sources/CNIOBoringSSL/crypto/dh/params.cc @@ -1,35 +1,43 @@ -/* - * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../fipsmodule/bn/internal.h" #include "../fipsmodule/dh/internal.h" -static BIGNUM *get_params(BIGNUM *ret, const BN_ULONG *words, size_t num_words) { - BIGNUM *alloc = NULL; - if (ret == NULL) { +using namespace bssl; + +static BIGNUM *get_params(BIGNUM *ret, Span words) { + BIGNUM *alloc = nullptr; + if (ret == nullptr) { alloc = BN_new(); - if (alloc == NULL) { - return NULL; + if (alloc == nullptr) { + return nullptr; } ret = alloc; } - if (!bn_set_words(ret, words, num_words)) { + if (!bn_set_words(ret, words.data(), words.size())) { BN_free(alloc); - return NULL; + return nullptr; } return ret; @@ -50,7 +58,7 @@ BIGNUM *BN_get_rfc3526_prime_1536(BIGNUM *ret) { TOBN(0x29024e08, 0x8a67cc74), TOBN(0xc4c6628b, 0x80dc1cd1), TOBN(0xc90fdaa2, 0x2168c234), TOBN(0xffffffff, 0xffffffff), }; - return get_params(ret, kWords, OPENSSL_ARRAY_SIZE(kWords)); + return get_params(ret, kWords); } BIGNUM *BN_get_rfc3526_prime_2048(BIGNUM *ret) { @@ -72,7 +80,7 @@ BIGNUM *BN_get_rfc3526_prime_2048(BIGNUM *ret) { TOBN(0x29024e08, 0x8a67cc74), TOBN(0xc4c6628b, 0x80dc1cd1), TOBN(0xc90fdaa2, 0x2168c234), TOBN(0xffffffff, 0xffffffff), }; - return get_params(ret, kWords, OPENSSL_ARRAY_SIZE(kWords)); + return get_params(ret, kWords); } BIGNUM *BN_get_rfc3526_prime_3072(BIGNUM *ret) { @@ -102,7 +110,7 @@ BIGNUM *BN_get_rfc3526_prime_3072(BIGNUM *ret) { TOBN(0x29024e08, 0x8a67cc74), TOBN(0xc4c6628b, 0x80dc1cd1), TOBN(0xc90fdaa2, 0x2168c234), TOBN(0xffffffff, 0xffffffff), }; - return get_params(ret, kWords, OPENSSL_ARRAY_SIZE(kWords)); + return get_params(ret, kWords); } BIGNUM *BN_get_rfc3526_prime_4096(BIGNUM *ret) { @@ -140,7 +148,7 @@ BIGNUM *BN_get_rfc3526_prime_4096(BIGNUM *ret) { TOBN(0x29024e08, 0x8a67cc74), TOBN(0xc4c6628b, 0x80dc1cd1), TOBN(0xc90fdaa2, 0x2168c234), TOBN(0xffffffff, 0xffffffff), }; - return get_params(ret, kWords, OPENSSL_ARRAY_SIZE(kWords)); + return get_params(ret, kWords); } BIGNUM *BN_get_rfc3526_prime_6144(BIGNUM *ret) { @@ -194,7 +202,7 @@ BIGNUM *BN_get_rfc3526_prime_6144(BIGNUM *ret) { TOBN(0x29024e08, 0x8a67cc74), TOBN(0xc4c6628b, 0x80dc1cd1), TOBN(0xc90fdaa2, 0x2168c234), TOBN(0xffffffff, 0xffffffff), }; - return get_params(ret, kWords, OPENSSL_ARRAY_SIZE(kWords)); + return get_params(ret, kWords); } BIGNUM *BN_get_rfc3526_prime_8192(BIGNUM *ret) { @@ -264,7 +272,7 @@ BIGNUM *BN_get_rfc3526_prime_8192(BIGNUM *ret) { TOBN(0x29024e08, 0x8a67cc74), TOBN(0xc4c6628b, 0x80dc1cd1), TOBN(0xc90fdaa2, 0x2168c234), TOBN(0xffffffff, 0xffffffff), }; - return get_params(ret, kWords, OPENSSL_ARRAY_SIZE(kWords)); + return get_params(ret, kWords); } int DH_generate_parameters_ex(DH *dh, int prime_bits, int generator, @@ -288,7 +296,7 @@ int DH_generate_parameters_ex(DH *dh, int prime_bits, int generator, // // I've implemented the second simple method :-). // Since DH should be using a safe prime (both p and q are prime), - // this generator function can take a very very long time to run. + // this generator function can take a very, very long time to run. // Actually there is no reason to insist that 'generator' be a generator. // It's just as OK (and in some sense better) to use a generator of the @@ -299,115 +307,81 @@ int DH_generate_parameters_ex(DH *dh, int prime_bits, int generator, return 0; } - BIGNUM *t1, *t2; - int g, ok = 0; - BN_CTX *ctx = NULL; - - ctx = BN_CTX_new(); - if (ctx == NULL) { - goto err; - } - BN_CTX_start(ctx); - t1 = BN_CTX_get(ctx); - t2 = BN_CTX_get(ctx); - if (t1 == NULL || t2 == NULL) { - goto err; - } - - // Make sure |dh| has the necessary elements - if (dh->p == NULL) { - dh->p = BN_new(); - if (dh->p == NULL) { - goto err; + // Make sure `dh` has the necessary elements + auto *impl = FromOpaque(dh); + if (impl->p == nullptr) { + impl->p.reset(BN_new()); + if (impl->p == nullptr) { + OPENSSL_PUT_ERROR(DH, ERR_R_BN_LIB); + return 0; } } - if (dh->g == NULL) { - dh->g = BN_new(); - if (dh->g == NULL) { - goto err; - } - } - - if (generator <= 1) { - OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR); - goto err; - } - if (generator == DH_GENERATOR_2) { - if (!BN_set_word(t1, 24)) { - goto err; - } - if (!BN_set_word(t2, 11)) { - goto err; - } - g = 2; - } else if (generator == DH_GENERATOR_5) { - if (!BN_set_word(t1, 10)) { - goto err; - } - if (!BN_set_word(t2, 3)) { - goto err; - } - // BN_set_word(t3,7); just have to miss - // out on these ones :-( - g = 5; - } else { - // in the general case, don't worry if 'generator' is a - // generator or not: since we are using safe primes, - // it will generate either an order-q or an order-2q group, - // which both is OK - if (!BN_set_word(t1, 2)) { - goto err; - } - if (!BN_set_word(t2, 1)) { - goto err; - } - g = generator; - } - - if (!BN_generate_prime_ex(dh->p, prime_bits, 1, t1, t2, cb)) { - goto err; - } - if (!BN_GENCB_call(cb, 3, 0)) { - goto err; - } - if (!BN_set_word(dh->g, g)) { - goto err; - } - ok = 1; - -err: - if (!ok) { - OPENSSL_PUT_ERROR(DH, ERR_R_BN_LIB); - } - - if (ctx != NULL) { - BN_CTX_end(ctx); - BN_CTX_free(ctx); - } - return ok; -} - -static int int_dh_bn_cpy(BIGNUM **dst, const BIGNUM *src) { - BIGNUM *a = NULL; - - if (src) { - a = BN_dup(src); - if (!a) { + if (impl->g == nullptr) { + impl->g.reset(BN_new()); + if (impl->g == nullptr) { + OPENSSL_PUT_ERROR(DH, ERR_R_BN_LIB); return 0; } } - BN_free(*dst); - *dst = a; + BN_ULONG t1, t2, g; + if (generator <= 1) { + OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR); + return 0; + } + if (generator == DH_GENERATOR_2) { + t1 = 24; + t2 = 11; + g = 2; + } else if (generator == DH_GENERATOR_5) { + t1 = 10; + t2 = 3; + g = 5; + } else { + // In the general case, don't worry if 'generator' is a generator or not: + // since we are using safe primes, it will generate either an order-q or an + // order-2q group, which both is OK. + t1 = 2; + t2 = 1; + g = generator; + } + + UniquePtr t1_bn(BN_new()), t2_bn(BN_new()); + if (t1_bn == nullptr || t2_bn == nullptr || + !BN_set_word(t1_bn.get(), t1) || // + !BN_set_word(t2_bn.get(), t2) || // + !BN_generate_prime_ex(impl->p.get(), prime_bits, 1, t1_bn.get(), + t2_bn.get(), cb) || + !BN_GENCB_call(cb, 3, 0) || // + !BN_set_word(impl->g.get(), g)) { + OPENSSL_PUT_ERROR(DH, ERR_R_BN_LIB); + return 0; + } + return 1; } -static int int_dh_param_copy(DH *to, const DH *from, int is_x942) { - if (is_x942 == -1) { - is_x942 = !!from->q; +static bool copy_bn(UniquePtr *dst, const BIGNUM *src) { + UniquePtr copy; + if (src) { + copy.reset(BN_dup(src)); + if (!copy) { + return false; + } } - if (!int_dh_bn_cpy(&to->p, from->p) || - !int_dh_bn_cpy(&to->g, from->g)) { + *dst = std::move(copy); + return true; +} + +static int int_dh_param_copy(DH *to, const DH *from, int is_x942) { + auto *to_impl = FromOpaque(to); + const auto *from_impl = FromOpaque(from); + + if (is_x942 == -1) { + is_x942 = !!from_impl->q; + } + if (!copy_bn(&to_impl->p, from_impl->p.get()) || + !copy_bn(&to_impl->g, from_impl->g.get())) { return 0; } @@ -415,7 +389,7 @@ static int int_dh_param_copy(DH *to, const DH *from, int is_x942) { return 1; } - if (!int_dh_bn_cpy(&to->q, from->q)) { + if (!copy_bn(&to_impl->q, from_impl->q.get())) { return 0; } @@ -425,12 +399,12 @@ static int int_dh_param_copy(DH *to, const DH *from, int is_x942) { DH *DHparams_dup(const DH *dh) { DH *ret = DH_new(); if (!ret) { - return NULL; + return nullptr; } if (!int_dh_param_copy(ret, dh, -1)) { DH_free(ret); - return NULL; + return nullptr; } return ret; diff --git a/Sources/CNIOBoringSSL/crypto/digest/digest_extra.cc b/Sources/CNIOBoringSSL/crypto/digest/digest_extra.cc index d244d633..a6ec8468 100644 --- a/Sources/CNIOBoringSSL/crypto/digest/digest_extra.cc +++ b/Sources/CNIOBoringSSL/crypto/digest/digest_extra.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -13,10 +18,13 @@ #include #include +#include #include #include #include #include +#include +#include #include "../asn1/internal.h" #include "../fipsmodule/digest/internal.h" @@ -25,7 +33,7 @@ struct nid_to_digest { int nid; - const EVP_MD *(*md_func)(void); + const EVP_MD *(*md_func)(); const char *short_name; const char *long_name; }; @@ -40,14 +48,14 @@ static const struct nid_to_digest nid_to_digest_mapping[] = { {NID_sha512, EVP_sha512, SN_sha512, LN_sha512}, {NID_sha512_256, EVP_sha512_256, SN_sha512_256, LN_sha512_256}, {NID_md5_sha1, EVP_md5_sha1, SN_md5_sha1, LN_md5_sha1}, - // As a remnant of signing |EVP_MD|s, OpenSSL returned the corresponding + // As a remnant of signing `EVP_MD`s, OpenSSL returned the corresponding // hash function when given a signature OID. To avoid unintended lax parsing // of hash OIDs, this is no longer supported for lookup by OID or NID. - // Node.js, however, exposes |EVP_get_digestbyname|'s full behavior to + // Node.js, however, exposes `EVP_get_digestbyname`'s full behavior to // consumers so we retain it there. {NID_undef, EVP_sha1, SN_dsaWithSHA, LN_dsaWithSHA}, {NID_undef, EVP_sha1, SN_dsaWithSHA1, LN_dsaWithSHA1}, - {NID_undef, EVP_sha1, SN_ecdsa_with_SHA1, NULL}, + {NID_undef, EVP_sha1, SN_ecdsa_with_SHA1, nullptr}, {NID_undef, EVP_md5, SN_md5WithRSAEncryption, LN_md5WithRSAEncryption}, {NID_undef, EVP_sha1, SN_sha1WithRSAEncryption, LN_sha1WithRSAEncryption}, {NID_undef, EVP_sha224, SN_sha224WithRSAEncryption, @@ -62,17 +70,17 @@ static const struct nid_to_digest nid_to_digest_mapping[] = { const EVP_MD *EVP_get_digestbynid(int nid) { if (nid == NID_undef) { - // Skip the |NID_undef| entries in |nid_to_digest_mapping|. - return NULL; + // Skip the `NID_undef` entries in `nid_to_digest_mapping`. + return nullptr; } - for (unsigned i = 0; i < OPENSSL_ARRAY_SIZE(nid_to_digest_mapping); i++) { - if (nid_to_digest_mapping[i].nid == nid) { - return nid_to_digest_mapping[i].md_func(); + for (const auto &mapping : nid_to_digest_mapping) { + if (mapping.nid == nid) { + return mapping.md_func(); } } - return NULL; + return nullptr; } static const struct { @@ -96,42 +104,41 @@ static const struct { {{0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04}, 9, NID_sha224}, }; -static const EVP_MD *cbs_to_md(const CBS *cbs) { - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kMDOIDs); i++) { - if (CBS_len(cbs) == kMDOIDs[i].oid_len && - OPENSSL_memcmp(CBS_data(cbs), kMDOIDs[i].oid, kMDOIDs[i].oid_len) == - 0) { - return EVP_get_digestbynid(kMDOIDs[i].nid); +static 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)) { + return md.nid; } } - - return NULL; + return NID_undef; } const EVP_MD *EVP_get_digestbyobj(const ASN1_OBJECT *obj) { - // Handle objects with no corresponding OID. Note we don't use |OBJ_obj2nid| - // here to avoid pulling in the OID table. - if (obj->nid != NID_undef) { - return EVP_get_digestbynid(obj->nid); + int nid = obj->nid; + if (nid == NID_undef) { + // Handle objects with no saved NID. Note we don't use `OBJ_obj2nid` here to + // avoid pulling in the OID table. + CBS cbs; + CBS_init(&cbs, OBJ_get0_data(obj), OBJ_length(obj)); + nid = cbs_to_digest_nid(&cbs); } - CBS cbs; - CBS_init(&cbs, OBJ_get0_data(obj), OBJ_length(obj)); - return cbs_to_md(&cbs); + return nid == NID_undef ? nullptr : EVP_get_digestbynid(nid); } -const EVP_MD *EVP_parse_digest_algorithm(CBS *cbs) { +int EVP_parse_digest_algorithm_nid(CBS *cbs) { CBS algorithm, oid; if (!CBS_get_asn1(cbs, &algorithm, CBS_ASN1_SEQUENCE) || !CBS_get_asn1(&algorithm, &oid, CBS_ASN1_OBJECT)) { OPENSSL_PUT_ERROR(DIGEST, DIGEST_R_DECODE_ERROR); - return NULL; + return NID_undef; } - const EVP_MD *ret = cbs_to_md(&oid); - if (ret == NULL) { + int ret = cbs_to_digest_nid(&oid); + if (ret == NID_undef) { OPENSSL_PUT_ERROR(DIGEST, DIGEST_R_UNKNOWN_HASH); - return NULL; + return NID_undef; } // The parameters, if present, must be NULL. Historically, whether the NULL @@ -144,28 +151,37 @@ const EVP_MD *EVP_parse_digest_algorithm(CBS *cbs) { CBS_len(¶m) != 0 || // CBS_len(&algorithm) != 0) { OPENSSL_PUT_ERROR(DIGEST, DIGEST_R_DECODE_ERROR); - return NULL; + return NID_undef; } } return ret; } -int EVP_marshal_digest_algorithm(CBB *cbb, const EVP_MD *md) { +const EVP_MD *EVP_parse_digest_algorithm(CBS *cbs) { + int nid = EVP_parse_digest_algorithm_nid(cbs); + if (nid == NID_undef) { + return nullptr; + } + return EVP_get_digestbynid(nid); +} + +static 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)) { return 0; } - int found = 0; + bool found = false; int nid = EVP_MD_type(md); - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kMDOIDs); i++) { - if (nid == kMDOIDs[i].nid) { - if (!CBB_add_bytes(&oid, kMDOIDs[i].oid, kMDOIDs[i].oid_len)) { + for (const auto &mdoid : kMDOIDs) { + if (nid == mdoid.nid) { + if (!CBB_add_bytes(&oid, mdoid.oid, mdoid.oid_len)) { return 0; } - found = 1; + found = true; break; } } @@ -175,8 +191,7 @@ int EVP_marshal_digest_algorithm(CBB *cbb, const EVP_MD *md) { return 0; } - // TODO(crbug.com/boringssl/710): Is this correct? See RFC 4055, section 2.1. - if (!CBB_add_asn1(&algorithm, &null, CBS_ASN1_NULL) || // + if ((with_null && !CBB_add_asn1(&algorithm, &null, CBS_ASN1_NULL)) || // !CBB_flush(cbb)) { return 0; } @@ -184,17 +199,52 @@ int EVP_marshal_digest_algorithm(CBB *cbb, const EVP_MD *md) { return 1; } +int EVP_marshal_digest_algorithm(CBB *cbb, const EVP_MD *md) { + return marshal_digest_algorithm(cbb, md, /*with_null=*/true); +} + +int EVP_marshal_digest_algorithm_no_params(CBB *cbb, const EVP_MD *md) { + return marshal_digest_algorithm(cbb, md, /*with_null=*/false); +} + const EVP_MD *EVP_get_digestbyname(const char *name) { - for (unsigned i = 0; i < OPENSSL_ARRAY_SIZE(nid_to_digest_mapping); i++) { - const char *short_name = nid_to_digest_mapping[i].short_name; - const char *long_name = nid_to_digest_mapping[i].long_name; + for (const auto &mapping : nid_to_digest_mapping) { + const char *short_name = mapping.short_name; + const char *long_name = mapping.long_name; if ((short_name && strcmp(short_name, name) == 0) || (long_name && strcmp(long_name, name) == 0)) { - return nid_to_digest_mapping[i].md_func(); + return mapping.md_func(); } } - return NULL; + return nullptr; +} + +EVP_MD *EVP_MD_fetch(OSSL_LIB_CTX *libctx, const char *name, + const char *propq) { + EVP_MD *ret = const_cast(EVP_get_digestbyname(name)); + if (ret == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); + } + return ret; +} + +int EVP_MD_up_ref(EVP_MD *md) { return 1; } + +void EVP_MD_free(EVP_MD *md) {} + +int EVP_Q_digest(OSSL_LIB_CTX *libctx, const char *name, const char *propq, + const void *in, size_t in_len, uint8_t *out, size_t *out_len) { + const EVP_MD *md = EVP_MD_fetch(libctx, name, propq); + if (md == nullptr) { + return 0; + } + unsigned len_u; + if (!EVP_Digest(in, in_len, out, &len_u, md, nullptr)) { + return 0; + } + *out_len = len_u; + return 1; } static void blake2b256_init(EVP_MD_CTX *ctx) { @@ -215,7 +265,9 @@ static const EVP_MD evp_md_blake2b256 = { BLAKE2B_CBLOCK, sizeof(BLAKE2B_CTX), }; -const EVP_MD *EVP_blake2b256(void) { return &evp_md_blake2b256; } +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) { @@ -242,7 +294,10 @@ static const EVP_MD evp_md_md4 = { sizeof(MD4_CTX), }; -const EVP_MD *EVP_md4(void) { return &evp_md_md4; } +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) { BSSL_CHECK(MD5_Init(reinterpret_cast(ctx->md_data))); @@ -262,7 +317,10 @@ static const EVP_MD evp_md_md5 = { md5_update, md5_final, 64, sizeof(MD5_CTX), }; -const EVP_MD *EVP_md5(void) { return &evp_md_md5; } +const EVP_MD *EVP_md5() { return &evp_md_md5; } + +static_assert(sizeof(MD5_CTX) <= EVP_MAX_MD_DATA_SIZE); + typedef struct { MD5_CTX md5; @@ -298,4 +356,6 @@ const EVP_MD evp_md_md5_sha1 = { sizeof(MD5_SHA1_CTX), }; -const EVP_MD *EVP_md5_sha1(void) { return &evp_md_md5_sha1; } +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/Sources/CNIOBoringSSL/crypto/dsa/dsa.cc b/Sources/CNIOBoringSSL/crypto/dsa/dsa.cc index 5d2855f5..fb380966 100644 --- a/Sources/CNIOBoringSSL/crypto/dsa/dsa.cc +++ b/Sources/CNIOBoringSSL/crypto/dsa/dsa.cc @@ -1,16 +1,23 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -19,160 +26,154 @@ #include #include #include -#include -#include +#include #include "../fipsmodule/bn/internal.h" #include "../fipsmodule/dh/internal.h" #include "../internal.h" +#include "../mem_internal.h" #include "internal.h" +using namespace bssl; + +static_assert(OPENSSL_DSA_MAX_MODULUS_BITS <= + BN_MONTGOMERY_MAX_WORDS * BN_BITS2, + "Max DSA size too big for Montgomery arithmetic"); + // Primality test according to FIPS PUB 186[-1], Appendix 2.1: 50 rounds of // Miller-Rabin. #define DSS_prime_checks 50 -static int dsa_sign_setup(const DSA *dsa, BN_CTX *ctx_in, BIGNUM **out_kinv, +static int dsa_sign_setup(const DSAImpl *dsa, BN_CTX *ctx_in, BIGNUM **out_kinv, BIGNUM **out_r); -static CRYPTO_EX_DATA_CLASS g_ex_data_class = CRYPTO_EX_DATA_CLASS_INIT; +static ExDataClass g_ex_data_class; -DSA *DSA_new(void) { - DSA *dsa = reinterpret_cast(OPENSSL_zalloc(sizeof(DSA))); - if (dsa == NULL) { - return NULL; - } +DSA *DSA_new() { return New(); } - dsa->references = 1; - CRYPTO_MUTEX_init(&dsa->method_mont_lock); - CRYPTO_new_ex_data(&dsa->ex_data); - return dsa; +DSAImpl::DSAImpl() : RefCounted(CheckSubClass()) { + CRYPTO_new_ex_data(&ex_data); } +DSAImpl::~DSAImpl() { CRYPTO_free_ex_data(&g_ex_data_class, &ex_data); } + void DSA_free(DSA *dsa) { - if (dsa == NULL) { + if (dsa == nullptr) { return; } - - if (!CRYPTO_refcount_dec_and_test_zero(&dsa->references)) { - return; - } - - CRYPTO_free_ex_data(&g_ex_data_class, dsa, &dsa->ex_data); - - BN_clear_free(dsa->p); - BN_clear_free(dsa->q); - BN_clear_free(dsa->g); - BN_clear_free(dsa->pub_key); - BN_clear_free(dsa->priv_key); - BN_MONT_CTX_free(dsa->method_mont_p); - BN_MONT_CTX_free(dsa->method_mont_q); - CRYPTO_MUTEX_cleanup(&dsa->method_mont_lock); - OPENSSL_free(dsa); + auto *impl = FromOpaque(dsa); + impl->DecRefInternal(); } int DSA_up_ref(DSA *dsa) { - CRYPTO_refcount_inc(&dsa->references); + auto *impl = FromOpaque(dsa); + impl->UpRefInternal(); return 1; } -unsigned DSA_bits(const DSA *dsa) { return BN_num_bits(dsa->p); } +unsigned DSA_bits(const DSA *dsa) { + return BN_num_bits(FromOpaque(dsa)->p.get()); +} -const BIGNUM *DSA_get0_pub_key(const DSA *dsa) { return dsa->pub_key; } +const BIGNUM *DSA_get0_pub_key(const DSA *dsa) { + return FromOpaque(dsa)->pub_key.get(); +} -const BIGNUM *DSA_get0_priv_key(const DSA *dsa) { return dsa->priv_key; } +const BIGNUM *DSA_get0_priv_key(const DSA *dsa) { + return FromOpaque(dsa)->priv_key.get(); +} -const BIGNUM *DSA_get0_p(const DSA *dsa) { return dsa->p; } +const BIGNUM *DSA_get0_p(const DSA *dsa) { return FromOpaque(dsa)->p.get(); } -const BIGNUM *DSA_get0_q(const DSA *dsa) { return dsa->q; } +const BIGNUM *DSA_get0_q(const DSA *dsa) { return FromOpaque(dsa)->q.get(); } -const BIGNUM *DSA_get0_g(const DSA *dsa) { return dsa->g; } +const BIGNUM *DSA_get0_g(const DSA *dsa) { return FromOpaque(dsa)->g.get(); } void DSA_get0_key(const DSA *dsa, const BIGNUM **out_pub_key, const BIGNUM **out_priv_key) { - if (out_pub_key != NULL) { - *out_pub_key = dsa->pub_key; + auto *impl = FromOpaque(dsa); + if (out_pub_key != nullptr) { + *out_pub_key = impl->pub_key.get(); } - if (out_priv_key != NULL) { - *out_priv_key = dsa->priv_key; + if (out_priv_key != nullptr) { + *out_priv_key = impl->priv_key.get(); } } void DSA_get0_pqg(const DSA *dsa, const BIGNUM **out_p, const BIGNUM **out_q, const BIGNUM **out_g) { - if (out_p != NULL) { - *out_p = dsa->p; + auto *impl = FromOpaque(dsa); + if (out_p != nullptr) { + *out_p = impl->p.get(); } - if (out_q != NULL) { - *out_q = dsa->q; + if (out_q != nullptr) { + *out_q = impl->q.get(); } - if (out_g != NULL) { - *out_g = dsa->g; + if (out_g != nullptr) { + *out_g = impl->g.get(); } } int DSA_set0_key(DSA *dsa, BIGNUM *pub_key, BIGNUM *priv_key) { - if (dsa->pub_key == NULL && pub_key == NULL) { + auto *impl = FromOpaque(dsa); + + if (impl->pub_key == nullptr && pub_key == nullptr) { return 0; } - if (pub_key != NULL) { - BN_free(dsa->pub_key); - dsa->pub_key = pub_key; + if (pub_key != nullptr) { + impl->pub_key.reset(pub_key); } - if (priv_key != NULL) { - BN_free(dsa->priv_key); - dsa->priv_key = priv_key; + if (priv_key != nullptr) { + impl->priv_key.reset(priv_key); } return 1; } int DSA_set0_pqg(DSA *dsa, BIGNUM *p, BIGNUM *q, BIGNUM *g) { - if ((dsa->p == NULL && p == NULL) || (dsa->q == NULL && q == NULL) || - (dsa->g == NULL && g == NULL)) { + auto *impl = FromOpaque(dsa); + + if ((impl->p == nullptr && p == nullptr) || + (impl->q == nullptr && q == nullptr) || + (impl->g == nullptr && g == nullptr)) { return 0; } - if (p != NULL) { - BN_free(dsa->p); - dsa->p = p; + if (p != nullptr) { + impl->p.reset(p); } - if (q != NULL) { - BN_free(dsa->q); - dsa->q = q; + if (q != nullptr) { + impl->q.reset(q); } - if (g != NULL) { - BN_free(dsa->g); - dsa->g = g; + if (g != nullptr) { + impl->g.reset(g); } - BN_MONT_CTX_free(dsa->method_mont_p); - dsa->method_mont_p = NULL; - BN_MONT_CTX_free(dsa->method_mont_q); - dsa->method_mont_q = NULL; + impl->method_mont_p = nullptr; + impl->method_mont_q = nullptr; return 1; } int DSA_generate_parameters_ex(DSA *dsa, unsigned bits, const uint8_t *seed_in, size_t seed_len, int *out_counter, unsigned long *out_h, BN_GENCB *cb) { + auto *impl = FromOpaque(dsa); + if (bits > OPENSSL_DSA_MAX_MODULUS_BITS) { OPENSSL_PUT_ERROR(DSA, DSA_R_INVALID_PARAMETERS); return 0; } - int ok = 0; unsigned char seed[SHA256_DIGEST_LENGTH]; unsigned char md[SHA256_DIGEST_LENGTH]; unsigned char buf[SHA256_DIGEST_LENGTH], buf2[SHA256_DIGEST_LENGTH]; BIGNUM *r0, *W, *X, *c, *test; - BIGNUM *g = NULL, *q = NULL, *p = NULL; - BN_MONT_CTX *mont = NULL; + BIGNUM *g = nullptr, *q = nullptr, *p = nullptr; int k, n = 0, m = 0; int counter = 0; int r = 0; - BN_CTX *ctx = NULL; unsigned int h = 2; const EVP_MD *evpmd; @@ -185,7 +186,7 @@ int DSA_generate_parameters_ex(DSA *dsa, unsigned bits, const uint8_t *seed_in, bits = (bits + 63) / 64 * 64; - if (seed_in != NULL) { + if (seed_in != nullptr) { if (seed_len < qsize) { return 0; } @@ -196,23 +197,23 @@ int DSA_generate_parameters_ex(DSA *dsa, unsigned bits, const uint8_t *seed_in, OPENSSL_memcpy(seed, seed_in, seed_len); } - ctx = BN_CTX_new(); - if (ctx == NULL) { - goto err; + UniquePtr ctx(BN_CTX_new()); + if (ctx == nullptr) { + return 0; } - BN_CTX_start(ctx); + BN_CTXScope scope(ctx.get()); - r0 = BN_CTX_get(ctx); - g = BN_CTX_get(ctx); - W = BN_CTX_get(ctx); - q = BN_CTX_get(ctx); - X = BN_CTX_get(ctx); - c = BN_CTX_get(ctx); - p = BN_CTX_get(ctx); - test = BN_CTX_get(ctx); + r0 = BN_CTX_get(ctx.get()); + g = BN_CTX_get(ctx.get()); + W = BN_CTX_get(ctx.get()); + q = BN_CTX_get(ctx.get()); + X = BN_CTX_get(ctx.get()); + c = BN_CTX_get(ctx.get()); + p = BN_CTX_get(ctx.get()); + test = BN_CTX_get(ctx.get()); - if (test == NULL || !BN_lshift(test, BN_value_one(), bits - 1)) { - goto err; + if (test == nullptr || !BN_lshift(test, BN_value_one(), bits - 1)) { + return 0; } for (;;) { @@ -220,19 +221,19 @@ int DSA_generate_parameters_ex(DSA *dsa, unsigned bits, const uint8_t *seed_in, for (;;) { // step 1 if (!BN_GENCB_call(cb, BN_GENCB_GENERATED, m++)) { - goto err; + return 0; } - int use_random_seed = (seed_in == NULL); + int use_random_seed = (seed_in == nullptr); if (use_random_seed) { if (!RAND_bytes(seed, qsize)) { - goto err; + return 0; } // DSA parameters are public. CONSTTIME_DECLASSIFY(seed, qsize); } else { // If we come back through, use random seed next time. - seed_in = NULL; + seed_in = nullptr; } OPENSSL_memcpy(buf, seed, qsize); OPENSSL_memcpy(buf2, seed, qsize); @@ -245,9 +246,9 @@ int DSA_generate_parameters_ex(DSA *dsa, unsigned bits, const uint8_t *seed_in, } // step 2 - if (!EVP_Digest(seed, qsize, md, NULL, evpmd, NULL) || - !EVP_Digest(buf, qsize, buf2, NULL, evpmd, NULL)) { - goto err; + if (!EVP_Digest(seed, qsize, md, nullptr, evpmd, nullptr) || + !EVP_Digest(buf, qsize, buf2, nullptr, evpmd, nullptr)) { + return 0; } for (size_t i = 0; i < qsize; i++) { md[i] ^= buf2[i]; @@ -257,17 +258,17 @@ int DSA_generate_parameters_ex(DSA *dsa, unsigned bits, const uint8_t *seed_in, md[0] |= 0x80; md[qsize - 1] |= 0x01; if (!BN_bin2bn(md, qsize, q)) { - goto err; + return 0; } // step 4 - r = BN_is_prime_fasttest_ex(q, DSS_prime_checks, ctx, use_random_seed, - cb); + r = BN_is_prime_fasttest_ex(q, DSS_prime_checks, ctx.get(), + use_random_seed, cb); if (r > 0) { break; } if (r != 0) { - goto err; + return 0; } // do a callback call @@ -275,7 +276,7 @@ int DSA_generate_parameters_ex(DSA *dsa, unsigned bits, const uint8_t *seed_in, } if (!BN_GENCB_call(cb, 2, 0) || !BN_GENCB_call(cb, 3, 0)) { - goto err; + return 0; } // step 6 @@ -286,7 +287,7 @@ int DSA_generate_parameters_ex(DSA *dsa, unsigned bits, const uint8_t *seed_in, for (;;) { if ((counter != 0) && !BN_GENCB_call(cb, BN_GENCB_GENERATED, counter)) { - goto err; + return 0; } // step 7 @@ -301,37 +302,37 @@ int DSA_generate_parameters_ex(DSA *dsa, unsigned bits, const uint8_t *seed_in, } } - if (!EVP_Digest(buf, qsize, md, NULL, evpmd, NULL)) { - goto err; + if (!EVP_Digest(buf, qsize, md, nullptr, evpmd, nullptr)) { + return 0; } // step 8 if (!BN_bin2bn(md, qsize, r0) || !BN_lshift(r0, r0, (qsize << 3) * k) || !BN_add(W, W, r0)) { - goto err; + return 0; } } // more of step 8 if (!BN_mask_bits(W, bits - 1) || !BN_copy(X, W) || !BN_add(X, X, test)) { - goto err; + return 0; } // step 9 - if (!BN_lshift1(r0, q) || !BN_mod(c, X, r0, ctx) || + if (!BN_lshift1(r0, q) || !BN_mod(c, X, r0, ctx.get()) || !BN_sub(r0, c, BN_value_one()) || !BN_sub(p, X, r0)) { - goto err; + return 0; } // step 10 if (BN_cmp(p, test) >= 0) { // step 11 - r = BN_is_prime_fasttest_ex(p, DSS_prime_checks, ctx, 1, cb); + r = BN_is_prime_fasttest_ex(p, DSS_prime_checks, ctx.get(), 1, cb); if (r > 0) { goto end; // found it } if (r != 0) { - goto err; + return 0; } } @@ -347,146 +348,102 @@ int DSA_generate_parameters_ex(DSA *dsa, unsigned bits, const uint8_t *seed_in, } end: if (!BN_GENCB_call(cb, 2, 1)) { - goto err; + return 0; } // We now need to generate g // Set r0=(p-1)/q - if (!BN_sub(test, p, BN_value_one()) || !BN_div(r0, NULL, test, q, ctx)) { - goto err; + if (!BN_sub(test, p, BN_value_one()) || + !BN_div(r0, nullptr, test, q, ctx.get())) { + return 0; } - mont = BN_MONT_CTX_new_for_modulus(p, ctx); - if (mont == NULL || !BN_set_word(test, h)) { - goto err; + UniquePtr mont(BN_MONT_CTX_new_for_modulus(p, ctx.get())); + if (mont == nullptr || !BN_set_word(test, h)) { + return 0; } for (;;) { // g=test^r0%p - if (!BN_mod_exp_mont(g, test, r0, p, ctx, mont)) { - goto err; + if (!BN_mod_exp_mont(g, test, r0, p, ctx.get(), mont.get())) { + return 0; } if (!BN_is_one(g)) { break; } if (!BN_add(test, test, BN_value_one())) { - goto err; + return 0; } h++; } if (!BN_GENCB_call(cb, 3, 1)) { - goto err; + return 0; } - ok = 1; - -err: - if (ok) { - BN_free(dsa->p); - BN_free(dsa->q); - BN_free(dsa->g); - dsa->p = BN_dup(p); - dsa->q = BN_dup(q); - dsa->g = BN_dup(g); - if (dsa->p == NULL || dsa->q == NULL || dsa->g == NULL) { - ok = 0; - goto err; - } - if (out_counter != NULL) { - *out_counter = counter; - } - if (out_h != NULL) { - *out_h = h; - } + impl->p.reset(BN_dup(p)); + impl->q.reset(BN_dup(q)); + impl->g.reset(BN_dup(g)); + if (impl->p == nullptr || impl->q == nullptr || impl->g == nullptr) { + return 0; + } + if (out_counter != nullptr) { + *out_counter = counter; + } + if (out_h != nullptr) { + *out_h = h; } - if (ctx) { - BN_CTX_end(ctx); - BN_CTX_free(ctx); - } - - BN_MONT_CTX_free(mont); - - return ok; + return 1; } DSA *DSAparams_dup(const DSA *dsa) { - DSA *ret = DSA_new(); - if (ret == NULL) { - return NULL; + auto *impl = FromOpaque(dsa); + DSAImpl *ret = FromOpaque(DSA_new()); + if (ret == nullptr) { + return nullptr; } - ret->p = BN_dup(dsa->p); - ret->q = BN_dup(dsa->q); - ret->g = BN_dup(dsa->g); - if (ret->p == NULL || ret->q == NULL || ret->g == NULL) { + ret->p.reset(BN_dup(impl->p.get())); + ret->q.reset(BN_dup(impl->q.get())); + ret->g.reset(BN_dup(impl->g.get())); + if (ret->p == nullptr || ret->q == nullptr || ret->g == nullptr) { DSA_free(ret); - return NULL; + return nullptr; } return ret; } int DSA_generate_key(DSA *dsa) { - if (!dsa_check_key(dsa)) { + auto *impl = FromOpaque(dsa); + + if (!dsa_check_key(impl)) { return 0; } - int ok = 0; - BIGNUM *pub_key = NULL, *priv_key = NULL; - BN_CTX *ctx = BN_CTX_new(); - if (ctx == NULL) { - goto err; + UniquePtr ctx(BN_CTX_new()); + UniquePtr pub_key(BN_new()), priv_key(BN_new()); + if (ctx == nullptr || pub_key == nullptr || priv_key == nullptr) { + return 0; } - priv_key = dsa->priv_key; - if (priv_key == NULL) { - priv_key = BN_new(); - if (priv_key == NULL) { - goto err; - } - } - - if (!BN_rand_range_ex(priv_key, 1, dsa->q)) { - goto err; - } - - pub_key = dsa->pub_key; - if (pub_key == NULL) { - pub_key = BN_new(); - if (pub_key == NULL) { - goto err; - } - } - - if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p, &dsa->method_mont_lock, - dsa->p, ctx) || - !BN_mod_exp_mont_consttime(pub_key, dsa->g, priv_key, dsa->p, ctx, - dsa->method_mont_p)) { - goto err; + if (!BN_rand_range_ex(priv_key.get(), 1, impl->q.get()) || + !BN_MONT_CTX_set_locked(&impl->method_mont_p, &impl->method_mont_lock, + impl->p.get(), ctx.get()) || + !BN_mod_exp_mont_consttime(pub_key.get(), impl->g.get(), priv_key.get(), + impl->p.get(), ctx.get(), + impl->method_mont_p.get())) { + return 0; } // The public key is computed from the private key, but is public. - bn_declassify(pub_key); + bn_declassify(pub_key.get()); - dsa->priv_key = priv_key; - dsa->pub_key = pub_key; - ok = 1; - -err: - if (dsa->pub_key == NULL) { - BN_free(pub_key); - } - if (dsa->priv_key == NULL) { - BN_free(priv_key); - } - BN_CTX_free(ctx); - - return ok; + impl->priv_key = std::move(priv_key); + impl->pub_key = std::move(pub_key); + return 1; } -DSA_SIG *DSA_SIG_new(void) { - return reinterpret_cast(OPENSSL_zalloc(sizeof(DSA_SIG))); -} +DSA_SIG *DSA_SIG_new() { return New(); } void DSA_SIG_free(DSA_SIG *sig) { if (!sig) { @@ -495,21 +452,21 @@ void DSA_SIG_free(DSA_SIG *sig) { BN_free(sig->r); BN_free(sig->s); - OPENSSL_free(sig); + Delete(sig); } void DSA_SIG_get0(const DSA_SIG *sig, const BIGNUM **out_r, const BIGNUM **out_s) { - if (out_r != NULL) { + if (out_r != nullptr) { *out_r = sig->r; } - if (out_s != NULL) { + if (out_s != nullptr) { *out_s = sig->s; } } int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s) { - if (r == NULL || s == NULL) { + if (r == nullptr || s == nullptr) { return 0; } BN_free(sig->r); @@ -519,46 +476,47 @@ int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s) { return 1; } -// mod_mul_consttime sets |r| to |a| * |b| modulo |mont->N|, treating |a| and -// |b| as secret. This function internally uses Montgomery reduction, but +// mod_mul_consttime sets `r` to `a` * `b` modulo `mont->N`, treating `a` and +// `b` as secret. This function internally uses Montgomery reduction, but // neither inputs nor outputs are in Montgomery form. static int mod_mul_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BN_MONT_CTX *mont, BN_CTX *ctx) { - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *tmp = BN_CTX_get(ctx); - // |BN_mod_mul_montgomery| removes a factor of R, so we cancel it with a - // single |BN_to_montgomery| which adds one factor of R. - int ok = tmp != NULL && BN_to_montgomery(tmp, a, mont, ctx) && - BN_mod_mul_montgomery(r, tmp, b, mont, ctx); - BN_CTX_end(ctx); - return ok; + // `BN_mod_mul_montgomery` removes a factor of R, so we cancel it with a + // single `BN_to_montgomery` which adds one factor of R. + return tmp != nullptr && // + BN_to_montgomery(tmp, a, mont, ctx) && + BN_mod_mul_montgomery(r, tmp, b, mont, ctx); } DSA_SIG *DSA_do_sign(const uint8_t *digest, size_t digest_len, const DSA *dsa) { - if (!dsa_check_key(dsa)) { - return NULL; + auto *impl = FromOpaque(dsa); + + if (!dsa_check_key(impl)) { + return nullptr; } - if (dsa->priv_key == NULL) { + if (impl->priv_key == nullptr) { OPENSSL_PUT_ERROR(DSA, DSA_R_MISSING_PARAMETERS); - return NULL; + return nullptr; } - BIGNUM *kinv = NULL, *r = NULL, *s = NULL; + BIGNUM *kinv = nullptr, *r = nullptr, *s = nullptr; BIGNUM m; BIGNUM xr; - BN_CTX *ctx = NULL; - DSA_SIG *ret = NULL; + BN_CTX *ctx = nullptr; + DSA_SIG *ret = nullptr; BN_init(&m); BN_init(&xr); s = BN_new(); { - if (s == NULL) { + if (s == nullptr) { goto err; } ctx = BN_CTX_new(); - if (ctx == NULL) { + if (ctx == nullptr) { goto err; } @@ -566,42 +524,43 @@ DSA_SIG *DSA_do_sign(const uint8_t *digest, size_t digest_len, const DSA *dsa) { // not impact valid parameters because the probability of requiring even one // retry is negligible, let alone 32. Unfortunately, DSA was mis-specified, // so invalid parameters are reachable from most callers handling untrusted - // private keys. (The |dsa_check_key| call above is not sufficient. Checking - // whether arbitrary paremeters form a valid DSA group is expensive.) + // private keys. (The `dsa_check_key` call above is not sufficient. Checking + // whether arbitrary parameters form a valid DSA group is expensive.) static const int kMaxIterations = 32; int iters = 0; redo: - if (!dsa_sign_setup(dsa, ctx, &kinv, &r)) { + if (!dsa_sign_setup(impl, ctx, &kinv, &r)) { goto err; } - if (digest_len > BN_num_bytes(dsa->q)) { - // If the digest length is greater than the size of |dsa->q| use the - // BN_num_bits(dsa->q) leftmost bits of the digest, see FIPS 186-3, 4.2. - // Note the above check that |dsa->q| is a multiple of 8 bits. - digest_len = BN_num_bytes(dsa->q); + if (digest_len > BN_num_bytes(impl->q.get())) { + // If the digest length is greater than the size of `impl->q` use the + // BN_num_bits(impl->q) leftmost bits of the digest, see FIPS 186-3, 4.2. + // Note the above check that `impl->q` is a multiple of 8 bits. + digest_len = BN_num_bytes(impl->q.get()); } - if (BN_bin2bn(digest, digest_len, &m) == NULL) { + if (BN_bin2bn(digest, digest_len, &m) == nullptr) { goto err; } - // |m| is bounded by 2^(num_bits(q)), which is slightly looser than q. This - // violates |bn_mod_add_consttime| and |mod_mul_consttime|'s preconditions. + // `m` is bounded by 2^(num_bits(q)), which is slightly looser than q. This + // violates `bn_mod_add_consttime` and `mod_mul_consttime`'s preconditions. // (The underlying algorithms could accept looser bounds, but we reduce for // simplicity.) - size_t q_width = bn_minimal_width(dsa->q); + size_t q_width = bn_minimal_width(impl->q.get()); if (!bn_resize_words(&m, q_width) || !bn_resize_words(&xr, q_width)) { goto err; } - bn_reduce_once_in_place(m.d, 0 /* no carry word */, dsa->q->d, + bn_reduce_once_in_place(m.d, 0 /* no carry word */, impl->q->d, xr.d /* scratch space */, q_width); - // Compute s = inv(k) (m + xr) mod q. Note |dsa->method_mont_q| is - // initialized by |dsa_sign_setup|. - if (!mod_mul_consttime(&xr, dsa->priv_key, r, dsa->method_mont_q, ctx) || - !bn_mod_add_consttime(s, &xr, &m, dsa->q, ctx) || - !mod_mul_consttime(s, s, kinv, dsa->method_mont_q, ctx)) { + // Compute s = inv(k) (m + xr) mod q. Note `impl->method_mont_q` is + // initialized by `dsa_sign_setup`. + if (!mod_mul_consttime(&xr, impl->priv_key.get(), r, + impl->method_mont_q.get(), ctx) || + !bn_mod_add_consttime(s, &xr, &m, impl->q.get(), ctx) || + !mod_mul_consttime(s, s, kinv, impl->method_mont_q.get(), ctx)) { goto err; } @@ -621,7 +580,7 @@ DSA_SIG *DSA_do_sign(const uint8_t *digest, size_t digest_len, const DSA *dsa) { } ret = DSA_SIG_new(); - if (ret == NULL) { + if (ret == nullptr) { goto err; } ret->r = r; @@ -629,7 +588,7 @@ DSA_SIG *DSA_do_sign(const uint8_t *digest, size_t digest_len, const DSA *dsa) { } err: - if (ret == NULL) { + if (ret == nullptr) { OPENSSL_PUT_ERROR(DSA, ERR_R_BN_LIB); BN_free(r); BN_free(s); @@ -654,12 +613,14 @@ int DSA_do_verify(const uint8_t *digest, size_t digest_len, const DSA_SIG *sig, int DSA_do_check_signature(int *out_valid, const uint8_t *digest, size_t digest_len, const DSA_SIG *sig, const DSA *dsa) { + auto *impl = FromOpaque(dsa); + *out_valid = 0; - if (!dsa_check_key(dsa)) { + if (!dsa_check_key(impl)) { return 0; } - if (dsa->pub_key == NULL) { + if (impl->pub_key == nullptr) { OPENSSL_PUT_ERROR(DSA, DSA_R_MISSING_PARAMETERS); return 0; } @@ -671,64 +632,69 @@ int DSA_do_check_signature(int *out_valid, const uint8_t *digest, BN_init(&t1); BN_CTX *ctx = BN_CTX_new(); { - if (ctx == NULL) { + if (ctx == nullptr) { goto err; } if (BN_is_zero(sig->r) || BN_is_negative(sig->r) || - BN_ucmp(sig->r, dsa->q) >= 0) { + BN_ucmp(sig->r, impl->q.get()) >= 0) { ret = 1; goto err; } if (BN_is_zero(sig->s) || BN_is_negative(sig->s) || - BN_ucmp(sig->s, dsa->q) >= 0) { + BN_ucmp(sig->s, impl->q.get()) >= 0) { ret = 1; goto err; } - // Calculate W = inv(S) mod Q - // save W in u2 - if (BN_mod_inverse(&u2, sig->s, dsa->q, ctx) == NULL) { + if (!BN_MONT_CTX_set_locked(&impl->method_mont_p, &impl->method_mont_lock, + impl->p.get(), ctx) || + !BN_MONT_CTX_set_locked(&impl->method_mont_q, &impl->method_mont_lock, + impl->q.get(), ctx)) { + goto err; + } + + // Calculate W = inv(S) mod Q, in the Montgomery domain. This is slightly + // more efficiently computed as FromMont(s)^-1 = (s * R^-1)^-1 = s^-1 * R, + // instead of ToMont(s^-1) = s^-1 * R. + if (!BN_from_montgomery(&u2, sig->s, impl->method_mont_q.get(), ctx) || + !BN_mod_inverse(&u2, &u2, impl->q.get(), ctx)) { goto err; } // save M in u1 - unsigned q_bits = BN_num_bits(dsa->q); + unsigned q_bits = BN_num_bits(impl->q.get()); if (digest_len > (q_bits >> 3)) { // if the digest length is greater than the size of q use the - // BN_num_bits(dsa->q) leftmost bits of the digest, see + // BN_num_bits(impl->q) leftmost bits of the digest, see // fips 186-3, 4.2 digest_len = (q_bits >> 3); } - if (BN_bin2bn(digest, digest_len, &u1) == NULL) { + if (BN_bin2bn(digest, digest_len, &u1) == nullptr) { goto err; } - // u1 = M * w mod q - if (!BN_mod_mul(&u1, &u1, &u2, dsa->q, ctx)) { + // u1 = M * w mod q. w was stored in the Montgomery domain while M was not, + // so the result will already be out of the Montgomery domain. + if (!BN_mod_mul_montgomery(&u1, &u1, &u2, impl->method_mont_q.get(), ctx)) { goto err; } - // u2 = r * w mod q - if (!BN_mod_mul(&u2, sig->r, &u2, dsa->q, ctx)) { + // u2 = r * w mod q. w was stored in the Montgomery domain while r was not, + // so the result will already be out of the Montgomery domain. + if (!BN_mod_mul_montgomery(&u2, sig->r, &u2, impl->method_mont_q.get(), + ctx)) { goto err; } - if (!BN_MONT_CTX_set_locked((BN_MONT_CTX **)&dsa->method_mont_p, - (CRYPTO_MUTEX *)&dsa->method_mont_lock, dsa->p, - ctx)) { + if (!BN_mod_exp2_mont(&t1, impl->g.get(), &u1, impl->pub_key.get(), &u2, + impl->p.get(), ctx, impl->method_mont_p.get())) { goto err; } - if (!BN_mod_exp2_mont(&t1, dsa->g, &u1, dsa->pub_key, &u2, dsa->p, ctx, - dsa->method_mont_p)) { - goto err; - } - - // BN_copy(&u1,&t1); // let u1 = u1 mod q - if (!BN_mod(&u1, &t1, dsa->q, ctx)) { + if (!BN_mod(&u1, &t1, impl->q.get(), ctx)) { goto err; } @@ -752,10 +718,8 @@ err: int DSA_sign(int type, const uint8_t *digest, size_t digest_len, uint8_t *out_sig, unsigned int *out_siglen, const DSA *dsa) { - DSA_SIG *s; - - s = DSA_do_sign(digest, digest_len, dsa); - if (s == NULL) { + DSA_SIG *s = DSA_do_sign(digest, digest_len, dsa); + if (s == nullptr) { *out_siglen = 0; return 0; } @@ -777,18 +741,19 @@ int DSA_verify(int type, const uint8_t *digest, size_t digest_len, int DSA_check_signature(int *out_valid, const uint8_t *digest, size_t digest_len, const uint8_t *sig, size_t sig_len, const DSA *dsa) { - DSA_SIG *s = NULL; + *out_valid = 0; + DSA_SIG *s = nullptr; int ret = 0; - uint8_t *der = NULL; + uint8_t *der = nullptr; s = DSA_SIG_new(); { - if (s == NULL) { + if (s == nullptr) { goto err; } const uint8_t *sigp = sig; - if (d2i_DSA_SIG(&s, &sigp, sig_len) == NULL || sigp != sig + sig_len) { + if (d2i_DSA_SIG(&s, &sigp, sig_len) == nullptr || sigp != sig + sig_len) { goto err; } @@ -808,7 +773,7 @@ err: return ret; } -// der_len_len returns the number of bytes needed to represent a length of |len| +// der_len_len returns the number of bytes needed to represent a length of `len` // in DER. static size_t der_len_len(size_t len) { if (len < 0x80) { @@ -823,12 +788,14 @@ static size_t der_len_len(size_t len) { } int DSA_size(const DSA *dsa) { - if (dsa->q == NULL) { + auto *impl = FromOpaque(dsa); + + if (impl->q == nullptr) { return 0; } - size_t order_len = BN_num_bytes(dsa->q); - // Compute the maximum length of an |order_len| byte integer. Defensively + size_t order_len = BN_num_bytes(impl->q.get()); + // Compute the maximum length of an `order_len` byte integer. Defensively // assume that the leading 0x00 is included. size_t integer_len = 1 /* tag */ + der_len_len(order_len + 1) + 1 + order_len; if (integer_len < order_len) { @@ -847,51 +814,49 @@ int DSA_size(const DSA *dsa) { return ret; } -static int dsa_sign_setup(const DSA *dsa, BN_CTX *ctx, BIGNUM **out_kinv, +static int dsa_sign_setup(const DSAImpl *dsa, BN_CTX *ctx, BIGNUM **out_kinv, BIGNUM **out_r) { int ret = 0; BIGNUM k; BN_init(&k); BIGNUM *r = BN_new(); BIGNUM *kinv = BN_new(); - if (r == NULL || kinv == NULL || + if (r == nullptr || kinv == nullptr || // Get random k - !BN_rand_range_ex(&k, 1, dsa->q) || - !BN_MONT_CTX_set_locked((BN_MONT_CTX **)&dsa->method_mont_p, - (CRYPTO_MUTEX *)&dsa->method_mont_lock, dsa->p, - ctx) || - !BN_MONT_CTX_set_locked((BN_MONT_CTX **)&dsa->method_mont_q, - (CRYPTO_MUTEX *)&dsa->method_mont_lock, dsa->q, - ctx) || + !BN_rand_range_ex(&k, 1, dsa->q.get()) || + !BN_MONT_CTX_set_locked(&dsa->method_mont_p, &dsa->method_mont_lock, + dsa->p.get(), ctx) || + !BN_MONT_CTX_set_locked(&dsa->method_mont_q, &dsa->method_mont_lock, + dsa->q.get(), ctx) || // Compute r = (g^k mod p) mod q - !BN_mod_exp_mont_consttime(r, dsa->g, &k, dsa->p, ctx, - dsa->method_mont_p)) { + !BN_mod_exp_mont_consttime(r, dsa->g.get(), &k, dsa->p.get(), ctx, + dsa->method_mont_p.get())) { OPENSSL_PUT_ERROR(DSA, ERR_R_BN_LIB); goto err; } - // Note |BN_mod| below is not constant-time and may leak information about - // |r|. |dsa->p| may be significantly larger than |dsa->q|, so this is not + // Note `BN_mod` below is not constant-time and may leak information about + // `r`. `dsa->p` may be significantly larger than `dsa->q`, so this is not // easily performed in constant-time with Montgomery reduction. // - // However, |r| at this point is g^k (mod p). It is almost the value of |r| + // However, `r` at this point is g^k (mod p). It is almost the value of `r` // revealed in the signature anyway (g^k (mod p) (mod q)), going from it to - // |k| would require computing a discrete log. + // `k` would require computing a discrete log. bn_declassify(r); - if (!BN_mod(r, r, dsa->q, ctx) || + 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, ctx, dsa->method_mont_q)) { + !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; } BN_clear_free(*out_kinv); *out_kinv = kinv; - kinv = NULL; + kinv = nullptr; BN_clear_free(*out_r); *out_r = r; - r = NULL; + r = nullptr; ret = 1; @@ -908,39 +873,50 @@ int DSA_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused, } int DSA_set_ex_data(DSA *dsa, int idx, void *arg) { - return CRYPTO_set_ex_data(&dsa->ex_data, idx, arg); + auto *impl = FromOpaque(dsa); + return CRYPTO_set_ex_data(&impl->ex_data, idx, arg); } void *DSA_get_ex_data(const DSA *dsa, int idx) { - return CRYPTO_get_ex_data(&dsa->ex_data, idx); + auto *impl = FromOpaque(dsa); + return CRYPTO_get_ex_data(&impl->ex_data, idx); +} + +static bool copy_bn(UniquePtr *dst, const BIGNUM *src) { + UniquePtr copy; + if (src) { + copy.reset(BN_dup(src)); + if (!copy) { + return false; + } + } + *dst = std::move(copy); + return true; } DH *DSA_dup_DH(const DSA *dsa) { - if (dsa == NULL) { - return NULL; + auto *impl = FromOpaque(dsa); + if (dsa == nullptr) { + return nullptr; } - DH *ret = DH_new(); - if (ret == NULL) { - goto err; + UniquePtr ret(DH_new()); + auto *dh = FromOpaque(ret.get()); + if (ret == nullptr) { + return nullptr; } - if (dsa->q != NULL) { - ret->priv_length = BN_num_bits(dsa->q); - if ((ret->q = BN_dup(dsa->q)) == NULL) { - goto err; + if (impl->q != nullptr) { + dh->priv_length = BN_num_bits(impl->q.get()); + if (!copy_bn(&dh->q, impl->q.get())) { + return nullptr; } } - if ((dsa->p != NULL && (ret->p = BN_dup(dsa->p)) == NULL) || - (dsa->g != NULL && (ret->g = BN_dup(dsa->g)) == NULL) || - (dsa->pub_key != NULL && (ret->pub_key = BN_dup(dsa->pub_key)) == NULL) || - (dsa->priv_key != NULL && - (ret->priv_key = BN_dup(dsa->priv_key)) == NULL)) { - goto err; + if (!copy_bn(&dh->p, impl->p.get()) || // + !copy_bn(&dh->g, impl->g.get()) || // + !copy_bn(&dh->pub_key, impl->pub_key.get()) || // + !copy_bn(&dh->priv_key, impl->priv_key.get())) { + return nullptr; } - return ret; - -err: - DH_free(ret); - return NULL; + return ret.release(); } diff --git a/Sources/CNIOBoringSSL/crypto/dsa/dsa_asn1.cc b/Sources/CNIOBoringSSL/crypto/dsa/dsa_asn1.cc index 3c674c80..6b8dc30f 100644 --- a/Sources/CNIOBoringSSL/crypto/dsa/dsa_asn1.cc +++ b/Sources/CNIOBoringSSL/crypto/dsa/dsa_asn1.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,65 +21,70 @@ #include #include -#include "internal.h" #include "../bytestring/internal.h" +#include "../mem_internal.h" +#include "internal.h" +using namespace bssl; + // This function is in dsa_asn1.c rather than dsa.c because it is reachable from -// |EVP_PKEY| parsers. This makes it easier for the static linker to drop most +// `EVP_PKEY` parsers. This makes it easier for the static linker to drop most // of the DSA implementation. -int dsa_check_key(const DSA *dsa) { +int bssl::dsa_check_key(const DSAImpl *dsa) { if (!dsa->p || !dsa->q || !dsa->g) { OPENSSL_PUT_ERROR(DSA, DSA_R_MISSING_PARAMETERS); return 0; } // Fully checking for invalid DSA groups is expensive, so security and - // correctness of the signature scheme depend on how |dsa| was computed. I.e. + // correctness of the signature scheme depend on how `dsa` was computed. I.e. // we leave "assurance of domain parameter validity" from FIPS 186-4 to the // caller. However, we check bounds on all values to avoid DoS vectors even // when domain parameters are invalid. In particular, signing will infinite - // loop if |g| is zero. - if (BN_is_negative(dsa->p) || BN_is_negative(dsa->q) || BN_is_zero(dsa->p) || - BN_is_zero(dsa->q) || !BN_is_odd(dsa->p) || !BN_is_odd(dsa->q) || - // |q| must be a prime divisor of |p - 1|, which implies |q < p|. - BN_cmp(dsa->q, dsa->p) >= 0 || - // |g| is in the multiplicative group of |p|. - BN_is_negative(dsa->g) || BN_is_zero(dsa->g) || - BN_cmp(dsa->g, dsa->p) >= 0) { + // loop if `g` is zero. + if (BN_is_negative(dsa->p.get()) || BN_is_negative(dsa->q.get()) || + BN_is_zero(dsa->p.get()) || BN_is_zero(dsa->q.get()) || + !BN_is_odd(dsa->p.get()) || !BN_is_odd(dsa->q.get()) || + // `q` must be a prime divisor of `p - 1`, which implies `q < p`. + BN_cmp(dsa->q.get(), dsa->p.get()) >= 0 || + // `g` is in the multiplicative group of `p`. + BN_is_negative(dsa->g.get()) || BN_is_zero(dsa->g.get()) || + BN_cmp(dsa->g.get(), dsa->p.get()) >= 0) { OPENSSL_PUT_ERROR(DSA, DSA_R_INVALID_PARAMETERS); return 0; } // FIPS 186-4 allows only three different sizes for q. - unsigned q_bits = BN_num_bits(dsa->q); + unsigned q_bits = BN_num_bits(dsa->q.get()); if (q_bits != 160 && q_bits != 224 && q_bits != 256) { OPENSSL_PUT_ERROR(DSA, DSA_R_BAD_Q_VALUE); return 0; } - // Bound |dsa->p| to avoid a DoS vector. Note this limit is much larger than + // Bound `dsa->p` to avoid a DoS vector. Note this limit is much larger than // the one in FIPS 186-4, which only allows L = 1024, 2048, and 3072. - if (BN_num_bits(dsa->p) > OPENSSL_DSA_MAX_MODULUS_BITS) { + if (BN_num_bits(dsa->p.get()) > OPENSSL_DSA_MAX_MODULUS_BITS) { OPENSSL_PUT_ERROR(DSA, DSA_R_MODULUS_TOO_LARGE); return 0; } - if (dsa->pub_key != NULL) { - // The public key is also in the multiplicative group of |p|. - if (BN_is_negative(dsa->pub_key) || BN_is_zero(dsa->pub_key) || - BN_cmp(dsa->pub_key, dsa->p) >= 0) { + if (dsa->pub_key != nullptr) { + // The public key is also in the multiplicative group of `p`. + if (BN_is_negative(dsa->pub_key.get()) || BN_is_zero(dsa->pub_key.get()) || + BN_cmp(dsa->pub_key.get(), dsa->p.get()) >= 0) { OPENSSL_PUT_ERROR(DSA, DSA_R_INVALID_PARAMETERS); return 0; } } - if (dsa->priv_key != NULL) { + if (dsa->priv_key != nullptr) { // The private key is a non-zero element of the scalar field, determined by - // |q|. - if (BN_is_negative(dsa->priv_key) || - constant_time_declassify_int(BN_is_zero(dsa->priv_key)) || - constant_time_declassify_int(BN_cmp(dsa->priv_key, dsa->q) >= 0)) { + // `q`. + if (BN_is_negative(dsa->priv_key.get()) || + constant_time_declassify_int(BN_is_zero(dsa->priv_key.get())) || + constant_time_declassify_int( + BN_cmp(dsa->priv_key.get(), dsa->q.get()) >= 0)) { OPENSSL_PUT_ERROR(DSA, DSA_R_INVALID_PARAMETERS); return 0; } @@ -83,17 +93,17 @@ int dsa_check_key(const DSA *dsa) { return 1; } -static int parse_integer(CBS *cbs, BIGNUM **out) { - assert(*out == NULL); - *out = BN_new(); - if (*out == NULL) { +static int parse_integer(CBS *cbs, UniquePtr *out) { + assert(*out == nullptr); + out->reset(BN_new()); + if (*out == nullptr) { return 0; } - return BN_parse_asn1_unsigned(cbs, *out); + return BN_parse_asn1_unsigned(cbs, out->get()); } static int marshal_integer(CBB *cbb, BIGNUM *bn) { - if (bn == NULL) { + if (bn == nullptr) { // A DSA object may be missing some components. OPENSSL_PUT_ERROR(DSA, ERR_R_PASSED_NULL_PARAMETER); return 0; @@ -103,18 +113,21 @@ static int marshal_integer(CBB *cbb, BIGNUM *bn) { DSA_SIG *DSA_SIG_parse(CBS *cbs) { DSA_SIG *ret = DSA_SIG_new(); - if (ret == NULL) { - return NULL; + if (ret == nullptr) { + return nullptr; } CBS child; + UniquePtr r, s; if (!CBS_get_asn1(cbs, &child, CBS_ASN1_SEQUENCE) || - !parse_integer(&child, &ret->r) || - !parse_integer(&child, &ret->s) || + !parse_integer(&child, &r) || + !parse_integer(&child, &s) || CBS_len(&child) != 0) { OPENSSL_PUT_ERROR(DSA, DSA_R_DECODE_ERROR); DSA_SIG_free(ret); - return NULL; + return nullptr; } + ret->r = r.release(); + ret->s = s.release(); return ret; } @@ -131,9 +144,9 @@ int DSA_SIG_marshal(CBB *cbb, const DSA_SIG *sig) { } DSA *DSA_parse_public_key(CBS *cbs) { - DSA *ret = DSA_new(); - if (ret == NULL) { - return NULL; + UniquePtr ret(FromOpaque(DSA_new())); + if (ret == nullptr) { + return nullptr; } CBS child; if (!CBS_get_asn1(cbs, &child, CBS_ASN1_SEQUENCE) || @@ -143,26 +156,23 @@ DSA *DSA_parse_public_key(CBS *cbs) { !parse_integer(&child, &ret->g) || CBS_len(&child) != 0) { OPENSSL_PUT_ERROR(DSA, DSA_R_DECODE_ERROR); - goto err; + return nullptr; } - if (!dsa_check_key(ret)) { - goto err; + if (!dsa_check_key(ret.get())) { + return nullptr; } - return ret; - -err: - DSA_free(ret); - return NULL; + return ret.release(); } int DSA_marshal_public_key(CBB *cbb, const DSA *dsa) { + const auto *impl = FromOpaque(dsa); + CBB child; if (!CBB_add_asn1(cbb, &child, CBS_ASN1_SEQUENCE) || - !marshal_integer(&child, dsa->pub_key) || - !marshal_integer(&child, dsa->p) || - !marshal_integer(&child, dsa->q) || - !marshal_integer(&child, dsa->g) || - !CBB_flush(cbb)) { + !marshal_integer(&child, impl->pub_key.get()) || + !marshal_integer(&child, impl->p.get()) || + !marshal_integer(&child, impl->q.get()) || + !marshal_integer(&child, impl->g.get()) || !CBB_flush(cbb)) { OPENSSL_PUT_ERROR(DSA, DSA_R_ENCODE_ERROR); return 0; } @@ -170,9 +180,9 @@ int DSA_marshal_public_key(CBB *cbb, const DSA *dsa) { } DSA *DSA_parse_parameters(CBS *cbs) { - DSA *ret = DSA_new(); - if (ret == NULL) { - return NULL; + UniquePtr ret(FromOpaque(DSA_new())); + if (ret == nullptr) { + return nullptr; } CBS child; if (!CBS_get_asn1(cbs, &child, CBS_ASN1_SEQUENCE) || @@ -181,25 +191,22 @@ DSA *DSA_parse_parameters(CBS *cbs) { !parse_integer(&child, &ret->g) || CBS_len(&child) != 0) { OPENSSL_PUT_ERROR(DSA, DSA_R_DECODE_ERROR); - goto err; + return nullptr; } - if (!dsa_check_key(ret)) { - goto err; + if (!dsa_check_key(ret.get())) { + return nullptr; } - return ret; - -err: - DSA_free(ret); - return NULL; + return ret.release(); } int DSA_marshal_parameters(CBB *cbb, const DSA *dsa) { + const auto *impl = FromOpaque(dsa); + CBB child; if (!CBB_add_asn1(cbb, &child, CBS_ASN1_SEQUENCE) || - !marshal_integer(&child, dsa->p) || - !marshal_integer(&child, dsa->q) || - !marshal_integer(&child, dsa->g) || - !CBB_flush(cbb)) { + !marshal_integer(&child, impl->p.get()) || + !marshal_integer(&child, impl->q.get()) || + !marshal_integer(&child, impl->g.get()) || !CBB_flush(cbb)) { OPENSSL_PUT_ERROR(DSA, DSA_R_ENCODE_ERROR); return 0; } @@ -207,9 +214,9 @@ int DSA_marshal_parameters(CBB *cbb, const DSA *dsa) { } DSA *DSA_parse_private_key(CBS *cbs) { - DSA *ret = DSA_new(); - if (ret == NULL) { - return NULL; + UniquePtr ret(FromOpaque(DSA_new())); + if (ret == nullptr) { + return nullptr; } CBS child; @@ -217,12 +224,12 @@ DSA *DSA_parse_private_key(CBS *cbs) { if (!CBS_get_asn1(cbs, &child, CBS_ASN1_SEQUENCE) || !CBS_get_asn1_uint64(&child, &version)) { OPENSSL_PUT_ERROR(DSA, DSA_R_DECODE_ERROR); - goto err; + return nullptr; } if (version != 0) { OPENSSL_PUT_ERROR(DSA, DSA_R_BAD_VERSION); - goto err; + return nullptr; } if (!parse_integer(&child, &ret->p) || @@ -232,29 +239,26 @@ DSA *DSA_parse_private_key(CBS *cbs) { !parse_integer(&child, &ret->priv_key) || CBS_len(&child) != 0) { OPENSSL_PUT_ERROR(DSA, DSA_R_DECODE_ERROR); - goto err; + return nullptr; } - if (!dsa_check_key(ret)) { - goto err; + if (!dsa_check_key(ret.get())) { + return nullptr; } - return ret; - -err: - DSA_free(ret); - return NULL; + return ret.release(); } int DSA_marshal_private_key(CBB *cbb, const DSA *dsa) { + const auto *impl = FromOpaque(dsa); + CBB child; if (!CBB_add_asn1(cbb, &child, CBS_ASN1_SEQUENCE) || !CBB_add_asn1_uint64(&child, 0 /* version */) || - !marshal_integer(&child, dsa->p) || - !marshal_integer(&child, dsa->q) || - !marshal_integer(&child, dsa->g) || - !marshal_integer(&child, dsa->pub_key) || - !marshal_integer(&child, dsa->priv_key) || - !CBB_flush(cbb)) { + !marshal_integer(&child, impl->p.get()) || + !marshal_integer(&child, impl->q.get()) || + !marshal_integer(&child, impl->g.get()) || + !marshal_integer(&child, impl->pub_key.get()) || + !marshal_integer(&child, impl->priv_key.get()) || !CBB_flush(cbb)) { OPENSSL_PUT_ERROR(DSA, DSA_R_ENCODE_ERROR); return 0; } @@ -262,113 +266,41 @@ int DSA_marshal_private_key(CBB *cbb, const DSA *dsa) { } DSA_SIG *d2i_DSA_SIG(DSA_SIG **out_sig, const uint8_t **inp, long len) { - if (len < 0) { - return NULL; - } - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - DSA_SIG *ret = DSA_SIG_parse(&cbs); - if (ret == NULL) { - return NULL; - } - if (out_sig != NULL) { - DSA_SIG_free(*out_sig); - *out_sig = ret; - } - *inp = CBS_data(&cbs); - return ret; + return D2IFromCBS(out_sig, inp, len, DSA_SIG_parse); } int i2d_DSA_SIG(const DSA_SIG *in, uint8_t **outp) { - CBB cbb; - if (!CBB_init(&cbb, 0) || - !DSA_SIG_marshal(&cbb, in)) { - CBB_cleanup(&cbb); - return -1; - } - return CBB_finish_i2d(&cbb, outp); + return I2DFromCBB( + /*initial_capacity=*/256, outp, + [&](CBB *cbb) -> bool { return DSA_SIG_marshal(cbb, in); }); } DSA *d2i_DSAPublicKey(DSA **out, const uint8_t **inp, long len) { - if (len < 0) { - return NULL; - } - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - DSA *ret = DSA_parse_public_key(&cbs); - if (ret == NULL) { - return NULL; - } - if (out != NULL) { - DSA_free(*out); - *out = ret; - } - *inp = CBS_data(&cbs); - return ret; + return D2IFromCBS(out, inp, len, DSA_parse_public_key); } int i2d_DSAPublicKey(const DSA *in, uint8_t **outp) { - CBB cbb; - if (!CBB_init(&cbb, 0) || - !DSA_marshal_public_key(&cbb, in)) { - CBB_cleanup(&cbb); - return -1; - } - return CBB_finish_i2d(&cbb, outp); + return I2DFromCBB( + /*initial_capacity=*/256, outp, + [&](CBB *cbb) -> bool { return DSA_marshal_public_key(cbb, in); }); } DSA *d2i_DSAPrivateKey(DSA **out, const uint8_t **inp, long len) { - if (len < 0) { - return NULL; - } - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - DSA *ret = DSA_parse_private_key(&cbs); - if (ret == NULL) { - return NULL; - } - if (out != NULL) { - DSA_free(*out); - *out = ret; - } - *inp = CBS_data(&cbs); - return ret; + return D2IFromCBS(out, inp, len, DSA_parse_private_key); } int i2d_DSAPrivateKey(const DSA *in, uint8_t **outp) { - CBB cbb; - if (!CBB_init(&cbb, 0) || - !DSA_marshal_private_key(&cbb, in)) { - CBB_cleanup(&cbb); - return -1; - } - return CBB_finish_i2d(&cbb, outp); + return I2DFromCBB( + /*initial_capacity=*/256, outp, + [&](CBB *cbb) -> bool { return DSA_marshal_private_key(cbb, in); }); } DSA *d2i_DSAparams(DSA **out, const uint8_t **inp, long len) { - if (len < 0) { - return NULL; - } - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - DSA *ret = DSA_parse_parameters(&cbs); - if (ret == NULL) { - return NULL; - } - if (out != NULL) { - DSA_free(*out); - *out = ret; - } - *inp = CBS_data(&cbs); - return ret; + return D2IFromCBS(out, inp, len, DSA_parse_parameters); } int i2d_DSAparams(const DSA *in, uint8_t **outp) { - CBB cbb; - if (!CBB_init(&cbb, 0) || - !DSA_marshal_parameters(&cbb, in)) { - CBB_cleanup(&cbb); - return -1; - } - return CBB_finish_i2d(&cbb, outp); + return I2DFromCBB( + /*initial_capacity=*/256, outp, + [&](CBB *cbb) -> bool { return DSA_marshal_parameters(cbb, in); }); } diff --git a/Sources/CNIOBoringSSL/crypto/dsa/internal.h b/Sources/CNIOBoringSSL/crypto/dsa/internal.h index 0ef73eaa..0b9689db 100644 --- a/Sources/CNIOBoringSSL/crypto/dsa/internal.h +++ b/Sources/CNIOBoringSSL/crypto/dsa/internal.h @@ -1,54 +1,56 @@ -/* Copyright 2020 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2020 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. -#ifndef OPENSSL_HEADER_DSA_INTERNAL_H -#define OPENSSL_HEADER_DSA_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_DSA_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_DSA_INTERNAL_H #include -#include - #include "../internal.h" - -#if defined(__cplusplus) -extern "C" { -#endif +#include "../mem_internal.h" -struct dsa_st { - BIGNUM *p; - BIGNUM *q; - BIGNUM *g; +DECLARE_OPAQUE_STRUCT(dsa_st, DSAImpl) - BIGNUM *pub_key; - BIGNUM *priv_key; +BSSL_NAMESPACE_BEGIN + +class DSAImpl : public dsa_st, public RefCounted { + public: + DSAImpl(); + + UniquePtr p; + UniquePtr q; + UniquePtr g; + + UniquePtr pub_key; + UniquePtr priv_key; // Normally used to cache montgomery values - CRYPTO_MUTEX method_mont_lock; - BN_MONT_CTX *method_mont_p; - BN_MONT_CTX *method_mont_q; - CRYPTO_refcount_t references; + mutable Mutex method_mont_lock; + mutable UniquePtr method_mont_p; + mutable UniquePtr method_mont_q; CRYPTO_EX_DATA ex_data; + + private: + friend RefCounted; + ~DSAImpl(); }; -// dsa_check_key performs cheap self-checks on |dsa|, and ensures it is within +// dsa_check_key performs cheap self-checks on `dsa`, and ensures it is within // DoS bounds. It returns one on success and zero on error. -int dsa_check_key(const DSA *dsa); +int dsa_check_key(const DSAImpl *dsa); +BSSL_NAMESPACE_END -#if defined(__cplusplus) -} // extern C -#endif - -#endif // OPENSSL_HEADER_DSA_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_DSA_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/ec/ec_asn1.cc b/Sources/CNIOBoringSSL/crypto/ec/ec_asn1.cc index 3e631aaf..a7fa697e 100644 --- a/Sources/CNIOBoringSSL/crypto/ec/ec_asn1.cc +++ b/Sources/CNIOBoringSSL/crypto/ec/ec_asn1.cc @@ -1,19 +1,28 @@ -/* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -21,24 +30,34 @@ #include "../bytestring/internal.h" #include "../fipsmodule/ec/internal.h" #include "../internal.h" +#include "../mem_internal.h" +#include "internal.h" +using namespace bssl; + static const CBS_ASN1_TAG kParametersTag = CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0; static const CBS_ASN1_TAG kPublicKeyTag = CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 1; -// TODO(https://crbug.com/boringssl/497): Allow parsers to specify a list of -// acceptable groups, so parsers don't have to pull in all four. -typedef const EC_GROUP *(*ec_group_func)(void); -static const ec_group_func kAllGroups[] = { - &EC_group_p224, - &EC_group_p256, - &EC_group_p384, - &EC_group_p521, -}; +static auto get_all_groups() { + return std::array{ + EC_group_p224(), + EC_group_p256(), + EC_group_p384(), + EC_group_p521(), + }; +} + +EC_KEY *bssl::ec_key_parse_private_key( + CBS *cbs, const EC_GROUP *group, + Span allowed_groups) { + // If a group was supplied externally, no other groups can be parsed. + if (group != nullptr) { + allowed_groups = Span(&group, 1); + } -EC_KEY *EC_KEY_parse_private_key(CBS *cbs, const EC_GROUP *group) { CBS ec_private_key, private_key; uint64_t version; if (!CBS_get_asn1(cbs, &ec_private_key, CBS_ASN1_SEQUENCE) || @@ -46,12 +65,10 @@ EC_KEY *EC_KEY_parse_private_key(CBS *cbs, const EC_GROUP *group) { version != 1 || !CBS_get_asn1(&ec_private_key, &private_key, CBS_ASN1_OCTETSTRING)) { OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR); - return NULL; + return nullptr; } // Parse the optional parameters field. - EC_KEY *ret = NULL; - BIGNUM *priv_key = NULL; if (CBS_peek_asn1_tag(&ec_private_key, kParametersTag)) { // Per SEC 1, as an alternative to omitting it, one is allowed to specify // this field and put in a NULL to mean inheriting this value. This was @@ -60,43 +77,52 @@ EC_KEY *EC_KEY_parse_private_key(CBS *cbs, const EC_GROUP *group) { CBS child; if (!CBS_get_asn1(&ec_private_key, &child, kParametersTag)) { OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR); - goto err; + return nullptr; } - const EC_GROUP *inner_group = EC_KEY_parse_parameters(&child); - if (inner_group == NULL) { - goto err; - } - if (group == NULL) { - group = inner_group; - } else if (EC_GROUP_cmp(group, inner_group, NULL) != 0) { - // If a group was supplied externally, it must match. - OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH); - goto err; + const EC_GROUP *inner_group = + ec_key_parse_parameters(&child, allowed_groups); + if (inner_group == nullptr) { + // If the caller already supplied a group, any explicit group is required + // to match. On mismatch, `ec_key_parse_parameters` will fail to recognize + // any other groups, so remap the error. + if (group != nullptr && + ERR_equals(ERR_peek_last_error(), ERR_LIB_EC, EC_R_UNKNOWN_GROUP)) { + ERR_clear_error(); + OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH); + } + return nullptr; } + // Overriding `allowed_groups` above ensures the only returned group will be + // the matching one. + assert(group == nullptr || inner_group == group); + group = inner_group; if (CBS_len(&child) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR); - goto err; + return nullptr; } } - if (group == NULL) { + // The group must have been specified either externally, or explicitly in the + // structure. + if (group == nullptr) { OPENSSL_PUT_ERROR(EC, EC_R_MISSING_PARAMETERS); - goto err; + return nullptr; } - ret = EC_KEY_new(); - if (ret == NULL || !EC_KEY_set_group(ret, group)) { - goto err; + UniquePtr ret(FromOpaque(EC_KEY_new())); + if (ret == nullptr || !EC_KEY_set_group(ret.get(), group)) { + return nullptr; } // Although RFC 5915 specifies the length of the key, OpenSSL historically // got this wrong, so accept any length. See upstream's // 30cd4ff294252c4b6a4b69cbef6a5b4117705d22. - priv_key = BN_bin2bn(CBS_data(&private_key), CBS_len(&private_key), NULL); + UniquePtr priv_key( + BN_bin2bn(CBS_data(&private_key), CBS_len(&private_key), nullptr)); ret->pub_key = EC_POINT_new(group); - if (priv_key == NULL || ret->pub_key == NULL || - !EC_KEY_set_private_key(ret, priv_key)) { - goto err; + if (priv_key == nullptr || ret->pub_key == nullptr || + !EC_KEY_set_private_key(ret.get(), priv_key.get())) { + return nullptr; } if (CBS_peek_asn1_tag(&ec_private_key, kPublicKeyTag)) { @@ -108,14 +134,14 @@ EC_KEY *EC_KEY_parse_private_key(CBS *cbs, const EC_GROUP *group) { // encoded as a BIT STRING with bits ordered as in the DER encoding. !CBS_get_u8(&public_key, &padding) || // padding != 0 || - // Explicitly check |public_key| is non-empty to save the conversion + // Explicitly check `public_key` is non-empty to save the conversion // form later. CBS_len(&public_key) == 0 || !EC_POINT_oct2point(group, ret->pub_key, CBS_data(&public_key), - CBS_len(&public_key), NULL) || + CBS_len(&public_key), nullptr) || CBS_len(&child) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR); - goto err; + return nullptr; } // Save the point conversion form. @@ -126,7 +152,7 @@ EC_KEY *EC_KEY_parse_private_key(CBS *cbs, const EC_GROUP *group) { // Compute the public key instead. if (!ec_point_mul_scalar_base(group, &ret->pub_key->raw, &ret->priv_key->scalar)) { - goto err; + return nullptr; } // Remember the original private-key-only encoding. // TODO(davidben): Consider removing this. @@ -135,26 +161,26 @@ EC_KEY *EC_KEY_parse_private_key(CBS *cbs, const EC_GROUP *group) { if (CBS_len(&ec_private_key) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR); - goto err; + return nullptr; } // Ensure the resulting key is valid. - if (!EC_KEY_check_key(ret)) { - goto err; + if (!EC_KEY_check_key(ret.get())) { + return nullptr; } - BN_free(priv_key); - return ret; + return ret.release(); +} -err: - EC_KEY_free(ret); - BN_free(priv_key); - return NULL; +EC_KEY *EC_KEY_parse_private_key(CBS *cbs, const EC_GROUP *group) { + return ec_key_parse_private_key(cbs, group, get_all_groups()); } int EC_KEY_marshal_private_key(CBB *cbb, const EC_KEY *key, unsigned enc_flags) { - if (key == NULL || key->group == NULL || key->priv_key == NULL) { + const ECKey *key_impl = FromOpaque(key); + if (key_impl == nullptr || key_impl->group == nullptr || + key_impl->priv_key == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } @@ -164,8 +190,8 @@ int EC_KEY_marshal_private_key(CBB *cbb, const EC_KEY *key, !CBB_add_asn1_uint64(&ec_private_key, 1 /* version */) || !CBB_add_asn1(&ec_private_key, &private_key, CBS_ASN1_OCTETSTRING) || !BN_bn2cbb_padded(&private_key, - BN_num_bytes(EC_GROUP_get0_order(key->group)), - EC_KEY_get0_private_key(key))) { + BN_num_bytes(EC_GROUP_get0_order(key_impl->group)), + EC_KEY_get0_private_key(key_impl))) { OPENSSL_PUT_ERROR(EC, EC_R_ENCODE_ERROR); return 0; } @@ -173,7 +199,7 @@ int EC_KEY_marshal_private_key(CBB *cbb, const EC_KEY *key, if (!(enc_flags & EC_PKEY_NO_PARAMETERS)) { CBB child; if (!CBB_add_asn1(&ec_private_key, &child, kParametersTag) || - !EC_KEY_marshal_curve_name(&child, key->group) || + !EC_KEY_marshal_curve_name(&child, key_impl->group) || !CBB_flush(&ec_private_key)) { OPENSSL_PUT_ERROR(EC, EC_R_ENCODE_ERROR); return 0; @@ -181,15 +207,15 @@ int EC_KEY_marshal_private_key(CBB *cbb, const EC_KEY *key, } // TODO(fork): replace this flexibility with sensible default? - if (!(enc_flags & EC_PKEY_NO_PUBKEY) && key->pub_key != NULL) { + if (!(enc_flags & EC_PKEY_NO_PUBKEY) && key_impl->pub_key != nullptr) { CBB child, public_key; if (!CBB_add_asn1(&ec_private_key, &child, kPublicKeyTag) || !CBB_add_asn1(&child, &public_key, CBS_ASN1_BITSTRING) || // As in a SubjectPublicKeyInfo, the byte-encoded public key is then // encoded as a BIT STRING with bits ordered as in the DER encoding. !CBB_add_u8(&public_key, 0 /* padding */) || - !EC_POINT_point2cbb(&public_key, key->group, key->pub_key, - key->conv_form, NULL) || + !EC_POINT_point2cbb(&public_key, key_impl->group, key_impl->pub_key, + key_impl->conv_form, nullptr) || !CBB_flush(&ec_private_key)) { OPENSSL_PUT_ERROR(EC, EC_R_ENCODE_ERROR); return 0; @@ -234,8 +260,8 @@ static int parse_explicit_prime_curve(CBS *in, !CBS_get_asn1(¶ms, &curve, CBS_ASN1_SEQUENCE) || !CBS_get_asn1(&curve, &out->a, CBS_ASN1_OCTETSTRING) || !CBS_get_asn1(&curve, &out->b, CBS_ASN1_OCTETSTRING) || - // |curve| has an optional BIT STRING seed which we ignore. - !CBS_get_optional_asn1(&curve, NULL, NULL, CBS_ASN1_BITSTRING) || + // `curve` has an optional BIT STRING seed which we ignore. + !CBS_get_optional_asn1(&curve, nullptr, nullptr, CBS_ASN1_BITSTRING) || CBS_len(&curve) != 0 || !CBS_get_asn1(¶ms, &base, CBS_ASN1_OCTETSTRING) || !CBS_get_asn1(¶ms, &out->order, CBS_ASN1_INTEGER) || @@ -274,12 +300,12 @@ static int parse_explicit_prime_curve(CBS *in, return 1; } -// integers_equal returns one if |bytes| is a big-endian encoding of |bn|, and +// integers_equal returns one if `bytes` is a big-endian encoding of `bn`, and // zero otherwise. static int integers_equal(const CBS *bytes, const BIGNUM *bn) { // Although, in SEC 1, Field-Element-to-Octet-String has a fixed width, - // OpenSSL mis-encodes the |a| and |b|, so we tolerate any number of leading - // zeros. (This matters for P-521 whose |b| has a leading 0.) + // OpenSSL mis-encodes the `a` and `b`, so we tolerate any number of leading + // zeros. (This matters for P-521 whose `b` has a leading 0.) CBS copy = *bytes; while (CBS_len(©) > 0 && CBS_data(©)[0] == 0) { CBS_skip(©, 1); @@ -297,23 +323,29 @@ static int integers_equal(const CBS *bytes, const BIGNUM *bn) { return CBS_mem_equal(©, buf, CBS_len(©)); } -EC_GROUP *EC_KEY_parse_curve_name(CBS *cbs) { +const EC_GROUP *bssl::ec_key_parse_curve_name( + CBS *cbs, Span allowed_groups) { CBS named_curve; if (!CBS_get_asn1(cbs, &named_curve, CBS_ASN1_OBJECT)) { OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR); - return NULL; + return nullptr; } // Look for a matching curve. - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kAllGroups); i++) { - const EC_GROUP *group = kAllGroups[i](); - if (CBS_mem_equal(&named_curve, group->oid, group->oid_len)) { - return (EC_GROUP *)group; + for (const EC_GROUP *group : allowed_groups) { + if (named_curve == Span(group->oid, group->oid_len)) { + return group; } } OPENSSL_PUT_ERROR(EC, EC_R_UNKNOWN_GROUP); - return NULL; + return nullptr; +} + +EC_GROUP *EC_KEY_parse_curve_name(CBS *cbs) { + // This function only ever returns a static `EC_GROUP`, but currently returns + // a non-const pointer for historical reasons. + return const_cast(ec_key_parse_curve_name(cbs, get_all_groups())); } int EC_KEY_marshal_curve_name(CBB *cbb, const EC_GROUP *group) { @@ -322,15 +354,13 @@ int EC_KEY_marshal_curve_name(CBB *cbb, const EC_GROUP *group) { return 0; } - CBB child; - return CBB_add_asn1(cbb, &child, CBS_ASN1_OBJECT) && - CBB_add_bytes(&child, group->oid, group->oid_len) && // - CBB_flush(cbb); + return CBB_add_asn1_element(cbb, CBS_ASN1_OBJECT, group->oid, group->oid_len); } -EC_GROUP *EC_KEY_parse_parameters(CBS *cbs) { +const EC_GROUP *bssl::ec_key_parse_parameters( + CBS *cbs, Span allowed_groups) { if (!CBS_peek_asn1_tag(cbs, CBS_ASN1_SEQUENCE)) { - return EC_KEY_parse_curve_name(cbs); + return ec_key_parse_curve_name(cbs, allowed_groups); } // OpenSSL sometimes produces ECPrivateKeys with explicitly-encoded versions @@ -339,59 +369,58 @@ EC_GROUP *EC_KEY_parse_parameters(CBS *cbs) { // TODO(davidben): Remove support for this. struct explicit_prime_curve curve; if (!parse_explicit_prime_curve(cbs, &curve)) { - return NULL; + return nullptr; } - const EC_GROUP *ret = NULL; - BIGNUM *p = BN_new(), *a = BN_new(), *b = BN_new(), *x = BN_new(), - *y = BN_new(); - if (p == NULL || a == NULL || b == NULL || x == NULL || y == NULL) { - goto err; + UniquePtr p(BN_new()); + UniquePtr a(BN_new()); + UniquePtr b(BN_new()); + UniquePtr x(BN_new()); + UniquePtr y(BN_new()); + if (p == nullptr || a == nullptr || b == nullptr || x == nullptr || + y == nullptr) { + return nullptr; } - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kAllGroups); i++) { - const EC_GROUP *group = kAllGroups[i](); + for (const EC_GROUP *group : allowed_groups) { if (!integers_equal(&curve.order, EC_GROUP_get0_order(group))) { continue; } // The order alone uniquely identifies the group, but we check the other // parameters to avoid misinterpreting the group. - if (!EC_GROUP_get_curve_GFp(group, p, a, b, NULL)) { - goto err; + if (!EC_GROUP_get_curve_GFp(group, p.get(), a.get(), b.get(), nullptr)) { + return nullptr; } - if (!integers_equal(&curve.prime, p) || !integers_equal(&curve.a, a) || - !integers_equal(&curve.b, b)) { + if (!integers_equal(&curve.prime, p.get()) || + !integers_equal(&curve.a, a.get()) || + !integers_equal(&curve.b, b.get())) { break; } if (!EC_POINT_get_affine_coordinates_GFp( - group, EC_GROUP_get0_generator(group), x, y, NULL)) { - goto err; + group, EC_GROUP_get0_generator(group), x.get(), y.get(), nullptr)) { + return nullptr; } - if (!integers_equal(&curve.base_x, x) || - !integers_equal(&curve.base_y, y)) { + if (!integers_equal(&curve.base_x, x.get()) || + !integers_equal(&curve.base_y, y.get())) { break; } - ret = group; - break; + return group; } - if (ret == NULL) { - OPENSSL_PUT_ERROR(EC, EC_R_UNKNOWN_GROUP); - } + OPENSSL_PUT_ERROR(EC, EC_R_UNKNOWN_GROUP); + return nullptr; +} -err: - BN_free(p); - BN_free(a); - BN_free(b); - BN_free(x); - BN_free(y); - return (EC_GROUP *)ret; +EC_GROUP *EC_KEY_parse_parameters(CBS *cbs) { + // This function only ever returns a static `EC_GROUP`, but currently returns + // a non-const pointer for historical reasons. + return const_cast(ec_key_parse_parameters(cbs, get_all_groups())); } int EC_POINT_point2cbb(CBB *out, const EC_GROUP *group, const EC_POINT *point, point_conversion_form_t form, BN_CTX *ctx) { - size_t len = EC_POINT_point2oct(group, point, form, NULL, 0, ctx); + size_t len = EC_POINT_point2oct(group, point, form, nullptr, 0, ctx); if (len == 0) { return 0; } @@ -401,132 +430,81 @@ int EC_POINT_point2cbb(CBB *out, const EC_GROUP *group, const EC_POINT *point, } EC_KEY *d2i_ECPrivateKey(EC_KEY **out, const uint8_t **inp, long len) { - // This function treats its |out| parameter differently from other |d2i| - // functions. If supplied, take the group from |*out|. - const EC_GROUP *group = NULL; - if (out != NULL && *out != NULL) { + // This function treats its `out` parameter differently from other `d2i` + // functions. If supplied, take the group from `*out`. + const EC_GROUP *group = nullptr; + if (out != nullptr && *out != nullptr) { group = EC_KEY_get0_group(*out); } - if (len < 0) { - OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR); - return NULL; - } - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - EC_KEY *ret = EC_KEY_parse_private_key(&cbs, group); - if (ret == NULL) { - return NULL; - } - if (out != NULL) { - EC_KEY_free(*out); - *out = ret; - } - *inp = CBS_data(&cbs); - return ret; + return D2IFromCBS(out, inp, len, [&](CBS *cbs) { + return EC_KEY_parse_private_key(cbs, group); + }); } int i2d_ECPrivateKey(const EC_KEY *key, uint8_t **outp) { - CBB cbb; - if (!CBB_init(&cbb, 0) || - !EC_KEY_marshal_private_key(&cbb, key, EC_KEY_get_enc_flags(key))) { - CBB_cleanup(&cbb); - return -1; - } - return CBB_finish_i2d(&cbb, outp); + return I2DFromCBB( + /*initial_capacity=*/64, outp, [&](CBB *cbb) -> bool { + return EC_KEY_marshal_private_key(cbb, key, EC_KEY_get_enc_flags(key)); + }); } EC_GROUP *d2i_ECPKParameters(EC_GROUP **out, const uint8_t **inp, long len) { - if (len < 0) { - return NULL; - } - - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - EC_GROUP *ret = EC_KEY_parse_parameters(&cbs); - if (ret == NULL) { - return NULL; - } - - if (out != NULL) { - EC_GROUP_free(*out); - *out = ret; - } - *inp = CBS_data(&cbs); - return ret; + return D2IFromCBS(out, inp, len, EC_KEY_parse_parameters); } int i2d_ECPKParameters(const EC_GROUP *group, uint8_t **outp) { - if (group == NULL) { + if (group == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return -1; } - - CBB cbb; - if (!CBB_init(&cbb, 0) || // - !EC_KEY_marshal_curve_name(&cbb, group)) { - CBB_cleanup(&cbb); - return -1; - } - return CBB_finish_i2d(&cbb, outp); + return I2DFromCBB( + /*initial_capacity=*/16, outp, + [&](CBB *cbb) -> bool { return EC_KEY_marshal_curve_name(cbb, group); }); } EC_KEY *d2i_ECParameters(EC_KEY **out_key, const uint8_t **inp, long len) { - if (len < 0) { - return NULL; - } - - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - const EC_GROUP *group = EC_KEY_parse_parameters(&cbs); - if (group == NULL) { - return NULL; - } - - EC_KEY *ret = EC_KEY_new(); - if (ret == NULL || !EC_KEY_set_group(ret, group)) { - EC_KEY_free(ret); - return NULL; - } - - if (out_key != NULL) { - EC_KEY_free(*out_key); - *out_key = ret; - } - *inp = CBS_data(&cbs); - return ret; + return D2IFromCBS(out_key, inp, len, [](CBS *cbs) -> UniquePtr { + const EC_GROUP *group = EC_KEY_parse_parameters(cbs); + if (group == nullptr) { + return nullptr; + } + UniquePtr ret(EC_KEY_new()); + if (ret == nullptr || !EC_KEY_set_group(ret.get(), group)) { + return nullptr; + } + return ret; + }); } int i2d_ECParameters(const EC_KEY *key, uint8_t **outp) { - if (key == NULL || key->group == NULL) { + const ECKey *key_impl = FromOpaque(key); + if (key_impl == nullptr || key_impl->group == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return -1; } - - CBB cbb; - if (!CBB_init(&cbb, 0) || // - !EC_KEY_marshal_curve_name(&cbb, key->group)) { - CBB_cleanup(&cbb); - return -1; - } - return CBB_finish_i2d(&cbb, outp); + return I2DFromCBB( + /*initial_capacity=*/16, outp, [&](CBB *cbb) -> bool { + return EC_KEY_marshal_curve_name(cbb, key_impl->group); + }); } EC_KEY *o2i_ECPublicKey(EC_KEY **keyp, const uint8_t **inp, long len) { - EC_KEY *ret = NULL; + ECKey *ret = nullptr; - if (keyp == NULL || *keyp == NULL || (*keyp)->group == NULL) { + if (keyp == nullptr || *keyp == nullptr || + FromOpaque(*keyp)->group == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); - return NULL; + return nullptr; } - ret = *keyp; - if (ret->pub_key == NULL && - (ret->pub_key = EC_POINT_new(ret->group)) == NULL) { - return NULL; + ret = FromOpaque(*keyp); + if (ret->pub_key == nullptr && + (ret->pub_key = EC_POINT_new(ret->group)) == nullptr) { + return nullptr; } - if (!EC_POINT_oct2point(ret->group, ret->pub_key, *inp, len, NULL)) { + if (!EC_POINT_oct2point(ret->group, ret->pub_key, *inp, len, nullptr)) { OPENSSL_PUT_ERROR(EC, ERR_R_EC_LIB); - return NULL; + return nullptr; } // save the point conversion form ret->conv_form = (point_conversion_form_t)(*inp[0] & ~0x01); @@ -535,31 +513,30 @@ EC_KEY *o2i_ECPublicKey(EC_KEY **keyp, const uint8_t **inp, long len) { } int i2o_ECPublicKey(const EC_KEY *key, uint8_t **outp) { - if (key == NULL) { + if (key == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } - CBB cbb; - if (!CBB_init(&cbb, 0) || // - !EC_POINT_point2cbb(&cbb, key->group, key->pub_key, key->conv_form, - NULL)) { - CBB_cleanup(&cbb); - return -1; - } - int ret = CBB_finish_i2d(&cbb, outp); + const ECKey *key_impl = FromOpaque(key); + // No initial capacity because `EC_POINT_point2cbb` will internally reserve + // the right size in one shot, so it's best to leave this at zero. + int ret = I2DFromCBB( + /*initial_capacity=*/0, outp, [&](CBB *cbb) -> bool { + return EC_POINT_point2cbb(cbb, key_impl->group, key_impl->pub_key, + key_impl->conv_form, nullptr); + }); // Historically, this function used the wrong return value on error. return ret > 0 ? ret : 0; } size_t EC_get_builtin_curves(EC_builtin_curve *out_curves, size_t max_num_curves) { - if (max_num_curves > OPENSSL_ARRAY_SIZE(kAllGroups)) { - max_num_curves = OPENSSL_ARRAY_SIZE(kAllGroups); - } + auto all = get_all_groups(); + max_num_curves = std::min(all.size(), max_num_curves); for (size_t i = 0; i < max_num_curves; i++) { - const EC_GROUP *group = kAllGroups[i](); + const EC_GROUP *group = all[i]; out_curves[i].nid = group->curve_name; out_curves[i].comment = group->comment; } - return OPENSSL_ARRAY_SIZE(kAllGroups); + return all.size(); } diff --git a/Sources/CNIOBoringSSL/crypto/ec/ec_derive.cc b/Sources/CNIOBoringSSL/crypto/ec/ec_derive.cc index 9d796c62..a52fc6f7 100644 --- a/Sources/CNIOBoringSSL/crypto/ec/ec_derive.cc +++ b/Sources/CNIOBoringSSL/crypto/ec/ec_derive.cc @@ -1,21 +1,22 @@ -/* Copyright 2019 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2019 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 @@ -29,13 +30,13 @@ EC_KEY *EC_KEY_derive_from_secret(const EC_GROUP *group, const uint8_t *secret, size_t secret_len) { #define EC_KEY_DERIVE_MAX_NAME_LEN 16 const char *name = EC_curve_nid2nist(EC_GROUP_get_curve_name(group)); - if (name == NULL || strlen(name) > EC_KEY_DERIVE_MAX_NAME_LEN) { + if (name == nullptr || strlen(name) > EC_KEY_DERIVE_MAX_NAME_LEN) { OPENSSL_PUT_ERROR(EC, EC_R_UNKNOWN_GROUP); - return NULL; + return nullptr; } - // Assemble a label string to provide some key separation in case |secret| is - // misused, but ultimately it's on the caller to ensure |secret| is suitably + // Assemble a label string to provide some key separation in case `secret` is + // misused, but ultimately it's on the caller to ensure `secret` is suitably // separated. static const char kLabel[] = "derive EC key "; char info[sizeof(kLabel) + EC_KEY_DERIVE_MAX_NAME_LEN]; @@ -51,7 +52,7 @@ EC_KEY *EC_KEY_derive_from_secret(const EC_GROUP *group, const uint8_t *secret, // (The actual bound is a bit tighter, but our curves are much larger than // 128-bit.) OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR); - return NULL; + return nullptr; } uint8_t derived[EC_KEY_DERIVE_EXTRA_BYTES + EC_MAX_BYTES]; @@ -59,38 +60,35 @@ EC_KEY *EC_KEY_derive_from_secret(const EC_GROUP *group, const uint8_t *secret, BN_num_bytes(EC_GROUP_get0_order(group)) + EC_KEY_DERIVE_EXTRA_BYTES; assert(derived_len <= sizeof(derived)); if (!HKDF(derived, derived_len, EVP_sha256(), secret, secret_len, - /*salt=*/NULL, /*salt_len=*/0, (const uint8_t *)info, + /*salt=*/nullptr, /*salt_len=*/0, (const uint8_t *)info, strlen(info))) { - return NULL; + return nullptr; } - EC_KEY *key = EC_KEY_new(); - BN_CTX *ctx = BN_CTX_new(); - BIGNUM *priv = BN_bin2bn(derived, derived_len, NULL); - EC_POINT *pub = EC_POINT_new(group); - if (key == NULL || ctx == NULL || priv == NULL || pub == NULL || - // Reduce |priv| with Montgomery reduction. First, convert "from" - // Montgomery form to compute |priv| * R^-1 mod |order|. This requires - // |priv| be under order * R, which is true if the group order is large + bssl::UniquePtr key(EC_KEY_new()); + bssl::UniquePtr ctx(BN_CTX_new()); + bssl::UniquePtr priv(BN_bin2bn(derived, derived_len, nullptr)); + bssl::UniquePtr pub(EC_POINT_new(group)); + if (key == nullptr || ctx == nullptr || priv == nullptr || pub == nullptr || + // Reduce `priv` with Montgomery reduction. First, convert "from" + // Montgomery form to compute `priv` * R^-1 mod `order`. This requires + // `priv` be under order * R, which is true if the group order is large // enough. 2^(num_bytes(order)) < 2^8 * order, so: // // priv < 2^8 * order * 2^128 < order * order < order * R - !BN_from_montgomery(priv, priv, &group->order, ctx) || + !BN_from_montgomery(priv.get(), priv.get(), &group->order, ctx.get()) || // Multiply by R^2 and do another Montgomery reduction to compute // priv * R^-1 * R^2 * R^-1 = priv mod order. - !BN_to_montgomery(priv, priv, &group->order, ctx) || - !EC_POINT_mul(group, pub, priv, NULL, NULL, ctx) || - !EC_KEY_set_group(key, group) || !EC_KEY_set_public_key(key, pub) || - !EC_KEY_set_private_key(key, priv)) { - EC_KEY_free(key); - key = NULL; - goto err; + !BN_to_montgomery(priv.get(), priv.get(), &group->order, ctx.get()) || + !EC_POINT_mul(group, pub.get(), priv.get(), nullptr, nullptr, + ctx.get()) || + !EC_KEY_set_group(key.get(), group) || + !EC_KEY_set_public_key(key.get(), pub.get()) || + !EC_KEY_set_private_key(key.get(), priv.get())) { + OPENSSL_cleanse(derived, sizeof(derived)); + return nullptr; } -err: OPENSSL_cleanse(derived, sizeof(derived)); - BN_CTX_free(ctx); - BN_free(priv); - EC_POINT_free(pub); - return key; + return key.release(); } diff --git a/Sources/CNIOBoringSSL/crypto/ec/hash_to_curve.cc b/Sources/CNIOBoringSSL/crypto/ec/hash_to_curve.cc index 2b273c63..4c0a3c2a 100644 --- a/Sources/CNIOBoringSSL/crypto/ec/hash_to_curve.cc +++ b/Sources/CNIOBoringSSL/crypto/ec/hash_to_curve.cc @@ -1,22 +1,26 @@ -/* Copyright 2020 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2020 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 @@ -26,6 +30,10 @@ #include "internal.h" +using namespace bssl; + +namespace { + // This file implements hash-to-curve, as described in RFC 9380. // // This hash-to-curve implementation is written generically with the @@ -33,13 +41,13 @@ // becomes a performance bottleneck, some possible optimizations by // specializing it to the curve: // -// - Rather than using a generic |felem_exp|, specialize the exponentation to -// c2 with a faster addition chain. +// - Rather than using a generic `ec_felem_exp`, specialize the exponentiation +// to c2 with a faster addition chain. // -// - |felem_mul| and |felem_sqr| are indirect calls to generic Montgomery -// code. Given the few curves, we could specialize -// |map_to_curve_simple_swu|. But doing this reasonably without duplicating -// code in C is difficult. (C++ templates would be useful here.) +// - `ec_felem_mul` and `ec_felem_sqr` are generic Montgomery code. Given the +// few curves, we could specialize `map_to_curve_simple_swu`. But doing this +// reasonably without duplicating code in C is difficult. (C++ templates +// would be useful here.) // // - P-521's Z and c2 have small power-of-two absolute values. We could save // two multiplications in SSWU. (Other curves have reasonable values of Z @@ -48,105 +56,97 @@ // expand_message_xmd implements the operation described in section 5.3.1 of // RFC 9380. It returns one on success and zero on error. -static int expand_message_xmd(const EVP_MD *md, uint8_t *out, size_t out_len, - const uint8_t *msg, size_t msg_len, - const uint8_t *dst, size_t dst_len) { +int expand_message_xmd(const EVP_MD *md, uint8_t *out, size_t out_len, + const uint8_t *msg, size_t msg_len, const uint8_t *dst, + size_t dst_len) { // See https://github.com/cfrg/draft-irtf-cfrg-hash-to-curve/issues/352 if (dst_len == 0) { OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } - int ret = 0; const size_t block_size = EVP_MD_block_size(md); const size_t md_size = EVP_MD_size(md); - EVP_MD_CTX ctx; - EVP_MD_CTX_init(&ctx); + ScopedEVP_MD_CTX ctx; - { - // Long DSTs are hashed down to size. See section 5.3.3. - static_assert(EVP_MAX_MD_SIZE < 256, "hashed DST still too large"); - uint8_t dst_buf[EVP_MAX_MD_SIZE]; - if (dst_len >= 256) { - static const char kPrefix[] = "H2C-OVERSIZE-DST-"; - if (!EVP_DigestInit_ex(&ctx, md, NULL) || - !EVP_DigestUpdate(&ctx, kPrefix, sizeof(kPrefix) - 1) || - !EVP_DigestUpdate(&ctx, dst, dst_len) || - !EVP_DigestFinal_ex(&ctx, dst_buf, NULL)) { - goto err; - } - dst = dst_buf; - dst_len = md_size; + // Long DSTs are hashed down to size. See section 5.3.3. + static_assert(EVP_MAX_MD_SIZE < 256, "hashed DST still too large"); + uint8_t dst_buf[EVP_MAX_MD_SIZE]; + if (dst_len >= 256) { + static const char kPrefix[] = "H2C-OVERSIZE-DST-"; + if (!EVP_DigestInit_ex(ctx.get(), md, nullptr) || + !EVP_DigestUpdate(ctx.get(), kPrefix, sizeof(kPrefix) - 1) || + !EVP_DigestUpdate(ctx.get(), dst, dst_len) || + !EVP_DigestFinal_ex(ctx.get(), dst_buf, nullptr)) { + return 0; } - uint8_t dst_len_u8 = (uint8_t)dst_len; + dst = dst_buf; + dst_len = md_size; + } + uint8_t dst_len_u8 = (uint8_t)dst_len; - // Compute b_0. - static const uint8_t kZeros[EVP_MAX_MD_BLOCK_SIZE] = {0}; - // If |out_len| exceeds 16 bits then |i| will wrap below causing an error to - // be returned. This depends on the static assert above. - uint8_t l_i_b_str_zero[3] = {static_cast(out_len >> 8), - static_cast(out_len), 0}; - uint8_t b_0[EVP_MAX_MD_SIZE]; - if (!EVP_DigestInit_ex(&ctx, md, NULL) || - !EVP_DigestUpdate(&ctx, kZeros, block_size) || - !EVP_DigestUpdate(&ctx, msg, msg_len) || - !EVP_DigestUpdate(&ctx, l_i_b_str_zero, sizeof(l_i_b_str_zero)) || - !EVP_DigestUpdate(&ctx, dst, dst_len) || - !EVP_DigestUpdate(&ctx, &dst_len_u8, 1) || - !EVP_DigestFinal_ex(&ctx, b_0, NULL)) { - goto err; - } - - uint8_t b_i[EVP_MAX_MD_SIZE]; - uint8_t i = 1; - while (out_len > 0) { - if (i == 0) { - // Input was too large. - OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR); - goto err; - } - if (i > 1) { - for (size_t j = 0; j < md_size; j++) { - b_i[j] ^= b_0[j]; - } - } else { - OPENSSL_memcpy(b_i, b_0, md_size); - } - - if (!EVP_DigestInit_ex(&ctx, md, NULL) || - !EVP_DigestUpdate(&ctx, b_i, md_size) || - !EVP_DigestUpdate(&ctx, &i, 1) || - !EVP_DigestUpdate(&ctx, dst, dst_len) || - !EVP_DigestUpdate(&ctx, &dst_len_u8, 1) || - !EVP_DigestFinal_ex(&ctx, b_i, NULL)) { - goto err; - } - - size_t todo = out_len >= md_size ? md_size : out_len; - OPENSSL_memcpy(out, b_i, todo); - out += todo; - out_len -= todo; - i++; - } - - ret = 1; + // Compute b_0. + static const uint8_t kZeros[EVP_MAX_MD_BLOCK_SIZE] = {0}; + // If `out_len` exceeds 16 bits then `i` will wrap below causing an error to + // be returned. This depends on the static assert above. + uint8_t l_i_b_str_zero[3] = {static_cast(out_len >> 8), + static_cast(out_len), 0}; + uint8_t b_0[EVP_MAX_MD_SIZE]; + if (!EVP_DigestInit_ex(ctx.get(), md, nullptr) || + !EVP_DigestUpdate(ctx.get(), kZeros, block_size) || + !EVP_DigestUpdate(ctx.get(), msg, msg_len) || + !EVP_DigestUpdate(ctx.get(), l_i_b_str_zero, sizeof(l_i_b_str_zero)) || + !EVP_DigestUpdate(ctx.get(), dst, dst_len) || + !EVP_DigestUpdate(ctx.get(), &dst_len_u8, 1) || + !EVP_DigestFinal_ex(ctx.get(), b_0, nullptr)) { + return 0; } -err: - EVP_MD_CTX_cleanup(&ctx); - return ret; + uint8_t b_i[EVP_MAX_MD_SIZE]; + uint8_t i = 1; + while (out_len > 0) { + if (i == 0) { + // Input was too large. + OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR); + return 0; + } + if (i > 1) { + for (size_t j = 0; j < md_size; j++) { + b_i[j] ^= b_0[j]; + } + } else { + OPENSSL_memcpy(b_i, b_0, md_size); + } + + if (!EVP_DigestInit_ex(ctx.get(), md, nullptr) || + !EVP_DigestUpdate(ctx.get(), b_i, md_size) || + !EVP_DigestUpdate(ctx.get(), &i, 1) || + !EVP_DigestUpdate(ctx.get(), dst, dst_len) || + !EVP_DigestUpdate(ctx.get(), &dst_len_u8, 1) || + !EVP_DigestFinal_ex(ctx.get(), b_i, nullptr)) { + return 0; + } + + size_t todo = out_len >= md_size ? md_size : out_len; + OPENSSL_memcpy(out, b_i, todo); + out += todo; + out_len -= todo; + i++; + } + + return 1; } // num_bytes_to_derive determines the number of bytes to derive when hashing to -// a number modulo |modulus|. See the hash_to_field operation defined in +// a number modulo `modulus`. See the hash_to_field operation defined in // section 5.2 of RFC 9380. -static int num_bytes_to_derive(size_t *out, const BIGNUM *modulus, unsigned k) { +int num_bytes_to_derive(size_t *out, const BIGNUM *modulus, unsigned k) { size_t bits = BN_num_bits(modulus); size_t L = (bits + k + 7) / 8; // We require 2^(8*L) < 2^(2*bits - 2) <= n^2 so to fit in bounds for - // |felem_reduce| and |ec_scalar_reduce|. All defined hash-to-curve suites - // define |k| to be well under this bound. (|k| is usually around half of - // |p_bits|.) + // `felem_reduce` and `ec_scalar_reduce`. All defined hash-to-curve suites + // define `k` to be well under this bound. (`k` is usually around half of + // `p_bits`.) if (L * 8 >= 2 * bits - 2 || L > 2 * EC_MAX_BYTES) { assert(0); OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR); @@ -157,45 +157,62 @@ static int num_bytes_to_derive(size_t *out, const BIGNUM *modulus, unsigned k) { return 1; } -// big_endian_to_words decodes |in| as a big-endian integer and writes the -// result to |out|. |num_words| must be large enough to contain the output. -static void big_endian_to_words(BN_ULONG *out, size_t num_words, - const uint8_t *in, size_t len) { - assert(len <= num_words * sizeof(BN_ULONG)); +// big_endian_to_words decodes `in` as a big-endian integer and writes the +// result to `out`. `out` must be large enough to contain the output. +void big_endian_to_words(Span out, Span in) { + BSSL_CHECK(in.size() <= out.size() * sizeof(BN_ULONG)); // Ensure any excess bytes are zeroed. - OPENSSL_memset(out, 0, num_words * sizeof(BN_ULONG)); - uint8_t *out_u8 = (uint8_t *)out; - for (size_t i = 0; i < len; i++) { - out_u8[len - 1 - i] = in[i]; + OPENSSL_memset(out.data(), 0, out.size() * sizeof(BN_ULONG)); + uint8_t *out_u8 = reinterpret_cast(out.data()); + for (size_t i = 0; i < in.size(); i++) { + out_u8[in.size() - 1 - i] = in[i]; } } +void big_endian_reduce_to_felem(const EC_GROUP *group, EC_FELEM *out, + Span in) { + BN_ULONG words_buf[2 * EC_MAX_WORDS]; + auto words = Span(words_buf).first(2 * group->field.N.width); + big_endian_to_words(words, in); + ec_felem_reduce(group, out, words.data(), words.size()); +} + // hash_to_field implements the operation described in section 5.2 -// of RFC 9380, with count = 2. |k| is the security factor. -static int hash_to_field2(const EC_GROUP *group, const EVP_MD *md, - EC_FELEM *out1, EC_FELEM *out2, const uint8_t *dst, - size_t dst_len, unsigned k, const uint8_t *msg, - size_t msg_len) { +// of RFC 9380, with count = 2. `k` is the security factor. +int hash_to_field2(const EC_GROUP *group, const EVP_MD *md, EC_FELEM *out1, + EC_FELEM *out2, const uint8_t *dst, size_t dst_len, + unsigned k, const uint8_t *msg, size_t msg_len) { size_t L; uint8_t buf[4 * EC_MAX_BYTES]; if (!num_bytes_to_derive(&L, &group->field.N, k) || !expand_message_xmd(md, buf, 2 * L, msg, msg_len, dst, dst_len)) { return 0; } - BN_ULONG words[2 * EC_MAX_WORDS]; - size_t num_words = 2 * group->field.N.width; - big_endian_to_words(words, num_words, buf, L); - group->meth->felem_reduce(group, out1, words, num_words); - big_endian_to_words(words, num_words, buf + L, L); - group->meth->felem_reduce(group, out2, words, num_words); + big_endian_reduce_to_felem(group, out1, Span(buf).first(L)); + big_endian_reduce_to_felem(group, out2, Span(buf).subspan(L, L)); return 1; } -// hash_to_scalar behaves like |hash_to_field2| but returns a value modulo the -// group order rather than a field element. |k| is the security factor. -static int hash_to_scalar(const EC_GROUP *group, const EVP_MD *md, - EC_SCALAR *out, const uint8_t *dst, size_t dst_len, - unsigned k, const uint8_t *msg, size_t msg_len) { +// hash_to_field1 implements the operation described in section 5.2 +// of RFC 9380, with count = 1. `k` is the security factor. +int hash_to_field1(const EC_GROUP *group, const EVP_MD *md, EC_FELEM *out, + const uint8_t *dst, size_t dst_len, unsigned k, + const uint8_t *msg, size_t msg_len) { + size_t L; + uint8_t buf[2 * EC_MAX_BYTES]; + if (!num_bytes_to_derive(&L, &group->field.N, k) || + !expand_message_xmd(md, buf, L, msg, msg_len, dst, dst_len)) { + return 0; + } + big_endian_reduce_to_felem(group, out, Span(buf).first(L)); + return 1; +} + +// hash_to_scalar behaves like `hash_to_field2` but returns a value modulo the +// group order rather than a field element. `k` is the security factor. +int hash_to_scalar(const EC_GROUP *group, const EVP_MD *md, EC_SCALAR *out, + const uint8_t *dst, size_t dst_len, unsigned k, + const uint8_t *msg, size_t msg_len) { const BIGNUM *order = EC_GROUP_get0_order(group); size_t L; uint8_t buf[EC_MAX_BYTES * 2]; @@ -206,13 +223,12 @@ static int hash_to_scalar(const EC_GROUP *group, const EVP_MD *md, BN_ULONG words[2 * EC_MAX_WORDS]; size_t num_words = 2 * order->width; - big_endian_to_words(words, num_words, buf, L); + big_endian_to_words(Span(words).first(num_words), Span(buf).first(L)); ec_scalar_reduce(group, out, words, num_words); return 1; } -static inline void mul_A(const EC_GROUP *group, EC_FELEM *out, - const EC_FELEM *in) { +void mul_A(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *in) { assert(group->a_is_minus3); EC_FELEM tmp; ec_felem_add(group, &tmp, in, in); // tmp = 2*in @@ -221,45 +237,36 @@ static inline void mul_A(const EC_GROUP *group, EC_FELEM *out, } // sgn0 implements the operation described in section 4.1.2 of RFC 9380. -static BN_ULONG sgn0(const EC_GROUP *group, const EC_FELEM *a) { +BN_ULONG sgn0(const EC_GROUP *group, const EC_FELEM *a) { uint8_t buf[EC_MAX_BYTES]; size_t len; ec_felem_to_bytes(group, buf, &len, a); return buf[len - 1] & 1; } -[[maybe_unused]] static int is_3mod4(const EC_GROUP *group) { - return group->field.N.width > 0 && (group->field.N.d[0] & 3) == 3; -} - // sqrt_ratio_3mod4 implements the operation described in appendix F.2.1.2 // of RFC 9380. -static BN_ULONG sqrt_ratio_3mod4(const EC_GROUP *group, const EC_FELEM *Z, - const BN_ULONG *c1, size_t num_c1, - const EC_FELEM *c2, EC_FELEM *out_y, - const EC_FELEM *u, const EC_FELEM *v) { - assert(is_3mod4(group)); - - void (*const felem_mul)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a, - const EC_FELEM *b) = group->meth->felem_mul; - void (*const felem_sqr)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a) = - group->meth->felem_sqr; +BN_ULONG sqrt_ratio_3mod4(const EC_GROUP *group, const EC_FELEM *Z, + const BN_ULONG *c1, size_t num_c1, const EC_FELEM *c2, + EC_FELEM *out_y, const EC_FELEM *u, + const EC_FELEM *v) { + assert(group->field_is_3_mod_4); EC_FELEM tv1, tv2, tv3, y1, y2; - felem_sqr(group, &tv1, v); // 1. tv1 = v^2 - felem_mul(group, &tv2, u, v); // 2. tv2 = u * v - felem_mul(group, &tv1, &tv1, &tv2); // 3. tv1 = tv1 * tv2 - group->meth->felem_exp(group, &y1, &tv1, c1, num_c1); // 4. y1 = tv1^c1 - felem_mul(group, &y1, &y1, &tv2); // 5. y1 = y1 * tv2 - felem_mul(group, &y2, &y1, c2); // 6. y2 = y1 * c2 - felem_sqr(group, &tv3, &y1); // 7. tv3 = y1^2 - felem_mul(group, &tv3, &tv3, v); // 8. tv3 = tv3 * v + ec_felem_sqr(group, &tv1, v); // 1. tv1 = v^2 + ec_felem_mul(group, &tv2, u, v); // 2. tv2 = u * v + ec_felem_mul(group, &tv1, &tv1, &tv2); // 3. tv1 = tv1 * tv2 + ec_felem_exp(group, &y1, &tv1, c1, num_c1); // 4. y1 = tv1^c1 + ec_felem_mul(group, &y1, &y1, &tv2); // 5. y1 = y1 * tv2 + ec_felem_mul(group, &y2, &y1, c2); // 6. y2 = y1 * c2 + ec_felem_sqr(group, &tv3, &y1); // 7. tv3 = y1^2 + ec_felem_mul(group, &tv3, &tv3, v); // 8. tv3 = tv3 * v // 9. isQR = tv3 == u // 10. y = CMOV(y2, y1, isQR) // 11. return (isQR, y) // - // Note the specification's CMOV function and our |ec_felem_select| have the + // Note the specification's CMOV function and our `ec_felem_select` have the // opposite argument order. ec_felem_sub(group, &tv1, &tv3, u); const BN_ULONG isQR = ~ec_felem_non_zero_mask(group, &tv1); @@ -269,49 +276,44 @@ static BN_ULONG sqrt_ratio_3mod4(const EC_GROUP *group, const EC_FELEM *Z, // map_to_curve_simple_swu implements the operation described in section 6.6.2 // of RFC 9380, using the straight-line implementation in appendix F.2. -static void map_to_curve_simple_swu(const EC_GROUP *group, const EC_FELEM *Z, - const BN_ULONG *c1, size_t num_c1, - const EC_FELEM *c2, EC_JACOBIAN *out, - const EC_FELEM *u) { +void map_to_curve_simple_swu(const EC_GROUP *group, const EC_FELEM *Z, + const BN_ULONG *c1, size_t num_c1, + const EC_FELEM *c2, EC_JACOBIAN *out, + const EC_FELEM *u) { // This function requires the prime be 3 mod 4, and that A = -3. - assert(is_3mod4(group)); + assert(group->field_is_3_mod_4); assert(group->a_is_minus3); - void (*const felem_mul)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a, - const EC_FELEM *b) = group->meth->felem_mul; - void (*const felem_sqr)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a) = - group->meth->felem_sqr; - EC_FELEM tv1, tv2, tv3, tv4, tv5, tv6, x, y, y1; - felem_sqr(group, &tv1, u); // 1. tv1 = u^2 - felem_mul(group, &tv1, Z, &tv1); // 2. tv1 = Z * tv1 - felem_sqr(group, &tv2, &tv1); // 3. tv2 = tv1^2 + ec_felem_sqr(group, &tv1, u); // 1. tv1 = u^2 + ec_felem_mul(group, &tv1, Z, &tv1); // 2. tv1 = Z * tv1 + ec_felem_sqr(group, &tv2, &tv1); // 3. tv2 = tv1^2 ec_felem_add(group, &tv2, &tv2, &tv1); // 4. tv2 = tv2 + tv1 ec_felem_add(group, &tv3, &tv2, ec_felem_one(group)); // 5. tv3 = tv2 + 1 - felem_mul(group, &tv3, &group->b, &tv3); // 6. tv3 = B * tv3 + ec_felem_mul(group, &tv3, &group->b, &tv3); // 6. tv3 = B * tv3 // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) const BN_ULONG tv2_non_zero = ec_felem_non_zero_mask(group, &tv2); ec_felem_neg(group, &tv4, &tv2); ec_felem_select(group, &tv4, tv2_non_zero, &tv4, Z); - mul_A(group, &tv4, &tv4); // 8. tv4 = A * tv4 - felem_sqr(group, &tv2, &tv3); // 9. tv2 = tv3^2 - felem_sqr(group, &tv6, &tv4); // 10. tv6 = tv4^2 - mul_A(group, &tv5, &tv6); // 11. tv5 = A * tv6 - ec_felem_add(group, &tv2, &tv2, &tv5); // 12. tv2 = tv2 + tv5 - felem_mul(group, &tv2, &tv2, &tv3); // 13. tv2 = tv2 * tv3 - felem_mul(group, &tv6, &tv6, &tv4); // 14. tv6 = tv6 * tv4 - felem_mul(group, &tv5, &group->b, &tv6); // 15. tv5 = B * tv6 - ec_felem_add(group, &tv2, &tv2, &tv5); // 16. tv2 = tv2 + tv5 - felem_mul(group, &x, &tv1, &tv3); // 17. x = tv1 * tv3 + mul_A(group, &tv4, &tv4); // 8. tv4 = A * tv4 + ec_felem_sqr(group, &tv2, &tv3); // 9. tv2 = tv3^2 + ec_felem_sqr(group, &tv6, &tv4); // 10. tv6 = tv4^2 + mul_A(group, &tv5, &tv6); // 11. tv5 = A * tv6 + ec_felem_add(group, &tv2, &tv2, &tv5); // 12. tv2 = tv2 + tv5 + ec_felem_mul(group, &tv2, &tv2, &tv3); // 13. tv2 = tv2 * tv3 + ec_felem_mul(group, &tv6, &tv6, &tv4); // 14. tv6 = tv6 * tv4 + ec_felem_mul(group, &tv5, &group->b, &tv6); // 15. tv5 = B * tv6 + ec_felem_add(group, &tv2, &tv2, &tv5); // 16. tv2 = tv2 + tv5 + ec_felem_mul(group, &x, &tv1, &tv3); // 17. x = tv1 * tv3 // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6) const BN_ULONG is_gx1_square = sqrt_ratio_3mod4(group, Z, c1, num_c1, c2, &y1, &tv2, &tv6); - felem_mul(group, &y, &tv1, u); // 19. y = tv1 * u - felem_mul(group, &y, &y, &y1); // 20. y = y * y1 + ec_felem_mul(group, &y, &tv1, u); // 19. y = tv1 * u + ec_felem_mul(group, &y, &y, &y1); // 20. y = y * y1 // 21. x = CMOV(x, tv3, is_gx1_square) ec_felem_select(group, &x, is_gx1_square, &tv3, &x); @@ -330,26 +332,19 @@ static void map_to_curve_simple_swu(const EC_GROUP *group, const EC_FELEM *Z, // 25. x = x / tv4 // - // Our output is in projective coordinates, so rather than inverting |tv4| + // Our output is in projective coordinates, so rather than inverting `tv4` // now, represent (x / tv4, y) as (x * tv4, y * tv4^3, tv4). This is much more // efficient if the caller will do further computation on the output. (If the // caller will immediately convert to affine coordinates, it is slightly less // efficient, but only by a few field multiplications.) - felem_mul(group, &out->X, &x, &tv4); - felem_mul(group, &out->Y, &y, &tv6); + ec_felem_mul(group, &out->X, &x, &tv4); + ec_felem_mul(group, &out->Y, &y, &tv6); out->Z = tv4; } -static int hash_to_curve(const EC_GROUP *group, const EVP_MD *md, - const EC_FELEM *Z, const EC_FELEM *c2, unsigned k, - EC_JACOBIAN *out, const uint8_t *dst, size_t dst_len, - const uint8_t *msg, size_t msg_len) { - EC_FELEM u0, u1; - if (!hash_to_field2(group, md, &u0, &u1, dst, dst_len, k, msg, msg_len)) { - return 0; - } - - // Compute |c1| = (p - 3) / 4. +int sswu_and_add(const EC_GROUP *group, const EC_FELEM *Z, const EC_FELEM *c2, + EC_JACOBIAN *out, const EC_FELEM *u0, const EC_FELEM *u1) { + // Compute `c1` = (p - 3) / 4. BN_ULONG c1[EC_MAX_WORDS]; size_t num_c1 = group->field.N.width; if (!bn_copy_words(c1, num_c1, &group->field.N)) { @@ -358,15 +353,46 @@ static int hash_to_curve(const EC_GROUP *group, const EVP_MD *md, bn_rshift_words(c1, c1, /*shift=*/2, /*num=*/num_c1); EC_JACOBIAN Q0, Q1; - map_to_curve_simple_swu(group, Z, c1, num_c1, c2, &Q0, &u0); - map_to_curve_simple_swu(group, Z, c1, num_c1, c2, &Q1, &u1); + map_to_curve_simple_swu(group, Z, c1, num_c1, c2, &Q0, u0); + map_to_curve_simple_swu(group, Z, c1, num_c1, c2, &Q1, u1); group->meth->add(group, out, &Q0, &Q1); // R = Q0 + Q1 - // All our curves have cofactor one, so |clear_cofactor| is a no-op. + // All our curves have cofactor one, so `clear_cofactor` is a no-op. return 1; } -static int felem_from_u8(const EC_GROUP *group, EC_FELEM *out, uint8_t a) { +int hash_to_curve(const EC_GROUP *group, const EVP_MD *md, const EC_FELEM *Z, + const EC_FELEM *c2, unsigned k, EC_JACOBIAN *out, + const uint8_t *dst, size_t dst_len, const uint8_t *msg, + size_t msg_len) { + EC_FELEM u0, u1; + return hash_to_field2(group, md, &u0, &u1, dst, dst_len, k, msg, msg_len) && + sswu_and_add(group, Z, c2, out, &u0, &u1); +} + +int encode_to_curve(const EC_GROUP *group, const EVP_MD *md, const EC_FELEM *Z, + const EC_FELEM *c2, unsigned k, EC_JACOBIAN *out, + const uint8_t *dst, size_t dst_len, const uint8_t *msg, + size_t msg_len) { + EC_FELEM u; + if (!hash_to_field1(group, md, &u, dst, dst_len, k, msg, msg_len)) { + return 0; + } + + // Compute `c1` = (p - 3) / 4. + BN_ULONG c1[EC_MAX_WORDS]; + size_t num_c1 = group->field.N.width; + if (!bn_copy_words(c1, num_c1, &group->field.N)) { + return 0; + } + bn_rshift_words(c1, c1, /*shift=*/2, /*num=*/num_c1); + + map_to_curve_simple_swu(group, Z, c1, num_c1, c2, out, &u); + // All our curves have cofactor one, so `clear_cofactor` is a no-op. + return 1; +} + +int felem_from_u8(const EC_GROUP *group, EC_FELEM *out, uint8_t a) { uint8_t bytes[EC_MAX_BYTES] = {0}; size_t len = BN_num_bytes(&group->field.N); bytes[len - 1] = a; @@ -380,10 +406,10 @@ static int felem_from_u8(const EC_GROUP *group, EC_FELEM *out, uint8_t a) { // c2 = pow(10, (p+1)//4, p) // assert pow(c2, 2, p) == 10 // ", ".join("0x%02x" % b for b in c2.to_bytes(256//8, 'big')) -static const uint8_t kP256Sqrt10[] = { - 0xda, 0x53, 0x8e, 0x3b, 0xe1, 0xd8, 0x9b, 0x99, 0xc9, 0x78, 0xfc, - 0x67, 0x51, 0x80, 0xaa, 0xb2, 0x7b, 0x8d, 0x1f, 0xf8, 0x4c, 0x55, - 0xd5, 0xb6, 0x2c, 0xcd, 0x34, 0x27, 0xe4, 0x33, 0xc4, 0x7f}; +const uint8_t kP256Sqrt10[] = {0xda, 0x53, 0x8e, 0x3b, 0xe1, 0xd8, 0x9b, 0x99, + 0xc9, 0x78, 0xfc, 0x67, 0x51, 0x80, 0xaa, 0xb2, + 0x7b, 0x8d, 0x1f, 0xf8, 0x4c, 0x55, 0xd5, 0xb6, + 0x2c, 0xcd, 0x34, 0x27, 0xe4, 0x33, 0xc4, 0x7f}; // kP384Sqrt12 is sqrt(12) in P-384's field. It was computed as follows in // python3: @@ -392,16 +418,17 @@ static const uint8_t kP256Sqrt10[] = { // c2 = pow(12, (p+1)//4, p) // assert pow(c2, 2, p) == 12 // ", ".join("0x%02x" % b for b in c2.to_bytes(384//8, 'big')) -static const uint8_t kP384Sqrt12[] = { +const uint8_t kP384Sqrt12[] = { 0x2a, 0xcc, 0xb4, 0xa6, 0x56, 0xb0, 0x24, 0x9c, 0x71, 0xf0, 0x50, 0x0e, 0x83, 0xda, 0x2f, 0xdd, 0x7f, 0x98, 0xe3, 0x83, 0xd6, 0x8b, 0x53, 0x87, 0x1f, 0x87, 0x2f, 0xcb, 0x9c, 0xcb, 0x80, 0xc5, 0x3c, 0x0d, 0xe1, 0xf8, 0xa8, 0x0f, 0x7e, 0x19, 0x14, 0xe2, 0xec, 0x69, 0xf5, 0xa6, 0x26, 0xb3}; -int ec_hash_to_curve_p256_xmd_sha256_sswu(const EC_GROUP *group, - EC_JACOBIAN *out, const uint8_t *dst, - size_t dst_len, const uint8_t *msg, - size_t msg_len) { +} // namespace + +int bssl::ec_hash_to_curve_p256_xmd_sha256_sswu( + const EC_GROUP *group, EC_JACOBIAN *out, const uint8_t *dst, size_t dst_len, + const uint8_t *msg, size_t msg_len) { // See section 8.3 of RFC 9380. if (EC_GROUP_get_curve_name(group) != NID_X9_62_prime256v1) { OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH); @@ -423,7 +450,7 @@ int ec_hash_to_curve_p256_xmd_sha256_sswu(const EC_GROUP *group, int EC_hash_to_curve_p256_xmd_sha256_sswu(const EC_GROUP *group, EC_POINT *out, const uint8_t *dst, size_t dst_len, const uint8_t *msg, size_t msg_len) { - if (EC_GROUP_cmp(group, out->group, NULL) != 0) { + if (EC_GROUP_cmp(group, out->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } @@ -431,10 +458,9 @@ int EC_hash_to_curve_p256_xmd_sha256_sswu(const EC_GROUP *group, EC_POINT *out, msg, msg_len); } -int ec_hash_to_curve_p384_xmd_sha384_sswu(const EC_GROUP *group, - EC_JACOBIAN *out, const uint8_t *dst, - size_t dst_len, const uint8_t *msg, - size_t msg_len) { +int bssl::ec_hash_to_curve_p384_xmd_sha384_sswu( + const EC_GROUP *group, EC_JACOBIAN *out, const uint8_t *dst, size_t dst_len, + const uint8_t *msg, size_t msg_len) { // See section 8.3 of RFC 9380. if (EC_GROUP_get_curve_name(group) != NID_secp384r1) { OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH); @@ -456,7 +482,7 @@ int ec_hash_to_curve_p384_xmd_sha384_sswu(const EC_GROUP *group, int EC_hash_to_curve_p384_xmd_sha384_sswu(const EC_GROUP *group, EC_POINT *out, const uint8_t *dst, size_t dst_len, const uint8_t *msg, size_t msg_len) { - if (EC_GROUP_cmp(group, out->group, NULL) != 0) { + if (EC_GROUP_cmp(group, out->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } @@ -464,9 +490,246 @@ int EC_hash_to_curve_p384_xmd_sha384_sswu(const EC_GROUP *group, EC_POINT *out, msg, msg_len); } -int ec_hash_to_scalar_p384_xmd_sha384(const EC_GROUP *group, EC_SCALAR *out, - const uint8_t *dst, size_t dst_len, - const uint8_t *msg, size_t msg_len) { +int bssl::ec_encode_to_curve_p256_xmd_sha256_sswu( + const EC_GROUP *group, EC_JACOBIAN *out, const uint8_t *dst, size_t dst_len, + const uint8_t *msg, size_t msg_len) { + // See section 8.3 of RFC 9380. + if (EC_GROUP_get_curve_name(group) != NID_X9_62_prime256v1) { + OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH); + return 0; + } + + // Z = -10, c2 = sqrt(10) + EC_FELEM Z, c2; + if (!felem_from_u8(group, &Z, 10) || + !ec_felem_from_bytes(group, &c2, kP256Sqrt10, sizeof(kP256Sqrt10))) { + return 0; + } + ec_felem_neg(group, &Z, &Z); + + return encode_to_curve(group, EVP_sha256(), &Z, &c2, /*k=*/128, out, dst, + dst_len, msg, msg_len); +} + +int EC_encode_to_curve_p256_xmd_sha256_sswu(const EC_GROUP *group, + EC_POINT *out, const uint8_t *dst, + size_t dst_len, const uint8_t *msg, + size_t msg_len) { + if (EC_GROUP_cmp(group, out->group, nullptr) != 0) { + OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); + return 0; + } + return ec_encode_to_curve_p256_xmd_sha256_sswu(group, &out->raw, dst, dst_len, + msg, msg_len); +} + +int bssl::ec_encode_to_curve_p384_xmd_sha384_sswu( + const EC_GROUP *group, EC_JACOBIAN *out, const uint8_t *dst, size_t dst_len, + const uint8_t *msg, size_t msg_len) { + // See section 8.3 of RFC 9380. + if (EC_GROUP_get_curve_name(group) != NID_secp384r1) { + OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH); + return 0; + } + + // Z = -12, c2 = sqrt(12) + EC_FELEM Z, c2; + if (!felem_from_u8(group, &Z, 12) || + !ec_felem_from_bytes(group, &c2, kP384Sqrt12, sizeof(kP384Sqrt12))) { + return 0; + } + ec_felem_neg(group, &Z, &Z); + + return encode_to_curve(group, EVP_sha384(), &Z, &c2, /*k=*/192, out, dst, + dst_len, msg, msg_len); +} + +int EC_encode_to_curve_p384_xmd_sha384_sswu(const EC_GROUP *group, + EC_POINT *out, const uint8_t *dst, + size_t dst_len, const uint8_t *msg, + size_t msg_len) { + if (EC_GROUP_cmp(group, out->group, nullptr) != 0) { + OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); + return 0; + } + return ec_encode_to_curve_p384_xmd_sha384_sswu(group, &out->raw, dst, dst_len, + msg, msg_len); +} + +int EC_wpa3_sae_hash_to_curve_p256(const EC_GROUP *group, EC_POINT *out, + const uint8_t *salt, size_t salt_len, + const uint8_t *ikm, size_t ikm_len) { + if (EC_GROUP_cmp(group, out->group, nullptr) != 0) { + OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); + return 0; + } + if (EC_GROUP_get_curve_name(group) != NID_X9_62_prime256v1) { + OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH); + return 0; + } + + // WPA3 uses a different process for computing `u0` and `u1` (called `u1` and + // `u2` in 802.11) than RFC 9380. + uint8_t pwd_seed[EVP_MAX_MD_SIZE]; + size_t pwd_seed_len; + if (!HKDF_extract(pwd_seed, &pwd_seed_len, EVP_sha256(), ikm, ikm_len, salt, + salt_len)) { + return 0; + } + + uint8_t pwd_value[48]; // `len` for P-256 is 32 + 32 / 2 + auto label = StringAsBytes("SAE Hash to Element u1 P1"); + if (!HKDF_expand(pwd_value, sizeof(pwd_value), EVP_sha256(), pwd_seed, + pwd_seed_len, label.data(), label.size())) { + return 0; + } + EC_FELEM u1; + big_endian_reduce_to_felem(group, &u1, pwd_value); + + label = StringAsBytes("SAE Hash to Element u2 P2"); + if (!HKDF_expand(pwd_value, sizeof(pwd_value), EVP_sha256(), pwd_seed, + pwd_seed_len, label.data(), label.size())) { + return 0; + } + EC_FELEM u2; + big_endian_reduce_to_felem(group, &u2, pwd_value); + + // Z = -10, c2 = sqrt(10) + EC_FELEM Z, c2; + if (!felem_from_u8(group, &Z, 10) || + !ec_felem_from_bytes(group, &c2, kP256Sqrt10, sizeof(kP256Sqrt10))) { + return 0; + } + ec_felem_neg(group, &Z, &Z); + + return sswu_and_add(group, &Z, &c2, &out->raw, &u1, &u2); +} + +// See IEEE Std 802.11-2020, Section 12.7.1.6.2. +static int kdf_hash_length(const EVP_MD *md, Span out, + Span key, Span label, + Span context) { + ScopedHMAC_CTX hmac; + if (!HMAC_Init_ex(hmac.get(), key.data(), key.size(), md, nullptr)) { + return 0; + } + + assert(out.size() <= 0xffff); + uint8_t len_bytes[2]; + CRYPTO_store_u16_le(len_bytes, static_cast(out.size() * 8)); + const size_t md_len = HMAC_size(hmac.get()); + for (uint16_t i = 1; !out.empty(); i++) { + uint8_t i_bytes[2]; + CRYPTO_store_u16_le(i_bytes, i); + if (!HMAC_Init_ex(hmac.get(), nullptr, 0, nullptr, nullptr) || // Reset + !HMAC_Update(hmac.get(), i_bytes, sizeof(i_bytes)) || + !HMAC_Update(hmac.get(), label.data(), label.size()) || + !HMAC_Update(hmac.get(), context.data(), context.size()) || + !HMAC_Update(hmac.get(), len_bytes, sizeof(len_bytes))) { + return 0; + } + + if (out.size() < md_len) { + uint8_t tmp[EVP_MAX_MD_SIZE]; + if (!HMAC_Final(hmac.get(), tmp, nullptr)) { + return 0; + } + OPENSSL_memcpy(out.data(), tmp, out.size()); + break; + } + + if (!HMAC_Final(hmac.get(), out.data(), nullptr)) { + return 0; + } + out = out.subspan(md_len); + } + + return 1; +} + +int EC_wpa3_sae_hunt_and_peck_p256(const EC_GROUP *group, EC_POINT *out, + const uint8_t *salt, size_t salt_len, + const uint8_t *password, size_t password_len, + uint8_t min_iterations) { + if (EC_GROUP_cmp(group, out->group, nullptr) != 0) { + OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); + return 0; + } + if (EC_GROUP_get_curve_name(group) != NID_X9_62_prime256v1) { + OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH); + return 0; + } + + static constexpr size_t kFieldBytes = 32; + static constexpr size_t kFieldWords = 32 / sizeof(BN_ULONG); + assert(static_cast(kFieldBytes) == BN_num_bytes(&group->field.N)); + assert(static_cast(kFieldWords) == group->field.N.width); + const EVP_MD *md = EVP_sha256(); + static const char kPWDValueLabel[] = "SAE Hunting and Pecking"; + + // The KDF uses the field as the context value. + uint8_t p_bytes[kFieldBytes]; + BSSL_CHECK(BN_bn2bin_padded(p_bytes, kFieldBytes, &group->field.N)); + + crypto_word_t ok = CONSTTIME_FALSE_W; + EC_AFFINE affine = {}; + for (uint8_t counter = 1; counter != 0; counter++) { + // Compute `pwd_seed`. This is an HKDF-Extract, or HMAC. + ScopedHMAC_CTX hmac; + uint8_t pwd_seed[EVP_MAX_MD_SIZE]; + unsigned pwd_seed_len; + if (!HMAC_Init_ex(hmac.get(), salt, salt_len, md, nullptr) || + !HMAC_Update(hmac.get(), password, password_len) || + !HMAC_Update(hmac.get(), &counter, 1) || + !HMAC_Final(hmac.get(), pwd_seed, &pwd_seed_len)) { + return 0; + } + + // Compute `pwd_value`. This uses something custom instead of HKDF-Expand. + uint8_t pwd_value[kFieldBytes]; + if (!kdf_hash_length(md, Span(pwd_value), Span(pwd_seed, pwd_seed_len), + StringAsBytes(kPWDValueLabel), p_bytes)) { + return 0; + } + + // Try to import `pwd_value` as a compressed point. + // The parity of y is determined by the least significant bit of `pwd_seed`. + uint8_t y_bit = pwd_seed[pwd_seed_len - 1] & 1; + EC_FELEM x, y2, y; + crypto_word_t iter_ok = + ec_felem_from_bytes_or_placeholder(group, &x, pwd_value, kFieldBytes); + ec_y_sqr_from_x(group, &y2, &x); + iter_ok &= ec_felem_sqrt_secret(group, &y, &y2, y_bit); + + // Save the first valid point. + crypto_word_t save = iter_ok & ~ok; + constant_time_conditional_memcpy(affine.X.words, x.words, + sizeof(BN_ULONG) * kFieldWords, save); + constant_time_conditional_memcpy(affine.Y.words, y.words, + sizeof(BN_ULONG) * kFieldWords, save); + ok |= save; + + // Stop if we've found something and iterated at least `min_iterations`. + if (constant_time_declassify_int( + ok & constant_time_ge_8(counter, min_iterations))) { + break; + } + } + + if (constant_time_declassify_w(ok) == 0) { + // This should be impossible. It can only fail with probabilty 2^-256. + OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR); + return 0; + } + + ec_affine_to_jacobian(group, &out->raw, &affine); + return 1; +} + +int bssl::ec_hash_to_scalar_p384_xmd_sha384(const EC_GROUP *group, + EC_SCALAR *out, const uint8_t *dst, + size_t dst_len, const uint8_t *msg, + size_t msg_len) { if (EC_GROUP_get_curve_name(group) != NID_secp384r1) { OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH); return 0; @@ -476,7 +739,7 @@ int ec_hash_to_scalar_p384_xmd_sha384(const EC_GROUP *group, EC_SCALAR *out, msg_len); } -int ec_hash_to_curve_p384_xmd_sha512_sswu_draft07( +int bssl::ec_hash_to_curve_p384_xmd_sha512_sswu_draft07( const EC_GROUP *group, EC_JACOBIAN *out, const uint8_t *dst, size_t dst_len, const uint8_t *msg, size_t msg_len) { // See section 8.3 of draft-irtf-cfrg-hash-to-curve-07. @@ -497,7 +760,7 @@ int ec_hash_to_curve_p384_xmd_sha512_sswu_draft07( dst_len, msg, msg_len); } -int ec_hash_to_scalar_p384_xmd_sha512_draft07( +int bssl::ec_hash_to_scalar_p384_xmd_sha512_draft07( const EC_GROUP *group, EC_SCALAR *out, const uint8_t *dst, size_t dst_len, const uint8_t *msg, size_t msg_len) { if (EC_GROUP_get_curve_name(group) != NID_secp384r1) { diff --git a/Sources/CNIOBoringSSL/crypto/ec/internal.h b/Sources/CNIOBoringSSL/crypto/ec/internal.h index 6f72332f..52da8161 100644 --- a/Sources/CNIOBoringSSL/crypto/ec/internal.h +++ b/Sources/CNIOBoringSSL/crypto/ec/internal.h @@ -1,57 +1,96 @@ -/* Copyright 2020 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2020 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. -#ifndef OPENSSL_HEADER_EC_EXTRA_INTERNAL_H -#define OPENSSL_HEADER_EC_EXTRA_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_EC_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_EC_INTERNAL_H #include +#include + #include "../fipsmodule/ec/internal.h" -#if defined(__cplusplus) -extern "C" { -#endif + +BSSL_NAMESPACE_BEGIN + +// Parsing functions. + +// ec_key_parse_curve_name behaves like `EC_KEY_parse_curve_name` but only +// supports the groups in `allowed_groups`. If no syntax errors were found but +// the group is unknown, it will fail with an error of `EC_R_UNKNOWN_GROUP`. +const EC_GROUP *ec_key_parse_curve_name( + CBS *cbs, bssl::Span allowed_groups); + +// ec_key_parse_parameters behaves like `EC_KEY_parse_parameters` but only +// supports the groups in `allowed_groups`. If no syntax errors were found but +// the group is unknown, it will fail with an error of `EC_R_UNKNOWN_GROUP`. +const EC_GROUP *ec_key_parse_parameters( + CBS *cbs, bssl::Span allowed_groups); + +// ec_key_parse_private_key behaves like `EC_KEY_parse_private_key` but only +// supports the groups in `allowed_groups`. If `group` is non-NULL, +// `allowed_groups` is ignored and instead only `group` is supported. +// +// TODO(crbug.com/boringssl/414361735): This should return a bssl::UniquePtr, +// but cannot until it is made C++ linkage. +EC_KEY *ec_key_parse_private_key( + CBS *cbs, const EC_GROUP *group, + bssl::Span allowed_groups); // Hash-to-curve. // -// Internal |EC_JACOBIAN| versions of the corresponding public APIs. +// Internal `EC_JACOBIAN` versions of the corresponding public APIs. -// ec_hash_to_curve_p256_xmd_sha256_sswu hashes |msg| to a point on |group| and -// writes the result to |out|, implementing the P256_XMD:SHA-256_SSWU_RO_ suite +// ec_hash_to_curve_p256_xmd_sha256_sswu hashes `msg` to a point on `group` and +// writes the result to `out`, implementing the P256_XMD:SHA-256_SSWU_RO_ suite // from RFC 9380. It returns one on success and zero on error. OPENSSL_EXPORT int ec_hash_to_curve_p256_xmd_sha256_sswu( const EC_GROUP *group, EC_JACOBIAN *out, const uint8_t *dst, size_t dst_len, const uint8_t *msg, size_t msg_len); -// ec_hash_to_curve_p384_xmd_sha384_sswu hashes |msg| to a point on |group| and -// writes the result to |out|, implementing the P384_XMD:SHA-384_SSWU_RO_ suite +// ec_hash_to_curve_p384_xmd_sha384_sswu hashes `msg` to a point on `group` and +// writes the result to `out`, implementing the P384_XMD:SHA-384_SSWU_RO_ suite // from RFC 9380. It returns one on success and zero on error. OPENSSL_EXPORT int ec_hash_to_curve_p384_xmd_sha384_sswu( const EC_GROUP *group, EC_JACOBIAN *out, const uint8_t *dst, size_t dst_len, const uint8_t *msg, size_t msg_len); -// ec_hash_to_scalar_p384_xmd_sha384 hashes |msg| to a scalar on |group| -// and writes the result to |out|, using the hash_to_field operation from the +// ec_encode_to_curve_p256_xmd_sha256_sswu hashes `msg` to a point on `group` +// and writes the result to `out`, implementing the P256_XMD:SHA-256_SSWU_NU_ +// suite from RFC 9380. It returns one on success and zero on error. +OPENSSL_EXPORT int ec_encode_to_curve_p256_xmd_sha256_sswu( + const EC_GROUP *group, EC_JACOBIAN *out, const uint8_t *dst, size_t dst_len, + const uint8_t *msg, size_t msg_len); + +// ec_encode_to_curve_p384_xmd_sha384_sswu hashes `msg` to a point on `group` +// and writes the result to `out`, implementing the P384_XMD:SHA-384_SSWU_NU_ +// suite from RFC 9380. It returns one on success and zero on error. +OPENSSL_EXPORT int ec_encode_to_curve_p384_xmd_sha384_sswu( + const EC_GROUP *group, EC_JACOBIAN *out, const uint8_t *dst, size_t dst_len, + const uint8_t *msg, size_t msg_len); + +// ec_hash_to_scalar_p384_xmd_sha384 hashes `msg` to a scalar on `group` +// and writes the result to `out`, using the hash_to_field operation from the // P384_XMD:SHA-384_SSWU_RO_ suite from RFC 9380, but generating a value modulo // the group order rather than a field element. OPENSSL_EXPORT int ec_hash_to_scalar_p384_xmd_sha384( const EC_GROUP *group, EC_SCALAR *out, const uint8_t *dst, size_t dst_len, const uint8_t *msg, size_t msg_len); -// ec_hash_to_curve_p384_xmd_sha512_sswu_draft07 hashes |msg| to a point on -// |group| and writes the result to |out|, implementing the +// ec_hash_to_curve_p384_xmd_sha512_sswu_draft07 hashes `msg` to a point on +// `group` and writes the result to `out`, implementing the // P384_XMD:SHA-512_SSWU_RO_ suite from draft-irtf-cfrg-hash-to-curve-07. It // returns one on success and zero on error. // @@ -60,8 +99,8 @@ OPENSSL_EXPORT int ec_hash_to_curve_p384_xmd_sha512_sswu_draft07( const EC_GROUP *group, EC_JACOBIAN *out, const uint8_t *dst, size_t dst_len, const uint8_t *msg, size_t msg_len); -// ec_hash_to_scalar_p384_xmd_sha512_draft07 hashes |msg| to a scalar on |group| -// and writes the result to |out|, using the hash_to_field operation from the +// ec_hash_to_scalar_p384_xmd_sha512_draft07 hashes `msg` to a scalar on `group` +// and writes the result to `out`, using the hash_to_field operation from the // P384_XMD:SHA-512_SSWU_RO_ suite from draft-irtf-cfrg-hash-to-curve-07, but // generating a value modulo the group order rather than a field element. // @@ -70,9 +109,6 @@ OPENSSL_EXPORT int ec_hash_to_scalar_p384_xmd_sha512_draft07( const EC_GROUP *group, EC_SCALAR *out, const uint8_t *dst, size_t dst_len, const uint8_t *msg, size_t msg_len); +BSSL_NAMESPACE_END -#if defined(__cplusplus) -} // extern C -#endif - -#endif // OPENSSL_HEADER_EC_EXTRA_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_EC_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/ecdh/ecdh.cc b/Sources/CNIOBoringSSL/crypto/ecdh/ecdh.cc index 833aa179..b392d8d8 100644 --- a/Sources/CNIOBoringSSL/crypto/ecdh/ecdh.cc +++ b/Sources/CNIOBoringSSL/crypto/ecdh/ecdh.cc @@ -1,12 +1,17 @@ -/* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. - * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. +// +// 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 @@ -21,17 +26,19 @@ #include "../internal.h" +using namespace bssl; + int ECDH_compute_key(void *out, size_t out_len, const EC_POINT *pub_key, const EC_KEY *priv_key, void *(*kdf)(const void *in, size_t inlen, void *out, size_t *out_len)) { - if (priv_key->priv_key == NULL) { + if (FromOpaque(priv_key)->priv_key == nullptr) { OPENSSL_PUT_ERROR(ECDH, ECDH_R_NO_PRIVATE_VALUE); return -1; } - const EC_SCALAR *const priv = &priv_key->priv_key->scalar; + const EC_SCALAR *const priv = &FromOpaque(priv_key)->priv_key->scalar; const EC_GROUP *const group = EC_KEY_get0_group(priv_key); - if (EC_GROUP_cmp(group, pub_key->group, NULL) != 0) { + if (EC_GROUP_cmp(group, pub_key->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return -1; } @@ -46,8 +53,8 @@ int ECDH_compute_key(void *out, size_t out_len, const EC_POINT *pub_key, return -1; } - if (kdf != NULL) { - if (kdf(buf, buf_len, out, &out_len) == NULL) { + if (kdf != nullptr) { + if (kdf(buf, buf_len, out, &out_len) == nullptr) { OPENSSL_PUT_ERROR(ECDH, ECDH_R_KDF_FAILED); return -1; } diff --git a/Sources/CNIOBoringSSL/crypto/ecdsa/ecdsa_asn1.cc b/Sources/CNIOBoringSSL/crypto/ecdsa/ecdsa_asn1.cc index 652294e3..d4588604 100644 --- a/Sources/CNIOBoringSSL/crypto/ecdsa/ecdsa_asn1.cc +++ b/Sources/CNIOBoringSSL/crypto/ecdsa/ecdsa_asn1.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -21,25 +26,28 @@ #include "../bytestring/internal.h" #include "../fipsmodule/ecdsa/internal.h" #include "../internal.h" +#include "../mem_internal.h" +using namespace bssl; + static ECDSA_SIG *ecdsa_sig_from_fixed(const EC_KEY *key, const uint8_t *in, size_t len) { const EC_GROUP *group = EC_KEY_get0_group(key); - if (group == NULL) { + if (group == nullptr) { OPENSSL_PUT_ERROR(ECDSA, ERR_R_PASSED_NULL_PARAMETER); - return NULL; + return nullptr; } size_t scalar_len = BN_num_bytes(EC_GROUP_get0_order(group)); if (len != 2 * scalar_len) { OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_BAD_SIGNATURE); - return NULL; + return nullptr; } ECDSA_SIG *ret = ECDSA_SIG_new(); - if (ret == NULL || !BN_bin2bn(in, scalar_len, ret->r) || + if (ret == nullptr || !BN_bin2bn(in, scalar_len, ret->r) || !BN_bin2bn(in + scalar_len, scalar_len, ret->s)) { ECDSA_SIG_free(ret); - return NULL; + return nullptr; } return ret; } @@ -47,7 +55,7 @@ static ECDSA_SIG *ecdsa_sig_from_fixed(const EC_KEY *key, const uint8_t *in, static int ecdsa_sig_to_fixed(const EC_KEY *key, uint8_t *out, size_t *out_len, size_t max_out, const ECDSA_SIG *sig) { const EC_GROUP *group = EC_KEY_get0_group(key); - if (group == NULL) { + if (group == nullptr) { OPENSSL_PUT_ERROR(ECDSA, ERR_R_PASSED_NULL_PARAMETER); return 0; } @@ -68,9 +76,10 @@ static int ecdsa_sig_to_fixed(const EC_KEY *key, uint8_t *out, size_t *out_len, int ECDSA_sign(int type, const uint8_t *digest, size_t digest_len, uint8_t *sig, unsigned int *out_sig_len, const EC_KEY *eckey) { - if (eckey->ecdsa_meth && eckey->ecdsa_meth->sign) { - return eckey->ecdsa_meth->sign(digest, digest_len, sig, out_sig_len, - (EC_KEY *)eckey /* cast away const */); + const ECKey *eckey_impl = FromOpaque(eckey); + if (eckey_impl->ecdsa_meth && eckey_impl->ecdsa_meth->sign) { + return eckey_impl->ecdsa_meth->sign(digest, digest_len, sig, out_sig_len, + (EC_KEY *)eckey /* cast away const */); } *out_sig_len = 0; @@ -83,25 +92,20 @@ int ECDSA_sign(int type, const uint8_t *digest, size_t digest_len, uint8_t *sig, // TODO(davidben): We can actually do better and go straight from the DER // format to the fixed-width format without a malloc. - ECDSA_SIG *s = ecdsa_sig_from_fixed(eckey, fixed, fixed_len); - if (s == NULL) { + UniquePtr s(ecdsa_sig_from_fixed(eckey, fixed, fixed_len)); + if (s == nullptr) { return 0; } - int ret = 0; CBB cbb; CBB_init_fixed(&cbb, sig, ECDSA_size(eckey)); size_t len; - if (!ECDSA_SIG_marshal(&cbb, s) || !CBB_finish(&cbb, NULL, &len)) { + if (!ECDSA_SIG_marshal(&cbb, s.get()) || !CBB_finish(&cbb, nullptr, &len)) { OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_ENCODE_ERROR); - goto err; + return 0; } - *out_sig_len = (unsigned)len; - ret = 1; - -err: - ECDSA_SIG_free(s); - return ret; + *out_sig_len = static_cast(len); + return 1; } int ECDSA_verify(int type, const uint8_t *digest, size_t digest_len, @@ -111,15 +115,15 @@ int ECDSA_verify(int type, const uint8_t *digest, size_t digest_len, // TODO(davidben): We can actually do better and go straight from the DER // format to the fixed-width format without a malloc. int ret = 0; - uint8_t *der = NULL; - ECDSA_SIG *s = ECDSA_SIG_from_bytes(sig, sig_len); - if (s == NULL) { + uint8_t *der = nullptr; + UniquePtr s(ECDSA_SIG_from_bytes(sig, sig_len)); + if (s == nullptr) { goto err; } // Defend against potential laxness in the DER parser. size_t der_len; - if (!ECDSA_SIG_to_bytes(&der, &der_len, s) || der_len != sig_len || + if (!ECDSA_SIG_to_bytes(&der, &der_len, s.get()) || der_len != sig_len || OPENSSL_memcmp(sig, der, sig_len) != 0) { // This should never happen. crypto/bytestring is strictly DER. OPENSSL_PUT_ERROR(ECDSA, ERR_R_INTERNAL_ERROR); @@ -128,23 +132,22 @@ int ECDSA_verify(int type, const uint8_t *digest, size_t digest_len, uint8_t fixed[ECDSA_MAX_FIXED_LEN]; size_t fixed_len; - ret = ecdsa_sig_to_fixed(eckey, fixed, &fixed_len, sizeof(fixed), s) && + ret = ecdsa_sig_to_fixed(eckey, fixed, &fixed_len, sizeof(fixed), s.get()) && ecdsa_verify_fixed(digest, digest_len, fixed, fixed_len, eckey); err: OPENSSL_free(der); - ECDSA_SIG_free(s); return ret; } size_t ECDSA_size(const EC_KEY *key) { - if (key == NULL) { + if (key == nullptr) { return 0; } const EC_GROUP *group = EC_KEY_get0_group(key); - if (group == NULL) { + if (group == nullptr) { return 0; } @@ -152,29 +155,28 @@ size_t ECDSA_size(const EC_KEY *key) { return ECDSA_SIG_max_len(group_order_size); } -ECDSA_SIG *ECDSA_SIG_new(void) { - ECDSA_SIG *sig = - reinterpret_cast(OPENSSL_malloc(sizeof(ECDSA_SIG))); - if (sig == NULL) { - return NULL; +ECDSA_SIG *ECDSA_SIG_new() { + ECDSA_SIG *sig = New(); + if (sig == nullptr) { + return nullptr; } sig->r = BN_new(); sig->s = BN_new(); - if (sig->r == NULL || sig->s == NULL) { + if (sig->r == nullptr || sig->s == nullptr) { ECDSA_SIG_free(sig); - return NULL; + return nullptr; } return sig; } void ECDSA_SIG_free(ECDSA_SIG *sig) { - if (sig == NULL) { + if (sig == nullptr) { return; } BN_free(sig->r); BN_free(sig->s); - OPENSSL_free(sig); + Delete(sig); } const BIGNUM *ECDSA_SIG_get0_r(const ECDSA_SIG *sig) { return sig->r; } @@ -183,16 +185,16 @@ const BIGNUM *ECDSA_SIG_get0_s(const ECDSA_SIG *sig) { return sig->s; } void ECDSA_SIG_get0(const ECDSA_SIG *sig, const BIGNUM **out_r, const BIGNUM **out_s) { - if (out_r != NULL) { + if (out_r != nullptr) { *out_r = sig->r; } - if (out_s != NULL) { + if (out_s != nullptr) { *out_s = sig->s; } } int ECDSA_SIG_set0(ECDSA_SIG *sig, BIGNUM *r, BIGNUM *s) { - if (r == NULL || s == NULL) { + if (r == nullptr || s == nullptr) { return 0; } BN_free(sig->r); @@ -220,7 +222,7 @@ ECDSA_SIG *ECDSA_sign_with_nonce_and_leak_private_key_for_testing( if (!ecdsa_sign_fixed_with_nonce_for_known_answer_test( digest, digest_len, sig, &sig_len, sizeof(sig), eckey, nonce, nonce_len)) { - return NULL; + return nullptr; } return ecdsa_sig_from_fixed(eckey, sig, sig_len); @@ -232,7 +234,7 @@ ECDSA_SIG *ECDSA_do_sign(const uint8_t *digest, size_t digest_len, size_t sig_len; if (!ecdsa_sign_fixed(digest, digest_len, sig, &sig_len, sizeof(sig), eckey)) { - return NULL; + return nullptr; } return ecdsa_sig_from_fixed(eckey, sig, sig_len); @@ -240,8 +242,8 @@ ECDSA_SIG *ECDSA_do_sign(const uint8_t *digest, size_t digest_len, ECDSA_SIG *ECDSA_SIG_parse(CBS *cbs) { ECDSA_SIG *ret = ECDSA_SIG_new(); - if (ret == NULL) { - return NULL; + if (ret == nullptr) { + return nullptr; } CBS child; if (!CBS_get_asn1(cbs, &child, CBS_ASN1_SEQUENCE) || @@ -249,7 +251,7 @@ ECDSA_SIG *ECDSA_SIG_parse(CBS *cbs) { !BN_parse_asn1_unsigned(&child, ret->s) || CBS_len(&child) != 0) { OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_BAD_SIGNATURE); ECDSA_SIG_free(ret); - return NULL; + return nullptr; } return ret; } @@ -258,10 +260,10 @@ ECDSA_SIG *ECDSA_SIG_from_bytes(const uint8_t *in, size_t in_len) { CBS cbs; CBS_init(&cbs, in, in_len); ECDSA_SIG *ret = ECDSA_SIG_parse(&cbs); - if (ret == NULL || CBS_len(&cbs) != 0) { + if (ret == nullptr || CBS_len(&cbs) != 0) { OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_BAD_SIGNATURE); ECDSA_SIG_free(ret); - return NULL; + return nullptr; } return ret; } @@ -290,7 +292,7 @@ int ECDSA_SIG_to_bytes(uint8_t **out_bytes, size_t *out_len, return 1; } -// der_len_len returns the number of bytes needed to represent a length of |len| +// der_len_len returns the number of bytes needed to represent a length of `len` // in DER. static size_t der_len_len(size_t len) { if (len < 0x80) { @@ -305,7 +307,7 @@ static size_t der_len_len(size_t len) { } size_t ECDSA_SIG_max_len(size_t order_len) { - // Compute the maximum length of an |order_len| byte integer. Defensively + // Compute the maximum length of an `order_len` byte integer. Defensively // assume that the leading 0x00 is included. size_t integer_len = 1 /* tag */ + der_len_len(order_len + 1) + 1 + order_len; if (integer_len < order_len) { @@ -325,28 +327,11 @@ size_t ECDSA_SIG_max_len(size_t order_len) { } ECDSA_SIG *d2i_ECDSA_SIG(ECDSA_SIG **out, const uint8_t **inp, long len) { - if (len < 0) { - return NULL; - } - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - ECDSA_SIG *ret = ECDSA_SIG_parse(&cbs); - if (ret == NULL) { - return NULL; - } - if (out != NULL) { - ECDSA_SIG_free(*out); - *out = ret; - } - *inp = CBS_data(&cbs); - return ret; + return D2IFromCBS(out, inp, len, ECDSA_SIG_parse); } int i2d_ECDSA_SIG(const ECDSA_SIG *sig, uint8_t **outp) { - CBB cbb; - if (!CBB_init(&cbb, 0) || !ECDSA_SIG_marshal(&cbb, sig)) { - CBB_cleanup(&cbb); - return -1; - } - return CBB_finish_i2d(&cbb, outp); + return I2DFromCBB( + /*initial_capacity=*/64, outp, + [&](CBB *cbb) -> bool { return ECDSA_SIG_marshal(cbb, sig); }); } diff --git a/Sources/CNIOBoringSSL/crypto/ecdsa/ecdsa_p1363.cc b/Sources/CNIOBoringSSL/crypto/ecdsa/ecdsa_p1363.cc new file mode 100644 index 00000000..3c036d21 --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/ecdsa/ecdsa_p1363.cc @@ -0,0 +1,54 @@ +// Copyright 2025 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 "../fipsmodule/ecdsa/internal.h" + + +using namespace bssl; + +int ECDSA_sign_p1363(const uint8_t *digest, size_t digest_len, uint8_t *sig, + size_t *out_sig_len, size_t max_sig_len, + const EC_KEY *eckey) { + return ecdsa_sign_fixed(digest, digest_len, sig, out_sig_len, max_sig_len, + eckey); +} + +int ECDSA_verify_p1363(const uint8_t *digest, size_t digest_len, + const uint8_t *sig, size_t sig_len, + const EC_KEY *eckey) { + return ecdsa_verify_fixed(digest, digest_len, sig, sig_len, eckey); +} + +size_t ECDSA_size_p1363(const EC_KEY *key) { + if (key == nullptr) { + return 0; + } + + const EC_GROUP *group = EC_KEY_get0_group(key); + if (group == nullptr) { + return 0; + } + + size_t group_order_size = BN_num_bytes(EC_GROUP_get0_order(group)); + return 2 * group_order_size; +} diff --git a/Sources/CNIOBoringSSL/crypto/engine/engine.cc b/Sources/CNIOBoringSSL/crypto/engine/engine.cc index d6e438b8..db731ad4 100644 --- a/Sources/CNIOBoringSSL/crypto/engine/engine.cc +++ b/Sources/CNIOBoringSSL/crypto/engine/engine.cc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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 @@ -21,28 +21,28 @@ #include #include #include -#include #include "../internal.h" +#include "../mem_internal.h" +using namespace bssl; + struct engine_st { RSA_METHOD *rsa_method; ECDSA_METHOD *ecdsa_method; }; -ENGINE *ENGINE_new(void) { - return reinterpret_cast(OPENSSL_zalloc(sizeof(ENGINE))); -} +ENGINE *ENGINE_new() { return New(); } int ENGINE_free(ENGINE *engine) { // Methods are currently required to be static so are not unref'ed. - OPENSSL_free(engine); + Delete(engine); return 1; } // set_method takes a pointer to a method and its given size and sets -// |*out_member| to point to it. This function might want to be extended in the +// `*out_member` to point to it. This function might want to be extended in the // future to support making a copy of the method so that a stable ABI for // ENGINEs can be supported. But, for the moment, all *_METHODS must be // static. @@ -86,7 +86,7 @@ void METHOD_unref(void *method_in) { struct openssl_method_common_st *method = reinterpret_cast(method_in); - if (method == NULL) { + if (method == nullptr) { return; } assert(method->is_static); diff --git a/Sources/CNIOBoringSSL/crypto/err/err.cc b/Sources/CNIOBoringSSL/crypto/err/err.cc index bae915c2..c53e2cd9 100644 --- a/Sources/CNIOBoringSSL/crypto/err/err.cc +++ b/Sources/CNIOBoringSSL/crypto/err/err.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. // Ensure we can't call OPENSSL_malloc circularly. #define _BORINGSSL_PROHIBIT_OPENSSL_MALLOC @@ -19,30 +24,29 @@ #include #if defined(OPENSSL_WINDOWS) -OPENSSL_MSVC_PRAGMA(warning(push, 3)) #include -OPENSSL_MSVC_PRAGMA(warning(pop)) #endif #include -#include #include "../internal.h" #include "./internal.h" +using namespace bssl; + namespace { struct err_error_st { // file contains the filename where the error occurred. const char *file; // data contains a NUL-terminated string with optional data. It is allocated - // with system |malloc| and must be freed with |free| (not |OPENSSL_free|) + // with system `malloc` and must be freed with `free` (not `OPENSSL_free`) char *data; // packed contains the error library and reason, as packed by ERR_PACK. uint32_t packed; // line contains the line number where the error occurred. uint16_t line; - // mark indicates a reversion point in the queue. See |ERR_pop_to_mark|. + // mark indicates a reversion point in the queue. See `ERR_pop_to_mark`. unsigned mark : 1; }; @@ -51,28 +55,32 @@ typedef struct err_state_st { // errors contains up to ERR_NUM_ERRORS - 1 most recent errors, organised as a // ring buffer. struct err_error_st errors[ERR_NUM_ERRORS]; - // top contains the index of the most recent error. If |top| equals |bottom| + // top contains the index of the most recent error. If `top` equals `bottom` // then the queue is empty. unsigned top; // bottom contains the index before the least recent error in the queue. unsigned bottom; // to_free, if not NULL, contains a pointer owned by this structure that was - // previously a |data| pointer of one of the elements of |errors|. + // previously a `data` pointer of one of the elements of `errors`. void *to_free; } ERR_STATE; } // namespace +BSSL_NAMESPACE_BEGIN + extern const uint32_t kOpenSSLReasonValues[]; extern const size_t kOpenSSLReasonValuesLen; extern const char kOpenSSLReasonStringData[]; +BSSL_NAMESPACE_END + static char *strdup_libc_malloc(const char *str) { - // |strdup| is not in C until C23, so MSVC triggers deprecation warnings, and + // `strdup` is not in C until C23, so MSVC triggers deprecation warnings, and // glibc and musl gate it on a feature macro. Reimplementing it is easier. size_t len = strlen(str); char *ret = reinterpret_cast(malloc(len + 1)); - if (ret != NULL) { + if (ret != nullptr) { memcpy(ret, str, len + 1); } return ret; @@ -87,7 +95,7 @@ static void err_clear(struct err_error_st *error) { static void err_copy(struct err_error_st *dst, const struct err_error_st *src) { err_clear(dst); dst->file = src->file; - if (src->data != NULL) { + if (src->data != nullptr) { // We can't use OPENSSL_strdup because we don't want to call OPENSSL_malloc, // which can affect the error stack. dst->data = strdup_libc_malloc(src->data); @@ -100,14 +108,14 @@ static void err_copy(struct err_error_st *dst, const struct err_error_st *src) { // global_next_library contains the next custom library value to return. static int global_next_library = ERR_NUM_LIBS; -// global_next_library_mutex protects |global_next_library| from concurrent +// global_next_library_mutex protects `global_next_library` from concurrent // updates. -static CRYPTO_MUTEX global_next_library_mutex = CRYPTO_MUTEX_INIT; +static StaticMutex global_next_library_mutex; static void err_state_free(void *statep) { ERR_STATE *state = reinterpret_cast(statep); - if (state == NULL) { + if (state == nullptr) { return; } @@ -119,18 +127,18 @@ static void err_state_free(void *statep) { } // err_get_state gets the ERR_STATE object for the current thread. -static ERR_STATE *err_get_state(void) { +static ERR_STATE *err_get_state() { ERR_STATE *state = reinterpret_cast( CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_ERR)); - if (state == NULL) { + if (state == nullptr) { state = reinterpret_cast(malloc(sizeof(ERR_STATE))); - if (state == NULL) { - return NULL; + if (state == nullptr) { + return nullptr; } OPENSSL_memset(state, 0, sizeof(ERR_STATE)); if (!CRYPTO_set_thread_local(OPENSSL_THREAD_LOCAL_ERR, state, err_state_free)) { - return NULL; + return nullptr; } } @@ -145,7 +153,7 @@ static uint32_t get_error_values(int inc, int top, const char **file, int *line, uint32_t ret; state = err_get_state(); - if (state == NULL || state->bottom == state->top) { + if (state == nullptr || state->bottom == state->top) { return 0; } @@ -160,8 +168,8 @@ static uint32_t get_error_values(int inc, int top, const char **file, int *line, error = &state->errors[i]; ret = error->packed; - if (file != NULL && line != NULL) { - if (error->file == NULL) { + if (file != nullptr && line != nullptr) { + if (error->file == nullptr) { *file = "NA"; *line = 0; } else { @@ -170,16 +178,16 @@ static uint32_t get_error_values(int inc, int top, const char **file, int *line, } } - if (data != NULL) { - if (error->data == NULL) { + if (data != nullptr) { + if (error->data == nullptr) { *data = ""; - if (flags != NULL) { + if (flags != nullptr) { *flags = 0; } } else { *data = error->data; - if (flags != NULL) { - // Without |ERR_FLAG_MALLOCED|, rust-openssl assumes the string has a + if (flags != nullptr) { + // Without `ERR_FLAG_MALLOCED`, rust-openssl assumes the string has a // static lifetime. In both cases, we retain ownership of the string, // and the caller is not expected to free it. *flags = ERR_FLAG_STRING | ERR_FLAG_MALLOCED; @@ -190,11 +198,11 @@ static uint32_t get_error_values(int inc, int top, const char **file, int *line, // ownership and retains it until the next call that affects the // error queue. if (inc) { - if (error->data != NULL) { + if (error->data != nullptr) { free(state->to_free); state->to_free = error->data; } - error->data = NULL; + error->data = nullptr; } } } @@ -208,12 +216,14 @@ static uint32_t get_error_values(int inc, int top, const char **file, int *line, return ret; } -uint32_t ERR_get_error(void) { - return get_error_values(1 /* inc */, 0 /* bottom */, NULL, NULL, NULL, NULL); +uint32_t ERR_get_error() { + return get_error_values(1 /* inc */, 0 /* bottom */, nullptr, nullptr, + nullptr, nullptr); } uint32_t ERR_get_error_line(const char **file, int *line) { - return get_error_values(1 /* inc */, 0 /* bottom */, file, line, NULL, NULL); + return get_error_values(1 /* inc */, 0 /* bottom */, file, line, nullptr, + nullptr); } uint32_t ERR_get_error_line_data(const char **file, int *line, @@ -221,12 +231,14 @@ uint32_t ERR_get_error_line_data(const char **file, int *line, return get_error_values(1 /* inc */, 0 /* bottom */, file, line, data, flags); } -uint32_t ERR_peek_error(void) { - return get_error_values(0 /* peek */, 0 /* bottom */, NULL, NULL, NULL, NULL); +uint32_t ERR_peek_error() { + return get_error_values(0 /* peek */, 0 /* bottom */, nullptr, nullptr, + nullptr, nullptr); } uint32_t ERR_peek_error_line(const char **file, int *line) { - return get_error_values(0 /* peek */, 0 /* bottom */, file, line, NULL, NULL); + return get_error_values(0 /* peek */, 0 /* bottom */, file, line, nullptr, + nullptr); } uint32_t ERR_peek_error_line_data(const char **file, int *line, @@ -235,12 +247,14 @@ uint32_t ERR_peek_error_line_data(const char **file, int *line, flags); } -uint32_t ERR_peek_last_error(void) { - return get_error_values(0 /* peek */, 1 /* top */, NULL, NULL, NULL, NULL); +uint32_t ERR_peek_last_error() { + return get_error_values(0 /* peek */, 1 /* top */, nullptr, nullptr, nullptr, + nullptr); } uint32_t ERR_peek_last_error_line(const char **file, int *line) { - return get_error_values(0 /* peek */, 1 /* top */, file, line, NULL, NULL); + return get_error_values(0 /* peek */, 1 /* top */, file, line, nullptr, + nullptr); } uint32_t ERR_peek_last_error_line_data(const char **file, int *line, @@ -248,11 +262,11 @@ uint32_t ERR_peek_last_error_line_data(const char **file, int *line, return get_error_values(0 /* peek */, 1 /* top */, file, line, data, flags); } -void ERR_clear_error(void) { +void ERR_clear_error() { ERR_STATE *const state = err_get_state(); unsigned i; - if (state == NULL) { + if (state == nullptr) { return; } @@ -260,13 +274,13 @@ void ERR_clear_error(void) { err_clear(&state->errors[i]); } free(state->to_free); - state->to_free = NULL; + state->to_free = nullptr; state->top = state->bottom = 0; } void ERR_remove_thread_state(const CRYPTO_THREADID *tid) { - if (tid != NULL) { + if (tid != nullptr) { assert(0); return; } @@ -274,22 +288,17 @@ void ERR_remove_thread_state(const CRYPTO_THREADID *tid) { ERR_clear_error(); } -int ERR_get_next_error_library(void) { - int ret; - - CRYPTO_MUTEX_lock_write(&global_next_library_mutex); - ret = global_next_library++; - CRYPTO_MUTEX_unlock_write(&global_next_library_mutex); - - return ret; +int ERR_get_next_error_library() { + MutexWriteLock lock(&global_next_library_mutex); + return global_next_library++; } void ERR_remove_state(unsigned long pid) { ERR_clear_error(); } -void ERR_clear_system_error(void) { errno = 0; } +void ERR_clear_system_error() { errno = 0; } // err_string_cmp is a compare function for searching error values with -// |bsearch| in |err_string_lookup|. +// `bsearch` in `err_string_lookup`. static int err_string_cmp(const void *a, const void *b) { const uint32_t a_key = *((const uint32_t *)a) >> 15; const uint32_t b_key = *((const uint32_t *)b) >> 15; @@ -303,32 +312,32 @@ static int err_string_cmp(const void *a, const void *b) { } } -// err_string_lookup looks up the string associated with |lib| and |key| in -// |values| and |string_data|. It returns the string or NULL if not found. +// err_string_lookup looks up the string associated with `lib` and `key` in +// `values` and `string_data`. It returns the string or NULL if not found. static const char *err_string_lookup(uint32_t lib, uint32_t key, const uint32_t *values, size_t num_values, const char *string_data) { - // |values| points to data in err_data.h, which is generated by + // `values` points to data in err_data.h, which is generated by // err_data_generate.go. It's an array of uint32_t values. Each value has the // following structure: // | lib | key | offset | // |6 bits| 11 bits | 15 bits | // - // The |lib| value is a library identifier: one of the |ERR_LIB_*| values. - // The |key| is a reason code, depending on the context. - // The |offset| is the number of bytes from the start of |string_data| where + // The `lib` value is a library identifier: one of the `ERR_LIB_*` values. + // The `key` is a reason code, depending on the context. + // The `offset` is the number of bytes from the start of `string_data` where // the (NUL terminated) string for this value can be found. // - // Values are sorted based on treating the |lib| and |key| part as an + // Values are sorted based on treating the `lib` and `key` part as an // unsigned integer. if (lib >= (1 << 6) || key >= (1 << 11)) { - return NULL; + return nullptr; } uint32_t search_key = lib << 26 | key << 15; const uint32_t *result = reinterpret_cast(bsearch( &search_key, values, num_values, sizeof(uint32_t), err_string_cmp)); - if (result == NULL) { - return NULL; + if (result == nullptr) { + return nullptr; } return &string_data[(*result) & 0x7fff]; @@ -343,7 +352,7 @@ typedef struct library_name_st { } // namespace static const LIBRARY_NAME kLibraryNames[ERR_NUM_LIBS] = { - {"invalid library (0)", NULL, NULL}, + {"invalid library (0)", nullptr, nullptr}, {"unknown library", "NONE", "NONE_LIB"}, {"system library", "SYS", "SYS_LIB"}, {"bignum routines", "BN", "BN_LIB"}, @@ -376,22 +385,23 @@ static const LIBRARY_NAME kLibraryNames[ERR_NUM_LIBS] = { {"Cipher functions", "CIPHER", "CIPHER_LIB"}, {"HKDF functions", "HKDF", "HKDF_LIB"}, {"Trust Token functions", "TRUST_TOKEN", "TRUST_TOKEN_LIB"}, + {"CMS routines", "CMS", "CMS_LIB"}, {"User defined functions", "USER", "USER_LIB"}, }; static const char *err_lib_error_string(uint32_t packed_error) { const uint32_t lib = ERR_GET_LIB(packed_error); - return lib >= ERR_NUM_LIBS ? NULL : kLibraryNames[lib].str; + return lib >= ERR_NUM_LIBS ? nullptr : kLibraryNames[lib].str; } const char *ERR_lib_error_string(uint32_t packed_error) { const char *ret = err_lib_error_string(packed_error); - return ret == NULL ? "unknown library" : ret; + return ret == nullptr ? "unknown library" : ret; } const char *ERR_lib_symbol_name(uint32_t packed_error) { const uint32_t lib = ERR_GET_LIB(packed_error); - return lib >= ERR_NUM_LIBS ? NULL : kLibraryNames[lib].symbol; + return lib >= ERR_NUM_LIBS ? nullptr : kLibraryNames[lib].symbol; } const char *ERR_func_error_string(uint32_t packed_error) { @@ -406,7 +416,7 @@ static const char *err_reason_error_string(uint32_t packed_error, int symbol) { if (!symbol && reason < 127) { return strerror(reason); } - return NULL; + return nullptr; } if (reason < ERR_NUM_LIBS) { @@ -431,19 +441,19 @@ static const char *err_reason_error_string(uint32_t packed_error, int symbol) { case ERR_R_OVERFLOW: return symbol ? "OVERFLOW" : "overflow"; default: - return NULL; + return nullptr; } } // Unlike OpenSSL, BoringSSL's reason strings already match symbol name, so we - // do not need to check |symbol|. + // do not need to check `symbol`. return err_string_lookup(lib, reason, kOpenSSLReasonValues, kOpenSSLReasonValuesLen, kOpenSSLReasonStringData); } const char *ERR_reason_error_string(uint32_t packed_error) { const char *ret = err_reason_error_string(packed_error, /*symbol=*/0); - return ret == NULL ? "unknown error" : ret; + return ret == nullptr ? "unknown error" : ret; } const char *ERR_reason_symbol_name(uint32_t packed_error) { @@ -453,14 +463,14 @@ const char *ERR_reason_symbol_name(uint32_t packed_error) { char *ERR_error_string(uint32_t packed_error, char *ret) { static char buf[ERR_ERROR_STRING_BUF_LEN]; - if (ret == NULL) { + if (ret == nullptr) { // TODO(fork): remove this. ret = buf; } #if !defined(NDEBUG) // This is aimed to help catch callers who don't provide - // |ERR_ERROR_STRING_BUF_LEN| bytes of space. + // `ERR_ERROR_STRING_BUF_LEN` bytes of space. OPENSSL_memset(ret, 0, ERR_ERROR_STRING_BUF_LEN); #endif @@ -469,7 +479,7 @@ char *ERR_error_string(uint32_t packed_error, char *ret) { char *ERR_error_string_n(uint32_t packed_error, char *buf, size_t len) { if (len == 0) { - return NULL; + return nullptr; } unsigned lib = ERR_GET_LIB(packed_error); @@ -479,12 +489,12 @@ char *ERR_error_string_n(uint32_t packed_error, char *buf, size_t len) { const char *reason_str = err_reason_error_string(packed_error, /*symbol=*/0); char lib_buf[32], reason_buf[32]; - if (lib_str == NULL) { + if (lib_str == nullptr) { snprintf(lib_buf, sizeof(lib_buf), "lib(%u)", lib); lib_str = lib_buf; } - if (reason_str == NULL) { + if (reason_str == nullptr) { snprintf(reason_buf, sizeof(reason_buf), "reason(%u)", reason); reason_str = reason_buf; } @@ -508,8 +518,8 @@ char *ERR_error_string_n(uint32_t packed_error, char *buf, size_t len) { char *colon = strchr(s, ':'); char *last_pos = &buf[len - 1] - num_colons + i; - if (colon == NULL || colon > last_pos) { - // set colon |i| at last possible position (buf[len-1] is the + if (colon == nullptr || colon > last_pos) { + // set colon `i` at last possible position (`buf[len-1]` is the // terminating 0). If we're setting this colon, then all whole of the // rest of the string must be colons in order to have the correct // number. @@ -531,7 +541,7 @@ void ERR_print_errors_cb(ERR_print_errors_callback_t callback, void *ctx) { int line, flags; uint32_t packed_error; - // thread_hash is the least-significant bits of the |ERR_STATE| pointer value + // thread_hash is the least-significant bits of the `ERR_STATE` pointer value // for this thread. const unsigned long thread_hash = (uintptr_t)err_get_state(); @@ -566,7 +576,7 @@ static void err_set_error_data(char *data) { ERR_STATE *const state = err_get_state(); struct err_error_st *error; - if (state == NULL || state->top == state->bottom) { + if (state == nullptr || state->top == state->bottom) { free(data); return; } @@ -582,7 +592,7 @@ void ERR_put_error(int library, int unused, int reason, const char *file, ERR_STATE *const state = err_get_state(); struct err_error_st *error; - if (state == NULL) { + if (state == nullptr) { return; } @@ -618,7 +628,7 @@ static void err_add_error_vdata(unsigned num, va_list args) { va_copy(args_copy, args); for (size_t i = 0; i < num; i++) { substr = va_arg(args_copy, const char *); - if (substr == NULL) { + if (substr == nullptr) { continue; } size_t substr_len = strlen(substr); @@ -632,13 +642,13 @@ static void err_add_error_vdata(unsigned num, va_list args) { return; // Would overflow. } total_size += 1; // NUL terminator. - if ((buf = reinterpret_cast(malloc(total_size))) == NULL) { + if ((buf = reinterpret_cast(malloc(total_size))) == nullptr) { return; } buf[0] = '\0'; for (size_t i = 0; i < num; i++) { substr = va_arg(args, const char *); - if (substr == NULL) { + if (substr == nullptr) { continue; } if (OPENSSL_strlcat(buf, substr, total_size) >= total_size) { @@ -656,14 +666,15 @@ void ERR_add_error_data(unsigned count, ...) { } void ERR_add_error_dataf(const char *format, ...) { - char *buf = NULL; + char *buf = nullptr; va_list ap; va_start(ap, format); - if (OPENSSL_vasprintf_internal(&buf, format, ap, /*system_malloc=*/1) == -1) { + int len = OPENSSL_vasprintf_internal(&buf, format, ap, /*system_malloc=*/1); + va_end(ap); + if (len == -1) { return; } - va_end(ap); err_set_error_data(buf); } @@ -677,30 +688,30 @@ void ERR_set_error_data(char *data, int flags) { // We can not use OPENSSL_strdup because we don't want to call OPENSSL_malloc, // which can affect the error stack. char *copy = strdup_libc_malloc(data); - if (copy != NULL) { + if (copy != nullptr) { err_set_error_data(copy); } if (flags & ERR_FLAG_MALLOCED) { - // We can not take ownership of |data| directly because it is allocated with - // |OPENSSL_malloc| and we will free it with system |free| later. + // We can not take ownership of `data` directly because it is allocated with + // `OPENSSL_malloc` and we will free it with system `free` later. OPENSSL_free(data); } } -int ERR_set_mark(void) { +int ERR_set_mark() { ERR_STATE *const state = err_get_state(); - if (state == NULL || state->bottom == state->top) { + if (state == nullptr || state->bottom == state->top) { return 0; } state->errors[state->top].mark = 1; return 1; } -int ERR_pop_to_mark(void) { +int ERR_pop_to_mark() { ERR_STATE *const state = err_get_state(); - if (state == NULL) { + if (state == nullptr) { return 0; } @@ -723,23 +734,27 @@ int ERR_pop_to_mark(void) { return 0; } -void ERR_load_crypto_strings(void) {} +void ERR_load_crypto_strings() {} -void ERR_free_strings(void) {} +void ERR_free_strings() {} -void ERR_load_BIO_strings(void) {} +void ERR_load_BIO_strings() {} -void ERR_load_ERR_strings(void) {} +void ERR_load_ERR_strings() {} -void ERR_load_RAND_strings(void) {} +void ERR_load_RAND_strings() {} + +BSSL_NAMESPACE_BEGIN struct err_save_state_st { struct err_error_st *errors; size_t num_errors; }; -void ERR_SAVE_STATE_free(ERR_SAVE_STATE *state) { - if (state == NULL) { +BSSL_NAMESPACE_END + +void bssl::ERR_SAVE_STATE_free(ERR_SAVE_STATE *state) { + if (state == nullptr) { return; } for (size_t i = 0; i < state->num_errors; i++) { @@ -749,16 +764,16 @@ void ERR_SAVE_STATE_free(ERR_SAVE_STATE *state) { free(state); } -ERR_SAVE_STATE *ERR_save_state(void) { +ERR_SAVE_STATE *bssl::ERR_save_state() { ERR_STATE *const state = err_get_state(); - if (state == NULL || state->top == state->bottom) { - return NULL; + if (state == nullptr || state->top == state->bottom) { + return nullptr; } ERR_SAVE_STATE *ret = reinterpret_cast(malloc(sizeof(ERR_SAVE_STATE))); - if (ret == NULL) { - return NULL; + if (ret == nullptr) { + return nullptr; } // Errors are stored in the range (bottom, top]. @@ -768,9 +783,9 @@ ERR_SAVE_STATE *ERR_save_state(void) { assert(num_errors < ERR_NUM_ERRORS); ret->errors = reinterpret_cast( malloc(num_errors * sizeof(struct err_error_st))); - if (ret->errors == NULL) { + if (ret->errors == nullptr) { free(ret); - return NULL; + return nullptr; } OPENSSL_memset(ret->errors, 0, num_errors * sizeof(struct err_error_st)); ret->num_errors = num_errors; @@ -782,8 +797,8 @@ ERR_SAVE_STATE *ERR_save_state(void) { return ret; } -void ERR_restore_state(const ERR_SAVE_STATE *state) { - if (state == NULL || state->num_errors == 0) { +void bssl::ERR_restore_state(const ERR_SAVE_STATE *state) { + if (state == nullptr || state->num_errors == 0) { ERR_clear_error(); return; } @@ -793,7 +808,7 @@ void ERR_restore_state(const ERR_SAVE_STATE *state) { } ERR_STATE *const dst = err_get_state(); - if (dst == NULL) { + if (dst == nullptr) { return; } diff --git a/Sources/CNIOBoringSSL/crypto/err/internal.h b/Sources/CNIOBoringSSL/crypto/err/internal.h index d6655848..5b291e83 100644 --- a/Sources/CNIOBoringSSL/crypto/err/internal.h +++ b/Sources/CNIOBoringSSL/crypto/err/internal.h @@ -1,58 +1,45 @@ -/* Copyright 2017 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2017 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. #ifndef OPENSSL_HEADER_CRYPTO_ERR_INTERNAL_H #define OPENSSL_HEADER_CRYPTO_ERR_INTERNAL_H #include -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN // Private error queue functions. // ERR_SAVE_STATE contains a saved representation of the error queue. It is -// slightly more compact than |ERR_STATE| as the error queue will typically not -// contain |ERR_NUM_ERRORS| entries. +// slightly more compact than `ERR_STATE` as the error queue will typically not +// contain `ERR_NUM_ERRORS` entries. typedef struct err_save_state_st ERR_SAVE_STATE; -// ERR_SAVE_STATE_free releases all memory associated with |state|. +// ERR_SAVE_STATE_free releases all memory associated with `state`. OPENSSL_EXPORT void ERR_SAVE_STATE_free(ERR_SAVE_STATE *state); -// ERR_save_state returns a newly-allocated |ERR_SAVE_STATE| structure +// ERR_save_state returns a newly-allocated `ERR_SAVE_STATE` structure // containing the current state of the error queue or NULL on allocation -// error. It should be released with |ERR_SAVE_STATE_free|. -OPENSSL_EXPORT ERR_SAVE_STATE *ERR_save_state(void); +// error. It should be released with `ERR_SAVE_STATE_free`. +OPENSSL_EXPORT ERR_SAVE_STATE *ERR_save_state(); -// ERR_restore_state clears the error queue and replaces it with |state|. +// ERR_restore_state clears the error queue and replaces it with `state`. OPENSSL_EXPORT void ERR_restore_state(const ERR_SAVE_STATE *state); - -#if defined(__cplusplus) -} // extern C - -extern "C++" { - -BSSL_NAMESPACE_BEGIN - BORINGSSL_MAKE_DELETER(ERR_SAVE_STATE, ERR_SAVE_STATE_free) BSSL_NAMESPACE_END -} // extern C++ -#endif - #endif // OPENSSL_HEADER_CRYPTO_ERR_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/evp/evp.cc b/Sources/CNIOBoringSSL/crypto/evp/evp.cc index 6dfcfc94..72498de0 100644 --- a/Sources/CNIOBoringSSL/crypto/evp/evp.cc +++ b/Sources/CNIOBoringSSL/crypto/evp/evp.cc @@ -1,27 +1,35 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../internal.h" +#include "../mem_internal.h" #include "internal.h" -// Node depends on |EVP_R_NOT_XOF_OR_INVALID_LENGTH|. +using namespace bssl; + +// Node depends on `EVP_R_NOT_XOF_OR_INVALID_LENGTH`. // // TODO(davidben): Fix Node to not touch the error queue itself and remove this. OPENSSL_DECLARE_ERROR_REASON(EVP, NOT_XOF_OR_INVALID_LENGTH) @@ -30,152 +38,145 @@ OPENSSL_DECLARE_ERROR_REASON(EVP, NOT_XOF_OR_INVALID_LENGTH) // directory. OPENSSL_DECLARE_ERROR_REASON(EVP, EMPTY_PSK) -EVP_PKEY *EVP_PKEY_new(void) { - EVP_PKEY *ret = - reinterpret_cast(OPENSSL_zalloc(sizeof(EVP_PKEY))); - if (ret == NULL) { - return NULL; - } +EVP_PKEY *EVP_PKEY_new() { return New(); } - ret->type = EVP_PKEY_NONE; - ret->references = 1; - return ret; -} +EvpPkey::EvpPkey() : RefCounted(CheckSubClass()) {} -static void free_it(EVP_PKEY *pkey) { - if (pkey->ameth && pkey->ameth->pkey_free) { - pkey->ameth->pkey_free(pkey); - pkey->pkey = NULL; - pkey->type = EVP_PKEY_NONE; - } -} +EvpPkey::~EvpPkey() { evp_pkey_set0(this, nullptr, nullptr); } void EVP_PKEY_free(EVP_PKEY *pkey) { - if (pkey == NULL) { + if (pkey == nullptr) { return; } - if (!CRYPTO_refcount_dec_and_test_zero(&pkey->references)) { - return; - } - - free_it(pkey); - OPENSSL_free(pkey); + auto *impl = FromOpaque(pkey); + impl->DecRefInternal(); } int EVP_PKEY_up_ref(EVP_PKEY *pkey) { - CRYPTO_refcount_inc(&pkey->references); + auto *impl = FromOpaque(pkey); + impl->UpRefInternal(); return 1; } +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; +} + int EVP_PKEY_is_opaque(const EVP_PKEY *pkey) { - if (pkey->ameth && pkey->ameth->pkey_opaque) { - return pkey->ameth->pkey_opaque(pkey); + auto *impl = FromOpaque(pkey); + if (impl->ameth && impl->ameth->pkey_opaque) { + return impl->ameth->pkey_opaque(impl); } return 0; } +int EVP_PKEY_eq(const EVP_PKEY *a, const EVP_PKEY *b) { + // This also checks that `EVP_PKEY_id` matches. + if (!EVP_PKEY_parameters_eq(a, b)) { + return 0; + } + + auto *a_impl = FromOpaque(a); + auto *b_impl = FromOpaque(b); + return a_impl->ameth != nullptr && a_impl->ameth->pub_equal != nullptr && + a_impl->pkey != nullptr && b_impl->pkey != nullptr && + a_impl->ameth->pub_equal(a_impl, b_impl); +} + int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { - if (a->type != b->type) { - return -1; - } - - if (a->ameth) { - int ret; - // Compare parameters if the algorithm has them - if (a->ameth->param_cmp) { - ret = a->ameth->param_cmp(a, b); - if (ret <= 0) { - return ret; - } - } - - if (a->ameth->pub_cmp) { - return a->ameth->pub_cmp(a, b); - } - } - - return -2; + return EVP_PKEY_eq(a, b); } int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from) { - if (to->type == EVP_PKEY_NONE) { - evp_pkey_set_method(to, from->ameth); - } else if (to->type != from->type) { + auto *to_impl = FromOpaque(to); + auto *from_impl = FromOpaque(from); + + if (EVP_PKEY_id(to_impl) == EVP_PKEY_NONE) { + // TODO(crbug.com/42290409): This shouldn't leave `to` in a half-empty state + // on error. The complexity here largely comes from parameterless DSA keys, + // which we no longer support, so this function can probably be trimmed + // down. + evp_pkey_set0(to_impl, from_impl->ameth, nullptr); + } else if (EVP_PKEY_id(to_impl) != EVP_PKEY_id(from_impl)) { OPENSSL_PUT_ERROR(EVP, EVP_R_DIFFERENT_KEY_TYPES); return 0; } - if (EVP_PKEY_missing_parameters(from)) { + if (EVP_PKEY_missing_parameters(from_impl)) { OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PARAMETERS); return 0; } // Once set, parameters may not change. - if (!EVP_PKEY_missing_parameters(to)) { - if (EVP_PKEY_cmp_parameters(to, from) == 1) { + if (!EVP_PKEY_missing_parameters(to_impl)) { + if (EVP_PKEY_parameters_eq(to_impl, from_impl) == 1) { return 1; } OPENSSL_PUT_ERROR(EVP, EVP_R_DIFFERENT_PARAMETERS); return 0; } - if (from->ameth && from->ameth->param_copy) { - return from->ameth->param_copy(to, from); + if (from_impl->ameth && from_impl->ameth->param_copy) { + return from_impl->ameth->param_copy(to_impl, from_impl); } - // TODO(https://crbug.com/boringssl/536): If the algorithm takes no - // parameters, copying them should vacuously succeed. + // TODO(https://crbug.com/42290406): If the algorithm takes no parameters, + // copying them should vacuously succeed. Better yet, simplify this whole + // notion of parameter copying above. return 0; } int EVP_PKEY_missing_parameters(const EVP_PKEY *pkey) { - if (pkey->ameth && pkey->ameth->param_missing) { - return pkey->ameth->param_missing(pkey); + auto *impl = FromOpaque(pkey); + if (impl->ameth == nullptr) { + return 0; // EVP_PKEY_NONE is not parameterized, so nothing is missing. } - return 0; + if (impl->pkey == nullptr) { + // This is an invalid, half-empty object. Report something is missing to + // stop other parameter-based functions. + return 1; + } + if (impl->ameth->param_missing) { + return impl->ameth->param_missing(impl); + } + return 0; // Not parameterized, so nothing is missing. } int EVP_PKEY_size(const EVP_PKEY *pkey) { - if (pkey && pkey->ameth && pkey->ameth->pkey_size) { - return pkey->ameth->pkey_size(pkey); + auto *impl = FromOpaque(pkey); + if (impl && impl->ameth && impl->ameth->pkey_size) { + return impl->ameth->pkey_size(impl); } return 0; } int EVP_PKEY_bits(const EVP_PKEY *pkey) { - if (pkey && pkey->ameth && pkey->ameth->pkey_bits) { - return pkey->ameth->pkey_bits(pkey); + auto *impl = FromOpaque(pkey); + if (impl && impl->ameth && impl->ameth->pkey_bits) { + return impl->ameth->pkey_bits(impl); } return 0; } -int EVP_PKEY_id(const EVP_PKEY *pkey) { return pkey->type; } - -// evp_pkey_asn1_find returns the ASN.1 method table for the given |nid|, which -// should be one of the |EVP_PKEY_*| values. It returns NULL if |nid| is -// unknown. -static const EVP_PKEY_ASN1_METHOD *evp_pkey_asn1_find(int nid) { - switch (nid) { - case EVP_PKEY_RSA: - return &rsa_asn1_meth; - case EVP_PKEY_EC: - return &ec_asn1_meth; - case EVP_PKEY_DSA: - return &dsa_asn1_meth; - case EVP_PKEY_ED25519: - return &ed25519_asn1_meth; - case EVP_PKEY_X25519: - return &x25519_asn1_meth; - default: - return NULL; - } +int EVP_PKEY_id(const EVP_PKEY *pkey) { + auto *impl = FromOpaque(pkey); + return impl->ameth != nullptr ? impl->ameth->pkey_id : EVP_PKEY_NONE; } -void evp_pkey_set_method(EVP_PKEY *pkey, const EVP_PKEY_ASN1_METHOD *method) { - free_it(pkey); +void bssl::evp_pkey_set0(EvpPkey *pkey, const EVP_PKEY_ASN1_METHOD *method, + void *pkey_data) { + if (pkey->ameth && pkey->ameth->pkey_free) { + pkey->ameth->pkey_free(pkey); + } pkey->ameth = method; - pkey->type = pkey->ameth->pkey_id; + pkey->pkey = pkey_data; } int EVP_PKEY_type(int nid) { @@ -205,117 +206,147 @@ int EVP_PKEY_assign(EVP_PKEY *pkey, int type, void *key) { } int EVP_PKEY_set_type(EVP_PKEY *pkey, int type) { - if (pkey && pkey->pkey) { - // This isn't strictly necessary, but historically |EVP_PKEY_set_type| would - // clear |pkey| even if |evp_pkey_asn1_find| failed, so we preserve that - // behavior. - free_it(pkey); + auto *impl = FromOpaque(pkey); + if (impl && impl->pkey) { + // Some callers rely on `pkey` getting cleared even if `type` is + // unsupported, usually setting `type` to `EVP_PKEY_NONE`. + evp_pkey_set0(impl, nullptr, nullptr); } - const EVP_PKEY_ASN1_METHOD *ameth = evp_pkey_asn1_find(type); - if (ameth == NULL) { + // This function broadly isn't useful. It initializes `EVP_PKEY` for a type, + // but forgets to put anything in the `pkey`. The one pattern where it does + // anything is `EVP_PKEY_X25519`, where it's needed to make + // `EVP_PKEY_set1_tls_encodedpoint` work, so we support only that. + const EVP_PKEY_ALG *alg; + if (type == EVP_PKEY_X25519) { + alg = EVP_pkey_x25519(); + } else { OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); ERR_add_error_dataf("algorithm %d", type); return 0; } - if (pkey) { - evp_pkey_set_method(pkey, ameth); + if (impl) { + evp_pkey_set0(impl, alg->method, nullptr); } return 1; } +EVP_PKEY *EVP_PKEY_from_raw_private_key(const EVP_PKEY_ALG *alg, + const uint8_t *in, size_t len) { + if (alg->method->set_priv_raw == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); + return nullptr; + } + UniquePtr ret(FromOpaque(EVP_PKEY_new())); + if (ret == nullptr || !alg->method->set_priv_raw(ret.get(), in, len)) { + return nullptr; + } + return ret.release(); +} + +EVP_PKEY *EVP_PKEY_from_private_seed(const EVP_PKEY_ALG *alg, const uint8_t *in, + size_t len) { + if (alg->method->set_priv_seed == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); + return nullptr; + } + UniquePtr ret(FromOpaque(EVP_PKEY_new())); + if (ret == nullptr || !alg->method->set_priv_seed(ret.get(), in, len)) { + return nullptr; + } + return ret.release(); +} + +EVP_PKEY *EVP_PKEY_from_raw_public_key(const EVP_PKEY_ALG *alg, + const uint8_t *in, size_t len) { + if (alg->method->set_pub_raw == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); + return nullptr; + } + UniquePtr ret(FromOpaque(EVP_PKEY_new())); + if (ret == nullptr || !alg->method->set_pub_raw(ret.get(), in, len)) { + return nullptr; + } + return ret.release(); +} + EVP_PKEY *EVP_PKEY_new_raw_private_key(int type, ENGINE *unused, const uint8_t *in, size_t len) { - // To avoid pulling in all key types, look for specifically the key types that - // support |set_priv_raw|. - const EVP_PKEY_ASN1_METHOD *method; - switch (type) { - case EVP_PKEY_X25519: - method = &x25519_asn1_meth; - break; - case EVP_PKEY_ED25519: - method = &ed25519_asn1_meth; - break; - default: - OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); - return nullptr; + for (const EVP_PKEY_ALG *alg : GetDefaultEVPAlgorithms()) { + if (alg->method && alg->method->pkey_id == type) { + return EVP_PKEY_from_raw_private_key(alg, in, len); + } } - - bssl::UniquePtr ret(EVP_PKEY_new()); - if (ret == nullptr) { - return nullptr; - } - evp_pkey_set_method(ret.get(), method); - - if (!ret->ameth->set_priv_raw(ret.get(), in, len)) { - return nullptr; - } - - return ret.release(); + OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); + return nullptr; } EVP_PKEY *EVP_PKEY_new_raw_public_key(int type, ENGINE *unused, const uint8_t *in, size_t len) { - // To avoid pulling in all key types, look for specifically the key types that - // support |set_pub_raw|. - const EVP_PKEY_ASN1_METHOD *method; - switch (type) { - case EVP_PKEY_X25519: - method = &x25519_asn1_meth; - break; - case EVP_PKEY_ED25519: - method = &ed25519_asn1_meth; - break; - default: - OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); - return nullptr; + for (const EVP_PKEY_ALG *alg : GetDefaultEVPAlgorithms()) { + if (alg->method && alg->method->pkey_id == type) { + return EVP_PKEY_from_raw_public_key(alg, in, len); + } } - - bssl::UniquePtr ret(EVP_PKEY_new()); - if (ret == nullptr) { - return nullptr; - } - evp_pkey_set_method(ret.get(), method); - - if (!ret->ameth->set_pub_raw(ret.get(), in, len)) { - return nullptr; - } - - return ret.release(); + OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); + return nullptr; } int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, uint8_t *out, size_t *out_len) { - if (pkey->ameth->get_priv_raw == NULL) { + auto *impl = FromOpaque(pkey); + + if (impl->ameth == nullptr || impl->ameth->get_priv_raw == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - return pkey->ameth->get_priv_raw(pkey, out, out_len); + return impl->ameth->get_priv_raw(impl, out, out_len); +} + +int EVP_PKEY_get_private_seed(const EVP_PKEY *pkey, uint8_t *out, + size_t *out_len) { + auto *impl = FromOpaque(pkey); + + if (impl->ameth == nullptr || impl->ameth->get_priv_seed == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + return 0; + } + + return impl->ameth->get_priv_seed(impl, out, out_len); } int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, uint8_t *out, size_t *out_len) { - if (pkey->ameth->get_pub_raw == NULL) { + auto *impl = FromOpaque(pkey); + + if (impl->ameth == nullptr || impl->ameth->get_pub_raw == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - return pkey->ameth->get_pub_raw(pkey, out, out_len); + return impl->ameth->get_pub_raw(impl, out, out_len); +} + +int EVP_PKEY_parameters_eq(const EVP_PKEY *a, const EVP_PKEY *b) { + if (EVP_PKEY_id(a) != EVP_PKEY_id(b)) { + return 0; + } + + auto *a_impl = FromOpaque(a); + auto *b_impl = FromOpaque(b); + if (a_impl->ameth && a_impl->ameth->param_equal) { + return a_impl->ameth->param_equal(a_impl, b_impl); + } + // If the algorithm does not use parameters, the two null value compare as + // vacuously equal. + return 1; } int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b) { - if (a->type != b->type) { - return -1; - } - if (a->ameth && a->ameth->param_cmp) { - return a->ameth->param_cmp(a, b); - } - // TODO(https://crbug.com/boringssl/536): If the algorithm doesn't use - // parameters, they should compare as vacuously equal. - return -2; + return EVP_PKEY_parameters_eq(a, b); } int EVP_PKEY_CTX_set_signature_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { @@ -328,42 +359,59 @@ int EVP_PKEY_CTX_get_signature_md(EVP_PKEY_CTX *ctx, const EVP_MD **out_md) { 0, (void *)out_md); } -void *EVP_PKEY_get0(const EVP_PKEY *pkey) { - // Node references, but never calls this function, so for now we return NULL. - // If other projects require complete support, call |EVP_PKEY_get0_RSA|, etc., - // rather than reading |pkey->pkey| directly. This avoids problems if our - // internal representation does not match the type the caller expects from - // OpenSSL. - return NULL; +int EVP_PKEY_CTX_set1_signature_context_string(EVP_PKEY_CTX *ctx, + const uint8_t *context, + size_t context_len) { + Span context_string(context, context_len); + return EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_TYPE_SIG, + EVP_PKEY_CTRL_SIGNATURE_CONTEXT_STRING, 0, + &context_string); } -void OpenSSL_add_all_algorithms(void) {} +void *EVP_PKEY_get0(const EVP_PKEY *pkey) { + // Node references, but never calls this function, so for now we return NULL. + // If other projects require complete support, call `EVP_PKEY_get0_RSA`, etc., + // rather than reading `pkey->pkey` directly. This avoids problems if our + // internal representation does not match the type the caller expects from + // OpenSSL. + return nullptr; +} -void OPENSSL_add_all_algorithms_conf(void) {} +void OpenSSL_add_all_algorithms() {} -void OpenSSL_add_all_ciphers(void) {} +void OPENSSL_add_all_algorithms_conf() {} -void OpenSSL_add_all_digests(void) {} +void OpenSSL_add_all_ciphers() {} -void EVP_cleanup(void) {} +void OpenSSL_add_all_digests() {} + +void EVP_cleanup() {} + +int EVP_default_properties_is_fips_enabled(OSSL_LIB_CTX *libctx) { + return FIPS_mode(); +} int EVP_PKEY_set1_tls_encodedpoint(EVP_PKEY *pkey, const uint8_t *in, size_t len) { - if (pkey->ameth->set1_tls_encodedpoint == NULL) { + auto *impl = FromOpaque(pkey); + + if (impl->ameth == nullptr || impl->ameth->set1_tls_encodedpoint == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - return pkey->ameth->set1_tls_encodedpoint(pkey, in, len); + return impl->ameth->set1_tls_encodedpoint(impl, in, len); } size_t EVP_PKEY_get1_tls_encodedpoint(const EVP_PKEY *pkey, uint8_t **out_ptr) { - if (pkey->ameth->get1_tls_encodedpoint == NULL) { + auto *impl = FromOpaque(pkey); + + if (impl->ameth == nullptr || impl->ameth->get1_tls_encodedpoint == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - return pkey->ameth->get1_tls_encodedpoint(pkey, out_ptr); + return impl->ameth->get1_tls_encodedpoint(impl, out_ptr); } int EVP_PKEY_base_id(const EVP_PKEY *pkey) { @@ -372,3 +420,35 @@ int EVP_PKEY_base_id(const EVP_PKEY *pkey) { // of DSA. We do not support these, so the base ID is simply the ID. return EVP_PKEY_id(pkey); } + +int EVP_PKEY_has_public(const EVP_PKEY *pkey) { + auto *impl = FromOpaque(pkey); + if (impl == nullptr || impl->ameth == nullptr || impl->pkey == nullptr || + impl->ameth->pub_present == nullptr) { + return 0; + } + return impl->ameth->pub_present(impl); +} + +int EVP_PKEY_has_private(const EVP_PKEY *pkey) { + auto *impl = FromOpaque(pkey); + if (impl == nullptr || impl->ameth == nullptr || impl->pkey == nullptr || + impl->ameth->priv_present == nullptr) { + return 0; + } + return impl->ameth->priv_present(impl); +} + +EVP_PKEY *EVP_PKEY_copy_public(const EVP_PKEY *pkey) { + auto *impl = FromOpaque(pkey); + if (impl == nullptr || impl->ameth == nullptr || impl->pkey == nullptr || + impl->ameth->pub_copy == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + return nullptr; + } + UniquePtr ret(FromOpaque(EVP_PKEY_new())); + if (ret == nullptr || !impl->ameth->pub_copy(ret.get(), impl)) { + return nullptr; + } + return ret.release(); +} diff --git a/Sources/CNIOBoringSSL/crypto/evp/evp_asn1.cc b/Sources/CNIOBoringSSL/crypto/evp/evp_asn1.cc index 93f5e863..d47c5fe5 100644 --- a/Sources/CNIOBoringSSL/crypto/evp/evp_asn1.cc +++ b/Sources/CNIOBoringSSL/crypto/evp/evp_asn1.cc @@ -1,162 +1,192 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "internal.h" #include "../bytestring/internal.h" #include "../internal.h" +#include "../mem_internal.h" +#include "internal.h" -// We intentionally omit |dh_asn1_meth| from this list. It is not serializable. -static const EVP_PKEY_ASN1_METHOD *const kASN1Methods[] = { - &rsa_asn1_meth, - &ec_asn1_meth, - &dsa_asn1_meth, - &ed25519_asn1_meth, - &x25519_asn1_meth, -}; +using namespace bssl; -static const EVP_PKEY_ASN1_METHOD *parse_key_type(CBS *cbs) { - CBS oid; - if (!CBS_get_asn1(cbs, &oid, CBS_ASN1_OBJECT)) { - return NULL; +EVP_PKEY *EVP_PKEY_from_subject_public_key_info(const uint8_t *in, size_t len, + const EVP_PKEY_ALG *const *algs, + size_t num_algs) { + // Parse the SubjectPublicKeyInfo. + CBS cbs, spki, algorithm, oid, key; + CBS_init(&cbs, in, len); + if (!CBS_get_asn1(&cbs, &spki, CBS_ASN1_SEQUENCE) || + !CBS_get_asn1(&spki, &algorithm, CBS_ASN1_SEQUENCE) || + !CBS_get_asn1(&algorithm, &oid, CBS_ASN1_OBJECT) || + !CBS_get_asn1(&spki, &key, CBS_ASN1_BITSTRING) || + CBS_len(&spki) != 0 || // + CBS_len(&cbs) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return nullptr; } - for (unsigned i = 0; i < OPENSSL_ARRAY_SIZE(kASN1Methods); i++) { - const EVP_PKEY_ASN1_METHOD *method = kASN1Methods[i]; - if (CBS_len(&oid) == method->oid_len && - OPENSSL_memcmp(CBS_data(&oid), method->oid, method->oid_len) == 0) { - return method; + UniquePtr ret(FromOpaque(EVP_PKEY_new())); + if (ret == nullptr) { + return nullptr; + } + for (const EVP_PKEY_ALG *alg : Span(algs, num_algs)) { + if (alg->method->pub_decode == nullptr || + Span(alg->method->oid, alg->method->oid_len) != oid) { + continue; + } + // Every key type we support encodes the key as a byte string with the same + // conversion to BIT STRING, so perform that common conversion ahead of + // time, but only after the OID is recognized as supported. + CBS key_bytes = key; + uint8_t padding; + if (!CBS_get_u8(&key_bytes, &padding) || padding != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return nullptr; + } + CBS params = algorithm; + switch (alg->method->pub_decode(alg, ret.get(), ¶ms, &key_bytes)) { + case evp_decode_error: + return nullptr; + case evp_decode_ok: + return ret.release(); + case evp_decode_unsupported: + // Continue trying other algorithms. + break; } } - return NULL; -} - -EVP_PKEY *EVP_parse_public_key(CBS *cbs) { - // Parse the SubjectPublicKeyInfo. - CBS spki, algorithm, key; - uint8_t padding; - if (!CBS_get_asn1(cbs, &spki, CBS_ASN1_SEQUENCE) || - !CBS_get_asn1(&spki, &algorithm, CBS_ASN1_SEQUENCE) || - !CBS_get_asn1(&spki, &key, CBS_ASN1_BITSTRING) || - CBS_len(&spki) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return nullptr; - } - const EVP_PKEY_ASN1_METHOD *method = parse_key_type(&algorithm); - if (method == nullptr) { - OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); - return nullptr; - } - if (// Every key type defined encodes the key as a byte string with the same - // conversion to BIT STRING. - !CBS_get_u8(&key, &padding) || - padding != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return nullptr; - } - - // Set up an |EVP_PKEY| of the appropriate type. - bssl::UniquePtr ret(EVP_PKEY_new()); - if (ret == nullptr) { - return nullptr; - } - evp_pkey_set_method(ret.get(), method); - - // Call into the type-specific SPKI decoding function. - if (ret->ameth->pub_decode == nullptr) { - OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); - return nullptr; - } - if (!ret->ameth->pub_decode(ret.get(), &algorithm, &key)) { - return nullptr; - } - - return ret.release(); + OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); + return nullptr; } int EVP_marshal_public_key(CBB *cbb, const EVP_PKEY *key) { - if (key->ameth == NULL || key->ameth->pub_encode == NULL) { + auto *impl = FromOpaque(key); + if (impl->ameth == nullptr || impl->ameth->pub_encode == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); return 0; } + if (impl->pkey == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); + return 0; + } - return key->ameth->pub_encode(cbb, key); + return impl->ameth->pub_encode(cbb, impl); } -EVP_PKEY *EVP_parse_private_key(CBS *cbs) { +EVP_PKEY *EVP_PKEY_from_private_key_info(const uint8_t *in, size_t len, + const EVP_PKEY_ALG *const *algs, + size_t num_algs) { // Parse the PrivateKeyInfo. - CBS pkcs8, algorithm, key; + CBS cbs, pkcs8, oid, algorithm, key; uint64_t version; - if (!CBS_get_asn1(cbs, &pkcs8, CBS_ASN1_SEQUENCE) || - !CBS_get_asn1_uint64(&pkcs8, &version) || - version != 0 || + CBS_init(&cbs, in, len); + if (!CBS_get_asn1(&cbs, &pkcs8, CBS_ASN1_SEQUENCE) || + !CBS_get_asn1_uint64(&pkcs8, &version) || version != 0 || !CBS_get_asn1(&pkcs8, &algorithm, CBS_ASN1_SEQUENCE) || - !CBS_get_asn1(&pkcs8, &key, CBS_ASN1_OCTETSTRING)) { + !CBS_get_asn1(&algorithm, &oid, CBS_ASN1_OBJECT) || + !CBS_get_asn1(&pkcs8, &key, CBS_ASN1_OCTETSTRING) || + // A PrivateKeyInfo ends with a SET of Attributes which we ignore. + CBS_len(&cbs) != 0) { OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); return nullptr; } - const EVP_PKEY_ASN1_METHOD *method = parse_key_type(&algorithm); - if (method == nullptr) { - OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); - return nullptr; - } - // A PrivateKeyInfo ends with a SET of Attributes which we ignore. - - // Set up an |EVP_PKEY| of the appropriate type. - bssl::UniquePtr ret(EVP_PKEY_new()); + UniquePtr ret(FromOpaque(EVP_PKEY_new())); if (ret == nullptr) { return nullptr; } - evp_pkey_set_method(ret.get(), method); - - // Call into the type-specific PrivateKeyInfo decoding function. - if (ret->ameth->priv_decode == nullptr) { - OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); - return nullptr; - } - if (!ret->ameth->priv_decode(ret.get(), &algorithm, &key)) { - return nullptr; + for (const EVP_PKEY_ALG *alg : Span(algs, num_algs)) { + if (alg->method->priv_decode == nullptr || + Span(alg->method->oid, alg->method->oid_len) != oid) { + continue; + } + CBS params = algorithm, key_copy = key; + switch (alg->method->priv_decode(alg, ret.get(), ¶ms, &key_copy)) { + case evp_decode_error: + return nullptr; + case evp_decode_ok: + return ret.release(); + case evp_decode_unsupported: + // Continue trying other algorithms. + break; + } } - return ret.release(); + OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); + return nullptr; } int EVP_marshal_private_key(CBB *cbb, const EVP_PKEY *key) { - if (key->ameth == NULL || key->ameth->priv_encode == NULL) { + auto *impl = FromOpaque(key); + if (impl->ameth == nullptr || impl->ameth->priv_encode == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); return 0; } + if (impl->pkey == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); + return 0; + } - return key->ameth->priv_encode(cbb, key); + return impl->ameth->priv_encode(cbb, impl); +} + +EVP_PKEY *EVP_parse_public_key(CBS *cbs) { + CBS elem; + if (!CBS_get_asn1_element(cbs, &elem, CBS_ASN1_SEQUENCE)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return nullptr; + } + + auto algs = GetDefaultEVPAlgorithms(); + return EVP_PKEY_from_subject_public_key_info(CBS_data(&elem), CBS_len(&elem), + algs.data(), algs.size()); +} + +EVP_PKEY *EVP_parse_private_key(CBS *cbs) { + CBS elem; + if (!CBS_get_asn1_element(cbs, &elem, CBS_ASN1_SEQUENCE)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return nullptr; + } + + auto algs = GetDefaultEVPAlgorithms(); + return EVP_PKEY_from_private_key_info(CBS_data(&elem), CBS_len(&elem), + algs.data(), algs.size()); } static bssl::UniquePtr old_priv_decode(CBS *cbs, int type) { - bssl::UniquePtr ret(EVP_PKEY_new()); + UniquePtr ret(EVP_PKEY_new()); if (ret == nullptr) { return nullptr; } switch (type) { case EVP_PKEY_EC: { - bssl::UniquePtr ec_key(EC_KEY_parse_private_key(cbs, nullptr)); + UniquePtr ec_key(EC_KEY_parse_private_key(cbs, nullptr)); if (ec_key == nullptr) { return nullptr; } @@ -164,7 +194,7 @@ static bssl::UniquePtr old_priv_decode(CBS *cbs, int type) { return ret; } case EVP_PKEY_DSA: { - bssl::UniquePtr dsa(DSA_parse_private_key(cbs)); + UniquePtr dsa(DSA_parse_private_key(cbs)); if (dsa == nullptr) { return nullptr; } @@ -172,7 +202,7 @@ static bssl::UniquePtr old_priv_decode(CBS *cbs, int type) { return ret; } case EVP_PKEY_RSA: { - bssl::UniquePtr rsa(RSA_parse_private_key(cbs)); + UniquePtr rsa(RSA_parse_private_key(cbs)); if (rsa == nullptr) { return nullptr; } @@ -187,38 +217,28 @@ static bssl::UniquePtr old_priv_decode(CBS *cbs, int type) { EVP_PKEY *d2i_PrivateKey(int type, EVP_PKEY **out, const uint8_t **inp, long len) { - if (len < 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return nullptr; - } - - // Parse with the legacy format. - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - bssl::UniquePtr ret = old_priv_decode(&cbs, type); - if (ret == nullptr) { - // Try again with PKCS#8. - ERR_clear_error(); - CBS_init(&cbs, *inp, (size_t)len); - ret.reset(EVP_parse_private_key(&cbs)); + return D2IFromCBS(out, inp, len, [&](CBS *cbs) -> UniquePtr { + // Parse with the legacy format. + CBS copy = *cbs; + UniquePtr ret = old_priv_decode(cbs, type); if (ret == nullptr) { - return nullptr; + // Try again with PKCS#8. + ERR_clear_error(); + *cbs = copy; + ret.reset(EVP_parse_private_key(cbs)); + if (ret == nullptr) { + return nullptr; + } + if (EVP_PKEY_id(ret.get()) != type) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DIFFERENT_KEY_TYPES); + return nullptr; + } } - if (ret->type != type) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DIFFERENT_KEY_TYPES); - return nullptr; - } - } - - if (out != nullptr) { - EVP_PKEY_free(*out); - *out = ret.get(); - } - *inp = CBS_data(&cbs); - return ret.release(); + return ret; + }); } -// num_elements parses one SEQUENCE from |in| and returns the number of elements +// num_elements parses one SEQUENCE from `in` and returns the number of elements // in it. On parse error, it returns zero. static size_t num_elements(const uint8_t *in, size_t in_len) { CBS cbs, sequence; @@ -230,7 +250,7 @@ static size_t num_elements(const uint8_t *in, size_t in_len) { size_t count = 0; while (CBS_len(&sequence) > 0) { - if (!CBS_get_any_asn1_element(&sequence, NULL, NULL, NULL)) { + if (!CBS_get_any_asn1_element(&sequence, nullptr, nullptr, nullptr)) { return 0; } @@ -243,15 +263,15 @@ static size_t num_elements(const uint8_t *in, size_t in_len) { EVP_PKEY *d2i_AutoPrivateKey(EVP_PKEY **out, const uint8_t **inp, long len) { if (len < 0) { OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return NULL; + return nullptr; } // Parse the input as a PKCS#8 PrivateKeyInfo. CBS cbs; CBS_init(&cbs, *inp, (size_t)len); EVP_PKEY *ret = EVP_parse_private_key(&cbs); - if (ret != NULL) { - if (out != NULL) { + if (ret != nullptr) { + if (out != nullptr) { EVP_PKEY_free(*out); *out = ret; } @@ -274,7 +294,7 @@ EVP_PKEY *d2i_AutoPrivateKey(EVP_PKEY **out, const uint8_t **inp, long len) { } int i2d_PublicKey(const EVP_PKEY *key, uint8_t **outp) { - switch (key->type) { + switch (EVP_PKEY_id(key)) { case EVP_PKEY_RSA: return i2d_RSAPublicKey(EVP_PKEY_get0_RSA(key), outp); case EVP_PKEY_DSA: @@ -289,93 +309,69 @@ int i2d_PublicKey(const EVP_PKEY *key, uint8_t **outp) { EVP_PKEY *d2i_PublicKey(int type, EVP_PKEY **out, const uint8_t **inp, long len) { - bssl::UniquePtr ret(EVP_PKEY_new()); - if (ret == nullptr) { - return nullptr; - } - - CBS cbs; - CBS_init(&cbs, *inp, len < 0 ? 0 : (size_t)len); - switch (type) { - case EVP_PKEY_RSA: { - bssl::UniquePtr rsa(RSA_parse_public_key(&cbs)); - if (rsa == nullptr) { - return nullptr; - } - EVP_PKEY_assign_RSA(ret.get(), rsa.release()); - break; - } - - // Unlike OpenSSL, we do not support EC keys with this API. The raw EC - // public key serialization requires knowing the group. In OpenSSL, calling - // this function with |EVP_PKEY_EC| and setting |out| to nullptr does not - // work. It requires |*out| to include a partially-initialized |EVP_PKEY| to - // extract the group. - default: - OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_PUBLIC_KEY_TYPE); + return D2IFromCBS(out, inp, len, [&](CBS *cbs) -> UniquePtr { + UniquePtr ret(EVP_PKEY_new()); + if (ret == nullptr) { return nullptr; - } + } + switch (type) { + case EVP_PKEY_RSA: { + UniquePtr rsa(RSA_parse_public_key(cbs)); + if (rsa == nullptr) { + return nullptr; + } + EVP_PKEY_assign_RSA(ret.get(), rsa.release()); + return ret; + } - *inp = CBS_data(&cbs); - if (out != nullptr) { - EVP_PKEY_free(*out); - *out = ret.get(); - } - return ret.release(); + // Unlike OpenSSL, we do not support EC keys with this API. The raw EC + // public key serialization requires knowing the group. In OpenSSL, + // calling this function with `EVP_PKEY_EC` and setting `out` to + // nullptr does not work. It requires `*out` to include a + // partially-initialized `EVP_PKEY` to extract the group. + default: + OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_PUBLIC_KEY_TYPE); + return nullptr; + } + }); } EVP_PKEY *d2i_PUBKEY(EVP_PKEY **out, const uint8_t **inp, long len) { - if (len < 0) { - return nullptr; - } - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - bssl::UniquePtr ret(EVP_parse_public_key(&cbs)); - if (ret == nullptr) { - return nullptr; - } - if (out != nullptr) { - EVP_PKEY_free(*out); - *out = ret.get(); - } - *inp = CBS_data(&cbs); - return ret.release(); + return D2IFromCBS(out, inp, len, EVP_parse_public_key); } int i2d_PUBKEY(const EVP_PKEY *pkey, uint8_t **outp) { - if (pkey == NULL) { + if (pkey == nullptr) { return 0; } + return I2DFromCBB( + /*initial_capacity=*/128, outp, + [&](CBB *cbb) -> bool { return EVP_marshal_public_key(cbb, pkey); }); +} - CBB cbb; - if (!CBB_init(&cbb, 128) || - !EVP_marshal_public_key(&cbb, pkey)) { - CBB_cleanup(&cbb); - return -1; +static bssl::UniquePtr parse_spki( + CBS *cbs, Span algs) { + CBS spki; + if (!CBS_get_asn1_element(cbs, &spki, CBS_ASN1_SEQUENCE)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return nullptr; } - return CBB_finish_i2d(&cbb, outp); + return UniquePtr(EVP_PKEY_from_subject_public_key_info( + CBS_data(&spki), CBS_len(&spki), algs.data(), algs.size())); +} + +static bssl::UniquePtr parse_spki(CBS *cbs, const EVP_PKEY_ALG *alg) { + return parse_spki(cbs, Span(&alg, 1)); } RSA *d2i_RSA_PUBKEY(RSA **out, const uint8_t **inp, long len) { - if (len < 0) { - return nullptr; - } - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - bssl::UniquePtr pkey(EVP_parse_public_key(&cbs)); - if (pkey == nullptr) { - return nullptr; - } - bssl::UniquePtr rsa(EVP_PKEY_get1_RSA(pkey.get())); - if (rsa == nullptr) { - return nullptr; - } - if (out != nullptr) { - RSA_free(*out); - *out = rsa.get(); - } - *inp = CBS_data(&cbs); - return rsa.release(); + return D2IFromCBS(out, inp, len, [](CBS *cbs) -> UniquePtr { + UniquePtr pkey = parse_spki(cbs, EVP_pkey_rsa()); + if (pkey == nullptr) { + return nullptr; + } + return UniquePtr(EVP_PKEY_get1_RSA(pkey.get())); + }); } int i2d_RSA_PUBKEY(const RSA *rsa, uint8_t **outp) { @@ -383,7 +379,7 @@ int i2d_RSA_PUBKEY(const RSA *rsa, uint8_t **outp) { return 0; } - bssl::UniquePtr pkey(EVP_PKEY_new()); + UniquePtr pkey(EVP_PKEY_new()); if (pkey == nullptr || !EVP_PKEY_set1_RSA(pkey.get(), const_cast(rsa))) { return -1; @@ -393,25 +389,13 @@ int i2d_RSA_PUBKEY(const RSA *rsa, uint8_t **outp) { } DSA *d2i_DSA_PUBKEY(DSA **out, const uint8_t **inp, long len) { - if (len < 0) { - return nullptr; - } - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - bssl::UniquePtr pkey(EVP_parse_public_key(&cbs)); - if (pkey == nullptr) { - return nullptr; - } - bssl::UniquePtr dsa(EVP_PKEY_get1_DSA(pkey.get())); - if (dsa == nullptr) { - return nullptr; - } - if (out != nullptr) { - DSA_free(*out); - *out = dsa.get(); - } - *inp = CBS_data(&cbs); - return dsa.release(); + return D2IFromCBS(out, inp, len, [](CBS *cbs) -> UniquePtr { + UniquePtr pkey = parse_spki(cbs, EVP_pkey_dsa()); + if (pkey == nullptr) { + return nullptr; + } + return UniquePtr(EVP_PKEY_get1_DSA(pkey.get())); + }); } int i2d_DSA_PUBKEY(const DSA *dsa, uint8_t **outp) { @@ -419,7 +403,7 @@ int i2d_DSA_PUBKEY(const DSA *dsa, uint8_t **outp) { return 0; } - bssl::UniquePtr pkey(EVP_PKEY_new()); + UniquePtr pkey(EVP_PKEY_new()); if (pkey == nullptr || !EVP_PKEY_set1_DSA(pkey.get(), const_cast(dsa))) { return -1; @@ -429,34 +413,23 @@ int i2d_DSA_PUBKEY(const DSA *dsa, uint8_t **outp) { } EC_KEY *d2i_EC_PUBKEY(EC_KEY **out, const uint8_t **inp, long len) { - if (len < 0) { - return NULL; - } - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - EVP_PKEY *pkey = EVP_parse_public_key(&cbs); - if (pkey == NULL) { - return NULL; - } - EC_KEY *ec_key = EVP_PKEY_get1_EC_KEY(pkey); - EVP_PKEY_free(pkey); - if (ec_key == NULL) { - return NULL; - } - if (out != NULL) { - EC_KEY_free(*out); - *out = ec_key; - } - *inp = CBS_data(&cbs); - return ec_key; + return D2IFromCBS(out, inp, len, [](CBS *cbs) -> UniquePtr { + const EVP_PKEY_ALG *const algs[] = {EVP_pkey_ec_p224(), EVP_pkey_ec_p256(), + EVP_pkey_ec_p384(), EVP_pkey_ec_p521()}; + UniquePtr pkey = parse_spki(cbs, algs); + if (pkey == nullptr) { + return nullptr; + } + return UniquePtr(EVP_PKEY_get1_EC_KEY(pkey.get())); + }); } int i2d_EC_PUBKEY(const EC_KEY *ec_key, uint8_t **outp) { - if (ec_key == NULL) { + if (ec_key == nullptr) { return 0; } - bssl::UniquePtr pkey(EVP_PKEY_new()); + UniquePtr pkey(EVP_PKEY_new()); if (pkey == nullptr || !EVP_PKEY_set1_EC_KEY(pkey.get(), const_cast(ec_key))) { return -1; diff --git a/Sources/CNIOBoringSSL/crypto/evp/evp_ctx.cc b/Sources/CNIOBoringSSL/crypto/evp/evp_ctx.cc index 263db684..cabff2c5 100644 --- a/Sources/CNIOBoringSSL/crypto/evp/evp_ctx.cc +++ b/Sources/CNIOBoringSSL/crypto/evp/evp_ctx.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,292 +19,318 @@ #include #include #include +#include #include "../internal.h" +#include "../mem_internal.h" +#include "../params_internal.h" #include "internal.h" -static const EVP_PKEY_METHOD *const evp_methods[] = { - &rsa_pkey_meth, &ec_pkey_meth, &ed25519_pkey_meth, - &x25519_pkey_meth, &hkdf_pkey_meth, -}; +using namespace bssl; -static const EVP_PKEY_METHOD *evp_pkey_meth_find(int type) { - for (size_t i = 0; i < sizeof(evp_methods) / sizeof(EVP_PKEY_METHOD *); i++) { - if (evp_methods[i]->pkey_id == type) { - return evp_methods[i]; - } - } - - return NULL; -} - -static EVP_PKEY_CTX *evp_pkey_ctx_new(EVP_PKEY *pkey, ENGINE *e, - const EVP_PKEY_METHOD *pmeth) { - EVP_PKEY_CTX *ret = - reinterpret_cast(OPENSSL_zalloc(sizeof(EVP_PKEY_CTX))); +static UniquePtr evp_pkey_ctx_new( + EvpPkey *pkey, const EVP_PKEY_ALG *alg, const EVP_PKEY_CTX_METHOD *pmeth) { + assert(pkey != nullptr || alg != nullptr); + UniquePtr ret = MakeUnique(); if (!ret) { - return NULL; + return nullptr; } - ret->engine = e; ret->pmeth = pmeth; ret->operation = EVP_PKEY_OP_UNDEFINED; + ret->pkey = UpRef(pkey); - if (pkey) { - EVP_PKEY_up_ref(pkey); - ret->pkey = pkey; - } - - if (pmeth->init) { - if (pmeth->init(ret) <= 0) { - EVP_PKEY_free(ret->pkey); - OPENSSL_free(ret); - return NULL; - } + if (pmeth->init && pmeth->init(ret.get(), alg) <= 0) { + ret->pmeth = nullptr; // Don't call `pmeth->cleanup`. + return nullptr; } return ret; } EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e) { - if (pkey == NULL || pkey->ameth == NULL) { + auto *pkey_impl = FromOpaque(pkey); + if (pkey_impl == nullptr || pkey_impl->ameth == nullptr) { OPENSSL_PUT_ERROR(EVP, ERR_R_PASSED_NULL_PARAMETER); - return NULL; + return nullptr; + } + if (pkey_impl->pkey == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); + return nullptr; } - const EVP_PKEY_METHOD *pkey_method = pkey->ameth->pkey_method; - if (pkey_method == NULL) { + const EVP_PKEY_CTX_METHOD *pkey_method = pkey_impl->ameth->pkey_method; + if (pkey_method == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); - ERR_add_error_dataf("algorithm %d", pkey->ameth->pkey_id); - return NULL; + ERR_add_error_dataf("algorithm %d", pkey_impl->ameth->pkey_id); + return nullptr; } - return evp_pkey_ctx_new(pkey, e, pkey_method); + return evp_pkey_ctx_new(pkey_impl, nullptr, pkey_method).release(); } EVP_PKEY_CTX *EVP_PKEY_CTX_new_id(int id, ENGINE *e) { - const EVP_PKEY_METHOD *pkey_method = evp_pkey_meth_find(id); - if (pkey_method == NULL) { + // `EVP_PKEY_RSA_PSS` is intentionally omitted from this list. These are types + // that can be created without an `EVP_PKEY`, and we do not support + // `EVP_PKEY_RSA_PSS` keygen. + const EVP_PKEY_ALG *alg = nullptr; + switch (id) { + case EVP_PKEY_RSA: + alg = EVP_pkey_rsa(); + break; + case EVP_PKEY_EC: + alg = evp_pkey_ec_no_curve(); + break; + case EVP_PKEY_ED25519: + alg = EVP_pkey_ed25519(); + break; + case EVP_PKEY_X25519: + alg = EVP_pkey_x25519(); + break; + case EVP_PKEY_HKDF: + alg = evp_pkey_hkdf(); + break; + case EVP_PKEY_ML_DSA_44: + alg = EVP_pkey_ml_dsa_44(); + break; + case EVP_PKEY_ML_DSA_65: + alg = EVP_pkey_ml_dsa_65(); + break; + case EVP_PKEY_ML_DSA_87: + alg = EVP_pkey_ml_dsa_87(); + break; + case EVP_PKEY_ML_KEM_768: + alg = EVP_pkey_ml_kem_768(); + break; + case EVP_PKEY_ML_KEM_1024: + alg = EVP_pkey_ml_kem_1024(); + break; + } + if (alg == nullptr || alg->pkey_method == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); ERR_add_error_dataf("algorithm %d", id); - return NULL; + return nullptr; } - - return evp_pkey_ctx_new(NULL, e, pkey_method); + return evp_pkey_ctx_new_alg(alg).release(); } -void EVP_PKEY_CTX_free(EVP_PKEY_CTX *ctx) { - if (ctx == NULL) { - return; - } - if (ctx->pmeth && ctx->pmeth->cleanup) { - ctx->pmeth->cleanup(ctx); - } - EVP_PKEY_free(ctx->pkey); - EVP_PKEY_free(ctx->peerkey); - OPENSSL_free(ctx); +UniquePtr bssl::evp_pkey_ctx_new_alg(const EVP_PKEY_ALG *alg) { + return evp_pkey_ctx_new(nullptr, alg, alg->pkey_method); } +EvpPkeyCtx::~EvpPkeyCtx() { + if (pmeth && pmeth->cleanup) { + pmeth->cleanup(this); + } +} + +void EVP_PKEY_CTX_free(EVP_PKEY_CTX *ctx) { Delete(FromOpaque(ctx)); } + EVP_PKEY_CTX *EVP_PKEY_CTX_dup(EVP_PKEY_CTX *ctx) { - if (!ctx->pmeth || !ctx->pmeth->copy) { - return NULL; + auto *impl = FromOpaque(ctx); + + if (!impl->pmeth || !impl->pmeth->copy) { + return nullptr; } - EVP_PKEY_CTX *ret = - reinterpret_cast(OPENSSL_zalloc(sizeof(EVP_PKEY_CTX))); + UniquePtr ret = MakeUnique(); if (!ret) { - return NULL; + return nullptr; } - ret->pmeth = ctx->pmeth; - ret->engine = ctx->engine; - ret->operation = ctx->operation; - - if (ctx->pkey != NULL) { - EVP_PKEY_up_ref(ctx->pkey); - ret->pkey = ctx->pkey; - } - - if (ctx->peerkey != NULL) { - EVP_PKEY_up_ref(ctx->peerkey); - ret->peerkey = ctx->peerkey; - } - - if (ctx->pmeth->copy(ret, ctx) <= 0) { - ret->pmeth = NULL; - EVP_PKEY_CTX_free(ret); + ret->pmeth = impl->pmeth; + ret->operation = impl->operation; + ret->pkey = UpRef(impl->pkey); + ret->peerkey = UpRef(impl->peerkey); + if (impl->pmeth->copy(ret.get(), impl) <= 0) { OPENSSL_PUT_ERROR(EVP, ERR_LIB_EVP); - return NULL; + return nullptr; } - return ret; + return ret.release(); } -EVP_PKEY *EVP_PKEY_CTX_get0_pkey(EVP_PKEY_CTX *ctx) { return ctx->pkey; } +EVP_PKEY *EVP_PKEY_CTX_get0_pkey(EVP_PKEY_CTX *ctx) { + auto *impl = FromOpaque(ctx); + return impl->pkey.get(); +} -int EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX *ctx, int keytype, int optype, int cmd, - int p1, void *p2) { - if (!ctx || !ctx->pmeth || !ctx->pmeth->ctrl) { +int bssl::EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX *ctx, int keytype, int optype, int cmd, + int p1, void *p2) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->ctrl) { OPENSSL_PUT_ERROR(EVP, EVP_R_COMMAND_NOT_SUPPORTED); return 0; } - if (keytype != -1 && ctx->pmeth->pkey_id != keytype) { + if (keytype != -1 && impl->pmeth->pkey_id != keytype) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - if (ctx->operation == EVP_PKEY_OP_UNDEFINED) { + if (impl->operation == EVP_PKEY_OP_UNDEFINED) { OPENSSL_PUT_ERROR(EVP, EVP_R_NO_OPERATION_SET); return 0; } - if (optype != -1 && !(ctx->operation & optype)) { + if (optype != -1 && !(impl->operation & optype)) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_OPERATION); return 0; } - return ctx->pmeth->ctrl(ctx, cmd, p1, p2); + return impl->pmeth->ctrl(impl, cmd, p1, p2); } int EVP_PKEY_sign_init(EVP_PKEY_CTX *ctx) { - if (ctx == NULL || ctx->pmeth == NULL || - (ctx->pmeth->sign == NULL && ctx->pmeth->sign_message == NULL)) { + auto *impl = FromOpaque(ctx); + if (!ctx || impl->pmeth == nullptr || + (impl->pmeth->sign == nullptr && impl->pmeth->sign_message == nullptr)) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - ctx->operation = EVP_PKEY_OP_SIGN; + impl->operation = EVP_PKEY_OP_SIGN; return 1; } int EVP_PKEY_sign(EVP_PKEY_CTX *ctx, uint8_t *sig, size_t *sig_len, const uint8_t *digest, size_t digest_len) { - if (!ctx || !ctx->pmeth || !ctx->pmeth->sign) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->sign) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - if (ctx->operation != EVP_PKEY_OP_SIGN) { - OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATON_NOT_INITIALIZED); + if (impl->operation != EVP_PKEY_OP_SIGN) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_INITIALIZED); return 0; } - return ctx->pmeth->sign(ctx, sig, sig_len, digest, digest_len); + return impl->pmeth->sign(impl, sig, sig_len, digest, digest_len); } int EVP_PKEY_verify_init(EVP_PKEY_CTX *ctx) { - if (ctx == NULL || ctx->pmeth == NULL || - (ctx->pmeth->verify == NULL && ctx->pmeth->verify_message == NULL)) { + auto *impl = FromOpaque(ctx); + if (!impl || impl->pmeth == nullptr || + (impl->pmeth->verify == nullptr && + impl->pmeth->verify_message == nullptr)) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - ctx->operation = EVP_PKEY_OP_VERIFY; + impl->operation = EVP_PKEY_OP_VERIFY; return 1; } int EVP_PKEY_verify(EVP_PKEY_CTX *ctx, const uint8_t *sig, size_t sig_len, const uint8_t *digest, size_t digest_len) { - if (!ctx || !ctx->pmeth || !ctx->pmeth->verify) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->verify) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - if (ctx->operation != EVP_PKEY_OP_VERIFY) { - OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATON_NOT_INITIALIZED); + if (impl->operation != EVP_PKEY_OP_VERIFY) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_INITIALIZED); return 0; } - return ctx->pmeth->verify(ctx, sig, sig_len, digest, digest_len); + return impl->pmeth->verify(impl, sig, sig_len, digest, digest_len); } int EVP_PKEY_encrypt_init(EVP_PKEY_CTX *ctx) { - if (!ctx || !ctx->pmeth || !ctx->pmeth->encrypt) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->encrypt) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - ctx->operation = EVP_PKEY_OP_ENCRYPT; + impl->operation = EVP_PKEY_OP_ENCRYPT; return 1; } int EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *outlen, const uint8_t *in, size_t inlen) { - if (!ctx || !ctx->pmeth || !ctx->pmeth->encrypt) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->encrypt) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - if (ctx->operation != EVP_PKEY_OP_ENCRYPT) { - OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATON_NOT_INITIALIZED); + if (impl->operation != EVP_PKEY_OP_ENCRYPT) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_INITIALIZED); return 0; } - return ctx->pmeth->encrypt(ctx, out, outlen, in, inlen); + return impl->pmeth->encrypt(impl, out, outlen, in, inlen); } int EVP_PKEY_decrypt_init(EVP_PKEY_CTX *ctx) { - if (!ctx || !ctx->pmeth || !ctx->pmeth->decrypt) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->decrypt) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - ctx->operation = EVP_PKEY_OP_DECRYPT; + impl->operation = EVP_PKEY_OP_DECRYPT; return 1; } int EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *outlen, const uint8_t *in, size_t inlen) { - if (!ctx || !ctx->pmeth || !ctx->pmeth->decrypt) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->decrypt) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - if (ctx->operation != EVP_PKEY_OP_DECRYPT) { - OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATON_NOT_INITIALIZED); + if (impl->operation != EVP_PKEY_OP_DECRYPT) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_INITIALIZED); return 0; } - return ctx->pmeth->decrypt(ctx, out, outlen, in, inlen); + return impl->pmeth->decrypt(impl, out, outlen, in, inlen); } int EVP_PKEY_verify_recover_init(EVP_PKEY_CTX *ctx) { - if (!ctx || !ctx->pmeth || !ctx->pmeth->verify_recover) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->verify_recover) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - ctx->operation = EVP_PKEY_OP_VERIFYRECOVER; + impl->operation = EVP_PKEY_OP_VERIFYRECOVER; return 1; } int EVP_PKEY_verify_recover(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *out_len, const uint8_t *sig, size_t sig_len) { - if (!ctx || !ctx->pmeth || !ctx->pmeth->verify_recover) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->verify_recover) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - if (ctx->operation != EVP_PKEY_OP_VERIFYRECOVER) { - OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATON_NOT_INITIALIZED); + if (impl->operation != EVP_PKEY_OP_VERIFYRECOVER) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_INITIALIZED); return 0; } - return ctx->pmeth->verify_recover(ctx, out, out_len, sig, sig_len); + return impl->pmeth->verify_recover(impl, out, out_len, sig, sig_len); } int EVP_PKEY_derive_init(EVP_PKEY_CTX *ctx) { - if (!ctx || !ctx->pmeth || !ctx->pmeth->derive) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->derive) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - ctx->operation = EVP_PKEY_OP_DERIVE; + impl->operation = EVP_PKEY_OP_DERIVE; return 1; } int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer) { - int ret; - if (!ctx || !ctx->pmeth || - !(ctx->pmeth->derive || ctx->pmeth->encrypt || ctx->pmeth->decrypt) || - !ctx->pmeth->ctrl) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || + !(impl->pmeth->derive || impl->pmeth->encrypt || impl->pmeth->decrypt) || + !impl->pmeth->ctrl) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - if (ctx->operation != EVP_PKEY_OP_DERIVE && - ctx->operation != EVP_PKEY_OP_ENCRYPT && - ctx->operation != EVP_PKEY_OP_DECRYPT) { - OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATON_NOT_INITIALIZED); + if (impl->operation != EVP_PKEY_OP_DERIVE && + impl->operation != EVP_PKEY_OP_ENCRYPT && + impl->operation != EVP_PKEY_OP_DECRYPT) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_INITIALIZED); return 0; } - ret = ctx->pmeth->ctrl(ctx, EVP_PKEY_CTRL_PEER_KEY, 0, peer); + int ret = impl->pmeth->ctrl(impl, EVP_PKEY_CTRL_PEER_KEY, 0, peer); if (ret <= 0) { return 0; @@ -309,69 +340,74 @@ int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer) { return 1; } - if (!ctx->pkey) { + if (!impl->pkey || !FromOpaque(peer)->pkey) { OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); return 0; } - if (ctx->pkey->type != peer->type) { + if (EVP_PKEY_id(impl->pkey.get()) != EVP_PKEY_id(peer)) { OPENSSL_PUT_ERROR(EVP, EVP_R_DIFFERENT_KEY_TYPES); return 0; } - // ran@cryptocom.ru: For clarity. The error is if parameters in peer are - // present (!missing) but don't match. EVP_PKEY_cmp_parameters may return - // 1 (match), 0 (don't match) and -2 (comparison is not defined). -1 - // (different key types) is impossible here because it is checked earlier. - // -2 is OK for us here, as well as 1, so we can check for 0 only. if (!EVP_PKEY_missing_parameters(peer) && - !EVP_PKEY_cmp_parameters(ctx->pkey, peer)) { + !EVP_PKEY_parameters_eq(impl->pkey.get(), peer)) { OPENSSL_PUT_ERROR(EVP, EVP_R_DIFFERENT_PARAMETERS); return 0; } - EVP_PKEY_free(ctx->peerkey); - ctx->peerkey = peer; - - ret = ctx->pmeth->ctrl(ctx, EVP_PKEY_CTRL_PEER_KEY, 1, peer); - + impl->peerkey = UpRef(FromOpaque(peer)); + ret = impl->pmeth->ctrl(impl, EVP_PKEY_CTRL_PEER_KEY, 1, peer); if (ret <= 0) { - ctx->peerkey = NULL; + impl->peerkey = nullptr; return 0; } - EVP_PKEY_up_ref(peer); return 1; } int EVP_PKEY_derive(EVP_PKEY_CTX *ctx, uint8_t *key, size_t *out_key_len) { - if (!ctx || !ctx->pmeth || !ctx->pmeth->derive) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->derive) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - if (ctx->operation != EVP_PKEY_OP_DERIVE) { - OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATON_NOT_INITIALIZED); + if (impl->operation != EVP_PKEY_OP_DERIVE) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_INITIALIZED); return 0; } - return ctx->pmeth->derive(ctx, key, out_key_len); + return impl->pmeth->derive(impl, key, out_key_len); +} + +EVP_PKEY *EVP_PKEY_generate_from_alg(const EVP_PKEY_ALG *alg) { + UniquePtr ctx = evp_pkey_ctx_new_alg(alg); + EVP_PKEY *pkey = nullptr; + if (ctx == nullptr || // + !EVP_PKEY_keygen_init(ctx.get()) || // + !EVP_PKEY_keygen(ctx.get(), &pkey)) { + return nullptr; + } + return pkey; } int EVP_PKEY_keygen_init(EVP_PKEY_CTX *ctx) { - if (!ctx || !ctx->pmeth || !ctx->pmeth->keygen) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->keygen) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - ctx->operation = EVP_PKEY_OP_KEYGEN; + impl->operation = EVP_PKEY_OP_KEYGEN; return 1; } int EVP_PKEY_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY **out_pkey) { - if (!ctx || !ctx->pmeth || !ctx->pmeth->keygen) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->keygen) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - if (ctx->operation != EVP_PKEY_OP_KEYGEN) { - OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATON_NOT_INITIALIZED); + if (impl->operation != EVP_PKEY_OP_KEYGEN) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_INITIALIZED); return 0; } @@ -387,30 +423,32 @@ int EVP_PKEY_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY **out_pkey) { } } - if (!ctx->pmeth->keygen(ctx, *out_pkey)) { + if (!impl->pmeth->keygen(impl, FromOpaque(*out_pkey))) { EVP_PKEY_free(*out_pkey); - *out_pkey = NULL; + *out_pkey = nullptr; return 0; } return 1; } int EVP_PKEY_paramgen_init(EVP_PKEY_CTX *ctx) { - if (!ctx || !ctx->pmeth || !ctx->pmeth->paramgen) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->paramgen) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - ctx->operation = EVP_PKEY_OP_PARAMGEN; + impl->operation = EVP_PKEY_OP_PARAMGEN; return 1; } int EVP_PKEY_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY **out_pkey) { - if (!ctx || !ctx->pmeth || !ctx->pmeth->paramgen) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->paramgen) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } - if (ctx->operation != EVP_PKEY_OP_PARAMGEN) { - OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATON_NOT_INITIALIZED); + if (impl->operation != EVP_PKEY_OP_PARAMGEN) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_INITIALIZED); return 0; } @@ -426,10 +464,78 @@ int EVP_PKEY_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY **out_pkey) { } } - if (!ctx->pmeth->paramgen(ctx, *out_pkey)) { + if (!impl->pmeth->paramgen(impl, FromOpaque(*out_pkey))) { EVP_PKEY_free(*out_pkey); - *out_pkey = NULL; + *out_pkey = nullptr; return 0; } return 1; } + +int EVP_PKEY_encapsulate_init(EVP_PKEY_CTX *ctx, const OSSL_PARAM *params) { + if (params != nullptr && !IsEndParam(*params)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PARAMETERS); + return 0; + } + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->encap) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + return 0; + } + impl->operation = EVP_PKEY_OP_ENCAPSULATE; + return 1; +} + +int EVP_PKEY_encapsulate(EVP_PKEY_CTX *ctx, uint8_t *out_ciphertext, + size_t *out_ciphertext_len, uint8_t *out_secret, + size_t *out_secret_len) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->encap) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + return 0; + } + if (impl->operation != EVP_PKEY_OP_ENCAPSULATE) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_INITIALIZED); + return 0; + } + if (!impl->pkey) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); + return 0; + } + return impl->pmeth->encap(impl, out_ciphertext, out_ciphertext_len, + out_secret, out_secret_len); +} + +int EVP_PKEY_decapsulate_init(EVP_PKEY_CTX *ctx, const OSSL_PARAM *params) { + if (params != nullptr && !IsEndParam(*params)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PARAMETERS); + return 0; + } + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->decap) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + return 0; + } + impl->operation = EVP_PKEY_OP_DECAPSULATE; + return 1; +} + +int EVP_PKEY_decapsulate(EVP_PKEY_CTX *ctx, uint8_t *out_secret, + size_t *out_secret_len, const uint8_t *ciphertext, + size_t ciphertext_len) { + auto *impl = FromOpaque(ctx); + if (!impl || !impl->pmeth || !impl->pmeth->decap) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + return 0; + } + if (impl->operation != EVP_PKEY_OP_DECAPSULATE) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_INITIALIZED); + return 0; + } + if (!impl->pkey) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); + return 0; + } + return impl->pmeth->decap(impl, out_secret, out_secret_len, ciphertext, + ciphertext_len); +} diff --git a/Sources/CNIOBoringSSL/crypto/evp/evp_kem.cc b/Sources/CNIOBoringSSL/crypto/evp/evp_kem.cc new file mode 100644 index 00000000..003daadb --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/evp/evp_kem.cc @@ -0,0 +1,101 @@ +// 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 "../internal.h" +#include "internal.h" + +using namespace bssl; + +// Checks whether KEM function invocation is valid. +// `ciphertext_len` may be nullptr if it is not required to match. +// `secret_len` must always match. +static bool check_kem_invocation(const EVP_KEM *kem, + const size_t *ciphertext_len, + size_t secret_len, + const bssl::EvpPkey *pkey_impl) { + if (pkey_impl == nullptr || pkey_impl->pkey == nullptr || + pkey_impl->ameth == nullptr) { + OPENSSL_PUT_ERROR(EVP, ERR_R_PASSED_NULL_PARAMETER); + return false; + } + if (kem->pkey_id != EVP_PKEY_id(pkey_impl)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); + return false; + } + if (ciphertext_len && *ciphertext_len != kem->ciphertext_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_CIPHERTEXT_LENGTH); + return false; + } + if (secret_len != kem->secret_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH); + return false; + } + return true; +} + +size_t EVP_KEM_ciphertext_len(const EVP_KEM *kem) { + return kem->ciphertext_len; +} + +size_t EVP_KEM_secret_len(const EVP_KEM *kem) { return kem->secret_len; } + +size_t EVP_KEM_entropy_len_for_testing(const EVP_KEM *kem) { + return kem->entropy_len; +} + +int EVP_KEM_encap(const EVP_KEM *kem, uint8_t *out_ciphertext, + size_t ciphertext_len, uint8_t *out_secret, size_t secret_len, + const EVP_PKEY *peer_key) { + auto *pkey_impl = FromOpaque(peer_key); + if (!check_kem_invocation(kem, &ciphertext_len, secret_len, pkey_impl)) { + return 0; + } + return kem->encap(Span(out_ciphertext, ciphertext_len), + Span(out_secret, secret_len), pkey_impl); +} + +int EVP_KEM_encap_external_entropy_for_testing( + const EVP_KEM *kem, uint8_t *out_ciphertext, size_t ciphertext_len, + uint8_t *out_secret, size_t secret_len, const EVP_PKEY *peer_key, + const uint8_t *entropy, size_t entropy_len) { + auto *pkey_impl = FromOpaque(peer_key); + if (!check_kem_invocation(kem, &ciphertext_len, secret_len, pkey_impl)) { + return 0; + } + if (entropy_len != kem->entropy_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_ENTROPY_LENGTH); + return 0; + } + return kem->encap_external_entropy(Span(out_ciphertext, ciphertext_len), + Span(out_secret, secret_len), pkey_impl, + Span(entropy, entropy_len)); +} + +int EVP_KEM_decap(const EVP_KEM *kem, uint8_t *out_secret, size_t secret_len, + const uint8_t *ciphertext, size_t ciphertext_len, + const EVP_PKEY *key) { + auto *pkey_impl = FromOpaque(key); + if (!check_kem_invocation(kem, nullptr, secret_len, pkey_impl)) { + return 0; + } + return kem->decap(Span(out_secret, secret_len), + Span(ciphertext, ciphertext_len), pkey_impl); +} diff --git a/Sources/CNIOBoringSSL/crypto/evp/internal.h b/Sources/CNIOBoringSSL/crypto/evp/internal.h index bdd8de4d..2edeaba1 100644 --- a/Sources/CNIOBoringSSL/crypto/evp/internal.h +++ b/Sources/CNIOBoringSSL/crypto/evp/internal.h @@ -1,102 +1,159 @@ -/* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. -#ifndef OPENSSL_HEADER_EVP_INTERNAL_H -#define OPENSSL_HEADER_EVP_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_EVP_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_EVP_INTERNAL_H -#include +#include -#include +#include -#if defined(__cplusplus) -extern "C" { -#endif +#include +#include "../internal.h" +#include "../mem_internal.h" + + +DECLARE_OPAQUE_STRUCT(evp_pkey_st, EvpPkey) +DECLARE_OPAQUE_STRUCT(evp_pkey_ctx_st, EvpPkeyCtx) + +BSSL_NAMESPACE_BEGIN typedef struct evp_pkey_asn1_method_st EVP_PKEY_ASN1_METHOD; -typedef struct evp_pkey_method_st EVP_PKEY_METHOD; +typedef struct evp_pkey_ctx_method_st EVP_PKEY_CTX_METHOD; + +BSSL_NAMESPACE_END + +struct evp_pkey_alg_st { + // method and pkey_method implement operations for this `EVP_PKEY_ALG`. + const bssl::EVP_PKEY_ASN1_METHOD *method; + const bssl::EVP_PKEY_CTX_METHOD *pkey_method; +}; + +BSSL_NAMESPACE_BEGIN + +enum evp_decode_result_t { + evp_decode_error = 0, + evp_decode_ok = 1, + evp_decode_unsupported = 2, +}; struct evp_pkey_asn1_method_st { + // pkey_id contains one of the `EVP_PKEY_*` values and corresponds to the OID + // in the key type's AlgorithmIdentifier. int pkey_id; uint8_t oid[9]; uint8_t oid_len; - const EVP_PKEY_METHOD *pkey_method; + const EVP_PKEY_CTX_METHOD *pkey_method; - // pub_decode decodes |params| and |key| as a SubjectPublicKeyInfo - // and writes the result into |out|. It returns one on success and zero on - // error. |params| is the AlgorithmIdentifier after the OBJECT IDENTIFIER - // type field, and |key| is the contents of the subjectPublicKey with the - // leading padding byte checked and removed. Although X.509 uses BIT STRINGs - // to represent SubjectPublicKeyInfo, every key type defined encodes the key - // as a byte string with the same conversion to BIT STRING. - int (*pub_decode)(EVP_PKEY *out, CBS *params, CBS *key); + // pub_decode decodes `params` and `key` as a SubjectPublicKeyInfo + // and writes the result into `out`. It returns `evp_decode_ok` on success, + // and `evp_decode_error` on error, and `evp_decode_unsupported` if the input + // was not supported by this `EVP_PKEY_ALG`. In case of + // `evp_decode_unsupported`, it does not add an error to the error queue. May + // modify `params` and `key`. Callers must make a copy if calling in a loop. + // + // `params` is the AlgorithmIdentifier after the OBJECT IDENTIFIER type field, + // and `key` is the contents of the subjectPublicKey with the leading padding + // byte checked and removed. Although X.509 uses BIT STRINGs to represent + // SubjectPublicKeyInfo, every key type defined encodes the key as a byte + // string with the same conversion to BIT STRING. + evp_decode_result_t (*pub_decode)(const EVP_PKEY_ALG *alg, EvpPkey *out, + CBS *params, CBS *key); - // pub_encode encodes |key| as a SubjectPublicKeyInfo and appends the result - // to |out|. It returns one on success and zero on error. - int (*pub_encode)(CBB *out, const EVP_PKEY *key); + // pub_encode encodes `key` as a SubjectPublicKeyInfo and appends the result + // to `out`. It returns one on success and zero on error. + int (*pub_encode)(CBB *out, const EvpPkey *key); - int (*pub_cmp)(const EVP_PKEY *a, const EVP_PKEY *b); + bool (*pub_equal)(const EvpPkey *a, const EvpPkey *b); - // priv_decode decodes |params| and |key| as a PrivateKeyInfo and writes the - // result into |out|. It returns one on success and zero on error. |params| is - // the AlgorithmIdentifier after the OBJECT IDENTIFIER type field, and |key| - // is the contents of the OCTET STRING privateKey field. - int (*priv_decode)(EVP_PKEY *out, CBS *params, CBS *key); + // pub_present returns true iff the `pk` has a public key. (If so, validity + // is not guaranteed and should be checked separately.) + bool (*pub_present)(const EvpPkey *pk); - // priv_encode encodes |key| as a PrivateKeyInfo and appends the result to - // |out|. It returns one on success and zero on error. - int (*priv_encode)(CBB *out, const EVP_PKEY *key); + // pub_copy sets the key data of `out` to a newly allocated key data structure + // which contains a copy of only the public key of `pk`, freeing any key + // previously in `out`. Returns true on success or false on failure. + bool (*pub_copy)(EvpPkey *out, const EvpPkey *pk); - int (*set_priv_raw)(EVP_PKEY *pkey, const uint8_t *in, size_t len); - int (*set_pub_raw)(EVP_PKEY *pkey, const uint8_t *in, size_t len); - int (*get_priv_raw)(const EVP_PKEY *pkey, uint8_t *out, size_t *out_len); - int (*get_pub_raw)(const EVP_PKEY *pkey, uint8_t *out, size_t *out_len); + // priv_decode decodes `params` and `key` as a PrivateKeyInfo and writes the + // result into `out`. It returns `evp_decode_ok` on success, and + // `evp_decode_error` on error, and `evp_decode_unsupported` if the key type + // was not supported by this `EVP_PKEY_ALG`. In case of + // `evp_decode_unsupported`, it does not add an error to the error queue. May + // modify `params` and `key`. Callers must make a copy if calling in a loop. + // + // `params` is the AlgorithmIdentifier after the OBJECT IDENTIFIER type field, + // and `key` is the contents of the OCTET STRING privateKey field. + evp_decode_result_t (*priv_decode)(const EVP_PKEY_ALG *alg, EvpPkey *out, + CBS *params, CBS *key); + + // priv_encode encodes `key` as a PrivateKeyInfo and appends the result to + // `out`. It returns one on success and zero on error. + int (*priv_encode)(CBB *out, const EvpPkey *key); + + // priv_present returns true iff the `pk` has a private key. (If so, validity + // is not guaranteed and should be checked separately.) + bool (*priv_present)(const EvpPkey *pk); + + int (*set_priv_raw)(EvpPkey *pkey, const uint8_t *in, size_t len); + int (*set_priv_seed)(EvpPkey *pkey, const uint8_t *in, size_t len); + int (*set_pub_raw)(EvpPkey *pkey, const uint8_t *in, size_t len); + int (*get_priv_raw)(const EvpPkey *pkey, uint8_t *out, size_t *out_len); + int (*get_priv_seed)(const EvpPkey *pkey, uint8_t *out, size_t *out_len); + int (*get_pub_raw)(const EvpPkey *pkey, uint8_t *out, size_t *out_len); // TODO(davidben): Can these be merged with the functions above? OpenSSL does - // not implement |EVP_PKEY_get_raw_public_key|, etc., for |EVP_PKEY_EC|, but + // not implement `EVP_PKEY_get_raw_public_key`, etc., for `EVP_PKEY_EC`, but // the distinction seems unimportant. OpenSSL 3.0 has since renamed - // |EVP_PKEY_get1_tls_encodedpoint| to |EVP_PKEY_get1_encoded_public_key|, and + // `EVP_PKEY_get1_tls_encodedpoint` to `EVP_PKEY_get1_encoded_public_key`, and // what is the difference between "raw" and an "encoded" public key. // // One nuisance is the notion of "raw" is slightly ambiguous for EC keys. Is // it a DER ECPrivateKey or just the scalar? - int (*set1_tls_encodedpoint)(EVP_PKEY *pkey, const uint8_t *in, size_t len); - size_t (*get1_tls_encodedpoint)(const EVP_PKEY *pkey, uint8_t **out_ptr); + int (*set1_tls_encodedpoint)(EvpPkey *pkey, const uint8_t *in, size_t len); + size_t (*get1_tls_encodedpoint)(const EvpPkey *pkey, uint8_t **out_ptr); - // pkey_opaque returns 1 if the |pk| is opaque. Opaque keys are backed by + // pkey_opaque returns 1 if the `pk` is opaque. Opaque keys are backed by // custom implementations which do not expose key material and parameters. - int (*pkey_opaque)(const EVP_PKEY *pk); + int (*pkey_opaque)(const EvpPkey *pk); - int (*pkey_size)(const EVP_PKEY *pk); - int (*pkey_bits)(const EVP_PKEY *pk); + int (*pkey_size)(const EvpPkey *pk); + int (*pkey_bits)(const EvpPkey *pk); - int (*param_missing)(const EVP_PKEY *pk); - int (*param_copy)(EVP_PKEY *to, const EVP_PKEY *from); - int (*param_cmp)(const EVP_PKEY *a, const EVP_PKEY *b); + int (*param_missing)(const EvpPkey *pk); + int (*param_copy)(EvpPkey *to, const EvpPkey *from); + bool (*param_equal)(const EvpPkey *a, const EvpPkey *b); - void (*pkey_free)(EVP_PKEY *pkey); + void (*pkey_free)(EvpPkey *pkey); } /* EVP_PKEY_ASN1_METHOD */; -struct evp_pkey_st { - CRYPTO_refcount_t references; +class EvpPkey : public evp_pkey_st, public RefCounted { + public: + EvpPkey(); - // type contains one of the EVP_PKEY_* values or NID_undef and determines - // the type of |pkey|. - int type; + // pkey contains a pointer to a structure dependent on `ameth`. + void *pkey = nullptr; - // pkey contains a pointer to a structure dependent on |type|. - void *pkey; + // ameth contains a pointer to a method table that determines the key type, or + // nullptr if the key is empty. + const bssl::EVP_PKEY_ASN1_METHOD *ameth = nullptr; - // ameth contains a pointer to a method table that contains many ASN.1 - // methods for the key type. - const EVP_PKEY_ASN1_METHOD *ameth; + private: + ~EvpPkey(); + friend RefCounted; } /* EVP_PKEY */; #define EVP_PKEY_OP_UNDEFINED 0 @@ -108,23 +165,22 @@ struct evp_pkey_st { #define EVP_PKEY_OP_DECRYPT (1 << 7) #define EVP_PKEY_OP_DERIVE (1 << 8) #define EVP_PKEY_OP_PARAMGEN (1 << 9) +#define EVP_PKEY_OP_ENCAPSULATE (1 << 10) +#define EVP_PKEY_OP_DECAPSULATE (1 << 11) #define EVP_PKEY_OP_TYPE_SIG \ (EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY | EVP_PKEY_OP_VERIFYRECOVER) #define EVP_PKEY_OP_TYPE_CRYPT (EVP_PKEY_OP_ENCRYPT | EVP_PKEY_OP_DECRYPT) -#define EVP_PKEY_OP_TYPE_NOGEN \ - (EVP_PKEY_OP_SIG | EVP_PKEY_OP_CRYPT | EVP_PKEY_OP_DERIVE) - #define EVP_PKEY_OP_TYPE_GEN (EVP_PKEY_OP_KEYGEN | EVP_PKEY_OP_PARAMGEN) -// EVP_PKEY_CTX_ctrl performs |cmd| on |ctx|. The |keytype| and |optype| +// EVP_PKEY_CTX_ctrl performs `cmd` on `ctx`. The `keytype` and `optype` // arguments can be -1 to specify that any type and operation are acceptable, -// otherwise |keytype| must match the type of |ctx| and the bits of |optype| -// must intersect the operation flags set on |ctx|. +// otherwise `keytype` must match the type of `ctx` and the bits of `optype` +// must intersect the operation flags set on `ctx`. // -// The |p1| and |p2| arguments depend on the value of |cmd|. +// The `p1` and `p2` arguments depend on the value of `cmd`. // // It returns one on success and zero on error. OPENSSL_EXPORT int EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX *ctx, int keytype, int optype, @@ -133,14 +189,14 @@ OPENSSL_EXPORT int EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX *ctx, int keytype, int optype, #define EVP_PKEY_CTRL_MD 1 #define EVP_PKEY_CTRL_GET_MD 2 -// EVP_PKEY_CTRL_PEER_KEY is called with different values of |p1|: -// 0: Is called from |EVP_PKEY_derive_set_peer| and |p2| contains a peer key. +// EVP_PKEY_CTRL_PEER_KEY is called with different values of `p1`: +// 0: Is called from `EVP_PKEY_derive_set_peer` and `p2` contains a peer key. // If the return value is <= 0, the key is rejected. -// 1: Is called at the end of |EVP_PKEY_derive_set_peer| and |p2| contains a +// 1: Is called at the end of `EVP_PKEY_derive_set_peer` and `p2` contains a // peer key. If the return value is <= 0, the key is rejected. -// 2: Is called with |p2| == NULL to test whether the peer's key was used. +// 2: Is called with `p2` == NULL to test whether the peer's key was used. // (EC)DH always return one in this case. -// 3: Is called with |p2| == NULL to set whether the peer's key was used. +// 3: Is called with `p2` == NULL to set whether the peer's key was used. // (EC)DH always return one in this case. This was only used for GOST. #define EVP_PKEY_CTRL_PEER_KEY 3 @@ -160,104 +216,212 @@ OPENSSL_EXPORT int EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX *ctx, int keytype, int optype, #define EVP_PKEY_CTRL_GET_RSA_MGF1_MD (EVP_PKEY_ALG_CTRL + 10) #define EVP_PKEY_CTRL_RSA_OAEP_LABEL (EVP_PKEY_ALG_CTRL + 11) #define EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL (EVP_PKEY_ALG_CTRL + 12) -#define EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID (EVP_PKEY_ALG_CTRL + 13) +#define EVP_PKEY_CTRL_EC_PARAMGEN_GROUP (EVP_PKEY_ALG_CTRL + 13) #define EVP_PKEY_CTRL_HKDF_MODE (EVP_PKEY_ALG_CTRL + 14) #define EVP_PKEY_CTRL_HKDF_MD (EVP_PKEY_ALG_CTRL + 15) #define EVP_PKEY_CTRL_HKDF_KEY (EVP_PKEY_ALG_CTRL + 16) #define EVP_PKEY_CTRL_HKDF_SALT (EVP_PKEY_ALG_CTRL + 17) #define EVP_PKEY_CTRL_HKDF_INFO (EVP_PKEY_ALG_CTRL + 18) #define EVP_PKEY_CTRL_DH_PAD (EVP_PKEY_ALG_CTRL + 19) +#define EVP_PKEY_CTRL_SIGNATURE_CONTEXT_STRING (EVP_PKEY_ALG_CTRL + 20) -struct evp_pkey_ctx_st { - // Method associated with this operation - const EVP_PKEY_METHOD *pmeth; - // Engine that implements this method or NULL if builtin - ENGINE *engine; - // Key: may be NULL - EVP_PKEY *pkey; - // Peer key for key agreement, may be NULL - EVP_PKEY *peerkey; - // operation contains one of the |EVP_PKEY_OP_*| values. - int operation; - // Algorithm specific data - void *data; -} /* EVP_PKEY_CTX */; +class EvpPkeyCtx : public evp_pkey_ctx_st { + public: + static constexpr bool kAllowUniquePtr = true; -struct evp_pkey_method_st { - int pkey_id; - - int (*init)(EVP_PKEY_CTX *ctx); - int (*copy)(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src); - void (*cleanup)(EVP_PKEY_CTX *ctx); - - int (*keygen)(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey); - - int (*sign)(EVP_PKEY_CTX *ctx, uint8_t *sig, size_t *siglen, - const uint8_t *tbs, size_t tbslen); - - int (*sign_message)(EVP_PKEY_CTX *ctx, uint8_t *sig, size_t *siglen, - const uint8_t *tbs, size_t tbslen); - - int (*verify)(EVP_PKEY_CTX *ctx, const uint8_t *sig, size_t siglen, - const uint8_t *tbs, size_t tbslen); - - int (*verify_message)(EVP_PKEY_CTX *ctx, const uint8_t *sig, size_t siglen, - const uint8_t *tbs, size_t tbslen); - - int (*verify_recover)(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *out_len, - const uint8_t *sig, size_t sig_len); - - int (*encrypt)(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *outlen, - const uint8_t *in, size_t inlen); - - int (*decrypt)(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *outlen, - const uint8_t *in, size_t inlen); - - int (*derive)(EVP_PKEY_CTX *ctx, uint8_t *key, size_t *keylen); - - int (*paramgen)(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey); - - int (*ctrl)(EVP_PKEY_CTX *ctx, int type, int p1, void *p2); -} /* EVP_PKEY_METHOD */; - -typedef struct { - // key is the concatenation of the private seed and public key. It is stored - // as a single 64-bit array to allow passing to |ED25519_sign|. If - // |has_private| is false, the first 32 bytes are uninitialized and the public - // key is in the last 32 bytes. - uint8_t key[64]; - char has_private; -} ED25519_KEY; - -#define ED25519_PUBLIC_KEY_OFFSET 32 - -typedef struct { - uint8_t pub[32]; - uint8_t priv[32]; - char has_private; -} X25519_KEY; - -extern const EVP_PKEY_ASN1_METHOD dsa_asn1_meth; -extern const EVP_PKEY_ASN1_METHOD ec_asn1_meth; -extern const EVP_PKEY_ASN1_METHOD rsa_asn1_meth; -extern const EVP_PKEY_ASN1_METHOD ed25519_asn1_meth; -extern const EVP_PKEY_ASN1_METHOD x25519_asn1_meth; -extern const EVP_PKEY_ASN1_METHOD dh_asn1_meth; - -extern const EVP_PKEY_METHOD rsa_pkey_meth; -extern const EVP_PKEY_METHOD ec_pkey_meth; -extern const EVP_PKEY_METHOD ed25519_pkey_meth; -extern const EVP_PKEY_METHOD x25519_pkey_meth; -extern const EVP_PKEY_METHOD hkdf_pkey_meth; -extern const EVP_PKEY_METHOD dh_pkey_meth; - -// evp_pkey_set_method behaves like |EVP_PKEY_set_type|, but takes a pointer to -// a method table. This avoids depending on every |EVP_PKEY_ASN1_METHOD|. -void evp_pkey_set_method(EVP_PKEY *pkey, const EVP_PKEY_ASN1_METHOD *method); - - -#if defined(__cplusplus) -} // extern C + // Use an optional virtual destructor. This class does not (yet) have a need + // for a vtable, but we intend to write code with vtables in the future. + // Virtual destructors add a reference to symbols in the C++ runtime, so trial + // the dependency here. This is, temporarily, gated on a build define. If this + // breaks your build, build with `BORINGSSL_TEMPORARY_NO_CXX_RUNTIME` and then + // contact the BoringSSL team, so we can help fix your build. + // + // TODO(crbug.com/486922845): Remove the `BORINGSSL_TEMPORARY_NO_CXX_RUNTIME` + // case. +#if defined(BORINGSSL_TEMPORARY_NO_CXX_RUNTIME) + ~EvpPkeyCtx(); +#else + virtual ~EvpPkeyCtx(); #endif -#endif // OPENSSL_HEADER_EVP_INTERNAL_H + // Method associated with this operation + const bssl::EVP_PKEY_CTX_METHOD *pmeth = nullptr; + // Key: may be nullptr + bssl::UniquePtr pkey; + // Peer key for key agreement, may be nullptr + bssl::UniquePtr peerkey; + // operation contains one of the `EVP_PKEY_OP_*` values. + int operation = EVP_PKEY_OP_UNDEFINED; + // Algorithm specific data. + // TODO(crbug.com/487376811): Since a `EVP_PKEY_CTX` never has its type change + // after creation, this should instead be a base class, with the + // algorithm-specific data on the subclass, coming from the same allocation. + void *data = nullptr; +}; + +struct evp_pkey_ctx_method_st { + int pkey_id; + + // `alg` may be nullptr. If non-null, `ctx` will have a key set. + int (*init)(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *alg); + int (*copy)(EvpPkeyCtx *dst, EvpPkeyCtx *src); + void (*cleanup)(EvpPkeyCtx *ctx); + + int (*keygen)(EvpPkeyCtx *ctx, EvpPkey *pkey); + + int (*sign)(EvpPkeyCtx *ctx, uint8_t *sig, size_t *siglen, const uint8_t *tbs, + size_t tbslen); + + int (*sign_message)(EvpPkeyCtx *ctx, uint8_t *sig, size_t *siglen, + const uint8_t *tbs, size_t tbslen); + + int (*verify)(EvpPkeyCtx *ctx, const uint8_t *sig, size_t siglen, + const uint8_t *tbs, size_t tbslen); + + int (*verify_message)(EvpPkeyCtx *ctx, const uint8_t *sig, size_t siglen, + const uint8_t *tbs, size_t tbslen); + + int (*verify_recover)(EvpPkeyCtx *ctx, uint8_t *out, size_t *out_len, + const uint8_t *sig, size_t sig_len); + + int (*encrypt)(EvpPkeyCtx *ctx, uint8_t *out, size_t *outlen, + const uint8_t *in, size_t inlen); + + int (*decrypt)(EvpPkeyCtx *ctx, uint8_t *out, size_t *outlen, + const uint8_t *in, size_t inlen); + + int (*derive)(EvpPkeyCtx *ctx, uint8_t *key, size_t *keylen); + + int (*paramgen)(EvpPkeyCtx *ctx, EvpPkey *pkey); + + int (*encap)(EvpPkeyCtx *ctx, uint8_t *out_ciphertext, + size_t *out_ciphertext_len, uint8_t *out_secret, + size_t *out_secret_len); + + int (*decap)(EvpPkeyCtx *ctx, uint8_t *out_secret, size_t *out_secret_len, + const uint8_t *ciphertext, size_t ciphertext_len); + + int (*ctrl)(EvpPkeyCtx *ctx, int type, int p1, void *p2); +} /* EVP_PKEY_CTX_METHOD */; + +BSSL_NAMESPACE_END + +// TODO(chlily): Make compatible with `EVP_HPKE_KEM`. +struct evp_kem_st { + // Identifies the type of EVP_PKEYs compatible with this KEM. + int pkey_id; + + // Constant lengths of ciphertexts and secrets produced/consumed by this KEM. + size_t ciphertext_len; + size_t secret_len; + // Fixed length of external entropy for testing. + size_t entropy_len; + + int (*encap)(bssl::Span out_ciphertext, + bssl::Span out_secret, const EVP_PKEY *peer_key); + int (*encap_external_entropy)(bssl::Span out_ciphertext, + bssl::Span out_secret, + const EVP_PKEY *peer_key, + bssl::Span entropy); + int (*decap)(bssl::Span out_secret, + bssl::Span ciphertext, const EVP_PKEY *key); +} /* EVP_KEM */; + +BSSL_NAMESPACE_BEGIN + +// KemAdapter is templated on an instance of EVP_KEM, and generates static +// methods matching the behavior and function signatures for `encap` and `decap` +// in EVP_PKEY_CTX_METHOD. +template +struct KemAdapter { + KemAdapter() = delete; + + static int EncapMethod(EvpPkeyCtx *ctx, uint8_t *out_ciphertext, + size_t *out_ciphertext_len, uint8_t *out_secret, + size_t *out_secret_len) { + if (out_ciphertext == nullptr) { + if (out_ciphertext_len != nullptr) { + *out_ciphertext_len = KEM.ciphertext_len; + } + if (out_secret_len != nullptr) { + *out_secret_len = KEM.secret_len; + } + return 1; + } + if (*out_ciphertext_len < KEM.ciphertext_len || + *out_secret_len < KEM.secret_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + if (KEM.encap(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; + return 1; + } + return 0; + } + + static int DecapMethod(EvpPkeyCtx *ctx, uint8_t *out_secret, + size_t *out_secret_len, const uint8_t *ciphertext, + size_t ciphertext_len) { + if (out_secret == nullptr) { + *out_secret_len = KEM.secret_len; + return 1; + } + if (*out_secret_len < KEM.secret_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + if (KEM.decap(Span(out_secret, KEM.secret_len), + Span(ciphertext, ciphertext_len), ctx->pkey.get())) { + *out_secret_len = KEM.secret_len; + return 1; + } + return 0; + } +}; + +// evp_pkey_ec_no_curve returns an internal curveless EC `EVP_PKEY_ALG`. This +// cannot be used to parse anything and is only useful for key generation. +const EVP_PKEY_ALG *evp_pkey_ec_no_curve(); + +// evp_pkey_hkdf returns an internal `EVP_PKEY_ALG` used to implement +// `EVP_PKEY_HKDF`. It has no associated key type. +const EVP_PKEY_ALG *evp_pkey_hkdf(); + +// evp_pkey_ctx_new_alg behaves like `EVP_PKEY_CTX_new_id` but takes an +// `EVP_PKEY_ALG`. +UniquePtr evp_pkey_ctx_new_alg(const EVP_PKEY_ALG *alg); + +// evp_pkey_set0 sets `pkey`'s method to `method` and data to `pkey_data`, +// freeing any key that may previously have been configured. This function takes +// ownership of `pkey_data`, which must be of the type expected by `method`. +void evp_pkey_set0(EvpPkey *pkey, const EVP_PKEY_ASN1_METHOD *method, + void *pkey_data); + +inline auto GetDefaultEVPAlgorithms() { + // A set of algorithms to use by default in `EVP_parse_public_key` and + // `EVP_parse_private_key`. + return std::array{ + EVP_pkey_ec_p224(), + EVP_pkey_ec_p256(), + EVP_pkey_ec_p384(), + EVP_pkey_ec_p521(), + EVP_pkey_ed25519(), + EVP_pkey_rsa(), + EVP_pkey_x25519(), + EVP_pkey_ml_dsa_44(), + EVP_pkey_ml_dsa_65(), + EVP_pkey_ml_dsa_87(), + EVP_pkey_ml_kem_768(), + EVP_pkey_ml_kem_1024(), + // TODO(crbug.com/438761503): Remove DSA from this set, after callers that + // need DSA pass in `EVP_pkey_dsa` explicitly. + EVP_pkey_dsa(), + }; +} + +BSSL_NAMESPACE_END + +#endif // OPENSSL_HEADER_CRYPTO_EVP_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_dh.cc b/Sources/CNIOBoringSSL/crypto/evp/p_dh.cc index 3bfd332d..b65a6fe3 100644 --- a/Sources/CNIOBoringSSL/crypto/evp/p_dh.cc +++ b/Sources/CNIOBoringSSL/crypto/evp/p_dh.cc @@ -1,33 +1,175 @@ -/* - * Copyright 2006-2019 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2006-2019 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../internal.h" +#include "../mem_internal.h" #include "internal.h" -namespace { -typedef struct dh_pkey_ctx_st { - int pad; -} DH_PKEY_CTX; -} // namespace +using namespace bssl; -static int pkey_dh_init(EVP_PKEY_CTX *ctx) { - DH_PKEY_CTX *dctx = - reinterpret_cast(OPENSSL_zalloc(sizeof(DH_PKEY_CTX))); - if (dctx == NULL) { +namespace { + +extern const EVP_PKEY_CTX_METHOD dh_pkey_meth; + +static void dh_free(EvpPkey *pkey) { + DH_free(reinterpret_cast(pkey->pkey)); + pkey->pkey = nullptr; +} + +static int dh_size(const EvpPkey *pkey) { + return DH_size(reinterpret_cast(pkey->pkey)); +} + +static int dh_bits(const EvpPkey *pkey) { + return DH_bits(reinterpret_cast(pkey->pkey)); +} + +static 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) { + if (dh_param_missing(from)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PARAMETERS); + return 0; + } + if (to->pkey == nullptr) { + to->pkey = DH_new(); + if (to->pkey == nullptr) { + return 0; + } + } + + const DH *dh = reinterpret_cast(from->pkey); + const BIGNUM *q_old = DH_get0_q(dh); + BIGNUM *p = BN_dup(DH_get0_p(dh)); + BIGNUM *q = q_old == nullptr ? nullptr : BN_dup(q_old); + BIGNUM *g = BN_dup(DH_get0_g(dh)); + if (p == nullptr || (q_old != nullptr && q == nullptr) || g == nullptr || + !DH_set0_pqg(reinterpret_cast(to->pkey), p, q, g)) { + BN_free(p); + BN_free(q); + BN_free(g); + return 0; + } + + // `DH_set0_pqg` took ownership of `p`, `q`, and `g`. + return 1; +} + +static bool dh_param_equal(const EvpPkey *a, const EvpPkey *b) { + if (dh_param_missing(a) || dh_param_missing(b)) { + return false; + } + + // Matching OpenSSL, only compare p and g for PKCS#3-style Diffie-Hellman. + // OpenSSL only checks q in X9.42-style Diffie-Hellman ("DHX"). + const DH *a_dh = reinterpret_cast(a->pkey); + const DH *b_dh = reinterpret_cast(b->pkey); + return BN_cmp(DH_get0_p(a_dh), DH_get0_p(b_dh)) == 0 && + BN_cmp(DH_get0_g(a_dh), DH_get0_g(b_dh)) == 0; +} + +static bool dh_pub_equal(const EvpPkey *a, const EvpPkey *b) { + if (!dh_param_equal(a, b)) { + return false; + } + + const DH *a_dh = reinterpret_cast(a->pkey); + const DH *b_dh = reinterpret_cast(b->pkey); + return BN_cmp(DH_get0_pub_key(a_dh), DH_get0_pub_key(b_dh)) == 0; +} + +static 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) { + const DH *pk_dh = reinterpret_cast(pk->pkey); + const BIGNUM *public_key = DH_get0_pub_key(pk_dh); + if (public_key == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PUBLIC_KEY); + return false; + } + UniquePtr public_copy_dh(DHparams_dup(pk_dh)); + BIGNUM *public_key_copy = BN_dup(public_key); + if (public_copy_dh == nullptr || public_key_copy == nullptr || + !DH_set0_key(public_copy_dh.get(), public_key_copy, nullptr)) { + BN_free(public_key_copy); + OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR); + return false; + } + evp_pkey_set0(out, pk->ameth, public_copy_dh.release()); + return true; +} + +static 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 = { + /*pkey_id=*/EVP_PKEY_DH, + /*oid=*/{0}, + /*oid_len=*/0, + /*pkey_method=*/&dh_pkey_meth, + /*pub_decode=*/nullptr, + /*pub_encode=*/nullptr, + /*pub_equal=*/dh_pub_equal, + /*pub_present=*/dh_has_pub, + /*pub_dup=*/dh_pub_copy, + /*priv_decode=*/nullptr, + /*priv_encode=*/nullptr, + /*priv_present=*/dh_has_priv, + /*set_priv_raw=*/nullptr, + /*set_priv_seed=*/nullptr, + /*set_pub_raw=*/nullptr, + /*get_priv_raw=*/nullptr, + /*get_priv_seed=*/nullptr, + /*get_pub_raw=*/nullptr, + /*set1_tls_encodedpoint=*/nullptr, + /*get1_tls_encodedpoint=*/nullptr, + /*pkey_opaque=*/nullptr, + /*pkey_size=*/dh_size, + /*pkey_bits=*/dh_bits, + /*param_missing=*/dh_param_missing, + /*param_copy=*/dh_param_copy, + /*param_equal=*/dh_param_equal, + /*pkey_free=*/dh_free, +}; + +struct DH_PKEY_CTX { + bool pad = false; +}; + +static int pkey_dh_init(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *) { + DH_PKEY_CTX *dctx = New(); + if (dctx == nullptr) { return 0; } @@ -35,8 +177,8 @@ static int pkey_dh_init(EVP_PKEY_CTX *ctx) { return 1; } -static int pkey_dh_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { - if (!pkey_dh_init(dst)) { +static int pkey_dh_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { + if (!pkey_dh_init(dst, nullptr)) { return 0; } @@ -46,46 +188,46 @@ static int pkey_dh_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { return 1; } -static void pkey_dh_cleanup(EVP_PKEY_CTX *ctx) { - OPENSSL_free(ctx->data); - ctx->data = NULL; +static void pkey_dh_cleanup(EvpPkeyCtx *ctx) { + Delete(reinterpret_cast(ctx->data)); } -static int pkey_dh_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { +static int pkey_dh_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { DH *dh = DH_new(); - if (dh == NULL || !EVP_PKEY_assign_DH(pkey, dh)) { + if (dh == nullptr || !EVP_PKEY_assign_DH(pkey, dh)) { DH_free(dh); return 0; } - if (ctx->pkey != NULL && !EVP_PKEY_copy_parameters(pkey, ctx->pkey)) { + if (ctx->pkey != nullptr && + !EVP_PKEY_copy_parameters(pkey, ctx->pkey.get())) { return 0; } return DH_generate_key(dh); } -static int pkey_dh_derive(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *out_len) { +static int pkey_dh_derive(EvpPkeyCtx *ctx, uint8_t *out, size_t *out_len) { DH_PKEY_CTX *dctx = reinterpret_cast(ctx->data); - if (ctx->pkey == NULL || ctx->peerkey == NULL) { + if (ctx->pkey == nullptr || ctx->peerkey == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_KEYS_NOT_SET); return 0; } DH *our_key = reinterpret_cast(ctx->pkey->pkey); DH *peer_key = reinterpret_cast(ctx->peerkey->pkey); - if (our_key == NULL || peer_key == NULL) { + if (our_key == nullptr || peer_key == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_KEYS_NOT_SET); return 0; } const BIGNUM *pub_key = DH_get0_pub_key(peer_key); - if (pub_key == NULL) { + if (pub_key == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_KEYS_NOT_SET); return 0; } - if (out == NULL) { + if (out == nullptr) { *out_len = DH_size(our_key); return 1; } @@ -106,11 +248,11 @@ static int pkey_dh_derive(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *out_len) { return 1; } -static int pkey_dh_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { +static 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: - // |EVP_PKEY_derive_set_peer| requires the key implement this command, + // `EVP_PKEY_derive_set_peer` requires the key implement this command, // even if it is a no-op. return 1; @@ -124,7 +266,7 @@ static int pkey_dh_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { } } -const EVP_PKEY_METHOD dh_pkey_meth = { +const EVP_PKEY_CTX_METHOD dh_pkey_meth = { /*pkey_id=*/EVP_PKEY_DH, /*init=*/pkey_dh_init, /*copy=*/pkey_dh_copy, @@ -139,10 +281,46 @@ const EVP_PKEY_METHOD dh_pkey_meth = { /*decrypt=*/nullptr, /*derive=*/pkey_dh_derive, /*paramgen=*/nullptr, + /*encap=*/nullptr, + /*decap=*/nullptr, /*ctrl=*/pkey_dh_ctrl, }; +} // 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_assign_DH(EVP_PKEY *pkey, DH *key) { + if (key == nullptr) { + return 0; + } + evp_pkey_set0(FromOpaque(pkey), &dh_asn1_meth, key); + return 1; +} + +DH *EVP_PKEY_get0_DH(const EVP_PKEY *pkey) { + if (EVP_PKEY_id(pkey) != EVP_PKEY_DH) { + OPENSSL_PUT_ERROR(EVP, EVP_R_EXPECTING_A_DH_KEY); + return nullptr; + } + return reinterpret_cast(const_cast(FromOpaque(pkey))->pkey); +} + +DH *EVP_PKEY_get1_DH(const EVP_PKEY *pkey) { + DH *dh = EVP_PKEY_get0_DH(pkey); + if (dh != nullptr) { + DH_up_ref(dh); + } + return dh; +} + int EVP_PKEY_CTX_set_dh_pad(EVP_PKEY_CTX *ctx, int pad) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_DERIVE, - EVP_PKEY_CTRL_DH_PAD, pad, NULL); + EVP_PKEY_CTRL_DH_PAD, pad, nullptr); } diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_dh_asn1.cc b/Sources/CNIOBoringSSL/crypto/evp/p_dh_asn1.cc deleted file mode 100644 index be3498a1..00000000 --- a/Sources/CNIOBoringSSL/crypto/evp/p_dh_asn1.cc +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ - -#include - -#include -#include -#include - -#include "../internal.h" -#include "internal.h" - - -static void dh_free(EVP_PKEY *pkey) { - DH_free(reinterpret_cast(pkey->pkey)); - pkey->pkey = NULL; -} - -static int dh_size(const EVP_PKEY *pkey) { - return DH_size(reinterpret_cast(pkey->pkey)); -} - -static int dh_bits(const EVP_PKEY *pkey) { - return DH_bits(reinterpret_cast(pkey->pkey)); -} - -static int dh_param_missing(const EVP_PKEY *pkey) { - const DH *dh = reinterpret_cast(pkey->pkey); - return dh == NULL || DH_get0_p(dh) == NULL || DH_get0_g(dh) == NULL; -} - -static int dh_param_copy(EVP_PKEY *to, const EVP_PKEY *from) { - if (dh_param_missing(from)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PARAMETERS); - return 0; - } - - const DH *dh = reinterpret_cast(from->pkey); - const BIGNUM *q_old = DH_get0_q(dh); - BIGNUM *p = BN_dup(DH_get0_p(dh)); - BIGNUM *q = q_old == NULL ? NULL : BN_dup(q_old); - BIGNUM *g = BN_dup(DH_get0_g(dh)); - if (p == NULL || (q_old != NULL && q == NULL) || g == NULL || - !DH_set0_pqg(reinterpret_cast(to->pkey), p, q, g)) { - BN_free(p); - BN_free(q); - BN_free(g); - return 0; - } - - // |DH_set0_pqg| took ownership of |p|, |q|, and |g|. - return 1; -} - -static int dh_param_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { - if (dh_param_missing(a) || dh_param_missing(b)) { - return -2; - } - - // Matching OpenSSL, only compare p and g for PKCS#3-style Diffie-Hellman. - // OpenSSL only checks q in X9.42-style Diffie-Hellman ("DHX"). - const DH *a_dh = reinterpret_cast(a->pkey); - const DH *b_dh = reinterpret_cast(b->pkey); - return BN_cmp(DH_get0_p(a_dh), DH_get0_p(b_dh)) == 0 && - BN_cmp(DH_get0_g(a_dh), DH_get0_g(b_dh)) == 0; -} - -static int dh_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { - if (dh_param_cmp(a, b) <= 0) { - return 0; - } - - const DH *a_dh = reinterpret_cast(a->pkey); - const DH *b_dh = reinterpret_cast(b->pkey); - return BN_cmp(DH_get0_pub_key(a_dh), DH_get0_pub_key(b_dh)) == 0; -} - -const EVP_PKEY_ASN1_METHOD dh_asn1_meth = { - /*pkey_id=*/EVP_PKEY_DH, - /*oid=*/{0}, - /*oid_len=*/0, - /*pkey_method=*/&dh_pkey_meth, - /*pub_decode=*/nullptr, - /*pub_encode=*/nullptr, - /*pub_cmp=*/dh_pub_cmp, - /*priv_decode=*/nullptr, - /*priv_encode=*/nullptr, - /*set_priv_raw=*/nullptr, - /*set_pub_raw=*/nullptr, - /*get_priv_raw=*/nullptr, - /*get_pub_raw=*/nullptr, - /*set1_tls_encodedpoint=*/nullptr, - /*get1_tls_encodedpoint=*/nullptr, - /*pkey_opaque=*/nullptr, - /*pkey_size=*/dh_size, - /*pkey_bits=*/dh_bits, - /*param_missing=*/dh_param_missing, - /*param_copy=*/dh_param_copy, - /*param_cmp=*/dh_param_cmp, - /*pkey_free=*/dh_free, -}; - -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_assign_DH(EVP_PKEY *pkey, DH *key) { - evp_pkey_set_method(pkey, &dh_asn1_meth); - pkey->pkey = key; - return key != NULL; -} - -DH *EVP_PKEY_get0_DH(const EVP_PKEY *pkey) { - if (pkey->type != EVP_PKEY_DH) { - OPENSSL_PUT_ERROR(EVP, EVP_R_EXPECTING_A_DH_KEY); - return NULL; - } - return reinterpret_cast(const_cast(pkey)->pkey); -} - -DH *EVP_PKEY_get1_DH(const EVP_PKEY *pkey) { - DH *dh = EVP_PKEY_get0_DH(pkey); - if (dh != NULL) { - DH_up_ref(dh); - } - return dh; -} diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_dsa.cc b/Sources/CNIOBoringSSL/crypto/evp/p_dsa.cc new file mode 100644 index 00000000..57551c79 --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/evp/p_dsa.cc @@ -0,0 +1,333 @@ +// Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../dsa/internal.h" +#include "../mem_internal.h" +#include "internal.h" + + +using namespace bssl; + +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) { + // See RFC 3279, section 2.3.2. + + // Decode parameters. RFC 3279 permits DSA parameters to be omitted, in which + // case they are implicitly determined from the issuing certificate, or + // somewhere unspecified and out-of-band. We do not support this mode. + UniquePtr dsa(FromOpaque(DSA_parse_parameters(params))); + if (dsa == nullptr || CBS_len(params) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + dsa->pub_key.reset(BN_new()); + if (dsa->pub_key == nullptr) { + return evp_decode_error; + } + + if (!BN_parse_asn1_unsigned(key, dsa->pub_key.get()) || CBS_len(key) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + EVP_PKEY_assign_DSA(out, dsa.release()); + return evp_decode_ok; +} + +static 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; + + // See RFC 5480, section 2. + 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, dsa_asn1_meth.oid, + dsa_asn1_meth.oid_len) || + (has_params && !DSA_marshal_parameters(&algorithm, dsa)) || + !CBB_add_asn1(&spki, &key_bitstring, CBS_ASN1_BITSTRING) || + !CBB_add_u8(&key_bitstring, 0 /* padding */) || + !BN_marshal_asn1(&key_bitstring, dsa->pub_key.get()) || !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); + return 0; + } + + return 1; +} + +static 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. + UniquePtr dsa(FromOpaque(DSA_parse_parameters(params))); + if (dsa == nullptr || CBS_len(params) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + dsa->priv_key.reset(BN_new()); + if (dsa->priv_key == nullptr) { + return evp_decode_error; + } + if (!BN_parse_asn1_unsigned(key, dsa->priv_key.get()) || CBS_len(key) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + // To avoid DoS attacks when importing private keys, check bounds on `dsa`. + // This bounds `dsa->priv_key` against `dsa->q` and bounds `dsa->q`'s bit + // width. + if (!dsa_check_key(dsa.get())) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + // Calculate the public key. + UniquePtr ctx(BN_CTX_new()); + dsa->pub_key.reset(BN_new()); + if (ctx == nullptr || dsa->pub_key == nullptr || + !BN_mod_exp_mont_consttime(dsa->pub_key.get(), dsa->g.get(), + dsa->priv_key.get(), dsa->p.get(), ctx.get(), + nullptr)) { + return evp_decode_error; + } + + EVP_PKEY_assign_DSA(out, dsa.release()); + return evp_decode_ok; +} + +static 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); + return 0; + } + + // See PKCS#11, v2.40, section 2.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, dsa_asn1_meth.oid, + dsa_asn1_meth.oid_len) || + !DSA_marshal_parameters(&algorithm, dsa) || + !CBB_add_asn1(&pkcs8, &private_key, CBS_ASN1_OCTETSTRING) || + !BN_marshal_asn1(&private_key, dsa->priv_key.get()) || !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); + return 0; + } + + return 1; +} + +static 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) { + const DSAImpl *dsa = reinterpret_cast(pkey->pkey); + return BN_num_bits(DSA_get0_p(dsa)); +} + +static 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) { + return 1; + } + return 0; +} + +static int dup_bn_into(UniquePtr *out, const BIGNUM *src) { + UniquePtr copy(BN_dup(src)); + if (copy == nullptr) { + return 0; + } + *out = std::move(copy); + return 1; +} + +static int dsa_copy_parameters(EvpPkey *to, const EvpPkey *from) { + if (to->pkey == nullptr) { + to->pkey = DSA_new(); + if (to->pkey == nullptr) { + return 0; + } + } + DSAImpl *to_dsa = reinterpret_cast(to->pkey); + const DSAImpl *from_dsa = reinterpret_cast(from->pkey); + if (!dup_bn_into(&to_dsa->p, from_dsa->p.get()) || + !dup_bn_into(&to_dsa->q, from_dsa->q.get()) || + !dup_bn_into(&to_dsa->g, from_dsa->g.get())) { + return 0; + } + + return 1; +} + +static 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 && + BN_cmp(DSA_get0_q(a_dsa), DSA_get0_q(b_dsa)) == 0 && + BN_cmp(DSA_get0_g(a_dsa), DSA_get0_g(b_dsa)) == 0; +} + +static 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) { + 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) { + const DSA *pk_dsa = reinterpret_cast(pk->pkey); + const BIGNUM *public_key = DSA_get0_pub_key(pk_dsa); + if (public_key == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PUBLIC_KEY); + return false; + } + UniquePtr public_copy_dsa(DSAparams_dup(pk_dsa)); + BIGNUM *public_key_copy = BN_dup(public_key); + if (public_copy_dsa == nullptr || public_key_copy == nullptr || + !DSA_set0_key(public_copy_dsa.get(), public_key_copy, nullptr)) { + BN_free(public_key_copy); + OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR); + return false; + } + evp_pkey_set0(out, pk->ameth, public_copy_dsa.release()); + return true; +} + +static 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) { + DSA_free(reinterpret_cast(pkey->pkey)); + pkey->pkey = nullptr; +} + +const EVP_PKEY_ASN1_METHOD dsa_asn1_meth = { + EVP_PKEY_DSA, + // 1.2.840.10040.4.1 + {0x2a, 0x86, 0x48, 0xce, 0x38, 0x04, 0x01}, + 7, + + /*pkey_method=*/nullptr, + + dsa_pub_decode, + dsa_pub_encode, + dsa_pub_equal, + dsa_pub_present, + dsa_pub_copy, + + dsa_priv_decode, + dsa_priv_encode, + dsa_priv_present, + + /*set_priv_raw=*/nullptr, + /*set_priv_seed=*/nullptr, + /*set_pub_raw=*/nullptr, + /*get_priv_raw=*/nullptr, + /*get_priv_seed=*/nullptr, + /*get_pub_raw=*/nullptr, + /*set1_tls_encodedpoint=*/nullptr, + /*get1_tls_encodedpoint=*/nullptr, + + /*pkey_opaque=*/nullptr, + + int_dsa_size, + dsa_bits, + + dsa_missing_parameters, + dsa_copy_parameters, + dsa_equal_parameters, + + int_dsa_free, +}; + +} // namespace + +const EVP_PKEY_ALG *EVP_pkey_dsa() { + static const EVP_PKEY_ALG kAlg = {&dsa_asn1_meth, nullptr}; + return &kAlg; +} + +int EVP_PKEY_CTX_set_dsa_paramgen_bits(EVP_PKEY_CTX *ctx, int nbits) { + // BoringSSL does not support DSA in `EVP_PKEY_CTX`. + OPENSSL_PUT_ERROR(EVP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return 0; +} + +int EVP_PKEY_CTX_set_dsa_paramgen_q_bits(EVP_PKEY_CTX *ctx, int qbits) { + // BoringSSL does not support DSA in `EVP_PKEY_CTX`. + OPENSSL_PUT_ERROR(EVP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + 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_assign_DSA(EVP_PKEY *pkey, DSA *key) { + if (key == nullptr) { + return 0; + } + evp_pkey_set0(FromOpaque(pkey), &dsa_asn1_meth, key); + return 1; +} + +DSA *EVP_PKEY_get0_DSA(const EVP_PKEY *pkey) { + if (EVP_PKEY_id(pkey) != EVP_PKEY_DSA) { + OPENSSL_PUT_ERROR(EVP, EVP_R_EXPECTING_A_DSA_KEY); + return nullptr; + } + return reinterpret_cast(FromOpaque(pkey)->pkey); +} + +DSA *EVP_PKEY_get1_DSA(const EVP_PKEY *pkey) { + DSA *dsa = EVP_PKEY_get0_DSA(pkey); + if (dsa != nullptr) { + DSA_up_ref(dsa); + } + return dsa; +} diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_dsa_asn1.cc b/Sources/CNIOBoringSSL/crypto/evp/p_dsa_asn1.cc deleted file mode 100644 index c5d8dea7..00000000 --- a/Sources/CNIOBoringSSL/crypto/evp/p_dsa_asn1.cc +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ - -#include - -#include -#include -#include -#include -#include - -#include "../dsa/internal.h" -#include "internal.h" - - -static int dsa_pub_decode(EVP_PKEY *out, CBS *params, CBS *key) { - // See RFC 3279, section 2.3.2. - - // Parameters may or may not be present. - bssl::UniquePtr dsa; - if (CBS_len(params) == 0) { - dsa.reset(DSA_new()); - if (dsa == nullptr) { - return 0; - } - } else { - dsa.reset(DSA_parse_parameters(params)); - if (dsa == nullptr || CBS_len(params) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - } - - dsa->pub_key = BN_new(); - if (dsa->pub_key == nullptr) { - return 0; - } - - if (!BN_parse_asn1_unsigned(key, dsa->pub_key) || CBS_len(key) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - EVP_PKEY_assign_DSA(out, dsa.release()); - return 1; -} - -static int dsa_pub_encode(CBB *out, const EVP_PKEY *key) { - const DSA *dsa = reinterpret_cast(key->pkey); - const int has_params = - dsa->p != nullptr && dsa->q != nullptr && dsa->g != nullptr; - - // See RFC 5480, section 2. - CBB spki, algorithm, oid, key_bitstring; - if (!CBB_add_asn1(out, &spki, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&spki, &algorithm, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&algorithm, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, dsa_asn1_meth.oid, dsa_asn1_meth.oid_len) || - (has_params && !DSA_marshal_parameters(&algorithm, dsa)) || - !CBB_add_asn1(&spki, &key_bitstring, CBS_ASN1_BITSTRING) || - !CBB_add_u8(&key_bitstring, 0 /* padding */) || - !BN_marshal_asn1(&key_bitstring, dsa->pub_key) || !CBB_flush(out)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); - return 0; - } - - return 1; -} - -static int dsa_priv_decode(EVP_PKEY *out, CBS *params, CBS *key) { - // See PKCS#11, v2.40, section 2.5. - - // Decode parameters. - bssl::UniquePtr dsa(DSA_parse_parameters(params)); - if (dsa == nullptr || CBS_len(params) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - dsa->priv_key = BN_new(); - if (dsa->priv_key == nullptr) { - return 0; - } - if (!BN_parse_asn1_unsigned(key, dsa->priv_key) || CBS_len(key) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - // To avoid DoS attacks when importing private keys, check bounds on |dsa|. - // This bounds |dsa->priv_key| against |dsa->q| and bounds |dsa->q|'s bit - // width. - if (!dsa_check_key(dsa.get())) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - // Calculate the public key. - bssl::UniquePtr ctx(BN_CTX_new()); - dsa->pub_key = BN_new(); - if (ctx == nullptr || dsa->pub_key == nullptr || - !BN_mod_exp_mont_consttime(dsa->pub_key, dsa->g, dsa->priv_key, dsa->p, - ctx.get(), nullptr)) { - return 0; - } - - EVP_PKEY_assign_DSA(out, dsa.release()); - return 1; -} - -static int dsa_priv_encode(CBB *out, const EVP_PKEY *key) { - const DSA *dsa = reinterpret_cast(key->pkey); - if (dsa == nullptr || dsa->priv_key == nullptr) { - OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PARAMETERS); - return 0; - } - - // See PKCS#11, v2.40, section 2.5. - CBB pkcs8, algorithm, oid, 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(&algorithm, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, dsa_asn1_meth.oid, dsa_asn1_meth.oid_len) || - !DSA_marshal_parameters(&algorithm, dsa) || - !CBB_add_asn1(&pkcs8, &private_key, CBS_ASN1_OCTETSTRING) || - !BN_marshal_asn1(&private_key, dsa->priv_key) || !CBB_flush(out)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); - return 0; - } - - return 1; -} - -static int int_dsa_size(const EVP_PKEY *pkey) { - const DSA *dsa = reinterpret_cast(pkey->pkey); - return DSA_size(dsa); -} - -static int dsa_bits(const EVP_PKEY *pkey) { - const DSA *dsa = reinterpret_cast(pkey->pkey); - return BN_num_bits(DSA_get0_p(dsa)); -} - -static int dsa_missing_parameters(const EVP_PKEY *pkey) { - const DSA *dsa = reinterpret_cast(pkey->pkey); - if (DSA_get0_p(dsa) == nullptr || DSA_get0_q(dsa) == nullptr || - DSA_get0_g(dsa) == nullptr) { - return 1; - } - return 0; -} - -static int dup_bn_into(BIGNUM **out, BIGNUM *src) { - bssl::UniquePtr a(BN_dup(src)); - if (a == nullptr) { - return 0; - } - BN_free(*out); - *out = a.release(); - return 1; -} - -static int dsa_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from) { - DSA *to_dsa = reinterpret_cast(to->pkey); - const DSA *from_dsa = reinterpret_cast(from->pkey); - if (!dup_bn_into(&to_dsa->p, from_dsa->p) || - !dup_bn_into(&to_dsa->q, from_dsa->q) || - !dup_bn_into(&to_dsa->g, from_dsa->g)) { - return 0; - } - - return 1; -} - -static int dsa_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b) { - const DSA *a_dsa = reinterpret_cast(a->pkey); - const DSA *b_dsa = reinterpret_cast(b->pkey); - return BN_cmp(DSA_get0_p(a_dsa), DSA_get0_p(b_dsa)) == 0 && - BN_cmp(DSA_get0_q(a_dsa), DSA_get0_q(b_dsa)) == 0 && - BN_cmp(DSA_get0_g(a_dsa), DSA_get0_g(b_dsa)) == 0; -} - -static int dsa_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { - const DSA *a_dsa = reinterpret_cast(a->pkey); - const DSA *b_dsa = reinterpret_cast(b->pkey); - return BN_cmp(DSA_get0_pub_key(b_dsa), DSA_get0_pub_key(a_dsa)) == 0; -} - -static void int_dsa_free(EVP_PKEY *pkey) { - DSA_free(reinterpret_cast(pkey->pkey)); - pkey->pkey = nullptr; -} - -const EVP_PKEY_ASN1_METHOD dsa_asn1_meth = { - EVP_PKEY_DSA, - // 1.2.840.10040.4.1 - {0x2a, 0x86, 0x48, 0xce, 0x38, 0x04, 0x01}, - 7, - - /*pkey_method=*/nullptr, - - dsa_pub_decode, - dsa_pub_encode, - dsa_pub_cmp, - - dsa_priv_decode, - dsa_priv_encode, - - /*set_priv_raw=*/nullptr, - /*set_pub_raw=*/nullptr, - /*get_priv_raw=*/nullptr, - /*get_pub_raw=*/nullptr, - /*set1_tls_encodedpoint=*/nullptr, - /*get1_tls_encodedpoint=*/nullptr, - - /*pkey_opaque=*/nullptr, - - int_dsa_size, - dsa_bits, - - dsa_missing_parameters, - dsa_copy_parameters, - dsa_cmp_parameters, - - int_dsa_free, -}; - -int EVP_PKEY_CTX_set_dsa_paramgen_bits(EVP_PKEY_CTX *ctx, int nbits) { - // BoringSSL does not support DSA in |EVP_PKEY_CTX|. - OPENSSL_PUT_ERROR(EVP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); - return 0; -} - -int EVP_PKEY_CTX_set_dsa_paramgen_q_bits(EVP_PKEY_CTX *ctx, int qbits) { - // BoringSSL does not support DSA in |EVP_PKEY_CTX|. - OPENSSL_PUT_ERROR(EVP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); - 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_assign_DSA(EVP_PKEY *pkey, DSA *key) { - evp_pkey_set_method(pkey, &dsa_asn1_meth); - pkey->pkey = key; - return key != nullptr; -} - -DSA *EVP_PKEY_get0_DSA(const EVP_PKEY *pkey) { - if (pkey->type != EVP_PKEY_DSA) { - OPENSSL_PUT_ERROR(EVP, EVP_R_EXPECTING_A_DSA_KEY); - return nullptr; - } - return reinterpret_cast(pkey->pkey); -} - -DSA *EVP_PKEY_get1_DSA(const EVP_PKEY *pkey) { - DSA *dsa = EVP_PKEY_get0_DSA(pkey); - if (dsa != nullptr) { - DSA_up_ref(dsa); - } - return dsa; -} diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_ec.cc b/Sources/CNIOBoringSSL/crypto/evp/p_ec.cc index 02362513..f4c2e4e8 100644 --- a/Sources/CNIOBoringSSL/crypto/evp/p_ec.cc +++ b/Sources/CNIOBoringSSL/crypto/evp/p_ec.cc @@ -1,17 +1,23 @@ -/* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -20,32 +26,334 @@ #include #include #include +#include +#include "../ec/internal.h" #include "../fipsmodule/ec/internal.h" #include "../internal.h" +#include "../mem_internal.h" #include "internal.h" -typedef struct { +using namespace bssl; + +namespace { + +struct EVP_PKEY_ALG_EC : public EVP_PKEY_ALG { + // ec_group returns the `EC_GROUP` for this algorithm. + const EC_GROUP *(*ec_group)(); +}; + +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); + const EC_GROUP *group = EC_KEY_get0_group(ec_key); + const EC_POINT *public_key = EC_KEY_get0_public_key(ec_key); + + // See RFC 5480, section 2. + 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, ec_asn1_meth.oid, + ec_asn1_meth.oid_len) || + !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) || + !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); + return 0; + } + + return 1; +} + +static 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; + } + + // See RFC 5480, section 2. + + // Check that `params` matches `alg`. Only the namedCurve form is allowed. + const EC_GROUP *group = ec_alg->ec_group(); + if (ec_key_parse_curve_name(params, Span(&group, 1)) == nullptr) { + if (ERR_equals(ERR_peek_last_error(), ERR_LIB_EC, EC_R_UNKNOWN_GROUP)) { + ERR_clear_error(); + return evp_decode_unsupported; + } + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + if (CBS_len(params) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + UniquePtr eckey(EC_KEY_new()); + if (eckey == nullptr || // + !EC_KEY_set_group(eckey.get(), group) || + !EC_KEY_oct2key(eckey.get(), CBS_data(key), CBS_len(key), nullptr)) { + return evp_decode_error; + } + + EVP_PKEY_assign_EC_KEY(out, eckey.release()); + return evp_decode_ok; +} + +static 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); + const EC_POINT *pa = EC_KEY_get0_public_key(a_ec), + *pb = EC_KEY_get0_public_key(b_ec); + 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) { + const auto *ec_alg = static_cast(alg); + if (ec_alg->ec_group == nullptr) { + return evp_decode_unsupported; + } + + // See RFC 5915. + const EC_GROUP *group = ec_alg->ec_group(); + if (ec_key_parse_parameters(params, Span(&group, 1)) == nullptr) { + if (ERR_equals(ERR_peek_last_error(), ERR_LIB_EC, EC_R_UNKNOWN_GROUP)) { + ERR_clear_error(); + return evp_decode_unsupported; + } + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + if (CBS_len(params) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + UniquePtr ec_key(ec_key_parse_private_key(key, group, {})); + if (ec_key == nullptr || CBS_len(key) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + EVP_PKEY_assign_EC_KEY(out, ec_key.release()); + return evp_decode_ok; +} + +static 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 + // aligns with PKCS #11. SEC 1 only says they may be omitted if known by other + // means. Both OpenSSL and NSS omit the redundant parameters, so we omit them + // as well. + unsigned enc_flags = EC_KEY_get_enc_flags(ec_key) | EC_PKEY_NO_PARAMETERS; + + // See RFC 5915. + 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, ec_asn1_meth.oid, + ec_asn1_meth.oid_len) || + !EC_KEY_marshal_curve_name(&algorithm, EC_KEY_get0_group(ec_key)) || + !CBB_add_asn1(&pkcs8, &private_key, CBS_ASN1_OCTETSTRING) || + !EC_KEY_marshal_private_key(&private_key, ec_key, enc_flags) || + !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); + return 0; + } + + return 1; +} + +static 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); + return 0; + } + + return EC_KEY_oct2key(ec_key, in, len, nullptr); +} + +static 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); + return 0; + } + + return EC_KEY_key2buf(ec_key, POINT_CONVERSION_UNCOMPRESSED, out_ptr, + nullptr); +} + +static 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) { + const EC_KEY *ec_key = reinterpret_cast(pkey->pkey); + const EC_GROUP *group = EC_KEY_get0_group(ec_key); + if (group == nullptr) { + ERR_clear_error(); + return 0; + } + return EC_GROUP_order_bits(group); +} + +static 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) { + const EC_KEY *from_key = reinterpret_cast(from->pkey); + if (from_key == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); + return 0; + } + const EC_GROUP *group = EC_KEY_get0_group(from_key); + if (group == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PARAMETERS); + return 0; + } + if (to->pkey == nullptr) { + to->pkey = EC_KEY_new(); + if (to->pkey == nullptr) { + return 0; + } + } + return EC_KEY_set_group(reinterpret_cast(to->pkey), group); +} + +static 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) { + return false; + } + const EC_GROUP *group_a = EC_KEY_get0_group(a_ec), + *group_b = EC_KEY_get0_group(b_ec); + if (group_a == nullptr || group_b == nullptr) { + return false; + } + // EC_GROUP_cmp returns zero on equality. + return EC_GROUP_cmp(group_a, group_b, nullptr) == 0; +} + +static void int_ec_free(EvpPkey *pkey) { + EC_KEY_free(reinterpret_cast(pkey->pkey)); + pkey->pkey = nullptr; +} + +static 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) { + 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) { + 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) { + OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PUBLIC_KEY); + return false; + } + UniquePtr public_copy_ec_key(EC_KEY_new()); + if (public_copy_ec_key == nullptr || + !EC_KEY_set_group(public_copy_ec_key.get(), public_key->group) || + !EC_KEY_set_public_key(public_copy_ec_key.get(), public_key)) { + OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR); + return false; + } + evp_pkey_set0(out, pkey->ameth, public_copy_ec_key.release()); + return true; +} + +static 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; +} + +const EVP_PKEY_ASN1_METHOD ec_asn1_meth = { + EVP_PKEY_EC, + // 1.2.840.10045.2.1 + {0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01}, + 7, + + &ec_pkey_meth, + + eckey_pub_decode, + eckey_pub_encode, + eckey_pub_equal, + eckey_pub_present, + eckey_pub_copy, + + eckey_priv_decode, + eckey_priv_encode, + eckey_priv_present, + + /*set_priv_raw=*/nullptr, + /*set_priv_seed=*/nullptr, + /*set_pub_raw=*/nullptr, + /*get_priv_raw=*/nullptr, + /*get_priv_seed=*/nullptr, + /*get_pub_raw=*/nullptr, + eckey_set1_tls_encodedpoint, + eckey_get1_tls_encodedpoint, + + eckey_opaque, + + int_ec_size, + ec_bits, + + ec_missing_parameters, + ec_copy_parameters, + ec_equal_parameters, + + int_ec_free, +}; + +struct EC_PKEY_CTX { // message digest - const EVP_MD *md; - const EC_GROUP *gen_group; -} EC_PKEY_CTX; + const EVP_MD *md = nullptr; + const EC_GROUP *gen_group = nullptr; +}; - -static int pkey_ec_init(EVP_PKEY_CTX *ctx) { - EC_PKEY_CTX *dctx = - reinterpret_cast(OPENSSL_zalloc(sizeof(EC_PKEY_CTX))); +static int pkey_ec_init(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *alg) { + EC_PKEY_CTX *dctx = New(); if (!dctx) { return 0; } + const auto *ec_alg = static_cast(alg); + if (ec_alg != nullptr && ec_alg->ec_group != nullptr) { + dctx->gen_group = ec_alg->ec_group(); + } + ctx->data = dctx; return 1; } -static int pkey_ec_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { - if (!pkey_ec_init(dst)) { +static int pkey_ec_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { + if (!pkey_ec_init(dst, nullptr)) { return 0; } @@ -56,16 +364,11 @@ static int pkey_ec_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { return 1; } -static void pkey_ec_cleanup(EVP_PKEY_CTX *ctx) { - EC_PKEY_CTX *dctx = reinterpret_cast(ctx->data); - if (!dctx) { - return; - } - - OPENSSL_free(dctx); +static void pkey_ec_cleanup(EvpPkeyCtx *ctx) { + Delete(reinterpret_cast(ctx->data)); } -static int pkey_ec_sign(EVP_PKEY_CTX *ctx, uint8_t *sig, size_t *siglen, +static 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) { @@ -84,13 +387,13 @@ static int pkey_ec_sign(EVP_PKEY_CTX *ctx, uint8_t *sig, size_t *siglen, return 1; } -static int pkey_ec_verify(EVP_PKEY_CTX *ctx, const uint8_t *sig, size_t siglen, +static 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(EVP_PKEY_CTX *ctx, uint8_t *key, size_t *keylen) { +static 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; @@ -110,7 +413,7 @@ static int pkey_ec_derive(EVP_PKEY_CTX *ctx, uint8_t *key, size_t *keylen) { // NB: unlike PKCS#3 DH, if *outlen is less than maximum size this is // not an error, the result is truncated. size_t outlen = *keylen; - int ret = ECDH_compute_key(key, outlen, pubkey, eckey, 0); + int ret = ECDH_compute_key(key, outlen, pubkey, eckey, nullptr); if (ret < 0) { return 0; } @@ -118,7 +421,7 @@ static int pkey_ec_derive(EVP_PKEY_CTX *ctx, uint8_t *key, size_t *keylen) { return 1; } -static int pkey_ec_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { +static int pkey_ec_ctrl(EvpPkeyCtx *ctx, int type, int p1, void *p2) { EC_PKEY_CTX *dctx = reinterpret_cast(ctx->data); switch (type) { @@ -143,12 +446,8 @@ static int pkey_ec_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { // Default behaviour is OK return 1; - case EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID: { - const EC_GROUP *group = EC_GROUP_new_by_curve_name(p1); - if (group == NULL) { - return 0; - } - dctx->gen_group = group; + case EVP_PKEY_CTRL_EC_PARAMGEN_GROUP: { + dctx->gen_group = static_cast(p2); return 1; } @@ -158,18 +457,19 @@ static int pkey_ec_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { } } -static int pkey_ec_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { +static 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 == NULL) { - if (ctx->pkey == NULL) { + if (group == nullptr) { + if (ctx->pkey == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_NO_PARAMETERS_SET); return 0; } group = EC_KEY_get0_group(reinterpret_cast(ctx->pkey->pkey)); } EC_KEY *ec = EC_KEY_new(); - if (ec == NULL || !EC_KEY_set_group(ec, group) || !EC_KEY_generate_key(ec)) { + if (ec == nullptr || !EC_KEY_set_group(ec, group) || + !EC_KEY_generate_key(ec)) { EC_KEY_free(ec); return 0; } @@ -177,14 +477,14 @@ static int pkey_ec_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { return 1; } -static int pkey_ec_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { +static int pkey_ec_paramgen(EvpPkeyCtx *ctx, EvpPkey *pkey) { EC_PKEY_CTX *dctx = reinterpret_cast(ctx->data); - if (dctx->gen_group == NULL) { + if (dctx->gen_group == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_NO_PARAMETERS_SET); return 0; } EC_KEY *ec = EC_KEY_new(); - if (ec == NULL || !EC_KEY_set_group(ec, dctx->gen_group)) { + if (ec == nullptr || !EC_KEY_set_group(ec, dctx->gen_group)) { EC_KEY_free(ec); return 0; } @@ -192,27 +492,238 @@ static int pkey_ec_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { return 1; } -const EVP_PKEY_METHOD ec_pkey_meth = { +const EVP_PKEY_CTX_METHOD ec_pkey_meth = { EVP_PKEY_EC, pkey_ec_init, pkey_ec_copy, pkey_ec_cleanup, pkey_ec_keygen, pkey_ec_sign, - NULL /* sign_message */, + nullptr /* sign_message */, pkey_ec_verify, - NULL /* verify_message */, - NULL /* verify_recover */, - NULL /* encrypt */, - NULL /* decrypt */, + nullptr /* verify_message */, + nullptr /* verify_recover */, + nullptr /* encrypt */, + nullptr /* decrypt */, pkey_ec_derive, pkey_ec_paramgen, + /*encap=*/nullptr, + /*decap=*/nullptr, pkey_ec_ctrl, }; +} // namespace + +const EVP_PKEY_ALG *EVP_pkey_ec_p224() { + static const EVP_PKEY_ALG_EC kAlg = {{&ec_asn1_meth, &ec_pkey_meth}, + &EC_group_p224}; + return &kAlg; +} + +const EVP_PKEY_ALG *EVP_pkey_ec_p256() { + static const EVP_PKEY_ALG_EC kAlg = {{&ec_asn1_meth, &ec_pkey_meth}, + &EC_group_p256}; + return &kAlg; +} + +const EVP_PKEY_ALG *EVP_pkey_ec_p384() { + static const EVP_PKEY_ALG_EC kAlg = {{&ec_asn1_meth, &ec_pkey_meth}, + &EC_group_p384}; + return &kAlg; +} + +const EVP_PKEY_ALG *EVP_pkey_ec_p521() { + static const EVP_PKEY_ALG_EC kAlg = {{&ec_asn1_meth, &ec_pkey_meth}, + &EC_group_p521}; + return &kAlg; +} + +const EVP_PKEY_ALG *bssl::evp_pkey_ec_no_curve() { + static const EVP_PKEY_ALG_EC kAlg = {{&ec_asn1_meth, &ec_pkey_meth}, nullptr}; + 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_assign_EC_KEY(EVP_PKEY *pkey, EC_KEY *key) { + if (key == nullptr) { + return 0; + } + evp_pkey_set0(FromOpaque(pkey), &ec_asn1_meth, key); + return 1; +} + +EC_KEY *EVP_PKEY_get0_EC_KEY(const EVP_PKEY *pkey) { + if (EVP_PKEY_id(pkey) != EVP_PKEY_EC) { + OPENSSL_PUT_ERROR(EVP, EVP_R_EXPECTING_A_EC_KEY); + return nullptr; + } + return reinterpret_cast(FromOpaque(pkey)->pkey); +} + +EC_KEY *EVP_PKEY_get1_EC_KEY(const EVP_PKEY *pkey) { + EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(pkey); + if (ec_key != nullptr) { + EC_KEY_up_ref(ec_key); + } + return ec_key; +} + +static const EC_GROUP *alg_to_group(const EVP_PKEY_ALG *alg) { + if (alg->method->pkey_id != EVP_PKEY_EC) { + OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); + return nullptr; + } + auto *alg_ec = static_cast(alg); + if (alg_ec->ec_group == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); + return nullptr; + } + return alg_ec->ec_group(); +} + +static EVP_PKEY *pkey_from_ec_point(const EC_GROUP *group, const uint8_t *in, + size_t len) { + UniquePtr pkey(EVP_PKEY_new()); + UniquePtr ec_key(EC_KEY_new()); + if (pkey == nullptr || ec_key == nullptr || + !EC_KEY_set_group(ec_key.get(), group) || + !EC_KEY_oct2key(ec_key.get(), in, len, nullptr)) { + return nullptr; + } + EVP_PKEY_assign_EC_KEY(pkey.get(), ec_key.release()); + return pkey.release(); +} + +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; + } + // The `EC_KEY` APIs are not separated by uncompressed and compressed. + if (len == 0 || in[0] != 0x04) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return nullptr; + } + return pkey_from_ec_point(group, in, len); +} + +EVP_PKEY *EVP_PKEY_from_ec_compressed_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; + } + // The `EC_KEY` APIs are not separated by uncompressed and compressed. + if (len == 0 || in[0] == 0x04) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return nullptr; + } + return pkey_from_ec_point(group, in, len); +} + +static int marshal_ec_point(CBB *cbb, const EVP_PKEY *key, + point_conversion_form_t form) { + const EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(key); + if (ec_key == nullptr) { + return 0; + } + const EC_GROUP *group = EC_KEY_get0_group(ec_key); + const EC_POINT *pub = EC_KEY_get0_public_key(ec_key); + if (group == nullptr || pub == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PUBLIC_KEY); + return 0; + } + return EC_POINT_point2cbb(cbb, group, pub, form, nullptr); +} + +int EVP_PKEY_marshal_ec_uncompressed_point(CBB *cbb, const EVP_PKEY *key) { + return marshal_ec_point(cbb, key, POINT_CONVERSION_UNCOMPRESSED); +} + +int EVP_PKEY_marshal_ec_compressed_point(CBB *cbb, const EVP_PKEY *key) { + return marshal_ec_point(cbb, key, POINT_CONVERSION_COMPRESSED); +} + +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); + if (group == nullptr) { + return nullptr; + } + UniquePtr pkey(EVP_PKEY_new()); + UniquePtr ec_key(EC_KEY_new()); + if (pkey == nullptr || ec_key == nullptr || + !EC_KEY_set_group(ec_key.get(), group) || + !EC_KEY_oct2priv(ec_key.get(), in, len)) { + return nullptr; + } + // TODO(crbug.com/42290404): `EC_KEY_oct2priv` should fill in the public key + // internally. + UniquePtr pub(EC_POINT_new(group)); + if (pub == nullptr || + !EC_POINT_mul(group, pub.get(), EC_KEY_get0_private_key(ec_key.get()), + nullptr, nullptr, nullptr) || + !EC_KEY_set_public_key(ec_key.get(), pub.get())) { + return 0; + } + + EVP_PKEY_assign_EC_KEY(pkey.get(), ec_key.release()); + return pkey.release(); +} + +int EVP_PKEY_marshal_ec_private_scalar(CBB *cbb, const EVP_PKEY *key) { + const EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(key); + if (ec_key == nullptr) { + return 0; + } + size_t len = EC_KEY_priv2oct(ec_key, nullptr, 0); + if (len == 0) { + return 0; + } + uint8_t *out; + if (!CBB_reserve(cbb, &out, len)) { + return 0; + } + len = EC_KEY_priv2oct(ec_key, out, len); + return len != 0 && CBB_did_write(cbb, len); +} + +int EVP_PKEY_get_ec_curve_nid(const EVP_PKEY *pkey) { + const EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(pkey); + if (ec_key == nullptr) { + return NID_undef; + } + const EC_GROUP *group = EC_KEY_get0_group(ec_key); + if (group == nullptr) { + return NID_undef; + } + return EC_GROUP_get_curve_name(group); +} + +int EVP_PKEY_get_ec_point_conv_form(const EVP_PKEY *pkey) { + const EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(pkey); + if (ec_key == nullptr) { + return 0; + } + return EC_KEY_get_conv_form(ec_key); +} + int EVP_PKEY_CTX_set_ec_paramgen_curve_nid(EVP_PKEY_CTX *ctx, int nid) { + const EC_GROUP *group = EC_GROUP_new_by_curve_name(nid); + if (group == nullptr) { + return 0; + } return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, EVP_PKEY_OP_TYPE_GEN, - EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID, nid, NULL); + EVP_PKEY_CTRL_EC_PARAMGEN_GROUP, 0, + const_cast(group)); } int EVP_PKEY_CTX_set_ec_param_enc(EVP_PKEY_CTX *ctx, int encoding) { diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_ec_asn1.cc b/Sources/CNIOBoringSSL/crypto/evp/p_ec_asn1.cc deleted file mode 100644 index 6a16ab1a..00000000 --- a/Sources/CNIOBoringSSL/crypto/evp/p_ec_asn1.cc +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ - -#include - -#include -#include -#include -#include -#include -#include - -#include "internal.h" - - -static int eckey_pub_encode(CBB *out, const EVP_PKEY *key) { - const EC_KEY *ec_key = reinterpret_cast(key->pkey); - const EC_GROUP *group = EC_KEY_get0_group(ec_key); - const EC_POINT *public_key = EC_KEY_get0_public_key(ec_key); - - // See RFC 5480, section 2. - CBB spki, algorithm, oid, key_bitstring; - if (!CBB_add_asn1(out, &spki, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&spki, &algorithm, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&algorithm, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, ec_asn1_meth.oid, ec_asn1_meth.oid_len) || - !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, NULL) || - !CBB_flush(out)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); - return 0; - } - - return 1; -} - -static int eckey_pub_decode(EVP_PKEY *out, CBS *params, CBS *key) { - // See RFC 5480, section 2. - - // The parameters are a named curve. - const EC_GROUP *group = EC_KEY_parse_curve_name(params); - if (group == NULL || CBS_len(params) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - bssl::UniquePtr eckey(EC_KEY_new()); - if (eckey == nullptr || // - !EC_KEY_set_group(eckey.get(), group) || - !EC_KEY_oct2key(eckey.get(), CBS_data(key), CBS_len(key), nullptr)) { - return 0; - } - - EVP_PKEY_assign_EC_KEY(out, eckey.release()); - return 1; -} - -static int eckey_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *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); - const EC_POINT *pa = EC_KEY_get0_public_key(a_ec), - *pb = EC_KEY_get0_public_key(b_ec); - int r = EC_POINT_cmp(group, pa, pb, NULL); - if (r == 0) { - return 1; - } else if (r == 1) { - return 0; - } else { - return -2; - } -} - -static int eckey_priv_decode(EVP_PKEY *out, CBS *params, CBS *key) { - // See RFC 5915. - const EC_GROUP *group = EC_KEY_parse_parameters(params); - if (group == NULL || CBS_len(params) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - EC_KEY *ec_key = EC_KEY_parse_private_key(key, group); - if (ec_key == NULL || CBS_len(key) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - EC_KEY_free(ec_key); - return 0; - } - - EVP_PKEY_assign_EC_KEY(out, ec_key); - return 1; -} - -static int eckey_priv_encode(CBB *out, const EVP_PKEY *key) { - const EC_KEY *ec_key = reinterpret_cast(key->pkey); - - // Omit the redundant copy of the curve name. This contradicts RFC 5915 but - // aligns with PKCS #11. SEC 1 only says they may be omitted if known by other - // means. Both OpenSSL and NSS omit the redundant parameters, so we omit them - // as well. - unsigned enc_flags = EC_KEY_get_enc_flags(ec_key) | EC_PKEY_NO_PARAMETERS; - - // See RFC 5915. - CBB pkcs8, algorithm, oid, 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(&algorithm, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, ec_asn1_meth.oid, ec_asn1_meth.oid_len) || - !EC_KEY_marshal_curve_name(&algorithm, EC_KEY_get0_group(ec_key)) || - !CBB_add_asn1(&pkcs8, &private_key, CBS_ASN1_OCTETSTRING) || - !EC_KEY_marshal_private_key(&private_key, ec_key, enc_flags) || - !CBB_flush(out)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); - return 0; - } - - return 1; -} - -static int eckey_set1_tls_encodedpoint(EVP_PKEY *pkey, const uint8_t *in, - size_t len) { - EC_KEY *ec_key = reinterpret_cast(pkey->pkey); - if (ec_key == NULL) { - OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); - return 0; - } - - return EC_KEY_oct2key(ec_key, in, len, NULL); -} - -static size_t eckey_get1_tls_encodedpoint(const EVP_PKEY *pkey, - uint8_t **out_ptr) { - const EC_KEY *ec_key = reinterpret_cast(pkey->pkey); - if (ec_key == NULL) { - OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); - return 0; - } - - return EC_KEY_key2buf(ec_key, POINT_CONVERSION_UNCOMPRESSED, out_ptr, NULL); -} - -static int int_ec_size(const EVP_PKEY *pkey) { - const EC_KEY *ec_key = reinterpret_cast(pkey->pkey); - return ECDSA_size(ec_key); -} - -static int ec_bits(const EVP_PKEY *pkey) { - const EC_KEY *ec_key = reinterpret_cast(pkey->pkey); - const EC_GROUP *group = EC_KEY_get0_group(ec_key); - if (group == NULL) { - ERR_clear_error(); - return 0; - } - return EC_GROUP_order_bits(group); -} - -static int ec_missing_parameters(const EVP_PKEY *pkey) { - const EC_KEY *ec_key = reinterpret_cast(pkey->pkey); - return ec_key == NULL || EC_KEY_get0_group(ec_key) == NULL; -} - -static int ec_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from) { - const EC_KEY *from_key = reinterpret_cast(from->pkey); - if (from_key == NULL) { - OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); - return 0; - } - const EC_GROUP *group = EC_KEY_get0_group(from_key); - if (group == NULL) { - OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PARAMETERS); - return 0; - } - if (to->pkey == NULL) { - to->pkey = EC_KEY_new(); - if (to->pkey == NULL) { - return 0; - } - } - return EC_KEY_set_group(reinterpret_cast(to->pkey), group); -} - -static int ec_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b) { - const EC_KEY *a_ec = reinterpret_cast(a->pkey); - const EC_KEY *b_ec = reinterpret_cast(b->pkey); - if (a_ec == NULL || b_ec == NULL) { - return -2; - } - const EC_GROUP *group_a = EC_KEY_get0_group(a_ec), - *group_b = EC_KEY_get0_group(b_ec); - if (group_a == NULL || group_b == NULL) { - return -2; - } - if (EC_GROUP_cmp(group_a, group_b, NULL) != 0) { - // mismatch - return 0; - } - return 1; -} - -static void int_ec_free(EVP_PKEY *pkey) { - EC_KEY_free(reinterpret_cast(pkey->pkey)); - pkey->pkey = NULL; -} - -static int eckey_opaque(const EVP_PKEY *pkey) { - const EC_KEY *ec_key = reinterpret_cast(pkey->pkey); - return EC_KEY_is_opaque(ec_key); -} - -const EVP_PKEY_ASN1_METHOD ec_asn1_meth = { - EVP_PKEY_EC, - // 1.2.840.10045.2.1 - {0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01}, - 7, - - &ec_pkey_meth, - - eckey_pub_decode, - eckey_pub_encode, - eckey_pub_cmp, - - eckey_priv_decode, - eckey_priv_encode, - - /*set_priv_raw=*/NULL, - /*set_pub_raw=*/NULL, - /*get_priv_raw=*/NULL, - /*get_pub_raw=*/NULL, - eckey_set1_tls_encodedpoint, - eckey_get1_tls_encodedpoint, - - eckey_opaque, - - int_ec_size, - ec_bits, - - ec_missing_parameters, - ec_copy_parameters, - ec_cmp_parameters, - - int_ec_free, -}; - -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_assign_EC_KEY(EVP_PKEY *pkey, EC_KEY *key) { - evp_pkey_set_method(pkey, &ec_asn1_meth); - pkey->pkey = key; - return key != NULL; -} - -EC_KEY *EVP_PKEY_get0_EC_KEY(const EVP_PKEY *pkey) { - if (pkey->type != EVP_PKEY_EC) { - OPENSSL_PUT_ERROR(EVP, EVP_R_EXPECTING_AN_EC_KEY_KEY); - return NULL; - } - return reinterpret_cast(pkey->pkey); -} - -EC_KEY *EVP_PKEY_get1_EC_KEY(const EVP_PKEY *pkey) { - EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(pkey); - if (ec_key != NULL) { - EC_KEY_up_ref(ec_key); - } - return ec_key; -} diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_ed25519.cc b/Sources/CNIOBoringSSL/crypto/evp/p_ed25519.cc index 145f1e77..97b21c1a 100644 --- a/Sources/CNIOBoringSSL/crypto/evp/p_ed25519.cc +++ b/Sources/CNIOBoringSSL/crypto/evp/p_ed25519.cc @@ -1,48 +1,295 @@ -/* Copyright 2017 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2017 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 "../internal.h" +#include "../mem_internal.h" #include "internal.h" +using namespace bssl; -// Ed25519 has no parameters to copy. -static int pkey_ed25519_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { return 1; } +namespace { -static int pkey_ed25519_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { - ED25519_KEY *key = - reinterpret_cast(OPENSSL_malloc(sizeof(ED25519_KEY))); - if (key == NULL) { +struct ED25519_KEY { + // key is the concatenation of the private seed and public key. It is stored + // as a single 64-bit array to allow passing to `ED25519_sign`. If + // `has_private` is false, the first 32 bytes are uninitialized and the public + // key is in the last 32 bytes. + uint8_t key[64]; + bool has_private; +}; + +extern const EVP_PKEY_ASN1_METHOD ed25519_asn1_meth; +extern const EVP_PKEY_CTX_METHOD ed25519_pkey_meth; + +#define ED25519_PUBLIC_KEY_OFFSET 32 + +static 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) { + if (len != 32) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); return 0; } - evp_pkey_set_method(pkey, &ed25519_asn1_meth); + ED25519_KEY *key = New(); + if (key == nullptr) { + return 0; + } + // The RFC 8032 encoding stores only the 32-byte seed, so we must recover the + // full representation which we use from it. uint8_t pubkey_unused[32]; - ED25519_keypair(pubkey_unused, key->key); - key->has_private = 1; - - OPENSSL_free(pkey->pkey); - pkey->pkey = key; + ED25519_keypair_from_seed(pubkey_unused, key->key, in); + key->has_private = true; + evp_pkey_set0(pkey, &ed25519_asn1_meth, key); return 1; } -static int pkey_ed25519_sign_message(EVP_PKEY_CTX *ctx, uint8_t *sig, +static 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; + } + + ED25519_KEY *key = New(); + if (key == nullptr) { + return 0; + } + + OPENSSL_memcpy(key->key + ED25519_PUBLIC_KEY_OFFSET, in, 32); + key->has_private = false; + evp_pkey_set0(pkey, &ed25519_asn1_meth, key); + return 1; +} + +static 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); + return 0; + } + + if (out == nullptr) { + *out_len = 32; + return 1; + } + + if (*out_len < 32) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + + // The raw private key format is the first 32 bytes of the private key. + OPENSSL_memcpy(out, key->key, 32); + *out_len = 32; + return 1; +} + +static 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; + return 1; + } + + if (*out_len < 32) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + + OPENSSL_memcpy(out, key->key + ED25519_PUBLIC_KEY_OFFSET, 32); + *out_len = 32; + return 1; +} + +static 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. + if (CBS_len(params) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + return ed25519_set_pub_raw(out, CBS_data(key), CBS_len(key)) + ? evp_decode_ok + : evp_decode_error; +} + +static int ed25519_pub_encode(CBB *out, const EvpPkey *pkey) { + const ED25519_KEY *key = reinterpret_cast(pkey->pkey); + + // See RFC 8410, section 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, ed25519_asn1_meth.oid, + ed25519_asn1_meth.oid_len) || + !CBB_add_asn1(&spki, &key_bitstring, CBS_ASN1_BITSTRING) || + !CBB_add_u8(&key_bitstring, 0 /* padding */) || + !CBB_add_bytes(&key_bitstring, key->key + ED25519_PUBLIC_KEY_OFFSET, + 32) || + !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); + return 0; + } + + return 1; +} + +static 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) { + // See RFC 8410, section 7. + + // Parameters must be empty. The key is a 32-byte value wrapped in an extra + // OCTET STRING layer. + CBS inner; + if (CBS_len(params) != 0 || + !CBS_get_asn1(key, &inner, CBS_ASN1_OCTETSTRING) || CBS_len(key) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + return ed25519_set_priv_raw(out, CBS_data(&inner), CBS_len(&inner)) + ? evp_decode_ok + : evp_decode_error; +} + +static 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); + return 0; + } + + // See RFC 8410, section 7. + CBB pkcs8, algorithm, private_key, inner; + 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, ed25519_asn1_meth.oid, + ed25519_asn1_meth.oid_len) || + !CBB_add_asn1(&pkcs8, &private_key, CBS_ASN1_OCTETSTRING) || + !CBB_add_asn1(&private_key, &inner, CBS_ASN1_OCTETSTRING) || + // The PKCS#8 encoding stores only the 32-byte seed which is the first 32 + // bytes of the private key. + !CBB_add_bytes(&inner, key->key, 32) || // + !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); + return 0; + } + + return 1; +} + +static bool ed25519_pub_present(const EvpPkey *) { return true; } + +static bool ed25519_pub_copy(EvpPkey *out, const EvpPkey *pkey) { + const ED25519_KEY *pkey_ed25519 = + reinterpret_cast(pkey->pkey); + ED25519_KEY *public_copy = New(); + if (public_copy == nullptr) { + return false; + } + OPENSSL_memcpy(public_copy->key + ED25519_PUBLIC_KEY_OFFSET, + pkey_ed25519->key + ED25519_PUBLIC_KEY_OFFSET, + ED25519_PUBLIC_KEY_LEN); + public_copy->has_private = false; + evp_pkey_set0(out, pkey->ameth, public_copy); + return true; +} + +static 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; } + +static int ed25519_bits(const EvpPkey *pkey) { return 253; } + +const EVP_PKEY_ASN1_METHOD ed25519_asn1_meth = { + EVP_PKEY_ED25519, + {0x2b, 0x65, 0x70}, + 3, + &ed25519_pkey_meth, + ed25519_pub_decode, + ed25519_pub_encode, + ed25519_pub_equal, + ed25519_pub_present, + ed25519_pub_copy, + ed25519_priv_decode, + ed25519_priv_encode, + ed25519_priv_present, + ed25519_set_priv_raw, + /*set_priv_seed=*/nullptr, + ed25519_set_pub_raw, + ed25519_get_priv_raw, + /*get_priv_seed=*/nullptr, + ed25519_get_pub_raw, + /*set1_tls_encodedpoint=*/nullptr, + /*get1_tls_encodedpoint=*/nullptr, + /*pkey_opaque=*/nullptr, + ed25519_size, + ed25519_bits, + /*param_missing=*/nullptr, + /*param_copy=*/nullptr, + /*param_equal=*/nullptr, + ed25519_free, +}; + +// Ed25519 has no parameters to copy. +static int pkey_ed25519_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { return 1; } + +static int pkey_ed25519_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { + ED25519_KEY *key = New(); + if (key == nullptr) { + return 0; + } + + uint8_t pubkey_unused[32]; + ED25519_keypair(pubkey_unused, key->key); + key->has_private = true; + + evp_pkey_set0(pkey, &ed25519_asn1_meth, key); + return 1; +} + +static int pkey_ed25519_sign_message(EvpPkeyCtx *ctx, uint8_t *sig, size_t *siglen, const uint8_t *tbs, size_t tbslen) { const ED25519_KEY *key = @@ -52,7 +299,7 @@ static int pkey_ed25519_sign_message(EVP_PKEY_CTX *ctx, uint8_t *sig, return 0; } - if (sig == NULL) { + if (sig == nullptr) { *siglen = 64; return 1; } @@ -70,7 +317,7 @@ static int pkey_ed25519_sign_message(EVP_PKEY_CTX *ctx, uint8_t *sig, return 1; } -static int pkey_ed25519_verify_message(EVP_PKEY_CTX *ctx, const uint8_t *sig, +static 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 = @@ -84,7 +331,7 @@ static int pkey_ed25519_verify_message(EVP_PKEY_CTX *ctx, const uint8_t *sig, return 1; } -const EVP_PKEY_METHOD ed25519_pkey_meth = { +const EVP_PKEY_CTX_METHOD ed25519_pkey_meth = { /*pkey_id=*/EVP_PKEY_ED25519, /*init=*/nullptr, /*copy=*/pkey_ed25519_copy, @@ -99,5 +346,14 @@ const EVP_PKEY_METHOD ed25519_pkey_meth = { /*decrypt=*/nullptr, /*derive=*/nullptr, /*paramgen=*/nullptr, + /*encap=*/nullptr, + /*decap=*/nullptr, /*ctrl=*/nullptr, }; + +} // namespace + +const EVP_PKEY_ALG *EVP_pkey_ed25519() { + static const EVP_PKEY_ALG kAlg = {&ed25519_asn1_meth, &ed25519_pkey_meth}; + return &kAlg; +} diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_ed25519_asn1.cc b/Sources/CNIOBoringSSL/crypto/evp/p_ed25519_asn1.cc deleted file mode 100644 index 9f912c5d..00000000 --- a/Sources/CNIOBoringSSL/crypto/evp/p_ed25519_asn1.cc +++ /dev/null @@ -1,225 +0,0 @@ -/* Copyright 2017 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#include - -#include -#include -#include -#include - -#include "../internal.h" -#include "internal.h" - - -static void ed25519_free(EVP_PKEY *pkey) { - OPENSSL_free(pkey->pkey); - pkey->pkey = NULL; -} - -static int ed25519_set_priv_raw(EVP_PKEY *pkey, const uint8_t *in, size_t len) { - if (len != 32) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - ED25519_KEY *key = - reinterpret_cast(OPENSSL_malloc(sizeof(ED25519_KEY))); - if (key == NULL) { - return 0; - } - - // The RFC 8032 encoding stores only the 32-byte seed, so we must recover the - // full representation which we use from it. - uint8_t pubkey_unused[32]; - ED25519_keypair_from_seed(pubkey_unused, key->key, in); - key->has_private = 1; - - ed25519_free(pkey); - pkey->pkey = key; - return 1; -} - -static int ed25519_set_pub_raw(EVP_PKEY *pkey, const uint8_t *in, size_t len) { - if (len != 32) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - ED25519_KEY *key = - reinterpret_cast(OPENSSL_malloc(sizeof(ED25519_KEY))); - if (key == NULL) { - return 0; - } - - OPENSSL_memcpy(key->key + ED25519_PUBLIC_KEY_OFFSET, in, 32); - key->has_private = 0; - - ed25519_free(pkey); - pkey->pkey = key; - return 1; -} - -static int ed25519_get_priv_raw(const EVP_PKEY *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); - return 0; - } - - if (out == NULL) { - *out_len = 32; - return 1; - } - - if (*out_len < 32) { - OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); - return 0; - } - - // The raw private key format is the first 32 bytes of the private key. - OPENSSL_memcpy(out, key->key, 32); - *out_len = 32; - return 1; -} - -static int ed25519_get_pub_raw(const EVP_PKEY *pkey, uint8_t *out, - size_t *out_len) { - const ED25519_KEY *key = reinterpret_cast(pkey->pkey); - if (out == NULL) { - *out_len = 32; - return 1; - } - - if (*out_len < 32) { - OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); - return 0; - } - - OPENSSL_memcpy(out, key->key + ED25519_PUBLIC_KEY_OFFSET, 32); - *out_len = 32; - return 1; -} - -static int ed25519_pub_decode(EVP_PKEY *out, CBS *params, CBS *key) { - // See RFC 8410, section 4. - - // The parameters must be omitted. Public keys have length 32. - if (CBS_len(params) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - return ed25519_set_pub_raw(out, CBS_data(key), CBS_len(key)); -} - -static int ed25519_pub_encode(CBB *out, const EVP_PKEY *pkey) { - const ED25519_KEY *key = reinterpret_cast(pkey->pkey); - - // See RFC 8410, section 4. - CBB spki, algorithm, oid, key_bitstring; - if (!CBB_add_asn1(out, &spki, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&spki, &algorithm, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&algorithm, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, ed25519_asn1_meth.oid, ed25519_asn1_meth.oid_len) || - !CBB_add_asn1(&spki, &key_bitstring, CBS_ASN1_BITSTRING) || - !CBB_add_u8(&key_bitstring, 0 /* padding */) || - !CBB_add_bytes(&key_bitstring, key->key + ED25519_PUBLIC_KEY_OFFSET, - 32) || - !CBB_flush(out)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); - return 0; - } - - return 1; -} - -static int ed25519_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *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 int ed25519_priv_decode(EVP_PKEY *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 - // OCTET STRING layer. - CBS inner; - if (CBS_len(params) != 0 || - !CBS_get_asn1(key, &inner, CBS_ASN1_OCTETSTRING) || CBS_len(key) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - return ed25519_set_priv_raw(out, CBS_data(&inner), CBS_len(&inner)); -} - -static int ed25519_priv_encode(CBB *out, const EVP_PKEY *pkey) { - const ED25519_KEY *key = reinterpret_cast(pkey->pkey); - if (!key->has_private) { - OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); - return 0; - } - - // See RFC 8410, section 7. - CBB pkcs8, algorithm, oid, private_key, inner; - 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(&algorithm, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, ed25519_asn1_meth.oid, ed25519_asn1_meth.oid_len) || - !CBB_add_asn1(&pkcs8, &private_key, CBS_ASN1_OCTETSTRING) || - !CBB_add_asn1(&private_key, &inner, CBS_ASN1_OCTETSTRING) || - // The PKCS#8 encoding stores only the 32-byte seed which is the first 32 - // bytes of the private key. - !CBB_add_bytes(&inner, key->key, 32) || // - !CBB_flush(out)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); - return 0; - } - - return 1; -} - -static int ed25519_size(const EVP_PKEY *pkey) { return 64; } - -static int ed25519_bits(const EVP_PKEY *pkey) { return 253; } - -const EVP_PKEY_ASN1_METHOD ed25519_asn1_meth = { - EVP_PKEY_ED25519, - {0x2b, 0x65, 0x70}, - 3, - &ed25519_pkey_meth, - ed25519_pub_decode, - ed25519_pub_encode, - ed25519_pub_cmp, - ed25519_priv_decode, - ed25519_priv_encode, - ed25519_set_priv_raw, - ed25519_set_pub_raw, - ed25519_get_priv_raw, - ed25519_get_pub_raw, - /*set1_tls_encodedpoint=*/NULL, - /*get1_tls_encodedpoint=*/NULL, - /*pkey_opaque=*/NULL, - ed25519_size, - ed25519_bits, - /*param_missing=*/NULL, - /*param_copy=*/NULL, - /*param_cmp=*/NULL, - ed25519_free, -}; diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_hkdf.cc b/Sources/CNIOBoringSSL/crypto/evp/p_hkdf.cc index 7c87bebe..2eb1fe12 100644 --- a/Sources/CNIOBoringSSL/crypto/evp/p_hkdf.cc +++ b/Sources/CNIOBoringSSL/crypto/evp/p_hkdf.cc @@ -1,57 +1,49 @@ -/* Copyright 2022 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2022 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 "../internal.h" +#include "../mem_internal.h" #include "internal.h" -typedef struct { - int mode; - const EVP_MD *md; - uint8_t *key; - size_t key_len; - uint8_t *salt; - size_t salt_len; - CBB info; -} HKDF_PKEY_CTX; +using namespace bssl; -static int pkey_hkdf_init(EVP_PKEY_CTX *ctx) { - HKDF_PKEY_CTX *hctx = - reinterpret_cast(OPENSSL_zalloc(sizeof(HKDF_PKEY_CTX))); - if (hctx == NULL) { - return 0; - } +namespace { - if (!CBB_init(&hctx->info, 0)) { - OPENSSL_free(hctx); - return 0; - } +struct HKDF_PKEY_CTX { + int mode = 0; + const EVP_MD *md = nullptr; + Array key; + Array salt; + Vector info; +}; - ctx->data = hctx; +static int pkey_hkdf_init(EvpPkeyCtx *ctx, const EVP_PKEY_ALG *) { + ctx->data = New(); return 1; } -static int pkey_hkdf_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { - if (!pkey_hkdf_init(dst)) { +static int pkey_hkdf_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { + if (!pkey_hkdf_init(dst, nullptr)) { return 0; } @@ -61,85 +53,64 @@ static int pkey_hkdf_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { hctx_dst->mode = hctx_src->mode; hctx_dst->md = hctx_src->md; - if (hctx_src->key_len != 0) { - hctx_dst->key = reinterpret_cast( - OPENSSL_memdup(hctx_src->key, hctx_src->key_len)); - if (hctx_dst->key == NULL) { - return 0; - } - hctx_dst->key_len = hctx_src->key_len; - } - - if (hctx_src->salt_len != 0) { - hctx_dst->salt = reinterpret_cast( - OPENSSL_memdup(hctx_src->salt, hctx_src->salt_len)); - if (hctx_dst->salt == NULL) { - return 0; - } - hctx_dst->salt_len = hctx_src->salt_len; - } - - if (!CBB_add_bytes(&hctx_dst->info, CBB_data(&hctx_src->info), - CBB_len(&hctx_src->info))) { + if (!hctx_dst->key.CopyFrom(hctx_src->key) || + !hctx_dst->salt.CopyFrom(hctx_src->salt) || + !hctx_dst->info.CopyFrom(hctx_src->info)) { return 0; } return 1; } -static void pkey_hkdf_cleanup(EVP_PKEY_CTX *ctx) { - HKDF_PKEY_CTX *hctx = reinterpret_cast(ctx->data); - if (hctx != NULL) { - OPENSSL_free(hctx->key); - OPENSSL_free(hctx->salt); - CBB_cleanup(&hctx->info); - OPENSSL_free(hctx); - ctx->data = NULL; - } +static void pkey_hkdf_cleanup(EvpPkeyCtx *ctx) { + Delete(reinterpret_cast(ctx->data)); } -static int pkey_hkdf_derive(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *out_len) { +static int pkey_hkdf_derive(EvpPkeyCtx *ctx, uint8_t *out, size_t *out_len) { HKDF_PKEY_CTX *hctx = reinterpret_cast(ctx->data); - if (hctx->md == NULL) { + if (hctx->md == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PARAMETERS); return 0; } - if (hctx->key_len == 0) { + if (hctx->key.empty()) { OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); return 0; } - if (out == NULL) { + if (out == nullptr) { if (hctx->mode == EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY) { *out_len = EVP_MD_size(hctx->md); } - // HKDF-Expand is variable-length and returns |*out_len| bytes. "Output" the + // HKDF-Expand is variable-length and returns `*out_len` bytes. "Output" the // input length by leaving it alone. return 1; } switch (hctx->mode) { case EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND: - return HKDF(out, *out_len, hctx->md, hctx->key, hctx->key_len, hctx->salt, - hctx->salt_len, CBB_data(&hctx->info), CBB_len(&hctx->info)); + return HKDF(out, *out_len, hctx->md, hctx->key.data(), hctx->key.size(), + hctx->salt.data(), hctx->salt.size(), hctx->info.data(), + hctx->info.size()); case EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY: if (*out_len < EVP_MD_size(hctx->md)) { OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); return 0; } - return HKDF_extract(out, out_len, hctx->md, hctx->key, hctx->key_len, - hctx->salt, hctx->salt_len); + return HKDF_extract(out, out_len, hctx->md, hctx->key.data(), + hctx->key.size(), hctx->salt.data(), + hctx->salt.size()); case EVP_PKEY_HKDEF_MODE_EXPAND_ONLY: - return HKDF_expand(out, *out_len, hctx->md, hctx->key, hctx->key_len, - CBB_data(&hctx->info), CBB_len(&hctx->info)); + return HKDF_expand(out, *out_len, hctx->md, hctx->key.data(), + hctx->key.size(), hctx->info.data(), + hctx->info.size()); } OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR); return 0; } -static int pkey_hkdf_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { +static 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: @@ -155,27 +126,18 @@ static int pkey_hkdf_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { hctx->md = reinterpret_cast(p2); return 1; case EVP_PKEY_CTRL_HKDF_KEY: { - const CBS *key = reinterpret_cast(p2); - if (!CBS_stow(key, &hctx->key, &hctx->key_len)) { - return 0; - } - return 1; + const auto *key = reinterpret_cast *>(p2); + return hctx->key.CopyFrom(*key); } case EVP_PKEY_CTRL_HKDF_SALT: { - const CBS *salt = reinterpret_cast(p2); - if (!CBS_stow(salt, &hctx->salt, &hctx->salt_len)) { - return 0; - } - return 1; + const auto *salt = reinterpret_cast *>(p2); + return hctx->salt.CopyFrom(*salt); } case EVP_PKEY_CTRL_HKDF_INFO: { - const CBS *info = reinterpret_cast(p2); - // |EVP_PKEY_CTX_add1_hkdf_info| appends to the info string, rather than + const auto *info = reinterpret_cast *>(p2); + // `EVP_PKEY_CTX_add1_hkdf_info` appends to the info string, rather than // replacing it. - if (!CBB_add_bytes(&hctx->info, CBS_data(info), CBS_len(info))) { - return 0; - } - return 1; + return hctx->info.Append(*info); } default: OPENSSL_PUT_ERROR(EVP, EVP_R_COMMAND_NOT_SUPPORTED); @@ -183,27 +145,36 @@ static int pkey_hkdf_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { } } -const EVP_PKEY_METHOD hkdf_pkey_meth = { - /*pkey_id=*/EVP_PKEY_HKDF, +const EVP_PKEY_CTX_METHOD hkdf_pkey_meth = { + EVP_PKEY_HKDF, pkey_hkdf_init, pkey_hkdf_copy, pkey_hkdf_cleanup, - /*keygen=*/NULL, - /*sign=*/NULL, - /*sign_message=*/NULL, - /*verify=*/NULL, - /*verify_message=*/NULL, - /*verify_recover=*/NULL, - /*encrypt=*/NULL, - /*decrypt=*/NULL, + /*keygen=*/nullptr, + /*sign=*/nullptr, + /*sign_message=*/nullptr, + /*verify=*/nullptr, + /*verify_message=*/nullptr, + /*verify_recover=*/nullptr, + /*encrypt=*/nullptr, + /*decrypt=*/nullptr, pkey_hkdf_derive, - /*paramgen=*/NULL, + /*paramgen=*/nullptr, + /*encap=*/nullptr, + /*decap=*/nullptr, pkey_hkdf_ctrl, }; +} // namespace + +const EVP_PKEY_ALG *bssl::evp_pkey_hkdf() { + static const EVP_PKEY_ALG kAlg = {nullptr, &hkdf_pkey_meth}; + return &kAlg; +} + int EVP_PKEY_CTX_hkdf_mode(EVP_PKEY_CTX *ctx, int mode) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_HKDF, EVP_PKEY_OP_DERIVE, - EVP_PKEY_CTRL_HKDF_MODE, mode, NULL); + EVP_PKEY_CTRL_HKDF_MODE, mode, nullptr); } int EVP_PKEY_CTX_set_hkdf_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { @@ -213,24 +184,21 @@ int EVP_PKEY_CTX_set_hkdf_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { int EVP_PKEY_CTX_set1_hkdf_key(EVP_PKEY_CTX *ctx, const uint8_t *key, size_t key_len) { - CBS cbs; - CBS_init(&cbs, key, key_len); + Span span(key, key_len); return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_HKDF, EVP_PKEY_OP_DERIVE, - EVP_PKEY_CTRL_HKDF_KEY, 0, &cbs); + EVP_PKEY_CTRL_HKDF_KEY, 0, &span); } int EVP_PKEY_CTX_set1_hkdf_salt(EVP_PKEY_CTX *ctx, const uint8_t *salt, size_t salt_len) { - CBS cbs; - CBS_init(&cbs, salt, salt_len); + Span span(salt, salt_len); return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_HKDF, EVP_PKEY_OP_DERIVE, - EVP_PKEY_CTRL_HKDF_SALT, 0, &cbs); + EVP_PKEY_CTRL_HKDF_SALT, 0, &span); } int EVP_PKEY_CTX_add1_hkdf_info(EVP_PKEY_CTX *ctx, const uint8_t *info, size_t info_len) { - CBS cbs; - CBS_init(&cbs, info, info_len); + Span span(info, info_len); return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_HKDF, EVP_PKEY_OP_DERIVE, - EVP_PKEY_CTRL_HKDF_INFO, 0, &cbs); + EVP_PKEY_CTRL_HKDF_INFO, 0, &span); } diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_mldsa.cc b/Sources/CNIOBoringSSL/crypto/evp/p_mldsa.cc new file mode 100644 index 00000000..29146baf --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/evp/p_mldsa.cc @@ -0,0 +1,549 @@ +// Copyright 2025 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 "../fipsmodule/bcm_interface.h" +#include "../mem_internal.h" +#include "internal.h" + +using namespace bssl; + +namespace { + +constexpr CBS_ASN1_TAG kSeedTag = CBS_ASN1_CONTEXT_SPECIFIC | 0; + +constexpr uint8_t kMLDSA44OID[] = {OBJ_ENC_ML_DSA_44}; +constexpr uint8_t kMLDSA65OID[] = {OBJ_ENC_ML_DSA_65}; +constexpr uint8_t kMLDSA87OID[] = {OBJ_ENC_ML_DSA_87}; + +constexpr int kMaxContextLength = 255; + +// We must generate EVP bindings for three ML-DSA algorithms. Define a traits +// type that captures the functions and other parameters of an ML-DSA algorithm. +#define MAKE_MLDSA_TRAITS(kl) \ + struct MLDSA##kl##Traits { \ + using PublicKey = MLDSA##kl##_public_key; \ + using PrivateKey = MLDSA##kl##_private_key; \ + static constexpr size_t kPublicKeyBytes = MLDSA##kl##_PUBLIC_KEY_BYTES; \ + static constexpr size_t kSignatureBytes = MLDSA##kl##_SIGNATURE_BYTES; \ + static constexpr int kType = EVP_PKEY_ML_DSA_##kl; \ + static constexpr Span kOID = kMLDSA##kl##OID; \ + static constexpr auto PrivateKeyFromSeed = \ + &MLDSA##kl##_private_key_from_seed; \ + static constexpr auto GenerateKey = &MLDSA##kl##_generate_key; \ + static constexpr auto Sign = &MLDSA##kl##_sign; \ + static constexpr auto ParsePublicKey = &MLDSA##kl##_parse_public_key; \ + static constexpr auto PublicOfPrivate = \ + &BCM_mldsa##kl##_public_of_private; \ + static constexpr auto MarshalPublicKey = &MLDSA##kl##_marshal_public_key; \ + static constexpr auto PublicKeysEqual = \ + &BCM_mldsa##kl##_public_keys_equal; \ + static constexpr auto Verify = &MLDSA##kl##_verify; \ + static_assert(std::is_trivially_copyable_v, \ + "PublicKey type must be trivially copyable."); \ + }; + +MAKE_MLDSA_TRAITS(44) +MAKE_MLDSA_TRAITS(65) +MAKE_MLDSA_TRAITS(87) + +// For each ML-DSA variant, the `EvpPkey` must hold a public or private key. +// EVP uses the same type for public and private keys, so the representation +// must support both. The private key type contains the public key struct in it, +// so we use a pointer to either a PrivateKeyData or +// PublicKeyData, with a common base class to dispatch between them. +// +// TODO(crbug.com/404286922): In C++20, we need fewer `typename`s in front of +// dependent type names. + +template +class PrivateKeyData; + +template +class KeyData { + public: + // Returns the underlying public key for the key. + const typename Traits::PublicKey *GetPublicKey() const; + + // Returns the PrivateKeyData struct for the key, or nullptr if this is a + // public key. + PrivateKeyData *AsPrivateKeyData(); + const PrivateKeyData *AsPrivateKeyData() const { + return const_cast(this)->AsPrivateKeyData(); + } + + // A KeyData cannot be freed directly. Rather, it must use this wrapper which + // calls the correct subclass's destructor. + static void Free(KeyData *data); + + protected: + explicit KeyData(bool is_private) : is_private_(is_private) {} + ~KeyData() = default; + bool is_private_; +}; + +template +class PublicKeyData : public KeyData { + public: + enum { kAllowUniquePtr = true }; + PublicKeyData() : KeyData(/*is_private=*/false) {} + + // Allows copying the PublicKey. + explicit PublicKeyData(const typename Traits::PublicKey &key) + : KeyData(/*is_private=*/false), pub(key) {} + + typename Traits::PublicKey pub; +}; + +template +class PrivateKeyData : public KeyData { + public: + enum { kAllowUniquePtr = true }; + PrivateKeyData() : KeyData(/*is_private=*/true) {} + typename Traits::PrivateKey priv; + uint8_t seed[MLDSA_SEED_BYTES]; +}; + +template +const typename Traits::PublicKey *KeyData::GetPublicKey() const { + auto *priv_data = AsPrivateKeyData(); + if (priv_data != nullptr) { + return Traits::PublicOfPrivate(&priv_data->priv); + } + return &static_cast *>(this)->pub; +} + +template +PrivateKeyData *KeyData::AsPrivateKeyData() { + if (is_private_) { + return static_cast *>(this); + } + return nullptr; +} + +template +void KeyData::Free(KeyData *data) { + if (data == nullptr) { + return; + } + // Delete the more specific subclass. This is moot for now, because neither + // type has a non-trivial destructor. + auto *priv_data = data->AsPrivateKeyData(); + if (priv_data) { + Delete(priv_data); + } else { + Delete(static_cast *>(data)); + } +} + +struct MldsaPkeyCtx { + bssl::Array context; +}; + + +// Finally, MLDSAImplementation instantiates the methods themselves. + +template +struct MLDSAImplementation { + static KeyData *GetKeyData(EvpPkey *pkey) { + assert(pkey->ameth == &asn1_method); + return static_cast *>(pkey->pkey); + } + + static const KeyData *GetKeyData(const EvpPkey *pkey) { + return GetKeyData(const_cast(pkey)); + } + + static void PkeyFree(EvpPkey *pkey) { + KeyData::Free(GetKeyData(pkey)); + pkey->pkey = nullptr; + } + + static int SetPrivateSeed(EvpPkey *pkey, const uint8_t *in, size_t len) { + auto priv = MakeUnique>(); + if (priv == nullptr) { + return 0; + } + + if (len != MLDSA_SEED_BYTES || + !Traits::PrivateKeyFromSeed(&priv->priv, in, len)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return 0; + } + OPENSSL_memcpy(priv->seed, in, len); + evp_pkey_set0(pkey, &asn1_method, priv.release()); + return 1; + } + + static int SetRawPublic(EvpPkey *pkey, const uint8_t *in, size_t len) { + auto pub = MakeUnique>(); + if (pub == nullptr) { + return 0; + } + CBS cbs; + CBS_init(&cbs, in, len); + if (!Traits::ParsePublicKey(&pub->pub, &cbs) || CBS_len(&cbs) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return 0; + } + evp_pkey_set0(pkey, &asn1_method, pub.release()); + return 1; + } + + static int GetPrivateSeed(const EvpPkey *pkey, uint8_t *out, + size_t *out_len) { + const auto *priv = GetKeyData(pkey)->AsPrivateKeyData(); + if (priv == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); + return 0; + } + if (out == nullptr) { + *out_len = MLDSA_SEED_BYTES; + return 1; + } + if (*out_len < MLDSA_SEED_BYTES) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + OPENSSL_memcpy(out, priv->seed, MLDSA_SEED_BYTES); + *out_len = MLDSA_SEED_BYTES; + return 1; + } + + static int GetRawPublic(const EvpPkey *pkey, uint8_t *out, size_t *out_len) { + const auto *pub = GetKeyData(pkey)->GetPublicKey(); + 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; + } + CBB cbb; + CBB_init_fixed(&cbb, out, Traits::kPublicKeyBytes); + BSSL_CHECK(Traits::MarshalPublicKey(&cbb, pub)); + BSSL_CHECK(CBB_len(&cbb) == 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 9881, Section 2. + 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 auto *pub = GetKeyData(pkey)->GetPublicKey(); + // See RFC 9881, Sections 2 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 */) || + !Traits::MarshalPublicKey(&key_bitstring, pub) || + !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 auto *a_pub = GetKeyData(a)->GetPublicKey(); + const auto *b_pub = GetKeyData(b)->GetPublicKey(); + return Traits::PublicKeysEqual(a_pub, b_pub); + } + + static bool HasPublic(const EvpPkey *pk) { return true; } + + static bool CopyPublic(EvpPkey *out, const EvpPkey *pk) { + auto *public_copy = + New>(*GetKeyData(pk)->GetPublicKey()); + if (public_copy == nullptr) { + OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR); + return false; + } + evp_pkey_set0(out, pk->ameth, public_copy); + 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 9881, Section 2. + if (CBS_len(params) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + // See RFC 9881, Section 6. Three different encodings were specified, adding + // complexity to the question of whether a private key is valid. We only + // implement the "seed" representation. Give this case a different error for + // easier diagnostics. + // + // The "expandedKey" representation was a last-minute accommodation for + // legacy hardware, which should be updated to use seeds. Supporting it + // complicates the notion of a private key with both seedful and seedless + // variants. + // + // The "both" representation is technically unsound and + // dangerous, so we do not implement it. Systems composed of components, + // some of which look at one half of the "both" representation, and half of + // the other, will appear to interop, but break when an input is + // inconsistent. The expanded key can be computed from the seed, so there is + // no purpose in this form. + CBS seed; + if (!CBS_get_asn1(key, &seed, kSeedTag)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_PRIVATE_KEY_WAS_NOT_SEED); + return evp_decode_error; + } + if (CBS_len(key) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + return SetPrivateSeed(out, CBS_data(&seed), CBS_len(&seed)) + ? evp_decode_ok + : evp_decode_error; + } + + static int EncodePrivate(CBB *out, const EvpPkey *pkey) { + const auto *priv = GetKeyData(pkey)->AsPrivateKeyData(); + if (priv == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); + return 0; + } + // See RFC 9881, Sections 2 and 6. We encode only the seed representation. + 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_asn1_element(&private_key, kSeedTag, priv->seed, + sizeof(priv->seed)) || + !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); + return 0; + } + return 1; + } + + static bool HasPrivate(const EvpPkey *pk) { + return GetKeyData(pk)->AsPrivateKeyData() != nullptr; + } + + 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 *) { + MldsaPkeyCtx *mctx = New(); + if (mctx == nullptr) { + return 0; + } + ctx->data = mctx; + 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; + } + MldsaPkeyCtx *sctx = static_cast(src->data); + MldsaPkeyCtx *dctx = static_cast(dst->data); + if (!dctx->context.CopyFrom(sctx->context)) { + return 0; + } + return 1; + } + + static int KeyGen(EvpPkeyCtx *ctx, EvpPkey *pkey) { + auto priv = MakeUnique>(); + if (priv == nullptr) { + return 0; + } + uint8_t unused_public[Traits::kPublicKeyBytes]; + if (!Traits::GenerateKey(unused_public, priv->seed, &priv->priv)) { + return 0; + } + evp_pkey_set0(pkey, &asn1_method, priv.release()); + return 1; + } + + static int SignMessage(EvpPkeyCtx *ctx, uint8_t *sig, size_t *siglen, + const uint8_t *tbs, size_t tbslen) { + const auto *priv_data = GetKeyData(ctx->pkey.get())->AsPrivateKeyData(); + if (priv_data == nullptr) { + 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; + } + MldsaPkeyCtx *mctx = static_cast(ctx->data); + if (!Traits::Sign(sig, &priv_data->priv, tbs, tbslen, mctx->context.data(), + mctx->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 auto *pub = GetKeyData(ctx->pkey.get())->GetPublicKey(); + MldsaPkeyCtx *mctx = static_cast(ctx->data); + if (!Traits::Verify(pub, sig, siglen, tbs, tbslen, mctx->context.data(), + mctx->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) { + MldsaPkeyCtx *mctx = 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 mctx->context.CopyFrom(*context_string); + } + + default: + OPENSSL_PUT_ERROR(EVP, EVP_R_COMMAND_NOT_SUPPORTED); + return 0; + } + } + + static constexpr EVP_PKEY_CTX_METHOD pkey_method = { + Traits::kType, + &Init, + &CopyContext, + &Cleanup, + &KeyGen, + /*sign=*/nullptr, + &SignMessage, + /*verify=*/nullptr, + &VerifyMessage, + /*verify_recover=*/nullptr, + /*encrypt=*/nullptr, + /*decrypt=*/nullptr, + /*derive=*/nullptr, + /*paramgen=*/nullptr, + /*encap=*/nullptr, + /*decap=*/nullptr, + &Ctrl, + }; + + 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, + // While exporting the seed as the "raw" private key would be natural, + // OpenSSL connected these APIs to the "raw private key", so we export + // the seed separately. + /*set_priv_raw=*/nullptr, + &SetPrivateSeed, + &SetRawPublic, + /*get_priv_raw=*/nullptr, + &GetPrivateSeed, + &GetRawPublic, + /*set1_tls_encodedpoint=*/nullptr, + /*get1_tls_encodedpoint=*/nullptr, + /*pkey_opaque=*/nullptr, + &PkeySize, + &PkeyBits, + /*param_missing=*/nullptr, + /*param_copy=*/nullptr, + /*param_equal=*/nullptr, + &PkeyFree, + }; + // TODO(crbug.com/404286922): Use std::copy in C++20, when it's constexpr. + // TODO(crbug.com/450823446): Better yet, make this field an InplaceVector + // and give it a suitable constructor. + 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_ml_dsa_44() { + return &MLDSAImplementation::pkey_alg; +} + +const EVP_PKEY_ALG *EVP_pkey_ml_dsa_65() { + return &MLDSAImplementation::pkey_alg; +} + +const EVP_PKEY_ALG *EVP_pkey_ml_dsa_87() { + return &MLDSAImplementation::pkey_alg; +} diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_mlkem.cc b/Sources/CNIOBoringSSL/crypto/evp/p_mlkem.cc new file mode 100644 index 00000000..8f69b265 --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/evp/p_mlkem.cc @@ -0,0 +1,510 @@ +// 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 "../fipsmodule/bcm_interface.h" +#include "../internal.h" +#include "../mem_internal.h" +#include "internal.h" + +using namespace bssl; + +namespace { + +constexpr CBS_ASN1_TAG kSeedTag = CBS_ASN1_CONTEXT_SPECIFIC | 0; + +constexpr uint8_t kMLKEM768OID[] = {OBJ_ENC_ML_KEM_768}; +constexpr uint8_t kMLKEM1024OID[] = {OBJ_ENC_ML_KEM_1024}; + +// Generate EVP bindings for multiple ML-KEM algorithms. +#define MAKE_MLKEM_TRAITS(x) \ + struct MLKEM##x##Traits { \ + using PublicKey = MLKEM##x##_public_key; \ + using PrivateKey = MLKEM##x##_private_key; \ + static constexpr size_t kPublicKeyBytes = MLKEM##x##_PUBLIC_KEY_BYTES; \ + static constexpr size_t kCiphertextBytes = MLKEM##x##_CIPHERTEXT_BYTES; \ + static constexpr int kType = EVP_PKEY_ML_KEM_##x; \ + static constexpr Span kOID = kMLKEM##x##OID; \ + static constexpr auto GenerateKey = &MLKEM##x##_generate_key; \ + static constexpr auto PrivateKeyFromSeed = \ + &MLKEM##x##_private_key_from_seed; \ + static constexpr auto PublicOfPrivate = &BCM_mlkem##x##_public_of_private; \ + static constexpr auto PublicKeysEqual = &BCM_mlkem##x##_public_keys_equal; \ + static constexpr auto Encap = &MLKEM##x##_encap; \ + static constexpr auto EncapExternalEntropy = \ + &BCM_mlkem##x##_encap_external_entropy; \ + static constexpr auto Decap = &MLKEM##x##_decap; \ + static constexpr auto MarshalPublicKey = &MLKEM##x##_marshal_public_key; \ + static constexpr auto ParsePublicKey = &MLKEM##x##_parse_public_key; \ + static_assert(std::is_trivially_copyable_v, \ + "PublicKey type must be trivially copyable."); \ + }; + +MAKE_MLKEM_TRAITS(768) +MAKE_MLKEM_TRAITS(1024) + +template +class PrivateKeyData; + +// The private key type contains the public key struct in it, so we use a +// pointer to either a PrivateKeyData or PublicKeyData, with a +// common base class to dispatch between them. +template +class KeyData { + public: + // Returns the underlying public key for the key. + const typename Traits::PublicKey *GetPublicKey() const; + + // Returns the PrivateKeyData struct for the key, or nullptr if this is a + // public key. + PrivateKeyData *AsPrivateKeyData(); + const PrivateKeyData *AsPrivateKeyData() const { + return const_cast(this)->AsPrivateKeyData(); + } + + // A KeyData cannot be freed directly. Rather, it must use this wrapper which + // calls the correct subclass's destructor. + static void Free(KeyData *data); + + protected: + explicit KeyData(bool is_private) : is_private_(is_private) {} + ~KeyData() = default; + bool is_private_; +}; + +template +class PublicKeyData : public KeyData { + public: + enum { kAllowUniquePtr = true }; + PublicKeyData() : KeyData(/*is_private=*/false) {} + + // Allows copying the PublicKey. + explicit PublicKeyData(const typename Traits::PublicKey &key) + : KeyData(/*is_private=*/false), pub(key) {} + + typename Traits::PublicKey pub; +}; + +template +class PrivateKeyData : public KeyData { + public: + enum { kAllowUniquePtr = true }; + PrivateKeyData() : KeyData(/*is_private=*/true) {} + typename Traits::PrivateKey priv; + uint8_t seed[MLKEM_SEED_BYTES]; +}; + +template +const typename Traits::PublicKey *KeyData::GetPublicKey() const { + auto *priv_data = AsPrivateKeyData(); + if (priv_data != nullptr) { + return Traits::PublicOfPrivate(&priv_data->priv); + } + return &static_cast *>(this)->pub; +} + +template +PrivateKeyData *KeyData::AsPrivateKeyData() { + if (is_private_) { + return static_cast *>(this); + } + return nullptr; +} + +template +void KeyData::Free(KeyData *data) { + if (data == nullptr) { + return; + } + // Delete the more specific subclass. This is moot for now, because neither + // type has a non-trivial destructor. + auto *priv_data = data->AsPrivateKeyData(); + if (priv_data) { + Delete(priv_data); + } else { + Delete(static_cast *>(data)); + } +} + +template +struct MLKEMImplementation { + static KeyData *GetKeyData(EvpPkey *pkey) { + assert(pkey->ameth == &asn1_method); + return static_cast *>(pkey->pkey); + } + + static const KeyData *GetKeyData(const EvpPkey *pkey) { + return GetKeyData(const_cast(pkey)); + } + + static void PkeyFree(EvpPkey *pkey) { + KeyData::Free(GetKeyData(pkey)); + pkey->pkey = nullptr; + } + + static int SetPrivateSeed(EvpPkey *pkey, const uint8_t *in, size_t len) { + auto priv = MakeUnique>(); + if (priv == nullptr) { + return 0; + } + + if (len != MLKEM_SEED_BYTES || + !Traits::PrivateKeyFromSeed(&priv->priv, in, len)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return 0; + } + OPENSSL_memcpy(priv->seed, in, len); + evp_pkey_set0(pkey, &asn1_method, priv.release()); + return 1; + } + + static int SetRawPublic(EvpPkey *pkey, const uint8_t *in, size_t len) { + auto pub = MakeUnique>(); + if (pub == nullptr) { + return 0; + } + CBS cbs; + CBS_init(&cbs, in, len); + if (!Traits::ParsePublicKey(&pub->pub, &cbs) || CBS_len(&cbs) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return 0; + } + evp_pkey_set0(pkey, &asn1_method, pub.release()); + return 1; + } + + static int GetPrivateSeed(const EvpPkey *pkey, uint8_t *out, + size_t *out_len) { + const auto *priv = GetKeyData(pkey)->AsPrivateKeyData(); + if (priv == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); + return 0; + } + if (out == nullptr) { + *out_len = MLKEM_SEED_BYTES; + return 1; + } + if (*out_len < MLKEM_SEED_BYTES) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + OPENSSL_memcpy(out, priv->seed, MLKEM_SEED_BYTES); + *out_len = MLKEM_SEED_BYTES; + return 1; + } + + static int GetRawPublic(const EvpPkey *pkey, uint8_t *out, size_t *out_len) { + const auto *pub = GetKeyData(pkey)->GetPublicKey(); + 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; + } + CBB cbb; + CBB_init_fixed(&cbb, out, Traits::kPublicKeyBytes); + BSSL_CHECK(Traits::MarshalPublicKey(&cbb, pub)); + BSSL_CHECK(CBB_len(&cbb) == 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) { + // Parameters must be absent. See RFC 9935, section 3. + 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 auto *pub = GetKeyData(pkey)->GetPublicKey(); + // See RFC 9935, section 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 */) || + !Traits::MarshalPublicKey(&key_bitstring, pub) || // + !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 auto *a_pub = GetKeyData(a)->GetPublicKey(); + const auto *b_pub = GetKeyData(b)->GetPublicKey(); + return Traits::PublicKeysEqual(a_pub, b_pub); + } + + static bool HasPublic(const EvpPkey *pk) { return true; } + + static bool CopyPublic(EvpPkey *out, const EvpPkey *pk) { + auto *public_copy = + New>(*GetKeyData(pk)->GetPublicKey()); + if (public_copy == nullptr) { + return false; + } + evp_pkey_set0(out, pk->ameth, public_copy); + return true; + } + + static evp_decode_result_t DecodePrivate(const EVP_PKEY_ALG *alg, + EvpPkey *out, CBS *params, + CBS *key) { + // Parameters must be absent. See RFC 9935, section 3. + if (CBS_len(params) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + // See RFC 9935, section 6. Three different encodings are specified. We only + // implement the "seed" representation. + CBS seed; + if (!CBS_get_asn1(key, &seed, kSeedTag)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_PRIVATE_KEY_WAS_NOT_SEED); + return evp_decode_error; + } + if (CBS_len(key) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + return SetPrivateSeed(out, CBS_data(&seed), CBS_len(&seed)) + ? evp_decode_ok + : evp_decode_error; + } + + static int EncodePrivate(CBB *out, const EvpPkey *pkey) { + const auto *priv = GetKeyData(pkey)->AsPrivateKeyData(); + if (priv == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); + return 0; + } + + // See RFC 9935, section 6. Three different encodings are specified. We only + // implement the "seed" representation. + 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_asn1_element(&private_key, kSeedTag, priv->seed, + sizeof(priv->seed)) || + !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); + return 0; + } + return 1; + } + + static bool HasPrivate(const EvpPkey *pk) { + return GetKeyData(pk)->AsPrivateKeyData() != nullptr; + } + + static int PkeySize(const EvpPkey *pkey) { return Traits::kCiphertextBytes; } + static int PkeyBits(const EvpPkey *pkey) { + return Traits::kPublicKeyBytes * 8; + } + + static int CopyCtx(EvpPkeyCtx *dst, EvpPkeyCtx *src) { return 1; } + + static int KeyGen(EvpPkeyCtx *ctx, EvpPkey *pkey) { + auto priv = MakeUnique>(); + if (priv == nullptr) { + OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR); + return 0; + } + uint8_t unused_public[Traits::kPublicKeyBytes]; + Traits::GenerateKey(unused_public, priv->seed, &priv->priv); + evp_pkey_set0(pkey, &asn1_method, priv.release()); + return 1; + } + + static int KemEncap(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); + return 0; + } + if (out_secret.size() != MLKEM_SHARED_SECRET_BYTES) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH); + return 0; + } + Traits::Encap(out_ciphertext.data(), out_secret.data(), peer_pubkey); + return 1; + } + + static int KemEncapExternalEntropy(Span out_ciphertext, + Span out_secret, + const EVP_PKEY *peer_key, + Span entropy) { + const auto *peer_pubkey = GetKeyData(FromOpaque(peer_key))->GetPublicKey(); + if (out_ciphertext.size() != Traits::kCiphertextBytes) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_CIPHERTEXT_LENGTH); + return 0; + } + if (out_secret.size() != MLKEM_SHARED_SECRET_BYTES) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH); + return 0; + } + if (entropy.size() != BCM_MLKEM_ENCAP_ENTROPY) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_ENTROPY_LENGTH); + return 0; + } + Traits::EncapExternalEntropy(out_ciphertext.data(), out_secret.data(), + peer_pubkey, entropy.data()); + return 1; + } + + static int KemDecap(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); + return 0; + } + if (out_secret.size() != MLKEM_SHARED_SECRET_BYTES) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH); + return 0; + } + return Traits::Decap(out_secret.data(), ciphertext.data(), + ciphertext.size(), &priv->priv); + } + + static constexpr EVP_KEM evp_kem = { + /*pkey_id=*/Traits::kType, + /*ciphertext_len=*/Traits::kCiphertextBytes, + /*secret_len=*/MLKEM_SHARED_SECRET_BYTES, + /*entropy_len=*/BCM_MLKEM_ENCAP_ENTROPY, + &KemEncap, + &KemEncapExternalEntropy, + &KemDecap, + }; + + static constexpr EVP_PKEY_CTX_METHOD pkey_method = { + Traits::kType, + /*init=*/nullptr, + &CopyCtx, + /*cleanup=*/nullptr, + &KeyGen, + /*sign=*/nullptr, + /*sign_message=*/nullptr, + /*verify=*/nullptr, + /*verify_message=*/nullptr, + /*verify_recover=*/nullptr, + /*encrypt=*/nullptr, + /*decrypt=*/nullptr, + /*derive=*/nullptr, + /*paramgen=*/nullptr, + &KemAdapter::EncapMethod, + &KemAdapter::DecapMethod, + /*ctrl=*/nullptr, + }; + + 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, + + /*set_priv_raw=*/nullptr, + &SetPrivateSeed, + &SetRawPublic, + /*get_priv_raw=*/nullptr, + &GetPrivateSeed, + &GetRawPublic, + + /*set1_tls_encodedpoint=*/nullptr, + /*get1_tls_encodedpoint=*/nullptr, + /*pkey_opaque=*/nullptr, + &PkeySize, + &PkeyBits, + + /*param_missing=*/nullptr, + /*param_copy=*/nullptr, + /*param_equal=*/nullptr, + + &PkeyFree, + }; + // TODO(crbug.com/404286922): Use std::copy in C++20, when it's constexpr. + // TODO(crbug.com/450823446): Better yet, make this field an InplaceVector + // and give it a suitable constructor. + 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_ml_kem_768() { + return &MLKEMImplementation::pkey_alg; +} + +const EVP_PKEY_ALG *EVP_pkey_ml_kem_1024() { + return &MLKEMImplementation::pkey_alg; +} + +const EVP_KEM *EVP_kem_ml_kem_768() { + return &MLKEMImplementation::evp_kem; +} + +const EVP_KEM *EVP_kem_ml_kem_1024() { + return &MLKEMImplementation::evp_kem; +} diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_rsa.cc b/Sources/CNIOBoringSSL/crypto/evp/p_rsa.cc index 4c46cba2..5d887aa1 100644 --- a/Sources/CNIOBoringSSL/crypto/evp/p_rsa.cc +++ b/Sources/CNIOBoringSSL/crypto/evp/p_rsa.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -19,63 +24,454 @@ #include #include #include +#include +#include "../fipsmodule/rsa/internal.h" #include "../internal.h" +#include "../mem_internal.h" #include "../rsa/internal.h" #include "internal.h" -typedef struct { - // Key gen parameters - int nbits; - BIGNUM *pub_exp; - // RSA padding mode - int pad_mode; - // message digest - const EVP_MD *md; - // message digest for MGF1 - const EVP_MD *mgf1md; - // PSS salt length - int saltlen; - // tbuf is a buffer which is either NULL, or is the size of the RSA modulus. - // It's used to store the output of RSA operations. - uint8_t *tbuf; - // OAEP label - uint8_t *oaep_label; - size_t oaep_labellen; -} RSA_PKEY_CTX; +using namespace bssl; -typedef struct { - uint8_t *data; - size_t len; -} RSA_OAEP_LABEL_PARAMS; +namespace { -static int pkey_rsa_init(EVP_PKEY_CTX *ctx) { - RSA_PKEY_CTX *rctx = - reinterpret_cast(OPENSSL_zalloc(sizeof(RSA_PKEY_CTX))); - if (!rctx) { +struct EVP_PKEY_ALG_RSA_PSS : public EVP_PKEY_ALG { + rsa_pss_params_t pss_params; +}; + +extern const EVP_PKEY_ASN1_METHOD rsa_asn1_meth; +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) { + // See RFC 3279, section 2.3.1. + const RSA *rsa = reinterpret_cast(key->pkey); + CBB spki, algorithm, null, 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, rsa_asn1_meth.oid, + rsa_asn1_meth.oid_len) || + !CBB_add_asn1(&algorithm, &null, CBS_ASN1_NULL) || + !CBB_add_asn1(&spki, &key_bitstring, CBS_ASN1_BITSTRING) || + !CBB_add_u8(&key_bitstring, 0 /* padding */) || + !RSA_marshal_public_key(&key_bitstring, rsa) || // + !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); return 0; } - rctx->nbits = 2048; - rctx->pad_mode = RSA_PKCS1_PADDING; - rctx->saltlen = -2; - - ctx->data = rctx; - return 1; } -static int pkey_rsa_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { +static 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. + CBS null; + if (!CBS_get_asn1(params, &null, CBS_ASN1_NULL) || CBS_len(&null) != 0 || + CBS_len(params) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + UniquePtr rsa(RSA_public_key_from_bytes(CBS_data(key), CBS_len(key))); + if (rsa == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + EVP_PKEY_assign_RSA(out, rsa.release()); + return evp_decode_ok; +} + +static 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, + // however, that OpenSSL does not compare parameters here. + const RSA *a_rsa = reinterpret_cast(a->pkey); + const RSA *b_rsa = reinterpret_cast(b->pkey); + return BN_cmp(RSA_get0_n(b_rsa), RSA_get0_n(a_rsa)) == 0 && + BN_cmp(RSA_get0_e(b_rsa), RSA_get0_e(a_rsa)) == 0; +} + +static 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 + // presence of e. + return RSA_get0_n(pk_rsa) != nullptr && RSA_get0_e(pk_rsa) != nullptr; +} + +static 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); + if (pk_n == nullptr || pk_e == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PUBLIC_KEY); + return false; + } + UniquePtr public_copy_rsa(RSA_new_public_key(pk_n, pk_e)); + if (!public_copy_rsa) { + OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR); + return false; + } + FromOpaque(public_copy_rsa.get())->pss_params = pk_rsa->pss_params; + evp_pkey_set0(out, pkey->ameth, public_copy_rsa.release()); + return true; +} + +static 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) || + !CBB_add_asn1_uint64(&pkcs8, 0 /* version */) || + !CBB_add_asn1(&pkcs8, &algorithm, CBS_ASN1_SEQUENCE) || + !CBB_add_asn1_element(&algorithm, CBS_ASN1_OBJECT, rsa_asn1_meth.oid, + rsa_asn1_meth.oid_len) || + !CBB_add_asn1(&algorithm, &null, CBS_ASN1_NULL) || + !CBB_add_asn1(&pkcs8, &private_key, CBS_ASN1_OCTETSTRING) || + !RSA_marshal_private_key(&private_key, rsa) || // + !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); + return 0; + } + + return 1; +} + +static 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 || + CBS_len(params) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + UniquePtr rsa(RSA_private_key_from_bytes(CBS_data(key), CBS_len(key))); + if (rsa == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + EVP_PKEY_assign_RSA(out, rsa.release()); + return evp_decode_ok; +} + +static 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( + rsa_pss_params_t expected, CBS *params) { + if (CBS_len(params) == 0) { + return evp_decode_unsupported; + } + rsa_pss_params_t pss_params; + if (!rsa_parse_pss_params(params, &pss_params, + /*allow_explicit_trailer=*/false) || + CBS_len(params) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + return pss_params == expected ? evp_decode_ok : evp_decode_unsupported; +} + +static 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) || + !CBB_add_asn1(&spki, &algorithm, CBS_ASN1_SEQUENCE) || + !CBB_add_asn1_element(&algorithm, CBS_ASN1_OBJECT, rsa_pss_asn1_meth.oid, + rsa_pss_asn1_meth.oid_len) || + !rsa_marshal_pss_params(&algorithm, rsa->pss_params) || + !CBB_add_asn1(&spki, &key_bitstring, CBS_ASN1_BITSTRING) || + !CBB_add_u8(&key_bitstring, 0 /* padding */) || + !RSA_marshal_public_key(&key_bitstring, rsa) || // + !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); + return 0; + } + + return 1; +} + +static 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) { + 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) { + return ret; + } + + UniquePtr rsa(RSA_public_key_from_bytes(CBS_data(key), CBS_len(key))); + if (rsa == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + evp_pkey_set0_pss(out, alg, std::move(rsa)); + return evp_decode_ok; +} + +static 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) || + !CBB_add_asn1_uint64(&pkcs8, 0 /* version */) || + !CBB_add_asn1(&pkcs8, &algorithm, CBS_ASN1_SEQUENCE) || + !CBB_add_asn1_element(&algorithm, CBS_ASN1_OBJECT, rsa_pss_asn1_meth.oid, + rsa_pss_asn1_meth.oid_len) || + !rsa_marshal_pss_params(&algorithm, rsa->pss_params) || + !CBB_add_asn1(&pkcs8, &private_key, CBS_ASN1_OCTETSTRING) || + !RSA_marshal_private_key(&private_key, rsa) || // + !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); + return 0; + } + + return 1; +} + +static 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) { + return ret; + } + + UniquePtr rsa(RSA_private_key_from_bytes(CBS_data(key), CBS_len(key))); + if (rsa == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + evp_pkey_set0_pss(out, alg, std::move(rsa)); + return evp_decode_ok; +} + +static 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) { + const RSA *rsa = reinterpret_cast(pkey->pkey); + return RSA_size(rsa); +} + +static int rsa_bits(const EvpPkey *pkey) { + const RSA *rsa = reinterpret_cast(pkey->pkey); + return RSA_bits(rsa); +} + +static void int_rsa_free(EvpPkey *pkey) { + RSA_free(reinterpret_cast(pkey->pkey)); + pkey->pkey = nullptr; +} + +static 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) { + const RSA *from_key = reinterpret_cast(from->pkey); + if (from_key == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); + return 0; + } + rsa_pss_params_t pss_params = FromOpaque(from_key)->pss_params; + if (pss_params == rsa_pss_none) { + OPENSSL_PUT_ERROR(EVP, EVP_R_MISSING_PARAMETERS); + return 0; + } + if (to->pkey == nullptr) { + to->pkey = RSA_new(); + if (to->pkey == nullptr) { + return 0; + } + } + FromOpaque(reinterpret_cast(to->pkey))->pss_params = pss_params; + return 1; +} + +static 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) { + return false; + } + rsa_pss_params_t a_pss_params = FromOpaque(a_rsa)->pss_params; + rsa_pss_params_t b_pss_params = FromOpaque(b_rsa)->pss_params; + if (a_pss_params == rsa_pss_none || b_pss_params == rsa_pss_none) { + return false; + } + return a_pss_params == b_pss_params; +} + +const EVP_PKEY_ASN1_METHOD rsa_asn1_meth = { + EVP_PKEY_RSA, + // 1.2.840.113549.1.1.1 + {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01}, + 9, + + &rsa_pkey_meth, + + rsa_pub_decode, + rsa_pub_encode, + rsa_pub_equal, + rsa_pub_present, + rsa_pub_copy, + + rsa_priv_decode, + rsa_priv_encode, + rsa_priv_present, + + /*set_priv_raw=*/nullptr, + /*set_priv_seed=*/nullptr, + /*set_pub_raw=*/nullptr, + /*get_priv_raw=*/nullptr, + /*get_priv_seed=*/nullptr, + /*get_pub_raw=*/nullptr, + /*set1_tls_encodedpoint=*/nullptr, + /*get1_tls_encodedpoint=*/nullptr, + + rsa_opaque, + + int_rsa_size, + rsa_bits, + + /*param_missing=*/nullptr, + /*param_copy=*/nullptr, + /*param_equal=*/nullptr, + + int_rsa_free, +}; + +const EVP_PKEY_ASN1_METHOD rsa_pss_asn1_meth = { + EVP_PKEY_RSA_PSS, + // 1.2.840.113549.1.1.10 + {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0a}, + 9, + + &rsa_pss_pkey_meth, + + rsa_pub_decode_pss, + rsa_pub_encode_pss, + rsa_pub_equal, + rsa_pub_present, + rsa_pub_copy, + + rsa_priv_decode_pss, + rsa_priv_encode_pss, + rsa_priv_present, + + /*set_priv_raw=*/nullptr, + /*set_priv_seed=*/nullptr, + /*set_pub_raw=*/nullptr, + /*get_priv_raw=*/nullptr, + /*get_priv_seed=*/nullptr, + /*get_pub_raw=*/nullptr, + /*set1_tls_encodedpoint=*/nullptr, + /*get1_tls_encodedpoint=*/nullptr, + + rsa_opaque, + + int_rsa_size, + rsa_bits, + + rsa_pss_params_missing, + rsa_pss_params_copy, + rsa_pss_params_equal, + + int_rsa_free, +}; + + +struct RSA_PKEY_CTX { + // Key gen parameters + int nbits = 2048; + UniquePtr pub_exp; + // RSA padding mode + int pad_mode = RSA_PKCS1_PADDING; + // message digest + const EVP_MD *md = nullptr; + // message digest for MGF1 + const EVP_MD *mgf1md = nullptr; + // PSS salt length + int saltlen = RSA_PSS_SALTLEN_DIGEST; + // restrict_pss_params, if true, indicates that the PSS signing/verifying + // parameters are restricted by the key's parameters. `md` and `mgf1md` may + // not change, and `saltlen` must be at least `md`'s hash length. + bool restrict_pss_params = false; + Array oaep_label; +}; + +static 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) { + RSA_PKEY_CTX *rctx = New(); + if (!rctx) { + return 0; + } + + if (is_pss_only(ctx)) { + rctx->pad_mode = RSA_PKCS1_PSS_PADDING; + // Pick up PSS parameters from the key or algorithm. We don't currently + // support keygen from PSS, so the algorithm does not currently do anything. + rsa_pss_params_t pss_params = rsa_pss_none; + const auto *alg_pss = static_cast(alg); + if (alg_pss != nullptr) { + pss_params = alg_pss->pss_params; + } else if (ctx->pkey != nullptr && ctx->pkey->pkey != nullptr) { + pss_params = static_cast(ctx->pkey->pkey)->pss_params; + } + const EVP_MD *md = rsa_pss_params_get_md(pss_params); + if (md != nullptr) { + rctx->md = rctx->mgf1md = md; + // All our supported modes use the digest length as the salt length. + rctx->saltlen = EVP_MD_size(rctx->md); + rctx->restrict_pss_params = true; + } + } + + ctx->data = rctx; + return 1; +} + +static int pkey_rsa_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { RSA_PKEY_CTX *dctx, *sctx; - if (!pkey_rsa_init(dst)) { + if (!pkey_rsa_init(dst, nullptr)) { return 0; } sctx = reinterpret_cast(src->data); dctx = reinterpret_cast(dst->data); dctx->nbits = sctx->nbits; if (sctx->pub_exp) { - dctx->pub_exp = BN_dup(sctx->pub_exp); + dctx->pub_exp.reset(BN_dup(sctx->pub_exp.get())); if (!dctx->pub_exp) { return 0; } @@ -85,49 +481,23 @@ static int pkey_rsa_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { dctx->md = sctx->md; dctx->mgf1md = sctx->mgf1md; dctx->saltlen = sctx->saltlen; - if (sctx->oaep_label) { - OPENSSL_free(dctx->oaep_label); - dctx->oaep_label = reinterpret_cast( - OPENSSL_memdup(sctx->oaep_label, sctx->oaep_labellen)); - if (!dctx->oaep_label) { - return 0; - } - dctx->oaep_labellen = sctx->oaep_labellen; - } - - return 1; -} - -static void pkey_rsa_cleanup(EVP_PKEY_CTX *ctx) { - RSA_PKEY_CTX *rctx = reinterpret_cast(ctx->data); - - if (rctx == NULL) { - return; - } - - BN_free(rctx->pub_exp); - OPENSSL_free(rctx->tbuf); - OPENSSL_free(rctx->oaep_label); - OPENSSL_free(rctx); -} - -static int setup_tbuf(RSA_PKEY_CTX *ctx, EVP_PKEY_CTX *pk) { - if (ctx->tbuf) { - return 1; - } - ctx->tbuf = - reinterpret_cast(OPENSSL_malloc(EVP_PKEY_size(pk->pkey))); - if (!ctx->tbuf) { + dctx->restrict_pss_params = sctx->restrict_pss_params; + if (!dctx->oaep_label.CopyFrom(sctx->oaep_label)) { return 0; } + return 1; } -static int pkey_rsa_sign(EVP_PKEY_CTX *ctx, uint8_t *sig, size_t *siglen, +static 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) { 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); + const size_t key_len = EVP_PKEY_size(ctx->pkey.get()); if (!sig) { *siglen = key_len; @@ -161,7 +531,7 @@ static int pkey_rsa_sign(EVP_PKEY_CTX *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(EVP_PKEY_CTX *ctx, const uint8_t *sig, size_t siglen, +static 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); @@ -181,13 +551,14 @@ static int pkey_rsa_verify(EVP_PKEY_CTX *ctx, const uint8_t *sig, size_t siglen, } size_t rslen; - const size_t key_len = EVP_PKEY_size(ctx->pkey); - if (!setup_tbuf(rctx, ctx) || - !RSA_verify_raw(rsa, &rslen, rctx->tbuf, key_len, sig, siglen, + const size_t key_len = EVP_PKEY_size(ctx->pkey.get()); + Array tbuf; + if (!tbuf.InitForOverwrite(key_len) || + !RSA_verify_raw(rsa, &rslen, tbuf.data(), tbuf.size(), sig, siglen, rctx->pad_mode)) { return 0; } - if (rslen != tbslen || CRYPTO_memcmp(tbs, rctx->tbuf, rslen) != 0) { + if (rslen != tbslen || CRYPTO_memcmp(tbs, tbuf.data(), rslen) != 0) { OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_SIGNATURE); return 0; } @@ -195,14 +566,14 @@ static int pkey_rsa_verify(EVP_PKEY_CTX *ctx, const uint8_t *sig, size_t siglen, return 1; } -static int pkey_rsa_verify_recover(EVP_PKEY_CTX *ctx, uint8_t *out, +static 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); + const size_t key_len = EVP_PKEY_size(ctx->pkey.get()); - if (out == NULL) { + if (out == nullptr) { *out_len = key_len; return 1; } @@ -212,7 +583,7 @@ static int pkey_rsa_verify_recover(EVP_PKEY_CTX *ctx, uint8_t *out, return 0; } - if (rctx->md == NULL) { + if (rctx->md == nullptr) { return RSA_verify_raw(rsa, out_len, out, *out_len, sig, sig_len, rctx->pad_mode); } @@ -227,44 +598,39 @@ static int pkey_rsa_verify_recover(EVP_PKEY_CTX *ctx, uint8_t *out, uint8_t *asn1_prefix; size_t asn1_prefix_len; int asn1_prefix_allocated; - if (!setup_tbuf(rctx, ctx) || - !RSA_add_pkcs1_prefix(&asn1_prefix, &asn1_prefix_len, + if (!RSA_add_pkcs1_prefix(&asn1_prefix, &asn1_prefix_len, &asn1_prefix_allocated, EVP_MD_type(rctx->md), kDummyHash, hash_len)) { return 0; } + UniquePtr free_asn1_prefix(asn1_prefix_allocated ? asn1_prefix + : nullptr); + Array tbuf; size_t rslen; - int ok = 1; - if (!RSA_verify_raw(rsa, &rslen, rctx->tbuf, key_len, sig, sig_len, + if (!tbuf.InitForOverwrite(key_len) || + !RSA_verify_raw(rsa, &rslen, tbuf.data(), tbuf.size(), sig, sig_len, RSA_PKCS1_PADDING) || rslen != asn1_prefix_len || // Compare all but the hash suffix. - CRYPTO_memcmp(rctx->tbuf, asn1_prefix, asn1_prefix_len - hash_len) != 0) { - ok = 0; - } - - if (asn1_prefix_allocated) { - OPENSSL_free(asn1_prefix); - } - - if (!ok) { + CRYPTO_memcmp(tbuf.data(), asn1_prefix, asn1_prefix_len - hash_len) != + 0) { return 0; } - if (out != NULL) { - OPENSSL_memcpy(out, rctx->tbuf + rslen - hash_len, hash_len); + if (out != nullptr) { + OPENSSL_memcpy(out, tbuf.data() + rslen - hash_len, hash_len); } *out_len = hash_len; return 1; } -static int pkey_rsa_encrypt(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *outlen, +static 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); + const size_t key_len = EVP_PKEY_size(ctx->pkey.get()); if (!out) { *outlen = key_len; @@ -277,11 +643,12 @@ static int pkey_rsa_encrypt(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *outlen, } if (rctx->pad_mode == RSA_PKCS1_OAEP_PADDING) { - if (!setup_tbuf(rctx, ctx) || - !RSA_padding_add_PKCS1_OAEP_mgf1(rctx->tbuf, key_len, in, inlen, - rctx->oaep_label, rctx->oaep_labellen, - rctx->md, rctx->mgf1md) || - !RSA_encrypt(rsa, outlen, out, *outlen, rctx->tbuf, key_len, + Array tbuf; + if (!tbuf.InitForOverwrite(key_len) || + !RSA_padding_add_PKCS1_OAEP_mgf1( + tbuf.data(), tbuf.size(), in, inlen, rctx->oaep_label.data(), + rctx->oaep_label.size(), rctx->md, rctx->mgf1md) || + !RSA_encrypt(rsa, outlen, out, *outlen, tbuf.data(), tbuf.size(), RSA_NO_PADDING)) { return 0; } @@ -291,11 +658,11 @@ static int pkey_rsa_encrypt(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *outlen, return RSA_encrypt(rsa, outlen, out, *outlen, in, inlen, rctx->pad_mode); } -static int pkey_rsa_decrypt(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *outlen, +static 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); + const size_t key_len = EVP_PKEY_size(ctx->pkey.get()); if (!out) { *outlen = key_len; @@ -308,13 +675,15 @@ static int pkey_rsa_decrypt(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *outlen, } if (rctx->pad_mode == RSA_PKCS1_OAEP_PADDING) { + Array tbuf; size_t padded_len; - if (!setup_tbuf(rctx, ctx) || - !RSA_decrypt(rsa, &padded_len, rctx->tbuf, key_len, in, inlen, + if (!tbuf.InitForOverwrite(key_len) || + !RSA_decrypt(rsa, &padded_len, tbuf.data(), tbuf.size(), in, inlen, RSA_NO_PADDING) || - !RSA_padding_check_PKCS1_OAEP_mgf1( - out, outlen, key_len, rctx->tbuf, padded_len, rctx->oaep_label, - rctx->oaep_labellen, rctx->md, rctx->mgf1md)) { + !RSA_padding_check_PKCS1_OAEP_mgf1(out, outlen, key_len, tbuf.data(), + padded_len, rctx->oaep_label.data(), + rctx->oaep_label.size(), rctx->md, + rctx->mgf1md)) { return 0; } return 1; @@ -348,10 +717,15 @@ static int is_known_padding(int padding_mode) { } } -static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { +static 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: + // PSS keys cannot be switched to other padding types. + if (is_pss_only(ctx) && p1 != RSA_PKCS1_PSS_PADDING) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE); + return 0; + } if (!is_known_padding(p1) || !check_padding_md(rctx->md, p1) || (p1 == RSA_PKCS1_PSS_PADDING && 0 == (ctx->operation & (EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY))) || @@ -360,8 +734,7 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { OPENSSL_PUT_ERROR(EVP, EVP_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE); return 0; } - if ((p1 == RSA_PKCS1_PSS_PADDING || p1 == RSA_PKCS1_OAEP_PADDING) && - rctx->md == NULL) { + if (p1 == RSA_PKCS1_OAEP_PADDING && rctx->md == nullptr) { rctx->md = EVP_sha1(); } rctx->pad_mode = p1; @@ -380,7 +753,21 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { if (type == EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN) { *(int *)p2 = rctx->saltlen; } else { - if (p1 < -2) { + // Negative salt lengths are special values. + if (p1 < 0) { + if (p1 != RSA_PSS_SALTLEN_DIGEST && p1 != RSA_PSS_SALTLEN_AUTO) { + return 0; + } + // All our PSS restrictions accept saltlen == hashlen, so allow + // `RSA_PSS_SALTLEN_DIGEST`. Reject `RSA_PSS_SALTLEN_AUTO` for + // simplicity. + if (rctx->restrict_pss_params && p1 != RSA_PSS_SALTLEN_DIGEST) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PSS_SALTLEN); + return 0; + } + } else if (rctx->restrict_pss_params && + static_cast(p1) < EVP_MD_size(rctx->md)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PSS_SALTLEN); return 0; } rctx->saltlen = p1; @@ -399,8 +786,7 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { if (!p2) { return 0; } - BN_free(rctx->pub_exp); - rctx->pub_exp = reinterpret_cast(p2); + rctx->pub_exp.reset(reinterpret_cast(p2)); return 1; case EVP_PKEY_CTRL_RSA_OAEP_MD: @@ -416,12 +802,19 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { } return 1; - case EVP_PKEY_CTRL_MD: - if (!check_padding_md(reinterpret_cast(p2), rctx->pad_mode)) { + case EVP_PKEY_CTRL_MD: { + const EVP_MD *md = reinterpret_cast(p2); + if (!check_padding_md(md, rctx->pad_mode)) { return 0; } - rctx->md = reinterpret_cast(p2); + if (rctx->restrict_pss_params && + EVP_MD_type(rctx->md) != EVP_MD_type(md)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_DIGEST_TYPE); + return 0; + } + rctx->md = md; return 1; + } case EVP_PKEY_CTRL_GET_MD: *(const EVP_MD **)p2 = rctx->md; @@ -441,7 +834,13 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { *(const EVP_MD **)p2 = rctx->md; } } else { - rctx->mgf1md = reinterpret_cast(p2); + const EVP_MD *md = reinterpret_cast(p2); + if (rctx->restrict_pss_params && + EVP_MD_type(rctx->mgf1md) != EVP_MD_type(md)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_MGF1_MD); + return 0; + } + rctx->mgf1md = md; } return 1; @@ -450,11 +849,10 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PADDING_MODE); return 0; } - OPENSSL_free(rctx->oaep_label); - RSA_OAEP_LABEL_PARAMS *params = - reinterpret_cast(p2); - rctx->oaep_label = params->data; - rctx->oaep_labellen = params->len; + // `EVP_PKEY_CTRL_RSA_OAEP_LABEL` takes ownership of `label`'s underlying + // buffer (via `Reset`), but only on success. + auto *label = reinterpret_cast *>(p2); + rctx->oaep_label.Reset(label->data(), label->size()); return 1; } @@ -463,7 +861,7 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PADDING_MODE); return 0; } - CBS_init((CBS *)p2, rctx->oaep_label, rctx->oaep_labellen); + *reinterpret_cast(p2) = CBS(rctx->oaep_label); return 1; default: @@ -472,126 +870,309 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { } } -static int pkey_rsa_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { - RSA *rsa = NULL; +static int pkey_rsa_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { RSA_PKEY_CTX *rctx = reinterpret_cast(ctx->data); - if (!rctx->pub_exp) { - rctx->pub_exp = BN_new(); - if (!rctx->pub_exp || !BN_set_word(rctx->pub_exp, RSA_F4)) { + rctx->pub_exp.reset(BN_new()); + if (!rctx->pub_exp || !BN_set_word(rctx->pub_exp.get(), RSA_F4)) { return 0; } } - rsa = RSA_new(); + UniquePtr rsa(RSA_new()); if (!rsa) { return 0; } - if (!RSA_generate_key_ex(rsa, rctx->nbits, rctx->pub_exp, NULL)) { - RSA_free(rsa); + if (!RSA_generate_key_ex(rsa.get(), rctx->nbits, rctx->pub_exp.get(), + nullptr)) { return 0; } - EVP_PKEY_assign_RSA(pkey, rsa); + EVP_PKEY_assign_RSA(pkey, rsa.release()); return 1; } -const EVP_PKEY_METHOD rsa_pkey_meth = { +const EVP_PKEY_CTX_METHOD rsa_pkey_meth = { EVP_PKEY_RSA, pkey_rsa_init, pkey_rsa_copy, pkey_rsa_cleanup, pkey_rsa_keygen, pkey_rsa_sign, - NULL /* sign_message */, + /*sign_message=*/nullptr, pkey_rsa_verify, - NULL /* verify_message */, + /*verify_message=*/nullptr, pkey_rsa_verify_recover, pkey_rsa_encrypt, pkey_rsa_decrypt, - NULL /* derive */, - NULL /* paramgen */, + /*derive=*/nullptr, + /*paramgen=*/nullptr, + /*encap=*/nullptr, + /*decap=*/nullptr, pkey_rsa_ctrl, }; +const EVP_PKEY_CTX_METHOD rsa_pss_pkey_meth = { + EVP_PKEY_RSA_PSS, + pkey_rsa_init, + pkey_rsa_copy, + pkey_rsa_cleanup, + // In OpenSSL, `EVP_PKEY_RSA_PSS` supports key generation and fills in PSS + // parameters based on a separate set of keygen-targetted setters: + // `EVP_PKEY_CTX_set_rsa_pss_keygen_saltlen`, + // `EVP_PKEY_CTX_set_rsa_pss_keygen_mgf1_md`, and + // `EVP_PKEY_CTX_rsa_pss_key_digest`. We do not currently implement this + // because we only support one parameter set. + /*keygen=*/nullptr, + pkey_rsa_sign, + /*sign_message=*/nullptr, + pkey_rsa_verify, + /*verify_message=*/nullptr, + /*verify_recover=*/nullptr, + /*encrypt=*/nullptr, + /*decrypt=*/nullptr, + /*derive=*/nullptr, + /*paramgen=*/nullptr, + /*encap=*/nullptr, + /*decap=*/nullptr, + pkey_rsa_ctrl, +}; + +} // namespace + +const EVP_PKEY_ALG *EVP_pkey_rsa() { + static const EVP_PKEY_ALG kAlg = {&rsa_asn1_meth, &rsa_pkey_meth}; + return &kAlg; +} + +const EVP_PKEY_ALG *EVP_pkey_rsa_pss_sha256() { + static const EVP_PKEY_ALG_RSA_PSS kAlg = { + {&rsa_pss_asn1_meth, &rsa_pss_pkey_meth}, rsa_pss_sha256}; + return &kAlg; +} + +const EVP_PKEY_ALG *EVP_pkey_rsa_pss_sha384() { + static const EVP_PKEY_ALG_RSA_PSS kAlg = { + {&rsa_pss_asn1_meth, &rsa_pss_pkey_meth}, rsa_pss_sha384}; + return &kAlg; +} + +const EVP_PKEY_ALG *EVP_pkey_rsa_pss_sha512() { + static const EVP_PKEY_ALG_RSA_PSS kAlg = { + {&rsa_pss_asn1_meth, &rsa_pss_pkey_meth}, rsa_pss_sha512}; + return &kAlg; +} + +EVP_PKEY *EVP_RSA_gen(unsigned bits) { + // TODO(crbug.com/487376811): After EVP_PKEY_CTX is switched to C++ + // subclassing, it should be possible to stack-allocate enough the + // RSA-specific subclass. + UniquePtr ctx = evp_pkey_ctx_new_alg(EVP_pkey_rsa()); + EVP_PKEY *pkey = nullptr; + if (ctx == nullptr || // + !EVP_PKEY_keygen_init(ctx.get()) || + !EVP_PKEY_CTX_set_rsa_keygen_bits(ctx.get(), bits) || + !EVP_PKEY_keygen(ctx.get(), &pkey)) { + return nullptr; + } + return pkey; +} + +EVP_PKEY *EVP_PKEY_from_rsa_public_key(const EVP_PKEY_ALG *alg, + const uint8_t *in, size_t len) { + if (alg->pkey_method->pkey_id != EVP_PKEY_RSA && + alg->pkey_method->pkey_id != EVP_PKEY_RSA_PSS) { + OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); + return nullptr; + } + UniquePtr rsa(RSA_public_key_from_bytes(in, len)); + if (rsa == nullptr) { + return nullptr; + } + UniquePtr ret(EVP_PKEY_new()); + if (ret == nullptr) { + return nullptr; + } + // Use the PSS-specific setter if needed, to fill in `rsa->pss_params`. + if (alg->pkey_method->pkey_id == EVP_PKEY_RSA) { + evp_pkey_set0(FromOpaque(ret.get()), alg->method, rsa.release()); + } else { + evp_pkey_set0_pss(FromOpaque(ret.get()), alg, std::move(rsa)); + } + return ret.release(); +} + +EVP_PKEY *EVP_PKEY_from_rsa_private_key(const EVP_PKEY_ALG *alg, + const uint8_t *in, size_t len) { + if (alg->pkey_method->pkey_id != EVP_PKEY_RSA && + alg->pkey_method->pkey_id != EVP_PKEY_RSA_PSS) { + OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM); + return nullptr; + } + UniquePtr rsa(RSA_private_key_from_bytes(in, len)); + if (rsa == nullptr) { + return nullptr; + } + UniquePtr ret(EVP_PKEY_new()); + if (ret == nullptr) { + return nullptr; + } + // Use the PSS-specific setter if needed, to fill in `rsa->pss_params`. + if (alg->pkey_method->pkey_id == EVP_PKEY_RSA) { + evp_pkey_set0(FromOpaque(ret.get()), alg->method, rsa.release()); + } else { + evp_pkey_set0_pss(FromOpaque(ret.get()), alg, std::move(rsa)); + } + return ret.release(); +} + +int EVP_PKEY_marshal_rsa_public_key(CBB *cbb, const EVP_PKEY *key) { + const RSA *rsa = EVP_PKEY_get0_RSA(key); + if (rsa == nullptr) { + return 0; + } + return RSA_marshal_public_key(cbb, rsa); +} + +int EVP_PKEY_marshal_rsa_private_key(CBB *cbb, const EVP_PKEY *key) { + const RSA *rsa = EVP_PKEY_get0_RSA(key); + if (rsa == nullptr) { + return 0; + } + 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_assign_RSA(EVP_PKEY *pkey, RSA *key) { + if (key == nullptr) { + return 0; + } + evp_pkey_set0(FromOpaque(pkey), &rsa_asn1_meth, key); + return 1; +} + +RSA *EVP_PKEY_get0_RSA(const EVP_PKEY *pkey) { + int pkey_id = EVP_PKEY_id(pkey); + if (pkey_id != EVP_PKEY_RSA && pkey_id != EVP_PKEY_RSA_PSS) { + OPENSSL_PUT_ERROR(EVP, EVP_R_EXPECTING_AN_RSA_KEY); + return nullptr; + } + return reinterpret_cast(FromOpaque(pkey)->pkey); +} + +RSA *EVP_PKEY_get1_RSA(const EVP_PKEY *pkey) { + RSA *rsa = EVP_PKEY_get0_RSA(pkey); + if (rsa != nullptr) { + RSA_up_ref(rsa); + } + return rsa; +} + +static int rsa_or_rsa_pss_ctrl(EvpPkeyCtx *ctx, int optype, int cmd, int p1, + void *p2) { + if (!ctx || !ctx->pmeth || !ctx->pmeth->ctrl) { + OPENSSL_PUT_ERROR(EVP, EVP_R_COMMAND_NOT_SUPPORTED); + return 0; + } + if (ctx->pmeth->pkey_id != EVP_PKEY_RSA && + ctx->pmeth->pkey_id != EVP_PKEY_RSA_PSS) { + OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + return 0; + } + return EVP_PKEY_CTX_ctrl(ctx, /*keytype=*/-1, optype, cmd, p1, p2); +} + int EVP_PKEY_CTX_set_rsa_padding(EVP_PKEY_CTX *ctx, int padding) { - return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, -1, EVP_PKEY_CTRL_RSA_PADDING, - padding, NULL); + return rsa_or_rsa_pss_ctrl(FromOpaque(ctx), -1, EVP_PKEY_CTRL_RSA_PADDING, + padding, nullptr); } int EVP_PKEY_CTX_get_rsa_padding(EVP_PKEY_CTX *ctx, int *out_padding) { - return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, -1, EVP_PKEY_CTRL_GET_RSA_PADDING, - 0, out_padding); + return rsa_or_rsa_pss_ctrl(FromOpaque(ctx), -1, EVP_PKEY_CTRL_GET_RSA_PADDING, + 0, out_padding); } int EVP_PKEY_CTX_set_rsa_pss_keygen_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { + // We currently do not support keygen with `EVP_PKEY_RSA_PSS`. return 0; } int EVP_PKEY_CTX_set_rsa_pss_keygen_saltlen(EVP_PKEY_CTX *ctx, int salt_len) { + // We currently do not support keygen with `EVP_PKEY_RSA_PSS`. return 0; } int EVP_PKEY_CTX_set_rsa_pss_keygen_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { + // We currently do not support keygen with `EVP_PKEY_RSA_PSS`. return 0; } int EVP_PKEY_CTX_set_rsa_pss_saltlen(EVP_PKEY_CTX *ctx, int salt_len) { - return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, - (EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY), - EVP_PKEY_CTRL_RSA_PSS_SALTLEN, salt_len, NULL); + return rsa_or_rsa_pss_ctrl(FromOpaque(ctx), + (EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY), + EVP_PKEY_CTRL_RSA_PSS_SALTLEN, salt_len, nullptr); } int EVP_PKEY_CTX_get_rsa_pss_saltlen(EVP_PKEY_CTX *ctx, int *out_salt_len) { - return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, - (EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY), - EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN, 0, out_salt_len); + return rsa_or_rsa_pss_ctrl( + FromOpaque(ctx), (EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY), + EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN, 0, out_salt_len); } int EVP_PKEY_CTX_set_rsa_keygen_bits(EVP_PKEY_CTX *ctx, int bits) { - return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_KEYGEN, - EVP_PKEY_CTRL_RSA_KEYGEN_BITS, bits, NULL); + return rsa_or_rsa_pss_ctrl(FromOpaque(ctx), EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_RSA_KEYGEN_BITS, bits, nullptr); } int EVP_PKEY_CTX_set_rsa_keygen_pubexp(EVP_PKEY_CTX *ctx, BIGNUM *e) { - return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_KEYGEN, - EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP, 0, e); + return rsa_or_rsa_pss_ctrl(FromOpaque(ctx), EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP, 0, e); } int EVP_PKEY_CTX_set_rsa_oaep_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { - return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, - EVP_PKEY_CTRL_RSA_OAEP_MD, 0, (void *)md); + return EVP_PKEY_CTX_ctrl(FromOpaque(ctx), EVP_PKEY_RSA, + EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_RSA_OAEP_MD, 0, + (void *)md); } int EVP_PKEY_CTX_get_rsa_oaep_md(EVP_PKEY_CTX *ctx, const EVP_MD **out_md) { - return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, + return EVP_PKEY_CTX_ctrl(FromOpaque(ctx), EVP_PKEY_RSA, + EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_GET_RSA_OAEP_MD, 0, (void *)out_md); } int EVP_PKEY_CTX_set_rsa_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { - return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, - EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT, - EVP_PKEY_CTRL_RSA_MGF1_MD, 0, (void *)md); + return rsa_or_rsa_pss_ctrl(FromOpaque(ctx), + EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT, + EVP_PKEY_CTRL_RSA_MGF1_MD, 0, (void *)md); } int EVP_PKEY_CTX_get_rsa_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD **out_md) { - return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, - EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT, - EVP_PKEY_CTRL_GET_RSA_MGF1_MD, 0, (void *)out_md); + return rsa_or_rsa_pss_ctrl(FromOpaque(ctx), + EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT, + EVP_PKEY_CTRL_GET_RSA_MGF1_MD, 0, (void *)out_md); } int EVP_PKEY_CTX_set0_rsa_oaep_label(EVP_PKEY_CTX *ctx, uint8_t *label, size_t label_len) { - RSA_OAEP_LABEL_PARAMS params = {label, label_len}; - return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, - EVP_PKEY_CTRL_RSA_OAEP_LABEL, 0, ¶ms); + Span span(label, label_len); + return EVP_PKEY_CTX_ctrl(FromOpaque(ctx), EVP_PKEY_RSA, + EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_RSA_OAEP_LABEL, + 0, &span); } int EVP_PKEY_CTX_get0_rsa_oaep_label(EVP_PKEY_CTX *ctx, const uint8_t **out_label) { CBS label; - if (!EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, + if (!EVP_PKEY_CTX_ctrl(FromOpaque(ctx), EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL, 0, &label)) { return -1; } diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_rsa_asn1.cc b/Sources/CNIOBoringSSL/crypto/evp/p_rsa_asn1.cc deleted file mode 100644 index 82e5fdaa..00000000 --- a/Sources/CNIOBoringSSL/crypto/evp/p_rsa_asn1.cc +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ - -#include - -#include -#include -#include -#include -#include -#include - -#include "../fipsmodule/rsa/internal.h" -#include "internal.h" - - -static int rsa_pub_encode(CBB *out, const EVP_PKEY *key) { - // See RFC 3279, section 2.3.1. - const RSA *rsa = reinterpret_cast(key->pkey); - CBB spki, algorithm, oid, null, key_bitstring; - if (!CBB_add_asn1(out, &spki, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&spki, &algorithm, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&algorithm, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, rsa_asn1_meth.oid, rsa_asn1_meth.oid_len) || - !CBB_add_asn1(&algorithm, &null, CBS_ASN1_NULL) || - !CBB_add_asn1(&spki, &key_bitstring, CBS_ASN1_BITSTRING) || - !CBB_add_u8(&key_bitstring, 0 /* padding */) || - !RSA_marshal_public_key(&key_bitstring, rsa) || // - !CBB_flush(out)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); - return 0; - } - - return 1; -} - -static int rsa_pub_decode(EVP_PKEY *out, CBS *params, CBS *key) { - // See RFC 3279, section 2.3.1. - - // The parameters must be NULL. - CBS null; - if (!CBS_get_asn1(params, &null, CBS_ASN1_NULL) || CBS_len(&null) != 0 || - CBS_len(params) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - RSA *rsa = RSA_parse_public_key(key); - if (rsa == NULL || CBS_len(key) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - RSA_free(rsa); - return 0; - } - - EVP_PKEY_assign_RSA(out, rsa); - return 1; -} - -static int rsa_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { - const RSA *a_rsa = reinterpret_cast(a->pkey); - const RSA *b_rsa = reinterpret_cast(b->pkey); - return BN_cmp(RSA_get0_n(b_rsa), RSA_get0_n(a_rsa)) == 0 && - BN_cmp(RSA_get0_e(b_rsa), RSA_get0_e(a_rsa)) == 0; -} - -static int rsa_priv_encode(CBB *out, const EVP_PKEY *key) { - const RSA *rsa = reinterpret_cast(key->pkey); - CBB pkcs8, algorithm, oid, null, 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(&algorithm, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, rsa_asn1_meth.oid, rsa_asn1_meth.oid_len) || - !CBB_add_asn1(&algorithm, &null, CBS_ASN1_NULL) || - !CBB_add_asn1(&pkcs8, &private_key, CBS_ASN1_OCTETSTRING) || - !RSA_marshal_private_key(&private_key, rsa) || // - !CBB_flush(out)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); - return 0; - } - - return 1; -} - -static int rsa_priv_decode(EVP_PKEY *out, CBS *params, CBS *key) { - // Per RFC 3447, A.1, the parameters have type NULL. - CBS null; - if (!CBS_get_asn1(params, &null, CBS_ASN1_NULL) || CBS_len(&null) != 0 || - CBS_len(params) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - RSA *rsa = RSA_parse_private_key(key); - if (rsa == NULL || CBS_len(key) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - RSA_free(rsa); - return 0; - } - - EVP_PKEY_assign_RSA(out, rsa); - return 1; -} - -static int rsa_opaque(const EVP_PKEY *pkey) { - const RSA *rsa = reinterpret_cast(pkey->pkey); - return RSA_is_opaque(rsa); -} - -static int int_rsa_size(const EVP_PKEY *pkey) { - const RSA *rsa = reinterpret_cast(pkey->pkey); - return RSA_size(rsa); -} - -static int rsa_bits(const EVP_PKEY *pkey) { - const RSA *rsa = reinterpret_cast(pkey->pkey); - return RSA_bits(rsa); -} - -static void int_rsa_free(EVP_PKEY *pkey) { - RSA_free(reinterpret_cast(pkey->pkey)); - pkey->pkey = NULL; -} - -const EVP_PKEY_ASN1_METHOD rsa_asn1_meth = { - EVP_PKEY_RSA, - // 1.2.840.113549.1.1.1 - {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01}, - 9, - - &rsa_pkey_meth, - - rsa_pub_decode, - rsa_pub_encode, - rsa_pub_cmp, - - rsa_priv_decode, - rsa_priv_encode, - - /*set_priv_raw=*/NULL, - /*set_pub_raw=*/NULL, - /*get_priv_raw=*/NULL, - /*get_pub_raw=*/NULL, - /*set1_tls_encodedpoint=*/NULL, - /*get1_tls_encodedpoint=*/NULL, - - rsa_opaque, - - int_rsa_size, - rsa_bits, - - 0, - 0, - 0, - - int_rsa_free, -}; - -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_assign_RSA(EVP_PKEY *pkey, RSA *key) { - evp_pkey_set_method(pkey, &rsa_asn1_meth); - pkey->pkey = key; - return key != NULL; -} - -RSA *EVP_PKEY_get0_RSA(const EVP_PKEY *pkey) { - if (pkey->type != EVP_PKEY_RSA) { - OPENSSL_PUT_ERROR(EVP, EVP_R_EXPECTING_AN_RSA_KEY); - return NULL; - } - return reinterpret_cast(pkey->pkey); -} - -RSA *EVP_PKEY_get1_RSA(const EVP_PKEY *pkey) { - RSA *rsa = EVP_PKEY_get0_RSA(pkey); - if (rsa != NULL) { - RSA_up_ref(rsa); - } - return rsa; -} diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_x25519.cc b/Sources/CNIOBoringSSL/crypto/evp/p_x25519.cc index 4ee5aa91..c2ab25e8 100644 --- a/Sources/CNIOBoringSSL/crypto/evp/p_x25519.cc +++ b/Sources/CNIOBoringSSL/crypto/evp/p_x25519.cc @@ -1,49 +1,302 @@ -/* Copyright 2019 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2019 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 "../internal.h" +#include "../mem_internal.h" #include "internal.h" -// X25519 has no parameters to copy. -static int pkey_x25519_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { return 1; } +using namespace bssl; -static int pkey_x25519_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { - X25519_KEY *key = - reinterpret_cast(OPENSSL_malloc(sizeof(X25519_KEY))); - if (key == NULL) { +namespace { + +struct X25519_KEY { + uint8_t pub[32]; + uint8_t priv[32]; + bool has_private; +}; + +extern const EVP_PKEY_ASN1_METHOD x25519_asn1_meth; +extern const EVP_PKEY_CTX_METHOD x25519_pkey_meth; + +static 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) { + if (len != 32) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); return 0; } - evp_pkey_set_method(pkey, &x25519_asn1_meth); + X25519_KEY *key = New(); + if (key == nullptr) { + return 0; + } - X25519_keypair(key->pub, key->priv); - key->has_private = 1; + OPENSSL_memcpy(key->priv, in, 32); + X25519_public_from_private(key->pub, key->priv); + key->has_private = true; - OPENSSL_free(pkey->pkey); - pkey->pkey = key; + evp_pkey_set0(pkey, &x25519_asn1_meth, key); return 1; } -static int pkey_x25519_derive(EVP_PKEY_CTX *ctx, uint8_t *out, +static 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; + } + + X25519_KEY *key = New(); + if (key == nullptr) { + return 0; + } + + OPENSSL_memcpy(key->pub, in, 32); + key->has_private = false; + + evp_pkey_set0(pkey, &x25519_asn1_meth, key); + return 1; +} + +static 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); + return 0; + } + + if (out == nullptr) { + *out_len = 32; + return 1; + } + + if (*out_len < 32) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + + OPENSSL_memcpy(out, key->priv, 32); + *out_len = 32; + return 1; +} + +static int x25519_get_pub_raw(const EvpPkey *pkey, uint8_t *out, size_t *out_len) { - if (ctx->pkey == NULL || ctx->peerkey == NULL) { + const X25519_KEY *key = reinterpret_cast(pkey->pkey); + if (out == nullptr) { + *out_len = 32; + return 1; + } + + if (*out_len < 32) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + + OPENSSL_memcpy(out, key->pub, 32); + *out_len = 32; + return 1; +} + +static 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) { + const X25519_KEY *key = reinterpret_cast(pkey->pkey); + if (key == nullptr) { + OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); + return 0; + } + + *out_ptr = reinterpret_cast(OPENSSL_memdup(key->pub, 32)); + 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) { + // See RFC 8410, section 4. + + // The parameters must be omitted. Public keys have length 32. + if (CBS_len(params) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + return x25519_set_pub_raw(out, CBS_data(key), CBS_len(key)) + ? evp_decode_ok + : evp_decode_error; +} + +static int x25519_pub_encode(CBB *out, const EvpPkey *pkey) { + const X25519_KEY *key = reinterpret_cast(pkey->pkey); + + // See RFC 8410, section 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, x25519_asn1_meth.oid, + x25519_asn1_meth.oid_len) || + !CBB_add_asn1(&spki, &key_bitstring, CBS_ASN1_BITSTRING) || + !CBB_add_u8(&key_bitstring, 0 /* padding */) || + !CBB_add_bytes(&key_bitstring, key->pub, 32) || // + !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); + return 0; + } + + return 1; +} + +static 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) { + // See RFC 8410, section 7. + + // Parameters must be empty. The key is a 32-byte value wrapped in an extra + // OCTET STRING layer. + CBS inner; + if (CBS_len(params) != 0 || + !CBS_get_asn1(key, &inner, CBS_ASN1_OCTETSTRING) || CBS_len(key) != 0) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return evp_decode_error; + } + + return x25519_set_priv_raw(out, CBS_data(&inner), CBS_len(&inner)) + ? evp_decode_ok + : evp_decode_error; +} + +static 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); + return 0; + } + + // See RFC 8410, section 7. + CBB pkcs8, algorithm, private_key, inner; + 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, x25519_asn1_meth.oid, + x25519_asn1_meth.oid_len) || + !CBB_add_asn1(&pkcs8, &private_key, CBS_ASN1_OCTETSTRING) || + !CBB_add_asn1(&private_key, &inner, CBS_ASN1_OCTETSTRING) || + // The PKCS#8 encoding stores only the 32-byte seed which is the first 32 + // bytes of the private key. + !CBB_add_bytes(&inner, key->priv, 32) || // + !CBB_flush(out)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); + return 0; + } + + return 1; +} + +static bool x25519_pub_present(const EvpPkey *) { return true; } + +static bool x25519_pub_copy(EvpPkey *out, const EvpPkey *pkey) { + const X25519_KEY *pkey_x25519 = + reinterpret_cast(pkey->pkey); + X25519_KEY *public_copy = New(); + if (public_copy == nullptr) { + return false; + } + OPENSSL_memcpy(public_copy->pub, pkey_x25519->pub, 32); + public_copy->has_private = false; + evp_pkey_set0(out, pkey->ameth, public_copy); + return true; +} + +static 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; } + +static int x25519_bits(const EvpPkey *pkey) { return 253; } + +const EVP_PKEY_ASN1_METHOD x25519_asn1_meth = { + EVP_PKEY_X25519, + {0x2b, 0x65, 0x6e}, + 3, + &x25519_pkey_meth, + x25519_pub_decode, + x25519_pub_encode, + x25519_pub_equal, + x25519_pub_present, + x25519_pub_copy, + x25519_priv_decode, + x25519_priv_encode, + x25519_priv_present, + x25519_set_priv_raw, + /*set_priv_seed=*/nullptr, + x25519_set_pub_raw, + x25519_get_priv_raw, + /*get_priv_seed=*/nullptr, + x25519_get_pub_raw, + x25519_set1_tls_encodedpoint, + x25519_get1_tls_encodedpoint, + /*pkey_opaque=*/nullptr, + x25519_size, + x25519_bits, + /*param_missing=*/nullptr, + /*param_copy=*/nullptr, + /*param_equal=*/nullptr, + x25519_free, +}; + +// X25519 has no parameters to copy. +static int pkey_x25519_copy(EvpPkeyCtx *dst, EvpPkeyCtx *src) { return 1; } + +static int pkey_x25519_keygen(EvpPkeyCtx *ctx, EvpPkey *pkey) { + X25519_KEY *key = New(); + if (key == nullptr) { + return 0; + } + + X25519_keypair(key->pub, key->priv); + key->has_private = true; + evp_pkey_set0(pkey, &x25519_asn1_meth, key); + return 1; +} + +static 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; } @@ -52,7 +305,7 @@ static int pkey_x25519_derive(EVP_PKEY_CTX *ctx, uint8_t *out, reinterpret_cast(ctx->pkey->pkey); const X25519_KEY *peer_key = reinterpret_cast(ctx->peerkey->pkey); - if (our_key == NULL || peer_key == NULL) { + if (our_key == nullptr || peer_key == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_KEYS_NOT_SET); return 0; } @@ -62,7 +315,7 @@ static int pkey_x25519_derive(EVP_PKEY_CTX *ctx, uint8_t *out, return 0; } - if (out != NULL) { + if (out != nullptr) { if (*out_len < 32) { OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); return 0; @@ -77,10 +330,10 @@ static int pkey_x25519_derive(EVP_PKEY_CTX *ctx, uint8_t *out, return 1; } -static int pkey_x25519_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { +static 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, + // `EVP_PKEY_derive_set_peer` requires the key implement this command, // even if it is a no-op. return 1; @@ -90,20 +343,29 @@ static int pkey_x25519_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { } } -const EVP_PKEY_METHOD x25519_pkey_meth = { +const EVP_PKEY_CTX_METHOD x25519_pkey_meth = { /*pkey_id=*/EVP_PKEY_X25519, - /*init=*/NULL, + /*init=*/nullptr, /*copy=*/pkey_x25519_copy, - /*cleanup=*/NULL, + /*cleanup=*/nullptr, /*keygen=*/pkey_x25519_keygen, - /*sign=*/NULL, - /*sign_message=*/NULL, - /*verify=*/NULL, - /*verify_message=*/NULL, - /*verify_recover=*/NULL, - /*encrypt=*/NULL, - /*decrypt=*/NULL, + /*sign=*/nullptr, + /*sign_message=*/nullptr, + /*verify=*/nullptr, + /*verify_message=*/nullptr, + /*verify_recover=*/nullptr, + /*encrypt=*/nullptr, + /*decrypt=*/nullptr, /*derive=*/pkey_x25519_derive, - /*paramgen=*/NULL, + /*paramgen=*/nullptr, + /*encap=*/nullptr, + /*decap=*/nullptr, /*ctrl=*/pkey_x25519_ctrl, }; + +} // namespace + +const EVP_PKEY_ALG *EVP_pkey_x25519() { + static const EVP_PKEY_ALG kAlg = {&x25519_asn1_meth, &x25519_pkey_meth}; + return &kAlg; +} diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_x25519_asn1.cc b/Sources/CNIOBoringSSL/crypto/evp/p_x25519_asn1.cc deleted file mode 100644 index 158fd4c1..00000000 --- a/Sources/CNIOBoringSSL/crypto/evp/p_x25519_asn1.cc +++ /dev/null @@ -1,237 +0,0 @@ -/* Copyright 2019 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#include - -#include -#include -#include -#include - -#include "../internal.h" -#include "internal.h" - - -static void x25519_free(EVP_PKEY *pkey) { - OPENSSL_free(pkey->pkey); - pkey->pkey = NULL; -} - -static int x25519_set_priv_raw(EVP_PKEY *pkey, const uint8_t *in, size_t len) { - if (len != 32) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - X25519_KEY *key = - reinterpret_cast(OPENSSL_malloc(sizeof(X25519_KEY))); - if (key == NULL) { - return 0; - } - - OPENSSL_memcpy(key->priv, in, 32); - X25519_public_from_private(key->pub, key->priv); - key->has_private = 1; - - x25519_free(pkey); - pkey->pkey = key; - return 1; -} - -static int x25519_set_pub_raw(EVP_PKEY *pkey, const uint8_t *in, size_t len) { - if (len != 32) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - X25519_KEY *key = - reinterpret_cast(OPENSSL_malloc(sizeof(X25519_KEY))); - if (key == NULL) { - return 0; - } - - OPENSSL_memcpy(key->pub, in, 32); - key->has_private = 0; - - x25519_free(pkey); - pkey->pkey = key; - return 1; -} - -static int x25519_get_priv_raw(const EVP_PKEY *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); - return 0; - } - - if (out == NULL) { - *out_len = 32; - return 1; - } - - if (*out_len < 32) { - OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); - return 0; - } - - OPENSSL_memcpy(out, key->priv, 32); - *out_len = 32; - return 1; -} - -static int x25519_get_pub_raw(const EVP_PKEY *pkey, uint8_t *out, - size_t *out_len) { - const X25519_KEY *key = reinterpret_cast(pkey->pkey); - if (out == NULL) { - *out_len = 32; - return 1; - } - - if (*out_len < 32) { - OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); - return 0; - } - - OPENSSL_memcpy(out, key->pub, 32); - *out_len = 32; - return 1; -} - -static int x25519_set1_tls_encodedpoint(EVP_PKEY *pkey, const uint8_t *in, - size_t len) { - return x25519_set_pub_raw(pkey, in, len); -} - -static size_t x25519_get1_tls_encodedpoint(const EVP_PKEY *pkey, - uint8_t **out_ptr) { - const X25519_KEY *key = reinterpret_cast(pkey->pkey); - if (key == NULL) { - OPENSSL_PUT_ERROR(EVP, EVP_R_NO_KEY_SET); - return 0; - } - - *out_ptr = reinterpret_cast(OPENSSL_memdup(key->pub, 32)); - return *out_ptr == NULL ? 0 : 32; -} - -static int x25519_pub_decode(EVP_PKEY *out, CBS *params, CBS *key) { - // See RFC 8410, section 4. - - // The parameters must be omitted. Public keys have length 32. - if (CBS_len(params) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - return x25519_set_pub_raw(out, CBS_data(key), CBS_len(key)); -} - -static int x25519_pub_encode(CBB *out, const EVP_PKEY *pkey) { - const X25519_KEY *key = reinterpret_cast(pkey->pkey); - - // See RFC 8410, section 4. - CBB spki, algorithm, oid, key_bitstring; - if (!CBB_add_asn1(out, &spki, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&spki, &algorithm, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&algorithm, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, x25519_asn1_meth.oid, x25519_asn1_meth.oid_len) || - !CBB_add_asn1(&spki, &key_bitstring, CBS_ASN1_BITSTRING) || - !CBB_add_u8(&key_bitstring, 0 /* padding */) || - !CBB_add_bytes(&key_bitstring, key->pub, 32) || // - !CBB_flush(out)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); - return 0; - } - - return 1; -} - -static int x25519_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *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 int x25519_priv_decode(EVP_PKEY *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 - // OCTET STRING layer. - CBS inner; - if (CBS_len(params) != 0 || - !CBS_get_asn1(key, &inner, CBS_ASN1_OCTETSTRING) || CBS_len(key) != 0) { - OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); - return 0; - } - - return x25519_set_priv_raw(out, CBS_data(&inner), CBS_len(&inner)); -} - -static int x25519_priv_encode(CBB *out, const EVP_PKEY *pkey) { - const X25519_KEY *key = reinterpret_cast(pkey->pkey); - if (!key->has_private) { - OPENSSL_PUT_ERROR(EVP, EVP_R_NOT_A_PRIVATE_KEY); - return 0; - } - - // See RFC 8410, section 7. - CBB pkcs8, algorithm, oid, private_key, inner; - 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(&algorithm, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, x25519_asn1_meth.oid, x25519_asn1_meth.oid_len) || - !CBB_add_asn1(&pkcs8, &private_key, CBS_ASN1_OCTETSTRING) || - !CBB_add_asn1(&private_key, &inner, CBS_ASN1_OCTETSTRING) || - // The PKCS#8 encoding stores only the 32-byte seed which is the first 32 - // bytes of the private key. - !CBB_add_bytes(&inner, key->priv, 32) || // - !CBB_flush(out)) { - OPENSSL_PUT_ERROR(EVP, EVP_R_ENCODE_ERROR); - return 0; - } - - return 1; -} - -static int x25519_size(const EVP_PKEY *pkey) { return 32; } - -static int x25519_bits(const EVP_PKEY *pkey) { return 253; } - -const EVP_PKEY_ASN1_METHOD x25519_asn1_meth = { - EVP_PKEY_X25519, - {0x2b, 0x65, 0x6e}, - 3, - &x25519_pkey_meth, - x25519_pub_decode, - x25519_pub_encode, - x25519_pub_cmp, - x25519_priv_decode, - x25519_priv_encode, - x25519_set_priv_raw, - x25519_set_pub_raw, - x25519_get_priv_raw, - x25519_get_pub_raw, - x25519_set1_tls_encodedpoint, - x25519_get1_tls_encodedpoint, - /*pkey_opaque=*/NULL, - x25519_size, - x25519_bits, - /*param_missing=*/NULL, - /*param_copy=*/NULL, - /*param_cmp=*/NULL, - x25519_free, -}; diff --git a/Sources/CNIOBoringSSL/crypto/evp/p_xwing.cc b/Sources/CNIOBoringSSL/crypto/evp/p_xwing.cc new file mode 100644 index 00000000..0bbcceac --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/evp/p_xwing.cc @@ -0,0 +1,300 @@ +// 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 "../mem_internal.h" +#include "internal.h" + + +using namespace bssl; + +namespace { + +struct XWING_KEY { + static constexpr bool kAllowUniquePtr = true; + + uint8_t pub[XWING_PUBLIC_KEY_BYTES]; + XWING_private_key priv; + bool has_private; +}; + +extern const EVP_PKEY_ASN1_METHOD xwing_asn1_meth; +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) { + Delete(reinterpret_cast(pkey->pkey)); +} + +static 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; } + +static 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) { + return false; + } + OPENSSL_memcpy(public_copy->pub, pkey_xwing->pub, XWING_PUBLIC_KEY_BYTES); + public_copy->has_private = false; + evp_pkey_set0(out, pkey->ameth, public_copy.release()); + return true; +} + +static 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) { + auto key = MakeUnique(); + if (key == nullptr) { + return 0; + } + CBS cbs; + CBS_init(&cbs, in, len); + if (!XWING_parse_private_key(&key->priv, &cbs) || CBS_len(&cbs) != 0 || + !XWING_public_from_private(key->pub, &key->priv)) { + OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR); + return 0; + } + key->has_private = true; + evp_pkey_set0(pkey, &xwing_asn1_meth, key.release()); + return 1; +} + +static 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); + return 0; + } + if (out == nullptr) { + *out_len = XWING_PRIVATE_KEY_BYTES; + return 1; + } + if (*out_len < XWING_PRIVATE_KEY_BYTES) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + CBB cbb; + CBB_init_fixed(&cbb, out, XWING_PRIVATE_KEY_BYTES); + if (!XWING_marshal_private_key(&cbb, &key->priv)) { + return 0; + } + *out_len = CBB_len(&cbb); + assert(*out_len == XWING_PRIVATE_KEY_BYTES); + return 1; +} + +static 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; + } + auto key = MakeUnique(); + if (key == nullptr) { + return 0; + } + OPENSSL_memcpy(key->pub, in, len); + key->has_private = false; + evp_pkey_set0(pkey, &xwing_asn1_meth, key.release()); + return 1; +} + +static 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; + } + if (*out_len < XWING_PUBLIC_KEY_BYTES) { + OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); + return 0; + } + const XWING_KEY *key = reinterpret_cast(pkey->pkey); + OPENSSL_memcpy(out, key->pub, XWING_PUBLIC_KEY_BYTES); + *out_len = XWING_PUBLIC_KEY_BYTES; + return 1; +} + +static int xwing_size(const EvpPkey *pkey) { return XWING_CIPHERTEXT_BYTES; } + +static 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; } + +static 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); + return 0; + } + key->has_private = true; + evp_pkey_set0(pkey, &xwing_asn1_meth, key.release()); + return 1; +} + +static int xwing_kem_encap(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; + } + if (out_secret.size() != XWING_SHARED_SECRET_BYTES) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH); + return 0; + } + const XWING_KEY *peer_pubkey = + reinterpret_cast(FromOpaque(peer_key)->pkey); + return XWING_encap(out_ciphertext.data(), out_secret.data(), + peer_pubkey->pub); +} + +static int xwing_kem_encap_external_entropy(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; + } + if (out_secret.size() != XWING_SHARED_SECRET_BYTES) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH); + return 0; + } + if (entropy.size() != kXwingEncapEntropyBytes) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_ENTROPY_LENGTH); + return 0; + } + const XWING_KEY *peer_pubkey = + reinterpret_cast(FromOpaque(peer_key)->pkey); + return XWING_encap_external_entropy(out_ciphertext.data(), out_secret.data(), + peer_pubkey->pub, entropy.data()); +} + +static int xwing_kem_decap(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); + return 0; + } + if (out_secret.size() != XWING_SHARED_SECRET_BYTES) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH); + return 0; + } + // XWING_decap does not accept wrong ciphertext lengths, so we must check for + // the proper length here. For consistency, we don't add an error to the error + // queue when a KEM decap fails due to incorrect ciphertext length. + if (ciphertext.size() != XWING_CIPHERTEXT_BYTES) { + return 0; + } + return XWING_decap(out_secret.data(), ciphertext.data(), &priv->priv); +} + +static const EVP_KEM xwing_evp_kem = { + EVP_PKEY_XWING, // + XWING_CIPHERTEXT_BYTES, // + XWING_SHARED_SECRET_BYTES, // + kXwingEncapEntropyBytes, // + &xwing_kem_encap, // + &xwing_kem_encap_external_entropy, // + &xwing_kem_decap, // +}; + +const EVP_PKEY_CTX_METHOD xwing_pkey_meth = { + /*pkey_id=*/EVP_PKEY_XWING, + /*init=*/nullptr, + &pkey_xwing_copy_ctx, + /*cleanup=*/nullptr, + &pkey_xwing_keygen, + /*sign=*/nullptr, + /*sign_message=*/nullptr, + /*verify=*/nullptr, + /*verify_message=*/nullptr, + /*verify_recover=*/nullptr, + /*encrypt=*/nullptr, + /*decrypt=*/nullptr, + /*derive=*/nullptr, + /*paramgen=*/nullptr, + &KemAdapter::EncapMethod, + &KemAdapter::DecapMethod, + /*ctrl=*/nullptr, +}; + +const EVP_PKEY_ASN1_METHOD xwing_asn1_meth = { + EVP_PKEY_XWING, + /*oid=*/{}, + /*oid_len=*/0, + &xwing_pkey_meth, + + /*pub_decode=*/nullptr, + /*pub_encode=*/nullptr, + &xwing_pub_equal, + &xwing_pub_present, + &xwing_pub_copy, + + /*priv_decode=*/nullptr, + /*priv_encode=*/nullptr, + &xwing_priv_present, + + /*set_priv_raw=*/nullptr, + &xwing_set_priv_seed, + &xwing_set_pub_raw, + /*get_priv_raw=*/nullptr, + &xwing_get_priv_seed, + &xwing_get_pub_raw, + + /*set1_tls_encodedpoint=*/nullptr, + /*get1_tls_encodedpoint=*/nullptr, + /*pkey_opaque=*/nullptr, + + &xwing_size, + &xwing_bits, + + /*param_missing=*/nullptr, + /*param_copy=*/nullptr, + /*param_equal=*/nullptr, + + /*pkey_free=*/&xwing_free, +}; + +} // namespace + +const EVP_PKEY_ALG *EVP_pkey_xwing() { + static const EVP_PKEY_ALG kAlg = {&xwing_asn1_meth, &xwing_pkey_meth}; + return &kAlg; +} + +const EVP_KEM *EVP_kem_xwing() { return &xwing_evp_kem; } diff --git a/Sources/CNIOBoringSSL/crypto/evp/pbkdf.cc b/Sources/CNIOBoringSSL/crypto/evp/pbkdf.cc index 9d5c4a30..2482b4bd 100644 --- a/Sources/CNIOBoringSSL/crypto/evp/pbkdf.cc +++ b/Sources/CNIOBoringSSL/crypto/evp/pbkdf.cc @@ -1,32 +1,44 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../internal.h" +using namespace bssl; + int PKCS5_PBKDF2_HMAC(const char *password, size_t password_len, const uint8_t *salt, size_t salt_len, uint32_t iterations, const EVP_MD *digest, size_t key_len, uint8_t *out_key) { // See RFC 8018, section 5.2. - bssl::ScopedHMAC_CTX hctx; - if (!HMAC_Init_ex(hctx.get(), password, password_len, digest, NULL)) { + ScopedHMAC_CTX hctx; + if (!HMAC_Init_ex(hctx.get(), password, password_len, digest, nullptr)) { return 0; } uint32_t i = 1; size_t md_len = EVP_MD_size(digest); + if (key_len > ((uint64_t{1} << 32) - 1) * md_len) { + OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH); + return 0; + } while (key_len > 0) { size_t todo = md_len; if (todo > key_len) { @@ -41,19 +53,19 @@ int PKCS5_PBKDF2_HMAC(const char *password, size_t password_len, // Compute U_1. uint8_t digest_tmp[EVP_MAX_MD_SIZE]; - if (!HMAC_Init_ex(hctx.get(), NULL, 0, NULL, NULL) || + if (!HMAC_Init_ex(hctx.get(), nullptr, 0, nullptr, nullptr) || !HMAC_Update(hctx.get(), salt, salt_len) || !HMAC_Update(hctx.get(), i_buf, 4) || - !HMAC_Final(hctx.get(), digest_tmp, NULL)) { + !HMAC_Final(hctx.get(), digest_tmp, nullptr)) { return 0; } OPENSSL_memcpy(out_key, digest_tmp, todo); for (uint32_t j = 1; j < iterations; j++) { // Compute the remaining U_* values and XOR. - if (!HMAC_Init_ex(hctx.get(), NULL, 0, NULL, NULL) || + if (!HMAC_Init_ex(hctx.get(), nullptr, 0, nullptr, nullptr) || !HMAC_Update(hctx.get(), digest_tmp, md_len) || - !HMAC_Final(hctx.get(), digest_tmp, NULL)) { + !HMAC_Final(hctx.get(), digest_tmp, nullptr)) { return 0; } for (size_t k = 0; k < todo; k++) { @@ -70,7 +82,7 @@ int PKCS5_PBKDF2_HMAC(const char *password, size_t password_len, // value of 0 is an error. // // Unfortunately not all consumers of PKCS5_PBKDF2_HMAC() check their return - // value, expecting it to succeed and unconditionally using |out_key|. As a + // value, expecting it to succeed and unconditionally using `out_key`. As a // precaution for such callsites in external code, the old behavior of // iterations < 1 being treated as iterations == 1 is preserved, but // additionally an error result is returned. diff --git a/Sources/CNIOBoringSSL/crypto/evp/print.cc b/Sources/CNIOBoringSSL/crypto/evp/print.cc index 76c4cb80..d6dbb465 100644 --- a/Sources/CNIOBoringSSL/crypto/evp/print.cc +++ b/Sources/CNIOBoringSSL/crypto/evp/print.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -19,10 +24,11 @@ #include #include -#include "../fipsmodule/rsa/internal.h" #include "../internal.h" +using namespace bssl; + static int print_hex(BIO *bp, const uint8_t *data, size_t len, int off) { for (size_t i = 0; i < len; i++) { if ((i % 15) == 0) { @@ -42,7 +48,7 @@ static int print_hex(BIO *bp, const uint8_t *data, size_t len, int off) { } static int bn_print(BIO *bp, const char *name, const BIGNUM *num, int off) { - if (num == NULL) { + if (num == nullptr) { return 1; } @@ -68,14 +74,14 @@ static int bn_print(BIO *bp, const char *name, const BIGNUM *num, int off) { return 0; } - // Print |num| in hex, adding a leading zero, as in ASN.1, if the high bit + // Print `num` in hex, adding a leading zero, as in ASN.1, if the high bit // is set. // // TODO(davidben): Do we need to do this? We already print "(Negative)" above // and negative values are never valid in keys anyway. size_t len = BN_num_bytes(num); uint8_t *buf = reinterpret_cast(OPENSSL_malloc(len + 1)); - if (buf == NULL) { + if (buf == nullptr) { return 0; } @@ -98,8 +104,8 @@ static int bn_print(BIO *bp, const char *name, const BIGNUM *num, int off) { static int do_rsa_print(BIO *out, const RSA *rsa, int off, int include_private) { int mod_len = 0; - if (rsa->n != NULL) { - mod_len = BN_num_bits(rsa->n); + if (RSA_get0_n(rsa) != nullptr) { + mod_len = RSA_bits(rsa); } if (!BIO_indent(out, off, 128)) { @@ -107,7 +113,7 @@ static int do_rsa_print(BIO *out, const RSA *rsa, int off, } const char *s, *str; - if (include_private && rsa->d) { + if (include_private && RSA_get0_d(rsa) != nullptr) { if (BIO_printf(out, "Private-Key: (%d bit)\n", mod_len) <= 0) { return 0; } @@ -120,17 +126,18 @@ static int do_rsa_print(BIO *out, const RSA *rsa, int off, str = "Modulus:"; s = "Exponent:"; } - if (!bn_print(out, str, rsa->n, off) || !bn_print(out, s, rsa->e, off)) { + if (!bn_print(out, str, RSA_get0_n(rsa), off) || + !bn_print(out, s, RSA_get0_e(rsa), off)) { return 0; } if (include_private) { - if (!bn_print(out, "privateExponent:", rsa->d, off) || - !bn_print(out, "prime1:", rsa->p, off) || - !bn_print(out, "prime2:", rsa->q, off) || - !bn_print(out, "exponent1:", rsa->dmp1, off) || - !bn_print(out, "exponent2:", rsa->dmq1, off) || - !bn_print(out, "coefficient:", rsa->iqmp, off)) { + if (!bn_print(out, "privateExponent:", RSA_get0_d(rsa), off) || + !bn_print(out, "prime1:", RSA_get0_p(rsa), off) || + !bn_print(out, "prime2:", RSA_get0_q(rsa), off) || + !bn_print(out, "exponent1:", RSA_get0_dmp1(rsa), off) || + !bn_print(out, "exponent2:", RSA_get0_dmq1(rsa), off) || + !bn_print(out, "coefficient:", RSA_get0_iqmp(rsa), off)) { return 0; } } @@ -147,60 +154,11 @@ static int rsa_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent) { } -// DSA keys. - -static int do_dsa_print(BIO *bp, const DSA *x, int off, int ptype) { - const BIGNUM *priv_key = NULL; - if (ptype == 2) { - priv_key = DSA_get0_priv_key(x); - } - - const BIGNUM *pub_key = NULL; - if (ptype > 0) { - pub_key = DSA_get0_pub_key(x); - } - - const char *ktype = "DSA-Parameters"; - if (ptype == 2) { - ktype = "Private-Key"; - } else if (ptype == 1) { - ktype = "Public-Key"; - } - - if (!BIO_indent(bp, off, 128) || - BIO_printf(bp, "%s: (%u bit)\n", ktype, BN_num_bits(DSA_get0_p(x))) <= - 0 || - // |priv_key| and |pub_key| may be NULL, in which case |bn_print| will - // silently skip them. - !bn_print(bp, "priv:", priv_key, off) || - !bn_print(bp, "pub:", pub_key, off) || - !bn_print(bp, "P:", DSA_get0_p(x), off) || - !bn_print(bp, "Q:", DSA_get0_q(x), off) || - !bn_print(bp, "G:", DSA_get0_g(x), off)) { - return 0; - } - - return 1; -} - -static int dsa_param_print(BIO *bp, const EVP_PKEY *pkey, int indent) { - return do_dsa_print(bp, EVP_PKEY_get0_DSA(pkey), indent, 0); -} - -static int dsa_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent) { - return do_dsa_print(bp, EVP_PKEY_get0_DSA(pkey), indent, 1); -} - -static int dsa_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent) { - return do_dsa_print(bp, EVP_PKEY_get0_DSA(pkey), indent, 2); -} - - // EC keys. static int do_EC_KEY_print(BIO *bp, const EC_KEY *x, int off, int ktype) { const EC_GROUP *group; - if (x == NULL || (group = EC_KEY_get0_group(x)) == NULL) { + if (x == nullptr || (group = EC_KEY_get0_group(x)) == nullptr) { OPENSSL_PUT_ERROR(EVP, ERR_R_PASSED_NULL_PARAMETER); return 0; } @@ -227,15 +185,15 @@ static int do_EC_KEY_print(BIO *bp, const EC_KEY *x, int off, int ktype) { if (ktype == 2) { const BIGNUM *priv_key = EC_KEY_get0_private_key(x); - if (priv_key != NULL && // + if (priv_key != nullptr && // !bn_print(bp, "priv:", priv_key, off)) { return 0; } } - if (ktype > 0 && EC_KEY_get0_public_key(x) != NULL) { - uint8_t *pub = NULL; - size_t pub_len = EC_KEY_key2buf(x, EC_KEY_get_conv_form(x), &pub, NULL); + if (ktype > 0 && EC_KEY_get0_public_key(x) != nullptr) { + uint8_t *pub = nullptr; + size_t pub_len = EC_KEY_key2buf(x, EC_KEY_get_conv_form(x), &pub, nullptr); if (pub_len == 0) { return 0; } @@ -272,18 +230,12 @@ typedef struct { int (*param_print)(BIO *out, const EVP_PKEY *pkey, int indent); } EVP_PKEY_PRINT_METHOD; -static EVP_PKEY_PRINT_METHOD kPrintMethods[] = { +static const EVP_PKEY_PRINT_METHOD kPrintMethods[] = { { EVP_PKEY_RSA, rsa_pub_print, rsa_priv_print, - NULL /* param_print */, - }, - { - EVP_PKEY_DSA, - dsa_pub_print, - dsa_priv_print, - dsa_param_print, + /*param_print=*/nullptr, }, { EVP_PKEY_EC, @@ -293,15 +245,13 @@ static EVP_PKEY_PRINT_METHOD kPrintMethods[] = { }, }; -static size_t kPrintMethodsLen = OPENSSL_ARRAY_SIZE(kPrintMethods); - -static EVP_PKEY_PRINT_METHOD *find_method(int type) { - for (size_t i = 0; i < kPrintMethodsLen; i++) { - if (kPrintMethods[i].type == type) { - return &kPrintMethods[i]; +static const EVP_PKEY_PRINT_METHOD *find_method(int type) { + for (const auto &p : kPrintMethods) { + if (p.type == type) { + return &p; } } - return NULL; + return nullptr; } static int print_unsupported(BIO *out, const EVP_PKEY *pkey, int indent, @@ -313,8 +263,8 @@ static int print_unsupported(BIO *out, const EVP_PKEY *pkey, int indent, int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx) { - EVP_PKEY_PRINT_METHOD *method = find_method(EVP_PKEY_id(pkey)); - if (method != NULL && method->pub_print != NULL) { + const EVP_PKEY_PRINT_METHOD *method = find_method(EVP_PKEY_id(pkey)); + if (method != nullptr && method->pub_print != nullptr) { return method->pub_print(out, pkey, indent); } return print_unsupported(out, pkey, indent, "Public Key"); @@ -322,8 +272,8 @@ int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey, int indent, int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx) { - EVP_PKEY_PRINT_METHOD *method = find_method(EVP_PKEY_id(pkey)); - if (method != NULL && method->priv_print != NULL) { + const EVP_PKEY_PRINT_METHOD *method = find_method(EVP_PKEY_id(pkey)); + if (method != nullptr && method->priv_print != nullptr) { return method->priv_print(out, pkey, indent); } return print_unsupported(out, pkey, indent, "Private Key"); @@ -331,8 +281,8 @@ int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey, int indent, int EVP_PKEY_print_params(BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx) { - EVP_PKEY_PRINT_METHOD *method = find_method(EVP_PKEY_id(pkey)); - if (method != NULL && method->param_print != NULL) { + const EVP_PKEY_PRINT_METHOD *method = find_method(EVP_PKEY_id(pkey)); + if (method != nullptr && method->param_print != nullptr) { return method->param_print(out, pkey, indent); } return print_unsupported(out, pkey, indent, "Parameters"); diff --git a/Sources/CNIOBoringSSL/crypto/evp/scrypt.cc b/Sources/CNIOBoringSSL/crypto/evp/scrypt.cc index a7ff5eef..91785f34 100644 --- a/Sources/CNIOBoringSSL/crypto/evp/scrypt.cc +++ b/Sources/CNIOBoringSSL/crypto/evp/scrypt.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -21,11 +26,13 @@ // // Note scrypt refers to both "blocks" and a "block size" parameter, r. These // are two different notions of blocks. A Salsa20 block is 64 bytes long, -// represented in this implementation by 16 |uint32_t|s. |r| determines the -// number of 64-byte Salsa20 blocks in a scryptBlockMix block, which is 2 * |r| +// represented in this implementation by 16 `uint32_t`s. `r` determines the +// number of 64-byte Salsa20 blocks in a scryptBlockMix block, which is 2 * `r` // Salsa20 blocks. This implementation refers to them as Salsa20 blocks and // scrypt blocks, respectively. +using namespace bssl; + // A block_t is a Salsa20 block. typedef struct { uint32_t words[16]; @@ -34,7 +41,7 @@ typedef struct { static_assert(sizeof(block_t) == 64, "block_t has padding"); // salsa208_word_specification implements the Salsa20/8 core function, also -// described in RFC 7914, section 3. It modifies the block at |inout| +// described in RFC 7914, section 3. It modifies the block at `inout` // in-place. static void salsa208_word_specification(block_t *inout) { block_t x; @@ -80,7 +87,7 @@ static void salsa208_word_specification(block_t *inout) { } } -// xor_block sets |*out| to be |*a| XOR |*b|. +// xor_block sets `*out` to be `*a` XOR `*b`. static void xor_block(block_t *out, const block_t *a, const block_t *b) { for (size_t i = 0; i < 16; i++) { out->words[i] = a->words[i] ^ b->words[i]; @@ -88,8 +95,8 @@ static void xor_block(block_t *out, const block_t *a, const block_t *b) { } // scryptBlockMix implements the function described in RFC 7914, section 4. B' -// is written to |out|. |out| and |B| may not alias and must be each one scrypt -// block (2 * |r| Salsa20 blocks) long. +// is written to `out`. `out` and `B` may not alias and must be each one scrypt +// block (2 * `r` Salsa20 blocks) long. static void scryptBlockMix(block_t *out, const block_t *B, uint64_t r) { assert(out != B); @@ -104,11 +111,11 @@ static void scryptBlockMix(block_t *out, const block_t *B, uint64_t r) { } } -// scryptROMix implements the function described in RFC 7914, section 5. |B| is -// an scrypt block (2 * |r| Salsa20 blocks) and is modified in-place. |T| and -// |V| are scratch space allocated by the caller. |T| must have space for one -// scrypt block (2 * |r| Salsa20 blocks). |V| must have space for |N| scrypt -// blocks (2 * |r| * |N| Salsa20 blocks). +// scryptROMix implements the function described in RFC 7914, section 5. `B` is +// an scrypt block (2 * `r` Salsa20 blocks) and is modified in-place. `T` and +// `V` are scratch space allocated by the caller. `T` must have space for one +// scrypt block (2 * `r` Salsa20 blocks). `V` must have space for `N` scrypt +// blocks (2 * `r` * `N` Salsa20 blocks). static void scryptROMix(block_t *B, uint64_t r, uint64_t N, block_t *T, block_t *V) { // Steps 1 and 2. @@ -121,7 +128,7 @@ static void scryptROMix(block_t *B, uint64_t r, uint64_t N, block_t *T, // Step 3. for (uint64_t i = 0; i < N; i++) { - // Note this assumes |N| <= 2^32 and is a power of 2. + // Note this assumes `N` <= 2^32 and is a power of 2. uint32_t j = B[2 * r - 1].words[0] & (N - 1); for (size_t k = 0; k < 2 * r; k++) { xor_block(&T[k], &B[k], &V[2 * r * j + k]); @@ -139,7 +146,7 @@ static void scryptROMix(block_t *B, uint64_t r, uint64_t N, block_t *T, #define SCRYPT_PR_MAX ((1 << 30) - 1) // SCRYPT_MAX_MEM is the default maximum memory that may be allocated by -// |EVP_PBE_scrypt|. +// `EVP_PBE_scrypt`. #define SCRYPT_MAX_MEM (1024 * 1024 * 65) int EVP_PBE_scrypt(const char *password, size_t password_len, @@ -147,18 +154,18 @@ int EVP_PBE_scrypt(const char *password, size_t password_len, uint64_t p, size_t max_mem, uint8_t *out_key, size_t key_len) { if (r == 0 || p == 0 || p > SCRYPT_PR_MAX / r || - // |N| must be a power of two. + // `N` must be a power of two. N < 2 || (N & (N - 1)) || - // We only support |N| <= 2^32 in |scryptROMix|. + // We only support `N` <= 2^32 in `scryptROMix`. N > UINT64_C(1) << 32 || - // Check that |N| < 2^(128×r / 8). + // Check that `N` < 2^(128×r / 8). (16 * r <= 63 && N >= UINT64_C(1) << (16 * r))) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PARAMETERS); return 0; } - // Determine the amount of memory needed. B, T, and V are |p|, 1, and |N| - // scrypt blocks, respectively. Each scrypt block is 2*|r| |block_t|s. + // Determine the amount of memory needed. B, T, and V are `p`, 1, and `N` + // scrypt blocks, respectively. Each scrypt block is 2*`r` `block_t`s. if (max_mem == 0) { max_mem = SCRYPT_MAX_MEM; } @@ -169,7 +176,7 @@ int EVP_PBE_scrypt(const char *password, size_t password_len, return 0; } - // Allocate and divide up the scratch space. |max_mem| fits in a size_t, which + // Allocate and divide up the scratch space. `max_mem` fits in a size_t, which // is no bigger than uint64_t, so none of these operations may overflow. static_assert(UINT64_MAX >= SIZE_MAX, "size_t exceeds uint64_t"); size_t B_blocks = p * 2 * r; @@ -178,7 +185,7 @@ int EVP_PBE_scrypt(const char *password, size_t password_len, size_t V_blocks = N * 2 * r; block_t *B = reinterpret_cast( OPENSSL_calloc(B_blocks + T_blocks + V_blocks, sizeof(block_t))); - if (B == NULL) { + if (B == nullptr) { return 0; } @@ -187,7 +194,7 @@ int EVP_PBE_scrypt(const char *password, size_t password_len, block_t *V = T + T_blocks; // NOTE: PKCS5_PBKDF2_HMAC can only fail due to allocation failure - // or |iterations| of 0 (we pass 1 here). This is consistent with + // or `iterations` of 0 (we pass 1 here). This is consistent with // the documented failure conditions of EVP_PBE_scrypt. if (!PKCS5_PBKDF2_HMAC(password, password_len, salt, salt_len, 1, EVP_sha256(), B_bytes, (uint8_t *)B)) { diff --git a/Sources/CNIOBoringSSL/crypto/evp/sign.cc b/Sources/CNIOBoringSSL/crypto/evp/sign.cc index c81d1e87..f29c45f4 100644 --- a/Sources/CNIOBoringSSL/crypto/evp/sign.cc +++ b/Sources/CNIOBoringSSL/crypto/evp/sign.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -31,39 +36,30 @@ 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) { - uint8_t m[EVP_MAX_MD_SIZE]; - unsigned m_len; - int ret = 0; - EVP_MD_CTX tmp_ctx; - EVP_PKEY_CTX *pkctx = NULL; + // Ensure the final result will fit in `unsigned`. size_t sig_len = EVP_PKEY_size(pkey); - - // Ensure the final result will fit in |unsigned|. if (sig_len > UINT_MAX) { sig_len = UINT_MAX; } *out_sig_len = 0; - EVP_MD_CTX_init(&tmp_ctx); - if (!EVP_MD_CTX_copy_ex(&tmp_ctx, ctx) || - !EVP_DigestFinal_ex(&tmp_ctx, m, &m_len)) { - goto out; + uint8_t m[EVP_MAX_MD_SIZE]; + unsigned m_len; + bssl::ScopedEVP_MD_CTX tmp_ctx; + if (!EVP_MD_CTX_copy_ex(tmp_ctx.get(), ctx) || + !EVP_DigestFinal_ex(tmp_ctx.get(), m, &m_len)) { + return 0; } - EVP_MD_CTX_cleanup(&tmp_ctx); - pkctx = EVP_PKEY_CTX_new(pkey, NULL); + bssl::UniquePtr pkctx(EVP_PKEY_CTX_new(pkey, nullptr)); if (!pkctx || // - !EVP_PKEY_sign_init(pkctx) || - !EVP_PKEY_CTX_set_signature_md(pkctx, ctx->digest) || - !EVP_PKEY_sign(pkctx, sig, &sig_len, m, m_len)) { - goto out; + !EVP_PKEY_sign_init(pkctx.get()) || + !EVP_PKEY_CTX_set_signature_md(pkctx.get(), ctx->digest) || + !EVP_PKEY_sign(pkctx.get(), sig, &sig_len, m, m_len)) { + return 0; } - *out_sig_len = (unsigned)sig_len; - ret = 1; - -out: - EVP_PKEY_CTX_free(pkctx); - return ret; + *out_sig_len = static_cast(sig_len); + return 1; } int EVP_VerifyInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl) { @@ -82,28 +78,18 @@ int EVP_VerifyFinal(EVP_MD_CTX *ctx, const uint8_t *sig, size_t sig_len, EVP_PKEY *pkey) { uint8_t m[EVP_MAX_MD_SIZE]; unsigned m_len; - int ret = 0; - EVP_MD_CTX tmp_ctx; - EVP_PKEY_CTX *pkctx = NULL; - - EVP_MD_CTX_init(&tmp_ctx); - if (!EVP_MD_CTX_copy_ex(&tmp_ctx, ctx) || - !EVP_DigestFinal_ex(&tmp_ctx, m, &m_len)) { - EVP_MD_CTX_cleanup(&tmp_ctx); - goto out; + bssl::ScopedEVP_MD_CTX tmp_ctx; + if (!EVP_MD_CTX_copy_ex(tmp_ctx.get(), ctx) || + !EVP_DigestFinal_ex(tmp_ctx.get(), m, &m_len)) { + return 0; } - EVP_MD_CTX_cleanup(&tmp_ctx); - pkctx = EVP_PKEY_CTX_new(pkey, NULL); + bssl::UniquePtr pkctx(EVP_PKEY_CTX_new(pkey, nullptr)); if (!pkctx || - !EVP_PKEY_verify_init(pkctx) || - !EVP_PKEY_CTX_set_signature_md(pkctx, ctx->digest)) { - goto out; + !EVP_PKEY_verify_init(pkctx.get()) || + !EVP_PKEY_CTX_set_signature_md(pkctx.get(), ctx->digest)) { + return 0; } - ret = EVP_PKEY_verify(pkctx, sig, sig_len, m, m_len); - -out: - EVP_PKEY_CTX_free(pkctx); - return ret; + return EVP_PKEY_verify(pkctx.get(), sig, sig_len, m, m_len); } diff --git a/Sources/CNIOBoringSSL/crypto/ex_data.cc b/Sources/CNIOBoringSSL/crypto/ex_data.cc index 9ae6bd82..e12fd819 100644 --- a/Sources/CNIOBoringSSL/crypto/ex_data.cc +++ b/Sources/CNIOBoringSSL/crypto/ex_data.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,47 +22,45 @@ #include #include #include -#include #include "internal.h" +#include "mem_internal.h" -DEFINE_STACK_OF(CRYPTO_EX_DATA_FUNCS) +BSSL_NAMESPACE_BEGIN -struct crypto_ex_data_func_st { - long argl; // Arbitary long - void *argp; // Arbitary void pointer +struct ExDataFuncs { + long argl; // Arbitrary long + void *argp; // Arbitrary void pointer CRYPTO_EX_free *free_func; - // next points to the next |CRYPTO_EX_DATA_FUNCS| or NULL if this is the last - // one. It may only be read if synchronized with a read from |num_funcs|. - CRYPTO_EX_DATA_FUNCS *next; + // next points to the next `ExDataFuncs` or NULL if this is the last + // one. It may only be read if synchronized with a read from `num_funcs`. + ExDataFuncs *next; }; -int CRYPTO_get_ex_new_index_ex(CRYPTO_EX_DATA_CLASS *ex_data_class, long argl, +int CRYPTO_get_ex_new_index_ex(ExDataClass *ex_data_class, long argl, void *argp, CRYPTO_EX_free *free_func) { - CRYPTO_EX_DATA_FUNCS *funcs = reinterpret_cast( - OPENSSL_malloc(sizeof(CRYPTO_EX_DATA_FUNCS))); - if (funcs == NULL) { + ExDataFuncs *funcs = New(); + if (funcs == nullptr) { return -1; } funcs->argl = argl; funcs->argp = argp; funcs->free_func = free_func; - funcs->next = NULL; + funcs->next = nullptr; - CRYPTO_MUTEX_lock_write(&ex_data_class->lock); + MutexWriteLock lock(&ex_data_class->lock); - uint32_t num_funcs = CRYPTO_atomic_load_u32(&ex_data_class->num_funcs); - // The index must fit in |int|. + uint32_t num_funcs = ex_data_class->num_funcs.load(); + // The index must fit in `int`. if (num_funcs > (size_t)(INT_MAX - ex_data_class->num_reserved)) { OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW); - CRYPTO_MUTEX_unlock_write(&ex_data_class->lock); return -1; } - // Append |funcs| to the linked list. - if (ex_data_class->last == NULL) { + // Append `funcs` to the linked list. + if (ex_data_class->last == nullptr) { assert(num_funcs == 0); ex_data_class->funcs = funcs; ex_data_class->last = funcs; @@ -66,29 +69,28 @@ int CRYPTO_get_ex_new_index_ex(CRYPTO_EX_DATA_CLASS *ex_data_class, long argl, ex_data_class->last = funcs; } - CRYPTO_atomic_store_u32(&ex_data_class->num_funcs, num_funcs + 1); - CRYPTO_MUTEX_unlock_write(&ex_data_class->lock); + ex_data_class->num_funcs.store(num_funcs + 1); return (int)num_funcs + ex_data_class->num_reserved; } int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int index, void *val) { if (index < 0) { // A caller that can accidentally pass in an invalid index into this - // function will hit an memory error if |index| happened to be valid, and - // expected |val| to be of a different type. + // function will hit a memory error if `index` happened to be valid, and + // expected `val` to be of a different type. abort(); } - if (ad->sk == NULL) { + if (ad->sk == nullptr) { ad->sk = sk_void_new_null(); - if (ad->sk == NULL) { + if (ad->sk == nullptr) { return 0; } } // Add NULL values until the stack is long enough. for (size_t i = sk_void_num(ad->sk); i <= (size_t)index; i++) { - if (!sk_void_push(ad->sk, NULL)) { + if (!sk_void_push(ad->sk, nullptr)) { return 0; } } @@ -98,39 +100,41 @@ int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int index, void *val) { } void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int idx) { - if (ad->sk == NULL || idx < 0 || (size_t)idx >= sk_void_num(ad->sk)) { - return NULL; + if (ad->sk == nullptr || idx < 0 || (size_t)idx >= sk_void_num(ad->sk)) { + return nullptr; } return sk_void_value(ad->sk, idx); } -void CRYPTO_new_ex_data(CRYPTO_EX_DATA *ad) { ad->sk = NULL; } +void CRYPTO_new_ex_data(CRYPTO_EX_DATA *ad) { ad->sk = nullptr; } -void CRYPTO_free_ex_data(CRYPTO_EX_DATA_CLASS *ex_data_class, void *obj, - CRYPTO_EX_DATA *ad) { - if (ad->sk == NULL) { +void CRYPTO_free_ex_data(ExDataClass *ex_data_class, CRYPTO_EX_DATA *ad) { + if (ad->sk == nullptr) { // Nothing to do. return; } - uint32_t num_funcs = CRYPTO_atomic_load_u32(&ex_data_class->num_funcs); - // |CRYPTO_get_ex_new_index_ex| will not allocate indices beyond |INT_MAX|. + uint32_t num_funcs = ex_data_class->num_funcs.load(); + // `CRYPTO_get_ex_new_index_ex` will not allocate indices beyond `INT_MAX`. assert(num_funcs <= (size_t)(INT_MAX - ex_data_class->num_reserved)); - // Defer dereferencing |ex_data_class->funcs| and |funcs->next|. It must come - // after the |num_funcs| comparison to be correctly synchronized. - CRYPTO_EX_DATA_FUNCS *const *funcs = &ex_data_class->funcs; + // Defer dereferencing `ex_data_class->funcs` and `funcs->next`. It must come + // after the `num_funcs` comparison to be correctly synchronized. + ExDataFuncs *const *funcs = &ex_data_class->funcs; for (uint32_t i = 0; i < num_funcs; i++) { - if ((*funcs)->free_func != NULL) { + if ((*funcs)->free_func != nullptr) { int index = (int)i + ex_data_class->num_reserved; void *ptr = CRYPTO_get_ex_data(ad, index); - (*funcs)->free_func(obj, ptr, ad, index, (*funcs)->argl, (*funcs)->argp); + (*funcs)->free_func(/*parent=*/nullptr, ptr, /*ad*/ nullptr, index, + (*funcs)->argl, (*funcs)->argp); } funcs = &(*funcs)->next; } sk_void_free(ad->sk); - ad->sk = NULL; + ad->sk = nullptr; } -void CRYPTO_cleanup_all_ex_data(void) {} +BSSL_NAMESPACE_END + +void CRYPTO_cleanup_all_ex_data() {} diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/aes.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/aes.cc.inc index e7859e01..f18906b0 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/aes.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/aes.cc.inc @@ -1,25 +1,32 @@ -/* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ - -#include +// Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../bcm_interface.h" #include "internal.h" -// Be aware that different sets of AES functions use incompatible key -// representations, varying in format of the key schedule, the |AES_KEY.rounds| -// value, or both. Therefore they cannot mix. Also, on AArch64, the plain-C -// code, above, is incompatible with the |aes_hw_*| functions. +using namespace bssl; -void AES_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { +// Be aware that different sets of AES functions use incompatible key +// representations, varying in format of the key schedule, the `AES_KEY.rounds` +// value, or both. Therefore they cannot mix. Also, on AArch64, the plain-C +// code, above, is incompatible with the `aes_hw_*` functions. + +bcm_infallible bssl::BCM_aes_encrypt(const uint8_t *in, uint8_t *out, + const AES_KEY *key) { if (hwaes_capable()) { aes_hw_encrypt(in, out, key); } else if (vpaes_capable()) { @@ -27,9 +34,11 @@ void AES_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { } else { aes_nohw_encrypt(in, out, key); } + return bcm_infallible::not_approved; } -void AES_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { +bcm_infallible bssl::BCM_aes_decrypt(const uint8_t *in, uint8_t *out, + const AES_KEY *key) { if (hwaes_capable()) { aes_hw_decrypt(in, out, key); } else if (vpaes_capable()) { @@ -37,39 +46,49 @@ void AES_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { } else { aes_nohw_decrypt(in, out, key); } + return bcm_infallible::not_approved; } -int AES_set_encrypt_key(const uint8_t *key, unsigned bits, AES_KEY *aeskey) { - if (bits != 128 && bits != 192 && bits != 256) { - return -2; - } +bcm_status bssl::BCM_aes_set_encrypt_key(const uint8_t *key, unsigned bits, + AES_KEY *aeskey) { + int ret = -1; if (hwaes_capable()) { - return aes_hw_set_encrypt_key(key, bits, aeskey); + ret = aes_hw_set_encrypt_key(key, bits, aeskey); } else if (vpaes_capable()) { - return vpaes_set_encrypt_key(key, bits, aeskey); + ret = vpaes_set_encrypt_key(key, bits, aeskey); } else { - return aes_nohw_set_encrypt_key(key, bits, aeskey); + ret = aes_nohw_set_encrypt_key(key, bits, aeskey); } + if (ret < 0) { + return bcm_status::failure; + } + BSSL_CHECK(ret == 0); + return bcm_status::not_approved; } -int AES_set_decrypt_key(const uint8_t *key, unsigned bits, AES_KEY *aeskey) { - if (bits != 128 && bits != 192 && bits != 256) { - return -2; - } +bcm_status bssl::BCM_aes_set_decrypt_key(const uint8_t *key, unsigned bits, + AES_KEY *aeskey) { + int ret = -1; if (hwaes_capable()) { - return aes_hw_set_decrypt_key(key, bits, aeskey); + ret = aes_hw_set_decrypt_key(key, bits, aeskey); } else if (vpaes_capable()) { - return vpaes_set_decrypt_key(key, bits, aeskey); + ret = vpaes_set_decrypt_key(key, bits, aeskey); } else { - return aes_nohw_set_decrypt_key(key, bits, aeskey); + ret = aes_nohw_set_decrypt_key(key, bits, aeskey); } + if (ret < 0) { + return bcm_status::failure; + } + BSSL_CHECK(ret == 0); + return bcm_status::not_approved; } #if defined(HWAES) && (defined(OPENSSL_X86) || defined(OPENSSL_X86_64)) -// On x86 and x86_64, |aes_hw_set_decrypt_key|, we implement -// |aes_hw_encrypt_key_to_decrypt_key| in assembly and rely on C code to combine +// On x86 and x86_64, `aes_hw_set_decrypt_key`, we implement +// `aes_hw_encrypt_key_to_decrypt_key` in assembly and rely on C code to combine // the operations. -int aes_hw_set_decrypt_key(const uint8_t *user_key, int bits, AES_KEY *key) { +int bssl::aes_hw_set_decrypt_key(const uint8_t *user_key, int bits, + AES_KEY *key) { int ret = aes_hw_set_encrypt_key(user_key, bits, key); if (ret == 0) { aes_hw_encrypt_key_to_decrypt_key(key); @@ -77,7 +96,8 @@ int aes_hw_set_decrypt_key(const uint8_t *user_key, int bits, AES_KEY *key) { return ret; } -int aes_hw_set_encrypt_key(const uint8_t *user_key, int bits, AES_KEY *key) { +int bssl::aes_hw_set_encrypt_key(const uint8_t *user_key, int bits, + AES_KEY *key) { if (aes_hw_set_encrypt_key_alt_preferred()) { return aes_hw_set_encrypt_key_alt(user_key, bits, key); } else { @@ -87,10 +107,11 @@ int aes_hw_set_encrypt_key(const uint8_t *user_key, int bits, AES_KEY *key) { #endif #if defined(VPAES) && defined(OPENSSL_X86) -// On x86, there is no |vpaes_ctr32_encrypt_blocks|, so we implement it +// On x86, there is no `vpaes_ctr32_encrypt_blocks`, so we implement it // ourselves. This avoids all callers needing to account for a missing function. -void vpaes_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, size_t blocks, - const AES_KEY *key, const uint8_t iv[16]) { +void bssl::vpaes_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, + size_t blocks, const AES_KEY *key, + const uint8_t iv[16]) { uint32_t ctr = CRYPTO_load_u32_be(iv + 12); uint8_t iv_buf[16], enc[16]; OPENSSL_memcpy(iv_buf, iv, 12); @@ -106,10 +127,11 @@ void vpaes_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, size_t blocks, #endif #if defined(BSAES) -void vpaes_ctr32_encrypt_blocks_with_bsaes(const uint8_t *in, uint8_t *out, - size_t blocks, const AES_KEY *key, - const uint8_t ivec[16]) { - // |bsaes_ctr32_encrypt_blocks| is faster than |vpaes_ctr32_encrypt_blocks|, +void bssl::vpaes_ctr32_encrypt_blocks_with_bsaes(const uint8_t *in, + uint8_t *out, size_t blocks, + const AES_KEY *key, + const uint8_t ivec[16]) { + // `bsaes_ctr32_encrypt_blocks` is faster than `vpaes_ctr32_encrypt_blocks`, // but it takes at least one full 8-block batch to amortize the conversion. if (blocks < 8) { vpaes_ctr32_encrypt_blocks(in, out, blocks, key, ivec); @@ -118,9 +140,9 @@ void vpaes_ctr32_encrypt_blocks_with_bsaes(const uint8_t *in, uint8_t *out, size_t bsaes_blocks = blocks; if (bsaes_blocks % 8 < 6) { - // |bsaes_ctr32_encrypt_blocks| internally works in 8-block batches. If the + // `bsaes_ctr32_encrypt_blocks` internally works in 8-block batches. If the // final batch is too small (under six blocks), it is faster to loop over - // |vpaes_encrypt|. Round |bsaes_blocks| down to a multiple of 8. + // `vpaes_encrypt`. Round `bsaes_blocks` down to a multiple of 8. bsaes_blocks -= bsaes_blocks % 8; } @@ -138,14 +160,14 @@ void vpaes_ctr32_encrypt_blocks_with_bsaes(const uint8_t *in, uint8_t *out, uint32_t ctr = CRYPTO_load_u32_be(ivec + 12) + bsaes_blocks; CRYPTO_store_u32_be(new_ivec + 12, ctr); - // Finish any remaining blocks with |vpaes_ctr32_encrypt_blocks|. + // Finish any remaining blocks with `vpaes_ctr32_encrypt_blocks`. vpaes_ctr32_encrypt_blocks(in, out, blocks, key, new_ivec); } #endif // BSAES -ctr128_f aes_ctr_set_key(AES_KEY *aes_key, int *out_is_hwaes, - block128_f *out_block, const uint8_t *key, - size_t key_bytes) { +ctr128_f bssl::aes_ctr_set_key(AES_KEY *aes_key, int *out_is_hwaes, + block128_f *out_block, const uint8_t *key, + size_t key_bytes) { // This function assumes the key length was previously validated. assert(key_bytes == 128 / 8 || key_bytes == 192 / 8 || key_bytes == 256 / 8); if (hwaes_capable()) { diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/aes_nohw.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/aes_nohw.cc.inc index 5bc7194d..7288c5ff 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/aes_nohw.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/aes_nohw.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2019 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2019 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 @@ -25,6 +25,8 @@ #endif +using namespace bssl; + // This file contains a constant-time implementation of AES, bitsliced with // 32-bit, 64-bit, or 128-bit words, operating on two-, four-, and eight-block // batches, respectively. The 128-bit implementation requires SSE2 intrinsics. @@ -43,18 +45,18 @@ // shifts match the operations themselves, which makes them reversed in a // little-endian, left-to-right reading. // -// Eight |aes_word_t|s contain |AES_NOHW_BATCH_SIZE| blocks. The bits in an -// |aes_word_t| are divided into 16 consecutive groups of |AES_NOHW_BATCH_SIZE| +// Eight `aes_word_t`s contain `AES_NOHW_BATCH_SIZE` blocks. The bits in an +// `aes_word_t` are divided into 16 consecutive groups of `AES_NOHW_BATCH_SIZE` // bits each, each corresponding to a byte in an AES block in column-major // order (AES's byte order). We refer to these as "logical bytes". Note, in the // 32-bit and 64-bit implementations, they are smaller than a byte. (The // contents of a logical byte will be described later.) // -// MSVC does not support C bit operators on |__m128i|, so the wrapper functions -// |aes_nohw_and|, etc., should be used instead. Note |aes_nohw_shift_left| and -// |aes_nohw_shift_right| measure the shift in logical bytes. That is, the shift -// value ranges from 0 to 15 independent of |aes_word_t| and -// |AES_NOHW_BATCH_SIZE|. +// MSVC does not support C bit operators on `__m128i`, so the wrapper functions +// `aes_nohw_and`, etc., should be used instead. Note `aes_nohw_shift_left` and +// `aes_nohw_shift_right` measure the shift in logical bytes. That is, the shift +// value ranges from 0 to 15 independent of `aes_word_t` and +// `AES_NOHW_BATCH_SIZE`. // // This ordering is different from https://eprint.iacr.org/2009/129.pdf, which // uses row-major order. Matching the AES order was easier to reason about, and @@ -81,24 +83,24 @@ typedef __m128i aes_word_t; #define AES_NOHW_COL3_MASK \ _mm_set_epi32(0xffffffff, 0x00000000, 0x00000000, 0x00000000) -static inline aes_word_t aes_nohw_and(aes_word_t a, aes_word_t b) { +static aes_word_t aes_nohw_and(aes_word_t a, aes_word_t b) { return _mm_and_si128(a, b); } -static inline aes_word_t aes_nohw_or(aes_word_t a, aes_word_t b) { +static aes_word_t aes_nohw_or(aes_word_t a, aes_word_t b) { return _mm_or_si128(a, b); } -static inline aes_word_t aes_nohw_xor(aes_word_t a, aes_word_t b) { +static aes_word_t aes_nohw_xor(aes_word_t a, aes_word_t b) { return _mm_xor_si128(a, b); } -static inline aes_word_t aes_nohw_not(aes_word_t a) { +static aes_word_t aes_nohw_not(aes_word_t a) { return _mm_xor_si128( a, _mm_set_epi32(0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff)); } -// These are macros because parameters to |_mm_slli_si128| and |_mm_srli_si128| +// These are macros because parameters to `_mm_slli_si128` and `_mm_srli_si128` // must be constants. #define aes_nohw_shift_left(/* aes_word_t */ a, /* const */ i) \ _mm_slli_si128((a), (i)) @@ -129,25 +131,19 @@ typedef uint32_t aes_word_t; #define AES_NOHW_COL3_MASK 0xff000000 #endif // OPENSSL_64_BIT -static inline aes_word_t aes_nohw_and(aes_word_t a, aes_word_t b) { - return a & b; -} +static aes_word_t aes_nohw_and(aes_word_t a, aes_word_t b) { return a & b; } -static inline aes_word_t aes_nohw_or(aes_word_t a, aes_word_t b) { - return a | b; -} +static aes_word_t aes_nohw_or(aes_word_t a, aes_word_t b) { return a | b; } -static inline aes_word_t aes_nohw_xor(aes_word_t a, aes_word_t b) { - return a ^ b; -} +static aes_word_t aes_nohw_xor(aes_word_t a, aes_word_t b) { return a ^ b; } -static inline aes_word_t aes_nohw_not(aes_word_t a) { return ~a; } +static aes_word_t aes_nohw_not(aes_word_t a) { return ~a; } -static inline aes_word_t aes_nohw_shift_left(aes_word_t a, aes_word_t i) { +static aes_word_t aes_nohw_shift_left(aes_word_t a, aes_word_t i) { return a << (i * AES_NOHW_BATCH_SIZE); } -static inline aes_word_t aes_nohw_shift_right(aes_word_t a, aes_word_t i) { +static aes_word_t aes_nohw_shift_right(aes_word_t a, aes_word_t i) { return a >> (i * AES_NOHW_BATCH_SIZE); } #endif // OPENSSL_SSE2 @@ -162,8 +158,8 @@ static_assert(AES_NOHW_WORD_SIZE == sizeof(aes_word_t), // // This implementation uses three representations for AES blocks. First, the // public API represents blocks as uint8_t[16] in the usual way. Second, most -// AES steps are evaluated in bitsliced form, stored in an |AES_NOHW_BATCH|. -// This stores |AES_NOHW_BATCH_SIZE| blocks in bitsliced order. For 64-bit words +// AES steps are evaluated in bitsliced form, stored in an `AES_NOHW_BATCH`. +// This stores `AES_NOHW_BATCH_SIZE` blocks in bitsliced order. For 64-bit words // containing bitsliced blocks a, b, c, d, this would be as follows (vertical // bars divide logical bytes): // @@ -176,10 +172,10 @@ static_assert(AES_NOHW_WORD_SIZE == sizeof(aes_word_t), // Finally, an individual block may be stored as an intermediate form in an // aes_word_t[AES_NOHW_BLOCK_WORDS]. In this form, we permute the bits in each // block, so that block[0]'s ith logical byte contains least-significant -// |AES_NOHW_BATCH_SIZE| bits of byte i, block[1] contains the next group of -// |AES_NOHW_BATCH_SIZE| bits, and so on. We refer to this transformation as +// `AES_NOHW_BATCH_SIZE` bits of byte i, block[1] contains the next group of +// `AES_NOHW_BATCH_SIZE` bits, and so on. We refer to this transformation as // "compacting" the block. Note this is no-op with 128-bit words because then -// |AES_NOHW_BLOCK_WORDS| is one and |AES_NOHW_BATCH_SIZE| is eight. For 64-bit +// `AES_NOHW_BLOCK_WORDS` is one and `AES_NOHW_BATCH_SIZE` is eight. For 64-bit // words, one block would be stored in two words: // // block[0] = a0 a1 a2 a3 | a8 a9 a10 a11 | a16 a17 a18 a19 ... @@ -187,8 +183,8 @@ static_assert(AES_NOHW_WORD_SIZE == sizeof(aes_word_t), // // Observe that the distances between corresponding bits in bitsliced and // compact bit orders match. If we line up corresponding words of each block, -// the bitsliced and compact representations may be converted by tranposing bits -// in corresponding logical bytes. Continuing the 64-bit example: +// the bitsliced and compact representations may be converted by transposing +// bits in corresponding logical bytes. Continuing the 64-bit example: // // block_a[0] = a0 a1 a2 a3 | a8 a9 a10 a11 | a16 a17 a18 a19 ... // block_b[0] = b0 b1 b2 b3 | b8 b9 b10 b11 | b16 b17 b18 b19 ... @@ -201,40 +197,40 @@ static_assert(AES_NOHW_WORD_SIZE == sizeof(aes_word_t), // batch.w[3] = a3 b3 c3 d3 | a11 b11 c11 d11 | a19 b19 c19 d19 ... // // Note also that bitwise operations and (logical) byte permutations on an -// |aes_word_t| work equally for the bitsliced and compact words. +// `aes_word_t` work equally for the bitsliced and compact words. // -// We use the compact form in the |AES_KEY| representation to save work -// inflating round keys into |AES_NOHW_BATCH|. The compact form also exists -// temporarily while moving blocks in or out of an |AES_NOHW_BATCH|, immediately -// before or after |aes_nohw_transpose|. +// We use the compact form in the `AES_KEY` representation to save work +// inflating round keys into `AES_NOHW_BATCH`. The compact form also exists +// temporarily while moving blocks in or out of an `AES_NOHW_BATCH`, immediately +// before or after `aes_nohw_transpose`. #define AES_NOHW_BLOCK_WORDS (16 / sizeof(aes_word_t)) -// An AES_NOHW_BATCH stores |AES_NOHW_BATCH_SIZE| blocks. Unless otherwise +// An AES_NOHW_BATCH stores `AES_NOHW_BATCH_SIZE` blocks. Unless otherwise // specified, it is in bitsliced form. typedef struct { aes_word_t w[8]; } AES_NOHW_BATCH; // An AES_NOHW_SCHEDULE is an expanded bitsliced AES key schedule. It is -// suitable for encryption or decryption. It is as large as |AES_NOHW_BATCH| -// |AES_KEY|s so it should not be used as a long-term key representation. +// suitable for encryption or decryption. It is as large as `AES_NOHW_BATCH` +// `AES_KEY`s so it should not be used as a long-term key representation. typedef struct { // keys is an array of batches, one for each round key. Each batch stores - // |AES_NOHW_BATCH_SIZE| copies of the round key in bitsliced form. + // `AES_NOHW_BATCH_SIZE` copies of the round key in bitsliced form. AES_NOHW_BATCH keys[AES_MAXNR + 1]; } AES_NOHW_SCHEDULE; -// aes_nohw_batch_set sets the |i|th block of |batch| to |in|. |batch| is in +// aes_nohw_batch_set sets the `i`th block of `batch` to `in`. `batch` is in // compact form. -static inline void aes_nohw_batch_set(AES_NOHW_BATCH *batch, - const aes_word_t in[AES_NOHW_BLOCK_WORDS], - size_t i) { - // Note the words are interleaved. The order comes from |aes_nohw_transpose|. - // If |i| is zero and this is the 64-bit implementation, in[0] contains bits +static void aes_nohw_batch_set(AES_NOHW_BATCH *batch, + const aes_word_t in[AES_NOHW_BLOCK_WORDS], + size_t i) { + // Note the words are interleaved. The order comes from `aes_nohw_transpose`. + // If `i` is zero and this is the 64-bit implementation, in[0] contains bits // 0-3 and in[1] contains bits 4-7. We place in[0] at w[0] and in[1] at // w[4] so that bits 0 and 4 are in the correct position. (In general, bits - // along diagonals of |AES_NOHW_BATCH_SIZE| by |AES_NOHW_BATCH_SIZE| squares + // along diagonals of `AES_NOHW_BATCH_SIZE` by `AES_NOHW_BATCH_SIZE` squares // will be correctly placed.) assert(i < AES_NOHW_BATCH_SIZE); #if defined(OPENSSL_SSE2) @@ -250,11 +246,10 @@ static inline void aes_nohw_batch_set(AES_NOHW_BATCH *batch, #endif } -// aes_nohw_batch_get writes the |i|th block of |batch| to |out|. |batch| is in +// aes_nohw_batch_get writes the `i`th block of `batch` to `out`. `batch` is in // compact form. -static inline void aes_nohw_batch_get(const AES_NOHW_BATCH *batch, - aes_word_t out[AES_NOHW_BLOCK_WORDS], - size_t i) { +static void aes_nohw_batch_get(const AES_NOHW_BATCH *batch, + aes_word_t out[AES_NOHW_BLOCK_WORDS], size_t i) { assert(i < AES_NOHW_BATCH_SIZE); #if defined(OPENSSL_SSE2) out[0] = batch->w[i]; @@ -270,10 +265,10 @@ static inline void aes_nohw_batch_get(const AES_NOHW_BATCH *batch, } #if !defined(OPENSSL_SSE2) -// aes_nohw_delta_swap returns |a| with bits |a & mask| and -// |a & (mask << shift)| swapped. |mask| and |mask << shift| may not overlap. -static inline aes_word_t aes_nohw_delta_swap(aes_word_t a, aes_word_t mask, - aes_word_t shift) { +// aes_nohw_delta_swap returns `a` with bits |a & mask| and +// |a & (mask << shift)| swapped. `mask` and |mask << shift| may not overlap. +static aes_word_t aes_nohw_delta_swap(aes_word_t a, aes_word_t mask, + aes_word_t shift) { // See // https://reflectionsonsecurity.wordpress.com/2014/05/11/efficient-bit-permutation-using-delta-swaps/ aes_word_t b = (a ^ (a >> shift)) & mask; @@ -281,14 +276,14 @@ static inline aes_word_t aes_nohw_delta_swap(aes_word_t a, aes_word_t mask, } // In the 32-bit and 64-bit implementations, a block spans multiple words. -// |aes_nohw_compact_block| must permute bits across different words. First we -// implement |aes_nohw_compact_word| which performs a smaller version of the +// `aes_nohw_compact_block` must permute bits across different words. First we +// implement `aes_nohw_compact_word` which performs a smaller version of the // transformation which stays within a single word. // // These transformations are generalizations of the output of // http://programming.sirrida.de/calcperm.php on smaller inputs. #if defined(OPENSSL_64_BIT) -static inline uint64_t aes_nohw_compact_word(uint64_t a) { +static uint64_t aes_nohw_compact_word(uint64_t a) { // Numbering the 64/2 = 16 4-bit chunks, least to most significant, we swap // quartets of those chunks: // 0 1 2 3 | 4 5 6 7 | 8 9 10 11 | 12 13 14 15 => @@ -305,15 +300,15 @@ static inline uint64_t aes_nohw_compact_word(uint64_t a) { return a; } -static inline uint64_t aes_nohw_uncompact_word(uint64_t a) { - // Reverse the steps of |aes_nohw_uncompact_word|. +static uint64_t aes_nohw_uncompact_word(uint64_t a) { + // Reverse the steps of `aes_nohw_uncompact_word`. a = aes_nohw_delta_swap(a, UINT64_C(0x00000000ffff0000), 16); a = aes_nohw_delta_swap(a, UINT64_C(0x0000ff000000ff00), 8); a = aes_nohw_delta_swap(a, UINT64_C(0x00f000f000f000f0), 4); return a; } #else // !OPENSSL_64_BIT -static inline uint32_t aes_nohw_compact_word(uint32_t a) { +static uint32_t aes_nohw_compact_word(uint32_t a) { // Numbering the 32/2 = 16 pairs of bits, least to most significant, we swap: // 0 1 2 3 | 4 5 6 7 | 8 9 10 11 | 12 13 14 15 => // 0 4 2 6 | 1 5 3 7 | 8 12 10 14 | 9 13 11 15 @@ -328,23 +323,23 @@ static inline uint32_t aes_nohw_compact_word(uint32_t a) { return a; } -static inline uint32_t aes_nohw_uncompact_word(uint32_t a) { - // Reverse the steps of |aes_nohw_uncompact_word|. +static uint32_t aes_nohw_uncompact_word(uint32_t a) { + // Reverse the steps of `aes_nohw_uncompact_word`. a = aes_nohw_delta_swap(a, 0x0000f0f0, 12); a = aes_nohw_delta_swap(a, 0x00cc00cc, 6); return a; } -static inline uint32_t aes_nohw_word_from_bytes(uint8_t a0, uint8_t a1, - uint8_t a2, uint8_t a3) { +static uint32_t aes_nohw_word_from_bytes(uint8_t a0, uint8_t a1, uint8_t a2, + uint8_t a3) { return (uint32_t)a0 | ((uint32_t)a1 << 8) | ((uint32_t)a2 << 16) | ((uint32_t)a3 << 24); } #endif // OPENSSL_64_BIT #endif // !OPENSSL_SSE2 -static inline void aes_nohw_compact_block(aes_word_t out[AES_NOHW_BLOCK_WORDS], - const uint8_t in[16]) { +static void aes_nohw_compact_block(aes_word_t out[AES_NOHW_BLOCK_WORDS], + const uint8_t in[16]) { memcpy(out, in, 16); #if defined(OPENSSL_SSE2) // No conversions needed. @@ -370,7 +365,7 @@ static inline void aes_nohw_compact_block(aes_word_t out[AES_NOHW_BLOCK_WORDS], #endif } -static inline void aes_nohw_uncompact_block( +static void aes_nohw_uncompact_block( uint8_t out[16], const aes_word_t in[AES_NOHW_BLOCK_WORDS]) { #if defined(OPENSSL_SSE2) memcpy(out, in, 16); // No conversions needed. @@ -411,11 +406,11 @@ static inline void aes_nohw_uncompact_block( } // aes_nohw_swap_bits is a variation on a delta swap. It swaps the bits in -// |*a & (mask << shift)| with the bits in |*b & mask|. |mask| and -// |mask << shift| must not overlap. |mask| is specified as a |uint32_t|, but it -// is repeated to the full width of |aes_word_t|. +// `*a & (mask << shift)` with the bits in `*b & mask`. `mask` and +// `mask << shift` must not overlap. `mask` is specified as a `uint32_t`, but it +// is repeated to the full width of `aes_word_t`. #if defined(OPENSSL_SSE2) -// This must be a macro because |_mm_srli_epi32| and |_mm_slli_epi32| require +// This must be a macro because `_mm_srli_epi32` and `_mm_slli_epi32` require // constant shift values. #define aes_nohw_swap_bits(/*__m128i* */ a, /*__m128i* */ b, \ /* uint32_t */ mask, /* const */ shift) \ @@ -428,8 +423,8 @@ static inline void aes_nohw_uncompact_block( \ } while (0) #else -static inline void aes_nohw_swap_bits(aes_word_t *a, aes_word_t *b, - uint32_t mask, aes_word_t shift) { +static void aes_nohw_swap_bits(aes_word_t *a, aes_word_t *b, uint32_t mask, + aes_word_t shift) { #if defined(OPENSSL_64_BIT) aes_word_t mask_w = (((uint64_t)mask) << 32) | mask; #else @@ -442,7 +437,7 @@ static inline void aes_nohw_swap_bits(aes_word_t *a, aes_word_t *b, } #endif // OPENSSL_SSE2 -// aes_nohw_transpose converts |batch| to and from bitsliced form. It divides +// aes_nohw_transpose converts `batch` to and from bitsliced form. It divides // the 8 × word_size bits into AES_NOHW_BATCH_SIZE × AES_NOHW_BATCH_SIZE squares // and transposes each square. static void aes_nohw_transpose(AES_NOHW_BATCH *batch) { @@ -469,8 +464,8 @@ static void aes_nohw_transpose(AES_NOHW_BATCH *batch) { #endif } -// aes_nohw_to_batch initializes |out| with the |num_blocks| blocks from |in|. -// |num_blocks| must be at most |AES_NOHW_BATCH|. +// aes_nohw_to_batch initializes `out` with the `num_blocks` blocks from `in`. +// `num_blocks` must be at most `AES_NOHW_BATCH`. static void aes_nohw_to_batch(AES_NOHW_BATCH *out, const uint8_t *in, size_t num_blocks) { // Don't leave unused blocks uninitialized. @@ -485,8 +480,8 @@ static void aes_nohw_to_batch(AES_NOHW_BATCH *out, const uint8_t *in, aes_nohw_transpose(out); } -// aes_nohw_to_batch writes the first |num_blocks| blocks in |batch| to |out|. -// |num_blocks| must be at most |AES_NOHW_BATCH|. +// aes_nohw_to_batch writes the first `num_blocks` blocks in `batch` to `out`. +// `num_blocks` must be at most `AES_NOHW_BATCH`. static void aes_nohw_from_batch(uint8_t *out, size_t num_blocks, const AES_NOHW_BATCH *batch) { AES_NOHW_BATCH copy = *batch; @@ -701,8 +696,8 @@ static void aes_nohw_inv_sub_bytes(AES_NOHW_BATCH *batch) { aes_nohw_sub_bytes_inv_affine(batch); } -// aes_nohw_rotate_cols_right returns |v| with the columns in each row rotated -// to the right by |n|. This is a macro because |aes_nohw_shift_*| require +// aes_nohw_rotate_cols_right returns `v` with the columns in each row rotated +// to the right by `n`. This is a macro because `aes_nohw_shift_*` require // constant shift counts in the SSE2 implementation. #define aes_nohw_rotate_cols_right(/* aes_word_t */ v, /* const */ n) \ (aes_nohw_or(aes_nohw_shift_right((v), (n)*4), \ @@ -734,9 +729,9 @@ static void aes_nohw_inv_shift_rows(AES_NOHW_BATCH *batch) { } } -// aes_nohw_rotate_rows_down returns |v| with the rows in each column rotated +// aes_nohw_rotate_rows_down returns `v` with the rows in each column rotated // down by one. -static inline aes_word_t aes_nohw_rotate_rows_down(aes_word_t v) { +static aes_word_t aes_nohw_rotate_rows_down(aes_word_t v) { #if defined(OPENSSL_SSE2) return _mm_or_si128(_mm_srli_epi32(v, 8), _mm_slli_epi32(v, 24)); #elif defined(OPENSSL_64_BIT) @@ -747,9 +742,9 @@ static inline aes_word_t aes_nohw_rotate_rows_down(aes_word_t v) { #endif } -// aes_nohw_rotate_rows_twice returns |v| with the rows in each column rotated +// aes_nohw_rotate_rows_twice returns `v` with the rows in each column rotated // by two. -static inline aes_word_t aes_nohw_rotate_rows_twice(aes_word_t v) { +static aes_word_t aes_nohw_rotate_rows_twice(aes_word_t v) { #if defined(OPENSSL_SSE2) return _mm_or_si128(_mm_srli_epi32(v, 16), _mm_slli_epi32(v, 16)); #elif defined(OPENSSL_64_BIT) @@ -828,7 +823,7 @@ static void aes_nohw_inv_mix_columns(AES_NOHW_BATCH *batch) { // | 0d 09 0e 0b | | 01 01 02 03 | | 04 00 05 00 | // | 0b 0d 09 0e | | 03 01 01 02 | | 00 04 00 05 | // - // First, apply the [5 0 4 0] matrix. Multiplying by 4 in F_(2^8) is described + // First, apply the [5 0 4 0] matrix. Multiplying by 4 in F_(2⁸) is described // by the following bit equations: // // b0 = a6 @@ -915,9 +910,9 @@ static void aes_nohw_expand_round_keys(AES_NOHW_SCHEDULE *out, static const uint8_t aes_nohw_rcon[10] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36}; -// aes_nohw_rcon_slice returns the |i|th group of |AES_NOHW_BATCH_SIZE| bits in -// |rcon|, stored in a |aes_word_t|. -static inline aes_word_t aes_nohw_rcon_slice(uint8_t rcon, size_t i) { +// aes_nohw_rcon_slice returns the `i`th group of `AES_NOHW_BATCH_SIZE` bits in +// `rcon`, stored in a `aes_word_t`. +static aes_word_t aes_nohw_rcon_slice(uint8_t rcon, size_t i) { rcon = (rcon >> (i * AES_NOHW_BATCH_SIZE)) & ((1 << AES_NOHW_BATCH_SIZE) - 1); #if defined(OPENSSL_SSE2) return _mm_set_epi32(0, 0, 0, rcon); @@ -949,7 +944,7 @@ static void aes_nohw_setup_key_128(AES_KEY *key, const uint8_t in[16]) { aes_nohw_sub_block(sub, block); uint8_t rcon = aes_nohw_rcon[i - 1]; for (size_t j = 0; j < AES_NOHW_BLOCK_WORDS; j++) { - // Incorporate |rcon| and the transformed word into the first word. + // Incorporate `rcon` and the transformed word into the first word. block[j] = aes_nohw_xor(block[j], aes_nohw_rcon_slice(rcon, j)); block[j] = aes_nohw_xor( block[j], @@ -976,9 +971,9 @@ static void aes_nohw_setup_key_192(AES_KEY *key, const uint8_t in[24]) { // We maintain a sliding window of two blocks, filled to 1.5 blocks at a time. // We loop below every three blocks or two key schedule iterations. // - // On entry to the loop, |block1| and the first half of |block2| contain the - // previous key schedule iteration. |block1| has been written to |key|, but - // |block2| has not as it is incomplete. + // On entry to the loop, `block1` and the first half of `block2` contain the + // previous key schedule iteration. `block1` has been written to `key`, but + // `block2` has not as it is incomplete. aes_nohw_compact_block(block1, in); memcpy(key->rd_key, block1, 16); @@ -992,17 +987,17 @@ static void aes_nohw_setup_key_192(AES_KEY *key, const uint8_t in[24]) { uint8_t rcon = aes_nohw_rcon[2 * i]; for (size_t j = 0; j < AES_NOHW_BLOCK_WORDS; j++) { // Compute the first two words of the next key schedule iteration, which - // go in the second half of |block2|. The first two words of the previous - // iteration are in the first half of |block1|. Apply |rcon| here too + // go in the second half of `block2`. The first two words of the previous + // iteration are in the first half of `block1`. Apply `rcon` here too // because the shifts match. block2[j] = aes_nohw_or( block2[j], aes_nohw_shift_left( aes_nohw_xor(block1[j], aes_nohw_rcon_slice(rcon, j)), 8)); // Incorporate the transformed word and propagate. Note the last word of - // the previous iteration corresponds to the second word of |copy|. This + // the previous iteration corresponds to the second word of `copy`. This // is incorporated into the first word of the next iteration, or the third - // word of |block2|. + // word of `block2`. block2[j] = aes_nohw_xor( block2[j], aes_nohw_and(aes_nohw_shift_left( aes_nohw_rotate_rows_down(sub[j]), 4), @@ -1011,12 +1006,12 @@ static void aes_nohw_setup_key_192(AES_KEY *key, const uint8_t in[24]) { block2[j], aes_nohw_and(aes_nohw_shift_left(block2[j], 4), AES_NOHW_COL3_MASK)); - // Compute the remaining four words, which fill |block1|. Begin by moving + // Compute the remaining four words, which fill `block1`. Begin by moving // the corresponding words of the previous iteration: the second half of - // |block1| and the first half of |block2|. + // `block1` and the first half of `block2`. block1[j] = aes_nohw_shift_right(block1[j], 8); block1[j] = aes_nohw_or(block1[j], aes_nohw_shift_left(block2[j], 8)); - // Incorporate the second word, computed previously in |block2|, and + // Incorporate the second word, computed previously in `block2`, and // propagate. block1[j] = aes_nohw_xor(block1[j], aes_nohw_shift_right(block2[j], 12)); aes_word_t v = block1[j]; @@ -1025,7 +1020,7 @@ static void aes_nohw_setup_key_192(AES_KEY *key, const uint8_t in[24]) { block1[j] = aes_nohw_xor(block1[j], aes_nohw_shift_left(v, 12)); } - // This completes two round keys. Note half of |block2| was computed in the + // This completes two round keys. Note half of `block2` was computed in the // previous loop iteration but was not yet output. memcpy(key->rd_key + 4 * (3 * i + 1), block2, 16); memcpy(key->rd_key + 4 * (3 * i + 2), block1, 16); @@ -1034,12 +1029,12 @@ static void aes_nohw_setup_key_192(AES_KEY *key, const uint8_t in[24]) { rcon = aes_nohw_rcon[2 * i + 1]; for (size_t j = 0; j < AES_NOHW_BLOCK_WORDS; j++) { // Compute the first four words of the next key schedule iteration in - // |block2|. Begin by moving the corresponding words of the previous - // iteration: the second half of |block2| and the first half of |block1|. + // `block2`. Begin by moving the corresponding words of the previous + // iteration: the second half of `block2` and the first half of `block1`. block2[j] = aes_nohw_shift_right(block2[j], 8); block2[j] = aes_nohw_or(block2[j], aes_nohw_shift_left(block1[j], 8)); // Incorporate rcon and the transformed word. Note the last word of the - // previous iteration corresponds to the last word of |copy|. + // previous iteration corresponds to the last word of `copy`. block2[j] = aes_nohw_xor(block2[j], aes_nohw_rcon_slice(rcon, j)); block2[j] = aes_nohw_xor( block2[j], @@ -1050,9 +1045,9 @@ static void aes_nohw_setup_key_192(AES_KEY *key, const uint8_t in[24]) { block2[j] = aes_nohw_xor(block2[j], aes_nohw_shift_left(v, 8)); block2[j] = aes_nohw_xor(block2[j], aes_nohw_shift_left(v, 12)); - // Compute the last two words, which go in the first half of |block1|. The + // Compute the last two words, which go in the first half of `block1`. The // last two words of the previous iteration are in the second half of - // |block1|. + // `block1`. block1[j] = aes_nohw_shift_right(block1[j], 8); // Propagate blocks and mask off the excess. block1[j] = aes_nohw_xor(block1[j], aes_nohw_shift_right(block2[j], 12)); @@ -1060,7 +1055,7 @@ static void aes_nohw_setup_key_192(AES_KEY *key, const uint8_t in[24]) { block1[j] = aes_nohw_and(block1[j], AES_NOHW_COL01_MASK); } - // |block2| has a complete round key. |block1| will be completed in the next + // `block2` has a complete round key. `block1` will be completed in the next // iteration. memcpy(key->rd_key + 4 * (3 * i + 3), block2, 16); @@ -1087,7 +1082,7 @@ static void aes_nohw_setup_key_256(AES_KEY *key, const uint8_t in[32]) { aes_nohw_sub_block(sub, block2); uint8_t rcon = aes_nohw_rcon[i / 2 - 1]; for (size_t j = 0; j < AES_NOHW_BLOCK_WORDS; j++) { - // Incorporate |rcon| and the transformed word into the first word. + // Incorporate `rcon` and the transformed word into the first word. block1[j] = aes_nohw_xor(block1[j], aes_nohw_rcon_slice(rcon, j)); block1[j] = aes_nohw_xor( block1[j], @@ -1121,8 +1116,8 @@ static void aes_nohw_setup_key_256(AES_KEY *key, const uint8_t in[32]) { // External API. -int aes_nohw_set_encrypt_key(const uint8_t *key, unsigned bits, - AES_KEY *aeskey) { +int bssl::aes_nohw_set_encrypt_key(const uint8_t *key, unsigned bits, + AES_KEY *aeskey) { switch (bits) { case 128: aes_nohw_setup_key_128(aeskey, key); @@ -1137,12 +1132,13 @@ int aes_nohw_set_encrypt_key(const uint8_t *key, unsigned bits, return 1; } -int aes_nohw_set_decrypt_key(const uint8_t *key, unsigned bits, - AES_KEY *aeskey) { +int bssl::aes_nohw_set_decrypt_key(const uint8_t *key, unsigned bits, + AES_KEY *aeskey) { return aes_nohw_set_encrypt_key(key, bits, aeskey); } -void aes_nohw_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { +void bssl::aes_nohw_encrypt(const uint8_t *in, uint8_t *out, + const AES_KEY *key) { AES_NOHW_SCHEDULE sched; aes_nohw_expand_round_keys(&sched, key); AES_NOHW_BATCH batch; @@ -1151,7 +1147,8 @@ void aes_nohw_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { aes_nohw_from_batch(out, /*num_blocks=*/1, &batch); } -void aes_nohw_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { +void bssl::aes_nohw_decrypt(const uint8_t *in, uint8_t *out, + const AES_KEY *key) { AES_NOHW_SCHEDULE sched; aes_nohw_expand_round_keys(&sched, key); AES_NOHW_BATCH batch; @@ -1160,8 +1157,8 @@ void aes_nohw_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { aes_nohw_from_batch(out, /*num_blocks=*/1, &batch); } -static inline void aes_nohw_xor_block(uint8_t out[16], const uint8_t a[16], - const uint8_t b[16]) { +static void aes_nohw_xor_block(uint8_t out[16], const uint8_t a[16], + const uint8_t b[16]) { for (size_t i = 0; i < 16; i += sizeof(aes_word_t)) { aes_word_t x, y; memcpy(&x, a + i, sizeof(aes_word_t)); @@ -1171,9 +1168,9 @@ static inline void aes_nohw_xor_block(uint8_t out[16], const uint8_t a[16], } } -void aes_nohw_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, - size_t blocks, const AES_KEY *key, - const uint8_t ivec[16]) { +void bssl::aes_nohw_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, + size_t blocks, const AES_KEY *key, + const uint8_t ivec[16]) { if (blocks == 0) { return; } @@ -1181,7 +1178,7 @@ void aes_nohw_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, AES_NOHW_SCHEDULE sched; aes_nohw_expand_round_keys(&sched, key); - // Make |AES_NOHW_BATCH_SIZE| copies of |ivec|. + // Make `AES_NOHW_BATCH_SIZE` copies of `ivec`. alignas(AES_NOHW_WORD_SIZE) uint8_t ivs[AES_NOHW_BATCH_SIZE * 16]; alignas(AES_NOHW_WORD_SIZE) uint8_t enc_ivs[AES_NOHW_BATCH_SIZE * 16]; for (size_t i = 0; i < AES_NOHW_BATCH_SIZE; i++) { @@ -1216,8 +1213,9 @@ void aes_nohw_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, } } -void aes_nohw_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len, - const AES_KEY *key, uint8_t *ivec, const int enc) { +void bssl::aes_nohw_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len, + const AES_KEY *key, uint8_t *ivec, + const int enc) { assert(len % 16 == 0); size_t blocks = len / 16; if (blocks == 0) { diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/cbc.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/cbc.cc.inc index 2cbfcffe..5ed6373e 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/cbc.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/cbc.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,16 +19,18 @@ #include "../../internal.h" -void CRYPTO_cbc128_encrypt(const uint8_t *in, uint8_t *out, size_t len, - const AES_KEY *key, uint8_t ivec[16], - block128_f block) { - assert(key != NULL && ivec != NULL); +using namespace bssl; + +void bssl::CRYPTO_cbc128_encrypt(const uint8_t *in, uint8_t *out, size_t len, + const AES_KEY *key, uint8_t ivec[16], + block128_f block) { + assert(key != nullptr && ivec != nullptr); if (len == 0) { - // Avoid |ivec| == |iv| in the |memcpy| below, which is not legal in C. + // Avoid `ivec` == `iv` in the `memcpy` below, which is not legal in C. return; } - assert(in != NULL && out != NULL); + assert(in != nullptr && out != nullptr); size_t n; const uint8_t *iv = ivec; while (len >= 16) { @@ -55,26 +62,26 @@ void CRYPTO_cbc128_encrypt(const uint8_t *in, uint8_t *out, size_t len, OPENSSL_memcpy(ivec, iv, 16); } -void CRYPTO_cbc128_decrypt(const uint8_t *in, uint8_t *out, size_t len, - const AES_KEY *key, uint8_t ivec[16], - block128_f block) { - assert(key != NULL && ivec != NULL); +void bssl::CRYPTO_cbc128_decrypt(const uint8_t *in, uint8_t *out, size_t len, + const AES_KEY *key, uint8_t ivec[16], + block128_f block) { + assert(key != nullptr && ivec != nullptr); if (len == 0) { - // Avoid |ivec| == |iv| in the |memcpy| below, which is not legal in C. + // Avoid `ivec` == `iv` in the `memcpy` below, which is not legal in C. return; } - assert(in != NULL && out != NULL); + assert(in != nullptr && out != nullptr); const uintptr_t inptr = (uintptr_t) in; const uintptr_t outptr = (uintptr_t) out; - // If |in| and |out| alias, |in| must be ahead. + // If `in` and `out` alias, `in` must be ahead. assert(inptr >= outptr || inptr + len <= outptr); size_t n; alignas(16) uint8_t tmp[16]; if ((inptr >= 32 && outptr <= inptr - 32) || inptr < outptr) { - // If |out| is at least two blocks behind |in| or completely disjoint, there + // If `out` is at least two blocks behind `in` or completely disjoint, there // is no need to decrypt to a temporary block. const uint8_t *iv = ivec; while (len >= 16) { diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/cfb.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/cfb.cc.inc index 42d3aba9..3db78b15 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/cfb.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/cfb.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -13,11 +18,13 @@ #include "internal.h" +using namespace bssl; + static_assert(16 % sizeof(size_t) == 0, "block cannot be divided into size_t"); -void CRYPTO_cfb128_encrypt(const uint8_t *in, uint8_t *out, size_t len, - const AES_KEY *key, uint8_t ivec[16], unsigned *num, - int enc, block128_f block) { +void bssl::CRYPTO_cfb128_encrypt(const uint8_t *in, uint8_t *out, size_t len, + const AES_KEY *key, uint8_t ivec[16], + unsigned *num, int enc, block128_f block) { assert(in && out && key && ivec && num); unsigned n = *num; @@ -129,9 +136,9 @@ static void cfbr_encrypt_block(const uint8_t *in, uint8_t *out, unsigned nbits, } // N.B. This expects the input to be packed, MS bit first -void CRYPTO_cfb128_1_encrypt(const uint8_t *in, uint8_t *out, size_t bits, - const AES_KEY *key, uint8_t ivec[16], - unsigned *num, int enc, block128_f block) { +void bssl::CRYPTO_cfb128_1_encrypt(const uint8_t *in, uint8_t *out, size_t bits, + const AES_KEY *key, uint8_t ivec[16], + unsigned *num, int enc, block128_f block) { size_t n; uint8_t c[1], d[1]; @@ -146,10 +153,10 @@ void CRYPTO_cfb128_1_encrypt(const uint8_t *in, uint8_t *out, size_t bits, } } -void CRYPTO_cfb128_8_encrypt(const unsigned char *in, unsigned char *out, - size_t length, const AES_KEY *key, - unsigned char ivec[16], unsigned *num, int enc, - block128_f block) { +void bssl::CRYPTO_cfb128_8_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char ivec[16], unsigned *num, + int enc, block128_f block) { size_t n; assert(in && out && key && ivec && num); diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/ctr.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/ctr.cc.inc index 364743f3..1a333305 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/ctr.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/ctr.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,6 +19,8 @@ #include "../../internal.h" +using namespace bssl; + static_assert(16 % sizeof(crypto_word_t) == 0, "block cannot be divided into crypto_word_t"); @@ -29,10 +36,10 @@ static void ctr96_inc(uint8_t *counter) { } while (n); } -void CRYPTO_ctr128_encrypt_ctr32(const uint8_t *in, uint8_t *out, size_t len, - const AES_KEY *key, uint8_t ivec[16], - uint8_t ecount_buf[16], unsigned int *num, - ctr128_f func) { +void bssl::CRYPTO_ctr128_encrypt_ctr32(const uint8_t *in, uint8_t *out, + size_t len, const AES_KEY *key, + uint8_t ivec[16], uint8_t ecount_buf[16], + unsigned int *num, ctr128_f func) { unsigned int n, ctr32; assert(key && ecount_buf && num); @@ -68,7 +75,7 @@ void CRYPTO_ctr128_encrypt_ctr32(const uint8_t *in, uint8_t *out, size_t len, (*func)(in, out, blocks, key, ivec); // (*func) does not update ivec, caller does: CRYPTO_store_u32_be(ivec + 12, ctr32); - // ... overflow was detected, propogate carry. + // ... overflow was detected, propagate carry. if (ctr32 == 0) { ctr96_inc(ivec); } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/gcm.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/gcm.cc.inc index be28b4d6..7d910dad 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/gcm.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/gcm.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2010-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2010-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -18,12 +23,14 @@ #include "internal.h" +using namespace bssl; + // kSizeTWithoutLower4Bits is a mask that can be used to zero the lower four -// bits of a |size_t|. +// bits of a `size_t`. static const size_t kSizeTWithoutLower4Bits = (size_t) -16; -#define GCM_MUL(key, ctx, Xi) gcm_gmult_nohw((ctx)->Xi, (key)->Htable) +#define GCM_MUL(key, ctx, Xi) bssl::gcm_gmult_nohw((ctx)->Xi, (key)->Htable) #define GHASH(key, ctx, in, len) \ gcm_ghash_nohw((ctx)->Xi, (key)->Htable, in, len) // GHASH_CHUNK is "stride parameter" missioned to mitigate cache @@ -32,7 +39,7 @@ static const size_t kSizeTWithoutLower4Bits = (size_t) -16; #define GHASH_CHUNK (3 * 1024) #if defined(GHASH_ASM_X86_64) || defined(GHASH_ASM_X86) -static inline void gcm_reduce_1bit(u128 *V) { +static void gcm_reduce_1bit(u128 *V) { if (sizeof(crypto_word_t) == 8) { uint64_t T = UINT64_C(0xe100000000000000) & (0 - (V->hi & 1)); V->hi = (V->lo << 63) | (V->hi >> 1); @@ -44,7 +51,7 @@ static inline void gcm_reduce_1bit(u128 *V) { } } -void gcm_init_ssse3(u128 Htable[16], const uint64_t H[2]) { +void bssl::gcm_init_ssse3(u128 Htable[16], const uint64_t H[2]) { Htable[0].hi = 0; Htable[0].lo = 0; u128 V; @@ -72,7 +79,7 @@ void gcm_init_ssse3(u128 Htable[16], const uint64_t H[2]) { Htable[14].hi = V.hi ^ Htable[6].hi, Htable[14].lo = V.lo ^ Htable[6].lo; Htable[15].hi = V.hi ^ Htable[7].hi, Htable[15].lo = V.lo ^ Htable[7].lo; - // Treat |Htable| as a 16x16 byte table and transpose it. Thus, Htable[i] + // Treat `Htable` as a 16x16 byte table and transpose it. Thus, Htable[i] // contains the i'th byte of j*H for all j. uint8_t *Hbytes = (uint8_t *)Htable; for (int i = 0; i < 16; i++) { @@ -104,9 +111,9 @@ static size_t hw_gcm_encrypt(const uint8_t *in, uint8_t *out, size_t len, aes_gcm_enc_update_vaes_avx2(in, out, len, key, ivec, Htable, Xi); CRYPTO_store_u32_be(&ivec[12], CRYPTO_load_u32_be(&ivec[12]) + len / 16); return len; - case gcm_x86_vaes_avx10_512: + case gcm_x86_vaes_avx512: len &= kSizeTWithoutLower4Bits; - aes_gcm_enc_update_vaes_avx10_512(in, out, len, key, ivec, Htable, Xi); + aes_gcm_enc_update_vaes_avx512(in, out, len, key, ivec, Htable, Xi); CRYPTO_store_u32_be(&ivec[12], CRYPTO_load_u32_be(&ivec[12]) + len / 16); return len; default: @@ -124,9 +131,9 @@ static size_t hw_gcm_decrypt(const uint8_t *in, uint8_t *out, size_t len, aes_gcm_dec_update_vaes_avx2(in, out, len, key, ivec, Htable, Xi); CRYPTO_store_u32_be(&ivec[12], CRYPTO_load_u32_be(&ivec[12]) + len / 16); return len; - case gcm_x86_vaes_avx10_512: + case gcm_x86_vaes_avx512: len &= kSizeTWithoutLower4Bits; - aes_gcm_dec_update_vaes_avx10_512(in, out, len, key, ivec, Htable, Xi); + aes_gcm_dec_update_vaes_avx512(in, out, len, key, ivec, Htable, Xi); CRYPTO_store_u32_be(&ivec[12], CRYPTO_load_u32_be(&ivec[12]) + len / 16); return len; default: @@ -145,6 +152,10 @@ static size_t hw_gcm_encrypt(const uint8_t *in, uint8_t *out, size_t len, if (!len_blocks) { return 0; } + if (impl == gcm_arm64_aes_eor3) { + aes_gcm_enc_kernel_eor3(in, len_blocks * 8, out, Xi, ivec, key, Htable); + return len_blocks; + } aes_gcm_enc_kernel(in, len_blocks * 8, out, Xi, ivec, key, Htable); return len_blocks; } @@ -157,15 +168,19 @@ static size_t hw_gcm_decrypt(const uint8_t *in, uint8_t *out, size_t len, if (!len_blocks) { return 0; } + if (impl == gcm_arm64_aes_eor3) { + aes_gcm_dec_kernel_eor3(in, len_blocks * 8, out, Xi, ivec, key, Htable); + return len_blocks; + } aes_gcm_dec_kernel(in, len_blocks * 8, out, Xi, ivec, key, Htable); return len_blocks; } #endif // HW_GCM && AARCH64 -void CRYPTO_ghash_init(gmult_func *out_mult, ghash_func *out_hash, - u128 out_table[16], const uint8_t gcm_key[16]) { - // H is passed to |gcm_init_*| as a pair of byte-swapped, 64-bit values. +void bssl::CRYPTO_ghash_init(gmult_func *out_mult, ghash_func *out_hash, + u128 out_table[16], const uint8_t gcm_key[16]) { + // H is passed to `gcm_init_*` as a pair of byte-swapped, 64-bit values. uint64_t H[2] = {CRYPTO_load_u64_be(gcm_key), CRYPTO_load_u64_be(gcm_key + 8)}; @@ -174,9 +189,9 @@ void CRYPTO_ghash_init(gmult_func *out_mult, ghash_func *out_hash, if (CRYPTO_is_VPCLMULQDQ_capable() && CRYPTO_is_AVX2_capable()) { if (CRYPTO_is_AVX512BW_capable() && CRYPTO_is_AVX512VL_capable() && CRYPTO_is_BMI2_capable() && !CRYPTO_cpu_avoid_zmm_registers()) { - gcm_init_vpclmulqdq_avx10_512(out_table, H); - *out_mult = gcm_gmult_vpclmulqdq_avx10; - *out_hash = gcm_ghash_vpclmulqdq_avx10_512; + gcm_init_vpclmulqdq_avx512(out_table, H); + *out_mult = gcm_gmult_vpclmulqdq_avx512; + *out_hash = gcm_ghash_vpclmulqdq_avx512; return; } gcm_init_vpclmulqdq_avx2(out_table, H); @@ -235,8 +250,8 @@ void CRYPTO_ghash_init(gmult_func *out_mult, ghash_func *out_hash, *out_hash = gcm_ghash_nohw; } -void CRYPTO_gcm128_init_aes_key(GCM128_KEY *gcm_key, const uint8_t *key, - size_t key_bytes) { +void bssl::CRYPTO_gcm128_init_aes_key(GCM128_KEY *gcm_key, const uint8_t *key, + size_t key_bytes) { switch (key_bytes) { case 16: boringssl_fips_inc_counter(fips_counter_evp_aes_128_gcm); @@ -261,25 +276,27 @@ void CRYPTO_gcm128_init_aes_key(GCM128_KEY *gcm_key, const uint8_t *key, #if !defined(OPENSSL_NO_ASM) #if defined(OPENSSL_X86_64) - if (gcm_key->ghash == gcm_ghash_vpclmulqdq_avx10_512 && + if (gcm_key->ghash == gcm_ghash_vpclmulqdq_avx512 && is_hwaes && CRYPTO_is_VAES_capable()) { - gcm_key->impl = gcm_x86_vaes_avx10_512; - } else if (gcm_key->ghash == gcm_ghash_vpclmulqdq_avx2 && + gcm_key->impl = gcm_x86_vaes_avx512; + } else if (gcm_key->ghash == gcm_ghash_vpclmulqdq_avx2 && is_hwaes && CRYPTO_is_VAES_capable()) { gcm_key->impl = gcm_x86_vaes_avx2; } else if (gcm_key->ghash == gcm_ghash_avx && is_hwaes) { gcm_key->impl = gcm_x86_aesni; } #elif defined(OPENSSL_AARCH64) - if (gcm_pmull_capable() && is_hwaes) { + if (gcm_eor3_capable() && is_hwaes) { + gcm_key->impl = gcm_arm64_aes_eor3; + } else if (gcm_pmull_capable() && is_hwaes) { gcm_key->impl = gcm_arm64_aes; } #endif #endif } -void CRYPTO_gcm128_init_ctx(const GCM128_KEY *key, GCM128_CONTEXT *ctx, - const uint8_t *iv, size_t iv_len) { +void bssl::CRYPTO_gcm128_init_ctx(const GCM128_KEY *key, GCM128_CONTEXT *ctx, + const uint8_t *iv, size_t iv_len) { #ifdef GCM_FUNCREF void (*gcm_gmult_p)(uint8_t Xi[16], const u128 Htable[16]) = key->gmult; #endif @@ -326,8 +343,8 @@ void CRYPTO_gcm128_init_ctx(const GCM128_KEY *key, GCM128_CONTEXT *ctx, CRYPTO_store_u32_be(ctx->Yi + 12, ctr); } -int CRYPTO_gcm128_aad(const GCM128_KEY *key, GCM128_CONTEXT *ctx, - const uint8_t *aad, size_t aad_len) { +int bssl::CRYPTO_gcm128_aad(const GCM128_KEY *key, GCM128_CONTEXT *ctx, + const uint8_t *aad, size_t aad_len) { #ifdef GCM_FUNCREF void (*gcm_gmult_p)(uint8_t Xi[16], const u128 Htable[16]) = key->gmult; void (*gcm_ghash_p)(uint8_t Xi[16], const u128 Htable[16], const uint8_t *inp, @@ -380,8 +397,8 @@ int CRYPTO_gcm128_aad(const GCM128_KEY *key, GCM128_CONTEXT *ctx, return 1; } -int CRYPTO_gcm128_encrypt(const GCM128_KEY *key, GCM128_CONTEXT *ctx, - const uint8_t *in, uint8_t *out, size_t len) { +int bssl::CRYPTO_gcm128_encrypt(const GCM128_KEY *key, GCM128_CONTEXT *ctx, + const uint8_t *in, uint8_t *out, size_t len) { #ifdef GCM_FUNCREF void (*gcm_gmult_p)(uint8_t Xi[16], const u128 Htable[16]) = key->gmult; void (*gcm_ghash_p)(uint8_t Xi[16], const u128 Htable[16], const uint8_t *inp, @@ -417,9 +434,8 @@ int CRYPTO_gcm128_encrypt(const GCM128_KEY *key, GCM128_CONTEXT *ctx, } #if defined(HW_GCM) - // Check |len| to work around a C language bug. See https://crbug.com/1019588. if (key->impl != gcm_separate && len > 0) { - // |hw_gcm_encrypt| may not process all the input given to it. It may + // `hw_gcm_encrypt` may not process all the input given to it. It may // not process *any* of its input if it is deemed too small. size_t bulk = hw_gcm_encrypt(in, out, len, &key->aes, ctx->Yi, ctx->Xi, key->Htable, key->impl); @@ -467,8 +483,8 @@ int CRYPTO_gcm128_encrypt(const GCM128_KEY *key, GCM128_CONTEXT *ctx, return 1; } -int CRYPTO_gcm128_decrypt(const GCM128_KEY *key, GCM128_CONTEXT *ctx, - const uint8_t *in, uint8_t *out, size_t len) { +int bssl::CRYPTO_gcm128_decrypt(const GCM128_KEY *key, GCM128_CONTEXT *ctx, + const uint8_t *in, uint8_t *out, size_t len) { #ifdef GCM_FUNCREF void (*gcm_gmult_p)(uint8_t Xi[16], const u128 Htable[16]) = key->gmult; void (*gcm_ghash_p)(uint8_t Xi[16], const u128 Htable[16], const uint8_t *inp, @@ -506,9 +522,8 @@ int CRYPTO_gcm128_decrypt(const GCM128_KEY *key, GCM128_CONTEXT *ctx, } #if defined(HW_GCM) - // Check |len| to work around a C language bug. See https://crbug.com/1019588. if (key->impl != gcm_separate && len > 0) { - // |hw_gcm_decrypt| may not process all the input given to it. It may + // `hw_gcm_decrypt` may not process all the input given to it. It may // not process *any* of its input if it is deemed too small. size_t bulk = hw_gcm_decrypt(in, out, len, &key->aes, ctx->Yi, ctx->Xi, key->Htable, key->impl); @@ -558,8 +573,8 @@ int CRYPTO_gcm128_decrypt(const GCM128_KEY *key, GCM128_CONTEXT *ctx, return 1; } -int CRYPTO_gcm128_finish(const GCM128_KEY *key, GCM128_CONTEXT *ctx, - const uint8_t *tag, size_t len) { +int bssl::CRYPTO_gcm128_finish(const GCM128_KEY *key, GCM128_CONTEXT *ctx, + const uint8_t *tag, size_t len) { #ifdef GCM_FUNCREF void (*gcm_gmult_p)(uint8_t Xi[16], const u128 Htable[16]) = key->gmult; #endif @@ -582,16 +597,16 @@ int CRYPTO_gcm128_finish(const GCM128_KEY *key, GCM128_CONTEXT *ctx, } } -void CRYPTO_gcm128_tag(const GCM128_KEY *key, GCM128_CONTEXT *ctx, uint8_t *tag, - size_t len) { - CRYPTO_gcm128_finish(key, ctx, NULL, 0); +void bssl::CRYPTO_gcm128_tag(const GCM128_KEY *key, GCM128_CONTEXT *ctx, + uint8_t *tag, size_t len) { + CRYPTO_gcm128_finish(key, ctx, nullptr, 0); OPENSSL_memcpy(tag, ctx->Xi, len <= sizeof(ctx->Xi) ? len : sizeof(ctx->Xi)); } #if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) -int crypto_gcm_clmul_enabled(void) { +int bssl::crypto_gcm_clmul_enabled() { #if defined(GHASH_ASM_X86) || defined(GHASH_ASM_X86_64) - return CRYPTO_is_FXSR_capable() && CRYPTO_is_PCLMUL_capable(); + return CRYPTO_is_PCLMUL_capable() && CRYPTO_is_SSSE3_capable(); #else return 0; #endif diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/gcm_nohw.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/gcm_nohw.cc.inc index ac36ca1e..3943daf9 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/gcm_nohw.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/gcm_nohw.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2019 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2019 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 @@ -22,6 +22,8 @@ #endif +using namespace bssl; + // This file contains a constant-time implementation of GHASH based on the notes // in https://bearssl.org/constanttime.html#ghash-for-gcm and the reduction // algorithm described in @@ -38,7 +40,7 @@ static void gcm_mul64_nohw(uint64_t *out_lo, uint64_t *out_hi, uint64_t a, // One term every four bits means the largest term is 64/4 = 16, which barely // overflows into the next term. Using one term every five bits would cost 25 // multiplications instead of 16. It is faster to mask off the bottom four - // bits of |a|, giving a largest term of 60/4 = 15, and apply the bottom bits + // bits of `a`, giving a largest term of 60/4 = 15, and apply the bottom bits // separately. uint64_t a0 = a & UINT64_C(0x1111111111111110); uint64_t a1 = a & UINT64_C(0x2222222222222220); @@ -59,7 +61,7 @@ static void gcm_mul64_nohw(uint64_t *out_lo, uint64_t *out_hi, uint64_t a, uint128_t c3 = (a0 * (uint128_t)b3) ^ (a1 * (uint128_t)b2) ^ (a2 * (uint128_t)b1) ^ (a3 * (uint128_t)b0); - // Multiply the bottom four bits of |a| with |b|. + // Multiply the bottom four bits of `a` with `b`. uint64_t a0_mask = UINT64_C(0) - (a & 1); uint64_t a1_mask = UINT64_C(0) - ((a >> 1) & 1); uint64_t a2_mask = UINT64_C(0) - ((a >> 2) & 1); @@ -192,14 +194,14 @@ static void gcm_mul64_nohw(uint64_t *out_lo, uint64_t *out_hi, uint64_t a, #endif // BORINGSSL_HAS_UINT128 -void gcm_init_nohw(u128 Htable[16], const uint64_t Xi[2]) { +void bssl::gcm_init_nohw(u128 Htable[16], const uint64_t Xi[2]) { // We implement GHASH in terms of POLYVAL, as described in RFC 8452. This // avoids a shift by 1 in the multiplication, needed to account for bit // reversal losing a bit after multiplication, that is, // rev128(X) * rev128(Y) = rev255(X*Y). // // Per Appendix A, we run mulX_POLYVAL. Note this is the same transformation - // applied by |gcm_init_clmul|, etc. Note |Xi| has already been byteswapped. + // applied by `gcm_init_clmul`, etc. Note `Xi` has already been byteswapped. // // See also slide 16 of // https://crypto.stanford.edu/RealWorldCrypto/slides/gueron.pdf @@ -218,12 +220,12 @@ void gcm_init_nohw(u128 Htable[16], const uint64_t Xi[2]) { Htable[0].lo ^= carry & 1; Htable[0].hi ^= carry & UINT64_C(0xc200000000000000); - // This implementation does not use the rest of |Htable|. + // This implementation does not use the rest of `Htable`. } static void gcm_polyval_nohw(uint64_t Xi[2], const u128 *H) { - // Karatsuba multiplication. The product of |Xi| and |H| is stored in |r0| - // through |r3|. Note there is no byte or bit reversal because we are + // Karatsuba multiplication. The product of `Xi` and `H` is stored in `r0` + // through `r3`. Note there is no byte or bit reversal because we are // evaluating POLYVAL. uint64_t r0, r1; gcm_mul64_nohw(&r0, &r1, Xi[0], H->lo); @@ -236,8 +238,8 @@ static void gcm_polyval_nohw(uint64_t Xi[2], const u128 *H) { r2 ^= mid1; r1 ^= mid0; - // Now we multiply our 256-bit result by x^-128 and reduce. |r2| and - // |r3| shifts into position and we must multiply |r0| and |r1| by x^-128. We + // Now we multiply our 256-bit result by x^-128 and reduce. `r2` and + // `r3` shifts into position and we must multiply `r0` and `r1` by x^-128. We // have: // // 1 = x^121 + x^126 + x^127 + x^128 @@ -247,7 +249,7 @@ static void gcm_polyval_nohw(uint64_t Xi[2], const u128 *H) { // The x^-7, x^-2, and x^-1 terms shift bits past x^0, which would require // another reduction steps. Instead, we gather the excess bits, incorporate - // them into |r0| and |r1| and reduce once. See slides 17-19 + // them into `r0` and `r1` and reduce once. See slides 17-19 // of https://crypto.stanford.edu/RealWorldCrypto/slides/gueron.pdf. r1 ^= (r0 << 63) ^ (r0 << 62) ^ (r0 << 57); @@ -274,7 +276,7 @@ static void gcm_polyval_nohw(uint64_t Xi[2], const u128 *H) { Xi[1] = r3; } -void gcm_gmult_nohw(uint8_t Xi[16], const u128 Htable[16]) { +void bssl::gcm_gmult_nohw(uint8_t Xi[16], const u128 Htable[16]) { uint64_t swapped[2]; swapped[0] = CRYPTO_load_u64_be(Xi + 8); swapped[1] = CRYPTO_load_u64_be(Xi); @@ -283,8 +285,8 @@ void gcm_gmult_nohw(uint8_t Xi[16], const u128 Htable[16]) { CRYPTO_store_u64_be(Xi + 8, swapped[0]); } -void gcm_ghash_nohw(uint8_t Xi[16], const u128 Htable[16], const uint8_t *inp, - size_t len) { +void bssl::gcm_ghash_nohw(uint8_t Xi[16], const u128 Htable[16], + const uint8_t *inp, size_t len) { uint64_t swapped[2]; swapped[0] = CRYPTO_load_u64_be(Xi + 8); swapped[1] = CRYPTO_load_u64_be(Xi); diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/internal.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/internal.h index ee47d8ab..3ee356c5 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/internal.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/internal.h @@ -1,35 +1,34 @@ -/* Copyright 2017 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2017 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. -#ifndef OPENSSL_HEADER_AES_INTERNAL_H -#define OPENSSL_HEADER_AES_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_AES_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_AES_INTERNAL_H #include -#include - #include "../../internal.h" +#include "../bcm_interface.h" -extern "C" { +BSSL_NAMESPACE_BEGIN // block128_f is the type of an AES block cipher implementation. // // Unlike upstream OpenSSL, it and the other functions in this file hard-code -// |AES_KEY|. It is undefined in C to call a function pointer with anything -// other than the original type. Thus we either must match |block128_f| to the -// type signature of |AES_encrypt| and friends or pass in |void*| wrapper +// `AES_KEY`. It is undefined in C to call a function pointer with anything +// other than the original type. Thus we either must match `block128_f` to the +// type signature of `BCM_aes_encrypt` and friends or pass in `void*` wrapper // functions. // // These functions are called exclusively with AES, so we use the former. @@ -40,9 +39,9 @@ typedef void (*block128_f)(const uint8_t in[16], uint8_t out[16], typedef void (*ctr128_f)(const uint8_t *in, uint8_t *out, size_t blocks, const AES_KEY *key, const uint8_t ivec[16]); -// aes_ctr_set_key initialises |*aes_key| using |key_bytes| bytes from |key|, -// where |key_bytes| must either be 16, 24 or 32. If not NULL, |*out_block| is -// set to a function that encrypts single blocks. If not NULL, |*out_is_hwaes| +// aes_ctr_set_key initialises `*aes_key` using `key_bytes` bytes from `key`, +// where `key_bytes` must either be 16, 24 or 32. If not NULL, `*out_block` is +// set to a function that encrypts single blocks. If not NULL, `*out_is_hwaes` // is set to whether the hardware AES implementation was used. It returns a // function for optimised CTR-mode. ctr128_f aes_ctr_set_key(AES_KEY *aes_key, int *out_is_hwaes, @@ -58,28 +57,28 @@ ctr128_f aes_ctr_set_key(AES_KEY *aes_key, int *out_is_hwaes, #define HWAES #define HWAES_ECB -inline int hwaes_capable(void) { return CRYPTO_is_AESNI_capable(); } +inline int hwaes_capable() { return CRYPTO_is_AESNI_capable(); } #define VPAES #define VPAES_CBC -inline int vpaes_capable(void) { return CRYPTO_is_SSSE3_capable(); } +inline int vpaes_capable() { return CRYPTO_is_SSSE3_capable(); } #elif defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64) #define HWAES -inline int hwaes_capable(void) { return CRYPTO_is_ARMv8_AES_capable(); } +inline int hwaes_capable() { return CRYPTO_is_ARMv8_AES_capable(); } #if defined(OPENSSL_ARM) #define BSAES #define VPAES -inline int bsaes_capable(void) { return CRYPTO_is_NEON_capable(); } -inline int vpaes_capable(void) { return CRYPTO_is_NEON_capable(); } +inline int bsaes_capable() { return CRYPTO_is_NEON_capable(); } +inline int vpaes_capable() { return CRYPTO_is_NEON_capable(); } #endif #if defined(OPENSSL_AARCH64) #define VPAES #define VPAES_CBC -inline int vpaes_capable(void) { return CRYPTO_is_NEON_capable(); } +inline int vpaes_capable() { return CRYPTO_is_NEON_capable(); } #endif #endif @@ -89,19 +88,25 @@ inline int vpaes_capable(void) { return CRYPTO_is_NEON_capable(); } #if defined(HWAES) -int aes_hw_set_encrypt_key(const uint8_t *user_key, int bits, AES_KEY *key); -int aes_hw_set_decrypt_key(const uint8_t *user_key, int bits, AES_KEY *key); -void aes_hw_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key); -void aes_hw_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key); -void aes_hw_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, - const AES_KEY *key, uint8_t *ivec, int enc); -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]); +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]); #if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) -// On x86 and x86_64, |aes_hw_set_decrypt_key| is implemented in terms of -// |aes_hw_set_encrypt_key| and a conversion function. -void aes_hw_encrypt_key_to_decrypt_key(AES_KEY *key); +// On x86 and x86_64, `aes_hw_set_decrypt_key` is implemented in terms of +// `aes_hw_set_encrypt_key` and a conversion function. +extern "C" void aes_hw_encrypt_key_to_decrypt_key(AES_KEY *key); // There are two variants of this function, one which uses aeskeygenassist // ("base") and one which uses aesenclast + pshufb ("alt"). aesenclast is @@ -113,22 +118,23 @@ void aes_hw_encrypt_key_to_decrypt_key(AES_KEY *key); // worthwhile. However, the aesenclast version requires SSSE3. SSSE3 long // predates AES-NI, but it's not clear if AES-NI implies SSSE3. In OpenSSL, the // CCM AES-NI assembly seems to assume it does. -inline int aes_hw_set_encrypt_key_alt_capable(void) { +inline int aes_hw_set_encrypt_key_alt_capable() { return hwaes_capable() && CRYPTO_is_SSSE3_capable(); } -inline int aes_hw_set_encrypt_key_alt_preferred(void) { +inline int aes_hw_set_encrypt_key_alt_preferred() { return hwaes_capable() && CRYPTO_is_AVX_capable(); } -int aes_hw_set_encrypt_key_base(const uint8_t *user_key, int bits, - AES_KEY *key); -int aes_hw_set_encrypt_key_alt(const uint8_t *user_key, int bits, AES_KEY *key); +extern "C" int aes_hw_set_encrypt_key_base(const uint8_t *user_key, int bits, + AES_KEY *key); +extern "C" int aes_hw_set_encrypt_key_alt(const uint8_t *user_key, int bits, + AES_KEY *key); #endif // OPENSSL_X86 || OPENSSL_X86_64 #else // If HWAES isn't defined then we provide dummy functions for each of the hwaes // functions. -inline int hwaes_capable(void) { return 0; } +inline int hwaes_capable() { return 0; } inline int aes_hw_set_encrypt_key(const uint8_t *user_key, int bits, AES_KEY *key) { @@ -165,68 +171,53 @@ inline void aes_hw_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, #if defined(HWAES_ECB) -void aes_hw_ecb_encrypt(const uint8_t *in, uint8_t *out, size_t length, - const AES_KEY *key, int enc); +extern "C" void aes_hw_ecb_encrypt(const uint8_t *in, uint8_t *out, + size_t length, const AES_KEY *key, int enc); #endif // HWAES_ECB #if defined(BSAES) -// Note |bsaes_cbc_encrypt| requires |enc| to be zero. -void bsaes_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, - const AES_KEY *key, uint8_t ivec[16], int enc); -void bsaes_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, size_t len, - const AES_KEY *key, const uint8_t ivec[16]); +// 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); +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]); // VPAES to BSAES conversions are available on all BSAES platforms. -void vpaes_encrypt_key_to_bsaes(AES_KEY *out_bsaes, const AES_KEY *vpaes); -void vpaes_decrypt_key_to_bsaes(AES_KEY *out_bsaes, const AES_KEY *vpaes); +extern "C" void vpaes_encrypt_key_to_bsaes(AES_KEY *out_bsaes, + const AES_KEY *vpaes); +extern "C" void vpaes_decrypt_key_to_bsaes(AES_KEY *out_bsaes, + const AES_KEY *vpaes); void vpaes_ctr32_encrypt_blocks_with_bsaes(const uint8_t *in, uint8_t *out, size_t blocks, const AES_KEY *key, const uint8_t ivec[16]); -#else -inline int bsaes_capable(void) { return 0; } - -// On other platforms, bsaes_capable() will always return false and so the -// following will never be called. -inline void bsaes_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, - const AES_KEY *key, uint8_t ivec[16], int enc) { - abort(); -} - -inline void bsaes_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, - size_t len, const AES_KEY *key, - const uint8_t ivec[16]) { - abort(); -} - -inline void vpaes_encrypt_key_to_bsaes(AES_KEY *out_bsaes, - const AES_KEY *vpaes) { - abort(); -} - -inline void vpaes_decrypt_key_to_bsaes(AES_KEY *out_bsaes, - const AES_KEY *vpaes) { - abort(); -} #endif // !BSAES #if defined(VPAES) // On platforms where VPAES gets defined (just above), then these functions are // provided by asm. -int vpaes_set_encrypt_key(const uint8_t *userKey, int bits, AES_KEY *key); -int vpaes_set_decrypt_key(const uint8_t *userKey, int bits, AES_KEY *key); +extern "C" int vpaes_set_encrypt_key(const uint8_t *userKey, int bits, + AES_KEY *key); +extern "C" int vpaes_set_decrypt_key(const uint8_t *userKey, int bits, + AES_KEY *key); -void vpaes_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key); -void vpaes_decrypt(const uint8_t *in, uint8_t *out, const 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); #if defined(VPAES_CBC) -void vpaes_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, - const AES_KEY *key, uint8_t *ivec, int enc); +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); #endif -void vpaes_ctr32_encrypt_blocks(const uint8_t *in, uint8_t *out, size_t len, - const AES_KEY *key, const uint8_t ivec[16]); +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]); #else -inline int vpaes_capable(void) { return 0; } +inline int vpaes_capable() { return 0; } // On other platforms, vpaes_capable() will always return false and so the // following will never be called. @@ -273,8 +264,8 @@ void aes_nohw_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len, inline void CRYPTO_xor16(uint8_t out[16], const uint8_t a[16], const uint8_t b[16]) { // TODO(davidben): Ideally we'd leave this to the compiler, which could use - // vector registers, etc. But the compiler doesn't know that |in| and |out| - // cannot partially alias. |restrict| is slightly two strict (we allow exact + // vector registers, etc. But the compiler doesn't know that `in` and `out` + // cannot partially alias. `restrict` is slightly two strict (we allow exact // aliasing), but perhaps in-place could be a separate function? static_assert(16 % sizeof(crypto_word_t) == 0, "block cannot be evenly divided into words"); @@ -288,12 +279,12 @@ inline void CRYPTO_xor16(uint8_t out[16], const uint8_t a[16], // CTR. // CRYPTO_ctr128_encrypt_ctr32 encrypts (or decrypts, it's the same in CTR mode) -// |len| bytes from |in| to |out| using |block| in counter mode. There's no -// requirement that |len| be a multiple of any value and any partial blocks are -// stored in |ecount_buf| and |*num|, which must be zeroed before the initial -// call. The counter is a 128-bit, big-endian value in |ivec| and is +// `len` bytes from `in` to `out` using `block` in counter mode. There's no +// requirement that `len` be a multiple of any value and any partial blocks are +// stored in `ecount_buf` and `*num`, which must be zeroed before the initial +// call. The counter is a 128-bit, big-endian value in `ivec` and is // incremented by this function. If the counter overflows, it wraps around. -// |ctr| must be a function that performs CTR mode but only deals with the lower +// `ctr` must be a function that performs CTR mode but only deals with the lower // 32 bits of the counter. void CRYPTO_ctr128_encrypt_ctr32(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, uint8_t ivec[16], @@ -303,10 +294,10 @@ void CRYPTO_ctr128_encrypt_ctr32(const uint8_t *in, uint8_t *out, size_t len, // GCM. // -// This API differs from the upstream API slightly. The |GCM128_CONTEXT| does -// not have a |key| pointer that points to the key as upstream's version does. -// Instead, every function takes a |key| parameter. This way |GCM128_CONTEXT| -// can be safely copied. Additionally, |gcm_key| is split into a separate +// This API differs from the upstream API slightly. The `GCM128_CONTEXT` does +// not have a `key` pointer that points to the key as upstream's version does. +// Instead, every function takes a `key` parameter. This way `GCM128_CONTEXT` +// can be safely copied. Additionally, `gcm_key` is split into a separate // struct. // gcm_impl_t specifies an assembly implementation of AES-GCM. @@ -314,18 +305,19 @@ enum gcm_impl_t { gcm_separate = 0, // No combined AES-GCM, but may have AES-CTR and GHASH. gcm_x86_aesni, gcm_x86_vaes_avx2, - gcm_x86_vaes_avx10_512, + gcm_x86_vaes_avx512, gcm_arm64_aes, + gcm_arm64_aes_eor3, }; typedef struct { uint64_t hi,lo; } u128; -// gmult_func multiplies |Xi| by the GCM key and writes the result back to -// |Xi|. +// gmult_func multiplies `Xi` by the GCM key and writes the result back to +// `Xi`. typedef void (*gmult_func)(uint8_t Xi[16], const u128 Htable[16]); -// ghash_func repeatedly multiplies |Xi| by the GCM key and adds in blocks from -// |inp|. The result is written back to |Xi| and the |len| argument must be a +// ghash_func repeatedly multiplies `Xi` by the GCM key and adds in blocks from +// `inp`. The result is written back to `Xi` and the `len` argument must be a // multiple of 16. typedef void (*ghash_func)(uint8_t Xi[16], const u128 Htable[16], const uint8_t *inp, size_t len); @@ -359,51 +351,51 @@ typedef struct { #if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) // crypto_gcm_clmul_enabled returns one if the CLMUL implementation of GCM is // used. -int crypto_gcm_clmul_enabled(void); +int crypto_gcm_clmul_enabled(); #endif -// CRYPTO_ghash_init writes a precomputed table of powers of |gcm_key| to -// |out_table| and sets |*out_mult| and |*out_hash| to (potentially hardware +// CRYPTO_ghash_init writes a precomputed table of powers of `gcm_key` to +// `out_table` and sets `*out_mult` and `*out_hash` to (potentially hardware // accelerated) functions for performing operations in the GHASH field. void CRYPTO_ghash_init(gmult_func *out_mult, ghash_func *out_hash, u128 out_table[16], const uint8_t gcm_key[16]); -// CRYPTO_gcm128_init_aes_key initialises |gcm_key| to with AES key |key|. +// CRYPTO_gcm128_init_aes_key initialises `gcm_key` to with AES key `key`. 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|. +// 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_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 -// value that was passed to |CRYPTO_gcm128_init_ctx|. It returns one on success +// This must be called before and data is encrypted. `key` must be the same +// value that was passed to `CRYPTO_gcm128_init_ctx`. It returns one on success // and zero otherwise. int CRYPTO_gcm128_aad(const GCM128_KEY *key, GCM128_CONTEXT *ctx, const uint8_t *aad, size_t aad_len); -// CRYPTO_gcm128_encrypt encrypts |len| bytes from |in| to |out|. |key| must be -// the same value that was passed to |CRYPTO_gcm128_init_ctx|. It returns one on +// CRYPTO_gcm128_encrypt encrypts `len` bytes from `in` to `out`. `key` must be +// the same value that was passed to `CRYPTO_gcm128_init_ctx`. It returns one on // success and zero otherwise. int CRYPTO_gcm128_encrypt(const GCM128_KEY *key, GCM128_CONTEXT *ctx, const uint8_t *in, uint8_t *out, size_t len); -// CRYPTO_gcm128_decrypt decrypts |len| bytes from |in| to |out|. |key| must be -// the same value that was passed to |CRYPTO_gcm128_init_ctx|. It returns one on +// CRYPTO_gcm128_decrypt decrypts `len` bytes from `in` to `out`. `key` must be +// the same value that was passed to `CRYPTO_gcm128_init_ctx`. It returns one on // success and zero otherwise. int CRYPTO_gcm128_decrypt(const GCM128_KEY *key, GCM128_CONTEXT *ctx, const uint8_t *in, uint8_t *out, size_t len); // CRYPTO_gcm128_finish calculates the authenticator and compares it against -// |len| bytes of |tag|. |key| must be the same value that was passed to -// |CRYPTO_gcm128_init_ctx|. It returns one on success and zero otherwise. +// `len` bytes of `tag`. `key` must be the same value that was passed to +// `CRYPTO_gcm128_init_ctx`. It returns one on success and zero otherwise. int CRYPTO_gcm128_finish(const GCM128_KEY *key, GCM128_CONTEXT *ctx, const uint8_t *tag, size_t len); -// CRYPTO_gcm128_tag calculates the authenticator and copies it into |tag|. -// The minimum of |len| and 16 bytes are copied into |tag|. |key| must be the -// same value that was passed to |CRYPTO_gcm128_init_ctx|. +// CRYPTO_gcm128_tag calculates the authenticator and copies it into `tag`. +// The minimum of `len` and 16 bytes are copied into `tag`. `key` must be the +// same value that was passed to `CRYPTO_gcm128_init_ctx`. void CRYPTO_gcm128_tag(const GCM128_KEY *key, GCM128_CONTEXT *ctx, uint8_t *tag, size_t len); @@ -419,54 +411,64 @@ 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 -void gcm_init_clmul(u128 Htable[16], const uint64_t Xi[2]); -void gcm_gmult_clmul(uint8_t Xi[16], const u128 Htable[16]); -void gcm_ghash_clmul(uint8_t Xi[16], const u128 Htable[16], const uint8_t *inp, - size_t len); +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); void gcm_init_ssse3(u128 Htable[16], const uint64_t Xi[2]); -void gcm_gmult_ssse3(uint8_t Xi[16], const u128 Htable[16]); -void gcm_ghash_ssse3(uint8_t Xi[16], const u128 Htable[16], const uint8_t *in, - size_t len); +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); #if defined(OPENSSL_X86_64) #define GHASH_ASM_X86_64 -void gcm_init_avx(u128 Htable[16], const uint64_t Xi[2]); -void gcm_gmult_avx(uint8_t Xi[16], const u128 Htable[16]); -void gcm_ghash_avx(uint8_t Xi[16], const u128 Htable[16], const uint8_t *in, - size_t len); +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); #define HW_GCM -size_t aesni_gcm_encrypt(const uint8_t *in, uint8_t *out, size_t len, - const AES_KEY *key, uint8_t ivec[16], - const u128 Htable[16], uint8_t Xi[16]); -size_t aesni_gcm_decrypt(const uint8_t *in, uint8_t *out, size_t len, - const AES_KEY *key, uint8_t ivec[16], - const u128 Htable[16], uint8_t Xi[16]); +extern "C" size_t aesni_gcm_encrypt(const uint8_t *in, uint8_t *out, size_t len, + const AES_KEY *key, uint8_t ivec[16], + const u128 Htable[16], uint8_t Xi[16]); +extern "C" size_t aesni_gcm_decrypt(const uint8_t *in, uint8_t *out, size_t len, + const AES_KEY *key, uint8_t ivec[16], + const u128 Htable[16], uint8_t Xi[16]); -void gcm_init_vpclmulqdq_avx2(u128 Htable[16], const uint64_t H[2]); -void gcm_gmult_vpclmulqdq_avx2(uint8_t Xi[16], const u128 Htable[16]); -void gcm_ghash_vpclmulqdq_avx2(uint8_t Xi[16], const u128 Htable[16], - const uint8_t *in, size_t len); -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], - const u128 Htable[16], uint8_t Xi[16]); -void aes_gcm_dec_update_vaes_avx2(const uint8_t *in, uint8_t *out, size_t len, - const AES_KEY *key, const uint8_t ivec[16], - 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); +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], + const u128 Htable[16], + uint8_t Xi[16]); +extern "C" void aes_gcm_dec_update_vaes_avx2(const uint8_t *in, uint8_t *out, + size_t len, const AES_KEY *key, + const uint8_t ivec[16], + const u128 Htable[16], + uint8_t Xi[16]); -void gcm_init_vpclmulqdq_avx10_512(u128 Htable[16], const uint64_t H[2]); -void gcm_gmult_vpclmulqdq_avx10(uint8_t Xi[16], const u128 Htable[16]); -void gcm_ghash_vpclmulqdq_avx10_512(uint8_t Xi[16], const u128 Htable[16], - const uint8_t *in, size_t len); -void aes_gcm_enc_update_vaes_avx10_512(const uint8_t *in, uint8_t *out, - size_t len, const AES_KEY *key, - const uint8_t ivec[16], - const u128 Htable[16], uint8_t Xi[16]); -void aes_gcm_dec_update_vaes_avx10_512(const uint8_t *in, uint8_t *out, - size_t len, const AES_KEY *key, - const uint8_t ivec[16], - const u128 Htable[16], uint8_t Xi[16]); +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); +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], + const u128 Htable[16], + uint8_t Xi[16]); +extern "C" void aes_gcm_dec_update_vaes_avx512(const uint8_t *in, uint8_t *out, + size_t len, const AES_KEY *key, + const uint8_t ivec[16], + const u128 Htable[16], + uint8_t Xi[16]); #endif // OPENSSL_X86_64 @@ -479,29 +481,41 @@ void aes_gcm_dec_update_vaes_avx10_512(const uint8_t *in, uint8_t *out, #define GHASH_ASM_ARM #define GCM_FUNCREF -inline int gcm_pmull_capable(void) { return CRYPTO_is_ARMv8_PMULL_capable(); } +inline int gcm_pmull_capable() { return CRYPTO_is_ARMv8_PMULL_capable(); } +inline int gcm_eor3_capable() { + // SHA3 and EOR3 belong to the same ISA extension. + return CRYPTO_is_ARMv8_PMULL_capable() && CRYPTO_is_ARMv8_SHA3_capable(); +} -void gcm_init_v8(u128 Htable[16], const uint64_t H[2]); -void gcm_gmult_v8(uint8_t Xi[16], const u128 Htable[16]); -void gcm_ghash_v8(uint8_t Xi[16], const u128 Htable[16], const uint8_t *inp, - size_t len); +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); -inline int gcm_neon_capable(void) { return CRYPTO_is_NEON_capable(); } +inline int gcm_neon_capable() { return CRYPTO_is_NEON_capable(); } -void gcm_init_neon(u128 Htable[16], const uint64_t H[2]); -void gcm_gmult_neon(uint8_t Xi[16], const u128 Htable[16]); -void gcm_ghash_neon(uint8_t Xi[16], const u128 Htable[16], const uint8_t *inp, - size_t len); +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); #if defined(OPENSSL_AARCH64) #define HW_GCM // These functions are defined in aesv8-gcm-armv8.pl. -void aes_gcm_enc_kernel(const uint8_t *in, uint64_t in_bits, void *out, - void *Xi, uint8_t *ivec, const AES_KEY *key, - const u128 Htable[16]); -void aes_gcm_dec_kernel(const uint8_t *in, uint64_t in_bits, void *out, - void *Xi, uint8_t *ivec, const AES_KEY *key, - const u128 Htable[16]); +extern "C" void aes_gcm_enc_kernel(const uint8_t *in, uint64_t in_bits, + void *out, void *Xi, uint8_t *ivec, + const AES_KEY *key, const u128 Htable[16]); +extern "C" void aes_gcm_dec_kernel(const uint8_t *in, uint64_t in_bits, + void *out, void *Xi, uint8_t *ivec, + const AES_KEY *key, const u128 Htable[16]); +extern "C" void aes_gcm_enc_kernel_eor3(const uint8_t *in, uint64_t in_bits, + void *out, void *Xi, uint8_t *ivec, + const AES_KEY *key, + const u128 Htable[16]); +extern "C" void aes_gcm_dec_kernel_eor3(const uint8_t *in, uint64_t in_bits, + void *out, void *Xi, uint8_t *ivec, + const AES_KEY *key, + const u128 Htable[16]); #endif #endif @@ -514,7 +528,7 @@ void aes_gcm_dec_kernel(const uint8_t *in, uint64_t in_bits, void *out, typedef void (*cbc128_f)(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, uint8_t ivec[16], int enc); -// CRYPTO_cbc128_encrypt encrypts |len| bytes from |in| to |out| using the +// CRYPTO_cbc128_encrypt encrypts `len` bytes from `in` to `out` using the // given IV and block cipher in CBC mode. The input need not be a multiple of // 128 bits long, but the output will round up to the nearest 128 bit multiple, // zero padding the input if needed. The IV will be updated on return. @@ -522,10 +536,10 @@ void CRYPTO_cbc128_encrypt(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, uint8_t ivec[16], block128_f block); -// CRYPTO_cbc128_decrypt decrypts |len| bytes from |in| to |out| using the -// given IV and block cipher in CBC mode. If |len| is not a multiple of 128 +// CRYPTO_cbc128_decrypt decrypts `len` bytes from `in` to `out` using the +// given IV and block cipher in CBC mode. If `len` is not a multiple of 128 // bits then only that many bytes will be written, but a multiple of 128 bits -// is always read from |in|. The IV will be updated on return. +// is always read from `in`. The IV will be updated on return. void CRYPTO_cbc128_decrypt(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, uint8_t ivec[16], block128_f block); @@ -534,9 +548,9 @@ void CRYPTO_cbc128_decrypt(const uint8_t *in, uint8_t *out, size_t len, // OFB. // CRYPTO_ofb128_encrypt encrypts (or decrypts, it's the same with OFB mode) -// |len| bytes from |in| to |out| using |block| in OFB mode. There's no -// requirement that |len| be a multiple of any value and any partial blocks are -// stored in |ivec| and |*num|, the latter must be zero before the initial +// `len` bytes from `in` to `out` using `block` in OFB mode. There's no +// requirement that `len` be a multiple of any value and any partial blocks are +// stored in `ivec` and `*num`, the latter must be zero before the initial // call. void CRYPTO_ofb128_encrypt(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, uint8_t ivec[16], unsigned *num, @@ -545,24 +559,24 @@ void CRYPTO_ofb128_encrypt(const uint8_t *in, uint8_t *out, size_t len, // CFB. -// CRYPTO_cfb128_encrypt encrypts (or decrypts, if |enc| is zero) |len| bytes -// from |in| to |out| using |block| in CFB mode. There's no requirement that -// |len| be a multiple of any value and any partial blocks are stored in |ivec| -// and |*num|, the latter must be zero before the initial call. +// CRYPTO_cfb128_encrypt encrypts (or decrypts, if `enc` is zero) `len` bytes +// from `in` to `out` using `block` in CFB mode. There's no requirement that +// `len` be a multiple of any value and any partial blocks are stored in `ivec` +// and `*num`, the latter must be zero before the initial call. void CRYPTO_cfb128_encrypt(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, uint8_t ivec[16], unsigned *num, int enc, block128_f block); -// CRYPTO_cfb128_8_encrypt encrypts (or decrypts, if |enc| is zero) |len| bytes -// from |in| to |out| using |block| in CFB-8 mode. Prior to the first call -// |num| should be set to zero. +// CRYPTO_cfb128_8_encrypt encrypts (or decrypts, if `enc` is zero) `len` bytes +// from `in` to `out` using `block` in CFB-8 mode. Prior to the first call +// `num` should be set to zero. void CRYPTO_cfb128_8_encrypt(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, uint8_t ivec[16], unsigned *num, int enc, block128_f block); -// CRYPTO_cfb128_1_encrypt encrypts (or decrypts, if |enc| is zero) |len| bytes -// from |in| to |out| using |block| in CFB-1 mode. Prior to the first call -// |num| should be set to zero. +// CRYPTO_cfb128_1_encrypt encrypts (or decrypts, if `enc` is zero) `len` bytes +// from `in` to `out` using `block` in CFB-1 mode. Prior to the first call +// `num` should be set to zero. void CRYPTO_cfb128_1_encrypt(const uint8_t *in, uint8_t *out, size_t bits, const AES_KEY *key, uint8_t ivec[16], unsigned *num, int enc, block128_f block); @@ -571,33 +585,6 @@ size_t CRYPTO_cts128_encrypt_block(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, uint8_t ivec[16], block128_f block); +BSSL_NAMESPACE_END -// POLYVAL. -// -// POLYVAL is a polynomial authenticator that operates over a field very -// similar to the one that GHASH uses. See -// https://www.rfc-editor.org/rfc/rfc8452.html#section-3. - -struct polyval_ctx { - uint8_t S[16]; - u128 Htable[16]; - gmult_func gmult; - ghash_func ghash; -}; - -// CRYPTO_POLYVAL_init initialises |ctx| using |key|. -void CRYPTO_POLYVAL_init(struct polyval_ctx *ctx, const uint8_t key[16]); - -// CRYPTO_POLYVAL_update_blocks updates the accumulator in |ctx| given the -// blocks from |in|. Only a whole number of blocks can be processed so |in_len| -// must be a multiple of 16. -void CRYPTO_POLYVAL_update_blocks(struct polyval_ctx *ctx, const uint8_t *in, - size_t in_len); - -// CRYPTO_POLYVAL_finish writes the accumulator from |ctx| to |out|. -void CRYPTO_POLYVAL_finish(const struct polyval_ctx *ctx, uint8_t out[16]); - - -} // extern C - -#endif // OPENSSL_HEADER_AES_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_AES_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/key_wrap.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/key_wrap.cc.inc index 62ce4553..53449c6c 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/key_wrap.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/key_wrap.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -15,10 +20,13 @@ #include +#include "../bcm_interface.h" #include "../../internal.h" #include "../service_indicator/internal.h" +using namespace bssl; + // kDefaultIV is the default IV value given in RFC 3394, 2.2.3.1. static const uint8_t kDefaultIV[] = { 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, @@ -35,7 +43,7 @@ int AES_wrap_key(const AES_KEY *key, const uint8_t *iv, uint8_t *out, return -1; } - if (iv == NULL) { + if (iv == nullptr) { iv = kDefaultIV; } @@ -48,7 +56,7 @@ int AES_wrap_key(const AES_KEY *key, const uint8_t *iv, uint8_t *out, for (unsigned j = 0; j < kBound; j++) { for (size_t i = 1; i <= n; i++) { OPENSSL_memcpy(A + 8, out + 8 * i, 8); - AES_encrypt(A, A, key); + BCM_aes_encrypt(A, A, key); uint32_t t = (uint32_t)(n * j + i); A[7] ^= t & 0xff; @@ -91,7 +99,7 @@ static int aes_unwrap_key_inner(const AES_KEY *key, uint8_t *out, A[5] ^= (t >> 16) & 0xff; A[4] ^= (t >> 24) & 0xff; OPENSSL_memcpy(A + 8, out + 8 * (i - 1), 8); - AES_decrypt(A, A, key); + BCM_aes_decrypt(A, A, key); OPENSSL_memcpy(out + 8 * (i - 1), A + 8, 8); } } @@ -107,7 +115,7 @@ int AES_unwrap_key(const AES_KEY *key, const uint8_t *iv, uint8_t *out, return -1; } - if (iv == NULL) { + if (iv == nullptr) { iv = kDefaultIV; } if (CRYPTO_memcmp(calculated_iv, iv, 8) != 0) { @@ -140,13 +148,13 @@ int AES_wrap_key_padded(const AES_KEY *key, uint8_t *out, size_t *out_len, if (in_len <= 8) { memset(block + 8, 0, 8); memcpy(block + 8, in, in_len); - AES_encrypt(block, out, key); + BCM_aes_encrypt(block, out, key); *out_len = AES_BLOCK_SIZE; return 1; } uint8_t *padded_in = reinterpret_cast(OPENSSL_malloc(padded_len)); - if (padded_in == NULL) { + if (padded_in == nullptr) { return 0; } assert(padded_len >= 8); @@ -174,7 +182,7 @@ int AES_unwrap_key_padded(const AES_KEY *key, uint8_t *out, size_t *out_len, uint8_t iv[8]; if (in_len == AES_BLOCK_SIZE) { uint8_t block[AES_BLOCK_SIZE]; - AES_decrypt(in, block, key); + BCM_aes_decrypt(in, block, key); memcpy(iv, block, sizeof(iv)); memcpy(out, block + 8, 8); } else if (!aes_unwrap_key_inner(key, out, iv, in, in_len)) { diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/mode_wrappers.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/mode_wrappers.cc.inc index efedf1e4..531a88e7 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/mode_wrappers.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/mode_wrappers.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -15,6 +20,18 @@ #include "../service_indicator/internal.h" +using namespace bssl; + +namespace { +void aes_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { + BCM_aes_encrypt(in, out, key); +} + +void aes_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { + BCM_aes_decrypt(in, out, key); +} +} // namespace + void AES_ctr128_encrypt(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, uint8_t ivec[AES_BLOCK_SIZE], uint8_t ecount_buf[AES_BLOCK_SIZE], unsigned int *num) { @@ -22,8 +39,8 @@ void AES_ctr128_encrypt(const uint8_t *in, uint8_t *out, size_t len, CRYPTO_ctr128_encrypt_ctr32(in, out, len, key, ivec, ecount_buf, num, aes_hw_ctr32_encrypt_blocks); } else if (vpaes_capable()) { - // TODO(davidben): On ARM, where |BSAES| is additionally defined, this could - // use |vpaes_ctr32_encrypt_blocks_with_bsaes|. + // TODO(davidben): On ARM, where `BSAES` is additionally defined, this could + // use `vpaes_ctr32_encrypt_blocks_with_bsaes`. CRYPTO_ctr128_encrypt_ctr32(in, out, len, key, ivec, ecount_buf, num, vpaes_ctr32_encrypt_blocks); } else { @@ -40,9 +57,9 @@ void AES_ecb_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key, assert((AES_ENCRYPT == enc) || (AES_DECRYPT == enc)); if (AES_ENCRYPT == enc) { - AES_encrypt(in, out, key); + BCM_aes_encrypt(in, out, key); } else { - AES_decrypt(in, out, key); + BCM_aes_decrypt(in, out, key); } FIPS_service_indicator_update_state(); @@ -50,14 +67,15 @@ void AES_ecb_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key, void AES_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, uint8_t *ivec, const int enc) { + assert(len % AES_BLOCK_SIZE == 0); if (hwaes_capable()) { aes_hw_cbc_encrypt(in, out, len, key, ivec, enc); } else if (!vpaes_capable()) { aes_nohw_cbc_encrypt(in, out, len, key, ivec, enc); } else if (enc) { - CRYPTO_cbc128_encrypt(in, out, len, key, ivec, AES_encrypt); + CRYPTO_cbc128_encrypt(in, out, len, key, ivec, aes_encrypt); } else { - CRYPTO_cbc128_decrypt(in, out, len, key, ivec, AES_decrypt); + CRYPTO_cbc128_decrypt(in, out, len, key, ivec, aes_decrypt); } FIPS_service_indicator_update_state(); @@ -66,7 +84,7 @@ void AES_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len, void AES_ofb128_encrypt(const uint8_t *in, uint8_t *out, size_t length, const AES_KEY *key, uint8_t *ivec, int *num) { unsigned num_u = (unsigned)(*num); - CRYPTO_ofb128_encrypt(in, out, length, key, ivec, &num_u, AES_encrypt); + CRYPTO_ofb128_encrypt(in, out, length, key, ivec, &num_u, aes_encrypt); *num = (int)num_u; } @@ -74,6 +92,6 @@ void AES_cfb128_encrypt(const uint8_t *in, uint8_t *out, size_t length, const AES_KEY *key, uint8_t *ivec, int *num, int enc) { unsigned num_u = (unsigned)(*num); - CRYPTO_cfb128_encrypt(in, out, length, key, ivec, &num_u, enc, AES_encrypt); + CRYPTO_cfb128_encrypt(in, out, length, key, ivec, &num_u, enc, aes_encrypt); *num = (int)num_u; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/ofb.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/ofb.cc.inc index 38e8795f..23e0ac66 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/ofb.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/ofb.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -13,13 +18,15 @@ #include "internal.h" +using namespace bssl; + static_assert(16 % sizeof(size_t) == 0, "block cannot be divided into size_t"); -void CRYPTO_ofb128_encrypt(const uint8_t *in, uint8_t *out, size_t len, - const AES_KEY *key, uint8_t ivec[16], unsigned *num, - block128_f block) { - assert(key != NULL && ivec != NULL && num != NULL); - assert(len == 0 || (in != NULL && out != NULL)); +void bssl::CRYPTO_ofb128_encrypt(const uint8_t *in, uint8_t *out, size_t len, + const AES_KEY *key, uint8_t ivec[16], + unsigned *num, block128_f block) { + assert(key != nullptr && ivec != nullptr && num != nullptr); + assert(len == 0 || (in != nullptr && out != nullptr)); unsigned n = *num; diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/polyval.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/polyval.cc.inc deleted file mode 100644 index 2f674f03..00000000 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/aes/polyval.cc.inc +++ /dev/null @@ -1,89 +0,0 @@ -/* Copyright 2016 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#include - -#include -#include - -#include "internal.h" -#include "../../internal.h" - - -// byte_reverse reverses the order of the bytes in |b->c|. -static void byte_reverse(uint8_t b[16]) { - uint64_t hi = CRYPTO_load_u64_le(b); - uint64_t lo = CRYPTO_load_u64_le(b + 8); - CRYPTO_store_u64_le(b, CRYPTO_bswap8(lo)); - CRYPTO_store_u64_le(b + 8, CRYPTO_bswap8(hi)); -} - -// reverse_and_mulX_ghash interprets |b| as a reversed element of the GHASH -// field, multiplies that by 'x' and serialises the result back into |b|, but -// with GHASH's backwards bit ordering. -static void reverse_and_mulX_ghash(uint8_t b[16]) { - uint64_t hi = CRYPTO_load_u64_le(b); - uint64_t lo = CRYPTO_load_u64_le(b + 8); - const crypto_word_t carry = constant_time_eq_w(hi & 1, 1); - hi >>= 1; - hi |= lo << 63; - lo >>= 1; - lo ^= ((uint64_t) constant_time_select_w(carry, 0xe1, 0)) << 56; - - CRYPTO_store_u64_le(b, CRYPTO_bswap8(lo)); - CRYPTO_store_u64_le(b + 8, CRYPTO_bswap8(hi)); -} - -// POLYVAL(H, X_1, ..., X_n) = -// ByteReverse(GHASH(mulX_GHASH(ByteReverse(H)), ByteReverse(X_1), ..., -// ByteReverse(X_n))). -// -// See https://www.rfc-editor.org/rfc/rfc8452.html#appendix-A. - -void CRYPTO_POLYVAL_init(struct polyval_ctx *ctx, const uint8_t key[16]) { - alignas(8) uint8_t H[16]; - OPENSSL_memcpy(H, key, 16); - reverse_and_mulX_ghash(H); - - CRYPTO_ghash_init(&ctx->gmult, &ctx->ghash, ctx->Htable, H); - OPENSSL_memset(&ctx->S, 0, sizeof(ctx->S)); -} - -void CRYPTO_POLYVAL_update_blocks(struct polyval_ctx *ctx, const uint8_t *in, - size_t in_len) { - assert((in_len & 15) == 0); - alignas(8) uint8_t buf[32 * 16]; - - while (in_len > 0) { - size_t todo = in_len; - if (todo > sizeof(buf)) { - todo = sizeof(buf); - } - OPENSSL_memcpy(buf, in, todo); - in += todo; - in_len -= todo; - - size_t blocks = todo / 16; - for (size_t i = 0; i < blocks; i++) { - byte_reverse(buf + 16 * i); - } - - ctx->ghash(ctx->S, ctx->Htable, buf, todo); - } -} - -void CRYPTO_POLYVAL_finish(const struct polyval_ctx *ctx, uint8_t out[16]) { - OPENSSL_memcpy(out, &ctx->S, 16); - byte_reverse(out); -} diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bcm.cc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bcm.cc index 92c7937f..7fc6bdeb 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bcm.cc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bcm.cc @@ -1,16 +1,16 @@ -/* Copyright 2017 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2017 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. #if !defined(_GNU_SOURCE) #define _GNU_SOURCE // needed for syscall() on Linux. @@ -26,14 +26,21 @@ #include #include -#include +#include +#include #include "../bcm_support.h" #include "../internal.h" #include "bcm_interface.h" +// The .cc.inc files are not written as headers, but .cc files which we +// currently need to combine together in the style of a unity or jumbo build. +// -Wheader-hygiene interprets them as headers. +// // TODO(crbug.com/362530616): When delocate is removed, build these files as // separate compilation units again. +OPENSSL_CLANG_PRAGMA("clang diagnostic push") +OPENSSL_CLANG_PRAGMA("clang diagnostic ignored \"-Wheader-hygiene\"") #include "aes/aes.cc.inc" #include "aes/aes_nohw.cc.inc" #include "aes/cbc.cc.inc" @@ -44,7 +51,6 @@ #include "aes/key_wrap.cc.inc" #include "aes/mode_wrappers.cc.inc" #include "aes/ofb.cc.inc" -#include "aes/polyval.cc.inc" #include "bn/add.cc.inc" #include "bn/asm/x86_64-gcc.cc.inc" #include "bn/bn.cc.inc" @@ -81,7 +87,6 @@ #include "ec/ec_montgomery.cc.inc" #include "ec/felem.cc.inc" #include "ec/oct.cc.inc" -#include "ec/p224-64.cc.inc" #include "ec/p256-nistz.cc.inc" #include "ec/p256.cc.inc" #include "ec/scalar.cc.inc" @@ -91,14 +96,15 @@ #include "ec/wnaf.cc.inc" #include "ecdh/ecdh.cc.inc" #include "ecdsa/ecdsa.cc.inc" +#include "entropy/jitter.cc.inc" #include "hkdf/hkdf.cc.inc" #include "hmac/hmac.cc.inc" #include "keccak/keccak.cc.inc" #include "mldsa/mldsa.cc.inc" #include "mlkem/mlkem.cc.inc" +#include "rand/android_entropy_client.cc.inc" #include "rand/ctrdrbg.cc.inc" #include "rand/rand.cc.inc" -#include "rsa/blinding.cc.inc" #include "rsa/padding.cc.inc" #include "rsa/rsa.cc.inc" #include "rsa/rsa_impl.cc.inc" @@ -114,8 +120,11 @@ #include "slhdsa/thash.cc.inc" #include "slhdsa/wots.cc.inc" #include "tls/kdf.cc.inc" +OPENSSL_CLANG_PRAGMA("clang diagnostic pop") +using namespace bssl; + #if defined(BORINGSSL_FIPS) #if !defined(OPENSSL_ASAN) @@ -125,7 +134,7 @@ // the location of the integrity hash, respectively. extern const uint8_t BORINGSSL_bcm_text_start[]; extern const uint8_t BORINGSSL_bcm_text_end[]; -extern const uint8_t BORINGSSL_bcm_text_hash[]; +extern const uint8_t BORINGSSL_bcm_text_hash[SHA256_DIGEST_LENGTH]; #if defined(BORINGSSL_SHARED_LIBRARY) extern const uint8_t BORINGSSL_bcm_rodata_start[]; extern const uint8_t BORINGSSL_bcm_rodata_end[]; @@ -154,7 +163,7 @@ static void assert_within(const void *start, const void *symbol, static void BORINGSSL_maybe_set_module_text_permissions(int permission) { // Android may be compiled in execute-only-memory mode, in which case the // .text segment cannot be read. That conflicts with the need for a FIPS - // module to hash its own contents, therefore |mprotect| is used to make + // module to hash its own contents, therefore `mprotect` is used to make // the module's .text readable for the duration of the hashing process. In // other build configurations this is a no-op. const uintptr_t page_size = getpagesize(); @@ -173,8 +182,8 @@ static void BORINGSSL_maybe_set_module_text_permissions(int permission) {} #endif // !ASAN -static void __attribute__((constructor)) -BORINGSSL_bcm_power_on_self_test(void) { +static void __attribute__((constructor)) BORINGSSL_bcm_power_on_self_test( + void) { #if !defined(OPENSSL_ASAN) // Integrity tests cannot run under ASAN because it involves reading the full // .text section, which triggers the global-buffer overflow detection. @@ -194,11 +203,11 @@ err: } #if !defined(OPENSSL_ASAN) -int BORINGSSL_integrity_test(void) { +int BORINGSSL_integrity_test() { const uint8_t *const start = BORINGSSL_bcm_text_start; const uint8_t *const end = BORINGSSL_bcm_text_end; - assert_within(start, reinterpret_cast(AES_encrypt), end); + assert_within(start, reinterpret_cast(BCM_aes_encrypt), end); assert_within(start, reinterpret_cast(RSA_sign), end); assert_within(start, reinterpret_cast(BCM_rand_bytes), end); assert_within(start, reinterpret_cast(EC_GROUP_cmp), end); @@ -220,7 +229,6 @@ int BORINGSSL_integrity_test(void) { assert_within(rodata_start, kPKCS1SigPrefixes, rodata_end); uint8_t result[SHA256_DIGEST_LENGTH]; - const EVP_MD *const kHashFunction = EVP_sha256(); if (!boringssl_self_test_sha256() || !boringssl_self_test_hmac_sha256()) { return 0; } @@ -229,8 +237,8 @@ int BORINGSSL_integrity_test(void) { unsigned result_len; HMAC_CTX hmac_ctx; HMAC_CTX_init(&hmac_ctx); - if (!HMAC_Init_ex(&hmac_ctx, kHMACKey, sizeof(kHMACKey), kHashFunction, - NULL /* no ENGINE */)) { + if (!HMAC_Init_ex(&hmac_ctx, kHMACKey, sizeof(kHMACKey), EVP_sha256(), + nullptr /* no ENGINE */)) { fprintf(CRYPTO_get_stderr(), "HMAC_Init_ex failed.\n"); return 0; } @@ -249,16 +257,14 @@ int BORINGSSL_integrity_test(void) { #endif BORINGSSL_maybe_set_module_text_permissions(PROT_EXEC); - if (!HMAC_Final(&hmac_ctx, result, &result_len) || - result_len != sizeof(result)) { + if (!HMAC_Final(&hmac_ctx, result, &result_len)) { fprintf(CRYPTO_get_stderr(), "HMAC failed.\n"); return 0; } HMAC_CTX_cleanse(&hmac_ctx); // FIPS 140-3, AS05.10. - const uint8_t *expected = BORINGSSL_bcm_text_hash; - - if (!check_test(expected, result, sizeof(result), "FIPS integrity test")) { + if (!BORINGSSL_check_test(BORINGSSL_bcm_text_hash, Span(result, result_len), + "FIPS integrity test")) { #if !defined(BORINGSSL_FIPS_BREAK_TESTS) return 0; #endif @@ -268,11 +274,11 @@ int BORINGSSL_integrity_test(void) { return 1; } -const uint8_t *FIPS_module_hash(void) { return BORINGSSL_bcm_text_hash; } +const uint8_t *FIPS_module_hash() { return BORINGSSL_bcm_text_hash; } #endif // OPENSSL_ASAN -void BORINGSSL_FIPS_abort(void) { +void bssl::BORINGSSL_FIPS_abort() { for (;;) { abort(); exit(1); diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bcm_interface.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/bcm_interface.h index 9d1114ac..3b24f696 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bcm_interface.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bcm_interface.h @@ -1,21 +1,26 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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. -#ifndef OPENSSL_HEADER_CRYPTO_BCM_INTERFACE_H -#define OPENSSL_HEADER_CRYPTO_BCM_INTERFACE_H +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_BCM_INTERFACE_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_BCM_INTERFACE_H + +#include +#include +#include +#include +#include -#include // This header will eventually become the interface between BCM and the // rest of libcrypto. More cleanly separating the two is still a work in @@ -25,9 +30,7 @@ // Over time, calls from libcrypto to BCM will all move to this header // and the separation will become more meaningful. -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN // Enumerated types for return values from bcm functions, both infallible // and fallible functions. Two success values are used to correspond to the @@ -55,6 +58,9 @@ inline bcm_status_t bcm_as_approved_status(int result) { return result ? bcm_status::approved : bcm_status::failure; } +inline bcm_status_t bcm_as_not_approved_status(int result) { + return result ? bcm_status::not_approved : bcm_status::failure; +} // Random number generator. @@ -67,111 +73,95 @@ inline bcm_status_t bcm_as_approved_status(int result) { #endif // BORINGSSL_FIPS -// BCM_rand_load_entropy supplies |entropy_len| bytes of entropy to the BCM -// module. The |want_additional_input| parameter is true iff the entropy was -// obtained from a source other than the system, e.g. directly from the CPU. -bcm_infallible BCM_rand_load_entropy(const uint8_t *entropy, size_t entropy_len, - int want_additional_input); - -// BCM_rand_bytes is the same as the public |RAND_bytes| function, other +// BCM_rand_bytes is the same as the public `RAND_bytes` function, other // than returning a bcm_infallible status indicator. -OPENSSL_EXPORT bcm_infallible BCM_rand_bytes(uint8_t *out, size_t out_len); +bcm_infallible BCM_rand_bytes(uint8_t *out, size_t out_len); -// BCM_rand_bytes_hwrng attempts to fill |out| with |len| bytes of entropy from +// BCM_rand_bytes_hwrng attempts to fill `out` with `len` bytes of entropy from // the CPU hardware random number generator if one is present. // bcm_status_approved is returned on success, and a failure status is // returned otherwise. bcm_status BCM_rand_bytes_hwrng(uint8_t *out, size_t len); // BCM_rand_bytes_with_additional_data samples from the RNG after mixing 32 -// bytes from |user_additional_data| in. +// bytes from `user_additional_data` in. bcm_infallible BCM_rand_bytes_with_additional_data( uint8_t *out, size_t out_len, const uint8_t user_additional_data[32]); // SHA-1 -// BCM_SHA_DIGEST_LENGTH is the length of a SHA-1 digest. -#define BCM_SHA_DIGEST_LENGTH 20 - -// BCM_sha1_init initialises |sha|. +// BCM_sha1_init initialises `sha`. bcm_infallible BCM_sha1_init(SHA_CTX *sha); -// BCM_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|. -bcm_infallible BCM_sha1_transform(SHA_CTX *c, - const uint8_t data[BCM_SHA_CBLOCK]); +// 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`. +bcm_infallible BCM_sha1_transform(SHA_CTX *c, const uint8_t data[SHA_CBLOCK]); -// BCM_sha1_update adds |len| bytes from |data| to |sha|. +// BCM_sha1_update adds `len` bytes from `data` to `sha`. bcm_infallible BCM_sha1_update(SHA_CTX *c, const void *data, size_t len); -// BCM_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. -bcm_infallible BCM_sha1_final(uint8_t out[BCM_SHA_DIGEST_LENGTH], SHA_CTX *c); +// BCM_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. +bcm_infallible BCM_sha1_final(uint8_t out[SHA_DIGEST_LENGTH], SHA_CTX *c); -// BCM_fips_186_2_prf derives |out_len| bytes from |xkey| using the PRF +// BCM_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 // input is all zeros. // // The PRF generates a sequence of 320-bit numbers. Each number is encoded as a -// 40-byte string in big-endian and then concatenated to form |out|. If -// |out_len| is not a multiple of 40, the result is truncated. This matches the +// 40-byte string in big-endian and then concatenated to form `out`. If +// `out_len` is not a multiple of 40, the result is truncated. This matches the // construction used in Section 7 of RFC 4186 and Section 7 of RFC 4187. // // This PRF is based on SHA-1, a weak hash function, and should not be used // in new protocols. It is provided for compatibility with some legacy EAP // methods. bcm_infallible BCM_fips_186_2_prf(uint8_t *out, size_t out_len, - const uint8_t xkey[BCM_SHA_DIGEST_LENGTH]); + const uint8_t xkey[SHA_DIGEST_LENGTH]); // SHA-224 -// SHA224_DIGEST_LENGTH is the length of a SHA-224 digest. -#define BCM_SHA224_DIGEST_LENGTH 28 - -// BCM_sha224_unit initialises |sha|. +// BCM_sha224_unit initialises `sha`. bcm_infallible BCM_sha224_init(SHA256_CTX *sha); -// BCM_sha224_update adds |len| bytes from |data| to |sha|. +// BCM_sha224_update adds `len` bytes from `data` to `sha`. bcm_infallible BCM_sha224_update(SHA256_CTX *sha, const void *data, size_t len); -// BCM_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 +// BCM_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 aborts on programmer error. -bcm_infallible BCM_sha224_final(uint8_t out[BCM_SHA224_DIGEST_LENGTH], +bcm_infallible BCM_sha224_final(uint8_t out[SHA224_DIGEST_LENGTH], SHA256_CTX *sha); // SHA-256 -// BCM_SHA256_DIGEST_LENGTH is the length of a SHA-256 digest. -#define BCM_SHA256_DIGEST_LENGTH 32 - -// BCM_sha256_init initialises |sha|. +// BCM_sha256_init initialises `sha`. bcm_infallible BCM_sha256_init(SHA256_CTX *sha); -// BCM_sha256_update adds |len| bytes from |data| to |sha|. +// BCM_sha256_update adds `len` bytes from `data` to `sha`. bcm_infallible BCM_sha256_update(SHA256_CTX *sha, const void *data, size_t len); -// BCM_sha256_final adds the final padding to |sha| and writes the resulting -// digest to |out|, which must have at least |BCM_SHA256_DIGEST_LENGTH| bytes of +// BCM_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 aborts on programmer error. -bcm_infallible BCM_sha256_final(uint8_t out[BCM_SHA256_DIGEST_LENGTH], +bcm_infallible BCM_sha256_final(uint8_t out[SHA256_DIGEST_LENGTH], SHA256_CTX *sha); // BCM_sha256_transform is a low-level function that performs a single, SHA-256 -// block transformation using the state from |sha| and |BCM_SHA256_CBLOCK| bytes -// from |block|. +// block transformation using the state from `sha` and `SHA256_CBLOCK` bytes +// from `block`. bcm_infallible BCM_sha256_transform(SHA256_CTX *sha, - const uint8_t block[BCM_SHA256_CBLOCK]); + const uint8_t block[SHA256_CBLOCK]); -// BCM_sha256_transform_blocks is a low-level function that takes |num_blocks| * -// |BCM_SHA256_CBLOCK| bytes of data and performs SHA-256 transforms on it to -// update |state|. +// BCM_sha256_transform_blocks is a low-level function that takes `num_blocks` * +// `SHA256_CBLOCK` bytes of data and performs SHA-256 transforms on it to update +// `state`. bcm_infallible BCM_sha256_transform_blocks(uint32_t state[8], const uint8_t *data, size_t num_blocks); @@ -179,63 +169,55 @@ bcm_infallible BCM_sha256_transform_blocks(uint32_t state[8], // SHA-384. -// BCM_SHA384_DIGEST_LENGTH is the length of a SHA-384 digest. -#define BCM_SHA384_DIGEST_LENGTH 48 - -// BCM_sha384_init initialises |sha|. +// BCM_sha384_init initialises `sha`. bcm_infallible BCM_sha384_init(SHA512_CTX *sha); -// BCM_sha384_update adds |len| bytes from |data| to |sha|. +// BCM_sha384_update adds `len` bytes from `data` to `sha`. bcm_infallible BCM_sha384_update(SHA512_CTX *sha, const void *data, size_t len); -// BCM_sha384_final adds the final padding to |sha| and writes the resulting -// digest to |out|, which must have at least |BCM_sha384_DIGEST_LENGTH| bytes of +// BCM_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 may abort on programmer error. -bcm_infallible BCM_sha384_final(uint8_t out[BCM_SHA384_DIGEST_LENGTH], +bcm_infallible BCM_sha384_final(uint8_t out[SHA384_DIGEST_LENGTH], SHA512_CTX *sha); // SHA-512. -// BCM_SHA512_DIGEST_LENGTH is the length of a SHA-512 digest. -#define BCM_SHA512_DIGEST_LENGTH 64 - -// BCM_sha512_init initialises |sha|. +// BCM_sha512_init initialises `sha`. bcm_infallible BCM_sha512_init(SHA512_CTX *sha); -// BCM_sha512_update adds |len| bytes from |data| to |sha|. +// BCM_sha512_update adds `len` bytes from `data` to `sha`. bcm_infallible BCM_sha512_update(SHA512_CTX *sha, const void *data, size_t len); -// BCM_sha512_final adds the final padding to |sha| and writes the resulting -// digest to |out|, which must have at least |BCM_sha512_DIGEST_LENGTH| bytes of +// BCM_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. -bcm_infallible BCM_sha512_final(uint8_t out[BCM_SHA512_DIGEST_LENGTH], +bcm_infallible BCM_sha512_final(uint8_t out[SHA512_DIGEST_LENGTH], SHA512_CTX *sha); // BCM_sha512_transform is a low-level function that performs a single, SHA-512 -// block transformation using the state from |sha| and |BCM_sha512_CBLOCK| bytes -// from |block|. +// block transformation using the state from `sha` and `SHA512_CBLOCK` bytes +// from `block`. bcm_infallible BCM_sha512_transform(SHA512_CTX *sha, - const uint8_t block[BCM_SHA512_CBLOCK]); + const uint8_t block[SHA512_CBLOCK]); // SHA-512-256 // // See https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf section 5.3.6 -#define BCM_SHA512_256_DIGEST_LENGTH 32 - -// BCM_sha512_256_init initialises |sha|. +// BCM_sha512_256_init initialises `sha`. bcm_infallible BCM_sha512_256_init(SHA512_CTX *sha); -// BCM_sha512_256_update adds |len| bytes from |data| to |sha|. +// BCM_sha512_256_update adds `len` bytes from `data` to `sha`. bcm_infallible BCM_sha512_256_update(SHA512_CTX *sha, const void *data, size_t len); -// BCM_sha512_256_final adds the final padding to |sha| and writes the resulting -// digest to |out|, which must have at least |BCM_sha512_256_DIGEST_LENGTH| -// bytes of space. It may abort on programmer error. -bcm_infallible BCM_sha512_256_final(uint8_t out[BCM_SHA512_256_DIGEST_LENGTH], +// BCM_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 may abort on programmer error. +bcm_infallible BCM_sha512_256_final(uint8_t out[SHA512_256_DIGEST_LENGTH], SHA512_CTX *sha); @@ -248,193 +230,357 @@ bcm_infallible BCM_sha512_256_final(uint8_t out[BCM_SHA512_256_DIGEST_LENGTH], // random entropy necessary to generate a signature in randomized mode. #define BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES 32 -// BCM_MLDSA_SEED_BYTES is the number of bytes in an ML-DSA seed value. -#define BCM_MLDSA_SEED_BYTES 32 - // BCM_MLDSA65_PRIVATE_KEY_BYTES is the number of bytes in an encoded ML-DSA-65 // private key. #define BCM_MLDSA65_PRIVATE_KEY_BYTES 4032 -// BCM_MLDSA65_PUBLIC_KEY_BYTES is the number of bytes in an encoded ML-DSA-65 -// public key. -#define BCM_MLDSA65_PUBLIC_KEY_BYTES 1952 - -// BCM_MLDSA65_SIGNATURE_BYTES is the number of bytes in an encoded ML-DSA-65 -// signature. -#define BCM_MLDSA65_SIGNATURE_BYTES 3309 - -struct BCM_mldsa65_private_key { - union { - uint8_t bytes[32 + 32 + 64 + 256 * 4 * (5 + 6 + 6)]; - uint32_t alignment; - } opaque; -}; - -struct BCM_mldsa65_public_key { - union { - uint8_t bytes[32 + 64 + 256 * 4 * 6]; - uint32_t alignment; - } opaque; -}; - OPENSSL_EXPORT bcm_status BCM_mldsa65_generate_key( - uint8_t out_encoded_public_key[BCM_MLDSA65_PUBLIC_KEY_BYTES], - uint8_t out_seed[BCM_MLDSA_SEED_BYTES], - struct BCM_mldsa65_private_key *out_private_key); + uint8_t out_encoded_public_key[MLDSA65_PUBLIC_KEY_BYTES], + uint8_t out_seed[MLDSA_SEED_BYTES], MLDSA65_private_key *out_private_key); OPENSSL_EXPORT bcm_status BCM_mldsa65_private_key_from_seed( - struct BCM_mldsa65_private_key *out_private_key, - const uint8_t seed[BCM_MLDSA_SEED_BYTES]); + MLDSA65_private_key *out_private_key, const uint8_t seed[MLDSA_SEED_BYTES]); OPENSSL_EXPORT bcm_status BCM_mldsa65_public_from_private( - struct BCM_mldsa65_public_key *out_public_key, - const struct BCM_mldsa65_private_key *private_key); + MLDSA65_public_key *out_public_key, const MLDSA65_private_key *private_key); -OPENSSL_EXPORT bcm_status BCM_mldsa65_sign( - uint8_t out_encoded_signature[BCM_MLDSA65_SIGNATURE_BYTES], - const struct BCM_mldsa65_private_key *private_key, const uint8_t *msg, - size_t msg_len, const uint8_t *context, size_t context_len); +// BCM_mldsa65_public_of_private returns the public half of `private_key`. +const MLDSA65_public_key *BCM_mldsa65_public_of_private( + const MLDSA65_private_key *private_key); + +OPENSSL_EXPORT bcm_status +BCM_mldsa65_check_key_fips(MLDSA65_private_key *private_key); + +OPENSSL_EXPORT bcm_status BCM_mldsa65_generate_key_fips( + uint8_t out_encoded_public_key[MLDSA65_PUBLIC_KEY_BYTES], + uint8_t out_seed[MLDSA_SEED_BYTES], MLDSA65_private_key *out_private_key); + +OPENSSL_EXPORT bcm_status BCM_mldsa65_private_key_from_seed_fips( + MLDSA65_private_key *out_private_key, const uint8_t seed[MLDSA_SEED_BYTES]); + +OPENSSL_EXPORT bcm_status +BCM_mldsa65_sign(uint8_t out_encoded_signature[MLDSA65_SIGNATURE_BYTES], + const MLDSA65_private_key *private_key, const uint8_t *msg, + size_t msg_len, const uint8_t *context, size_t context_len); OPENSSL_EXPORT bcm_status BCM_mldsa65_verify( - const struct BCM_mldsa65_public_key *public_key, - const uint8_t signature[BCM_MLDSA65_SIGNATURE_BYTES], const uint8_t *msg, + const MLDSA65_public_key *public_key, + const uint8_t signature[MLDSA65_SIGNATURE_BYTES], const uint8_t *msg, size_t msg_len, const uint8_t *context, size_t context_len); -OPENSSL_EXPORT bcm_status BCM_mldsa65_marshal_public_key( - CBB *out, const struct BCM_mldsa65_public_key *public_key); +OPENSSL_EXPORT void BCM_mldsa65_prehash_init( + MLDSA65_prehash *out_prehash_ctx, const MLDSA65_public_key *public_key, + const uint8_t *context, size_t context_len); -OPENSSL_EXPORT bcm_status BCM_mldsa65_parse_public_key( - struct BCM_mldsa65_public_key *public_key, CBS *in); +OPENSSL_EXPORT void BCM_mldsa65_prehash_update( + MLDSA65_prehash *inout_prehash_ctx, const uint8_t *msg, size_t msg_len); -OPENSSL_EXPORT bcm_status BCM_mldsa65_parse_private_key( - struct BCM_mldsa65_private_key *private_key, CBS *in); +OPENSSL_EXPORT void BCM_mldsa65_prehash_finalize( + uint8_t out_msg_rep[MLDSA_MU_BYTES], MLDSA65_prehash *inout_prehash_ctx); + +OPENSSL_EXPORT bcm_status BCM_mldsa65_sign_message_representative( + uint8_t out_encoded_signature[MLDSA65_SIGNATURE_BYTES], + const MLDSA65_private_key *private_key, + const uint8_t msg_rep[MLDSA_MU_BYTES]); + +OPENSSL_EXPORT bcm_status BCM_mldsa65_verify_message_representative( + const MLDSA65_public_key *public_key, + const uint8_t signature[MLDSA65_SIGNATURE_BYTES], + const uint8_t msg_rep[MLDSA_MU_BYTES]); + +OPENSSL_EXPORT bcm_status +BCM_mldsa65_marshal_public_key(CBB *out, const MLDSA65_public_key *public_key); + +OPENSSL_EXPORT bcm_status +BCM_mldsa65_parse_public_key(MLDSA65_public_key *public_key, CBS *in); + +OPENSSL_EXPORT bcm_status +BCM_mldsa65_parse_private_key(MLDSA65_private_key *private_key, CBS *in); // BCM_mldsa65_generate_key_external_entropy generates a public/private key pair // using the given seed, writes the encoded public key to -// |out_encoded_public_key| and sets |out_private_key| to the private key. +// `out_encoded_public_key` and sets `out_private_key` to the private key. OPENSSL_EXPORT bcm_status BCM_mldsa65_generate_key_external_entropy( - uint8_t out_encoded_public_key[BCM_MLDSA65_PUBLIC_KEY_BYTES], - struct BCM_mldsa65_private_key *out_private_key, - const uint8_t entropy[BCM_MLDSA_SEED_BYTES]); + uint8_t out_encoded_public_key[MLDSA65_PUBLIC_KEY_BYTES], + MLDSA65_private_key *out_private_key, + const uint8_t entropy[MLDSA_SEED_BYTES]); -// BCM_mldsa5_sign_internal signs |msg| using |private_key| and writes the -// signature to |out_encoded_signature|. The |context_prefix| and |context| are -// prefixed to the message, in that order, before signing. The |randomizer| +OPENSSL_EXPORT bcm_status BCM_mldsa65_generate_key_external_entropy_fips( + uint8_t out_encoded_public_key[MLDSA65_PUBLIC_KEY_BYTES], + MLDSA65_private_key *out_private_key, + const uint8_t entropy[MLDSA_SEED_BYTES]); + +// BCM_mldsa5_sign_internal signs `msg` using `private_key` and writes the +// signature to `out_encoded_signature`. The `context_prefix` and `context` are +// prefixed to the message, in that order, before signing. The `randomizer` // value can be set to zero bytes in order to make a deterministic signature, or -// else filled with entropy for the usual |MLDSA_sign| behavior. +// else filled with entropy for the usual `MLDSA_sign` behavior. OPENSSL_EXPORT bcm_status BCM_mldsa65_sign_internal( - uint8_t out_encoded_signature[BCM_MLDSA65_SIGNATURE_BYTES], - const struct BCM_mldsa65_private_key *private_key, const uint8_t *msg, - size_t msg_len, const uint8_t *context_prefix, size_t context_prefix_len, + uint8_t out_encoded_signature[MLDSA65_SIGNATURE_BYTES], + const MLDSA65_private_key *private_key, const uint8_t *msg, size_t msg_len, + const uint8_t *context_prefix, size_t context_prefix_len, const uint8_t *context, size_t context_len, const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]); -// BCM_mldsa5_verify_internal verifies that |encoded_signature| is a valid -// signature of |msg| by |public_key|. The |context_prefix| and |context| are +OPENSSL_EXPORT bcm_status BCM_mldsa65_sign_mu_internal( + uint8_t out_encoded_signature[MLDSA65_SIGNATURE_BYTES], + const MLDSA65_private_key *private_key, + const uint8_t msg_rep[MLDSA_MU_BYTES], + const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]); + +// BCM_mldsa5_verify_internal verifies that `encoded_signature` is a valid +// signature of `msg` by `public_key`. The `context_prefix` and `context` are // prefixed to the message before verification, in that order. OPENSSL_EXPORT bcm_status BCM_mldsa65_verify_internal( - const struct BCM_mldsa65_public_key *public_key, - const uint8_t encoded_signature[BCM_MLDSA65_SIGNATURE_BYTES], + const MLDSA65_public_key *public_key, + const uint8_t encoded_signature[MLDSA65_SIGNATURE_BYTES], const uint8_t *msg, size_t msg_len, const uint8_t *context_prefix, size_t context_prefix_len, const uint8_t *context, size_t context_len); -// BCM_mldsa65_marshal_private_key serializes |private_key| to |out| in the +// BCM_mldsa65_marshal_private_key serializes `private_key` to `out` in the // NIST format for ML-DSA-65 private keys. OPENSSL_EXPORT bcm_status BCM_mldsa65_marshal_private_key( - CBB *out, const struct BCM_mldsa65_private_key *private_key); + CBB *out, const MLDSA65_private_key *private_key); + +// BCM_mldsa65_public_keys_equal returns one if `a` and `b` are equal and zero +// otherwise. +int BCM_mldsa65_public_keys_equal(const MLDSA65_public_key *a, + const MLDSA65_public_key *b); // BCM_MLDSA87_PRIVATE_KEY_BYTES is the number of bytes in an encoded ML-DSA-87 // private key. #define BCM_MLDSA87_PRIVATE_KEY_BYTES 4896 -// BCM_MLDSA87_PUBLIC_KEY_BYTES is the number of bytes in an encoded ML-DSA-87 -// public key. -#define BCM_MLDSA87_PUBLIC_KEY_BYTES 2592 - -// BCM_MLDSA87_SIGNATURE_BYTES is the number of bytes in an encoded ML-DSA-87 -// signature. -#define BCM_MLDSA87_SIGNATURE_BYTES 4627 - -struct BCM_mldsa87_private_key { - union { - uint8_t bytes[32 + 32 + 64 + 256 * 4 * (7 + 8 + 8)]; - uint32_t alignment; - } opaque; -}; - -struct BCM_mldsa87_public_key { - union { - uint8_t bytes[32 + 64 + 256 * 4 * 8]; - uint32_t alignment; - } opaque; -}; - OPENSSL_EXPORT bcm_status BCM_mldsa87_generate_key( - uint8_t out_encoded_public_key[BCM_MLDSA87_PUBLIC_KEY_BYTES], - uint8_t out_seed[BCM_MLDSA_SEED_BYTES], - struct BCM_mldsa87_private_key *out_private_key); + uint8_t out_encoded_public_key[MLDSA87_PUBLIC_KEY_BYTES], + uint8_t out_seed[MLDSA_SEED_BYTES], MLDSA87_private_key *out_private_key); OPENSSL_EXPORT bcm_status BCM_mldsa87_private_key_from_seed( - struct BCM_mldsa87_private_key *out_private_key, - const uint8_t seed[BCM_MLDSA_SEED_BYTES]); + MLDSA87_private_key *out_private_key, const uint8_t seed[MLDSA_SEED_BYTES]); OPENSSL_EXPORT bcm_status BCM_mldsa87_public_from_private( - struct BCM_mldsa87_public_key *out_public_key, - const struct BCM_mldsa87_private_key *private_key); + MLDSA87_public_key *out_public_key, const MLDSA87_private_key *private_key); -OPENSSL_EXPORT bcm_status BCM_mldsa87_sign( - uint8_t out_encoded_signature[BCM_MLDSA87_SIGNATURE_BYTES], - const struct BCM_mldsa87_private_key *private_key, const uint8_t *msg, - size_t msg_len, const uint8_t *context, size_t context_len); +// BCM_mldsa87_public_of_private returns the public half of `private_key`. +const MLDSA87_public_key *BCM_mldsa87_public_of_private( + const MLDSA87_private_key *private_key); OPENSSL_EXPORT bcm_status -BCM_mldsa87_verify(const struct BCM_mldsa87_public_key *public_key, +BCM_mldsa87_check_key_fips(MLDSA87_private_key *private_key); + +OPENSSL_EXPORT bcm_status BCM_mldsa87_generate_key_fips( + uint8_t out_encoded_public_key[MLDSA87_PUBLIC_KEY_BYTES], + uint8_t out_seed[MLDSA_SEED_BYTES], MLDSA87_private_key *out_private_key); + +OPENSSL_EXPORT bcm_status BCM_mldsa87_private_key_from_seed_fips( + MLDSA87_private_key *out_private_key, const uint8_t seed[MLDSA_SEED_BYTES]); + +OPENSSL_EXPORT bcm_status +BCM_mldsa87_sign(uint8_t out_encoded_signature[MLDSA87_SIGNATURE_BYTES], + const MLDSA87_private_key *private_key, const uint8_t *msg, + size_t msg_len, const uint8_t *context, size_t context_len); + +OPENSSL_EXPORT bcm_status +BCM_mldsa87_verify(const MLDSA87_public_key *public_key, const uint8_t *signature, const uint8_t *msg, size_t msg_len, const uint8_t *context, size_t context_len); -OPENSSL_EXPORT bcm_status BCM_mldsa87_marshal_public_key( - CBB *out, const struct BCM_mldsa87_public_key *public_key); +OPENSSL_EXPORT void BCM_mldsa87_prehash_init( + MLDSA87_prehash *out_prehash_ctx, const MLDSA87_public_key *public_key, + const uint8_t *context, size_t context_len); -OPENSSL_EXPORT bcm_status BCM_mldsa87_parse_public_key( - struct BCM_mldsa87_public_key *public_key, CBS *in); +OPENSSL_EXPORT void BCM_mldsa87_prehash_update( + MLDSA87_prehash *inout_prehash_ctx, const uint8_t *msg, size_t msg_len); -OPENSSL_EXPORT bcm_status BCM_mldsa87_parse_private_key( - struct BCM_mldsa87_private_key *private_key, CBS *in); +OPENSSL_EXPORT void BCM_mldsa87_prehash_finalize( + uint8_t out_msg_rep[MLDSA_MU_BYTES], MLDSA87_prehash *inout_prehash_ctx); + +OPENSSL_EXPORT bcm_status BCM_mldsa87_sign_message_representative( + uint8_t out_encoded_signature[MLDSA87_SIGNATURE_BYTES], + const MLDSA87_private_key *private_key, + const uint8_t msg_rep[MLDSA_MU_BYTES]); + +OPENSSL_EXPORT bcm_status BCM_mldsa87_verify_message_representative( + const MLDSA87_public_key *public_key, + const uint8_t signature[MLDSA87_SIGNATURE_BYTES], + const uint8_t msg_rep[MLDSA_MU_BYTES]); + +OPENSSL_EXPORT bcm_status +BCM_mldsa87_marshal_public_key(CBB *out, const MLDSA87_public_key *public_key); + +OPENSSL_EXPORT bcm_status +BCM_mldsa87_parse_public_key(MLDSA87_public_key *public_key, CBS *in); + +OPENSSL_EXPORT bcm_status +BCM_mldsa87_parse_private_key(MLDSA87_private_key *private_key, CBS *in); // BCM_mldsa87_generate_key_external_entropy generates a public/private key pair // using the given seed, writes the encoded public key to -// |out_encoded_public_key| and sets |out_private_key| to the private key. +// `out_encoded_public_key` and sets `out_private_key` to the private key. OPENSSL_EXPORT bcm_status BCM_mldsa87_generate_key_external_entropy( - uint8_t out_encoded_public_key[BCM_MLDSA87_PUBLIC_KEY_BYTES], - struct BCM_mldsa87_private_key *out_private_key, - const uint8_t entropy[BCM_MLDSA_SEED_BYTES]); + uint8_t out_encoded_public_key[MLDSA87_PUBLIC_KEY_BYTES], + MLDSA87_private_key *out_private_key, + const uint8_t entropy[MLDSA_SEED_BYTES]); -// BCM_mldsa87_sign_internal signs |msg| using |private_key| and writes the -// signature to |out_encoded_signature|. The |context_prefix| and |context| are -// prefixed to the message, in that order, before signing. The |randomizer| +OPENSSL_EXPORT bcm_status BCM_mldsa87_generate_key_external_entropy_fips( + uint8_t out_encoded_public_key[MLDSA87_PUBLIC_KEY_BYTES], + MLDSA87_private_key *out_private_key, + const uint8_t entropy[MLDSA_SEED_BYTES]); + +// BCM_mldsa87_sign_internal signs `msg` using `private_key` and writes the +// signature to `out_encoded_signature`. The `context_prefix` and `context` are +// prefixed to the message, in that order, before signing. The `randomizer` // value can be set to zero bytes in order to make a deterministic signature, or -// else filled with entropy for the usual |MLDSA_sign| behavior. +// else filled with entropy for the usual `MLDSA_sign` behavior. OPENSSL_EXPORT bcm_status BCM_mldsa87_sign_internal( - uint8_t out_encoded_signature[BCM_MLDSA87_SIGNATURE_BYTES], - const struct BCM_mldsa87_private_key *private_key, const uint8_t *msg, - size_t msg_len, const uint8_t *context_prefix, size_t context_prefix_len, + uint8_t out_encoded_signature[MLDSA87_SIGNATURE_BYTES], + const MLDSA87_private_key *private_key, const uint8_t *msg, size_t msg_len, + const uint8_t *context_prefix, size_t context_prefix_len, const uint8_t *context, size_t context_len, const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]); -// BCM_mldsa87_verify_internal verifies that |encoded_signature| is a valid -// signature of |msg| by |public_key|. The |context_prefix| and |context| are +OPENSSL_EXPORT bcm_status BCM_mldsa87_sign_mu_internal( + uint8_t out_encoded_signature[MLDSA87_SIGNATURE_BYTES], + const MLDSA87_private_key *private_key, + const uint8_t msg_rep[MLDSA_MU_BYTES], + const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]); + +// BCM_mldsa87_verify_internal verifies that `encoded_signature` is a valid +// signature of `msg` by `public_key`. The `context_prefix` and `context` are // prefixed to the message before verification, in that order. OPENSSL_EXPORT bcm_status BCM_mldsa87_verify_internal( - const struct BCM_mldsa87_public_key *public_key, - const uint8_t encoded_signature[BCM_MLDSA87_SIGNATURE_BYTES], + const MLDSA87_public_key *public_key, + const uint8_t encoded_signature[MLDSA87_SIGNATURE_BYTES], const uint8_t *msg, size_t msg_len, const uint8_t *context_prefix, size_t context_prefix_len, const uint8_t *context, size_t context_len); -// BCM_mldsa87_marshal_private_key serializes |private_key| to |out| in the +// BCM_mldsa87_marshal_private_key serializes `private_key` to `out` in the // NIST format for ML-DSA-87 private keys. OPENSSL_EXPORT bcm_status BCM_mldsa87_marshal_private_key( - CBB *out, const struct BCM_mldsa87_private_key *private_key); + CBB *out, const MLDSA87_private_key *private_key); + +// BCM_mldsa87_public_keys_equal returns one if `a` and `b` are equal and zero +// otherwise. +int BCM_mldsa87_public_keys_equal(const MLDSA87_public_key *a, + const MLDSA87_public_key *b); + +// BCM_MLDSA44_PRIVATE_KEY_BYTES is the number of bytes in an encoded ML-DSA-44 +// private key. +#define BCM_MLDSA44_PRIVATE_KEY_BYTES 2560 + +OPENSSL_EXPORT bcm_status BCM_mldsa44_generate_key( + uint8_t out_encoded_public_key[MLDSA44_PUBLIC_KEY_BYTES], + uint8_t out_seed[MLDSA_SEED_BYTES], MLDSA44_private_key *out_private_key); + +OPENSSL_EXPORT bcm_status BCM_mldsa44_private_key_from_seed( + MLDSA44_private_key *out_private_key, const uint8_t seed[MLDSA_SEED_BYTES]); + +OPENSSL_EXPORT bcm_status BCM_mldsa44_public_from_private( + MLDSA44_public_key *out_public_key, const MLDSA44_private_key *private_key); + +// BCM_mldsa44_public_of_private returns the public half of `private_key`. +const MLDSA44_public_key *BCM_mldsa44_public_of_private( + const MLDSA44_private_key *private_key); + +OPENSSL_EXPORT bcm_status +BCM_mldsa44_check_key_fips(MLDSA44_private_key *private_key); + +OPENSSL_EXPORT bcm_status BCM_mldsa44_generate_key_fips( + uint8_t out_encoded_public_key[MLDSA44_PUBLIC_KEY_BYTES], + uint8_t out_seed[MLDSA_SEED_BYTES], MLDSA44_private_key *out_private_key); + +OPENSSL_EXPORT bcm_status BCM_mldsa44_private_key_from_seed_fips( + MLDSA44_private_key *out_private_key, const uint8_t seed[MLDSA_SEED_BYTES]); + +OPENSSL_EXPORT bcm_status +BCM_mldsa44_sign(uint8_t out_encoded_signature[MLDSA44_SIGNATURE_BYTES], + const MLDSA44_private_key *private_key, const uint8_t *msg, + size_t msg_len, const uint8_t *context, size_t context_len); + +OPENSSL_EXPORT bcm_status +BCM_mldsa44_verify(const MLDSA44_public_key *public_key, + const uint8_t *signature, const uint8_t *msg, size_t msg_len, + const uint8_t *context, size_t context_len); + +OPENSSL_EXPORT void BCM_mldsa44_prehash_init( + MLDSA44_prehash *out_prehash_ctx, const MLDSA44_public_key *public_key, + const uint8_t *context, size_t context_len); + +OPENSSL_EXPORT void BCM_mldsa44_prehash_update( + MLDSA44_prehash *inout_prehash_ctx, const uint8_t *msg, size_t msg_len); + +OPENSSL_EXPORT void BCM_mldsa44_prehash_finalize( + uint8_t out_msg_rep[MLDSA_MU_BYTES], MLDSA44_prehash *inout_prehash_ctx); + +OPENSSL_EXPORT bcm_status BCM_mldsa44_sign_message_representative( + uint8_t out_encoded_signature[MLDSA44_SIGNATURE_BYTES], + const MLDSA44_private_key *private_key, + const uint8_t msg_rep[MLDSA_MU_BYTES]); + +OPENSSL_EXPORT bcm_status BCM_mldsa44_verify_message_representative( + const MLDSA44_public_key *public_key, + const uint8_t signature[MLDSA44_SIGNATURE_BYTES], + const uint8_t msg_rep[MLDSA_MU_BYTES]); + +OPENSSL_EXPORT bcm_status +BCM_mldsa44_marshal_public_key(CBB *out, const MLDSA44_public_key *public_key); + +OPENSSL_EXPORT bcm_status +BCM_mldsa44_parse_public_key(MLDSA44_public_key *public_key, CBS *in); + +OPENSSL_EXPORT bcm_status +BCM_mldsa44_parse_private_key(MLDSA44_private_key *private_key, CBS *in); + +// BCM_mldsa44_generate_key_external_entropy generates a public/private key pair +// using the given seed, writes the encoded public key to +// `out_encoded_public_key` and sets `out_private_key` to the private key. +OPENSSL_EXPORT bcm_status BCM_mldsa44_generate_key_external_entropy( + uint8_t out_encoded_public_key[MLDSA44_PUBLIC_KEY_BYTES], + MLDSA44_private_key *out_private_key, + const uint8_t entropy[MLDSA_SEED_BYTES]); + +OPENSSL_EXPORT bcm_status BCM_mldsa44_generate_key_external_entropy_fips( + uint8_t out_encoded_public_key[MLDSA44_PUBLIC_KEY_BYTES], + MLDSA44_private_key *out_private_key, + const uint8_t entropy[MLDSA_SEED_BYTES]); + +// BCM_mldsa44_sign_internal signs `msg` using `private_key` and writes the +// signature to `out_encoded_signature`. The `context_prefix` and `context` are +// prefixed to the message, in that order, before signing. The `randomizer` +// value can be set to zero bytes in order to make a deterministic signature, or +// else filled with entropy for the usual `MLDSA_sign` behavior. +OPENSSL_EXPORT bcm_status BCM_mldsa44_sign_internal( + uint8_t out_encoded_signature[MLDSA44_SIGNATURE_BYTES], + const MLDSA44_private_key *private_key, const uint8_t *msg, size_t msg_len, + const uint8_t *context_prefix, size_t context_prefix_len, + const uint8_t *context, size_t context_len, + const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]); + +OPENSSL_EXPORT bcm_status BCM_mldsa44_sign_mu_internal( + uint8_t out_encoded_signature[MLDSA44_SIGNATURE_BYTES], + const MLDSA44_private_key *private_key, + const uint8_t msg_rep[MLDSA_MU_BYTES], + const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]); + +// BCM_mldsa44_verify_internal verifies that `encoded_signature` is a valid +// signature of `msg` by `public_key`. The `context_prefix` and `context` are +// prefixed to the message before verification, in that order. +OPENSSL_EXPORT bcm_status BCM_mldsa44_verify_internal( + const MLDSA44_public_key *public_key, + const uint8_t encoded_signature[MLDSA44_SIGNATURE_BYTES], + const uint8_t *msg, size_t msg_len, const uint8_t *context_prefix, + size_t context_prefix_len, const uint8_t *context, size_t context_len); + +// BCM_mldsa44_marshal_private_key serializes `private_key` to `out` in the +// NIST format for ML-DSA-44 private keys. +OPENSSL_EXPORT bcm_status BCM_mldsa44_marshal_private_key( + CBB *out, const MLDSA44_private_key *private_key); + +// BCM_mldsa44_public_keys_equal returns one if `a` and `b` are equal and zero +// otherwise. +int BCM_mldsa44_public_keys_equal(const MLDSA44_public_key *a, + const MLDSA44_public_key *b); // ML-KEM @@ -447,200 +593,182 @@ OPENSSL_EXPORT bcm_status BCM_mldsa87_marshal_private_key( // decapsulating party. #define BCM_MLKEM_ENCAP_ENTROPY 32 -// BCM_MLKEM768_PUBLIC_KEY_BYTES is the number of bytes in an encoded ML-KEM-768 -// public key. -#define BCM_MLKEM768_PUBLIC_KEY_BYTES 1184 - -// BCM_MLKEM1024_PUBLIC_KEY_BYTES is the number of bytes in an encoded -// ML-KEM-1024 public key. -#define BCM_MLKEM1024_PUBLIC_KEY_BYTES 1568 - -// BCM_MLKEM768_CIPHERTEXT_BYTES is number of bytes in the ML-KEM-768 -// ciphertext. -#define BCM_MLKEM768_CIPHERTEXT_BYTES 1088 - -// BCM_MLKEM1024_CIPHERTEXT_BYTES is number of bytes in the ML-KEM-1024 -// ciphertext. -#define BCM_MLKEM1024_CIPHERTEXT_BYTES 1568 - // BCM_MLKEM768_PRIVATE_KEY_BYTES is the length of the data produced by -// |BCM_mlkem768_marshal_private_key|. +// `BCM_mlkem768_marshal_private_key`. #define BCM_MLKEM768_PRIVATE_KEY_BYTES 2400 // BCM_MLKEM1024_PRIVATE_KEY_BYTES is the length of the data produced by -// |BCM_mlkem1024_marshal_private_key|. +// `BCM_mlkem1024_marshal_private_key`. #define BCM_MLKEM1024_PRIVATE_KEY_BYTES 3168 -// BCM_MLKEM_SEED_BYTES is the number of bytes in an ML-KEM seed. -#define BCM_MLKEM_SEED_BYTES 64 - -// BCM_mlkem_SHARED_SECRET_BYTES is the number of bytes in an ML-KEM shared -// secret. -#define BCM_MLKEM_SHARED_SECRET_BYTES 32 - -struct BCM_mlkem768_public_key { - union { - uint8_t bytes[512 * (3 + 9) + 32 + 32]; - uint16_t alignment; - } opaque; -}; - -struct BCM_mlkem768_private_key { - union { - uint8_t bytes[512 * (3 + 3 + 9) + 32 + 32 + 32]; - uint16_t alignment; - } opaque; -}; - OPENSSL_EXPORT bcm_infallible BCM_mlkem768_generate_key( - uint8_t out_encoded_public_key[BCM_MLKEM768_PUBLIC_KEY_BYTES], - uint8_t optional_out_seed[BCM_MLKEM_SEED_BYTES], - struct BCM_mlkem768_private_key *out_private_key); - -OPENSSL_EXPORT bcm_status BCM_mlkem768_private_key_from_seed( - struct BCM_mlkem768_private_key *out_private_key, const uint8_t *seed, - size_t seed_len); - -OPENSSL_EXPORT bcm_infallible BCM_mlkem768_public_from_private( - struct BCM_mlkem768_public_key *out_public_key, - const struct BCM_mlkem768_private_key *private_key); - -OPENSSL_EXPORT bcm_infallible -BCM_mlkem768_encap(uint8_t out_ciphertext[BCM_MLKEM768_CIPHERTEXT_BYTES], - uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], - const struct BCM_mlkem768_public_key *public_key); + uint8_t out_encoded_public_key[MLKEM768_PUBLIC_KEY_BYTES], + uint8_t optional_out_seed[MLKEM_SEED_BYTES], + MLKEM768_private_key *out_private_key); OPENSSL_EXPORT bcm_status -BCM_mlkem768_decap(uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], +BCM_mlkem768_private_key_from_seed(MLKEM768_private_key *out_private_key, + const uint8_t *seed, size_t seed_len); + +OPENSSL_EXPORT bcm_status BCM_mlkem768_generate_key_fips( + uint8_t out_encoded_public_key[MLKEM768_PUBLIC_KEY_BYTES], + uint8_t optional_out_seed[MLKEM_SEED_BYTES], + MLKEM768_private_key *out_private_key); + +OPENSSL_EXPORT bcm_status +BCM_mlkem768_check_fips(const MLKEM768_private_key *private_key); + +OPENSSL_EXPORT bcm_infallible +BCM_mlkem768_public_from_private(MLKEM768_public_key *out_public_key, + const MLKEM768_private_key *private_key); + +OPENSSL_EXPORT const MLKEM768_public_key *BCM_mlkem768_public_of_private( + const MLKEM768_private_key *private_key); + +OPENSSL_EXPORT bcm_infallible +BCM_mlkem768_encap(uint8_t out_ciphertext[MLKEM768_CIPHERTEXT_BYTES], + uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], + const MLKEM768_public_key *public_key); + +OPENSSL_EXPORT bcm_status +BCM_mlkem768_decap(uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], const uint8_t *ciphertext, size_t ciphertext_len, - const struct BCM_mlkem768_private_key *private_key); + const MLKEM768_private_key *private_key); OPENSSL_EXPORT bcm_status BCM_mlkem768_marshal_public_key( - CBB *out, const struct BCM_mlkem768_public_key *public_key); + CBB *out, const MLKEM768_public_key *public_key); -OPENSSL_EXPORT bcm_status BCM_mlkem768_parse_public_key( - struct BCM_mlkem768_public_key *out_public_key, CBS *in); +// BCM_mlkem768_public_keys_equal returns one if `a` and `b` are equal and zero +// otherwise. +int BCM_mlkem768_public_keys_equal(const MLKEM768_public_key *a, + const MLKEM768_public_key *b); + +OPENSSL_EXPORT bcm_status +BCM_mlkem768_parse_public_key(MLKEM768_public_key *out_public_key, CBS *in); // BCM_mlkem768_parse_private_key parses a private key, in NIST's format for -// private keys, from |in| and writes the result to |out_private_key|. It +// private keys, from `in` and writes the result to `out_private_key`. It // returns one on success or zero on parse error or if there are trailing bytes -// in |in|. This format is verbose and should be avoided. Private keys should be -// stored as seeds and parsed using |BCM_mlkem768_private_key_from_seed|. -OPENSSL_EXPORT bcm_status BCM_mlkem768_parse_private_key( - struct BCM_mlkem768_private_key *out_private_key, CBS *in); +// in `in`. This format is verbose and should be avoided. Private keys should be +// stored as seeds and parsed using `BCM_mlkem768_private_key_from_seed`. +OPENSSL_EXPORT bcm_status +BCM_mlkem768_parse_private_key(MLKEM768_private_key *out_private_key, CBS *in); // BCM_mlkem768_generate_key_external_seed is a deterministic function to create // a pair of ML-KEM-768 keys, using the supplied seed. The seed needs to be // uniformly random. This function should only be used for tests; regular -// callers should use the non-deterministic |BCM_mlkem768_generate_key| +// callers should use the non-deterministic `BCM_mlkem768_generate_key` // directly. OPENSSL_EXPORT bcm_infallible BCM_mlkem768_generate_key_external_seed( - uint8_t out_encoded_public_key[BCM_MLKEM768_PUBLIC_KEY_BYTES], - struct BCM_mlkem768_private_key *out_private_key, - const uint8_t seed[BCM_MLKEM_SEED_BYTES]); + uint8_t out_encoded_public_key[MLKEM768_PUBLIC_KEY_BYTES], + MLKEM768_private_key *out_private_key, + const uint8_t seed[MLKEM_SEED_BYTES]); -// BCM_mlkem768_encap_external_entropy behaves like |MLKEM768_encap|, but uses -// |MLKEM_ENCAP_ENTROPY| bytes of |entropy| for randomization. The decapsulating -// side will be able to recover |entropy| in full. This function should only be +// BCM_mlkem768_encap_external_entropy behaves like `MLKEM768_encap`, but uses +// `MLKEM_ENCAP_ENTROPY` bytes of `entropy` for randomization. The decapsulating +// side will be able to recover `entropy` in full. This function should only be // used for tests, regular callers should use the non-deterministic -// |BCM_mlkem768_encap| directly. +// `BCM_mlkem768_encap` directly. OPENSSL_EXPORT bcm_infallible BCM_mlkem768_encap_external_entropy( - uint8_t out_ciphertext[BCM_MLKEM768_CIPHERTEXT_BYTES], - uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], - const struct BCM_mlkem768_public_key *public_key, + uint8_t out_ciphertext[MLKEM768_CIPHERTEXT_BYTES], + uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], + const MLKEM768_public_key *public_key, const uint8_t entropy[BCM_MLKEM_ENCAP_ENTROPY]); -// BCM_mlkem768_marshal_private_key serializes |private_key| to |out| in the +// BCM_mlkem768_marshal_private_key serializes `private_key` to `out` in the // NIST format for ML-KEM-768 private keys. (Note that one can also save just -// the seed value produced by |BCM_mlkem768_generate_key|, which is +// the seed value produced by `BCM_mlkem768_generate_key`, which is // significantly smaller.) OPENSSL_EXPORT bcm_status BCM_mlkem768_marshal_private_key( - CBB *out, const struct BCM_mlkem768_private_key *private_key); - -struct BCM_mlkem1024_public_key { - union { - uint8_t bytes[512 * (4 + 16) + 32 + 32]; - uint16_t alignment; - } opaque; -}; - -struct BCM_mlkem1024_private_key { - union { - uint8_t bytes[512 * (4 + 4 + 16) + 32 + 32 + 32]; - uint16_t alignment; - } opaque; -}; + CBB *out, const MLKEM768_private_key *private_key); OPENSSL_EXPORT bcm_infallible BCM_mlkem1024_generate_key( - uint8_t out_encoded_public_key[BCM_MLKEM1024_PUBLIC_KEY_BYTES], - uint8_t optional_out_seed[BCM_MLKEM_SEED_BYTES], - struct BCM_mlkem1024_private_key *out_private_key); + uint8_t out_encoded_public_key[MLKEM1024_PUBLIC_KEY_BYTES], + uint8_t optional_out_seed[MLKEM_SEED_BYTES], + MLKEM1024_private_key *out_private_key); -OPENSSL_EXPORT bcm_status BCM_mlkem1024_private_key_from_seed( - struct BCM_mlkem1024_private_key *out_private_key, const uint8_t *seed, - size_t seed_len); - -OPENSSL_EXPORT bcm_infallible BCM_mlkem1024_public_from_private( - struct BCM_mlkem1024_public_key *out_public_key, - const struct BCM_mlkem1024_private_key *private_key); - -OPENSSL_EXPORT bcm_infallible -BCM_mlkem1024_encap(uint8_t out_ciphertext[BCM_MLKEM1024_CIPHERTEXT_BYTES], - uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], - const struct BCM_mlkem1024_public_key *public_key); +OPENSSL_EXPORT bcm_status BCM_mlkem1024_generate_key_fips( + uint8_t out_encoded_public_key[MLKEM1024_PUBLIC_KEY_BYTES], + uint8_t optional_out_seed[MLKEM_SEED_BYTES], + MLKEM1024_private_key *out_private_key); OPENSSL_EXPORT bcm_status -BCM_mlkem1024_decap(uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], +BCM_mlkem1024_check_fips(const MLKEM1024_private_key *private_key); + +OPENSSL_EXPORT bcm_status +BCM_mlkem1024_private_key_from_seed(MLKEM1024_private_key *out_private_key, + const uint8_t *seed, size_t seed_len); + +OPENSSL_EXPORT bcm_infallible +BCM_mlkem1024_public_from_private(MLKEM1024_public_key *out_public_key, + const MLKEM1024_private_key *private_key); + +OPENSSL_EXPORT const MLKEM1024_public_key *BCM_mlkem1024_public_of_private( + const MLKEM1024_private_key *private_key); + +OPENSSL_EXPORT bcm_infallible +BCM_mlkem1024_encap(uint8_t out_ciphertext[MLKEM1024_CIPHERTEXT_BYTES], + uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], + const MLKEM1024_public_key *public_key); + +OPENSSL_EXPORT bcm_status +BCM_mlkem1024_decap(uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], const uint8_t *ciphertext, size_t ciphertext_len, - const struct BCM_mlkem1024_private_key *private_key); + const MLKEM1024_private_key *private_key); OPENSSL_EXPORT bcm_status BCM_mlkem1024_marshal_public_key( - CBB *out, const struct BCM_mlkem1024_public_key *public_key); + CBB *out, const MLKEM1024_public_key *public_key); -OPENSSL_EXPORT bcm_status BCM_mlkem1024_parse_public_key( - struct BCM_mlkem1024_public_key *out_public_key, CBS *in); +// BCM_mlkem1024_public_keys_equal returns one if `a` and `b` are equal and zero +// otherwise. +int BCM_mlkem1024_public_keys_equal(const MLKEM1024_public_key *a, + const MLKEM1024_public_key *b); + +OPENSSL_EXPORT bcm_status +BCM_mlkem1024_parse_public_key(MLKEM1024_public_key *out_public_key, CBS *in); // BCM_mlkem1024_parse_private_key parses a private key, in NIST's format for -// private keys, from |in| and writes the result to |out_private_key|. It +// private keys, from `in` and writes the result to `out_private_key`. It // returns one on success or zero on parse error or if there are trailing bytes -// in |in|. This format is verbose and should be avoided. Private keys should be -// stored as seeds and parsed using |BCM_mlkem1024_private_key_from_seed|. +// in `in`. This format is verbose and should be avoided. Private keys should be +// stored as seeds and parsed using `BCM_mlkem1024_private_key_from_seed`. OPENSSL_EXPORT bcm_status BCM_mlkem1024_parse_private_key( - struct BCM_mlkem1024_private_key *out_private_key, CBS *in); + MLKEM1024_private_key *out_private_key, CBS *in); // BCM_mlkem1024_generate_key_external_seed is a deterministic function to // create a pair of ML-KEM-1024 keys, using the supplied seed. The seed needs to // be uniformly random. This function should only be used for tests, regular -// callers should use the non-deterministic |BCM_mlkem1024_generate_key| +// callers should use the non-deterministic `BCM_mlkem1024_generate_key` // directly. OPENSSL_EXPORT bcm_infallible BCM_mlkem1024_generate_key_external_seed( - uint8_t out_encoded_public_key[BCM_MLKEM1024_PUBLIC_KEY_BYTES], - struct BCM_mlkem1024_private_key *out_private_key, - const uint8_t seed[BCM_MLKEM_SEED_BYTES]); + uint8_t out_encoded_public_key[MLKEM1024_PUBLIC_KEY_BYTES], + MLKEM1024_private_key *out_private_key, + const uint8_t seed[MLKEM_SEED_BYTES]); -// BCM_mlkem1024_encap_external_entropy behaves like |MLKEM1024_encap|, but uses -// |MLKEM_ENCAP_ENTROPY| bytes of |entropy| for randomization. The -// decapsulating side will be able to recover |entropy| in full. This function +// BCM_mlkem1024_encap_external_entropy behaves like `MLKEM1024_encap`, but uses +// `MLKEM_ENCAP_ENTROPY` bytes of `entropy` for randomization. The +// decapsulating side will be able to recover `entropy` in full. This function // should only be used for tests, regular callers should use the -// non-deterministic |BCM_mlkem1024_encap| directly. +// non-deterministic `BCM_mlkem1024_encap` directly. OPENSSL_EXPORT bcm_infallible BCM_mlkem1024_encap_external_entropy( - uint8_t out_ciphertext[BCM_MLKEM1024_CIPHERTEXT_BYTES], - uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], - const struct BCM_mlkem1024_public_key *public_key, + uint8_t out_ciphertext[MLKEM1024_CIPHERTEXT_BYTES], + uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], + const MLKEM1024_public_key *public_key, const uint8_t entropy[BCM_MLKEM_ENCAP_ENTROPY]); -// BCM_mlkem1024_marshal_private_key serializes |private_key| to |out| in the +// BCM_mlkem1024_marshal_private_key serializes `private_key` to `out` in the // NIST format for ML-KEM-1024 private keys. (Note that one can also save just -// the seed value produced by |BCM_mlkem1024_generate_key|, which is +// the seed value produced by `BCM_mlkem1024_generate_key`, which is // significantly smaller.) OPENSSL_EXPORT bcm_status BCM_mlkem1024_marshal_private_key( - CBB *out, const struct BCM_mlkem1024_private_key *private_key); + CBB *out, const MLKEM1024_private_key *private_key); // SLH-DSA // Output length of the hash function. #define BCM_SLHDSA_SHA2_128S_N 16 +#define BCM_SLHDSA_SHAKE_256F_N 32 // The number of bytes at the beginning of M', the augmented message, before the // context. @@ -649,28 +777,49 @@ OPENSSL_EXPORT bcm_status BCM_mlkem1024_marshal_private_key( // SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES is the number of bytes in an // SLH-DSA-SHA2-128s public key. #define BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES 32 +#define BCM_SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES 64 // BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES is the number of bytes in an // SLH-DSA-SHA2-128s private key. #define BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES 64 +#define BCM_SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES 128 // BCM_SLHDSA_SHA2_128S_SIGNATURE_BYTES is the number of bytes in an // SLH-DSA-SHA2-128s signature. #define BCM_SLHDSA_SHA2_128S_SIGNATURE_BYTES 7856 +#define BCM_SLHDSA_SHAKE_256F_SIGNATURE_BYTES 49856 -// SLHDSA_SHA2_128S_generate_key_from_seed generates an SLH-DSA-SHA2-128s key -// pair from a 48-byte seed and writes the result to |out_public_key| and -// |out_secret_key|. +// BCM_slhdsa_sha2_128s_generate_key_from_seed generates an SLH-DSA-SHA2-128s +// key pair from a 48-byte seed and writes the result to `out_public_key` and +// `out_secret_key`. OPENSSL_EXPORT bcm_infallible BCM_slhdsa_sha2_128s_generate_key_from_seed( uint8_t out_public_key[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], uint8_t out_secret_key[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES], const uint8_t seed[3 * BCM_SLHDSA_SHA2_128S_N]); -// BCM_slhdsa_sha2_128s_sign_internal acts like |SLHDSA_SHA2_128S_sign| but +OPENSSL_EXPORT bcm_infallible 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]); + +// BCM_slhdsa_sha2_128s_generate_key_from_seed_fips does the same thing as +// `BCM_slhdsa_sha2_128s_generate_key_from_seed` but implements the required +// second check before generating a key by testing for nullptr arguments. +OPENSSL_EXPORT bcm_status BCM_slhdsa_sha2_128s_generate_key_from_seed_fips( + uint8_t out_public_key[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], + uint8_t out_secret_key[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES], + const uint8_t seed[3 * BCM_SLHDSA_SHA2_128S_N]); + +OPENSSL_EXPORT bcm_status BCM_slhdsa_shake_256f_generate_key_from_seed_fips( + 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]); + +// BCM_slhdsa_sha2_128s_sign_internal acts like `SLHDSA_SHA2_128S_sign` but // accepts an explicit entropy input, which can be PK.seed (bytes 32..48 of // the private key) to generate deterministic signatures. It also takes the // input message in three parts so that the "internal" version of the signing -// function, from section 9.2, can be implemented. The |header| argument may be +// function, from section 9.2, can be implemented. The `header` argument may be // NULL to omit it. OPENSSL_EXPORT bcm_infallible BCM_slhdsa_sha2_128s_sign_internal( uint8_t out_signature[BCM_SLHDSA_SHA2_128S_SIGNATURE_BYTES], @@ -679,9 +828,16 @@ OPENSSL_EXPORT bcm_infallible BCM_slhdsa_sha2_128s_sign_internal( size_t context_len, const uint8_t *msg, size_t msg_len, const uint8_t entropy[BCM_SLHDSA_SHA2_128S_N]); -// BCM_slhdsa_sha2_128s_verify_internal acts like |SLHDSA_SHA2_128S_verify| but +OPENSSL_EXPORT bcm_infallible BCM_slhdsa_shake_256f_sign_internal( + uint8_t out_signature[BCM_SLHDSA_SHAKE_256F_SIGNATURE_BYTES], + const uint8_t secret_key[BCM_SLHDSA_SHAKE_256F_PRIVATE_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, + const uint8_t entropy[BCM_SLHDSA_SHAKE_256F_N]); + +// BCM_slhdsa_sha2_128s_verify_internal acts like `SLHDSA_SHA2_128S_verify` but // takes the input message in three parts so that the "internal" version of the -// verification function, from section 9.3, can be implemented. The |header| +// verification function, from section 9.3, can be implemented. The `header` // argument may be NULL to omit it. OPENSSL_EXPORT bcm_status BCM_slhdsa_sha2_128s_verify_internal( const uint8_t *signature, size_t signature_len, @@ -689,41 +845,109 @@ OPENSSL_EXPORT bcm_status BCM_slhdsa_sha2_128s_verify_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); +OPENSSL_EXPORT bcm_status BCM_slhdsa_shake_256f_verify_internal( + const uint8_t *signature, size_t signature_len, + 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); + OPENSSL_EXPORT bcm_infallible BCM_slhdsa_sha2_128s_generate_key( uint8_t out_public_key[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], uint8_t out_private_key[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES]); +OPENSSL_EXPORT bcm_infallible BCM_slhdsa_shake_256f_generate_key( + uint8_t out_public_key[BCM_SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], + uint8_t out_private_key[BCM_SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES]); + +OPENSSL_EXPORT bcm_status BCM_slhdsa_sha2_128s_generate_key_fips( + uint8_t out_public_key[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], + uint8_t out_private_key[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES]); + +OPENSSL_EXPORT bcm_status BCM_slhdsa_shake_256f_generate_key_fips( + uint8_t out_public_key[BCM_SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], + uint8_t out_private_key[BCM_SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES]); + OPENSSL_EXPORT bcm_infallible BCM_slhdsa_sha2_128s_public_from_private( uint8_t out_public_key[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], const uint8_t private_key[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES]); +OPENSSL_EXPORT bcm_infallible BCM_slhdsa_shake_256f_public_from_private( + uint8_t out_public_key[BCM_SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], + const uint8_t private_key[BCM_SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES]); + OPENSSL_EXPORT bcm_status BCM_slhdsa_sha2_128s_sign( uint8_t out_signature[BCM_SLHDSA_SHA2_128S_SIGNATURE_BYTES], const uint8_t private_key[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES], const uint8_t *msg, size_t msg_len, const uint8_t *context, size_t context_len); +OPENSSL_EXPORT bcm_status BCM_slhdsa_shake_256f_sign( + uint8_t out_signature[BCM_SLHDSA_SHAKE_256F_SIGNATURE_BYTES], + const uint8_t private_key[BCM_SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES], + const uint8_t *msg, size_t msg_len, const uint8_t *context, + size_t context_len); + OPENSSL_EXPORT bcm_status BCM_slhdsa_sha2_128s_verify( const uint8_t *signature, size_t signature_len, const uint8_t public_key[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], const uint8_t *msg, size_t msg_len, const uint8_t *context, size_t context_len); +OPENSSL_EXPORT bcm_status BCM_slhdsa_shake_256f_verify( + const uint8_t *signature, size_t signature_len, + const uint8_t public_key[BCM_SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], + const uint8_t *msg, size_t msg_len, const uint8_t *context, + size_t context_len); + OPENSSL_EXPORT bcm_status BCM_slhdsa_sha2_128s_prehash_sign( uint8_t out_signature[BCM_SLHDSA_SHA2_128S_SIGNATURE_BYTES], const uint8_t private_key[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES], const uint8_t *hashed_msg, size_t hashed_msg_len, int hash_nid, const uint8_t *context, size_t context_len); +OPENSSL_EXPORT bcm_status BCM_slhdsa_shake_256f_prehash_sign( + uint8_t out_signature[BCM_SLHDSA_SHAKE_256F_SIGNATURE_BYTES], + const uint8_t private_key[BCM_SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES], + const uint8_t *hashed_msg, size_t hashed_msg_len, int hash_nid, + const uint8_t *context, size_t context_len); + OPENSSL_EXPORT bcm_status BCM_slhdsa_sha2_128s_prehash_verify( const uint8_t *signature, size_t signature_len, const uint8_t public_key[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], const uint8_t *hashed_msg, size_t hashed_msg_len, int hash_nid, const uint8_t *context, size_t context_len); +OPENSSL_EXPORT bcm_status BCM_slhdsa_shake_256f_prehash_verify( + const uint8_t *signature, size_t signature_len, + const uint8_t public_key[BCM_SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], + const uint8_t *hashed_msg, size_t hashed_msg_len, int hash_nid, + const uint8_t *context, size_t context_len); -#if defined(__cplusplus) -} // extern C -#endif -#endif // OPENSSL_HEADER_CRYPTO_BCM_INTERFACE_H +// AES + +// BCM_aes_encrypt encrypts a single block from `in` to `out` with `key`. The +// `in` and `out` pointers may overlap. +bcm_infallible BCM_aes_encrypt(const uint8_t *in, uint8_t *out, + const AES_KEY *key); +// BCM_aes_decrypt decrypts a single block from `in` to `out` with `key`. The +// `in` and `out` pointers may overlap. +bcm_infallible BCM_aes_decrypt(const uint8_t *in, uint8_t *out, + const AES_KEY *key); + +// BCM_aes_set_encrypt_key configures `aeskey` to encrypt with the `bits`-bit +// key, `key`. `key` must point to `bits`/8 bytes. It will return failure if +// `bits` is an invalid AES key size. +bcm_status BCM_aes_set_encrypt_key(const uint8_t *key, unsigned bits, + AES_KEY *aeskey); + +// BCM_aes_set_decrypt_key configures `aeskey` to decrypt with the `bits`-bit +// key, `key`. `key` must point to `bits`/8 bytes. It will return failure if +// `bits` is an invalid AES key size. +bcm_status BCM_aes_set_decrypt_key(const uint8_t *key, unsigned bits, + AES_KEY *aeskey); + +BSSL_NAMESPACE_END + + +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_BCM_INTERFACE_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/add.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/add.cc.inc index 13bde184..f73be4ce 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/add.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/add.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -18,6 +23,16 @@ #include "internal.h" +using namespace bssl; + +BN_ULONG bssl::bn_add_carry_words(BN_ULONG *rp, const BN_ULONG *ap, + BN_ULONG carry, size_t num) { + for (size_t i = 0; i < num; i++) { + rp[i] = CRYPTO_addc_w(ap[i], 0, carry, &carry); + } + return carry; +} + int BN_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b) { const BIGNUM *tmp; int a_neg = a->neg, ret; @@ -54,8 +69,8 @@ int BN_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b) { return ret; } -int bn_uadd_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b) { - // Widths are public, so we normalize to make |a| the larger one. +int bssl::bn_uadd_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b) { + // Widths are public, so we normalize to make `a` the larger one. if (a->width < b->width) { const BIGNUM *tmp = a; a = b; @@ -70,10 +85,7 @@ int bn_uadd_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b) { r->width = max + 1; BN_ULONG carry = bn_add_words(r->d, a->d, b->d, min); - for (int i = min; i < max; i++) { - r->d[i] = CRYPTO_addc_w(a->d[i], 0, carry, &carry); - } - + carry = bn_add_carry_words(r->d + min, a->d + min, carry, max - min); r->d[max] = carry; return 1; } @@ -174,9 +186,9 @@ int BN_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b) { return 1; } -int bn_usub_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b) { - // |b| may have more words than |a| given non-minimal inputs, but all words - // beyond |a->width| must then be zero. +int bssl::bn_usub_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b) { + // `b` may have more words than `a` given non-minimal inputs, but all words + // beyond `a->width` must then be zero. int b_width = b->width; if (b_width > a->width) { if (!bn_fits_in_words(b, a->width)) { diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/asm/x86_64-gcc.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/asm/x86_64-gcc.cc.inc index 3ba98123..f35018b1 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/asm/x86_64-gcc.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/asm/x86_64-gcc.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. /* x86_64 BIGNUM accelerator version 0.1, December 2002. * @@ -13,8 +18,7 @@ * project. * * Rights for redistribution and usage in source and binary forms are - * granted according to the OpenSSL license. Warranty of any kind is - * disclaimed. + * granted according to the License. Warranty of any kind is disclaimed. * * Q. Version 0.1? It doesn't sound like Andy, he used to assign real * versions, like 1.0... @@ -68,23 +72,23 @@ #include "../internal.h" +using namespace bssl; + #undef mul #undef mul_add // "m"(a), "+m"(r) is the way to favor DirectPath µ-code; -// "g"(0) let the compiler to decide where does it -// want to keep the value of zero; #define mul_add(r, a, word, carry) \ do { \ BN_ULONG high, low; \ __asm__("mulq %3" : "=a"(low), "=d"(high) : "a"(word), "m"(a) : "cc"); \ - __asm__("addq %2,%0; adcq %3,%1" \ + __asm__("addq %2,%0; adcq $0,%1" \ : "+r"(carry), "+d"(high) \ - : "a"(low), "g"(0) \ + : "a"(low) \ : "cc"); \ - __asm__("addq %2,%0; adcq %3,%1" \ + __asm__("addq %2,%0; adcq $0,%1" \ : "+m"(r), "+d"(high) \ - : "r"(carry), "g"(0) \ + : "r"(carry) \ : "cc"); \ (carry) = high; \ } while (0) @@ -93,18 +97,34 @@ do { \ BN_ULONG high, low; \ __asm__("mulq %3" : "=a"(low), "=d"(high) : "a"(word), "g"(a) : "cc"); \ - __asm__("addq %2,%0; adcq %3,%1" \ + __asm__("addq %2,%0; adcq $0,%1" \ : "+r"(carry), "+d"(high) \ - : "a"(low), "g"(0) \ + : "a"(low) \ : "cc"); \ (r) = (carry); \ (carry) = high; \ } while (0) -#undef sqr -#define sqr(r0, r1, a) __asm__("mulq %2" : "=a"(r0), "=d"(r1) : "a"(a) : "cc"); -BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, - BN_ULONG w) { +// r0:r1:carry = r0:r1 + a² + carry:0 +#define sqr_add(r0, r1, a, carry) \ + do { \ + BN_ULONG high, low; \ + /* lo:hi = a² */ \ + __asm__("mulq %2" : "=a"(low), "=d"(high) : "a"(a) : "cc"); \ + /* carry:hi = lo:hi + carry:0 = a² + carry */ \ + __asm__("addq %2,%0; adcq $0,%1" \ + : "+r"(carry), "+d"(high) \ + : "a"(low) \ + : "cc"); \ + /* r0:r1:carry = carry:hi + r0:r1 */ \ + __asm__("addq %2,%0; adcq %3,%1; movq $0, %2; adcq $0, %2" \ + : "+m"(r0), "+m"(r1), "+r"(carry) \ + : "d"(high) \ + : "cc"); \ + } while (0) + +BN_ULONG bssl::bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, + BN_ULONG w) { BN_ULONG c1 = 0; if (num == 0) { @@ -136,8 +156,8 @@ BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, return c1; } -BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, - BN_ULONG w) { +BN_ULONG bssl::bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, + BN_ULONG w) { BN_ULONG c1 = 0; if (num == 0) { @@ -167,35 +187,36 @@ BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, return c1; } -void bn_sqr_words(BN_ULONG *r, const BN_ULONG *a, size_t n) { +void bssl::bn_sqr_add_words(BN_ULONG *r, const BN_ULONG *a, size_t n) { if (n == 0) { return; } + BN_ULONG carry = 0; while (n & ~3) { - sqr(r[0], r[1], a[0]); - sqr(r[2], r[3], a[1]); - sqr(r[4], r[5], a[2]); - sqr(r[6], r[7], a[3]); + sqr_add(r[0], r[1], a[0], carry); + sqr_add(r[2], r[3], a[1], carry); + sqr_add(r[4], r[5], a[2], carry); + sqr_add(r[6], r[7], a[3], carry); a += 4; r += 8; n -= 4; } if (n) { - sqr(r[0], r[1], a[0]); + sqr_add(r[0], r[1], a[0], carry); if (--n == 0) { return; } - sqr(r[2], r[3], a[1]); + sqr_add(r[2], r[3], a[1], carry); if (--n == 0) { return; } - sqr(r[4], r[5], a[2]); + sqr_add(r[4], r[5], a[2], carry); } } -BN_ULONG bn_add_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, - size_t n) { +BN_ULONG bssl::bn_add_words(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *bp, size_t n) { BN_ULONG ret; size_t i = 0; @@ -215,15 +236,15 @@ BN_ULONG bn_add_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, " dec %1 \n" " jnz 1b \n" " sbbq %0,%0 \n" - : "=&r"(ret), "+c"(n), "+r"(i) + : "=&r"(ret), "+&c"(n), "+&r"(i) : "r"(rp), "r"(ap), "r"(bp) : "cc", "memory"); return ret & 1; } -BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, - size_t n) { +BN_ULONG bssl::bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *bp, size_t n) { BN_ULONG ret; size_t i = 0; @@ -243,7 +264,7 @@ BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, " dec %1 \n" " jnz 1b \n" " sbbq %0,%0 \n" - : "=&r"(ret), "+c"(n), "+r"(i) + : "=&r"(ret), "+&c"(n), "+&r"(i) : "r"(rp), "r"(ap), "r"(bp) : "cc", "memory"); @@ -252,7 +273,7 @@ BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, // mul_add_c(a,b,c0,c1,c2) -- c+=a*b for three word number c=(c2,c1,c0) // mul_add_c2(a,b,c0,c1,c2) -- c+=2*a*b for three word number c=(c2,c1,c0) -// sqr_add_c(a,i,c0,c1,c2) -- c+=a[i]^2 for three word number c=(c2,c1,c0) +// sqr_add_c(a,i,c0,c1,c2) -- c+=a[i]² for three word number c=(c2,c1,c0) // sqr_add_c2(a,i,c0,c1,c2) -- c+=2*a[i]*a[j] for three word number c=(c2,c1,c0) // Keep in mind that carrying into high part of multiplication result can not @@ -261,9 +282,9 @@ BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, do { \ BN_ULONG t1, t2; \ __asm__("mulq %3" : "=a"(t1), "=d"(t2) : "a"(a), "m"(b) : "cc"); \ - __asm__("addq %3,%0; adcq %4,%1; adcq %5,%2" \ - : "+r"(c0), "+r"(c1), "+r"(c2) \ - : "r"(t1), "r"(t2), "g"(0) \ + __asm__("addq %3,%0; adcq %4,%1; adcq $0,%2" \ + : "+&r"(c0), "+r"(c1), "+r"(c2) \ + : "r"(t1), "r"(t2) \ : "cc"); \ } while (0) @@ -271,9 +292,9 @@ BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, do { \ BN_ULONG t1, t2; \ __asm__("mulq %2" : "=a"(t1), "=d"(t2) : "a"((a)[i]) : "cc"); \ - __asm__("addq %3,%0; adcq %4,%1; adcq %5,%2" \ - : "+r"(c0), "+r"(c1), "+r"(c2) \ - : "r"(t1), "r"(t2), "g"(0) \ + __asm__("addq %3,%0; adcq %4,%1; adcq $0,%2" \ + : "+&r"(c0), "+r"(c1), "+r"(c2) \ + : "r"(t1), "r"(t2) \ : "cc"); \ } while (0) @@ -281,19 +302,20 @@ BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, do { \ BN_ULONG t1, t2; \ __asm__("mulq %3" : "=a"(t1), "=d"(t2) : "a"(a), "m"(b) : "cc"); \ - __asm__("addq %3,%0; adcq %4,%1; adcq %5,%2" \ - : "+r"(c0), "+r"(c1), "+r"(c2) \ - : "r"(t1), "r"(t2), "g"(0) \ + __asm__("addq %3,%0; adcq %4,%1; adcq $0,%2" \ + : "+&r"(c0), "+r"(c1), "+r"(c2) \ + : "r"(t1), "r"(t2) \ : "cc"); \ - __asm__("addq %3,%0; adcq %4,%1; adcq %5,%2" \ - : "+r"(c0), "+r"(c1), "+r"(c2) \ - : "r"(t1), "r"(t2), "g"(0) \ + __asm__("addq %3,%0; adcq %4,%1; adcq $0,%2" \ + : "+&r"(c0), "+r"(c1), "+r"(c2) \ + : "r"(t1), "r"(t2) \ : "cc"); \ } while (0) #define sqr_add_c2(a, i, j, c0, c1, c2) mul_add_c2((a)[i], (a)[j], c0, c1, c2) -void bn_mul_comba8(BN_ULONG r[16], const BN_ULONG a[8], const BN_ULONG b[8]) { +void bssl::bn_mul_comba8(BN_ULONG r[16], const BN_ULONG a[8], + const BN_ULONG b[8]) { BN_ULONG c1, c2, c3; c1 = 0; @@ -395,7 +417,8 @@ void bn_mul_comba8(BN_ULONG r[16], const BN_ULONG a[8], const BN_ULONG b[8]) { r[15] = c1; } -void bn_mul_comba4(BN_ULONG r[8], const BN_ULONG a[4], const BN_ULONG b[4]) { +void bssl::bn_mul_comba4(BN_ULONG r[8], const BN_ULONG a[4], + const BN_ULONG b[4]) { BN_ULONG c1, c2, c3; c1 = 0; @@ -433,7 +456,7 @@ void bn_mul_comba4(BN_ULONG r[8], const BN_ULONG a[4], const BN_ULONG b[4]) { r[7] = c2; } -void bn_sqr_comba8(BN_ULONG r[16], const BN_ULONG a[8]) { +void bssl::bn_sqr_comba8(BN_ULONG r[16], const BN_ULONG a[8]) { BN_ULONG c1, c2, c3; c1 = 0; @@ -507,7 +530,7 @@ void bn_sqr_comba8(BN_ULONG r[16], const BN_ULONG a[8]) { r[15] = c1; } -void bn_sqr_comba4(BN_ULONG r[8], const BN_ULONG a[4]) { +void bssl::bn_sqr_comba4(BN_ULONG r[8], const BN_ULONG a[4]) { BN_ULONG c1, c2, c3; c1 = 0; diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/bn.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/bn.cc.inc index 397eb44c..0af9fc55 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/bn.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/bn.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,20 +21,23 @@ #include #include +#include "../../mem_internal.h" #include "../delocate.h" #include "internal.h" -// BN_MAX_WORDS is the maximum number of words allowed in a |BIGNUM|. It is -// sized so byte and bit counts of a |BIGNUM| always fit in |int|, with room to +using namespace bssl; + +// BN_MAX_WORDS is the maximum number of words allowed in a `BIGNUM`. It is +// sized so byte and bit counts of a `BIGNUM` always fit in `int`, with room to // spare. #define BN_MAX_WORDS (INT_MAX / (4 * BN_BITS2)) -BIGNUM *BN_new(void) { - BIGNUM *bn = reinterpret_cast(OPENSSL_malloc(sizeof(BIGNUM))); +BIGNUM *BN_new() { + BIGNUM *bn = New(); - if (bn == NULL) { - return NULL; + if (bn == nullptr) { + return nullptr; } OPENSSL_memset(bn, 0, sizeof(BIGNUM)); @@ -38,12 +46,12 @@ BIGNUM *BN_new(void) { return bn; } -BIGNUM *BN_secure_new(void) { return BN_new(); } +BIGNUM *BN_secure_new() { return BN_new(); } void BN_init(BIGNUM *bn) { OPENSSL_memset(bn, 0, sizeof(BIGNUM)); } void BN_free(BIGNUM *bn) { - if (bn == NULL) { + if (bn == nullptr) { return; } @@ -52,9 +60,9 @@ void BN_free(BIGNUM *bn) { } if (bn->flags & BN_FLG_MALLOCED) { - OPENSSL_free(bn); + Delete(bn); } else { - bn->d = NULL; + bn->d = nullptr; } } @@ -63,18 +71,18 @@ void BN_clear_free(BIGNUM *bn) { BN_free(bn); } BIGNUM *BN_dup(const BIGNUM *src) { BIGNUM *copy; - if (src == NULL) { - return NULL; + if (src == nullptr) { + return nullptr; } copy = BN_new(); - if (copy == NULL) { - return NULL; + if (copy == nullptr) { + return nullptr; } if (!BN_copy(copy, src)) { BN_free(copy); - return NULL; + return nullptr; } return copy; @@ -86,7 +94,7 @@ BIGNUM *BN_copy(BIGNUM *dest, const BIGNUM *src) { } if (!bn_wexpand(dest, src->width)) { - return NULL; + return nullptr; } OPENSSL_memcpy(dest->d, src->d, sizeof(src->d[0]) * src->width); @@ -97,7 +105,7 @@ BIGNUM *BN_copy(BIGNUM *dest, const BIGNUM *src) { } void BN_clear(BIGNUM *bn) { - if (bn->d != NULL) { + if (bn->d != nullptr) { OPENSSL_memset(bn->d, 0, bn->dmax * sizeof(bn->d[0])); } @@ -115,25 +123,25 @@ DEFINE_METHOD_FUNCTION(BIGNUM, BN_value_one) { } // BN_num_bits_word returns the minimum number of bits needed to represent the -// value in |l|. +// value in `l`. unsigned BN_num_bits_word(BN_ULONG l) { - // |BN_num_bits| is often called on RSA prime factors. These have public bit + // `BN_num_bits` is often called on RSA prime factors. These have public bit // lengths, but all bits beyond the high bit are secret, so count bits in // constant time. BN_ULONG x, mask; int bits = (l != 0); #if BN_BITS2 > 32 - // Look at the upper half of |x|. |x| is at most 64 bits long. + // Look at the upper half of `x`. `x` is at most 64 bits long. x = l >> 32; - // Set |mask| to all ones if |x| (the top 32 bits of |l|) is non-zero and all + // Set `mask` to all ones if `x` (the top 32 bits of `l`) is non-zero and all // all zeros otherwise. mask = 0u - x; mask = (0u - (mask >> (BN_BITS2 - 1))); - // If |x| is non-zero, the lower half is included in the bit count in full, + // If `x` is non-zero, the lower half is included in the bit count in full, // and we count the upper half. Otherwise, we count the lower half. bits += 32 & mask; - l ^= (x ^ l) & mask; // |l| is |x| if |mask| and remains |l| otherwise. + l ^= (x ^ l) & mask; // `l` is `x` if `mask` and remains `l` otherwise. #endif // The remaining blocks are analogous iterations at lower powers of two. @@ -222,18 +230,18 @@ int BN_set_u64(BIGNUM *bn, uint64_t value) { #endif } -int bn_set_words(BIGNUM *bn, const BN_ULONG *words, size_t num) { +int bssl::bn_set_words(BIGNUM *bn, const BN_ULONG *words, size_t num) { if (!bn_wexpand(bn, num)) { return 0; } OPENSSL_memmove(bn->d, words, num * sizeof(BN_ULONG)); - // |bn_wexpand| verified that |num| isn't too large. + // `bn_wexpand` verified that `num` isn't too large. bn->width = (int)num; bn->neg = 0; return 1; } -void bn_set_static_words(BIGNUM *bn, const BN_ULONG *words, size_t num) { +void bssl::bn_set_static_words(BIGNUM *bn, const BN_ULONG *words, size_t num) { if ((bn->flags & BN_FLG_STATIC_DATA) == 0) { OPENSSL_free(bn->d); } @@ -246,8 +254,8 @@ void bn_set_static_words(BIGNUM *bn, const BN_ULONG *words, size_t num) { bn->flags |= BN_FLG_STATIC_DATA; } -int bn_fits_in_words(const BIGNUM *bn, size_t num) { - // All words beyond |num| must be zero. +int bssl::bn_fits_in_words(const BIGNUM *bn, size_t num) { + // All words beyond `num` must be zero. BN_ULONG mask = 0; for (size_t i = num; i < (size_t)bn->width; i++) { mask |= bn->d[i]; @@ -255,7 +263,7 @@ int bn_fits_in_words(const BIGNUM *bn, size_t num) { return mask == 0; } -int bn_copy_words(BN_ULONG *out, size_t num, const BIGNUM *bn) { +int bssl::bn_copy_words(BN_ULONG *out, size_t num, const BIGNUM *bn) { if (bn->neg) { OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER); return 0; @@ -285,7 +293,7 @@ void BN_set_negative(BIGNUM *bn, int sign) { } } -int bn_wexpand(BIGNUM *bn, size_t words) { +int bssl::bn_wexpand(BIGNUM *bn, size_t words) { BN_ULONG *a; if (words <= (size_t)bn->dmax) { @@ -303,7 +311,7 @@ int bn_wexpand(BIGNUM *bn, size_t words) { } a = reinterpret_cast(OPENSSL_calloc(words, sizeof(BN_ULONG))); - if (a == NULL) { + if (a == nullptr) { return 0; } @@ -316,7 +324,7 @@ int bn_wexpand(BIGNUM *bn, size_t words) { return 1; } -int bn_expand(BIGNUM *bn, size_t bits) { +int bssl::bn_expand(BIGNUM *bn, size_t bits) { if (bits + BN_BITS2 - 1 < bits) { OPENSSL_PUT_ERROR(BN, BN_R_BIGNUM_TOO_LONG); return 0; @@ -324,7 +332,7 @@ int bn_expand(BIGNUM *bn, size_t bits) { return bn_wexpand(bn, (bits + BN_BITS2 - 1) / BN_BITS2); } -int bn_resize_words(BIGNUM *bn, size_t words) { +int bssl::bn_resize_words(BIGNUM *bn, size_t words) { if ((size_t)bn->width <= words) { if (!bn_wexpand(bn, words)) { return 0; @@ -344,8 +352,8 @@ int bn_resize_words(BIGNUM *bn, size_t words) { return 1; } -void bn_select_words(BN_ULONG *r, BN_ULONG mask, const BN_ULONG *a, - const BN_ULONG *b, size_t num) { +void bssl::bn_select_words(BN_ULONG *r, BN_ULONG mask, const BN_ULONG *a, + const BN_ULONG *b, size_t num) { for (size_t i = 0; i < num; i++) { static_assert(sizeof(BN_ULONG) <= sizeof(crypto_word_t), "crypto_word_t is too small"); @@ -353,7 +361,7 @@ void bn_select_words(BN_ULONG *r, BN_ULONG mask, const BN_ULONG *a, } } -int bn_minimal_width(const BIGNUM *bn) { +int bssl::bn_minimal_width(const BIGNUM *bn) { int ret = bn->width; while (ret > 0 && bn->d[ret - 1] == 0) { ret--; @@ -361,7 +369,7 @@ int bn_minimal_width(const BIGNUM *bn) { return ret; } -void bn_set_minimal_width(BIGNUM *bn) { +void bssl::bn_set_minimal_width(BIGNUM *bn) { bn->width = bn_minimal_width(bn); if (bn->width == 0) { bn->neg = 0; diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/bytes.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/bytes.cc.inc index c1dbb6c6..f02a668c 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/bytes.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/bytes.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,10 +19,13 @@ #include "internal.h" -void bn_big_endian_to_words(BN_ULONG *out, size_t out_len, const uint8_t *in, - size_t in_len) { - // The caller should have sized |out| to fit |in| without truncating. This - // condition ensures we do not overflow |out|, so use a runtime check. + +using namespace bssl; + +void bssl::bn_big_endian_to_words(BN_ULONG *out, size_t out_len, + const uint8_t *in, size_t in_len) { + // The caller should have sized `out` to fit `in` without truncating. This + // condition ensures we do not overflow `out`, so use a runtime check. BSSL_CHECK(in_len <= out_len * sizeof(BN_ULONG)); // Load whole words. @@ -44,42 +52,11 @@ void bn_big_endian_to_words(BN_ULONG *out, size_t out_len, const uint8_t *in, } BIGNUM *BN_bin2bn(const uint8_t *in, size_t len, BIGNUM *ret) { - BIGNUM *bn = NULL; - if (ret == NULL) { + BIGNUM *bn = nullptr; + if (ret == nullptr) { bn = BN_new(); - if (bn == NULL) { - return NULL; - } - ret = bn; - } - - if (len == 0) { - ret->width = 0; - return ret; - } - - size_t num_words = ((len - 1) / BN_BYTES) + 1; - if (!bn_wexpand(ret, num_words)) { - BN_free(bn); - return NULL; - } - - // |bn_wexpand| must check bounds on |num_words| to write it into - // |ret->dmax|. - assert(num_words <= INT_MAX); - ret->width = (int)num_words; - ret->neg = 0; - - bn_big_endian_to_words(ret->d, ret->width, in, len); - return ret; -} - -BIGNUM *BN_lebin2bn(const uint8_t *in, size_t len, BIGNUM *ret) { - BIGNUM *bn = NULL; - if (ret == NULL) { - bn = BN_new(); - if (bn == NULL) { - return NULL; + if (bn == nullptr) { + return nullptr; } ret = bn; } @@ -90,13 +67,46 @@ BIGNUM *BN_lebin2bn(const uint8_t *in, size_t len, BIGNUM *ret) { return ret; } - // Reserve enough space in |ret|. size_t num_words = ((len - 1) / BN_BYTES) + 1; if (!bn_wexpand(ret, num_words)) { BN_free(bn); - return NULL; + return nullptr; + } + + // `bn_wexpand` must check bounds on `num_words` to write it into + // `ret->dmax`. + assert(num_words <= INT_MAX); + ret->width = (int)num_words; + ret->neg = 0; + + bn_big_endian_to_words(ret->d, ret->width, in, len); + return ret; +} + +BIGNUM *BN_lebin2bn(const uint8_t *in, size_t len, BIGNUM *ret) { + BIGNUM *bn = nullptr; + if (ret == nullptr) { + bn = BN_new(); + if (bn == nullptr) { + return nullptr; + } + ret = bn; + } + + if (len == 0) { + ret->width = 0; + ret->neg = 0; + return ret; + } + + // Reserve enough space in `ret`. + size_t num_words = ((len - 1) / BN_BYTES) + 1; + if (!bn_wexpand(ret, num_words)) { + BN_free(bn); + return nullptr; } ret->width = (int)num_words; + ret->neg = 0; // Make sure the top bytes will be zeroed. ret->d[num_words - 1] = 0; @@ -111,8 +121,8 @@ BIGNUM *BN_le2bn(const uint8_t *in, size_t len, BIGNUM *ret) { return BN_lebin2bn(in, len, ret); } -// fits_in_bytes returns one if the |num_words| words in |words| can be -// represented in |num_bytes| bytes. +// fits_in_bytes returns one if the `num_words` words in `words` can be +// represented in `num_bytes` bytes. static int fits_in_bytes(const BN_ULONG *words, size_t num_words, size_t num_bytes) { const uint8_t *bytes = (const uint8_t *)words; @@ -124,7 +134,7 @@ static int fits_in_bytes(const BN_ULONG *words, size_t num_words, return mask == 0; } -void bn_assert_fits_in_bytes(const BIGNUM *bn, size_t num) { +void bssl::bn_assert_fits_in_bytes(const BIGNUM *bn, size_t num) { const uint8_t *bytes = (const uint8_t *)bn->d; size_t tot_bytes = bn->width * sizeof(BN_ULONG); if (tot_bytes > num) { @@ -136,8 +146,8 @@ void bn_assert_fits_in_bytes(const BIGNUM *bn, size_t num) { } } -void bn_words_to_big_endian(uint8_t *out, size_t out_len, const BN_ULONG *in, - size_t in_len) { +void bssl::bn_words_to_big_endian(uint8_t *out, size_t out_len, + const BN_ULONG *in, size_t in_len) { // The caller should have selected an output length without truncation. declassify_assert(fits_in_bytes(in, in_len, out_len)); diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/cmp.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/cmp.cc.inc index 1db54879..351ca924 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/cmp.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/cmp.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,6 +22,8 @@ #include "../../internal.h" +using namespace bssl; + static int bn_cmp_words_consttime(const BN_ULONG *a, size_t a_len, const BN_ULONG *b, size_t b_len) { static_assert(sizeof(BN_ULONG) <= sizeof(crypto_word_t), @@ -31,7 +38,7 @@ static int bn_cmp_words_consttime(const BN_ULONG *a, size_t a_len, constant_time_select_int(eq, ret, constant_time_select_int(lt, -1, 1)); } - // If |a| or |b| has non-zero words beyond |min|, they take precedence. + // If `a` or `b` has non-zero words beyond `min`, they take precedence. if (a_len < b_len) { crypto_word_t mask = 0; for (size_t i = a_len; i < b_len; i++) { @@ -54,10 +61,10 @@ int BN_ucmp(const BIGNUM *a, const BIGNUM *b) { } int BN_cmp(const BIGNUM *a, const BIGNUM *b) { - if ((a == NULL) || (b == NULL)) { - if (a != NULL) { + if ((a == nullptr) || (b == nullptr)) { + if (a != nullptr) { return -1; - } else if (b != NULL) { + } else if (b != nullptr) { return 1; } else { return 0; @@ -65,7 +72,7 @@ int BN_cmp(const BIGNUM *a, const BIGNUM *b) { } // We do not attempt to process the sign bit in constant time. Negative - // |BIGNUM|s should never occur in crypto, only calculators. + // `BIGNUM`s should never occur in crypto, only calculators. if (a->neg != b->neg) { if (a->neg) { return -1; @@ -77,7 +84,7 @@ int BN_cmp(const BIGNUM *a, const BIGNUM *b) { return a->neg ? -ret : ret; } -int bn_less_than_words(const BN_ULONG *a, const BN_ULONG *b, size_t len) { +int bssl::bn_less_than_words(const BN_ULONG *a, const BN_ULONG *b, size_t len) { return bn_cmp_words_consttime(a, len, b, len) < 0; } @@ -136,7 +143,7 @@ int BN_is_pow2(const BIGNUM *bn) { int BN_equal_consttime(const BIGNUM *a, const BIGNUM *b) { BN_ULONG mask = 0; - // If |a| or |b| has more words than the other, all those words must be zero. + // If `a` or `b` has more words than the other, all those words must be zero. for (int i = a->width; i < b->width; i++) { mask |= b->d[i]; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/ctx.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/ctx.cc.inc index bfdd06aa..9d25eef7 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/ctx.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/ctx.cc.inc @@ -1,186 +1,127 @@ -/* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../../internal.h" +#include "../../mem_internal.h" -// The stack frame info is resizing, set a first-time expansion size; -#define BN_CTX_START_FRAMES 32 +using namespace bssl; +DECLARE_OPAQUE_STRUCT(bignum_ctx, BignumCtx) -// BN_STACK +BSSL_NAMESPACE_BEGIN -// A |BN_STACK| is a stack of |size_t| values. -typedef struct { - // Array of indexes into |ctx->bignums|. - size_t *indexes; - // Number of stack frames, and the size of the allocated array - size_t depth, size; -} BN_STACK; +class BignumCtx : public bignum_ctx { + public: + ~BignumCtx() { + // All `BN_CTX_start` calls must be matched with `BN_CTX_end`, otherwise the + // function may use more memory than expected, potentially without bound if + // done in a loop. Assert that all `BIGNUM`s have been released. + assert(used_ == 0 || error_); + } -static void BN_STACK_init(BN_STACK *); -static void BN_STACK_cleanup(BN_STACK *); -static int BN_STACK_push(BN_STACK *, size_t idx); -static size_t BN_STACK_pop(BN_STACK *); - - -// BN_CTX - -DEFINE_STACK_OF(BIGNUM) - -// The opaque BN_CTX type -struct bignum_ctx { - // bignums is the stack of |BIGNUM|s managed by this |BN_CTX|. - STACK_OF(BIGNUM) *bignums; - // stack is the stack of |BN_CTX_start| frames. It is the value of |used| at - // the time |BN_CTX_start| was called. - BN_STACK stack; - // used is the number of |BIGNUM|s from |bignums| that have been used. - size_t used; - // error is one if any operation on this |BN_CTX| failed. All subsequent + // bignums_ is the stack of `BIGNUM`s managed by this `BN_CTX`. + Vector> bignums_; + // stack_ is the stack of `BN_CTX_start` frames. It is the value of `used_` at + // the time `BN_CTX_start` was called. + Vector stack_; + // used_ is the number of `BIGNUM`s from `bignums_` that have been used. + size_t used_ = 0; + // error_ is whether any operation on this `BN_CTX` failed. All subsequent // operations will fail. - char error; - // defer_error is one if an operation on this |BN_CTX| has failed, but no + bool error_ = false; + // defer_error_ is whether an operation on this `BN_CTX` has failed, but no // error has been pushed to the queue yet. This is used to defer errors from - // |BN_CTX_start| to |BN_CTX_get|. - char defer_error; + // `BN_CTX_start` to `BN_CTX_get`. + bool defer_error_ = false; }; -BN_CTX *BN_CTX_new(void) { - BN_CTX *ret = reinterpret_cast(OPENSSL_malloc(sizeof(BN_CTX))); - if (!ret) { - return NULL; - } +BSSL_NAMESPACE_END - // Initialise the structure - ret->bignums = NULL; - BN_STACK_init(&ret->stack); - ret->used = 0; - ret->error = 0; - ret->defer_error = 0; - return ret; -} +BN_CTX *BN_CTX_new() { return New(); } void BN_CTX_free(BN_CTX *ctx) { - // All |BN_CTX_start| calls must be matched with |BN_CTX_end|, otherwise the - // function may use more memory than expected, potentially without bound if - // done in a loop. Assert that all |BIGNUM|s have been released. - if (ctx == nullptr) { - return; + if (ctx != nullptr) { + Delete(FromOpaque(ctx)); } - assert(ctx->used == 0 || ctx->error); - sk_BIGNUM_pop_free(ctx->bignums, BN_free); - BN_STACK_cleanup(&ctx->stack); - OPENSSL_free(ctx); } void BN_CTX_start(BN_CTX *ctx) { - if (ctx->error) { - // Once an operation has failed, |ctx->stack| no longer matches the number - // of |BN_CTX_end| calls to come. Do nothing. + auto *impl = FromOpaque(ctx); + + if (impl->error_) { + // Once an operation has failed, `impl->stack` no longer matches the number + // of `BN_CTX_end` calls to come. Do nothing. return; } - if (!BN_STACK_push(&ctx->stack, ctx->used)) { - ctx->error = 1; - // |BN_CTX_start| cannot fail, so defer the error to |BN_CTX_get|. - ctx->defer_error = 1; + if (!impl->stack_.Push(impl->used_)) { + impl->error_ = true; + // `BN_CTX_start` cannot fail, so defer the error to `BN_CTX_get`. + impl->defer_error_ = true; + ERR_clear_error(); } } BIGNUM *BN_CTX_get(BN_CTX *ctx) { + auto *impl = FromOpaque(ctx); + // Once any operation has failed, they all do. - if (ctx->error) { - if (ctx->defer_error) { + if (impl->error_) { + if (impl->defer_error_) { OPENSSL_PUT_ERROR(BN, BN_R_TOO_MANY_TEMPORARY_VARIABLES); - ctx->defer_error = 0; + impl->defer_error_ = false; } - return NULL; + return nullptr; } - if (ctx->bignums == NULL) { - ctx->bignums = sk_BIGNUM_new_null(); - if (ctx->bignums == NULL) { - ctx->error = 1; - return NULL; - } - } - - if (ctx->used == sk_BIGNUM_num(ctx->bignums)) { - BIGNUM *bn = BN_new(); - if (bn == NULL || !sk_BIGNUM_push(ctx->bignums, bn)) { + if (impl->used_ == impl->bignums_.size()) { + UniquePtr bn(BN_new()); + if (bn == nullptr || !impl->bignums_.Push(std::move(bn))) { OPENSSL_PUT_ERROR(BN, BN_R_TOO_MANY_TEMPORARY_VARIABLES); - BN_free(bn); - ctx->error = 1; - return NULL; + impl->error_ = true; + return nullptr; } } - BIGNUM *ret = sk_BIGNUM_value(ctx->bignums, ctx->used); + BIGNUM *ret = impl->bignums_[impl->used_].get(); BN_zero(ret); - // This is bounded by |sk_BIGNUM_num|, so it cannot overflow. - ctx->used++; + // This is bounded by `impl->bignums_.size()`, so it cannot overflow. + impl->used_++; return ret; } void BN_CTX_end(BN_CTX *ctx) { - if (ctx->error) { - // Once an operation has failed, |ctx->stack| no longer matches the number - // of |BN_CTX_end| calls to come. Do nothing. + auto *impl = FromOpaque(ctx); + + if (impl->error_) { + // Once an operation has failed, `impl->stack_` no longer matches the number + // of `BN_CTX_end` calls to come. Do nothing. return; } - ctx->used = BN_STACK_pop(&ctx->stack); -} - - -// BN_STACK - -static void BN_STACK_init(BN_STACK *st) { - st->indexes = NULL; - st->depth = st->size = 0; -} - -static void BN_STACK_cleanup(BN_STACK *st) { OPENSSL_free(st->indexes); } - -static int BN_STACK_push(BN_STACK *st, size_t idx) { - if (st->depth == st->size) { - // This function intentionally does not push to the error queue on error. - // Error-reporting is deferred to |BN_CTX_get|. - size_t new_size = st->size != 0 ? st->size * 3 / 2 : BN_CTX_START_FRAMES; - if (new_size <= st->size || new_size > SIZE_MAX / sizeof(size_t)) { - return 0; - } - size_t *new_indexes = reinterpret_cast( - OPENSSL_realloc(st->indexes, new_size * sizeof(size_t))); - if (new_indexes == NULL) { - return 0; - } - st->indexes = new_indexes; - st->size = new_size; - } - - st->indexes[st->depth] = idx; - st->depth++; - return 1; -} - -static size_t BN_STACK_pop(BN_STACK *st) { - assert(st->depth > 0); - st->depth--; - return st->indexes[st->depth]; + assert(!impl->stack_.empty()); + impl->used_ = impl->stack_.back(); + impl->stack_.pop_back(); } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/div.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/div.cc.inc index 4e5c45e4..744dfb26 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/div.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/div.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,10 +21,25 @@ #include "internal.h" +#if (defined(OPENSSL_X86) || defined(OPENSSL_X86_64)) && defined(_MSC_VER) && \ + !defined(__clang__) +#define HAVE_MSVC_DIV_INTRINSICS +#include +#if defined(OPENSSL_X86) +#pragma intrinsic(_udiv64) +#else +#pragma intrinsic(_udiv128) +#endif +#endif -// bn_div_words divides a double-width |h|,|l| by |d| and returns the result, -// which must fit in a |BN_ULONG|. -static inline BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d) { + +using namespace bssl; + +// bn_div_words divides a double-width `h`,`l` by `d` and returns the result, +// which must fit in a `BN_ULONG`, i.e. `h < d`. +[[maybe_unused]] +static BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d) { + assert(h < d); BN_ULONG dh, dl, q, ret = 0, th, tl, t; int i, count = 2; @@ -88,42 +108,49 @@ static inline BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d) { return ret; } -static inline void bn_div_rem_words(BN_ULONG *quotient_out, BN_ULONG *rem_out, - BN_ULONG n0, BN_ULONG n1, BN_ULONG d0) { - // GCC and Clang generate function calls to |__udivdi3| and |__umoddi3| when - // the |BN_ULLONG|-based C code is used. - // - // GCC bugs: - // * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=14224 - // * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=43721 - // * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54183 - // * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58897 - // * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65668 - // - // Clang bugs: - // * https://github.com/llvm/llvm-project/issues/6769 - // * https://github.com/llvm/llvm-project/issues/12790 +// bn_div_rem_words divides a double-width numerator (high half `nh` and low +// half `nl`) with a single-width divisor. It sets `*quotient_out` and +// `*rem_out` to be the quotient and numerator, respectively. The quotient must +// fit in a `BN_ULONG`, i.e. `nh < d`. +static void bn_div_rem_words(BN_ULONG *quotient_out, BN_ULONG *rem_out, + BN_ULONG nh, BN_ULONG nl, BN_ULONG d) { + assert(nh < d); + // This operation is the x86 and x86_64 DIV instruction, but it is difficult + // for the compiler to emit it. Dividing a `BN_ULLONG` by a `BN_ULONG` does + // not work because, a priori, the quotient may not fit in `BN_ULONG` and DIV + // will trap on overflow, not truncate. The compiler will instead emit a call + // to a more expensive support function (e.g. `__udivdi3`). Thus we use inline + // assembly or intrinsics to get the instruction. // // These is specific to x86 and x86_64; Arm and RISC-V do not have double-wide // division instructions. #if defined(BN_CAN_USE_INLINE_ASM) && defined(OPENSSL_X86) __asm__ volatile("divl %4" : "=a"(*quotient_out), "=d"(*rem_out) - : "a"(n1), "d"(n0), "rm"(d0) + : "a"(nl), "d"(nh), "rm"(d) : "cc"); #elif defined(BN_CAN_USE_INLINE_ASM) && defined(OPENSSL_X86_64) __asm__ volatile("divq %4" : "=a"(*quotient_out), "=d"(*rem_out) - : "a"(n1), "d"(n0), "rm"(d0) + : "a"(nl), "d"(nh), "rm"(d) : "cc"); +#elif defined(HAVE_MSVC_DIV_INTRINSICS) && defined(OPENSSL_X86) + BN_ULLONG n = (((BN_ULLONG)nh) << BN_BITS2) | nl; + unsigned rem; + *quotient_out = _udiv64(n, d, &rem); + *rem_out = rem; +#elif defined(HAVE_MSVC_DIV_INTRINSICS) && defined(OPENSSL_X86_64) + unsigned __int64 rem; + *quotient_out = _udiv128(nh, nl, d, &rem); + *rem_out = rem; #else #if defined(BN_CAN_DIVIDE_ULLONG) - BN_ULLONG n = (((BN_ULLONG)n0) << BN_BITS2) | n1; - *quotient_out = (BN_ULONG)(n / d0); + BN_ULLONG n = (((BN_ULLONG)nh) << BN_BITS2) | nl; + *quotient_out = (BN_ULONG)(n / d); #else - *quotient_out = bn_div_words(n0, n1, d0); -#endif - *rem_out = n1 - (*quotient_out * d0); + *quotient_out = bn_div_words(nh, nl, d); +#endif // BN_CAN_DIVIDE_ULLONG + *rem_out = nl - (*quotient_out * d); #endif } @@ -142,15 +169,15 @@ int BN_div(BIGNUM *quotient, BIGNUM *rem, const BIGNUM *numerator, return 0; } - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *tmp = BN_CTX_get(ctx); BIGNUM *snum = BN_CTX_get(ctx); BIGNUM *sdiv = BN_CTX_get(ctx); - BIGNUM *res = quotient == NULL ? BN_CTX_get(ctx) : quotient; + BIGNUM *res = quotient == nullptr ? BN_CTX_get(ctx) : quotient; int norm_shift, num_n, loop, div_n; BN_ULONG d0, d1; - if (tmp == NULL || snum == NULL || sdiv == NULL || res == NULL) { - goto err; + if (tmp == nullptr || snum == nullptr || sdiv == nullptr || res == nullptr) { + return 0; } // Knuth step D1: Normalise the numbers such that the divisor's MSB is set. @@ -159,11 +186,11 @@ int BN_div(BIGNUM *quotient, BIGNUM *rem, const BIGNUM *numerator, norm_shift = BN_BITS2 - (BN_num_bits(divisor) % BN_BITS2); if (!BN_lshift(sdiv, divisor, norm_shift) || !BN_lshift(snum, numerator, norm_shift)) { - goto err; + return 0; } - // This algorithm relies on |sdiv| being minimal width. We do not use this - // function on secret inputs, so leaking this is fine. Also minimize |snum| to + // This algorithm relies on `sdiv` being minimal width. We do not use this + // function on secret inputs, so leaking this is fine. Also minimize `snum` to // avoid looping on leading zeros, as we're not trying to be leak-free. bn_set_minimal_width(sdiv); bn_set_minimal_width(snum); @@ -172,14 +199,14 @@ int BN_div(BIGNUM *quotient, BIGNUM *rem, const BIGNUM *numerator, d1 = (div_n == 1) ? 0 : sdiv->d[div_n - 2]; assert(d0 & (((BN_ULONG)1) << (BN_BITS2 - 1))); - // Extend |snum| with zeros to satisfy the long division invariants: - // - |snum| must have at least |div_n| + 1 words. - // - |snum|'s most significant word must be zero to guarantee the first loop - // iteration works with a prefix greater than |sdiv|. (This is the extra u0 + // Extend `snum` with zeros to satisfy the long division invariants: + // - `snum` must have at least `div_n` + 1 words. + // - `snum`'s most significant word must be zero to guarantee the first loop + // iteration works with a prefix greater than `sdiv`. (This is the extra u0 // digit in Knuth step D1.) num_n = snum->width <= div_n ? div_n + 1 : snum->width + 1; if (!bn_resize_words(snum, num_n)) { - goto err; + return 0; } // Knuth step D2: The quotient's width is the difference between numerator and @@ -188,7 +215,7 @@ int BN_div(BIGNUM *quotient, BIGNUM *rem, const BIGNUM *numerator, res->neg = snum->neg ^ sdiv->neg; if (!bn_wexpand(res, loop) || // !bn_wexpand(tmp, div_n + 1)) { - goto err; + return 0; } res->width = loop; @@ -306,16 +333,11 @@ int BN_div(BIGNUM *quotient, BIGNUM *rem, const BIGNUM *numerator, bn_set_minimal_width(res); // Knuth step D8: Unnormalize. snum now contains the remainder. - if (rem != NULL && !BN_rshift(rem, snum, norm_shift)) { - goto err; + if (rem != nullptr && !BN_rshift(rem, snum, norm_shift)) { + return 0; } - BN_CTX_end(ctx); return 1; - -err: - BN_CTX_end(ctx); - return 0; } int BN_nnmod(BIGNUM *r, const BIGNUM *m, const BIGNUM *d, BN_CTX *ctx) { @@ -331,37 +353,38 @@ int BN_nnmod(BIGNUM *r, const BIGNUM *m, const BIGNUM *d, BN_CTX *ctx) { return BN_usub(r, d, r); } -BN_ULONG bn_reduce_once(BN_ULONG *r, const BN_ULONG *a, BN_ULONG carry, - const BN_ULONG *m, size_t num) { +BN_ULONG bssl::bn_reduce_once(BN_ULONG *r, const BN_ULONG *a, BN_ULONG carry, + const BN_ULONG *m, size_t num) { assert(r != a); - // |r| = |a| - |m|. |bn_sub_words| performs the bulk of the subtraction, and - // then we apply the borrow to |carry|. + // `r` = `a` - `m`. `bn_sub_words` performs the bulk of the subtraction, and + // then we apply the borrow to `carry`. carry -= bn_sub_words(r, a, m, num); - // We know 0 <= |a| < 2*|m|, so -|m| <= |r| < |m|. + // We know 0 <= `a` < 2*`m`, so -`m` <= `r` < `m`. // - // If 0 <= |r| < |m|, |r| fits in |num| words and |carry| is zero. We then - // wish to select |r| as the answer. Otherwise -m <= r < 0 and we wish to - // return |r| + |m|, or |a|. |carry| must then be -1 or all ones. In both - // cases, |carry| is a suitable input to |bn_select_words|. + // If 0 <= `r` < `m`, `r` fits in `num` words and `carry` is zero. We then + // wish to select `r` as the answer. Otherwise -m <= r < 0 and we wish to + // return `r` + `m`, or `a`. `carry` must then be -1 or all ones. In both + // cases, `carry` is a suitable input to `bn_select_words`. // - // Although |carry| may be one if it was one on input and |bn_sub_words| - // returns zero, this would give |r| > |m|, violating our input assumptions. + // Although `carry` may be one if it was one on input and `bn_sub_words` + // returns zero, this would give `r` > `m`, violating our input assumptions. declassify_assert(carry + 1 <= 1); bn_select_words(r, carry, a /* r < 0 */, r /* r >= 0 */, num); return carry; } -BN_ULONG bn_reduce_once_in_place(BN_ULONG *r, BN_ULONG carry, const BN_ULONG *m, - BN_ULONG *tmp, size_t num) { - // See |bn_reduce_once| for why this logic works. +BN_ULONG bssl::bn_reduce_once_in_place(BN_ULONG *r, BN_ULONG carry, + const BN_ULONG *m, BN_ULONG *tmp, + size_t num) { + // See `bn_reduce_once` for why this logic works. carry -= bn_sub_words(tmp, r, m, num); declassify_assert(carry + 1 <= 1); bn_select_words(r, carry, r /* tmp < 0 */, tmp /* tmp >= 0 */, num); return carry; } -void bn_mod_sub_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, - const BN_ULONG *m, BN_ULONG *tmp, size_t num) { +void bssl::bn_mod_sub_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, + const BN_ULONG *m, BN_ULONG *tmp, size_t num) { // r = a - b BN_ULONG borrow = bn_sub_words(r, a, b, num); // tmp = a - b + m @@ -369,15 +392,15 @@ void bn_mod_sub_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, bn_select_words(r, 0 - borrow, tmp /* r < 0 */, r /* r >= 0 */, num); } -void bn_mod_add_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, - const BN_ULONG *m, BN_ULONG *tmp, size_t num) { +void bssl::bn_mod_add_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, + const BN_ULONG *m, BN_ULONG *tmp, size_t num) { BN_ULONG carry = bn_add_words(r, a, b, num); bn_reduce_once_in_place(r, carry, m, tmp, num); } -int bn_div_consttime(BIGNUM *quotient, BIGNUM *remainder, - const BIGNUM *numerator, const BIGNUM *divisor, - unsigned divisor_min_bits, BN_CTX *ctx) { +int bssl::bn_div_consttime(BIGNUM *quotient, BIGNUM *remainder, + const BIGNUM *numerator, const BIGNUM *divisor, + unsigned divisor_min_bits, BN_CTX *ctx) { if (BN_is_negative(numerator) || BN_is_negative(divisor)) { OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER); return 0; @@ -391,21 +414,20 @@ int bn_div_consttime(BIGNUM *quotient, BIGNUM *remainder, // but it is simple, easy to make constant-time, and performant enough for RSA // key generation. - int ret = 0; - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *q = quotient, *r = remainder; - if (quotient == NULL || quotient == numerator || quotient == divisor) { + if (quotient == nullptr || quotient == numerator || quotient == divisor) { q = BN_CTX_get(ctx); } - if (remainder == NULL || remainder == numerator || remainder == divisor) { + if (remainder == nullptr || remainder == numerator || remainder == divisor) { r = BN_CTX_get(ctx); } BIGNUM *tmp = BN_CTX_get(ctx); int initial_words; - if (q == NULL || r == NULL || tmp == NULL || + if (q == nullptr || r == nullptr || tmp == nullptr || !bn_wexpand(q, numerator->width) || !bn_wexpand(r, divisor->width) || !bn_wexpand(tmp, divisor->width)) { - goto err; + return 0; } OPENSSL_memset(q->d, 0, numerator->width * sizeof(BN_ULONG)); @@ -416,14 +438,14 @@ int bn_div_consttime(BIGNUM *quotient, BIGNUM *remainder, r->width = divisor->width; r->neg = 0; - // Incorporate |numerator| into |r|, one bit at a time, reducing after each - // step. We maintain the invariant that |0 <= r < divisor| and - // |q * divisor + r = n| where |n| is the portion of |numerator| incorporated + // Incorporate `numerator` into `r`, one bit at a time, reducing after each + // step. We maintain the invariant that `0 <= r < divisor` and + // `q * divisor + r = n` where `n` is the portion of `numerator` incorporated // so far. // - // First, we short-circuit the loop: if we know |divisor| has at least - // |divisor_min_bits| bits, the top |divisor_min_bits - 1| can be incorporated - // without reductions. This significantly speeds up |RSA_check_key|. For + // First, we short-circuit the loop: if we know `divisor` has at least + // `divisor_min_bits` bits, the top `divisor_min_bits - 1` can be incorporated + // without reductions. This significantly speeds up `RSA_check_key`. For // simplicity, we round down to a whole number of words. declassify_assert(divisor_min_bits <= BN_num_bits(divisor)); initial_words = 0; @@ -440,13 +462,13 @@ int bn_div_consttime(BIGNUM *quotient, BIGNUM *remainder, for (int bit = BN_BITS2 - 1; bit >= 0; bit--) { // Incorporate the next bit of the numerator, by computing // r = 2*r or 2*r + 1. Note the result fits in one more word. We store the - // extra word in |carry|. + // extra word in `carry`. BN_ULONG carry = bn_add_words(r->d, r->d, r->d, divisor->width); r->d[0] |= (numerator->d[i] >> bit) & 1; - // |r| was previously fully-reduced, so we know: + // `r` was previously fully-reduced, so we know: // 2*0 <= r <= 2*(divisor-1) + 1 // 0 <= r <= 2*divisor - 1 < 2*divisor. - // Thus |r| satisfies the preconditions for |bn_reduce_once_in_place|. + // Thus `r` satisfies the preconditions for `bn_reduce_once_in_place`. BN_ULONG subtracted = bn_reduce_once_in_place(r->d, carry, divisor->d, tmp->d, divisor->width); // The corresponding bit of the quotient is set iff we needed to subtract. @@ -454,33 +476,29 @@ int bn_div_consttime(BIGNUM *quotient, BIGNUM *remainder, } } - if ((quotient != NULL && !BN_copy(quotient, q)) || - (remainder != NULL && !BN_copy(remainder, r))) { - goto err; + if ((quotient != nullptr && !BN_copy(quotient, q)) || + (remainder != nullptr && !BN_copy(remainder, r))) { + return 0; } - ret = 1; - -err: - BN_CTX_end(ctx); - return ret; + return 1; } static BIGNUM *bn_scratch_space_from_ctx(size_t width, BN_CTX *ctx) { BIGNUM *ret = BN_CTX_get(ctx); - if (ret == NULL || !bn_wexpand(ret, width)) { - return NULL; + if (ret == nullptr || !bn_wexpand(ret, width)) { + return nullptr; } ret->neg = 0; ret->width = (int)width; return ret; } -// bn_resized_from_ctx returns |bn| with width at least |width| or NULL on +// bn_resized_from_ctx returns `bn` with width at least `width` or NULL on // error. This is so it may be used with low-level "words" functions. If -// necessary, it allocates a new |BIGNUM| with a lifetime of the current scope -// in |ctx|, so the caller does not need to explicitly free it. |bn| must fit in -// |width| words. +// necessary, it allocates a new `BIGNUM` with a lifetime of the current scope +// in `ctx`, so the caller does not need to explicitly free it. `bn` must fit in +// `width` words. static const BIGNUM *bn_resized_from_ctx(const BIGNUM *bn, size_t width, BN_CTX *ctx) { if ((size_t)bn->width >= width) { @@ -489,8 +507,8 @@ static const BIGNUM *bn_resized_from_ctx(const BIGNUM *bn, size_t width, return bn; } BIGNUM *ret = bn_scratch_space_from_ctx(width, ctx); - if (ret == NULL || !BN_copy(ret, bn) || !bn_resize_words(ret, width)) { - return NULL; + if (ret == nullptr || !BN_copy(ret, bn) || !bn_resize_words(ret, width)) { + return nullptr; } return ret; } @@ -505,26 +523,24 @@ int BN_mod_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, int BN_mod_add_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m) { - BN_CTX *ctx = BN_CTX_new(); - int ok = ctx != NULL && bn_mod_add_consttime(r, a, b, m, ctx); - BN_CTX_free(ctx); - return ok; + UniquePtr ctx(BN_CTX_new()); + return ctx != nullptr && bn_mod_add_consttime(r, a, b, m, ctx.get()); } -int bn_mod_add_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, - const BIGNUM *m, BN_CTX *ctx) { - BN_CTX_start(ctx); +int bssl::bn_mod_add_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + const BIGNUM *m, BN_CTX *ctx) { + BN_CTXScope scope(ctx); a = bn_resized_from_ctx(a, m->width, ctx); b = bn_resized_from_ctx(b, m->width, ctx); BIGNUM *tmp = bn_scratch_space_from_ctx(m->width, ctx); - int ok = a != NULL && b != NULL && tmp != NULL && bn_wexpand(r, m->width); - if (ok) { - bn_mod_add_words(r->d, a->d, b->d, m->d, tmp->d, m->width); - r->width = m->width; - r->neg = 0; + if (a == nullptr || b == nullptr || tmp == nullptr || + !bn_wexpand(r, m->width)) { + return 0; } - BN_CTX_end(ctx); - return ok; + bn_mod_add_words(r->d, a->d, b->d, m->d, tmp->d, m->width); + r->width = m->width; + r->neg = 0; + return 1; } int BN_mod_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, @@ -535,60 +551,51 @@ int BN_mod_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, return BN_nnmod(r, r, m, ctx); } -int bn_mod_sub_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, - const BIGNUM *m, BN_CTX *ctx) { - BN_CTX_start(ctx); +int bssl::bn_mod_sub_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + const BIGNUM *m, BN_CTX *ctx) { + BN_CTXScope scope(ctx); a = bn_resized_from_ctx(a, m->width, ctx); b = bn_resized_from_ctx(b, m->width, ctx); BIGNUM *tmp = bn_scratch_space_from_ctx(m->width, ctx); - int ok = a != NULL && b != NULL && tmp != NULL && bn_wexpand(r, m->width); - if (ok) { - bn_mod_sub_words(r->d, a->d, b->d, m->d, tmp->d, m->width); - r->width = m->width; - r->neg = 0; + if (a == nullptr || b == nullptr || tmp == nullptr || + !bn_wexpand(r, m->width)) { + return 0; } - BN_CTX_end(ctx); - return ok; + bn_mod_sub_words(r->d, a->d, b->d, m->d, tmp->d, m->width); + r->width = m->width; + r->neg = 0; + return 1; } int BN_mod_sub_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m) { - BN_CTX *ctx = BN_CTX_new(); - int ok = ctx != NULL && bn_mod_sub_consttime(r, a, b, m, ctx); - BN_CTX_free(ctx); - return ok; + UniquePtr ctx(BN_CTX_new()); + return ctx != nullptr && bn_mod_sub_consttime(r, a, b, m, ctx.get()); } int BN_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, BN_CTX *ctx) { - BIGNUM *t; - int ret = 0; - - BN_CTX_start(ctx); - t = BN_CTX_get(ctx); - if (t == NULL) { - goto err; + BN_CTXScope scope(ctx); + BIGNUM *t = BN_CTX_get(ctx); + if (t == nullptr) { + return 0; } if (a == b) { if (!BN_sqr(t, a, ctx)) { - goto err; + return 0; } } else { if (!BN_mul(t, a, b, ctx)) { - goto err; + return 0; } } if (!BN_nnmod(r, t, m, ctx)) { - goto err; + return 0; } - ret = 1; - -err: - BN_CTX_end(ctx); - return ret; + return 1; } int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) { @@ -602,51 +609,43 @@ int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) { int BN_mod_lshift(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m, BN_CTX *ctx) { - BIGNUM *abs_m = NULL; - int ret; - if (!BN_nnmod(r, a, m, ctx)) { return 0; } + UniquePtr abs_m; if (m->neg) { - abs_m = BN_dup(m); - if (abs_m == NULL) { + abs_m.reset(BN_dup(m)); + if (abs_m == nullptr) { return 0; } abs_m->neg = 0; } - ret = bn_mod_lshift_consttime(r, r, n, (abs_m ? abs_m : m), ctx); - - BN_free(abs_m); - return ret; + return bn_mod_lshift_consttime(r, r, n, (abs_m ? abs_m.get() : m), ctx); } -int bn_mod_lshift_consttime(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m, - BN_CTX *ctx) { +int bssl::bn_mod_lshift_consttime(BIGNUM *r, const BIGNUM *a, int n, + const BIGNUM *m, BN_CTX *ctx) { if (!BN_copy(r, a) || !bn_resize_words(r, m->width)) { return 0; } - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *tmp = bn_scratch_space_from_ctx(m->width, ctx); - int ok = tmp != NULL; - if (ok) { - for (int i = 0; i < n; i++) { - bn_mod_add_words(r->d, r->d, r->d, m->d, tmp->d, m->width); - } - r->neg = 0; + if (tmp == nullptr) { + return 0; } - BN_CTX_end(ctx); - return ok; + for (int i = 0; i < n; i++) { + bn_mod_add_words(r->d, r->d, r->d, m->d, tmp->d, m->width); + } + r->neg = 0; + return 1; } int BN_mod_lshift_quick(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m) { - BN_CTX *ctx = BN_CTX_new(); - int ok = ctx != NULL && bn_mod_lshift_consttime(r, a, n, m, ctx); - BN_CTX_free(ctx); - return ok; + UniquePtr ctx(BN_CTX_new()); + return ctx != nullptr && bn_mod_lshift_consttime(r, a, n, m, ctx.get()); } int BN_mod_lshift1(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) { @@ -657,16 +656,14 @@ int BN_mod_lshift1(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) { return BN_nnmod(r, r, m, ctx); } -int bn_mod_lshift1_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, - BN_CTX *ctx) { +int bssl::bn_mod_lshift1_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, + BN_CTX *ctx) { return bn_mod_add_consttime(r, a, a, m, ctx); } int BN_mod_lshift1_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *m) { - BN_CTX *ctx = BN_CTX_new(); - int ok = ctx != NULL && bn_mod_lshift1_consttime(r, a, m, ctx); - BN_CTX_free(ctx); - return ok; + UniquePtr ctx(BN_CTX_new()); + return ctx != nullptr && bn_mod_lshift1_consttime(r, a, m, ctx.get()); } BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w) { @@ -682,7 +679,7 @@ BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w) { return 0; } - // normalize input for |bn_div_rem_words|. + // normalize input for `bn_div_rem_words`. j = BN_BITS2 - BN_num_bits_word(w); w <<= j; if (!BN_lshift(a, a, j)) { @@ -716,11 +713,11 @@ BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w) { } #ifndef BN_CAN_DIVIDE_ULLONG - // If |w| is too long and we don't have |BN_ULLONG| division then we need to - // fall back to using |BN_div_word|. + // If `w` is too long and we don't have `BN_ULLONG` division then we need to + // fall back to using `BN_div_word`. if (w > ((BN_ULONG)1 << BN_BITS4)) { BIGNUM *tmp = BN_dup(a); - if (tmp == NULL) { + if (tmp == nullptr) { return (BN_ULONG)-1; } ret = BN_div_word(tmp, w); @@ -739,82 +736,3 @@ BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w) { } return (BN_ULONG)ret; } - -int BN_mod_pow2(BIGNUM *r, const BIGNUM *a, size_t e) { - if (e == 0 || a->width == 0) { - BN_zero(r); - return 1; - } - - size_t num_words = 1 + ((e - 1) / BN_BITS2); - - // If |a| definitely has less than |e| bits, just BN_copy. - if ((size_t)a->width < num_words) { - return BN_copy(r, a) != NULL; - } - - // Otherwise, first make sure we have enough space in |r|. - // Note that this will fail if num_words > INT_MAX. - if (!bn_wexpand(r, num_words)) { - return 0; - } - - // Copy the content of |a| into |r|. - OPENSSL_memcpy(r->d, a->d, num_words * sizeof(BN_ULONG)); - - // If |e| isn't word-aligned, we have to mask off some of our bits. - size_t top_word_exponent = e % (sizeof(BN_ULONG) * 8); - if (top_word_exponent != 0) { - r->d[num_words - 1] &= (((BN_ULONG)1) << top_word_exponent) - 1; - } - - // Fill in the remaining fields of |r|. - r->neg = a->neg; - r->width = (int)num_words; - bn_set_minimal_width(r); - return 1; -} - -int BN_nnmod_pow2(BIGNUM *r, const BIGNUM *a, size_t e) { - if (!BN_mod_pow2(r, a, e)) { - return 0; - } - - // If the returned value was non-negative, we're done. - if (BN_is_zero(r) || !r->neg) { - return 1; - } - - size_t num_words = 1 + (e - 1) / BN_BITS2; - - // Expand |r| to the size of our modulus. - if (!bn_wexpand(r, num_words)) { - return 0; - } - - // Clear the upper words of |r|. - OPENSSL_memset(&r->d[r->width], 0, (num_words - r->width) * BN_BYTES); - - // Set parameters of |r|. - r->neg = 0; - r->width = (int)num_words; - - // Now, invert every word. The idea here is that we want to compute 2^e-|x|, - // which is actually equivalent to the twos-complement representation of |x| - // in |e| bits, which is -x = ~x + 1. - for (int i = 0; i < r->width; i++) { - r->d[i] = ~r->d[i]; - } - - // If our exponent doesn't span the top word, we have to mask the rest. - size_t top_word_exponent = e % BN_BITS2; - if (top_word_exponent != 0) { - r->d[r->width - 1] &= (((BN_ULONG)1) << top_word_exponent) - 1; - } - - // Keep the minimal-width invariant for |BIGNUM|. - bn_set_minimal_width(r); - - // Finally, add one, for the reason described above. - return BN_add(r, r, BN_value_one()); -} diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/div_extra.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/div_extra.cc.inc index 53e9eb57..6d4f3979 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/div_extra.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/div_extra.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2018 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2018 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 @@ -19,17 +19,20 @@ #include "internal.h" +using namespace bssl; + // The following functions use a Barrett reduction variant to avoid leaking the -// numerator. See http://ridiculousfish.com/blog/posts/labor-of-division-episode-i.html +// numerator. See +// http://ridiculousfish.com/blog/posts/labor-of-division-episode-i.html // // We use 32-bit numerator and 16-bit divisor for simplicity. This allows -// computing |m| and |q| without architecture-specific code. +// computing `m` and `q` without architecture-specific code. -// mod_u16 returns |n| mod |d|. |p| and |m| are the "magic numbers" for |d| (see +// mod_u16 returns `n` mod `d`. `p` and `m` are the "magic numbers" for `d` (see // reference). For proof of correctness in Coq, see // https://github.com/davidben/fiat-crypto/blob/barrett/src/Arithmetic/BarrettReduction/RidiculousFish.v -// Note the Coq version of |mod_u16| additionally includes the computation of -// |p| and |m| from |bn_mod_u16_consttime| below. +// Note the Coq version of `mod_u16` additionally includes the computation of +// `p` and `m` from `bn_mod_u16_consttime` below. static uint16_t mod_u16(uint32_t n, uint16_t d, uint32_t p, uint32_t m) { // Compute floor(n/d) per steps 3 through 5. uint32_t q = ((uint64_t)m * n) >> 32; @@ -43,11 +46,11 @@ static uint16_t mod_u16(uint32_t n, uint16_t d, uint32_t p, uint32_t m) { return n; } -// shift_and_add_mod_u16 returns |r| * 2^32 + |a| mod |d|. |p| and |m| are the -// "magic numbers" for |d| (see reference). +// shift_and_add_mod_u16 returns `r` * 2^32 + `a` mod `d`. `p` and `m` are the +// "magic numbers" for `d` (see reference). static uint16_t shift_and_add_mod_u16(uint16_t r, uint32_t a, uint16_t d, uint32_t p, uint32_t m) { - // Incorporate |a| in two 16-bit chunks. + // Incorporate `a` in two 16-bit chunks. uint32_t t = r; t <<= 16; t |= a >> 16; @@ -59,16 +62,16 @@ static uint16_t shift_and_add_mod_u16(uint16_t r, uint32_t a, uint16_t d, return t; } -uint16_t bn_mod_u16_consttime(const BIGNUM *bn, uint16_t d) { +uint16_t bssl::bn_mod_u16_consttime(const BIGNUM *bn, uint16_t d) { if (d <= 1) { return 0; } - // Compute the "magic numbers" for |d|. See steps 1 and 2. + // Compute the "magic numbers" for `d`. See steps 1 and 2. // This computes p = ceil(log_2(d)). uint32_t p = BN_num_bits_word(d - 1); - // This operation is not constant-time, but |p| and |d| are public values. - // Note that |p| is at most 16, so the computation fits in |uint64_t|. + // This operation is not constant-time, but `p` and `d` are public values. + // Note that `p` is at most 16, so the computation fits in `uint64_t`. assert(p <= 16); uint32_t m = (uint32_t)(((UINT64_C(1) << (32 + p)) + d - 1) / d); diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/exponentiation.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/exponentiation.cc.inc index 0487913c..4c9fbba9 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/exponentiation.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/exponentiation.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -20,13 +25,16 @@ #include "internal.h" #include "rsaz_exp.h" + +using namespace bssl; + #if defined(OPENSSL_BN_ASM_MONT5) -// bn_mul_mont_gather5 multiples loads index |power| of |table|, multiplies it -// by |ap| modulo |np|, and stores the result in |rp|. The values are |num| -// words long and represented in Montgomery form. |n0| is a pointer to the -// corresponding field in |BN_MONT_CTX|. |table| must be aligned to at least -// 16 bytes. |power| must be less than 32 and is treated as secret. +// bn_mul_mont_gather5 multiples loads index `power` of `table`, multiplies it +// by `ap` modulo `np`, and stores the result in `rp`. The values are `num` +// words long and represented in Montgomery form. `n0` is a pointer to the +// corresponding field in `BN_MONT_CTX`. `table` must be aligned to at least +// 16 bytes. `power` must be less than 32 and is treated as secret. // // WARNING: This function implements Almost Montgomery Multiplication from // https://eprint.iacr.org/2011/239. The inputs do not need to be fully reduced. @@ -43,11 +51,11 @@ static void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap, } } -// bn_power5 squares |ap| five times and multiplies it by the value stored at -// index |power| of |table|, modulo |np|. It stores the result in |rp|. The -// values are |num| words long and represented in Montgomery form. |n0| is a -// pointer to the corresponding field in |BN_MONT_CTX|. |num| must be divisible -// by 8. |power| must be less than 32 and is treated as secret. +// bn_power5 squares `ap` five times and multiplies it by the value stored at +// index `power` of `table`, modulo `np`. It stores the result in `rp`. The +// values are `num` words long and represented in Montgomery form. `n0` is a +// pointer to the corresponding field in `BN_MONT_CTX`. `num` must be divisible +// by 8. `power` must be less than 32 and is treated as secret. // // WARNING: This function implements Almost Montgomery Multiplication from // https://eprint.iacr.org/2011/239. The inputs do not need to be fully reduced. @@ -65,263 +73,8 @@ static void bn_power5(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *table, #endif // defined(OPENSSL_BN_ASM_MONT5) -int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { - int i, bits, ret = 0; - BIGNUM *v, *rr; - - BN_CTX_start(ctx); - if (r == a || r == p) { - rr = BN_CTX_get(ctx); - } else { - rr = r; - } - - v = BN_CTX_get(ctx); - if (rr == NULL || v == NULL) { - goto err; - } - - if (BN_copy(v, a) == NULL) { - goto err; - } - bits = BN_num_bits(p); - - if (BN_is_odd(p)) { - if (BN_copy(rr, a) == NULL) { - goto err; - } - } else { - if (!BN_one(rr)) { - goto err; - } - } - - for (i = 1; i < bits; i++) { - if (!BN_sqr(v, v, ctx)) { - goto err; - } - if (BN_is_bit_set(p, i)) { - if (!BN_mul(rr, rr, v, ctx)) { - goto err; - } - } - } - - if (r != rr && !BN_copy(r, rr)) { - goto err; - } - ret = 1; - -err: - BN_CTX_end(ctx); - return ret; -} - -namespace { -typedef struct bn_recp_ctx_st { - BIGNUM N; // the divisor - BIGNUM Nr; // the reciprocal - int num_bits; - int shift; - int flags; -} BN_RECP_CTX; -} // namespace - -static void BN_RECP_CTX_init(BN_RECP_CTX *recp) { - BN_init(&recp->N); - BN_init(&recp->Nr); - recp->num_bits = 0; - recp->shift = 0; - recp->flags = 0; -} - -static void BN_RECP_CTX_free(BN_RECP_CTX *recp) { - if (recp == nullptr) { - return; - } - BN_free(&recp->N); - BN_free(&recp->Nr); -} - -static int BN_RECP_CTX_set(BN_RECP_CTX *recp, const BIGNUM *d, BN_CTX *ctx) { - if (!BN_copy(&(recp->N), d)) { - return 0; - } - BN_zero(&recp->Nr); - recp->num_bits = BN_num_bits(d); - recp->shift = 0; - - return 1; -} - -// len is the expected size of the result We actually calculate with an extra -// word of precision, so we can do faster division if the remainder is not -// required. -// r := 2^len / m -static int BN_reciprocal(BIGNUM *r, const BIGNUM *m, int len, BN_CTX *ctx) { - int ret = -1; - BIGNUM *t; - - BN_CTX_start(ctx); - t = BN_CTX_get(ctx); - if (t == NULL) { - goto err; - } - - if (!BN_set_bit(t, len)) { - goto err; - } - - if (!BN_div(r, NULL, t, m, ctx)) { - goto err; - } - - ret = len; - -err: - BN_CTX_end(ctx); - return ret; -} - -static int BN_div_recp(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, - BN_RECP_CTX *recp, BN_CTX *ctx) { - int i, j, ret = 0; - BIGNUM *a, *b, *d, *r; - - BN_CTX_start(ctx); - a = BN_CTX_get(ctx); - b = BN_CTX_get(ctx); - if (dv != NULL) { - d = dv; - } else { - d = BN_CTX_get(ctx); - } - - if (rem != NULL) { - r = rem; - } else { - r = BN_CTX_get(ctx); - } - - if (a == NULL || b == NULL || d == NULL || r == NULL) { - goto err; - } - - if (BN_ucmp(m, &recp->N) < 0) { - BN_zero(d); - if (!BN_copy(r, m)) { - goto err; - } - BN_CTX_end(ctx); - return 1; - } - - // We want the remainder - // Given input of ABCDEF / ab - // we need multiply ABCDEF by 3 digests of the reciprocal of ab - - // i := max(BN_num_bits(m), 2*BN_num_bits(N)) - i = BN_num_bits(m); - j = recp->num_bits << 1; - if (j > i) { - i = j; - } - - // Nr := round(2^i / N) - if (i != recp->shift) { - recp->shift = - BN_reciprocal(&(recp->Nr), &(recp->N), i, - ctx); // BN_reciprocal returns i, or -1 for an error - } - - if (recp->shift == -1) { - goto err; - } - - // d := |round(round(m / 2^BN_num_bits(N)) * recp->Nr / 2^(i - - // BN_num_bits(N)))| - // = |round(round(m / 2^BN_num_bits(N)) * round(2^i / N) / 2^(i - - // BN_num_bits(N)))| - // <= |(m / 2^BN_num_bits(N)) * (2^i / N) * (2^BN_num_bits(N) / 2^i)| - // = |m/N| - if (!BN_rshift(a, m, recp->num_bits)) { - goto err; - } - if (!BN_mul(b, a, &(recp->Nr), ctx)) { - goto err; - } - if (!BN_rshift(d, b, i - recp->num_bits)) { - goto err; - } - d->neg = 0; - - if (!BN_mul(b, &(recp->N), d, ctx)) { - goto err; - } - if (!BN_usub(r, m, b)) { - goto err; - } - r->neg = 0; - - j = 0; - while (BN_ucmp(r, &(recp->N)) >= 0) { - if (j++ > 2) { - OPENSSL_PUT_ERROR(BN, BN_R_BAD_RECIPROCAL); - goto err; - } - if (!BN_usub(r, r, &(recp->N))) { - goto err; - } - if (!BN_add_word(d, 1)) { - goto err; - } - } - - r->neg = BN_is_zero(r) ? 0 : m->neg; - d->neg = m->neg ^ recp->N.neg; - ret = 1; - -err: - BN_CTX_end(ctx); - return ret; -} - -static int BN_mod_mul_reciprocal(BIGNUM *r, const BIGNUM *x, const BIGNUM *y, - BN_RECP_CTX *recp, BN_CTX *ctx) { - int ret = 0; - BIGNUM *a; - const BIGNUM *ca; - - BN_CTX_start(ctx); - a = BN_CTX_get(ctx); - if (a == NULL) { - goto err; - } - - if (y != NULL) { - if (x == y) { - if (!BN_sqr(a, x, ctx)) { - goto err; - } - } else { - if (!BN_mul(a, x, y, ctx)) { - goto err; - } - } - ca = a; - } else { - ca = x; // Just do the mod - } - - ret = BN_div_recp(NULL, r, ca, recp, ctx); - -err: - BN_CTX_end(ctx); - return ret; -} - // BN_window_bits_for_exponent_size returns sliding window size for mod_exp with -// a |b| bit exponent. +// a `b` bit exponent. // // For window size 'w' (w >= 2) and a random 'b' bits exponent, the number of // multiplications is a constant plus on average @@ -361,175 +114,18 @@ static int BN_window_bits_for_exponent_size(size_t b) { // TABLE_SIZE is the maximum precomputation table size for *variable* sliding // windows. This must be 2^(max_window - 1), where max_window is the largest -// value returned from |BN_window_bits_for_exponent_size|. +// value returned from `BN_window_bits_for_exponent_size`. #define TABLE_SIZE 32 // TABLE_BITS_SMALL is the smallest value returned from -// |BN_window_bits_for_exponent_size| when |b| is at most |BN_BITS2| * -// |BN_SMALL_MAX_WORDS| words. +// `BN_window_bits_for_exponent_size` when `b` is at most `BN_BITS2` * +// `BN_SMALL_MAX_WORDS` words. #define TABLE_BITS_SMALL 5 -// TABLE_SIZE_SMALL is the same as |TABLE_SIZE|, but when |b| is at most -// |BN_BITS2| * |BN_SMALL_MAX_WORDS|. +// TABLE_SIZE_SMALL is the same as `TABLE_SIZE`, but when `b` is at most +// `BN_BITS2` * `BN_SMALL_MAX_WORDS`. #define TABLE_SIZE_SMALL (1 << (TABLE_BITS_SMALL - 1)) -static int mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, - const BIGNUM *m, BN_CTX *ctx) { - int i, j, ret = 0, wstart, window; - int start = 1; - BIGNUM *aa; - // Table of variables obtained from 'ctx' - BIGNUM *val[TABLE_SIZE]; - BN_RECP_CTX recp; - - // This function is only called on even moduli. - assert(!BN_is_odd(m)); - - int bits = BN_num_bits(p); - if (bits == 0) { - return BN_one(r); - } - - BN_RECP_CTX_init(&recp); - BN_CTX_start(ctx); - aa = BN_CTX_get(ctx); - val[0] = BN_CTX_get(ctx); - if (!aa || !val[0]) { - goto err; - } - - if (m->neg) { - // ignore sign of 'm' - if (!BN_copy(aa, m)) { - goto err; - } - aa->neg = 0; - if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0) { - goto err; - } - } else { - if (BN_RECP_CTX_set(&recp, m, ctx) <= 0) { - goto err; - } - } - - if (!BN_nnmod(val[0], a, m, ctx)) { - goto err; // 1 - } - if (BN_is_zero(val[0])) { - BN_zero(r); - ret = 1; - goto err; - } - - window = BN_window_bits_for_exponent_size(bits); - if (window > 1) { - if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx)) { - goto err; // 2 - } - j = 1 << (window - 1); - for (i = 1; i < j; i++) { - if (((val[i] = BN_CTX_get(ctx)) == NULL) || - !BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx)) { - goto err; - } - } - } - - start = 1; // This is used to avoid multiplication etc - // when there is only the value '1' in the - // buffer. - wstart = bits - 1; // The top bit of the window - - if (!BN_one(r)) { - goto err; - } - - for (;;) { - int wvalue; // The 'value' of the window - int wend; // The bottom bit of the window - - if (!BN_is_bit_set(p, wstart)) { - if (!start) { - if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx)) { - goto err; - } - } - if (wstart == 0) { - break; - } - wstart--; - continue; - } - - // We now have wstart on a 'set' bit, we now need to work out - // how bit a window to do. To do this we need to scan - // forward until the last set bit before the end of the - // window - wvalue = 1; - wend = 0; - for (i = 1; i < window; i++) { - if (wstart - i < 0) { - break; - } - if (BN_is_bit_set(p, wstart - i)) { - wvalue <<= (i - wend); - wvalue |= 1; - wend = i; - } - } - - // wend is the size of the current window - j = wend + 1; - // add the 'bytes above' - if (!start) { - for (i = 0; i < j; i++) { - if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx)) { - goto err; - } - } - } - - // wvalue will be an odd number < 2^window - if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx)) { - goto err; - } - - // move the 'window' down further - wstart -= wend + 1; - start = 0; - if (wstart < 0) { - break; - } - } - ret = 1; - -err: - BN_CTX_end(ctx); - BN_RECP_CTX_free(&recp); - return ret; -} - -int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, - BN_CTX *ctx) { - if (m->neg) { - OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER); - return 0; - } - if (a->neg || BN_ucmp(a, m) >= 0) { - if (!BN_nnmod(r, a, m, ctx)) { - return 0; - } - a = r; - } - - if (BN_is_odd(m)) { - return BN_mod_exp_mont(r, a, p, m, ctx, NULL); - } - - return mod_exp_recp(r, a, p, m, ctx); -} - int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, const BN_MONT_CTX *mont) { if (!BN_is_odd(m)) { @@ -540,7 +136,7 @@ int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER); return 0; } - // |a| is secret, but |a < m| is not. + // `a` is secret, but `a < m` is not. if (a->neg || constant_time_declassify_int(BN_ucmp(a, m)) >= 0) { OPENSSL_PUT_ERROR(BN, BN_R_INPUT_NOT_REDUCED); return 0; @@ -556,57 +152,55 @@ int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, return BN_one(rr); } - int ret = 0; BIGNUM *val[TABLE_SIZE]; - BN_MONT_CTX *new_mont = NULL; - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *r = BN_CTX_get(ctx); val[0] = BN_CTX_get(ctx); - int window, r_is_one, wstart; - if (r == NULL || val[0] == NULL) { - goto err; + if (r == nullptr || val[0] == nullptr) { + return 0; } // Allocate a montgomery context if it was not supplied by the caller. - if (mont == NULL) { - new_mont = BN_MONT_CTX_new_consttime(m, ctx); - if (new_mont == NULL) { - goto err; + UniquePtr new_mont; + if (mont == nullptr) { + new_mont.reset(BN_MONT_CTX_new_consttime(m, ctx)); + if (new_mont == nullptr) { + return 0; } - mont = new_mont; + mont = new_mont.get(); } // We exponentiate by looking at sliding windows of the exponent and - // precomputing powers of |a|. Windows may be shifted so they always end on a + // precomputing powers of `a`. Windows may be shifted so they always end on a // set bit, so only precompute odd powers. We compute val[i] = a^(2*i + 1) // for i = 0 to 2^(window-1), all in Montgomery form. - window = BN_window_bits_for_exponent_size(bits); + int window = BN_window_bits_for_exponent_size(bits); if (!BN_to_montgomery(val[0], a, mont, ctx)) { - goto err; + return 0; } if (window > 1) { BIGNUM *d = BN_CTX_get(ctx); - if (d == NULL || !BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx)) { - goto err; + if (d == nullptr || !BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx)) { + return 0; } for (int i = 1; i < 1 << (window - 1); i++) { val[i] = BN_CTX_get(ctx); - if (val[i] == NULL || + if (val[i] == nullptr || !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx)) { - goto err; + return 0; } } } - // |p| is non-zero, so at least one window is non-zero. To save some - // multiplications, defer initializing |r| until then. - r_is_one = 1; - wstart = bits - 1; // The top bit of the window. + // `p` is non-zero, so at least one window is non-zero. To save some + // multiplications, defer initializing `r` until then. + int r_is_one = 1; + int wstart = bits - 1; // The top bit of the window. for (;;) { if (!BN_is_bit_set(p, wstart)) { if (!r_is_one && !BN_mod_mul_montgomery(r, r, r, mont, ctx)) { - goto err; + return 0; } if (wstart == 0) { break; @@ -626,11 +220,11 @@ int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, } } - // Shift |r| to the end of the window. + // Shift `r` to the end of the window. if (!r_is_one) { for (int i = 0; i < wsize + 1; i++) { if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) { - goto err; + return 0; } } } @@ -639,10 +233,10 @@ int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, assert(wvalue < (1 << window)); if (r_is_one) { if (!BN_copy(r, val[wvalue >> 1])) { - goto err; + return 0; } } else if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx)) { - goto err; + return 0; } r_is_one = 0; @@ -652,31 +246,23 @@ int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, wstart -= wsize + 1; } - // |p| is non-zero, so |r_is_one| must be cleared at some point. + // `p` is non-zero, so `r_is_one` must be cleared at some point. assert(!r_is_one); - if (!BN_from_montgomery(rr, r, mont, ctx)) { - goto err; - } - ret = 1; - -err: - BN_MONT_CTX_free(new_mont); - BN_CTX_end(ctx); - return ret; + return BN_from_montgomery(rr, r, mont, ctx); } -void bn_mod_exp_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num, - const BN_ULONG *p, size_t num_p, - const BN_MONT_CTX *mont) { +void bssl::bn_mod_exp_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num, + const BN_ULONG *p, size_t num_p, + const BN_MONT_CTX *mont) { if (num != (size_t)mont->N.width || num > BN_SMALL_MAX_WORDS || num_p > SIZE_MAX / BN_BITS2) { abort(); } assert(BN_is_odd(&mont->N)); - // Count the number of bits in |p|, skipping leading zeros. Note this function - // treats |p| as public. + // Count the number of bits in `p`, skipping leading zeros. Note this function + // treats `p` as public. while (num_p != 0 && p[num_p - 1] == 0) { num_p--; } @@ -688,12 +274,12 @@ void bn_mod_exp_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num, assert(bits != 0); // We exponentiate by looking at sliding windows of the exponent and - // precomputing powers of |a|. Windows may be shifted so they always end on a + // precomputing powers of `a`. Windows may be shifted so they always end on a // set bit, so only precompute odd powers. We compute val[i] = a^(2*i + 1) for // i = 0 to 2^(window-1), all in Montgomery form. unsigned window = BN_window_bits_for_exponent_size(bits); if (window > TABLE_BITS_SMALL) { - window = TABLE_BITS_SMALL; // Tolerate excessively large |p|. + window = TABLE_BITS_SMALL; // Tolerate excessively large `p`. } BN_ULONG val[TABLE_SIZE_SMALL][BN_SMALL_MAX_WORDS]; OPENSSL_memcpy(val[0], a, num * sizeof(BN_ULONG)); @@ -705,8 +291,8 @@ void bn_mod_exp_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num, } } - // |p| is non-zero, so at least one window is non-zero. To save some - // multiplications, defer initializing |r| until then. + // `p` is non-zero, so at least one window is non-zero. To save some + // multiplications, defer initializing `r` until then. int r_is_one = 1; size_t wstart = bits - 1; // The top bit of the window. for (;;) { @@ -732,7 +318,7 @@ void bn_mod_exp_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num, } } - // Shift |r| to the end of the window. + // Shift `r` to the end of the window. if (!r_is_one) { for (unsigned i = 0; i < wsize + 1; i++) { bn_mod_mul_montgomery_small(r, r, r, num, mont); @@ -753,14 +339,15 @@ void bn_mod_exp_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num, wstart -= wsize + 1; } - // |p| is non-zero, so |r_is_one| must be cleared at some point. + // `p` is non-zero, so `r_is_one` must be cleared at some point. assert(!r_is_one); OPENSSL_cleanse(val, sizeof(val)); } -void bn_mod_inverse0_prime_mont_small(BN_ULONG *r, const BN_ULONG *a, - size_t num, const BN_MONT_CTX *mont) { - if (num != (size_t)mont->N.width || num > BN_SMALL_MAX_WORDS) { +void bssl::bn_mod_inverse0_prime_mont_small(BN_ULONG *r, const BN_ULONG *a, + size_t num, + const BN_MONT_CTX *mont) { + if (num != (size_t)mont->N.width || num > BN_SMALL_MAX_WORDS || num == 0) { abort(); } @@ -785,7 +372,7 @@ void bn_mod_inverse0_prime_mont_small(BN_ULONG *r, const BN_ULONG *a, static void copy_to_prebuf(const BIGNUM *b, int top, BN_ULONG *table, int idx, int window) { int ret = bn_copy_words(table + idx * top, top, b); - assert(ret); // |b| is guaranteed to fit. + assert(ret); // `b` is guaranteed to fit. (void)ret; } @@ -798,9 +385,9 @@ static int copy_from_prebuf(BIGNUM *b, int top, const BN_ULONG *table, int idx, OPENSSL_memset(b->d, 0, sizeof(BN_ULONG) * top); 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| + // 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 + // 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++) { @@ -822,7 +409,7 @@ static int copy_from_prebuf(BIGNUM *b, int top, const BN_ULONG *table, int idx, ((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 +// 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, // http://www.daemonology.net/hyperthreading-considered-harmful/) @@ -830,11 +417,10 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, const BN_MONT_CTX *mont) { int i, ret = 0, wvalue; - BN_MONT_CTX *new_mont = NULL; - void *powerbuf_free = NULL; + void *powerbuf_free = nullptr; size_t powerbuf_len = 0; - BN_ULONG *powerbuf = NULL; + BN_ULONG *powerbuf = nullptr; if (!BN_is_odd(m)) { OPENSSL_PUT_ERROR(BN, BN_R_CALLED_WITH_EVEN_MODULUS); @@ -844,14 +430,14 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER); return 0; } - // |a| is secret, but it is required to be in range, so these comparisons may + // `a` is secret, but it is required to be in range, so these comparisons may // be leaked. if (a->neg || constant_time_declassify_int(BN_ucmp(a, m) >= 0)) { OPENSSL_PUT_ERROR(BN, BN_R_INPUT_NOT_REDUCED); return 0; } - // Use all bits stored in |p|, rather than |BN_num_bits|, so we do not leak + // Use all bits stored in `p`, rather than `BN_num_bits`, so we do not leak // whether the top bits are zero. int max_bits = p->width * BN_BITS2; int bits = max_bits; @@ -866,16 +452,17 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, // Allocate a montgomery context if it was not supplied by the caller. int top, num_powers, window; - if (mont == NULL) { - new_mont = BN_MONT_CTX_new_consttime(m, ctx); - if (new_mont == NULL) { + UniquePtr new_mont; + if (mont == nullptr) { + new_mont.reset(BN_MONT_CTX_new_consttime(m, ctx)); + if (new_mont == nullptr) { goto err; } - mont = new_mont; + mont = new_mont.get(); } - // Use the width in |mont->N|, rather than the copy in |m|. The assembly - // implementation assumes it can use |top| to size R. + // Use the width in `mont->N`, rather than the copy in `m`. The assembly + // implementation assumes it can use `top` to size R. top = mont->N.width; #if defined(OPENSSL_BN_ASM_MONT5) || defined(RSAZ_ENABLED) @@ -907,7 +494,7 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, window = BN_window_bits_for_ctime_exponent_size(bits); assert(window <= BN_MAX_MOD_EXP_CTIME_WINDOW); - // Calculating |powerbuf_len| below cannot overflow because of the bound on + // Calculating `powerbuf_len` below cannot overflow because of the bound on // Montgomery reduction. assert((size_t)top <= BN_MONTGOMERY_MAX_WORDS); static_assert( @@ -918,13 +505,13 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, #if defined(OPENSSL_BN_ASM_MONT5) if (window >= 5) { window = 5; // ~5% improvement for RSA2048 sign, and even for RSA4096 - // Reserve space for the |mont->N| copy. + // Reserve space for the `mont->N` copy. powerbuf_len += top * sizeof(mont->N.d[0]); } #endif // Allocate a buffer large enough to hold all of the pre-computed - // powers of |am|, |am| itself, and |tmp|. + // powers of `am`, `am` itself, and `tmp`. num_powers = 1 << window; powerbuf_len += sizeof(m->d[0]) * top * (num_powers + 2); @@ -932,12 +519,12 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, if (powerbuf_len <= sizeof(storage)) { powerbuf = storage; } - // |storage| is more than large enough to handle 1024-bit inputs. - assert(powerbuf != NULL || top * BN_BITS2 > 1024); + // `storage` is more than large enough to handle 1024-bit inputs. + assert(powerbuf != nullptr || top * BN_BITS2 > 1024); #endif - if (powerbuf == NULL) { + if (powerbuf == nullptr) { powerbuf_free = OPENSSL_malloc(powerbuf_len + MOD_EXP_CTIME_ALIGN); - if (powerbuf_free == NULL) { + if (powerbuf_free == nullptr) { goto err; } powerbuf = reinterpret_cast( @@ -945,7 +532,7 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, } OPENSSL_memset(powerbuf, 0, powerbuf_len); - // Place |tmp| and |am| right after powers table. + // Place `tmp` and `am` right after powers table. BIGNUM tmp, am; tmp.d = powerbuf + top * num_powers; am.d = tmp.d + top; @@ -958,7 +545,7 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, goto err; } - // Prepare a^1 in the Montgomery domain. + // Prepare a¹ in the Montgomery domain. assert(!a->neg); declassify_assert(BN_ucmp(a, m) < 0); if (!BN_to_montgomery(&am, a, mont, ctx) || !bn_resize_words(&am, top)) { @@ -974,41 +561,41 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, // exponentiation, used in RSA-1024 with CRT, but RSA-1024 is no longer // important. // - // |bn_mul_mont_gather5| and |bn_power5| implement the "almost" reduction + // `bn_mul_mont_gather5` and `bn_power5` implement the "almost" reduction // variant, so the values here may not be fully reduced. They are bounded by R - // (i.e. they fit in |top| words), not |m|. Additionally, we pass these - // "almost" reduced inputs into |bn_mul_mont|, which implements the normal - // reduction variant. Given those inputs, |bn_mul_mont| may not give reduced - // output, but it will still produce "almost" reduced output. + // (i.e. they fit in `top` words), not `m`. Additionally, we pass these + // "almost" reduced inputs into `bn_mul_mont_words`, which implements the + // normal reduction variant. Given those inputs, `bn_mul_mont_words` may not + // give reduced output, but it will still produce "almost" reduced output. // // TODO(davidben): Using "almost" reduction complicates analysis of this code, // and its interaction with other parts of the project. Determine whether this // is actually necessary for performance. if (window == 5 && top > 1) { - // Copy |mont->N| to improve cache locality. + // Copy `mont->N` to improve cache locality. BN_ULONG *np = am.d + top; for (i = 0; i < top; i++) { np[i] = mont->N.d[i]; } - // Fill |powerbuf| with the first 32 powers of |am|. + // Fill `powerbuf` with the first 32 powers of `am`. const BN_ULONG *n0 = mont->n0; bn_scatter5(tmp.d, top, powerbuf, 0); bn_scatter5(am.d, am.width, powerbuf, 1); - bn_mul_mont(tmp.d, am.d, am.d, np, n0, top); + bn_mul_mont_words(tmp.d, am.d, am.d, np, n0, top); bn_scatter5(tmp.d, top, powerbuf, 2); // Square to compute powers of two. for (i = 4; i < 32; i *= 2) { - bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); + bn_mul_mont_words(tmp.d, tmp.d, tmp.d, np, n0, top); bn_scatter5(tmp.d, top, powerbuf, i); } - // Compute odd powers |i| based on |i - 1|, then all powers |i * 2^j|. + // Compute odd powers `i` based on `i - 1`, then all powers `i * 2^j`. for (i = 3; i < 32; i += 2) { bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1); bn_scatter5(tmp.d, top, powerbuf, i); for (int j = 2 * i; j < 32; j *= 2) { - bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); + bn_mul_mont_words(tmp.d, tmp.d, tmp.d, np, n0, top); bn_scatter5(tmp.d, top, powerbuf, j); } } @@ -1019,7 +606,7 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, } bn_gather5(tmp.d, top, powerbuf, wvalue); - // At this point |bits| is 4 mod 5 and at least -1. (|bits| is the first bit + // At this point `bits` is 4 mod 5 and at least -1. (`bits` is the first bit // that has not been read yet.) assert(bits >= -1 && (bits == -1 || bits % 5 == 4)); @@ -1031,26 +618,26 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); } - bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); - bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); - bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); - bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); - bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); + bn_mul_mont_words(tmp.d, tmp.d, tmp.d, np, n0, top); + bn_mul_mont_words(tmp.d, tmp.d, tmp.d, np, n0, top); + bn_mul_mont_words(tmp.d, tmp.d, tmp.d, np, n0, top); + bn_mul_mont_words(tmp.d, tmp.d, tmp.d, np, n0, top); + bn_mul_mont_words(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue); } } else { const uint8_t *p_bytes = (const uint8_t *)p->d; assert(bits < max_bits); - // |p = 0| has been handled as a special case, so |max_bits| is at least + // `p = 0` has been handled as a special case, so `max_bits` is at least // one word. assert(max_bits >= 64); // If the first bit to be read lands in the last byte, unroll the first - // iteration to avoid reading past the bounds of |p->d|. (After the first - // iteration, we are guaranteed to be past the last byte.) Note |bits| + // iteration to avoid reading past the bounds of `p->d`. (After the first + // iteration, we are guaranteed to be past the last byte.) Note `bits` // here is the top bit, inclusive. if (bits - 4 >= max_bits - 8) { - // Read five bits from |bits-4| through |bits|, inclusive. + // Read five bits from `bits-4` through `bits`, inclusive. wvalue = p_bytes[p->width * BN_BYTES - 1]; wvalue >>= (bits - 4) & 7; wvalue &= 0x1f; @@ -1058,7 +645,7 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue); } while (bits >= 0) { - // Read five bits from |bits-4| through |bits|, inclusive. + // Read five bits from `bits-4` through `bits`, inclusive. int first_bit = bits - 4; uint16_t val; OPENSSL_memcpy(&val, p_bytes + (first_bit >> 3), sizeof(val)); @@ -1068,8 +655,8 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, val); } } - // The result is now in |tmp| in Montgomery form, but it may not be fully - // reduced. This is within bounds for |BN_from_montgomery| (tmp < R <= m*R) + // The result is now in `tmp` in Montgomery form, but it may not be fully + // reduced. This is within bounds for `BN_from_montgomery` (tmp < R <= m*R) // so it will, when converting from Montgomery form, produce a fully reduced // result. // @@ -1085,7 +672,7 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, // If the window size is greater than 1, then calculate // val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) - // (even powers could instead be computed as (a^(i/2))^2 + // (even powers could instead be computed as (a^(i/2))² // to use the slight performance advantage of sqr over mul). if (window > 1) { if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx)) { @@ -1138,9 +725,9 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, } // Convert the final result from Montgomery to standard format. If we used the - // |OPENSSL_BN_ASM_MONT5| codepath, |tmp| may not be fully reduced. It is only - // bounded by R rather than |m|. However, that is still within bounds for - // |BN_from_montgomery|, which implements full Montgomery reduction, not + // `OPENSSL_BN_ASM_MONT5` codepath, `tmp` may not be fully reduced. It is only + // bounded by R rather than `m`. However, that is still within bounds for + // `BN_from_montgomery`, which implements full Montgomery reduction, not // "almost" Montgomery reduction. if (!BN_from_montgomery(rr, &tmp, mont, ctx)) { goto err; @@ -1148,75 +735,9 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, ret = 1; err: - BN_MONT_CTX_free(new_mont); - if (powerbuf != NULL && powerbuf_free == NULL) { + if (powerbuf != nullptr && powerbuf_free == nullptr) { OPENSSL_cleanse(powerbuf, powerbuf_len); } OPENSSL_free(powerbuf_free); return ret; } - -int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p, - const BIGNUM *m, BN_CTX *ctx, - const BN_MONT_CTX *mont) { - BIGNUM a_bignum; - BN_init(&a_bignum); - - int ret = 0; - - // BN_mod_exp_mont requires reduced inputs. - if (bn_minimal_width(m) == 1) { - a %= m->d[0]; - } - - if (!BN_set_word(&a_bignum, a)) { - OPENSSL_PUT_ERROR(BN, ERR_R_INTERNAL_ERROR); - goto err; - } - - ret = BN_mod_exp_mont(rr, &a_bignum, p, m, ctx, mont); - -err: - BN_free(&a_bignum); - - return ret; -} - -#define TABLE_SIZE 32 - -int BN_mod_exp2_mont(BIGNUM *rr, const BIGNUM *a1, const BIGNUM *p1, - const BIGNUM *a2, const BIGNUM *p2, const BIGNUM *m, - BN_CTX *ctx, const BN_MONT_CTX *mont) { - BIGNUM tmp; - BN_init(&tmp); - - int ret = 0; - BN_MONT_CTX *new_mont = NULL; - - // Allocate a montgomery context if it was not supplied by the caller. - if (mont == NULL) { - new_mont = BN_MONT_CTX_new_for_modulus(m, ctx); - if (new_mont == NULL) { - goto err; - } - mont = new_mont; - } - - // BN_mod_mul_montgomery removes one Montgomery factor, so passing one - // Montgomery-encoded and one non-Montgomery-encoded value gives a - // non-Montgomery-encoded result. - if (!BN_mod_exp_mont(rr, a1, p1, m, ctx, mont) || - !BN_mod_exp_mont(&tmp, a2, p2, m, ctx, mont) || - !BN_to_montgomery(rr, rr, mont, ctx) || - !BN_mod_mul_montgomery(rr, rr, &tmp, mont, ctx)) { - goto err; - } - - ret = 1; - -err: - BN_MONT_CTX_free(new_mont); - BN_free(&tmp); - - return ret; -} diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/gcd.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/gcd.cc.inc index 27c6a49c..a19332da 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/gcd.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/gcd.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,6 +19,8 @@ #include "internal.h" +using namespace bssl; + int BN_mod_inverse_odd(BIGNUM *out, int *out_no_inverse, const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx) { *out_no_inverse = 0; @@ -28,23 +35,20 @@ int BN_mod_inverse_odd(BIGNUM *out, int *out_no_inverse, const BIGNUM *a, return 0; } - BIGNUM *A, *B, *X, *Y; - int ret = 0; int sign; - - BN_CTX_start(ctx); - A = BN_CTX_get(ctx); - B = BN_CTX_get(ctx); - X = BN_CTX_get(ctx); - Y = BN_CTX_get(ctx); + BN_CTXScope scope(ctx); + BIGNUM *A = BN_CTX_get(ctx); + BIGNUM *B = BN_CTX_get(ctx); + BIGNUM *X = BN_CTX_get(ctx); + BIGNUM *Y = BN_CTX_get(ctx); BIGNUM *R = out; - if (Y == NULL) { - goto err; + if (Y == nullptr) { + return 0; } BN_zero(Y); - if (!BN_one(X) || BN_copy(B, a) == NULL || BN_copy(A, n) == NULL) { - goto err; + if (!BN_one(X) || BN_copy(B, a) == nullptr || BN_copy(A, n) == nullptr) { + return 0; } A->neg = 0; sign = -1; @@ -75,17 +79,17 @@ int BN_mod_inverse_odd(BIGNUM *out, int *out_no_inverse, const BIGNUM *a, if (BN_is_odd(X)) { if (!BN_uadd(X, X, n)) { - goto err; + return 0; } } // now X is even, so we can easily divide it by two if (!BN_rshift1(X, X)) { - goto err; + return 0; } } if (shift > 0) { if (!BN_rshift(B, B, shift)) { - goto err; + return 0; } } @@ -97,17 +101,17 @@ int BN_mod_inverse_odd(BIGNUM *out, int *out_no_inverse, const BIGNUM *a, if (BN_is_odd(Y)) { if (!BN_uadd(Y, Y, n)) { - goto err; + return 0; } } // now Y is even if (!BN_rshift1(Y, Y)) { - goto err; + return 0; } } if (shift > 0) { if (!BN_rshift(A, A, shift)) { - goto err; + return 0; } } @@ -124,21 +128,21 @@ int BN_mod_inverse_odd(BIGNUM *out, int *out_no_inverse, const BIGNUM *a, if (BN_ucmp(B, A) >= 0) { // -sign*(X + Y)*a == B - A (mod |n|) if (!BN_uadd(X, X, Y)) { - goto err; + return 0; } // NB: we could use BN_mod_add_quick(X, X, Y, n), but that // actually makes the algorithm slower if (!BN_usub(B, B, A)) { - goto err; + return 0; } } else { // sign*(X + Y)*a == A - B (mod |n|) if (!BN_uadd(Y, Y, X)) { - goto err; + return 0; } // as above, BN_mod_add_quick(Y, Y, X, n) would slow things down if (!BN_usub(A, A, B)) { - goto err; + return 0; } } } @@ -146,7 +150,7 @@ int BN_mod_inverse_odd(BIGNUM *out, int *out_no_inverse, const BIGNUM *a, if (!BN_is_one(A)) { *out_no_inverse = 1; OPENSSL_PUT_ERROR(BN, BN_R_NO_INVERSE); - goto err; + return 0; } // The while loop (Euclid's algorithm) ends when @@ -157,7 +161,7 @@ int BN_mod_inverse_odd(BIGNUM *out, int *out_no_inverse, const BIGNUM *a, if (sign < 0) { if (!BN_sub(Y, n, Y)) { - goto err; + return 0; } } // Now Y*a == A (mod |n|). @@ -165,61 +169,49 @@ int BN_mod_inverse_odd(BIGNUM *out, int *out_no_inverse, const BIGNUM *a, // Y*a == 1 (mod |n|) if (Y->neg || BN_ucmp(Y, n) >= 0) { if (!BN_nnmod(Y, Y, n, ctx)) { - goto err; + return 0; } } if (!BN_copy(R, Y)) { - goto err; + return 0; } - ret = 1; - -err: - BN_CTX_end(ctx); - return ret; + return 1; } BIGNUM *BN_mod_inverse(BIGNUM *out, const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx) { - BIGNUM *new_out = NULL; - if (out == NULL) { - new_out = BN_new(); - if (new_out == NULL) { - return NULL; + UniquePtr new_out; + if (out == nullptr) { + new_out.reset(BN_new()); + if (new_out == nullptr) { + return nullptr; } - out = new_out; + out = new_out.get(); } - int ok = 0; - BIGNUM *a_reduced = NULL; + UniquePtr a_reduced; if (a->neg || BN_ucmp(a, n) >= 0) { - a_reduced = BN_dup(a); - if (a_reduced == NULL) { - goto err; + a_reduced.reset(BN_dup(a)); + if (a_reduced == nullptr) { + return nullptr; } - if (!BN_nnmod(a_reduced, a_reduced, n, ctx)) { - goto err; + if (!BN_nnmod(a_reduced.get(), a_reduced.get(), n, ctx)) { + return nullptr; } - a = a_reduced; + a = a_reduced.get(); } int no_inverse; if (!BN_is_odd(n)) { if (!bn_mod_inverse_consttime(out, &no_inverse, a, n, ctx)) { - goto err; + return nullptr; } } else if (!BN_mod_inverse_odd(out, &no_inverse, a, n, ctx)) { - goto err; + return nullptr; } - ok = 1; - -err: - if (!ok) { - BN_free(new_out); - out = NULL; - } - BN_free(a_reduced); + new_out.release(); // Passed to the caller via `out`. return out; } @@ -227,7 +219,7 @@ int BN_mod_inverse_blinded(BIGNUM *out, int *out_no_inverse, const BIGNUM *a, const BN_MONT_CTX *mont, BN_CTX *ctx) { *out_no_inverse = 0; - // |a| is secret, but it is required to be in range, so these comparisons may + // `a` is secret, but it is required to be in range, so these comparisons may // be leaked. if (BN_is_negative(a) || constant_time_declassify_int(BN_cmp(a, &mont->N) >= 0)) { @@ -235,61 +227,55 @@ int BN_mod_inverse_blinded(BIGNUM *out, int *out_no_inverse, const BIGNUM *a, return 0; } - int ret = 0; - BIGNUM blinding_factor; - BN_init(&blinding_factor); + UniquePtr blinding_factor(BN_new()); + if (blinding_factor == nullptr) { + return 0; + } - // |BN_mod_inverse_odd| is leaky, so generate a secret blinding factor and - // blind |a|. This works because (ar)^-1 * r = a^-1, supposing r is + // `BN_mod_inverse_odd` is leaky, so generate a secret blinding factor and + // blind `a`. This works because (ar)^-1 * r = a^-1, supposing r is // invertible. If r is not invertible, this function will fail. However, we // only use this in RSA, where stumbling on an uninvertible element means // stumbling on the key's factorization. That is, if this function fails, the // RSA key was not actually a product of two large primes. // // TODO(crbug.com/boringssl/677): When the PRNG output is marked secret by - // default, the explicit |bn_secret| call can be removed. - if (!BN_rand_range_ex(&blinding_factor, 1, &mont->N)) { - goto err; + // default, the explicit `bn_secret` call can be removed. + if (!BN_rand_range_ex(blinding_factor.get(), 1, &mont->N)) { + return 0; } - bn_secret(&blinding_factor); - if (!BN_mod_mul_montgomery(out, &blinding_factor, a, mont, ctx)) { - goto err; + bn_secret(blinding_factor.get()); + if (!BN_mod_mul_montgomery(out, blinding_factor.get(), a, mont, ctx)) { + return 0; } - // Once blinded, |out| is no longer secret, so it may be passed to a leaky - // mod inverse function. Note |blinding_factor| is secret, so |out| will be + // Once blinded, `out` is no longer secret, so it may be passed to a leaky + // mod inverse function. Note `blinding_factor` is secret, so `out` will be // secret again after multiplying. bn_declassify(out); if (!BN_mod_inverse_odd(out, out_no_inverse, out, &mont->N, ctx) || - !BN_mod_mul_montgomery(out, &blinding_factor, out, mont, ctx)) { - goto err; + !BN_mod_mul_montgomery(out, blinding_factor.get(), out, mont, ctx)) { + return 0; } - ret = 1; - -err: - BN_free(&blinding_factor); - return ret; + return 1; } -int bn_mod_inverse_prime(BIGNUM *out, const BIGNUM *a, const BIGNUM *p, - BN_CTX *ctx, const BN_MONT_CTX *mont_p) { - BN_CTX_start(ctx); +int bssl::bn_mod_inverse_prime(BIGNUM *out, const BIGNUM *a, const BIGNUM *p, + BN_CTX *ctx, const BN_MONT_CTX *mont_p) { + BN_CTXScope scope(ctx); BIGNUM *p_minus_2 = BN_CTX_get(ctx); - int ok = p_minus_2 != NULL && BN_copy(p_minus_2, p) && - BN_sub_word(p_minus_2, 2) && - BN_mod_exp_mont(out, a, p_minus_2, p, ctx, mont_p); - BN_CTX_end(ctx); - return ok; + return p_minus_2 != nullptr && BN_copy(p_minus_2, p) && + BN_sub_word(p_minus_2, 2) && + BN_mod_exp_mont(out, a, p_minus_2, p, ctx, mont_p); } -int bn_mod_inverse_secret_prime(BIGNUM *out, const BIGNUM *a, const BIGNUM *p, - BN_CTX *ctx, const BN_MONT_CTX *mont_p) { - BN_CTX_start(ctx); +int bssl::bn_mod_inverse_secret_prime(BIGNUM *out, const BIGNUM *a, + const BIGNUM *p, BN_CTX *ctx, + const BN_MONT_CTX *mont_p) { + BN_CTXScope scope(ctx); BIGNUM *p_minus_2 = BN_CTX_get(ctx); - int ok = p_minus_2 != NULL && BN_copy(p_minus_2, p) && - BN_sub_word(p_minus_2, 2) && - BN_mod_exp_mont_consttime(out, a, p_minus_2, p, ctx, mont_p); - BN_CTX_end(ctx); - return ok; + return p_minus_2 != nullptr && BN_copy(p_minus_2, p) && + BN_sub_word(p_minus_2, 2) && + BN_mod_exp_mont_consttime(out, a, p_minus_2, p, ctx, mont_p); } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/gcd_extra.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/gcd_extra.cc.inc index 64a109f1..3f5e9dae 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/gcd_extra.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/gcd_extra.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2018 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2018 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 @@ -21,6 +21,8 @@ #include "internal.h" +using namespace bssl; + static BN_ULONG word_is_odd_mask(BN_ULONG a) { return (BN_ULONG)0 - (a & 1); } static void maybe_rshift1_words(BN_ULONG *a, BN_ULONG mask, BN_ULONG *tmp, @@ -56,43 +58,42 @@ static int bn_gcd_consttime(BIGNUM *r, unsigned *out_shift, const BIGNUM *x, } // This is a constant-time implementation of Stein's algorithm (binary GCD). - int ret = 0; - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *u = BN_CTX_get(ctx); BIGNUM *v = BN_CTX_get(ctx); BIGNUM *tmp = BN_CTX_get(ctx); unsigned x_bits, y_bits, num_iters, shift; - if (u == NULL || v == NULL || tmp == NULL || // + if (u == nullptr || v == nullptr || tmp == nullptr || // !BN_copy(u, x) || // !BN_copy(v, y) || // !bn_resize_words(u, width) || // !bn_resize_words(v, width) || // !bn_resize_words(tmp, width)) { - goto err; + return 0; } - // Each loop iteration halves at least one of |u| and |v|. Thus we need at + // Each loop iteration halves at least one of `u` and `v`. Thus we need at // most the combined bit width of inputs for at least one value to be zero. x_bits = x->width * BN_BITS2; y_bits = y->width * BN_BITS2; num_iters = x_bits + y_bits; if (num_iters < x_bits) { OPENSSL_PUT_ERROR(BN, BN_R_BIGNUM_TOO_LONG); - goto err; + return 0; } shift = 0; for (unsigned i = 0; i < num_iters; i++) { BN_ULONG both_odd = word_is_odd_mask(u->d[0]) & word_is_odd_mask(v->d[0]); - // If both |u| and |v| are odd, subtract the smaller from the larger. + // If both `u` and `v` are odd, subtract the smaller from the larger. BN_ULONG u_less_than_v = (BN_ULONG)0 - bn_sub_words(tmp->d, u->d, v->d, width); bn_select_words(u->d, both_odd & ~u_less_than_v, tmp->d, u->d, width); bn_sub_words(tmp->d, v->d, u->d, width); bn_select_words(v->d, both_odd & u_less_than_v, tmp->d, v->d, width); - // At least one of |u| and |v| is now even. + // At least one of `u` and `v` is now even. BN_ULONG u_is_odd = word_is_odd_mask(u->d[0]); BN_ULONG v_is_odd = word_is_odd_mask(v->d[0]); declassify_assert(!(u_is_odd & v_is_odd)); @@ -105,8 +106,8 @@ static int bn_gcd_consttime(BIGNUM *r, unsigned *out_shift, const BIGNUM *x, maybe_rshift1_words(v->d, ~v_is_odd, tmp->d, width); } - // One of |u| or |v| is zero at this point. The algorithm usually makes |u| - // zero, unless |y| was already zero on input. Fix this by combining the + // One of `u` or `v` is zero at this point. The algorithm usually makes `u` + // zero, unless `y` was already zero on input. Fix this by combining the // values. declassify_assert(BN_is_zero(u) | BN_is_zero(v)); for (size_t i = 0; i < width; i++) { @@ -114,11 +115,7 @@ static int bn_gcd_consttime(BIGNUM *r, unsigned *out_shift, const BIGNUM *x, } *out_shift = shift; - ret = bn_set_words(r, v->d, width); - -err: - BN_CTX_end(ctx); - return ret; + return bn_set_words(r, v->d, width); } int BN_gcd(BIGNUM *r, const BIGNUM *x, const BIGNUM *y, BN_CTX *ctx) { @@ -126,17 +123,16 @@ int BN_gcd(BIGNUM *r, const BIGNUM *x, const BIGNUM *y, BN_CTX *ctx) { return bn_gcd_consttime(r, &shift, x, y, ctx) && BN_lshift(r, r, shift); } -int bn_is_relatively_prime(int *out_relatively_prime, const BIGNUM *x, - const BIGNUM *y, BN_CTX *ctx) { - int ret = 0; - BN_CTX_start(ctx); +int bssl::bn_is_relatively_prime(int *out_relatively_prime, const BIGNUM *x, + const BIGNUM *y, BN_CTX *ctx) { + BN_CTXScope scope(ctx); unsigned shift; BIGNUM *gcd = BN_CTX_get(ctx); - if (gcd == NULL || !bn_gcd_consttime(gcd, &shift, x, y, ctx)) { - goto err; + if (gcd == nullptr || !bn_gcd_consttime(gcd, &shift, x, y, ctx)) { + return 0; } - // Check that 2^|shift| * |gcd| is one. + // Check that 2^`shift` * `gcd` is one. if (gcd->width == 0) { *out_relatively_prime = 0; } else { @@ -146,29 +142,26 @@ int bn_is_relatively_prime(int *out_relatively_prime, const BIGNUM *x, } *out_relatively_prime = mask == 0; } - ret = 1; -err: - BN_CTX_end(ctx); - return ret; + return 1; } -int bn_lcm_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { - BN_CTX_start(ctx); +int bssl::bn_lcm_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + BN_CTX *ctx) { + BN_CTXScope scope(ctx); unsigned shift; BIGNUM *gcd = BN_CTX_get(ctx); - int ret = gcd != NULL && // - bn_mul_consttime(r, a, b, ctx) && - bn_gcd_consttime(gcd, &shift, a, b, ctx) && - // |gcd| has a secret bit width. - bn_div_consttime(r, NULL, r, gcd, /*divisor_min_bits=*/0, ctx) && - bn_rshift_secret_shift(r, r, shift, ctx); - BN_CTX_end(ctx); - return ret; + return gcd != nullptr && // + bn_mul_consttime(r, a, b, ctx) && + bn_gcd_consttime(gcd, &shift, a, b, ctx) && + // `gcd` has a secret bit width. + bn_div_consttime(r, nullptr, r, gcd, /*divisor_min_bits=*/0, ctx) && + bn_rshift_secret_shift(r, r, shift, ctx); } -int bn_mod_inverse_consttime(BIGNUM *r, int *out_no_inverse, const BIGNUM *a, - const BIGNUM *n, BN_CTX *ctx) { +int bssl::bn_mod_inverse_consttime(BIGNUM *r, int *out_no_inverse, + const BIGNUM *a, const BIGNUM *n, + BN_CTX *ctx) { *out_no_inverse = 0; if (BN_is_negative(a) || BN_ucmp(a, n) >= 0) { OPENSSL_PUT_ERROR(BN, BN_R_INPUT_NOT_REDUCED); @@ -190,9 +183,9 @@ int bn_mod_inverse_consttime(BIGNUM *r, int *out_no_inverse, const BIGNUM *a, // negative numbers. // // For more details and proof of correctness, see - // https://github.com/mit-plv/fiat-crypto/pull/333. In particular, see |step| - // and |mod_inverse_consttime| for the algorithm in Gallina and see - // |mod_inverse_consttime_spec| for the correctness result. + // https://github.com/mit-plv/fiat-crypto/pull/333. In particular, see `step` + // and `mod_inverse_consttime` for the algorithm in Gallina and see + // `mod_inverse_consttime_spec` for the correctness result. if (!BN_is_odd(a) && !BN_is_odd(n)) { *out_no_inverse = 1; @@ -200,15 +193,14 @@ int bn_mod_inverse_consttime(BIGNUM *r, int *out_no_inverse, const BIGNUM *a, return 0; } - // This function exists to compute the RSA private exponent, where |a| is one - // word. We'll thus use |a_width| when available. + // This function exists to compute the RSA private exponent, where `a` is one + // word. We'll thus use `a_width` when available. size_t n_width = n->width, a_width = a->width; if (a_width > n_width) { a_width = n_width; } - int ret = 0; - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *u = BN_CTX_get(ctx); BIGNUM *v = BN_CTX_get(ctx); BIGNUM *A = BN_CTX_get(ctx); @@ -218,43 +210,43 @@ int bn_mod_inverse_consttime(BIGNUM *r, int *out_no_inverse, const BIGNUM *a, BIGNUM *tmp = BN_CTX_get(ctx); BIGNUM *tmp2 = BN_CTX_get(ctx); size_t a_bits, num_iters, n_bits; - if (u == NULL || // - v == NULL || // - A == NULL || // - B == NULL || // - C == NULL || // - D == NULL || // - tmp == NULL || // - tmp2 == NULL || // + if (u == nullptr || // + v == nullptr || // + A == nullptr || // + B == nullptr || // + C == nullptr || // + D == nullptr || // + tmp == nullptr || // + tmp2 == nullptr || // !BN_copy(u, a) || // !BN_copy(v, n) || // !BN_one(A) || // !BN_one(D) || - // For convenience, size |u| and |v| equivalently. + // For convenience, size `u` and `v` equivalently. !bn_resize_words(u, n_width) || // !bn_resize_words(v, n_width) || - // |A| and |C| are bounded by |m|. + // `A` and `C` are bounded by `m`. !bn_resize_words(A, n_width) || // !bn_resize_words(C, n_width) || - // |B| and |D| are bounded by |a|. + // `B` and `D` are bounded by `a`. !bn_resize_words(B, a_width) || // !bn_resize_words(D, a_width) || - // |tmp| and |tmp2| may be used at either size. + // `tmp` and `tmp2` may be used at either size. !bn_resize_words(tmp, n_width) || // !bn_resize_words(tmp2, n_width)) { - goto err; + return 0; } - // Each loop iteration halves at least one of |u| and |v|. Thus we need at + // Each loop iteration halves at least one of `u` and `v`. Thus we need at // most the combined bit width of inputs for at least one value to be zero. - // |a_bits| and |n_bits| cannot overflow because |bn_wexpand| ensures bit - // counts fit in even |int|. + // `a_bits` and `n_bits` cannot overflow because `bn_wexpand` ensures bit + // counts fit in even `int`. a_bits = a_width * BN_BITS2; n_bits = n_width * BN_BITS2; num_iters = a_bits + n_bits; if (num_iters < a_bits) { OPENSSL_PUT_ERROR(BN, BN_R_BIGNUM_TOO_LONG); - goto err; + return 0; } // Before and after each loop iteration, the following hold: @@ -273,7 +265,7 @@ int bn_mod_inverse_consttime(BIGNUM *r, int *out_no_inverse, const BIGNUM *a, for (size_t i = 0; i < num_iters; i++) { BN_ULONG both_odd = word_is_odd_mask(u->d[0]) & word_is_odd_mask(v->d[0]); - // If both |u| and |v| are odd, subtract the smaller from the larger. + // If both `u` and `v` are odd, subtract the smaller from the larger. BN_ULONG v_less_than_u = (BN_ULONG)0 - bn_sub_words(tmp->d, v->d, u->d, n_width); bn_select_words(v->d, both_odd & ~v_less_than_u, tmp->d, v->d, n_width); @@ -293,8 +285,8 @@ int bn_mod_inverse_consttime(BIGNUM *r, int *out_no_inverse, const BIGNUM *a, bn_select_words(B->d, both_odd & v_less_than_u, tmp->d, B->d, a_width); bn_select_words(D->d, both_odd & ~v_less_than_u, tmp->d, D->d, a_width); - // Our loop invariants hold at this point. Additionally, exactly one of |u| - // and |v| is now even. + // Our loop invariants hold at this point. Additionally, exactly one of `u` + // and `v` is now even. BN_ULONG u_is_even = ~word_is_odd_mask(u->d[0]); BN_ULONG v_is_even = ~word_is_odd_mask(v->d[0]); declassify_assert(u_is_even != v_is_even); @@ -328,12 +320,8 @@ int bn_mod_inverse_consttime(BIGNUM *r, int *out_no_inverse, const BIGNUM *a, if (constant_time_declassify_int(!BN_is_one(u))) { *out_no_inverse = 1; OPENSSL_PUT_ERROR(BN, BN_R_NO_INVERSE); - goto err; + return 0; } - ret = BN_copy(r, A) != NULL; - -err: - BN_CTX_end(ctx); - return ret; + return BN_copy(r, A) != nullptr; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/generic.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/generic.cc.inc index fd705fe3..ed741a83 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/generic.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/generic.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,23 +19,7 @@ #include "internal.h" -#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86) -// See asm/bn-586.pl. -#define BN_ADD_ASM -#define BN_MUL_ASM -#endif - -#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) && \ - (defined(__GNUC__) || defined(__clang__)) -// See asm/x86_64-gcc.c -#define BN_ADD_ASM -#define BN_MUL_ASM -#endif - -#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_AARCH64) -// See asm/bn-armv8.pl. -#define BN_ADD_ASM -#endif +using namespace bssl; #if !defined(BN_MUL_ASM) @@ -39,24 +28,24 @@ do { \ BN_ULLONG t; \ t = (BN_ULLONG)(w) * (a) + (r) + (c); \ - (r) = Lw(t); \ - (c) = Hw(t); \ + (r) = (BN_ULONG)(t); \ + (c) = (BN_ULONG)((t) >> BN_BITS2); \ } while (0) -#define mul(r, a, w, c) \ - do { \ - BN_ULLONG t; \ - t = (BN_ULLONG)(w) * (a) + (c); \ - (r) = Lw(t); \ - (c) = Hw(t); \ +#define mul(r, a, w, c) \ + do { \ + BN_ULLONG t; \ + t = (BN_ULLONG)(w) * (a) + (c); \ + (r) = (BN_ULONG)(t); \ + (c) = (BN_ULONG)((t) >> BN_BITS2); \ } while (0) -#define sqr(r0, r1, a) \ - do { \ - BN_ULLONG t; \ - t = (BN_ULLONG)(a) * (a); \ - (r0) = Lw(t); \ - (r1) = Hw(t); \ +#define sqr(r0, r1, a) \ + do { \ + BN_ULLONG t; \ + t = (BN_ULLONG)(a) * (a); \ + (r0) = (BN_ULONG)(t); \ + (r1) = (BN_ULONG)((t) >> BN_BITS2); \ } while (0) #else @@ -92,8 +81,8 @@ #endif // !BN_ULLONG -BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, - BN_ULONG w) { +BN_ULONG bssl::bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, + BN_ULONG w) { BN_ULONG c1 = 0; if (num == 0) { @@ -120,8 +109,8 @@ BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, return c1; } -BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, - BN_ULONG w) { +BN_ULONG bssl::bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, + BN_ULONG w) { BN_ULONG c1 = 0; if (num == 0) { @@ -146,22 +135,33 @@ BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, return c1; } -void bn_sqr_words(BN_ULONG *r, const BN_ULONG *a, size_t n) { +void bssl::bn_sqr_add_words(BN_ULONG *r, const BN_ULONG *a, size_t n) { if (n == 0) { return; } + BN_ULONG carry = 0, lo, hi; while (n & ~3) { - sqr(r[0], r[1], a[0]); - sqr(r[2], r[3], a[1]); - sqr(r[4], r[5], a[2]); - sqr(r[6], r[7], a[3]); + sqr(lo, hi, a[0]); + r[0] = CRYPTO_addc_w(r[0], lo, carry, &carry); + r[1] = CRYPTO_addc_w(r[1], hi, carry, &carry); + sqr(lo, hi, a[1]); + r[2] = CRYPTO_addc_w(r[2], lo, carry, &carry); + r[3] = CRYPTO_addc_w(r[3], hi, carry, &carry); + sqr(lo, hi, a[2]); + r[4] = CRYPTO_addc_w(r[4], lo, carry, &carry); + r[5] = CRYPTO_addc_w(r[5], hi, carry, &carry); + sqr(lo, hi, a[3]); + r[6] = CRYPTO_addc_w(r[6], lo, carry, &carry); + r[7] = CRYPTO_addc_w(r[7], hi, carry, &carry); a += 4; r += 8; n -= 4; } while (n) { - sqr(r[0], r[1], a[0]); + sqr(lo, hi, a[0]); + r[0] = CRYPTO_addc_w(r[0], lo, carry, &carry); + r[1] = CRYPTO_addc_w(r[1], hi, carry, &carry); a++; r += 2; n--; @@ -182,8 +182,8 @@ void bn_sqr_words(BN_ULONG *r, const BN_ULONG *a, size_t n) { BN_ULONG hi; \ BN_ULLONG t = (BN_ULLONG)(a) * (b); \ t += (c0); /* no carry */ \ - (c0) = (BN_ULONG)Lw(t); \ - hi = (BN_ULONG)Hw(t); \ + (c0) = (BN_ULONG)(t); \ + hi = (BN_ULONG)((t) >> BN_BITS2); \ (c1) += (hi); \ (c2) += (c1) < hi; \ } while (0) @@ -193,13 +193,13 @@ void bn_sqr_words(BN_ULONG *r, const BN_ULONG *a, size_t n) { BN_ULONG hi; \ BN_ULLONG t = (BN_ULLONG)(a) * (b); \ BN_ULLONG tt = t + (c0); /* no carry */ \ - (c0) = (BN_ULONG)Lw(tt); \ - hi = (BN_ULONG)Hw(tt); \ + (c0) = (BN_ULONG)(tt); \ + hi = (BN_ULONG)((tt) >> BN_BITS2); \ (c1) += hi; \ (c2) += (c1) < hi; \ t += (c0); /* no carry */ \ - (c0) = (BN_ULONG)Lw(t); \ - hi = (BN_ULONG)Hw(t); \ + (c0) = (BN_ULONG)(t); \ + hi = (BN_ULONG)((t) >> BN_BITS2); \ (c1) += hi; \ (c2) += (c1) < hi; \ } while (0) @@ -209,8 +209,8 @@ void bn_sqr_words(BN_ULONG *r, const BN_ULONG *a, size_t n) { BN_ULONG hi; \ BN_ULLONG t = (BN_ULLONG)(a)[i] * (a)[i]; \ t += (c0); /* no carry */ \ - (c0) = (BN_ULONG)Lw(t); \ - hi = (BN_ULONG)Hw(t); \ + (c0) = (BN_ULONG)(t); \ + hi = (BN_ULONG)((t) >> BN_BITS2); \ (c1) += hi; \ (c2) += (c1) < hi; \ } while (0) @@ -262,7 +262,8 @@ void bn_sqr_words(BN_ULONG *r, const BN_ULONG *a, size_t n) { #endif // !BN_ULLONG -void bn_mul_comba8(BN_ULONG r[16], const BN_ULONG a[8], const BN_ULONG b[8]) { +void bssl::bn_mul_comba8(BN_ULONG r[16], const BN_ULONG a[8], + const BN_ULONG b[8]) { BN_ULONG c1, c2, c3; c1 = 0; @@ -364,7 +365,8 @@ void bn_mul_comba8(BN_ULONG r[16], const BN_ULONG a[8], const BN_ULONG b[8]) { r[15] = c1; } -void bn_mul_comba4(BN_ULONG r[8], const BN_ULONG a[4], const BN_ULONG b[4]) { +void bssl::bn_mul_comba4(BN_ULONG r[8], const BN_ULONG a[4], + const BN_ULONG b[4]) { BN_ULONG c1, c2, c3; c1 = 0; @@ -402,7 +404,7 @@ void bn_mul_comba4(BN_ULONG r[8], const BN_ULONG a[4], const BN_ULONG b[4]) { r[7] = c2; } -void bn_sqr_comba8(BN_ULONG r[16], const BN_ULONG a[8]) { +void bssl::bn_sqr_comba8(BN_ULONG r[16], const BN_ULONG a[8]) { BN_ULONG c1, c2, c3; c1 = 0; @@ -476,7 +478,7 @@ void bn_sqr_comba8(BN_ULONG r[16], const BN_ULONG a[8]) { r[15] = c1; } -void bn_sqr_comba4(BN_ULONG r[8], const BN_ULONG a[4]) { +void bssl::bn_sqr_comba4(BN_ULONG r[8], const BN_ULONG a[4]) { BN_ULONG c1, c2, c3; c1 = 0; @@ -520,8 +522,8 @@ void bn_sqr_comba4(BN_ULONG r[8], const BN_ULONG a[4]) { #if !defined(BN_ADD_ASM) -BN_ULONG bn_add_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, - size_t n) { +BN_ULONG bssl::bn_add_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, + size_t n) { if (n == 0) { return 0; } @@ -547,8 +549,8 @@ BN_ULONG bn_add_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, return carry; } -BN_ULONG bn_sub_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, - size_t n) { +BN_ULONG bssl::bn_sub_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, + size_t n) { if (n == 0) { return (BN_ULONG)0; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/internal.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/internal.h index 3f8970f0..135b89f2 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/internal.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/internal.h @@ -1,30 +1,32 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. +// +// 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. -#ifndef OPENSSL_HEADER_BN_INTERNAL_H -#define OPENSSL_HEADER_BN_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_BN_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_BN_INTERNAL_H #include #if defined(OPENSSL_X86_64) && defined(_MSC_VER) -OPENSSL_MSVC_PRAGMA(warning(push, 3)) #include -OPENSSL_MSVC_PRAGMA(warning(pop)) #pragma intrinsic(__umulh, _umul128) #endif #include "../../internal.h" -#if defined(__cplusplus) -extern "C" { -#endif + +BSSL_NAMESPACE_BEGIN #if defined(OPENSSL_64_BIT) @@ -62,7 +64,7 @@ extern "C" { #define BN_MASK2h1 (0xffff8000UL) #define BN_MASK2h (0xffff0000UL) // On some 32-bit platforms, Montgomery multiplication is done using 64-bit -// arithmetic with SIMD instructions. On such platforms, |BN_MONT_CTX::n0| +// arithmetic with SIMD instructions. On such platforms, `BN_MONT_CTX::n0` // needs to be two words long. Only certain 32-bit platforms actually make use // of n0[1] and shorter R value would suffice for the others. However, // currently only the assembly files know which is which. @@ -79,7 +81,7 @@ extern "C" { #define BN_CAN_USE_INLINE_ASM #endif -// MOD_EXP_CTIME_ALIGN is the alignment needed for |BN_mod_exp_mont_consttime|'s +// MOD_EXP_CTIME_ALIGN is the alignment needed for `BN_mod_exp_mont_consttime`'s // tables. // // TODO(davidben): Historically, this alignment came from cache line @@ -89,8 +91,8 @@ extern "C" { // requirements. #define MOD_EXP_CTIME_ALIGN 64 -// MOD_EXP_CTIME_STORAGE_LEN is the number of |BN_ULONG|s needed for the -// |BN_mod_exp_mont_consttime| stack-allocated storage buffer. The buffer is +// MOD_EXP_CTIME_STORAGE_LEN is the number of `BN_ULONG`s needed for the +// `BN_mod_exp_mont_consttime` stack-allocated storage buffer. The buffer is // just the right size for the RSAZ and is about ~1KB larger than what's // necessary (4480 bytes) for 1024-bit inputs. #define MOD_EXP_CTIME_STORAGE_LEN \ @@ -102,223 +104,306 @@ extern "C" { sizeof(x) / sizeof(BN_ULONG), 0, BN_FLG_STATIC_DATA \ } -#if defined(BN_ULLONG) -#define Lw(t) ((BN_ULONG)(t)) -#define Hw(t) ((BN_ULONG)((t) >> BN_BITS2)) -#endif - // bn_minimal_width returns the minimal number of words needed to represent -// |bn|. +// `bn`. int bn_minimal_width(const BIGNUM *bn); -// bn_set_minimal_width sets |bn->width| to |bn_minimal_width(bn)|. If |bn| is -// zero, |bn->neg| is set to zero. +// bn_set_minimal_width sets `bn->width` to `bn_minimal_width(bn)`. If `bn` is +// zero, `bn->neg` is set to zero. void bn_set_minimal_width(BIGNUM *bn); -// bn_wexpand ensures that |bn| has at least |words| works of space without +// bn_wexpand ensures that `bn` has at least `words` works of space without // altering its value. It returns one on success or zero on allocation // failure. int bn_wexpand(BIGNUM *bn, size_t words); -// bn_expand acts the same as |bn_wexpand|, but takes a number of bits rather +// bn_expand acts the same as `bn_wexpand`, but takes a number of bits rather // than a number of words. int bn_expand(BIGNUM *bn, size_t bits); -// bn_resize_words adjusts |bn->width| to be |words|. It returns one on success -// and zero on allocation error or if |bn|'s value is too large. +// bn_resize_words adjusts `bn->width` to be `words`. It returns one on success +// and zero on allocation error or if `bn`'s value is too large. OPENSSL_EXPORT int bn_resize_words(BIGNUM *bn, size_t words); -// bn_select_words sets |r| to |a| if |mask| is all ones or |b| if |mask| is +// bn_select_words sets `r` to `a` if `mask` is all ones or `b` if `mask` is // all zeros. void bn_select_words(BN_ULONG *r, BN_ULONG mask, const BN_ULONG *a, const BN_ULONG *b, size_t num); -// bn_set_words sets |bn| to the value encoded in the |num| words in |words|, +// bn_set_words sets `bn` to the value encoded in the `num` words in `words`, // least significant word first. int bn_set_words(BIGNUM *bn, const BN_ULONG *words, size_t num); -// bn_set_static_words acts like |bn_set_words|, but doesn't copy the data. A -// flag is set on |bn| so that |BN_free| won't attempt to free the data. +// bn_set_static_words acts like `bn_set_words`, but doesn't copy the data. A +// flag is set on `bn` so that `BN_free` won't attempt to free the data. // -// The |STATIC_BIGNUM| macro is probably a better solution for this outside of +// The `STATIC_BIGNUM` macro is probably a better solution for this outside of // the FIPS module. Inside of the FIPS module that macro generates rel.ro data, // which doesn't work with FIPS requirements. void bn_set_static_words(BIGNUM *bn, const BN_ULONG *words, size_t num); -// bn_fits_in_words returns one if |bn| may be represented in |num| words, plus +// bn_fits_in_words returns one if `bn` may be represented in `num` words, plus // a sign bit, and zero otherwise. int bn_fits_in_words(const BIGNUM *bn, size_t num); -// bn_copy_words copies the value of |bn| to |out| and returns one if the value -// is representable in |num| words. Otherwise, it returns zero. +// bn_copy_words copies the value of `bn` to `out` and returns one if the value +// is representable in `num` words. Otherwise, it returns zero. int bn_copy_words(BN_ULONG *out, size_t num, const BIGNUM *bn); -// bn_assert_fits_in_bytes asserts that |bn| fits in |num| bytes. This is a +// bn_assert_fits_in_bytes asserts that `bn` fits in `num` bytes. This is a // no-op in release builds, but triggers an assert in debug builds, and // declassifies all bytes which are therefore known to be zero in constant-time // validation. void bn_assert_fits_in_bytes(const BIGNUM *bn, size_t num); -// bn_secret marks |bn|'s contents, but not its width or sign, as secret. See -// |CONSTTIME_SECRET| for details. +// bn_secret marks `bn`'s contents, but not its width or sign, as secret. See +// `CONSTTIME_SECRET` for details. inline void bn_secret(BIGNUM *bn) { CONSTTIME_SECRET(bn->d, bn->width * sizeof(BN_ULONG)); } -// bn_declassify marks |bn|'s value as public. See |CONSTTIME_DECLASSIFY| for +// bn_declassify marks `bn`'s value as public. See `CONSTTIME_DECLASSIFY` for // details. inline void bn_declassify(BIGNUM *bn) { CONSTTIME_DECLASSIFY(bn->d, bn->width * sizeof(BN_ULONG)); } -// bn_mul_add_words multiples |ap| by |w|, adds the result to |rp|, and places -// the result in |rp|. |ap| and |rp| must both be |num| words long. It returns -// the carry word of the operation. |ap| and |rp| may be equal but otherwise may +#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86) +// See asm/bn-586.pl. +#define BN_ADD_ASM +#define BN_MUL_ASM +#endif + +#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) && \ + (defined(__GNUC__) || defined(__clang__)) +// See asm/x86_64-gcc.c +#define BN_ADD_ASM +#define BN_MUL_ASM +#endif + +#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_AARCH64) +// See asm/bn-armv8.pl. +#define BN_ADD_ASM +#endif + +// bn_mul_add_words multiples `ap` by `w`, adds the result to `rp`, and places +// the result in `rp`. `ap` and `rp` must both be `num` words long. It returns +// the carry word of the operation. `ap` and `rp` may be equal but otherwise may // not alias. -BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, +#if defined(BN_MUL_ASM) +extern "C" +#endif + BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, + BN_ULONG w); + +// bn_mul_words multiples `ap` by `w` and places the result in `rp`. `ap` and +// `rp` must both be `num` words long. It returns the carry word of the +// operation. `ap` and `rp` may be equal but otherwise may not alias. +#if defined(BN_MUL_ASM) +extern "C" +#endif + BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, BN_ULONG w); -// bn_mul_words multiples |ap| by |w| and places the result in |rp|. |ap| and -// |rp| must both be |num| words long. It returns the carry word of the -// operation. |ap| and |rp| may be equal but otherwise may not alias. -BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num, BN_ULONG w); - -// bn_sqr_words sets |rp[2*i]| and |rp[2*i+1]| to |ap[i]|'s square, for all |i| -// up to |num|. |ap| is an array of |num| words and |rp| an array of |2*num| -// words. |ap| and |rp| may not alias. +// bn_sqr_add_words computes `tmp` where `tmp[2*i]` and `tmp[2*i+1]` are +// `ap[i]`'s square, for all `i` up to `num`, and adds the result to `rp`. If +// the result does not fit in `2*num` words, the final carry bit is truncated. +// `ap` is an array of `num` words and `rp` an array of `2*num` words. `ap` and +// `rp` may not alias. // -// This gives the contribution of the |ap[i]*ap[i]| terms when squaring |ap|. -void bn_sqr_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num); +// This gives the contribution of the `ap[i]*ap[i]` terms when squaring `ap`. +#if defined(BN_MUL_ASM) +extern "C" +#endif + void bn_sqr_add_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num); -// bn_add_words adds |ap| to |bp| and places the result in |rp|, each of which -// are |num| words long. It returns the carry bit, which is one if the operation -// overflowed and zero otherwise. Any pair of |ap|, |bp|, and |rp| may be equal +// bn_add_words adds `ap` to `bp` and places the result in `rp`, each of which +// are `num` words long. It returns the carry bit, which is one if the operation +// overflowed and zero otherwise. Any pair of `ap`, `bp`, and `rp` may be equal // to each other but otherwise may not alias. -BN_ULONG bn_add_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, - size_t num); +#if defined(BN_ADD_ASM) +extern "C" +#endif + BN_ULONG bn_add_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, + size_t num); -// bn_sub_words subtracts |bp| from |ap| and places the result in |rp|. It +// bn_sub_words subtracts `bp` from `ap` and places the result in `rp`. It // returns the borrow bit, which is one if the computation underflowed and zero -// otherwise. Any pair of |ap|, |bp|, and |rp| may be equal to each other but +// otherwise. Any pair of `ap`, `bp`, and `rp` may be equal to each other but // otherwise may not alias. -BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, - size_t num); +#if defined(BN_ADD_ASM) +extern "C" +#endif + BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, + size_t num); -// bn_mul_comba4 sets |r| to the product of |a| and |b|. -void bn_mul_comba4(BN_ULONG r[8], const BN_ULONG a[4], const BN_ULONG b[4]); +// bn_mul_comba4 sets `r` to the product of `a` and `b`. +#if defined(BN_MUL_ASM) +extern "C" +#endif + void bn_mul_comba4(BN_ULONG r[8], const BN_ULONG a[4], const BN_ULONG b[4]); -// bn_mul_comba8 sets |r| to the product of |a| and |b|. -void bn_mul_comba8(BN_ULONG r[16], const BN_ULONG a[8], const BN_ULONG b[8]); +// bn_mul_comba8 sets `r` to the product of `a` and `b`. +#if defined(BN_MUL_ASM) +extern "C" +#endif + void bn_mul_comba8(BN_ULONG r[16], const BN_ULONG a[8], + const BN_ULONG b[8]); -// bn_sqr_comba8 sets |r| to |a|^2. -void bn_sqr_comba8(BN_ULONG r[16], const BN_ULONG a[8]); +// bn_sqr_comba8 sets `r` to `a`². +#if defined(BN_MUL_ASM) +extern "C" +#endif + void bn_sqr_comba8(BN_ULONG r[16], const BN_ULONG a[8]); -// bn_sqr_comba4 sets |r| to |a|^2. -void bn_sqr_comba4(BN_ULONG r[8], const BN_ULONG a[4]); +// bn_sqr_comba4 sets `r` to `a`². +#if defined(BN_MUL_ASM) +extern "C" +#endif + void bn_sqr_comba4(BN_ULONG r[8], const BN_ULONG a[4]); -// bn_less_than_words returns one if |a| < |b| and zero otherwise, where |a| -// and |b| both are |len| words long. It runs in constant time. +// bn_add_carry_words adds `carry` to `ap` and places the result in `rp`. `ap` +// and `rp` are `num` words long and may alias. `carry` must be 0 or 1. It +// returns the carry bit, which is one if the operation overflowed and zero +// otherwise. +BN_ULONG bn_add_carry_words(BN_ULONG *rp, const BN_ULONG *ap, BN_ULONG carry, + size_t num); + +// bn_less_than_words returns one if `a` < `b` and zero otherwise, where `a` +// and `b` both are `len` words long. It runs in constant time. int bn_less_than_words(const BN_ULONG *a, const BN_ULONG *b, size_t len); -// bn_in_range_words returns one if |min_inclusive| <= |a| < |max_exclusive|, -// where |a| and |max_exclusive| both are |len| words long. |a| and -// |max_exclusive| are treated as secret. +// bn_in_range_words returns one if `min_inclusive` <= `a` < `max_exclusive`, +// where `a` and `max_exclusive` both are `len` words long. `a` and +// `max_exclusive` are treated as secret. int bn_in_range_words(const BN_ULONG *a, BN_ULONG min_inclusive, const BN_ULONG *max_exclusive, size_t len); -// bn_rand_range_words sets |out| to a uniformly distributed random number from -// |min_inclusive| to |max_exclusive|. Both |out| and |max_exclusive| are |len| +// bn_rand_range_words sets `out` to a uniformly distributed random number from +// `min_inclusive` to `max_exclusive`. Both `out` and `max_exclusive` are `len` // words long. // -// This function runs in time independent of the result, but |min_inclusive| and -// |max_exclusive| are public data. (Information about the range is unavoidably +// This function runs in time independent of the result, but `min_inclusive` and +// `max_exclusive` are public data. (Information about the range is unavoidably // leaked by how many iterations it took to select a number.) int bn_rand_range_words(BN_ULONG *out, BN_ULONG min_inclusive, const BN_ULONG *max_exclusive, size_t len, const uint8_t additional_data[32]); -// bn_range_secret_range behaves like |BN_rand_range_ex|, but treats -// |max_exclusive| as secret. Because of this constraint, the distribution of +// bn_range_secret_range behaves like `BN_rand_range_ex`, but treats +// `max_exclusive` as secret. Because of this constraint, the distribution of // values returned is more complex. // // Rather than repeatedly generating values until one is in range, which would // leak information, it generates one value. If the value is in range, it sets -// |*out_is_uniform| to one. Otherwise, it sets |*out_is_uniform| to zero, +// `*out_is_uniform` to one. Otherwise, it sets `*out_is_uniform` to zero, // fixing up the value to force it in range. // -// The subset of calls to |bn_rand_secret_range| which set |*out_is_uniform| to +// The subset of calls to `bn_rand_secret_range` which set `*out_is_uniform` to // one are uniformly distributed in the target range. Calls overall are not. // This function is intended for use in situations where the extra values are // still usable and where the number of iterations needed to reach the target // number of uniform outputs may be blinded for negligible probabilities of // timing leaks. // -// Although this function treats |max_exclusive| as secret, it treats the number -// of bits in |max_exclusive| as public. +// Although this function treats `max_exclusive` as secret, it treats the number +// of bits in `max_exclusive` as public. int bn_rand_secret_range(BIGNUM *r, int *out_is_uniform, BN_ULONG min_inclusive, const BIGNUM *max_exclusive); -// BN_MONTGOMERY_MAX_WORDS is the maximum numer of words allowed in a |BIGNUM| +// BN_MONTGOMERY_MAX_WORDS is the maximum number of words allowed in a `BIGNUM` // used with Montgomery reduction. Ideally this limit would be applied to all -// |BIGNUM|s, in |bn_wexpand|, but the exactfloat library needs to create 8 MiB +// `BIGNUM`s, in `bn_wexpand`, but the exactfloat library needs to create 8 MiB // values for other operations. -#define BN_MONTGOMERY_MAX_WORDS (8 * 1024 / sizeof(BN_ULONG)) +// +// This limit is set so that one number fits within 2 KiB, giving room to +// allocate a few of them on the stack. It is also set to limit the DoS impact +// of large RSA, DH, and DSA keys, which scale cubically. +#define BN_MONTGOMERY_MAX_WORDS (16384 / BN_BITS2) + +BSSL_NAMESPACE_END + +struct bn_mont_ctx_st { + // RR is R², reduced modulo `N`. It is used to convert to Montgomery form. It + // is guaranteed to have the same width as `N`. + BIGNUM RR; + // N is the modulus. It is always stored in minimal form, so `N.width` + // determines R. + BIGNUM N; + BN_ULONG n0[BN_MONT_CTX_N0_LIMBS]; // least significant words of (R*Ri-1)/N +}; + +BSSL_NAMESPACE_BEGIN #if !defined(OPENSSL_NO_ASM) && \ (defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || \ defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) #define OPENSSL_BN_ASM_MONT -// bn_mul_mont writes |ap| * |bp| mod |np| to |rp|, each |num| words -// long. Inputs and outputs are in Montgomery form. |n0| is a pointer to the -// corresponding field in |BN_MONT_CTX|. It returns one if |bn_mul_mont| handles -// inputs of this size and zero otherwise. +// bn_mul_mont_words writes `ap` * `bp` mod `np` to `rp`, each `num` words +// long. Inputs and outputs are in Montgomery form. `n0` is a pointer to the +// corresponding field in `BN_MONT_CTX`. // -// If at least one of |ap| or |bp| is fully reduced, |rp| will be fully reduced. +// If at least one of `ap` or `bp` is fully reduced, `rp` will be fully reduced. // If neither is fully-reduced, the output may not be either. // -// This function allocates |num| words on the stack, so |num| should be at most -// |BN_MONTGOMERY_MAX_WORDS|. +// This function allocates up to 2 * `num` words (plus a constant allocation) on +// the stack, so `num` should be at most `BN_MONTGOMERY_MAX_WORDS`. +// Additionally, `num` must be at least 128 / `BN_BITS2`. // // TODO(davidben): The x86_64 implementation expects a 32-bit input and masks // off upper bits. The aarch64 implementation expects a 64-bit input and does -// not. |size_t| is the safer option but not strictly correct for x86_64. But -// the |BN_MONTGOMERY_MAX_WORDS| bound makes this moot. +// not. `size_t` is the safer option but not strictly correct for x86_64. But +// the `BN_MONTGOMERY_MAX_WORDS` bound makes this moot. // -// See also discussion in |ToWord| in abi_test.h for notes on smaller-than-word +// See also discussion in `ToWord` in abi_test.h for notes on smaller-than-word // inputs. -int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, - const BN_ULONG *np, const BN_ULONG *n0, size_t num); +extern "C" void bn_mul_mont_words(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *bp, const BN_ULONG *np, + const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], + size_t num); #if defined(OPENSSL_X86_64) -inline int bn_mulx_adx_capable(void) { +inline int bn_mulx_adx_capable() { // MULX is in BMI2. return CRYPTO_is_BMI2_capable() && CRYPTO_is_ADX_capable(); } -int bn_mul_mont_nohw(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, - const BN_ULONG *np, const BN_ULONG *n0, size_t num); +extern "C" void bn_mul_mont_nohw(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *bp, const BN_ULONG *np, + const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], + size_t num); inline int bn_mul4x_mont_capable(size_t num) { return num >= 8 && (num & 3) == 0; } -int bn_mul4x_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, - const BN_ULONG *np, const BN_ULONG *n0, size_t num); +extern "C" void bn_mul4x_mont(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *bp, const BN_ULONG *np, + const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], + size_t num); inline int bn_mulx4x_mont_capable(size_t num) { return bn_mul4x_mont_capable(num) && bn_mulx_adx_capable(); } -int bn_mulx4x_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, - const BN_ULONG *np, const BN_ULONG *n0, size_t num); +extern "C" void bn_mulx4x_mont(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *bp, const BN_ULONG *np, + const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], + size_t num); inline int bn_sqr8x_mont_capable(size_t num) { return num >= 8 && (num & 7) == 0; } -int bn_sqr8x_mont(BN_ULONG *rp, const BN_ULONG *ap, BN_ULONG mulx_adx_capable, - const BN_ULONG *np, const BN_ULONG *n0, size_t num); +extern "C" void bn_sqr8x_mont(BN_ULONG *rp, const BN_ULONG *ap, + BN_ULONG mulx_adx_capable, const BN_ULONG *np, + const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], + size_t num); #elif defined(OPENSSL_ARM) inline int bn_mul8x_mont_neon_capable(size_t num) { return (num & 7) == 0 && CRYPTO_is_NEON_capable(); } -int bn_mul8x_mont_neon(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, - const BN_ULONG *np, const BN_ULONG *n0, size_t num); -int bn_mul_mont_nohw(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, - const BN_ULONG *np, const BN_ULONG *n0, size_t num); +extern "C" void bn_mul8x_mont_neon(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *bp, const BN_ULONG *np, + const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], + size_t num); +extern "C" void bn_mul_mont_nohw(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *bp, const BN_ULONG *np, + const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], + size_t num); #endif #endif // OPENSSL_BN_ASM_MONT @@ -326,40 +411,46 @@ int bn_mul_mont_nohw(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, #if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) #define OPENSSL_BN_ASM_MONT5 -// The following functions implement |bn_mul_mont_gather5|. See -// |bn_mul_mont_gather5| for details. +// The following functions implement `bn_mul_mont_gather5`. See +// `bn_mul_mont_gather5` for details. inline int bn_mul4x_mont_gather5_capable(int num) { return (num & 7) == 0; } -void bn_mul4x_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap, - const BN_ULONG *table, const BN_ULONG *np, - const BN_ULONG *n0, int num, int power); +extern "C" void bn_mul4x_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *table, const BN_ULONG *np, + const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], + int num, int power); inline int bn_mulx4x_mont_gather5_capable(int num) { return bn_mul4x_mont_gather5_capable(num) && CRYPTO_is_ADX_capable() && CRYPTO_is_BMI1_capable() && CRYPTO_is_BMI2_capable(); } -void bn_mulx4x_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap, - const BN_ULONG *table, const BN_ULONG *np, - const BN_ULONG *n0, int num, int power); +extern "C" void bn_mulx4x_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *table, + const BN_ULONG *np, + const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], + int num, int power); -void bn_mul_mont_gather5_nohw(BN_ULONG *rp, const BN_ULONG *ap, - const BN_ULONG *table, const BN_ULONG *np, - const BN_ULONG *n0, int num, int power); +extern "C" void bn_mul_mont_gather5_nohw( + BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *table, const BN_ULONG *np, + const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], int num, int power); -// bn_scatter5 stores |inp| to index |power| of |table|. |inp| and each entry of -// |table| are |num| words long. |power| must be less than 32 and is treated as -// public. |table| must be 32*|num| words long. |table| must be aligned to at +// bn_scatter5 stores `inp` to index `power` of `table`. `inp` and each entry of +// `table` are `num` words long. `power` must be less than 32 and is treated as +// public. `table` must be 32*`num` words long. `table` must be aligned to at // least 16 bytes. -void bn_scatter5(const BN_ULONG *inp, size_t num, BN_ULONG *table, - size_t power); +extern "C" void bn_scatter5(const BN_ULONG *inp, size_t num, BN_ULONG *table, + size_t power); -// bn_gather5 loads index |power| of |table| and stores it in |out|. |out| and -// each entry of |table| are |num| words long. |power| must be less than 32 and -// is treated as secret. |table| must be aligned to at least 16 bytes. -void bn_gather5(BN_ULONG *out, size_t num, const BN_ULONG *table, size_t power); +// bn_gather5 loads index `power` of `table` and stores it in `out`. `out` and +// each entry of `table` are `num` words long. `power` must be less than 32 and +// is treated as secret. `table` must be aligned to at least 16 bytes. +extern "C" void bn_gather5(BN_ULONG *out, size_t num, const BN_ULONG *table, + size_t power); -// The following functions implement |bn_power5|. See |bn_power5| for details. -void bn_power5_nohw(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *table, - const BN_ULONG *np, const BN_ULONG *n0, int num, int power); +// The following functions implement `bn_power5`. See `bn_power5` for details. +extern "C" void bn_power5_nohw(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *table, const BN_ULONG *np, + const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], int num, + int power); inline int bn_power5_capable(int num) { return (num & 7) == 0; } @@ -367,17 +458,19 @@ inline int bn_powerx5_capable(int num) { return bn_power5_capable(num) && CRYPTO_is_ADX_capable() && CRYPTO_is_BMI1_capable() && CRYPTO_is_BMI2_capable(); } -void bn_powerx5(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *table, - const BN_ULONG *np, const BN_ULONG *n0, int num, int power); +extern "C" void bn_powerx5(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *table, const BN_ULONG *np, + const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], int num, + int power); #endif // !OPENSSL_NO_ASM && OPENSSL_X86_64 uint64_t bn_mont_n0(const BIGNUM *n); -// bn_mont_ctx_set_RR_consttime initializes |mont->RR|. It returns one on -// success and zero on error. |mont->N| and |mont->n0| must have been -// initialized already. The bit width of |mont->N| is assumed public, but -// |mont->N| is otherwise treated as secret. +// bn_mont_ctx_set_RR_consttime initializes `mont->RR`. It returns one on +// success and zero on error. `mont->N` and `mont->n0` must have been +// initialized already. The bit width of `mont->N` is assumed public, but +// `mont->N` is otherwise treated as secret. int bn_mont_ctx_set_RR_consttime(BN_MONT_CTX *mont, BN_CTX *ctx); #if defined(_MSC_VER) @@ -398,35 +491,35 @@ int bn_mont_ctx_set_RR_consttime(BN_MONT_CTX *mont, BN_CTX *ctx); #error "Either BN_ULLONG or BN_UMULT_LOHI must be defined on every platform." #endif -// bn_jacobi returns the Jacobi symbol of |a| and |b| (which is -1, 0 or 1), or +// bn_jacobi returns the Jacobi symbol of `a` and `b` (which is -1, 0 or 1), or // -2 on error. int bn_jacobi(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); -// bn_is_bit_set_words returns one if bit |bit| is set in |a| and zero +// bn_is_bit_set_words returns one if bit `bit` is set in `a` and zero // otherwise. int bn_is_bit_set_words(const BN_ULONG *a, size_t num, size_t bit); -// bn_one_to_montgomery sets |r| to one in Montgomery form. It returns one on +// bn_one_to_montgomery sets `r` to one in Montgomery form. It returns one on // success and zero on error. This function treats the bit width of the modulus // as public. int bn_one_to_montgomery(BIGNUM *r, const BN_MONT_CTX *mont, BN_CTX *ctx); -// bn_less_than_montgomery_R returns one if |bn| is less than the Montgomery R -// value for |mont| and zero otherwise. +// bn_less_than_montgomery_R returns one if `bn` is less than the Montgomery R +// value for `mont` and zero otherwise. int bn_less_than_montgomery_R(const BIGNUM *bn, const BN_MONT_CTX *mont); -// bn_mod_u16_consttime returns |bn| mod |d|, ignoring |bn|'s sign bit. It runs -// in time independent of the value of |bn|, but it treats |d| as public. +// bn_mod_u16_consttime returns `bn` mod `d`, ignoring `bn`'s sign bit. It runs +// in time independent of the value of `bn`, but it treats `d` as public. OPENSSL_EXPORT uint16_t bn_mod_u16_consttime(const BIGNUM *bn, uint16_t d); -// bn_odd_number_is_obviously_composite returns one if |bn| is divisible by one +// bn_odd_number_is_obviously_composite returns one if `bn` is divisible by one // of the first several odd primes and zero otherwise. int bn_odd_number_is_obviously_composite(const BIGNUM *bn); // A BN_MILLER_RABIN stores state common to each Miller-Rabin iteration. It is -// initialized within an existing |BN_CTX| scope and may not be used after -// that scope is released with |BN_CTX_end|. Field names match those in FIPS -// 186-4, section C.3.1. +// initialized within an existing `BN_CTX` scope and may not be used after +// that scope is released with `BN_CTX_end`. Field names match those in FIPS +// 186-5, section B.3.1. typedef struct { // w1 is w-1. BIGNUM *w1; @@ -442,46 +535,46 @@ typedef struct { int a; } BN_MILLER_RABIN; -// bn_miller_rabin_init initializes |miller_rabin| for testing if |mont->N| is +// bn_miller_rabin_init initializes `miller_rabin` for testing if `mont->N` is // prime. It returns one on success and zero on error. OPENSSL_EXPORT int bn_miller_rabin_init(BN_MILLER_RABIN *miller_rabin, const BN_MONT_CTX *mont, BN_CTX *ctx); // bn_miller_rabin_iteration performs one Miller-Rabin iteration, checking if -// |b| is a composite witness for |mont->N|. |miller_rabin| must have been -// initialized with |bn_miller_rabin_setup|. On success, it returns one and sets -// |*out_is_possibly_prime| to one if |mont->N| may still be prime or zero if -// |b| shows it is composite. On allocation or internal failure, it returns +// `b` is a composite witness for `mont->N`. `miller_rabin` must have been +// initialized with `bn_miller_rabin_setup`. On success, it returns one and sets +// `*out_is_possibly_prime` to one if `mont->N` may still be prime or zero if +// `b` shows it is composite. On allocation or internal failure, it returns // zero. OPENSSL_EXPORT int bn_miller_rabin_iteration( const BN_MILLER_RABIN *miller_rabin, int *out_is_possibly_prime, const BIGNUM *b, const BN_MONT_CTX *mont, BN_CTX *ctx); -// bn_rshift1_words sets |r| to |a| >> 1, where both arrays are |num| bits wide. +// bn_rshift1_words sets `r` to `a` >> 1, where both arrays are `num` bits wide. void bn_rshift1_words(BN_ULONG *r, const BN_ULONG *a, size_t num); -// bn_rshift_words sets |r| to |a| >> |shift|, where both arrays are |num| bits +// bn_rshift_words sets `r` to `a` >> `shift`, where both arrays are `num` bits // wide. void bn_rshift_words(BN_ULONG *r, const BN_ULONG *a, unsigned shift, size_t num); -// bn_rshift_secret_shift behaves like |BN_rshift| but runs in time independent -// of both |a| and |n|. +// bn_rshift_secret_shift behaves like `BN_rshift` but runs in time independent +// of both `a` and `n`. OPENSSL_EXPORT int bn_rshift_secret_shift(BIGNUM *r, const BIGNUM *a, unsigned n, BN_CTX *ctx); -// bn_reduce_once sets |r| to |a| mod |m| where 0 <= |a| < 2*|m|. It returns -// zero if |a| < |m| and a mask of all ones if |a| >= |m|. Each array is |num| -// words long, but |a| has an additional word specified by |carry|. |carry| must -// be zero or one, as implied by the bounds on |a|. +// bn_reduce_once sets `r` to `a` mod `m` where 0 <= `a` < 2*`m`. It returns +// zero if `a` < `m` and a mask of all ones if `a` >= `m`. Each array is `num` +// words long, but `a` has an additional word specified by `carry`. `carry` must +// be zero or one, as implied by the bounds on `a`. // -// |r|, |a|, and |m| may not alias. Use |bn_reduce_once_in_place| if |r| and |a| +// `r`, `a`, and `m` may not alias. Use `bn_reduce_once_in_place` if `r` and `a` // must alias. BN_ULONG bn_reduce_once(BN_ULONG *r, const BN_ULONG *a, BN_ULONG carry, const BN_ULONG *m, size_t num); -// bn_reduce_once_in_place behaves like |bn_reduce_once| but acts in-place on -// |r|, using |tmp| as scratch space. |r|, |tmp|, and |m| may not alias. +// bn_reduce_once_in_place behaves like `bn_reduce_once` but acts in-place on +// `r`, using `tmp` as scratch space. `r`, `tmp`, and `m` may not alias. BN_ULONG bn_reduce_once_in_place(BN_ULONG *r, BN_ULONG carry, const BN_ULONG *m, BN_ULONG *tmp, size_t num); @@ -489,64 +582,64 @@ BN_ULONG bn_reduce_once_in_place(BN_ULONG *r, BN_ULONG carry, const BN_ULONG *m, // Constant-time non-modular arithmetic. // // The following functions implement non-modular arithmetic in constant-time -// and pessimally set |r->width| to the largest possible word size. +// and pessimally set `r->width` to the largest possible word size. // // Note this means that, e.g., repeatedly multiplying by one will cause widths // to increase without bound. The corresponding public API functions minimize // their outputs to avoid regressing calculator consumers. -// bn_uadd_consttime behaves like |BN_uadd|, but it pessimally sets -// |r->width| = |a->width| + |b->width| + 1. +// bn_uadd_consttime behaves like `BN_uadd`, but it pessimally sets +// `r->width` = `a->width` + `b->width` + 1. int bn_uadd_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b); -// bn_usub_consttime behaves like |BN_usub|, but it pessimally sets -// |r->width| = |a->width|. +// bn_usub_consttime behaves like `BN_usub`, but it pessimally sets +// `r->width` = `a->width`. int bn_usub_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b); -// bn_abs_sub_consttime sets |r| to the absolute value of |a| - |b|, treating +// bn_abs_sub_consttime sets `r` to the absolute value of `a` - `b`, treating // both inputs as secret. It returns one on success and zero on error. OPENSSL_EXPORT int bn_abs_sub_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); -// bn_mul_consttime behaves like |BN_mul|, but it rejects negative inputs and -// pessimally sets |r->width| to |a->width| + |b->width|, to avoid leaking -// information about |a| and |b|. +// bn_mul_consttime behaves like `BN_mul`, but it rejects negative inputs and +// pessimally sets `r->width` to `a->width` + `b->width`, to avoid leaking +// information about `a` and `b`. int bn_mul_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); -// bn_sqrt_consttime behaves like |BN_sqrt|, but it pessimally sets |r->width| -// to 2*|a->width|, to avoid leaking information about |a| and |b|. +// bn_sqrt_consttime behaves like `BN_sqrt`, but it pessimally sets `r->width` +// to 2*`a->width`, to avoid leaking information about `a` and `b`. int bn_sqr_consttime(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx); -// bn_div_consttime behaves like |BN_div|, but it rejects negative inputs and +// bn_div_consttime behaves like `BN_div`, but it rejects negative inputs and // treats both inputs, including their magnitudes, as secret. It is, as a -// result, much slower than |BN_div| and should only be used for rare operations -// where Montgomery reduction is not available. |divisor_min_bits| is a -// public lower bound for |BN_num_bits(divisor)|. When |divisor|'s bit width is +// result, much slower than `BN_div` and should only be used for rare operations +// where Montgomery reduction is not available. `divisor_min_bits` is a +// public lower bound for `BN_num_bits(divisor)`. When `divisor`'s bit width is // public, this can speed up the operation. // -// Note that |quotient->width| will be set pessimally to |numerator->width|. +// Note that `quotient->width` will be set pessimally to `numerator->width`. OPENSSL_EXPORT int bn_div_consttime(BIGNUM *quotient, BIGNUM *remainder, const BIGNUM *numerator, const BIGNUM *divisor, unsigned divisor_min_bits, BN_CTX *ctx); -// bn_is_relatively_prime checks whether GCD(|x|, |y|) is one. On success, it -// returns one and sets |*out_relatively_prime| to one if the GCD was one and +// bn_is_relatively_prime checks whether GCD(`x`, `y`) is one. On success, it +// returns one and sets `*out_relatively_prime` to one if the GCD was one and // zero otherwise. On error, it returns zero. OPENSSL_EXPORT int bn_is_relatively_prime(int *out_relatively_prime, const BIGNUM *x, const BIGNUM *y, BN_CTX *ctx); -// bn_lcm_consttime sets |r| to LCM(|a|, |b|). It returns one and success and -// zero on error. |a| and |b| are both treated as secret. +// bn_lcm_consttime sets `r` to LCM(`a`, `b`). It returns one and success and +// zero on error. `a` and `b` are both treated as secret. OPENSSL_EXPORT int bn_lcm_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); -// bn_mont_ctx_init zero-initialies |mont|. +// bn_mont_ctx_init zero-initialies `mont`. void bn_mont_ctx_init(BN_MONT_CTX *mont); -// bn_mont_ctx_cleanup releases memory associated with |mont|, without freeing -// |mont| itself. +// bn_mont_ctx_cleanup releases memory associated with `mont`, without freeing +// `mont` itself. void bn_mont_ctx_cleanup(BN_MONT_CTX *mont); @@ -554,66 +647,66 @@ void bn_mont_ctx_cleanup(BN_MONT_CTX *mont); // // The following functions implement basic constant-time modular arithmetic. -// bn_mod_add_words sets |r| to |a| + |b| (mod |m|), using |tmp| as scratch -// space. Each array is |num| words long. |a| and |b| must be < |m|. Any pair of -// |r|, |a|, and |b| may alias. +// bn_mod_add_words sets `r` to `a` + `b` (mod `m`), using `tmp` as scratch +// space. Each array is `num` words long. `a` and `b` must be < `m`. Any pair of +// `r`, `a`, and `b` may alias. void bn_mod_add_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, BN_ULONG *tmp, size_t num); -// bn_mod_add_consttime acts like |BN_mod_add_quick| but takes a |BN_CTX|. +// bn_mod_add_consttime acts like `BN_mod_add_quick` but takes a `BN_CTX`. int bn_mod_add_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, BN_CTX *ctx); -// bn_mod_sub_words sets |r| to |a| - |b| (mod |m|), using |tmp| as scratch -// space. Each array is |num| words long. |a| and |b| must be < |m|. Any pair of -// |r|, |a|, and |b| may alias. +// bn_mod_sub_words sets `r` to `a` - `b` (mod `m`), using `tmp` as scratch +// space. Each array is `num` words long. `a` and `b` must be < `m`. Any pair of +// `r`, `a`, and `b` may alias. void bn_mod_sub_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, BN_ULONG *tmp, size_t num); -// bn_mod_sub_consttime acts like |BN_mod_sub_quick| but takes a |BN_CTX|. +// bn_mod_sub_consttime acts like `BN_mod_sub_quick` but takes a `BN_CTX`. int bn_mod_sub_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, BN_CTX *ctx); -// bn_mod_lshift1_consttime acts like |BN_mod_lshift1_quick| but takes a -// |BN_CTX|. +// bn_mod_lshift1_consttime acts like `BN_mod_lshift1_quick` but takes a +// `BN_CTX`. int bn_mod_lshift1_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx); -// bn_mod_lshift_consttime acts like |BN_mod_lshift_quick| but takes a |BN_CTX|. +// bn_mod_lshift_consttime acts like `BN_mod_lshift_quick` but takes a `BN_CTX`. int bn_mod_lshift_consttime(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m, BN_CTX *ctx); -// bn_mod_inverse_consttime sets |r| to |a|^-1, mod |n|. |a| must be non- -// negative and less than |n|. It returns one on success and zero on error. On -// failure, if the failure was caused by |a| having no inverse mod |n| then -// |*out_no_inverse| will be set to one; otherwise it will be set to zero. +// bn_mod_inverse_consttime sets `r` to `a`^-1, mod `n`. `a` must be non- +// negative and less than `n`. It returns one on success and zero on error. On +// failure, if the failure was caused by `a` having no inverse mod `n` then +// `*out_no_inverse` will be set to one; otherwise it will be set to zero. // -// This function treats both |a| and |n| as secret, provided they are both non- +// This function treats both `a` and `n` as secret, provided they are both non- // zero and the inverse exists. It should only be used for even moduli where // none of the less general implementations are applicable. OPENSSL_EXPORT int bn_mod_inverse_consttime(BIGNUM *r, int *out_no_inverse, const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx); -// bn_mod_inverse_prime sets |out| to the modular inverse of |a| modulo |p|, +// bn_mod_inverse_prime sets `out` to the modular inverse of `a` modulo `p`, // computed with Fermat's Little Theorem. It returns one on success and zero on -// error. If |mont_p| is NULL, one will be computed temporarily. +// error. If `mont_p` is NULL, one will be computed temporarily. int bn_mod_inverse_prime(BIGNUM *out, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx, const BN_MONT_CTX *mont_p); -// bn_mod_inverse_secret_prime behaves like |bn_mod_inverse_prime| but uses -// |BN_mod_exp_mont_consttime| instead of |BN_mod_exp_mont| in hopes of +// bn_mod_inverse_secret_prime behaves like `bn_mod_inverse_prime` but uses +// `BN_mod_exp_mont_consttime` instead of `BN_mod_exp_mont` in hopes of // protecting the exponent. int bn_mod_inverse_secret_prime(BIGNUM *out, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx, const BN_MONT_CTX *mont_p); -// BN_MONT_CTX_set_locked takes |lock| and checks whether |*pmont| is NULL. If -// so, it creates a new |BN_MONT_CTX| and sets the modulus for it to |mod|. It -// then stores it as |*pmont|. It returns one on success and zero on error. Note -// this function assumes |mod| is public. +// BN_MONT_CTX_set_locked takes `lock` and checks whether `*pmont` is NULL. If +// so, it creates a new `BN_MONT_CTX` and sets the modulus for it to `mod`. It +// then stores it as `*pmont`. It returns one on success and zero on error. Note +// this function assumes `mod` is public. // -// If |*pmont| is already non-NULL then it does nothing and returns one. -int BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, CRYPTO_MUTEX *lock, +// If `*pmont` is already non-NULL then it does nothing and returns one. +int BN_MONT_CTX_set_locked(UniquePtr *pmont, Mutex *lock, const BIGNUM *mod, BN_CTX *bn_ctx); @@ -633,87 +726,85 @@ int BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, CRYPTO_MUTEX *lock, #define BN_SMALL_MAX_WORDS 9 #endif -// bn_mul_small sets |r| to |a|*|b|. |num_r| must be |num_a| + |num_b|. |r| may -// not alias with |a| or |b|. +// bn_mul_small sets `r` to `a`*`b`. `num_r` must be `num_a` + `num_b`. `r` may +// not alias with `a` or `b`. void bn_mul_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, size_t num_a, const BN_ULONG *b, size_t num_b); -// bn_sqr_small sets |r| to |a|^2. |num_a| must be at most |BN_SMALL_MAX_WORDS|. -// |num_r| must be |num_a|*2. |r| and |a| may not alias. +// bn_sqr_small sets `r` to `a`². `num_r` must be `num_a`*2. `r` and `a` may +// not alias. void bn_sqr_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, size_t num_a); -// In the following functions, the modulus must be at most |BN_SMALL_MAX_WORDS| +// In the following functions, the modulus must be at most `BN_SMALL_MAX_WORDS` // words long. -// bn_to_montgomery_small sets |r| to |a| translated to the Montgomery domain. -// |r| and |a| are |num| words long, which must be |mont->N.width|. |a| must be -// fully reduced and may alias |r|. +// bn_to_montgomery_small sets `r` to `a` translated to the Montgomery domain. +// `r` and `a` are `num` words long, which must be `mont->N.width`. `a` must be +// fully reduced and may alias `r`. void bn_to_montgomery_small(BN_ULONG *r, const BN_ULONG *a, size_t num, const BN_MONT_CTX *mont); -// bn_from_montgomery_small sets |r| to |a| translated out of the Montgomery -// domain. |r| and |a| are |num_r| and |num_a| words long, respectively. |num_r| -// must be |mont->N.width|. |a| must be at most |mont->N|^2 and may alias |r|. +// bn_from_montgomery_small sets `r` to `a` translated out of the Montgomery +// domain. `r` and `a` are `num_r` and `num_a` words long, respectively. `num_r` +// must be `mont->N.width`. `a` must be at most `mont->N`² and may alias `r`. // -// Unlike most of these functions, only |num_r| is bounded by -// |BN_SMALL_MAX_WORDS|. |num_a| may exceed it, but must be at most 2 * |num_r|. +// Unlike most of these functions, only `num_r` is bounded by +// `BN_SMALL_MAX_WORDS`. `num_a` may exceed it, but must be at most 2 * `num_r`. void bn_from_montgomery_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, size_t num_a, const BN_MONT_CTX *mont); -// bn_mod_mul_montgomery_small sets |r| to |a| * |b| mod |mont->N|. Both inputs -// and outputs are in the Montgomery domain. Each array is |num| words long, -// which must be |mont->N.width|. Any two of |r|, |a|, and |b| may alias. |a| -// and |b| must be reduced on input. +// bn_mod_mul_montgomery_small sets `r` to `a` * `b` mod `mont->N`. Both inputs +// and outputs are in the Montgomery domain. Each array is `num` words long, +// which must be `mont->N.width`. Any two of `r`, `a`, and `b` may alias. `a` +// and `b` must be reduced on input. void bn_mod_mul_montgomery_small(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, size_t num, const BN_MONT_CTX *mont); -// bn_mod_exp_mont_small sets |r| to |a|^|p| mod |mont->N|. It returns one on +// bn_mod_exp_mont_small sets `r` to `a`^`p` mod `mont->N`. It returns one on // success and zero on programmer or internal error. Both inputs and outputs are -// in the Montgomery domain. |r| and |a| are |num| words long, which must be -// |mont->N.width| and at most |BN_SMALL_MAX_WORDS|. |num_p|, measured in bits, -// must fit in |size_t|. |a| must be fully-reduced. This function runs in time -// independent of |a|, but |p| and |mont->N| are public values. |a| must be -// fully-reduced and may alias with |r|. +// in the Montgomery domain. `r` and `a` are `num` words long, which must be +// `mont->N.width` and at most `BN_SMALL_MAX_WORDS`. `num_p`, measured in bits, +// must fit in `size_t`. `a` must be fully-reduced. This function runs in time +// independent of `a`, but `p` and `mont->N` are public values. `a` must be +// fully-reduced and may alias with `r`. // -// Note this function differs from |BN_mod_exp_mont| which uses Montgomery +// Note this function differs from `BN_mod_exp_mont` which uses Montgomery // reduction but takes input and output outside the Montgomery domain. Combine -// this function with |bn_from_montgomery_small| and |bn_to_montgomery_small| +// this function with `bn_from_montgomery_small` and `bn_to_montgomery_small` // if necessary. void bn_mod_exp_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num, const BN_ULONG *p, size_t num_p, const BN_MONT_CTX *mont); -// bn_mod_inverse0_prime_mont_small sets |r| to |a|^-1 mod |mont->N|. If |a| is -// zero, |r| is set to zero. |mont->N| must be a prime. |r| and |a| are |num| -// words long, which must be |mont->N.width| and at most |BN_SMALL_MAX_WORDS|. -// |a| must be fully-reduced and may alias |r|. This function runs in time -// independent of |a|, but |mont->N| is a public value. +// bn_mod_inverse0_prime_mont_small sets `r` to `a`^-1 mod `mont->N`. If `a` is +// zero, `r` is set to zero. `mont->N` must be a prime. `r` and `a` are `num` +// words long, which must be `mont->N.width` and at most `BN_SMALL_MAX_WORDS`. +// `a` must be fully-reduced and may alias `r`. This function runs in time +// independent of `a`, but `mont->N` is a public value. void bn_mod_inverse0_prime_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num, const BN_MONT_CTX *mont); // Word-based byte conversion functions. -// bn_big_endian_to_words interprets |in_len| bytes from |in| as a big-endian, -// unsigned integer and writes the result to |out_len| words in |out|. |out_len| -// must be large enough to represent any |in_len|-byte value. That is, |in_len| -// must be at most |BN_BYTES * out_len|. +// bn_big_endian_to_words interprets `in_len` bytes from `in` as a big-endian, +// unsigned integer and writes the result to `out_len` words in `out`. `out_len` +// must be large enough to represent any `in_len`-byte value. That is, `in_len` +// must be at most `BN_BYTES * out_len`. void bn_big_endian_to_words(BN_ULONG *out, size_t out_len, const uint8_t *in, size_t in_len); -// bn_words_to_big_endian represents |in_len| words from |in| as a big-endian, -// unsigned integer in |out_len| bytes. It writes the result to |out|. |out_len| -// must be large enough to represent |in| without truncation. +// bn_words_to_big_endian represents `in_len` words from `in` as a big-endian, +// unsigned integer in `out_len` bytes. It writes the result to `out`. `out_len` +// must be large enough to represent `in` without truncation. // -// Note |out_len| may be less than |BN_BYTES * in_len| if |in| is known to have +// Note `out_len` may be less than `BN_BYTES * in_len` if `in` is known to have // leading zeros. void bn_words_to_big_endian(uint8_t *out, size_t out_len, const BN_ULONG *in, size_t in_len); +BSSL_NAMESPACE_END -#if defined(__cplusplus) -} // extern C -#endif -#endif // OPENSSL_HEADER_BN_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_BN_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/jacobi.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/jacobi.cc.inc index f7d7c840..b088f70b 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/jacobi.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/jacobi.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,10 +19,12 @@ #include "internal.h" -// least significant word -#define BN_lsw(n) (((n)->width == 0) ? (BN_ULONG) 0 : (n)->d[0]) +using namespace bssl; -int bn_jacobi(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { +// least significant word +#define BN_lsw(n) (((n)->width == 0) ? (BN_ULONG)0 : (n)->d[0]) + +int bssl::bn_jacobi(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { // In 'tab', only odd-indexed entries are relevant: // For any odd BIGNUM n, // tab[BN_lsw(n) & 7] @@ -37,32 +44,29 @@ int bn_jacobi(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { return -2; } - int ret = -2; - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *A = BN_CTX_get(ctx); BIGNUM *B = BN_CTX_get(ctx); - if (B == NULL) { - goto end; + if (B == nullptr) { + return -2; } if (!BN_copy(A, a) || !BN_copy(B, b)) { - goto end; + return -2; } // Adapted from logic to compute the Kronecker symbol, originally implemented // according to Henri Cohen, "A Course in Computational Algebraic Number // Theory" (algorithm 1.4.10). - ret = 1; - + int ret = 1; while (1) { // Cohen's step 3: // B is positive and odd if (BN_is_zero(A)) { - ret = BN_is_one(B) ? ret : 0; - goto end; + return BN_is_one(B) ? ret : 0; } // now A is non-zero @@ -71,12 +75,11 @@ int bn_jacobi(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { i++; } if (!BN_rshift(A, A, i)) { - ret = -2; - goto end; + return -2; } if (i & 1) { // i is odd - // multiply 'ret' by $(-1)^{(B^2-1)/8}$ + // multiply 'ret' by $(-1)^{(B²-1)/8}$ ret = ret * tab[BN_lsw(B) & 7]; } @@ -88,16 +91,11 @@ int bn_jacobi(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { // (A, B) := (B mod |A|, |A|) if (!BN_nnmod(B, B, A, ctx)) { - ret = -2; - goto end; + return -2; } BIGNUM *tmp = A; A = B; B = tmp; tmp->neg = 0; } - -end: - BN_CTX_end(ctx); - return ret; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/montgomery.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/montgomery.cc.inc index 3247c27a..bfda8365 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/montgomery.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/montgomery.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,28 +21,29 @@ #include #include -#include #include "../../internal.h" +#include "../../mem_internal.h" #include "internal.h" -void bn_mont_ctx_init(BN_MONT_CTX *mont) { +using namespace bssl; + +void bssl::bn_mont_ctx_init(BN_MONT_CTX *mont) { OPENSSL_memset(mont, 0, sizeof(BN_MONT_CTX)); BN_init(&mont->RR); BN_init(&mont->N); } -void bn_mont_ctx_cleanup(BN_MONT_CTX *mont) { +void bssl::bn_mont_ctx_cleanup(BN_MONT_CTX *mont) { BN_free(&mont->RR); BN_free(&mont->N); } -BN_MONT_CTX *BN_MONT_CTX_new(void) { - BN_MONT_CTX *ret = - reinterpret_cast(OPENSSL_malloc(sizeof(BN_MONT_CTX))); - if (ret == NULL) { - return NULL; +BN_MONT_CTX *BN_MONT_CTX_new() { + BN_MONT_CTX *ret = New(); + if (ret == nullptr) { + return nullptr; } bn_mont_ctx_init(ret); @@ -49,7 +55,7 @@ void BN_MONT_CTX_free(BN_MONT_CTX *mont) { return; } bn_mont_ctx_cleanup(mont); - OPENSSL_free(mont); + Delete(mont); } BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, const BN_MONT_CTX *from) { @@ -58,10 +64,11 @@ BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, const BN_MONT_CTX *from) { } if (!BN_copy(&to->RR, &from->RR) || !BN_copy(&to->N, &from->N)) { - return NULL; + return nullptr; + } + for (size_t i = 0; i < BN_MONT_CTX_N0_LIMBS; i++) { + to->n0[i] = from->n0[i]; } - to->n0[0] = from->n0[0]; - to->n0[1] = from->n0[1]; return to; } @@ -88,7 +95,7 @@ static int bn_mont_ctx_set_N_and_n0(BN_MONT_CTX *mont, const BIGNUM *mod) { OPENSSL_PUT_ERROR(BN, ERR_R_INTERNAL_ERROR); return 0; } - // |mont->N| is always stored minimally. Computing RR efficiently leaks the + // `mont->N` is always stored minimally. Computing RR efficiently leaks the // size of the modulus. While the modulus may be private in RSA (one of the // primes), their sizes are public, so this is fine. bn_set_minimal_width(&mont->N); @@ -96,8 +103,8 @@ static int bn_mont_ctx_set_N_and_n0(BN_MONT_CTX *mont, const BIGNUM *mod) { // Find n0 such that n0 * N == -1 (mod r). // // Only certain BN_BITS2<=32 platforms actually make use of n0[1]. For the - // others, we could use a shorter R value and use faster |BN_ULONG|-based - // math instead of |uint64_t|-based math, which would be double-precision. + // others, we could use a shorter R value and use faster `BN_ULONG`-based + // math instead of `uint64_t`-based math, which would be double-precision. // However, currently only the assembler files know which is which. static_assert(BN_MONT_CTX_N0_LIMBS == 1 || BN_MONT_CTX_N0_LIMBS == 2, "BN_MONT_CTX_N0_LIMBS value is invalid"); @@ -107,8 +114,6 @@ static int bn_mont_ctx_set_N_and_n0(BN_MONT_CTX *mont, const BIGNUM *mod) { mont->n0[0] = (BN_ULONG)n0; #if BN_MONT_CTX_N0_LIMBS == 2 mont->n0[1] = (BN_ULONG)(n0 >> BN_BITS2); -#else - mont->n0[1] = 0; #endif return 1; } @@ -118,10 +123,10 @@ int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx) { return 0; } - BN_CTX *new_ctx = NULL; - if (ctx == NULL) { + BN_CTX *new_ctx = nullptr; + if (ctx == nullptr) { new_ctx = BN_CTX_new(); - if (new_ctx == NULL) { + if (new_ctx == nullptr) { return 0; } ctx = new_ctx; @@ -129,9 +134,9 @@ int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx) { // Save RR = R**2 (mod N). R is the smallest power of 2**BN_BITS2 such that R // > mod. Even though the assembly on some 32-bit platforms works with 64-bit - // values, using |BN_BITS2| here, rather than |BN_MONT_CTX_N0_LIMBS * - // BN_BITS2|, is correct because R**2 will still be a multiple of the latter - // as |BN_MONT_CTX_N0_LIMBS| is either one or two. + // values, using `BN_BITS2` here, rather than + // `BN_MONT_CTX_N0_LIMBS * BN_BITS2`, is correct because R**2 will still be a + // multiple of the latter as `BN_MONT_CTX_N0_LIMBS` is either one or two. unsigned lgBigR = mont->N.width * BN_BITS2; BN_zero(&mont->RR); int ok = BN_set_bit(&mont->RR, lgBigR * 2) && @@ -143,40 +148,38 @@ int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx) { BN_MONT_CTX *BN_MONT_CTX_new_for_modulus(const BIGNUM *mod, BN_CTX *ctx) { BN_MONT_CTX *mont = BN_MONT_CTX_new(); - if (mont == NULL || !BN_MONT_CTX_set(mont, mod, ctx)) { + if (mont == nullptr || !BN_MONT_CTX_set(mont, mod, ctx)) { BN_MONT_CTX_free(mont); - return NULL; + return nullptr; } return mont; } BN_MONT_CTX *BN_MONT_CTX_new_consttime(const BIGNUM *mod, BN_CTX *ctx) { BN_MONT_CTX *mont = BN_MONT_CTX_new(); - if (mont == NULL || !bn_mont_ctx_set_N_and_n0(mont, mod) || + if (mont == nullptr || !bn_mont_ctx_set_N_and_n0(mont, mod) || !bn_mont_ctx_set_RR_consttime(mont, ctx)) { BN_MONT_CTX_free(mont); - return NULL; + return nullptr; } return mont; } -int BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, CRYPTO_MUTEX *lock, - const BIGNUM *mod, BN_CTX *bn_ctx) { - CRYPTO_MUTEX_lock_read(lock); - BN_MONT_CTX *ctx = *pmont; - CRYPTO_MUTEX_unlock_read(lock); +int bssl::BN_MONT_CTX_set_locked(UniquePtr *pmont, Mutex *lock, + const BIGNUM *mod, BN_CTX *bn_ctx) { + lock->LockRead(); + BN_MONT_CTX *ctx = pmont->get(); + lock->UnlockRead(); if (ctx) { return 1; } - CRYPTO_MUTEX_lock_write(lock); - if (*pmont == NULL) { - *pmont = BN_MONT_CTX_new_for_modulus(mod, bn_ctx); + MutexWriteLock write_lock(lock); + if (*pmont == nullptr) { + pmont->reset(BN_MONT_CTX_new_for_modulus(mod, bn_ctx)); } - const int ok = *pmont != NULL; - CRYPTO_MUTEX_unlock_write(lock); - return ok; + return *pmont != nullptr; } int BN_to_montgomery(BIGNUM *ret, const BIGNUM *a, const BN_MONT_CTX *mont, @@ -193,24 +196,21 @@ static int bn_from_montgomery_in_place(BN_ULONG *r, size_t num_r, BN_ULONG *a, return 0; } - // Add multiples of |n| to |r| until R = 2^(nl * BN_BITS2) divides it. On - // input, we had |r| < |n| * R, so now |r| < 2 * |n| * R. Note that |r| - // includes |carry| which is stored separately. + // Add multiples of `n` to `r` until R = 2^(nl * BN_BITS2) divides it. On + // input, we had `r` < `n` * R, so now `r` < 2 * `n` * R. Note that `r` + // includes `carry` which is stored separately. BN_ULONG n0 = mont->n0[0]; BN_ULONG carry = 0; for (size_t i = 0; i < num_n; i++) { BN_ULONG v = bn_mul_add_words(a + i, n, num_n, a[i] * n0); - v += carry + a[i + num_n]; - carry |= (v != a[i + num_n]); - carry &= (v <= a[i + num_n]); - a[i + num_n] = v; + a[i + num_n] = CRYPTO_addc_w(a[i + num_n], v, carry, &carry); } - // Shift |num_n| words to divide by R. We have |a| < 2 * |n|. Note that |a| - // includes |carry| which is stored separately. + // Shift `num_n` words to divide by R. We have `a` < 2 * `n`. Note that `a` + // includes `carry` which is stored separately. a += num_n; - // |a| thus requires at most one additional subtraction |n| to be reduced. + // `a` thus requires at most one additional subtraction `n` to be reduced. bn_reduce_once(r, a, carry, n, num_n); return 1; } @@ -240,26 +240,19 @@ static int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r, int BN_from_montgomery(BIGNUM *r, const BIGNUM *a, const BN_MONT_CTX *mont, BN_CTX *ctx) { - int ret = 0; - BIGNUM *t; - - BN_CTX_start(ctx); - t = BN_CTX_get(ctx); - if (t == NULL || !BN_copy(t, a)) { - goto err; + BN_CTXScope scope(ctx); + BIGNUM *t = BN_CTX_get(ctx); + if (t == nullptr || !BN_copy(t, a)) { + return 0; } - ret = BN_from_montgomery_word(r, t, mont); - -err: - BN_CTX_end(ctx); - - return ret; + return BN_from_montgomery_word(r, t, mont); } -int bn_one_to_montgomery(BIGNUM *r, const BN_MONT_CTX *mont, BN_CTX *ctx) { - // If the high bit of |n| is set, R = 2^(width*BN_BITS2) < 2 * |n|, so we - // compute R - |n| rather than perform Montgomery reduction. +int bssl::bn_one_to_montgomery(BIGNUM *r, const BN_MONT_CTX *mont, + BN_CTX *ctx) { + // If the high bit of `n` is set, R = 2^(width*BN_BITS2) < 2 * `n`, so we + // compute R - `n` rather than perform Montgomery reduction. const BIGNUM *n = &mont->N; if (n->width > 0 && (n->d[n->width - 1] >> (BN_BITS2 - 1)) != 0) { if (!bn_wexpand(r, n->width)) { @@ -281,34 +274,28 @@ static int bn_mod_mul_montgomery_fallback(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BN_MONT_CTX *mont, BN_CTX *ctx) { - int ret = 0; - - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *tmp = BN_CTX_get(ctx); - if (tmp == NULL) { - goto err; + if (tmp == nullptr) { + return 0; } if (a == b) { if (!bn_sqr_consttime(tmp, a, ctx)) { - goto err; + return 0; } } else { if (!bn_mul_consttime(tmp, a, b, ctx)) { - goto err; + return 0; } } // reduce from aRR to aR if (!BN_from_montgomery_word(r, tmp, mont)) { - goto err; + return 0; } - ret = 1; - -err: - BN_CTX_end(ctx); - return ret; + return 1; } int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, @@ -319,21 +306,16 @@ int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, } #if defined(OPENSSL_BN_ASM_MONT) - // |bn_mul_mont| requires at least 128 bits of limbs, at least for x86. + // `bn_mul_mont_words` requires at least 128 bits of limbs. int num = mont->N.width; if (num >= (128 / BN_BITS2) && a->width == num && b->width == num) { if (!bn_wexpand(r, num)) { return 0; } - // This bound is implied by |bn_mont_ctx_set_N_and_n0|. |bn_mul_mont| - // allocates |num| words on the stack, so |num| cannot be too large. + // This bound is implied by `bn_mont_ctx_set_N_and_n0`. `bn_mul_mont_words` + // allocates `num` words on the stack, so `num` cannot be too large. assert((size_t)num <= BN_MONTGOMERY_MAX_WORDS); - if (!bn_mul_mont(r->d, a->d, b->d, mont->N.d, mont->n0, num)) { - // The check above ensures this won't happen. - assert(0); - OPENSSL_PUT_ERROR(BN, ERR_R_INTERNAL_ERROR); - return 0; - } + bn_mul_mont_words(r->d, a->d, b->d, mont->N.d, mont->n0, num); r->neg = 0; r->width = num; return 1; @@ -343,17 +325,18 @@ int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, return bn_mod_mul_montgomery_fallback(r, a, b, mont, ctx); } -int bn_less_than_montgomery_R(const BIGNUM *bn, const BN_MONT_CTX *mont) { +int bssl::bn_less_than_montgomery_R(const BIGNUM *bn, const BN_MONT_CTX *mont) { return !BN_is_negative(bn) && bn_fits_in_words(bn, mont->N.width); } -void bn_to_montgomery_small(BN_ULONG *r, const BN_ULONG *a, size_t num, - const BN_MONT_CTX *mont) { +void bssl::bn_to_montgomery_small(BN_ULONG *r, const BN_ULONG *a, size_t num, + const BN_MONT_CTX *mont) { bn_mod_mul_montgomery_small(r, a, mont->RR.d, num, mont); } -void bn_from_montgomery_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, - size_t num_a, const BN_MONT_CTX *mont) { +void bssl::bn_from_montgomery_small(BN_ULONG *r, size_t num_r, + const BN_ULONG *a, size_t num_a, + const BN_MONT_CTX *mont) { if (num_r != (size_t)mont->N.width || num_r > BN_SMALL_MAX_WORDS || num_a > 2 * num_r) { abort(); @@ -366,19 +349,17 @@ void bn_from_montgomery_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, OPENSSL_cleanse(tmp, 2 * num_r * sizeof(BN_ULONG)); } -void bn_mod_mul_montgomery_small(BN_ULONG *r, const BN_ULONG *a, - const BN_ULONG *b, size_t num, - const BN_MONT_CTX *mont) { +void bssl::bn_mod_mul_montgomery_small(BN_ULONG *r, const BN_ULONG *a, + const BN_ULONG *b, size_t num, + const BN_MONT_CTX *mont) { if (num != (size_t)mont->N.width || num > BN_SMALL_MAX_WORDS) { abort(); } #if defined(OPENSSL_BN_ASM_MONT) - // |bn_mul_mont| requires at least 128 bits of limbs, at least for x86. + // `bn_mul_mont_words` requires at least 128 bits of limbs. if (num >= (128 / BN_BITS2)) { - if (!bn_mul_mont(r, a, b, mont->N.d, mont->n0, num)) { - abort(); // The check above ensures this won't happen. - } + bn_mul_mont_words(r, a, b, mont->N.d, mont->n0, num); return; } #endif @@ -399,27 +380,29 @@ void bn_mod_mul_montgomery_small(BN_ULONG *r, const BN_ULONG *a, } #if defined(OPENSSL_BN_ASM_MONT) && defined(OPENSSL_X86_64) -int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, - const BN_ULONG *np, const BN_ULONG *n0, size_t num) { +void bssl::bn_mul_mont_words(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *bp, const BN_ULONG *np, + const BN_ULONG *n0, size_t num) { if (ap == bp && bn_sqr8x_mont_capable(num)) { - return bn_sqr8x_mont(rp, ap, bn_mulx_adx_capable(), np, n0, num); + bn_sqr8x_mont(rp, ap, bn_mulx_adx_capable(), np, n0, num); + } else if (bn_mulx4x_mont_capable(num)) { + bn_mulx4x_mont(rp, ap, bp, np, n0, num); + } else if (bn_mul4x_mont_capable(num)) { + bn_mul4x_mont(rp, ap, bp, np, n0, num); + } else { + bn_mul_mont_nohw(rp, ap, bp, np, n0, num); } - if (bn_mulx4x_mont_capable(num)) { - return bn_mulx4x_mont(rp, ap, bp, np, n0, num); - } - if (bn_mul4x_mont_capable(num)) { - return bn_mul4x_mont(rp, ap, bp, np, n0, num); - } - return bn_mul_mont_nohw(rp, ap, bp, np, n0, num); } #endif #if defined(OPENSSL_BN_ASM_MONT) && defined(OPENSSL_ARM) -int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, - const BN_ULONG *np, const BN_ULONG *n0, size_t num) { +void bssl::bn_mul_mont_words(BN_ULONG *rp, const BN_ULONG *ap, + const BN_ULONG *bp, const BN_ULONG *np, + const BN_ULONG *n0, size_t num) { if (bn_mul8x_mont_neon_capable(num)) { - return bn_mul8x_mont_neon(rp, ap, bp, np, n0, num); + bn_mul8x_mont_neon(rp, ap, bp, np, n0, num); + } else { + bn_mul_mont_nohw(rp, ap, bp, np, n0, num); } - return bn_mul_mont_nohw(rp, ap, bp, np, n0, num); } #endif diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/montgomery_inv.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/montgomery_inv.cc.inc index 16423edc..ba81129b 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/montgomery_inv.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/montgomery_inv.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2016 Brian Smith. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2016 Brian Smith. +// +// 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 @@ -20,41 +20,40 @@ #include "../../internal.h" -static uint64_t bn_neg_inv_mod_r_u64(uint64_t n); +using namespace bssl; + +static uint64_t bn_neg_inv_mod_u64(uint64_t n); static_assert(BN_MONT_CTX_N0_LIMBS == 1 || BN_MONT_CTX_N0_LIMBS == 2, "BN_MONT_CTX_N0_LIMBS value is invalid"); static_assert(sizeof(BN_ULONG) * BN_MONT_CTX_N0_LIMBS == sizeof(uint64_t), "uint64_t is insufficient precision for n0"); -// LG_LITTLE_R is log_2(r). -#define LG_LITTLE_R (BN_MONT_CTX_N0_LIMBS * BN_BITS2) - -uint64_t bn_mont_n0(const BIGNUM *n) { - // These conditions are checked by the caller, |BN_MONT_CTX_set| or - // |BN_MONT_CTX_new_consttime|. +uint64_t bssl::bn_mont_n0(const BIGNUM *n) { + // These conditions are checked by the caller, `BN_MONT_CTX_set` or + // `BN_MONT_CTX_new_consttime`. assert(!BN_is_zero(n)); assert(!BN_is_negative(n)); assert(BN_is_odd(n)); - // r == 2**(BN_MONT_CTX_N0_LIMBS * BN_BITS2) and LG_LITTLE_R == lg(r). This - // ensures that we can do integer division by |r| by simply ignoring - // |BN_MONT_CTX_N0_LIMBS| limbs. Similarly, we can calculate values modulo - // |r| by just looking at the lowest |BN_MONT_CTX_N0_LIMBS| limbs. This is - // what makes Montgomery multiplication efficient. + // r == 2**(BN_MONT_CTX_N0_LIMBS * BN_BITS2) ensures that we can do integer + // division by `r` by simply ignoring `BN_MONT_CTX_N0_LIMBS` limbs. Similarly, + // we can calculate values modulo `r` by just looking at the lowest + // `BN_MONT_CTX_N0_LIMBS` limbs. This is what makes Montgomery multiplication + // efficient. // // As shown in Algorithm 1 of "Fast Prime Field Elliptic Curve Cryptography // with 256 Bit Primes" by Shay Gueron and Vlad Krasnov, in the loop of a - // multi-limb Montgomery multiplication of |a * b (mod n)|, given the - // unreduced product |t == a * b|, we repeatedly calculate: + // multi-limb Montgomery multiplication of `a * b (mod n)`, given the + // unreduced product `t == a * b`, we repeatedly calculate: // - // t1 := t % r |t1| is |t|'s lowest limb (see previous paragraph). + // t1 := t % r `t1` is `t`'s lowest limb (see previous paragraph). // t2 := t1*n0*n // t3 := t + t2 - // t := t3 / r copy all limbs of |t3| except the lowest to |t|. + // t := t3 / r copy all limbs of `t3` except the lowest to `t`. // // In the last step, it would only make sense to ignore the lowest limb of - // |t3| if it were zero. The middle steps ensure that this is the case: + // `t3` if it were zero. The middle steps ensure that this is the case: // // t3 == 0 (mod r) // t + t2 == 0 (mod r) @@ -65,10 +64,10 @@ uint64_t bn_mont_n0(const BIGNUM *n) { // n0 == -1/n (mod r) // // Thus, in each iteration of the loop, we multiply by the constant factor - // |n0|, the negative inverse of n (mod r). + // `n0`, the negative inverse of n (mod r). // n_mod_r = n % r. As explained above, this is done by taking the lowest - // |BN_MONT_CTX_N0_LIMBS| limbs of |n|. + // `BN_MONT_CTX_N0_LIMBS` limbs of `n`. uint64_t n_mod_r = n->d[0]; #if BN_MONT_CTX_N0_LIMBS == 2 if (n->width > 1) { @@ -76,90 +75,48 @@ uint64_t bn_mont_n0(const BIGNUM *n) { } #endif - return bn_neg_inv_mod_r_u64(n_mod_r); + // A 64-bit inverse is enough precision to invert by r. (r is also currently + // always 2^64.) + return bn_neg_inv_mod_u64(n_mod_r); } -// bn_neg_inv_r_mod_n_u64 calculates the -1/n mod r; i.e. it calculates |v| -// such that u*r - v*n == 1. |r| is the constant defined in |bn_mont_n0|. |n| -// must be odd. -// -// This is derived from |xbinGCD| in Henry S. Warren, Jr.'s "Montgomery -// Multiplication" (http://www.hackersdelight.org/MontgomeryMultiplication.pdf). -// It is very similar to the MODULAR-INVERSE function in Stephen R. Dussé's and -// Burton S. Kaliski Jr.'s "A Cryptographic Library for the Motorola DSP56000" -// (http://link.springer.com/chapter/10.1007%2F3-540-46877-3_21). -// -// This is inspired by Joppe W. Bos's "Constant Time Modular Inversion" -// (http://www.joppebos.com/files/CTInversion.pdf) so that the inversion is -// constant-time with respect to |n|. We assume uint64_t additions, -// subtractions, shifts, and bitwise operations are all constant time, which -// may be a large leap of faith on 32-bit targets. We avoid division and -// multiplication, which tend to be the most problematic in terms of timing -// leaks. -// -// Most GCD implementations return values such that |u*r + v*n == 1|, so the -// caller would have to negate the resultant |v| for the purpose of Montgomery -// multiplication. This implementation does the negation implicitly by doing -// the computations as a difference instead of a sum. -static uint64_t bn_neg_inv_mod_r_u64(uint64_t n) { +// bn_neg_inv_mod_u64 calculates -1/n mod 2^64. `n` must be odd. +static uint64_t bn_neg_inv_mod_u64(uint64_t n) { + // This is a modified version of the technique described in + // https://crypto.stackexchange.com/a/47496 and + // https://bearssl.org/bigint.html#montgomery-reduction-and-multiplication. We + // modify it to compute the negative inverse directly so that, on 32-bit, + // negation happens before we go to double-word precision, instead of at the + // end. + // + // If r = -n^-1 (mod m), then r * (r*n + 2) is -n^-1 (mod m²). This is + // because, for some k, r*n = k*m - 1. Then: + // + // r*n * (r*n + 2) = (k*m - 1) * (k*m + 1) = k²*m² - 1 = -1 (mod m²) + // + // We start with the negative inverse mod some small power of 2 and square the + // modulus up to 2^64. n = n^-1 (mod 8) for all odd n, so r = -n (mod 8). From + // there, four iterations are enough for 2^32 and five for 2^64. assert(n % 2 == 1); - - // alpha == 2**(lg r - 1) == r / 2. - static const uint64_t alpha = UINT64_C(1) << (LG_LITTLE_R - 1); - - const uint64_t beta = n; - - uint64_t u = 1; - uint64_t v = 0; - - // The invariant maintained from here on is: - // 2**(lg r - i) == u*2*alpha - v*beta. - for (size_t i = 0; i < LG_LITTLE_R; ++i) { -#if BN_BITS2 == 64 && defined(BN_ULLONG) - assert((BN_ULLONG)(1) << (LG_LITTLE_R - i) == - ((BN_ULLONG)u * 2 * alpha) - ((BN_ULLONG)v * beta)); -#endif - - // Delete a common factor of 2 in u and v if |u| is even. Otherwise, set - // |u = (u + beta) / 2| and |v = (v / 2) + alpha|. - - uint64_t u_is_odd = UINT64_C(0) - (u & 1); // Either 0xff..ff or 0. - - // The addition can overflow, so use Dietz's method for it. - // - // Dietz calculates (x+y)/2 by (x⊕y)>>1 + x&y. This is valid for all - // (unsigned) x and y, even when x+y overflows. Evidence for 32-bit values - // (embedded in 64 bits to so that overflow can be ignored): - // - // (declare-fun x () (_ BitVec 64)) - // (declare-fun y () (_ BitVec 64)) - // (assert (let ( - // (one (_ bv1 64)) - // (thirtyTwo (_ bv32 64))) - // (and - // (bvult x (bvshl one thirtyTwo)) - // (bvult y (bvshl one thirtyTwo)) - // (not (= - // (bvadd (bvlshr (bvxor x y) one) (bvand x y)) - // (bvlshr (bvadd x y) one))) - // ))) - // (check-sat) - uint64_t beta_if_u_is_odd = beta & u_is_odd; // Either |beta| or 0. - u = ((u ^ beta_if_u_is_odd) >> 1) + (u & beta_if_u_is_odd); - - uint64_t alpha_if_u_is_odd = alpha & u_is_odd; // Either |alpha| or 0. - v = (v >> 1) + alpha_if_u_is_odd; +#if defined(OPENSSL_32_BIT) + // Compute the result mod 2^32 first. + uint32_t n32 = static_cast(n); + uint32_t r = 0u - n32; + for (int i = 0; i < 4; i++) { + r *= r * n32 + 2; } - - // The invariant now shows that u*r - v*n == 1 since r == 2 * alpha. -#if BN_BITS2 == 64 && defined(BN_ULLONG) - declassify_assert(1 == ((BN_ULLONG)u * 2 * alpha) - ((BN_ULLONG)v * beta)); + // Run one more double-word iteration to get the result mod 2^64. + return r * (r * n + 2); +#else + uint64_t r = 0u - n; + for (int i = 0; i < 5; i++) { + r *= r * n + 2; + } + return r; #endif - - return v; } -int bn_mont_ctx_set_RR_consttime(BN_MONT_CTX *mont, BN_CTX *ctx) { +int bssl::bn_mont_ctx_set_RR_consttime(BN_MONT_CTX *mont, BN_CTX *ctx) { assert(!BN_is_zero(&mont->N)); assert(!BN_is_negative(&mont->N)); assert(BN_is_odd(&mont->N)); @@ -179,8 +136,8 @@ int bn_mont_ctx_set_RR_consttime(BN_MONT_CTX *mont, BN_CTX *ctx) { // Montgomery domain, 2R or 2^(lgBigR+1), and then use Montgomery // square-and-multiply to exponentiate. // - // The square steps take 2^n R to (2^n)*(2^n) R = 2^2n R. This is the same as - // doubling 2^n R, n times (doubling any x, n times, computes 2^n * x). When n + // The square steps take 2ⁿ R to (2ⁿ)*(2ⁿ) R = 2^2n R. This is the same as + // doubling 2ⁿ R, n times (doubling any x, n times, computes 2ⁿ * x). When n // is below some threshold, doubling is faster; when above, squaring is // faster. From benchmarking various 32-bit and 64-bit architectures, the word // count seems to work well as a threshold. (Doubling scales linearly and diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/mul.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/mul.cc.inc index 2b9bf955..92f1b199 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/mul.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/mul.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -20,16 +25,7 @@ #include "internal.h" -#define BN_MUL_RECURSIVE_SIZE_NORMAL 16 -#define BN_SQR_RECURSIVE_SIZE_NORMAL BN_MUL_RECURSIVE_SIZE_NORMAL - - -static void bn_abs_sub_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, - size_t num, BN_ULONG *tmp) { - BN_ULONG borrow = bn_sub_words(tmp, a, b, num); - bn_sub_words(r, b, a, num); - bn_select_words(r, 0 - borrow, r /* tmp < 0 */, tmp /* tmp >= 0 */, num); -} +using namespace bssl; static void bn_mul_normal(BN_ULONG *r, const BN_ULONG *a, size_t na, const BN_ULONG *b, size_t nb) { @@ -72,12 +68,12 @@ static void bn_mul_normal(BN_ULONG *r, const BN_ULONG *a, size_t na, } // bn_sub_part_words sets |r| to |a| - |b|. It returns the borrow bit, which is -// one if the operation underflowed and zero otherwise. |cl| is the common -// length, that is, the shorter of len(a) or len(b). |dl| is the delta length, +// one if the operation underflowed and zero otherwise. `cl` is the common +// length, that is, the shorter of len(a) or len(b). `dl` is the delta length, // that is, len(a) - len(b). |r|'s length matches the larger of |a| and |b|, or // cl + abs(dl). // -// TODO(davidben): Make this take |size_t|. The |cl| + |dl| calling convention +// TODO(davidben): Make this take `size_t`. The `cl` + `dl` calling convention // is confusing. static BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, int cl, int dl) { @@ -92,15 +88,15 @@ static BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a, b += cl; if (dl < 0) { - // |a| is shorter than |b|. Complete the subtraction as if the excess words - // in |a| were zeros. + // `a` is shorter than `b`. Complete the subtraction as if the excess words + // in `a` were zeros. dl = -dl; for (int i = 0; i < dl; i++) { r[i] = CRYPTO_subc_w(0, b[i], borrow, &borrow); } } else { - // |b| is shorter than |a|. Complete the subtraction as if the excess words - // in |b| were zeros. + // `b` is shorter than `a`. Complete the subtraction as if the excess words + // in `b` were zeros. for (int i = 0; i < dl; i++) { r[i] = CRYPTO_subc_w(a[i], 0, borrow, &borrow); } @@ -111,11 +107,16 @@ static BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a, // bn_abs_sub_part_words computes |r| = |a| - |b|, storing the absolute value // and returning a mask of all ones if the result was negative and all zeros if -// the result was positive. |cl| and |dl| follow the |bn_sub_part_words| calling +// the result was positive. `cl` and `dl` follow the `bn_sub_part_words` calling // convention. // -// TODO(davidben): Make this take |size_t|. The |cl| + |dl| calling convention +// TODO(davidben): Make this take `size_t`. The `cl` + `dl` calling convention // is confusing. +// +// TODO(davidben): This function used to be used as part of a general Karatsuba +// multiplication implementation, which had to account for differently-sized +// inputs. Now it is only used as part of RSA key generation, which does not +// need all this. static BN_ULONG bn_abs_sub_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, int cl, int dl, BN_ULONG *tmp) { @@ -127,241 +128,24 @@ static BN_ULONG bn_abs_sub_part_words(BN_ULONG *r, const BN_ULONG *a, return borrow; } -int bn_abs_sub_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, - BN_CTX *ctx) { +int bssl::bn_abs_sub_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + BN_CTX *ctx) { int cl = a->width < b->width ? a->width : b->width; int dl = a->width - b->width; int r_len = a->width < b->width ? b->width : a->width; - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *tmp = BN_CTX_get(ctx); - int ok = tmp != NULL && bn_wexpand(r, r_len) && bn_wexpand(tmp, r_len); - if (ok) { - bn_abs_sub_part_words(r->d, a->d, b->d, cl, dl, tmp->d); - r->width = r_len; + if (tmp == nullptr || !bn_wexpand(r, r_len) || !bn_wexpand(tmp, r_len)) { + return 0; } - BN_CTX_end(ctx); - return ok; + bn_abs_sub_part_words(r->d, a->d, b->d, cl, dl, tmp->d); + r->width = r_len; + r->neg = 0; + return 1; } -// Karatsuba recursive multiplication algorithm -// (cf. Knuth, The Art of Computer Programming, Vol. 2) - -// bn_mul_recursive sets |r| to |a| * |b|, using |t| as scratch space. |r| has -// length 2*|n2|, |a| has length |n2| + |dna|, |b| has length |n2| + |dnb|, and -// |t| has length 4*|n2|. |n2| must be a power of two. Finally, we must have -// -|BN_MUL_RECURSIVE_SIZE_NORMAL|/2 <= |dna| <= 0 and -// -|BN_MUL_RECURSIVE_SIZE_NORMAL|/2 <= |dnb| <= 0. -// -// TODO(davidben): Simplify and |size_t| the calling convention around lengths -// here. -static void bn_mul_recursive(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, - int n2, int dna, int dnb, BN_ULONG *t) { - // |n2| is a power of two. - assert(n2 != 0 && (n2 & (n2 - 1)) == 0); - // Check |dna| and |dnb| are in range. - assert(-BN_MUL_RECURSIVE_SIZE_NORMAL / 2 <= dna && dna <= 0); - assert(-BN_MUL_RECURSIVE_SIZE_NORMAL / 2 <= dnb && dnb <= 0); - - // Only call bn_mul_comba 8 if n2 == 8 and the - // two arrays are complete [steve] - if (n2 == 8 && dna == 0 && dnb == 0) { - bn_mul_comba8(r, a, b); - return; - } - - // Else do normal multiply - if (n2 < BN_MUL_RECURSIVE_SIZE_NORMAL) { - bn_mul_normal(r, a, n2 + dna, b, n2 + dnb); - if (dna + dnb < 0) { - OPENSSL_memset(&r[2 * n2 + dna + dnb], 0, - sizeof(BN_ULONG) * -(dna + dnb)); - } - return; - } - - // Split |a| and |b| into a0,a1 and b0,b1, where a0 and b0 have size |n|. - // Split |t| into t0,t1,t2,t3, each of size |n|, with the remaining 4*|n| used - // for recursive calls. - // Split |r| into r0,r1,r2,r3. We must contribute a0*b0 to r0,r1, a0*a1+b0*b1 - // to r1,r2, and a1*b1 to r2,r3. The middle term we will compute as: - // - // a0*a1 + b0*b1 = (a0 - a1)*(b1 - b0) + a1*b1 + a0*b0 - // - // Note that we know |n| >= |BN_MUL_RECURSIVE_SIZE_NORMAL|/2 above, so - // |tna| and |tnb| are non-negative. - int n = n2 / 2, tna = n + dna, tnb = n + dnb; - - // t0 = a0 - a1 and t1 = b1 - b0. The result will be multiplied, so we XOR - // their sign masks, giving the sign of (a0 - a1)*(b1 - b0). t0 and t1 - // themselves store the absolute value. - BN_ULONG neg = bn_abs_sub_part_words(t, a, &a[n], tna, n - tna, &t[n2]); - neg ^= bn_abs_sub_part_words(&t[n], &b[n], b, tnb, tnb - n, &t[n2]); - - // Compute: - // t2,t3 = t0 * t1 = |(a0 - a1)*(b1 - b0)| - // r0,r1 = a0 * b0 - // r2,r3 = a1 * b1 - if (n == 4 && dna == 0 && dnb == 0) { - bn_mul_comba4(&t[n2], t, &t[n]); - - bn_mul_comba4(r, a, b); - bn_mul_comba4(&r[n2], &a[n], &b[n]); - } else if (n == 8 && dna == 0 && dnb == 0) { - bn_mul_comba8(&t[n2], t, &t[n]); - - bn_mul_comba8(r, a, b); - bn_mul_comba8(&r[n2], &a[n], &b[n]); - } else { - BN_ULONG *p = &t[n2 * 2]; - bn_mul_recursive(&t[n2], t, &t[n], n, 0, 0, p); - bn_mul_recursive(r, a, b, n, 0, 0, p); - bn_mul_recursive(&r[n2], &a[n], &b[n], n, dna, dnb, p); - } - - // t0,t1,c = r0,r1 + r2,r3 = a0*b0 + a1*b1 - BN_ULONG c = bn_add_words(t, r, &r[n2], n2); - - // t2,t3,c = t0,t1,c + neg*t2,t3 = (a0 - a1)*(b1 - b0) + a1*b1 + a0*b0. - // The second term is stored as the absolute value, so we do this with a - // constant-time select. - BN_ULONG c_neg = c - bn_sub_words(&t[n2 * 2], t, &t[n2], n2); - BN_ULONG c_pos = c + bn_add_words(&t[n2], t, &t[n2], n2); - bn_select_words(&t[n2], neg, &t[n2 * 2], &t[n2], n2); - static_assert(sizeof(BN_ULONG) <= sizeof(crypto_word_t), - "crypto_word_t is too small"); - c = constant_time_select_w(neg, c_neg, c_pos); - - // We now have our three components. Add them together. - // r1,r2,c = r1,r2 + t2,t3,c - c += bn_add_words(&r[n], &r[n], &t[n2], n2); - - // Propagate the carry bit to the end. - for (int i = n + n2; i < n2 + n2; i++) { - BN_ULONG old = r[i]; - r[i] = old + c; - c = r[i] < old; - } - - // The product should fit without carries. - declassify_assert(c == 0); -} - -// bn_mul_part_recursive sets |r| to |a| * |b|, using |t| as scratch space. |r| -// has length 4*|n|, |a| has length |n| + |tna|, |b| has length |n| + |tnb|, and -// |t| has length 8*|n|. |n| must be a power of two. Additionally, we must have -// 0 <= tna < n and 0 <= tnb < n, and |tna| and |tnb| must differ by at most -// one. -// -// TODO(davidben): Make this take |size_t| and perhaps the actual lengths of |a| -// and |b|. -static void bn_mul_part_recursive(BN_ULONG *r, const BN_ULONG *a, - const BN_ULONG *b, int n, int tna, int tnb, - BN_ULONG *t) { - // |n| is a power of two. - assert(n != 0 && (n & (n - 1)) == 0); - // Check |tna| and |tnb| are in range. - assert(0 <= tna && tna < n); - assert(0 <= tnb && tnb < n); - assert(-1 <= tna - tnb && tna - tnb <= 1); - - int n2 = n * 2; - if (n < 8) { - bn_mul_normal(r, a, n + tna, b, n + tnb); - OPENSSL_memset(r + n2 + tna + tnb, 0, n2 - tna - tnb); - return; - } - - // Split |a| and |b| into a0,a1 and b0,b1, where a0 and b0 have size |n|. |a1| - // and |b1| have size |tna| and |tnb|, respectively. - // Split |t| into t0,t1,t2,t3, each of size |n|, with the remaining 4*|n| used - // for recursive calls. - // Split |r| into r0,r1,r2,r3. We must contribute a0*b0 to r0,r1, a0*a1+b0*b1 - // to r1,r2, and a1*b1 to r2,r3. The middle term we will compute as: - // - // a0*a1 + b0*b1 = (a0 - a1)*(b1 - b0) + a1*b1 + a0*b0 - - // t0 = a0 - a1 and t1 = b1 - b0. The result will be multiplied, so we XOR - // their sign masks, giving the sign of (a0 - a1)*(b1 - b0). t0 and t1 - // themselves store the absolute value. - BN_ULONG neg = bn_abs_sub_part_words(t, a, &a[n], tna, n - tna, &t[n2]); - neg ^= bn_abs_sub_part_words(&t[n], &b[n], b, tnb, tnb - n, &t[n2]); - - // Compute: - // t2,t3 = t0 * t1 = |(a0 - a1)*(b1 - b0)| - // r0,r1 = a0 * b0 - // r2,r3 = a1 * b1 - if (n == 8) { - bn_mul_comba8(&t[n2], t, &t[n]); - bn_mul_comba8(r, a, b); - - bn_mul_normal(&r[n2], &a[n], tna, &b[n], tnb); - // |bn_mul_normal| only writes |tna| + |tna| words. Zero the rest. - OPENSSL_memset(&r[n2 + tna + tnb], 0, sizeof(BN_ULONG) * (n2 - tna - tnb)); - } else { - BN_ULONG *p = &t[n2 * 2]; - bn_mul_recursive(&t[n2], t, &t[n], n, 0, 0, p); - bn_mul_recursive(r, a, b, n, 0, 0, p); - - OPENSSL_memset(&r[n2], 0, sizeof(BN_ULONG) * n2); - if (tna < BN_MUL_RECURSIVE_SIZE_NORMAL && - tnb < BN_MUL_RECURSIVE_SIZE_NORMAL) { - bn_mul_normal(&r[n2], &a[n], tna, &b[n], tnb); - } else { - int i = n; - for (;;) { - i /= 2; - if (i < tna || i < tnb) { - // E.g., n == 16, i == 8 and tna == 11. |tna| and |tnb| are within one - // of each other, so if |tna| is larger and tna > i, then we know - // tnb >= i, and this call is valid. - bn_mul_part_recursive(&r[n2], &a[n], &b[n], i, tna - i, tnb - i, p); - break; - } - if (i == tna || i == tnb) { - // If there is only a bottom half to the number, just do it. We know - // the larger of |tna - i| and |tnb - i| is zero. The other is zero or - // -1 by because of |tna| and |tnb| differ by at most one. - bn_mul_recursive(&r[n2], &a[n], &b[n], i, tna - i, tnb - i, p); - break; - } - - // This loop will eventually terminate when |i| falls below - // |BN_MUL_RECURSIVE_SIZE_NORMAL| because we know one of |tna| and |tnb| - // exceeds that. - } - } - } - - // t0,t1,c = r0,r1 + r2,r3 = a0*b0 + a1*b1 - BN_ULONG c = bn_add_words(t, r, &r[n2], n2); - - // t2,t3,c = t0,t1,c + neg*t2,t3 = (a0 - a1)*(b1 - b0) + a1*b1 + a0*b0. - // The second term is stored as the absolute value, so we do this with a - // constant-time select. - BN_ULONG c_neg = c - bn_sub_words(&t[n2 * 2], t, &t[n2], n2); - BN_ULONG c_pos = c + bn_add_words(&t[n2], t, &t[n2], n2); - bn_select_words(&t[n2], neg, &t[n2 * 2], &t[n2], n2); - static_assert(sizeof(BN_ULONG) <= sizeof(crypto_word_t), - "crypto_word_t is too small"); - c = constant_time_select_w(neg, c_neg, c_pos); - - // We now have our three components. Add them together. - // r1,r2,c = r1,r2 + t2,t3,c - c += bn_add_words(&r[n], &r[n], &t[n2], n2); - - // Propagate the carry bit to the end. - for (int i = n + n2; i < n2 + n2; i++) { - BN_ULONG old = r[i]; - r[i] = old + c; - c = r[i] < old; - } - - // The product should fit without carries. - declassify_assert(c == 0); -} - -// bn_mul_impl implements |BN_mul| and |bn_mul_consttime|. Note this function -// breaks |BIGNUM| invariants and may return a negative zero. This is handled by +// bn_mul_impl implements `BN_mul` and `bn_mul_consttime`. Note this function +// breaks `BIGNUM` invariants and may return a negative zero. This is handled by // the callers. static int bn_mul_impl(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { @@ -372,13 +156,13 @@ static int bn_mul_impl(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, return 1; } - int ret = 0, i, top; + int i, top; BIGNUM *rr; - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); if (r == a || r == b) { rr = BN_CTX_get(ctx); - if (rr == NULL) { - goto err; + if (rr == nullptr) { + return 0; } } else { rr = r; @@ -389,7 +173,7 @@ static int bn_mul_impl(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, if (i == 0) { if (al == 8) { if (!bn_wexpand(rr, 16)) { - goto err; + return 0; } rr->width = 16; bn_mul_comba8(rr->d, a->d, b->d); @@ -398,63 +182,17 @@ static int bn_mul_impl(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, } top = al + bl; - static const int kMulNormalSize = 16; - if (al >= kMulNormalSize && bl >= kMulNormalSize) { - if (-1 <= i && i <= 1) { - // Find the largest power of two less than or equal to the larger length. - int j; - if (i >= 0) { - j = BN_num_bits_word((BN_ULONG)al); - } else { - j = BN_num_bits_word((BN_ULONG)bl); - } - j = 1 << (j - 1); - assert(j <= al || j <= bl); - BIGNUM *t = BN_CTX_get(ctx); - if (t == NULL) { - goto err; - } - if (al > j || bl > j) { - // We know |al| and |bl| are at most one from each other, so if al > j, - // bl >= j, and vice versa. Thus we can use |bn_mul_part_recursive|. - // - // TODO(davidben): This codepath is almost unused in standard - // algorithms. Is this optimization necessary? See notes in - // https://boringssl-review.googlesource.com/q/I0bd604e2cd6a75c266f64476c23a730ca1721ea6 - assert(al >= j && bl >= j); - if (!bn_wexpand(t, j * 8) || !bn_wexpand(rr, j * 4)) { - goto err; - } - bn_mul_part_recursive(rr->d, a->d, b->d, j, al - j, bl - j, t->d); - } else { - // al <= j && bl <= j. Additionally, we know j <= al or j <= bl, so one - // of al - j or bl - j is zero. The other, by the bound on |i| above, is - // zero or -1. Thus, we can use |bn_mul_recursive|. - if (!bn_wexpand(t, j * 4) || !bn_wexpand(rr, j * 2)) { - goto err; - } - bn_mul_recursive(rr->d, a->d, b->d, j, al - j, bl - j, t->d); - } - rr->width = top; - goto end; - } - } - if (!bn_wexpand(rr, top)) { - goto err; + return 0; } rr->width = top; bn_mul_normal(rr->d, a->d, al, b->d, bl); end: if (r != rr && !BN_copy(r, rr)) { - goto err; + return 0; } - ret = 1; - -err: - BN_CTX_end(ctx); - return ret; + return 1; } int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { @@ -462,12 +200,13 @@ int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { return 0; } - // This additionally fixes any negative zeros created by |bn_mul_impl|. + // This additionally fixes any negative zeros created by `bn_mul_impl`. bn_set_minimal_width(r); return 1; } -int bn_mul_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { +int bssl::bn_mul_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + BN_CTX *ctx) { // Prevent negative zeros. if (a->neg || b->neg) { OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER); @@ -477,12 +216,12 @@ int bn_mul_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { return bn_mul_impl(r, a, b, ctx); } -void bn_mul_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, size_t num_a, - const BN_ULONG *b, size_t num_b) { +void bssl::bn_mul_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, + size_t num_a, const BN_ULONG *b, size_t num_b) { if (num_r != num_a + num_b) { abort(); } - // TODO(davidben): Should this call |bn_mul_comba4| too? |BN_mul| does not + // TODO(davidben): Should this call `bn_mul_comba4` too? `BN_mul` does not // hit that code. if (num_a == 8 && num_b == 8) { bn_mul_comba8(r, a, b); @@ -491,9 +230,7 @@ void bn_mul_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, size_t num_a, } } -// tmp must have 2*n words -static void bn_sqr_normal(BN_ULONG *r, const BN_ULONG *a, size_t n, - BN_ULONG *tmp) { +static void bn_sqr_normal(BN_ULONG *r, const BN_ULONG *a, size_t n) { if (n == 0) { return; } @@ -518,75 +255,14 @@ static void bn_sqr_normal(BN_ULONG *r, const BN_ULONG *a, size_t n, } } - // The final result fits in |max| words, so none of the following operations + // The final result fits in `max` words, so none of the following operations // will overflow. - // Double |r|, giving the contribution of a[i] * a[j] for all i != j. + // Double `r`, giving the contribution of a[i] * a[j] for all i != j. bn_add_words(r, r, r, max); // Add in the contribution of a[i] * a[i] for all i. - bn_sqr_words(tmp, a, n); - bn_add_words(r, r, tmp, max); -} - -// bn_sqr_recursive sets |r| to |a|^2, using |t| as scratch space. |r| has -// length 2*|n2|, |a| has length |n2|, and |t| has length 4*|n2|. |n2| must be -// a power of two. -static void bn_sqr_recursive(BN_ULONG *r, const BN_ULONG *a, size_t n2, - BN_ULONG *t) { - // |n2| is a power of two. - assert(n2 != 0 && (n2 & (n2 - 1)) == 0); - - if (n2 == 4) { - bn_sqr_comba4(r, a); - return; - } - if (n2 == 8) { - bn_sqr_comba8(r, a); - return; - } - if (n2 < BN_SQR_RECURSIVE_SIZE_NORMAL) { - bn_sqr_normal(r, a, n2, t); - return; - } - - // Split |a| into a0,a1, each of size |n|. - // Split |t| into t0,t1,t2,t3, each of size |n|, with the remaining 4*|n| used - // for recursive calls. - // Split |r| into r0,r1,r2,r3. We must contribute a0^2 to r0,r1, 2*a0*a1 to - // r1,r2, and a1^2 to r2,r3. - size_t n = n2 / 2; - BN_ULONG *t_recursive = &t[n2 * 2]; - - // t0 = |a0 - a1|. - bn_abs_sub_words(t, a, &a[n], n, &t[n]); - // t2,t3 = t0^2 = |a0 - a1|^2 = a0^2 - 2*a0*a1 + a1^2 - bn_sqr_recursive(&t[n2], t, n, t_recursive); - - // r0,r1 = a0^2 - bn_sqr_recursive(r, a, n, t_recursive); - - // r2,r3 = a1^2 - bn_sqr_recursive(&r[n2], &a[n], n, t_recursive); - - // t0,t1,c = r0,r1 + r2,r3 = a0^2 + a1^2 - BN_ULONG c = bn_add_words(t, r, &r[n2], n2); - // t2,t3,c = t0,t1,c - t2,t3 = 2*a0*a1 - c -= bn_sub_words(&t[n2], t, &t[n2], n2); - - // We now have our three components. Add them together. - // r1,r2,c = r1,r2 + t2,t3,c - c += bn_add_words(&r[n], &r[n], &t[n2], n2); - - // Propagate the carry bit to the end. - for (size_t i = n + n2; i < n2 + n2; i++) { - BN_ULONG old = r[i]; - r[i] = old + c; - c = r[i] < old; - } - - // The square should fit without carries. - assert(c == 0); + bn_sqr_add_words(r, a, n); } int BN_mul_word(BIGNUM *bn, BN_ULONG w) { @@ -610,7 +286,7 @@ int BN_mul_word(BIGNUM *bn, BN_ULONG w) { return 1; } -int bn_sqr_consttime(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { +int bssl::bn_sqr_consttime(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { int al = a->width; if (al <= 0) { r->width = 0; @@ -618,17 +294,15 @@ int bn_sqr_consttime(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { return 1; } - int ret = 0, max; - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *rr = (a != r) ? r : BN_CTX_get(ctx); - BIGNUM *tmp = BN_CTX_get(ctx); - if (!rr || !tmp) { - goto err; + if (!rr) { + return 0; } - max = 2 * al; // Non-zero (from above) + int max = 2 * al; // Non-zero (from above) if (!bn_wexpand(rr, max)) { - goto err; + return 0; } if (al == 4) { @@ -636,36 +310,16 @@ int bn_sqr_consttime(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { } else if (al == 8) { bn_sqr_comba8(rr->d, a->d); } else { - if (al < BN_SQR_RECURSIVE_SIZE_NORMAL) { - BN_ULONG t[BN_SQR_RECURSIVE_SIZE_NORMAL * 2]; - bn_sqr_normal(rr->d, a->d, al, t); - } else { - // If |al| is a power of two, we can use |bn_sqr_recursive|. - if (al != 0 && (al & (al - 1)) == 0) { - if (!bn_wexpand(tmp, al * 4)) { - goto err; - } - bn_sqr_recursive(rr->d, a->d, al, tmp->d); - } else { - if (!bn_wexpand(tmp, max)) { - goto err; - } - bn_sqr_normal(rr->d, a->d, al, tmp->d); - } - } + bn_sqr_normal(rr->d, a->d, al); } rr->neg = 0; rr->width = max; if (rr != r && !BN_copy(r, rr)) { - goto err; + return 0; } - ret = 1; - -err: - BN_CTX_end(ctx); - return ret; + return 1; } int BN_sqr(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { @@ -677,8 +331,10 @@ int BN_sqr(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { return 1; } -void bn_sqr_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, size_t num_a) { - if (num_r != 2 * num_a || num_a > BN_SMALL_MAX_WORDS) { +void bssl::bn_sqr_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, + size_t num_a) { + assert(r != a); + if (num_r != 2 * num_a) { abort(); } if (num_a == 4) { @@ -686,8 +342,6 @@ void bn_sqr_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, size_t num_a) { } else if (num_a == 8) { bn_sqr_comba8(r, a); } else { - BN_ULONG tmp[2 * BN_SMALL_MAX_WORDS]; - bn_sqr_normal(r, a, num_a, tmp); - OPENSSL_cleanse(tmp, 2 * num_a * sizeof(BN_ULONG)); + bn_sqr_normal(r, a, num_a); } } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/prime.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/prime.cc.inc index 9c54ae9a..0e1c7f15 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/prime.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/prime.cc.inc @@ -1,21 +1,31 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../../internal.h" +#include "../../mem_internal.h" #include "internal.h" +using namespace bssl; + // kPrimes contains the first 1024 primes. static const uint16_t kPrimes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, @@ -110,9 +120,9 @@ static const uint16_t kPrimes[] = { // necessary for generating a 'bits'-bit candidate prime. // // -// This table is generated using the algorithm of FIPS PUB 186-4 -// Digital Signature Standard (DSS), section F.1, page 117. -// (https://doi.org/10.6028/NIST.FIPS.186-4) +// This table is generated using the algorithm of FIPS PUB 186-5 +// Digital Signature Standard (DSS), section C.1, page 72. +// (https://doi.org/10.6028/NIST.FIPS.186-5). // The following magma script was used to generate the output: // securitybits:=125; // k:=1024; @@ -129,7 +139,7 @@ static const uint16_t kPrimes[] = { // S+:=2^(m-(m-1)*t)*s; // end for; // A:=2^(k-2-M*t); -// B:=8*(Pi(RealField(32))^2-6)/3*2^(k-2)*S; +// B:=8*(Pi(RealField(32))²-6)/3*2^(k-2)*S; // pkt:=2.00743*Log(2)*k*2^-k*(A+B); // seclevel:=Floor(-Log(2,pkt)); // if seclevel ge securitybits then @@ -188,15 +198,15 @@ static int BN_prime_checks_for_size(int bits) { // of excluding a candidate with trial division is larger. static size_t num_trial_division_primes(const BIGNUM *n) { if (n->width * BN_BITS2 > 1024) { - return OPENSSL_ARRAY_SIZE(kPrimes); + return std::size(kPrimes); } - return OPENSSL_ARRAY_SIZE(kPrimes) / 2; + return std::size(kPrimes) / 2; } // BN_PRIME_CHECKS_BLINDED is the iteration count for blinding the constant-time -// primality test. See |BN_primality_test| for details. This number is selected -// so that, for a candidate N-bit RSA prime, picking |BN_PRIME_CHECKS_BLINDED| -// random N-bit numbers will have at least |BN_prime_checks_for_size(N)| values +// primality test. See `BN_primality_test` for details. This number is selected +// so that, for a candidate N-bit RSA prime, picking `BN_PRIME_CHECKS_BLINDED` +// random N-bit numbers will have at least `BN_prime_checks_for_size(N)` values // in range with high probability. // // The following Python script computes the blinding factor needed for the @@ -204,7 +214,7 @@ static size_t num_trial_division_primes(const BIGNUM *n) { /* import math -# We choose candidate RSA primes between sqrt(2)/2 * 2^N and 2^N and select +# We choose candidate RSA primes between sqrt(2)/2 * 2ᴺ and 2ᴺ and select # witnesses by generating random N-bit numbers. Thus the probability of # selecting one in range is at least sqrt(2)/2. p = math.sqrt(2) / 2 @@ -221,8 +231,8 @@ def choose(a, b): return r def failure_rate(min_uniform, iterations): - """ Returns the probability that, for |iterations| candidate witnesses, fewer - than |min_uniform| of them will be uniform. """ + """ Returns the probability that, for `iterations` candidate witnesses, fewer + than `min_uniform` of them will be uniform. """ prob = 0.0 for i in xrange(min_uniform): prob += (choose(iterations, i) * @@ -260,11 +270,9 @@ static int probable_prime_dh(BIGNUM *rnd, int bits, const BIGNUM *add, static int probable_prime_dh_safe(BIGNUM *rnd, int bits, const BIGNUM *add, const BIGNUM *rem, BN_CTX *ctx); -BN_GENCB *BN_GENCB_new(void) { - return reinterpret_cast(OPENSSL_zalloc(sizeof(BN_GENCB))); -} +BN_GENCB *BN_GENCB_new() { return New(); } -void BN_GENCB_free(BN_GENCB *callback) { OPENSSL_free(callback); } +void BN_GENCB_free(BN_GENCB *callback) { Delete(callback); } void BN_GENCB_set(BN_GENCB *callback, int (*f)(int event, int n, struct bn_gencb_st *), void *arg) { @@ -285,9 +293,7 @@ void *BN_GENCB_get_arg(const BN_GENCB *callback) { return callback->arg; } int BN_generate_prime_ex(BIGNUM *ret, int bits, int safe, const BIGNUM *add, const BIGNUM *rem, BN_GENCB *cb) { BIGNUM *t; - int found = 0; int i, j, c1 = 0; - BN_CTX *ctx; int checks = BN_prime_checks_for_size(bits); if (bits < 2) { @@ -300,43 +306,43 @@ int BN_generate_prime_ex(BIGNUM *ret, int bits, int safe, const BIGNUM *add, return 0; } - ctx = BN_CTX_new(); - if (ctx == NULL) { - goto err; + UniquePtr ctx(BN_CTX_new()); + if (ctx == nullptr) { + return 0; } - BN_CTX_start(ctx); - t = BN_CTX_get(ctx); + BN_CTXScope scope(ctx.get()); + t = BN_CTX_get(ctx.get()); if (!t) { - goto err; + return 0; } loop: // make a random number and set the top and bottom bits - if (add == NULL) { + if (add == nullptr) { if (!probable_prime(ret, bits)) { - goto err; + return 0; } } else { if (safe) { - if (!probable_prime_dh_safe(ret, bits, add, rem, ctx)) { - goto err; + if (!probable_prime_dh_safe(ret, bits, add, rem, ctx.get())) { + return 0; } } else { - if (!probable_prime_dh(ret, bits, add, rem, ctx)) { - goto err; + if (!probable_prime_dh(ret, bits, add, rem, ctx.get())) { + return 0; } } } if (!BN_GENCB_call(cb, BN_GENCB_GENERATED, c1++)) { // aborted - goto err; + return 0; } if (!safe) { - i = BN_is_prime_fasttest_ex(ret, checks, ctx, 0, cb); + i = BN_is_prime_fasttest_ex(ret, checks, ctx.get(), 0, cb); if (i == -1) { - goto err; + return 0; } else if (i == 0) { goto loop; } @@ -344,52 +350,44 @@ loop: // for "safe prime" generation, check that (p-1)/2 is prime. Since a prime // is odd, We just need to divide by 2 if (!BN_rshift1(t, ret)) { - goto err; + return 0; } - // Interleave |ret| and |t|'s primality tests to avoid paying the full - // iteration count on |ret| only to quickly discover |t| is composite. + // Interleave `ret` and `t`'s primality tests to avoid paying the full + // iteration count on `ret` only to quickly discover `t` is composite. // // TODO(davidben): This doesn't quite work because an iteration count of 1 // still runs the blinding mechanism. for (i = 0; i < checks; i++) { - j = BN_is_prime_fasttest_ex(ret, 1, ctx, 0, NULL); + j = BN_is_prime_fasttest_ex(ret, 1, ctx.get(), 0, nullptr); if (j == -1) { - goto err; + return 0; } else if (j == 0) { goto loop; } - j = BN_is_prime_fasttest_ex(t, 1, ctx, 0, NULL); + j = BN_is_prime_fasttest_ex(t, 1, ctx.get(), 0, nullptr); if (j == -1) { - goto err; + return 0; } else if (j == 0) { goto loop; } if (!BN_GENCB_call(cb, BN_GENCB_PRIME_TEST, i)) { - goto err; + return 0; } // We have a safe prime test pass } } // we have a prime :-) - found = 1; - -err: - if (ctx != NULL) { - BN_CTX_end(ctx); - BN_CTX_free(ctx); - } - - return found; + return 1; } static int bn_trial_division(uint16_t *out, const BIGNUM *bn) { const size_t num_primes = num_trial_division_primes(bn); for (size_t i = 1; i < num_primes; i++) { - // During RSA key generation, |bn| may be secret, but only if |bn| was + // During RSA key generation, `bn` may be secret, but only if `bn` was // prime, so it is safe to leak failed trial divisions. if (constant_time_declassify_int(bn_mod_u16_consttime(bn, kPrimes[i]) == 0)) { @@ -400,29 +398,29 @@ static int bn_trial_division(uint16_t *out, const BIGNUM *bn) { return 0; } -int bn_odd_number_is_obviously_composite(const BIGNUM *bn) { +int bssl::bn_odd_number_is_obviously_composite(const BIGNUM *bn) { uint16_t prime; return bn_trial_division(&prime, bn) && !BN_is_word(bn, prime); } -int bn_miller_rabin_init(BN_MILLER_RABIN *miller_rabin, const BN_MONT_CTX *mont, - BN_CTX *ctx) { - // This function corresponds to steps 1 through 3 of FIPS 186-4, C.3.1. +int bssl::bn_miller_rabin_init(BN_MILLER_RABIN *miller_rabin, + const BN_MONT_CTX *mont, BN_CTX *ctx) { + // This function corresponds to steps 1 through 3 of FIPS 186-5, B.3.1. const BIGNUM *w = &mont->N; - // Note we do not call |BN_CTX_start| in this function. We intentionally + // Note we do not call `BN_CTX_start` in this function. We intentionally // allocate values in the containing scope so they outlive this function. miller_rabin->w1 = BN_CTX_get(ctx); miller_rabin->m = BN_CTX_get(ctx); miller_rabin->one_mont = BN_CTX_get(ctx); miller_rabin->w1_mont = BN_CTX_get(ctx); - if (miller_rabin->w1 == NULL || // - miller_rabin->m == NULL || // - miller_rabin->one_mont == NULL || // - miller_rabin->w1_mont == NULL) { + if (miller_rabin->w1 == nullptr || // + miller_rabin->m == nullptr || // + miller_rabin->one_mont == nullptr || // + miller_rabin->w1_mont == nullptr) { return 0; } - // See FIPS 186-4, C.3.1, steps 1 through 3. + // See FIPS 186-5, B.3.1, steps 1 through 3. if (!bn_usub_consttime(miller_rabin->w1, w, BN_value_one())) { return 0; } @@ -436,7 +434,7 @@ int bn_miller_rabin_init(BN_MILLER_RABIN *miller_rabin, const BN_MONT_CTX *mont, // Precompute some values in Montgomery form. if (!bn_one_to_montgomery(miller_rabin->one_mont, mont, ctx) || // w - 1 is -1 mod w, so we can compute it in the Montgomery domain, -R, - // with a subtraction. (|one_mont| cannot be zero.) + // with a subtraction. (`one_mont` cannot be zero.) !bn_usub_consttime(miller_rabin->w1_mont, w, miller_rabin->one_mont)) { return 0; } @@ -444,26 +442,25 @@ int bn_miller_rabin_init(BN_MILLER_RABIN *miller_rabin, const BN_MONT_CTX *mont, return 1; } -int bn_miller_rabin_iteration(const BN_MILLER_RABIN *miller_rabin, - int *out_is_possibly_prime, const BIGNUM *b, - const BN_MONT_CTX *mont, BN_CTX *ctx) { - // This function corresponds to steps 4.3 through 4.5 of FIPS 186-4, C.3.1. - int ret = 0; - BN_CTX_start(ctx); +int bssl::bn_miller_rabin_iteration(const BN_MILLER_RABIN *miller_rabin, + int *out_is_possibly_prime, const BIGNUM *b, + const BN_MONT_CTX *mont, BN_CTX *ctx) { + // This function corresponds to steps 4.3 through 4.5 of FIPS 186-5, B.3.1. + BN_CTXScope scope(ctx); // Step 4.3. We use Montgomery-encoding for better performance and to avoid // timing leaks. const BIGNUM *w = &mont->N; BIGNUM *z = BN_CTX_get(ctx); crypto_word_t is_possibly_prime; - if (z == NULL || + if (z == nullptr || !BN_mod_exp_mont_consttime(z, b, miller_rabin->m, w, ctx, mont) || !BN_to_montgomery(z, z, mont, ctx)) { - goto err; + return 0; } - // is_possibly_prime is all ones if we have determined |b| is not a composite - // witness for |w|. This is equivalent to going to step 4.7 in the original + // is_possibly_prime is all ones if we have determined `b` is not a composite + // witness for `w`. This is equivalent to going to step 4.7 in the original // algorithm. To avoid timing leaks, we run the algorithm to the end for prime // inputs. is_possibly_prime = 0; @@ -476,8 +473,8 @@ int bn_miller_rabin_iteration(const BN_MILLER_RABIN *miller_rabin, // Step 4.5. // - // To avoid leaking |a|, we run the loop to |w_bits| and mask off all - // iterations once |j| = |a|. + // To avoid leaking `a`, we run the loop to `w_bits` and mask off all + // iterations once `j` = `a`. for (int j = 1; j < miller_rabin->w_bits; j++) { if (constant_time_declassify_w(constant_time_eq_int(j, miller_rabin->a) & ~is_possibly_prime)) { @@ -488,14 +485,14 @@ int bn_miller_rabin_iteration(const BN_MILLER_RABIN *miller_rabin, // Step 4.5.1. if (!BN_mod_mul_montgomery(z, z, z, mont, ctx)) { - goto err; + return 0; } // Step 4.5.2. If z = w-1 and the loop is not done, this is not a composite // witness. crypto_word_t z_is_w1_mont = BN_equal_consttime(z, miller_rabin->w1_mont); z_is_w1_mont = 0 - z_is_w1_mont; // Make it all zeros or all ones. - is_possibly_prime |= z_is_w1_mont; // Go to step 4.7 if |z_is_w1_mont|. + is_possibly_prime |= z_is_w1_mont; // Go to step 4.7 if `z_is_w1_mont`. // Step 4.5.3. If z = 1 and the loop is not done, the previous value of z // was not -1. There are no non-trivial square roots of 1 modulo a prime, so @@ -508,11 +505,7 @@ int bn_miller_rabin_iteration(const BN_MILLER_RABIN *miller_rabin, } *out_is_possibly_prime = constant_time_declassify_w(is_possibly_prime) & 1; - ret = 1; - -err: - BN_CTX_end(ctx); - return ret; + return 1; } int BN_primality_test(int *out_is_probably_prime, const BIGNUM *w, int checks, @@ -521,35 +514,35 @@ int BN_primality_test(int *out_is_probably_prime, const BIGNUM *w, int checks, // generation. We generate RSA keys by selecting two large, secret primes with // rejection sampling. // - // We thus treat |w| as secret if turns out to be a large prime. However, if - // |w| is composite, we treat this and |w| itself as public. (Conversely, if - // |w| is prime, that it is prime is public. Only the value is secret.) This + // We thus treat `w` as secret if turns out to be a large prime. However, if + // `w` is composite, we treat this and `w` itself as public. (Conversely, if + // `w` is prime, that it is prime is public. Only the value is secret.) This // is fine for RSA key generation, but note it is important that we use // rejection sampling, with each candidate prime chosen independently. This // would not work for, e.g., an algorithm which looked for primes in // consecutive integers. These assumptions allow us to discard composites - // quickly. We additionally treat |w| as public when it is a small prime to + // quickly. We additionally treat `w` as public when it is a small prime to // simplify trial decryption and some edge cases. // // One RSA key generation will call this function on exactly two primes and // many more composites. The overall cost is a combination of several factors: // - // 1. Checking if |w| is divisible by a small prime is much faster than + // 1. Checking if `w` is divisible by a small prime is much faster than // learning it is composite by Miller-Rabin (see below for details on that // cost). Trial division by p saves 1/p of Miller-Rabin calls, so this is // worthwhile until p exceeds the ratio of the two costs. // // 2. For a random (i.e. non-adversarial) candidate large prime and candidate // witness, the probability of false witness is very low. (This is why FIPS - // 186-4 only requires a few iterations.) Thus composites not discarded by + // 186-5 only requires a few iterations.) Thus composites not discarded by // trial decryption, in practice, cost one Miller-Rabin iteration. Only the // two actual primes cost the full iteration count. // - // 3. A Miller-Rabin iteration is a modular exponentiation plus |a| additional - // modular squares, where |a| is the number of factors of two in |w-1|. |a| + // 3. A Miller-Rabin iteration is a modular exponentiation plus `a` additional + // modular squares, where `a` is the number of factors of two in `w-1`. `a` // is likely small (the distribution falls exponentially), but it is also - // potentially secret, so we loop up to its log(w) upper bound when |w| is - // prime. When |w| is composite, we break early, so only two calls pay this + // potentially secret, so we loop up to its log(w) upper bound when `w` is + // prime. When `w` is composite, we break early, so only two calls pay this // cost. (Note that all calls pay the modular exponentiation which is, // itself, log(w) modular multiplications and squares.) // @@ -593,57 +586,56 @@ int BN_primality_test(int *out_is_probably_prime, const BIGNUM *w, int checks, checks = BN_prime_checks_for_size(BN_num_bits(w)); } - BN_CTX *new_ctx = NULL; - if (ctx == NULL) { - new_ctx = BN_CTX_new(); - if (new_ctx == NULL) { + UniquePtr new_ctx; + if (ctx == nullptr) { + new_ctx.reset(BN_CTX_new()); + if (new_ctx == nullptr) { return 0; } - ctx = new_ctx; + ctx = new_ctx.get(); } - // See C.3.1 from FIPS 186-4. - int ret = 0; - BN_CTX_start(ctx); + // See B.3.1 from FIPS 186-5. + BN_CTXScope scope(ctx); BIGNUM *b = BN_CTX_get(ctx); - BN_MONT_CTX *mont = BN_MONT_CTX_new_consttime(w, ctx); + UniquePtr mont(BN_MONT_CTX_new_consttime(w, ctx)); BN_MILLER_RABIN miller_rabin; crypto_word_t uniform_iterations = 0; - if (b == NULL || mont == NULL || + if (b == nullptr || mont == nullptr || // Steps 1-3. - !bn_miller_rabin_init(&miller_rabin, mont, ctx)) { - goto err; + !bn_miller_rabin_init(&miller_rabin, mont.get(), ctx)) { + return 0; } // The following loop performs in inner iteration of the Miller-Rabin // Primality test (Step 4). // - // The algorithm as specified in FIPS 186-4 leaks information on |w|, the RSA + // The algorithm as specified in FIPS 186-5 leaks information on `w`, the RSA // private key. Instead, we run through each iteration unconditionally, // performing modular multiplications, masking off any effects to behave // equivalently to the specified algorithm. // - // We also blind the number of values of |b| we try. Steps 4.1–4.2 say to - // discard out-of-range values. To avoid leaking information on |w|, we use - // |bn_rand_secret_range| which, rather than discarding bad values, adjusts + // We also blind the number of values of `b` we try. Steps 4.1–4.2 say to + // discard out-of-range values. To avoid leaking information on `w`, we use + // `bn_rand_secret_range` which, rather than discarding bad values, adjusts // them to be in range. Though not uniformly selected, these adjusted values // are still usable as Miller-Rabin checks. // // Miller-Rabin is already probabilistic, so we could reach the desired // confidence levels by just suitably increasing the iteration count. However, - // to align with FIPS 186-4, we use a more pessimal analysis: we do not count + // to align with FIPS 186-5, we use a more pessimal analysis: we do not count // the non-uniform values towards the iteration count. As a result, this // function is more complex and has more timing risk than necessary. // // We count both total iterations and uniform ones and iterate until we've - // reached at least |BN_PRIME_CHECKS_BLINDED| and |iterations|, respectively. + // reached at least `BN_PRIME_CHECKS_BLINDED` and `iterations`, respectively. // If the latter is large enough, it will be the limiting factor with high // probability and we won't leak information. // // Note this blinding does not impact most calls when picking primes because // composites are rejected early. Only the two secret primes see extra work. - // Using |constant_time_lt_w| seems to prevent the compiler from optimizing + // Using `constant_time_lt_w` seems to prevent the compiler from optimizing // this into two jumps. for (int i = 1; constant_time_declassify_w( (i <= BN_PRIME_CHECKS_BLINDED) | @@ -652,39 +644,32 @@ int BN_primality_test(int *out_is_probably_prime, const BIGNUM *w, int checks, // Step 4.1-4.2 int is_uniform; if (!bn_rand_secret_range(b, &is_uniform, 2, miller_rabin.w1)) { - goto err; + return 0; } uniform_iterations += is_uniform; // Steps 4.3-4.5 int is_possibly_prime = 0; - if (!bn_miller_rabin_iteration(&miller_rabin, &is_possibly_prime, b, mont, - ctx)) { - goto err; + if (!bn_miller_rabin_iteration(&miller_rabin, &is_possibly_prime, b, + mont.get(), ctx)) { + return 0; } if (!is_possibly_prime) { // Step 4.6. We did not see z = w-1 before z = 1, so w must be composite. *out_is_probably_prime = 0; - ret = 1; - goto err; + return 1; } // Step 4.7 if (!BN_GENCB_call(cb, BN_GENCB_PRIME_TEST, i - 1)) { - goto err; + return 0; } } declassify_assert(uniform_iterations >= (crypto_word_t)checks); *out_is_probably_prime = 1; - ret = 1; - -err: - BN_MONT_CTX_free(mont); - BN_CTX_end(ctx); - BN_CTX_free(new_ctx); - return ret; + return 1; } int BN_is_prime_ex(const BIGNUM *candidate, int checks, BN_CTX *ctx, @@ -715,41 +700,36 @@ int BN_enhanced_miller_rabin_primality_test( checks = BN_prime_checks_for_size(BN_num_bits(w)); } - int ret = 0; - BN_MONT_CTX *mont = NULL; - - BN_CTX_start(ctx); - + BN_CTXScope scope(ctx); BIGNUM *w1 = BN_CTX_get(ctx); - BIGNUM *b, *g, *z, *x, *x1, *m; - int a; - if (w1 == NULL || !BN_copy(w1, w) || !BN_sub_word(w1, 1)) { - goto err; + if (w1 == nullptr || !BN_copy(w1, w) || !BN_sub_word(w1, 1)) { + return 0; } - // Write w1 as m*2^a (Steps 1 and 2). - a = 0; + // Write w1 as m*2ᵃ (Steps 1 and 2). + int a = 0; while (!BN_is_bit_set(w1, a)) { a++; } - m = BN_CTX_get(ctx); - if (m == NULL || !BN_rshift(m, w1, a)) { - goto err; + BIGNUM *m = BN_CTX_get(ctx); + if (m == nullptr || !BN_rshift(m, w1, a)) { + return 0; } - b = BN_CTX_get(ctx); - g = BN_CTX_get(ctx); - z = BN_CTX_get(ctx); - x = BN_CTX_get(ctx); - x1 = BN_CTX_get(ctx); - if (b == NULL || g == NULL || z == NULL || x == NULL || x1 == NULL) { - goto err; + BIGNUM *b = BN_CTX_get(ctx); + BIGNUM *g = BN_CTX_get(ctx); + BIGNUM *z = BN_CTX_get(ctx); + BIGNUM *x = BN_CTX_get(ctx); + BIGNUM *x1 = BN_CTX_get(ctx); + if (b == nullptr || g == nullptr || z == nullptr || x == nullptr || + x1 == nullptr) { + return 0; } // Montgomery setup for computations mod w - mont = BN_MONT_CTX_new_for_modulus(w, ctx); - if (mont == NULL) { - goto err; + UniquePtr mont(BN_MONT_CTX_new_for_modulus(w, ctx)); + if (mont == nullptr) { + return 0; } // The following loop performs in inner iteration of the Enhanced Miller-Rabin @@ -757,22 +737,21 @@ int BN_enhanced_miller_rabin_primality_test( for (int i = 1; i <= checks; i++) { // Step 4.1-4.2 if (!BN_rand_range_ex(b, 2, w1)) { - goto err; + return 0; } // Step 4.3-4.4 if (!BN_gcd(g, b, w, ctx)) { - goto err; + return 0; } if (BN_cmp_word(g, 1) > 0) { *out_result = bn_composite; - ret = 1; - goto err; + return 1; } // Step 4.5 - if (!BN_mod_exp_mont(z, b, m, w, ctx, mont)) { - goto err; + if (!BN_mod_exp_mont(z, b, m, w, ctx, mont.get())) { + return 0; } // Step 4.6 @@ -783,7 +762,7 @@ int BN_enhanced_miller_rabin_primality_test( // Step 4.7 for (int j = 1; j < a; j++) { if (!BN_copy(x, z) || !BN_mod_mul(z, x, x, w, ctx)) { - goto err; + return 0; } if (BN_cmp(z, w1) == 0) { goto loop; @@ -795,18 +774,18 @@ int BN_enhanced_miller_rabin_primality_test( // Step 4.8-4.9 if (!BN_copy(x, z) || !BN_mod_mul(z, x, x, w, ctx)) { - goto err; + return 0; } // Step 4.10-4.11 if (!BN_is_one(z) && !BN_copy(x, z)) { - goto err; + return 0; } composite: // Step 4.12-4.14 if (!BN_copy(x1, x) || !BN_sub_word(x1, 1) || !BN_gcd(g, x1, w, ctx)) { - goto err; + return 0; } if (BN_cmp_word(g, 1) > 0) { *out_result = bn_composite; @@ -814,24 +793,17 @@ int BN_enhanced_miller_rabin_primality_test( *out_result = bn_non_prime_power_composite; } - ret = 1; - goto err; + return 1; loop: // Step 4.15 if (!BN_GENCB_call(cb, BN_GENCB_PRIME_TEST, i - 1)) { - goto err; + return 0; } } *out_result = bn_probably_prime; - ret = 1; - -err: - BN_MONT_CTX_free(mont); - BN_CTX_end(ctx); - - return ret; + return 1; } static int probable_prime(BIGNUM *rnd, int bits) { @@ -845,111 +817,99 @@ static int probable_prime(BIGNUM *rnd, int bits) { static int probable_prime_dh(BIGNUM *rnd, int bits, const BIGNUM *add, const BIGNUM *rem, BN_CTX *ctx) { - int ret = 0; + BN_CTXScope scope(ctx); BIGNUM *t1; - - BN_CTX_start(ctx); - size_t num_primes; - if ((t1 = BN_CTX_get(ctx)) == NULL) { - goto err; + if ((t1 = BN_CTX_get(ctx)) == nullptr) { + return 0; } if (!BN_rand(rnd, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD)) { - goto err; + return 0; } // we need ((rnd-rem) % add) == 0 - if (!BN_mod(t1, rnd, add, ctx)) { - goto err; + return 0; } if (!BN_sub(rnd, rnd, t1)) { - goto err; + return 0; } - if (rem == NULL) { + if (rem == nullptr) { if (!BN_add_word(rnd, 1)) { - goto err; + return 0; } } else { if (!BN_add(rnd, rnd, rem)) { - goto err; + return 0; } } // we now have a random number 'rand' to test. - num_primes = num_trial_division_primes(rnd); + size_t num_primes = num_trial_division_primes(rnd); loop: for (size_t i = 1; i < num_primes; i++) { // check that rnd is a prime if (bn_mod_u16_consttime(rnd, kPrimes[i]) <= 1) { if (!BN_add(rnd, rnd, add)) { - goto err; + return 0; } goto loop; } } - ret = 1; - -err: - BN_CTX_end(ctx); - return ret; + return 1; } static int probable_prime_dh_safe(BIGNUM *p, int bits, const BIGNUM *padd, const BIGNUM *rem, BN_CTX *ctx) { - int ret = 0; - BIGNUM *t1, *qadd, *q; - bits--; - BN_CTX_start(ctx); - t1 = BN_CTX_get(ctx); - q = BN_CTX_get(ctx); - qadd = BN_CTX_get(ctx); - size_t num_primes; - if (qadd == NULL) { - goto err; + BN_CTXScope scope(ctx); + BIGNUM *t1 = BN_CTX_get(ctx); + BIGNUM *q = BN_CTX_get(ctx); + BIGNUM *qadd = BN_CTX_get(ctx); + if (qadd == nullptr) { + return 0; } if (!BN_rshift1(qadd, padd)) { - goto err; + return 0; } if (!BN_rand(q, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD)) { - goto err; + return 0; } // we need ((rnd-rem) % add) == 0 if (!BN_mod(t1, q, qadd, ctx)) { - goto err; + return 0; } if (!BN_sub(q, q, t1)) { - goto err; + return 0; } - if (rem == NULL) { + if (rem == nullptr) { if (!BN_add_word(q, 1)) { - goto err; + return 0; } } else { if (!BN_rshift1(t1, rem)) { - goto err; + return 0; } if (!BN_add(q, q, t1)) { - goto err; + return 0; } } // we now have a random number 'rand' to test. if (!BN_lshift1(p, q)) { - goto err; + return 0; } if (!BN_add_word(p, 1)) { - goto err; + return 0; } - num_primes = num_trial_division_primes(p); + size_t num_primes = num_trial_division_primes(p); loop: for (size_t i = 1; i < num_primes; i++) { // check that p and q are prime @@ -958,18 +918,14 @@ loop: if (bn_mod_u16_consttime(p, kPrimes[i]) == 0 || bn_mod_u16_consttime(q, kPrimes[i]) == 0) { if (!BN_add(p, p, padd)) { - goto err; + return 0; } if (!BN_add(q, q, qadd)) { - goto err; + return 0; } goto loop; } } - ret = 1; - -err: - BN_CTX_end(ctx); - return ret; + return 1; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/random.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/random.cc.inc index 8f6b5445..73be2361 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/random.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/random.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -21,8 +26,10 @@ #include "internal.h" +using namespace bssl; + int BN_rand(BIGNUM *rnd, int bits, int top, int bottom) { - if (rnd == NULL) { + if (rnd == nullptr) { return 0; } @@ -87,7 +94,7 @@ int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom) { } // bn_less_than_word_mask returns a mask of all ones if the number represented -// by |len| words at |a| is less than |b| and zero otherwise. It performs this +// by `len` words at |a| is less than |b| and zero otherwise. It performs this // computation in time independent of the value of |a|. |b| is assumed public. static crypto_word_t bn_less_than_word_mask(const BN_ULONG *a, size_t len, BN_ULONG b) { @@ -105,14 +112,14 @@ static crypto_word_t bn_less_than_word_mask(const BN_ULONG *a, size_t len, for (size_t i = 1; i < len; i++) { mask |= a[i]; } - // |mask| is now zero iff a[1..len-1] are all zero. + // `mask` is now zero iff a[1..len-1] are all zero. mask = constant_time_is_zero_w(mask); mask &= constant_time_lt_w(a[0], b); return mask; } -int bn_in_range_words(const BN_ULONG *a, BN_ULONG min_inclusive, - const BN_ULONG *max_exclusive, size_t len) { +int bssl::bn_in_range_words(const BN_ULONG *a, BN_ULONG min_inclusive, + const BN_ULONG *max_exclusive, size_t len) { crypto_word_t mask = ~bn_less_than_word_mask(a, len, min_inclusive); return mask & bn_less_than_words(a, max_exclusive, len); } @@ -120,7 +127,7 @@ int bn_in_range_words(const BN_ULONG *a, BN_ULONG min_inclusive, static int bn_range_to_mask(size_t *out_words, BN_ULONG *out_mask, size_t min_inclusive, const BN_ULONG *max_exclusive, size_t len) { - // The magnitude of |max_exclusive| is assumed public. + // The magnitude of `max_exclusive` is assumed public. size_t words = len; while (words > 0 && max_exclusive[words - 1] == 0) { words--; @@ -130,7 +137,7 @@ static int bn_range_to_mask(size_t *out_words, BN_ULONG *out_mask, return 0; } BN_ULONG mask = max_exclusive[words - 1]; - // This sets all bits in |mask| below the most significant bit. + // This sets all bits in `mask` below the most significant bit. mask |= mask >> 1; mask |= mask >> 2; mask |= mask >> 4; @@ -145,15 +152,15 @@ static int bn_range_to_mask(size_t *out_words, BN_ULONG *out_mask, return 1; } -int bn_rand_range_words(BN_ULONG *out, BN_ULONG min_inclusive, - const BN_ULONG *max_exclusive, size_t len, - const uint8_t additional_data[32]) { - // This function implements the equivalent of steps 4 through 7 of FIPS 186-4 - // appendices B.4.2 and B.5.2. When called in those contexts, |max_exclusive| - // is n and |min_inclusive| is one. +int bssl::bn_rand_range_words(BN_ULONG *out, BN_ULONG min_inclusive, + const BN_ULONG *max_exclusive, size_t len, + const uint8_t additional_data[32]) { + // This function implements the equivalent of steps 1 through 4 of FIPS 186-5 + // appendices A.2.2 and A.3.2, repeating the process on failure. When called + // in those contexts, `max_exclusive` is n and `min_inclusive` is one. - // Compute the bit length of |max_exclusive| (step 1), in terms of a number of - // |words| worth of entropy to fill and a mask of bits to clear in the top + // Compute the bit length of `max_exclusive` (step 1), in terms of a number of + // `words` worth of entropy to fill and a mask of bits to clear in the top // word. size_t words; BN_ULONG mask; @@ -171,21 +178,19 @@ int bn_rand_range_words(BN_ULONG *out, BN_ULONG min_inclusive, return 0; } - // Steps 4 and 5. Use |words| and |mask| together to obtain a string of N - // bits, where N is the bit length of |max_exclusive|. + // Use `words` and `mask` together to obtain a string of N bits, where N is + // the bit length of `max_exclusive`. FIPS_service_indicator_lock_state(); BCM_rand_bytes_with_additional_data( (uint8_t *)out, words * sizeof(BN_ULONG), additional_data); FIPS_service_indicator_unlock_state(); out[words - 1] &= mask; - // If out >= max_exclusive or out < min_inclusive, retry. This implements - // the equivalent of steps 6 and 7 without leaking the value of |out|. The - // result of this comparison may be treated as public. It only reveals how - // many attempts were needed before we found a value in range. This is - // independent of the final secret output, and has a distribution that - // depends only on |min_inclusive| and |max_exclusive|, both of which are - // public. + // If out >= max_exclusive or out < min_inclusive, retry. The result of this + // comparison may be treated as public. It only reveals how many attempts + // were needed before we found a value in range. This is independent of the + // final secret output, and has a distribution that depends only on + // `min_inclusive` and `max_exclusive`, both of which are public. } while (!constant_time_declassify_int( bn_in_range_words(out, min_inclusive, max_exclusive, words))); return 1; @@ -205,8 +210,9 @@ int BN_rand_range_ex(BIGNUM *r, BN_ULONG min_inclusive, return 1; } -int bn_rand_secret_range(BIGNUM *r, int *out_is_uniform, BN_ULONG min_inclusive, - const BIGNUM *max_exclusive) { +int bssl::bn_rand_secret_range(BIGNUM *r, int *out_is_uniform, + BN_ULONG min_inclusive, + const BIGNUM *max_exclusive) { size_t words; BN_ULONG mask; if (!bn_range_to_mask(&words, &mask, min_inclusive, max_exclusive->d, diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/rsaz_exp.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/rsaz_exp.cc.inc index 329d4572..2340a53f 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/rsaz_exp.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/rsaz_exp.cc.inc @@ -1,16 +1,21 @@ -/* - * Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved. - * Copyright (c) 2012, Intel Corporation. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - * - * Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) - * (1) Intel Corporation, Israel Development Center, Haifa, Israel - * (2) University of Haifa, Israel - */ +// Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright (c) 2012, Intel Corporation. All Rights Reserved. +// +// 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. +// +// Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) +// (1) Intel Corporation, Israel Development Center, Haifa, Israel +// (2) University of Haifa, Israel #include "rsaz_exp.h" @@ -24,6 +29,8 @@ #include "../../internal.h" +using namespace bssl; + // rsaz_one is 1 in RSAZ's representation. alignas(64) static const BN_ULONG rsaz_one[40] = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -34,18 +41,18 @@ alignas(64) static const BN_ULONG rsaz_two80[40] = { 0, 0, 1 << 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; -void RSAZ_1024_mod_exp_avx2(BN_ULONG result_norm[16], - const BN_ULONG base_norm[16], - const BN_ULONG exponent[16], - const BN_ULONG m_norm[16], const BN_ULONG RR[16], - BN_ULONG k0, - BN_ULONG storage[MOD_EXP_CTIME_STORAGE_LEN]) { +void bssl::RSAZ_1024_mod_exp_avx2(BN_ULONG result_norm[16], + const BN_ULONG base_norm[16], + const BN_ULONG exponent[16], + const BN_ULONG m_norm[16], + const BN_ULONG RR[16], BN_ULONG k0, + BN_ULONG storage[MOD_EXP_CTIME_STORAGE_LEN]) { static_assert(MOD_EXP_CTIME_ALIGN % 64 == 0, "MOD_EXP_CTIME_ALIGN is too small"); assert((uintptr_t)storage % 64 == 0); BN_ULONG *a_inv, *m, *result, *table_s = storage + 40 * 3, *R2 = table_s; - // Note |R2| aliases |table_s|. + // Note `R2` aliases `table_s`. if (((((uintptr_t)storage & 4095) + 320) >> 12) != 0) { result = storage; a_inv = storage + 40; @@ -60,33 +67,33 @@ void RSAZ_1024_mod_exp_avx2(BN_ULONG result_norm[16], rsaz_1024_norm2red_avx2(a_inv, base_norm); rsaz_1024_norm2red_avx2(R2, RR); - // Convert |R2| from the usual radix, giving R = 2^1024, to RSAZ's radix, + // Convert `R2` from the usual radix, giving R = 2^1024, to RSAZ's radix, // giving R = 2^(36*29) = 2^1044. rsaz_1024_mul_avx2(R2, R2, R2, m, k0); // R2 = 2^2048 * 2^2048 / 2^1044 = 2^3052 rsaz_1024_mul_avx2(R2, R2, rsaz_two80, m, k0); - // R2 = 2^3052 * 2^80 / 2^1044 = 2^2088 = (2^1044)^2 + // R2 = 2^3052 * 2^80 / 2^1044 = 2^2088 = (2^1044)² // table[0] = 1 - // table[1] = a_inv^1 + // table[1] = a_inv¹ rsaz_1024_mul_avx2(result, R2, rsaz_one, m, k0); rsaz_1024_mul_avx2(a_inv, a_inv, R2, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 0); rsaz_1024_scatter5_avx2(table_s, a_inv, 1); - // table[2] = a_inv^2 + // table[2] = a_inv² rsaz_1024_sqr_avx2(result, a_inv, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 2); - // table[4] = a_inv^4 + // table[4] = a_inv⁴ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 4); - // table[8] = a_inv^8 + // table[8] = a_inv⁸ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 8); // table[16] = a_inv^16 rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 16); for (int i = 3; i < 32; i += 2) { - // table[i] = table[i-1] * a_inv = a_inv^i + // table[i] = table[i-1] * a_inv = a_invⁱ rsaz_1024_gather5_avx2(result, table_s, i - 1); rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, i); @@ -112,7 +119,7 @@ void RSAZ_1024_mod_exp_avx2(BN_ULONG result_norm[16], wvalue = (wvalue >> (index % 8)) & 31; index -= 5; - rsaz_1024_gather5_avx2(a_inv, table_s, wvalue); // Borrow |a_inv|. + rsaz_1024_gather5_avx2(a_inv, table_s, wvalue); // Borrow `a_inv`. rsaz_1024_mul_avx2(result, result, a_inv, m, k0); } @@ -121,7 +128,7 @@ void RSAZ_1024_mod_exp_avx2(BN_ULONG result_norm[16], wvalue = p_str[0] & 15; - rsaz_1024_gather5_avx2(a_inv, table_s, wvalue); // Borrow |a_inv|. + rsaz_1024_gather5_avx2(a_inv, table_s, wvalue); // Borrow `a_inv`. rsaz_1024_mul_avx2(result, result, a_inv, m, k0); // Convert from Montgomery. diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/rsaz_exp.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/rsaz_exp.h index 6999a566..d3843013 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/rsaz_exp.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/rsaz_exp.h @@ -1,54 +1,57 @@ -/* - * Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved. - * Copyright (c) 2012, Intel Corporation. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - * - * Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) - * (1) Intel Corporation, Israel Development Center, Haifa, Israel - * (2) University of Haifa, Israel - */ +// Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright (c) 2012, Intel Corporation. All Rights Reserved. +// +// 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. +// +// Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) +// (1) Intel Corporation, Israel Development Center, Haifa, Israel +// (2) University of Haifa, Israel -#ifndef OPENSSL_HEADER_BN_RSAZ_EXP_H -#define OPENSSL_HEADER_BN_RSAZ_EXP_H +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_BN_RSAZ_EXP_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_BN_RSAZ_EXP_H #include -#include "internal.h" #include "../../internal.h" +#include "internal.h" -#if defined(__cplusplus) -extern "C" { -#endif + +BSSL_NAMESPACE_BEGIN #if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) #define RSAZ_ENABLED - -// RSAZ_1024_mod_exp_avx2 sets |result| to |base_norm| raised to |exponent| -// modulo |m_norm|. |base_norm| must be fully-reduced and |exponent| must have -// the high bit set (it is 1024 bits wide). |RR| and |k0| must be |RR| and |n0|, -// respectively, extracted from |m_norm|'s |BN_MONT_CTX|. |storage_words| is a -// temporary buffer that must be aligned to |MOD_EXP_CTIME_ALIGN| bytes. +// RSAZ_1024_mod_exp_avx2 sets `result` to `base_norm` raised to `exponent` +// modulo `m_norm`. `base_norm` must be fully-reduced and `exponent` must have +// the high bit set (it is 1024 bits wide). `RR` and `k0` must be `RR` and `n0`, +// respectively, extracted from `m_norm`'s `BN_MONT_CTX`. `storage_words` is a +// temporary buffer that must be aligned to `MOD_EXP_CTIME_ALIGN` bytes. void RSAZ_1024_mod_exp_avx2(BN_ULONG result[16], const BN_ULONG base_norm[16], const BN_ULONG exponent[16], const BN_ULONG m_norm[16], const BN_ULONG RR[16], BN_ULONG k0, BN_ULONG storage_words[MOD_EXP_CTIME_STORAGE_LEN]); -inline int rsaz_avx2_capable(void) { return CRYPTO_is_AVX2_capable(); } +inline int rsaz_avx2_capable() { return bssl::CRYPTO_is_AVX2_capable(); } -inline int rsaz_avx2_preferred(void) { - if (CRYPTO_is_BMI1_capable() && CRYPTO_is_BMI2_capable() && - CRYPTO_is_ADX_capable()) { +inline int rsaz_avx2_preferred() { + if (bssl::CRYPTO_is_BMI1_capable() && bssl::CRYPTO_is_BMI2_capable() && + bssl::CRYPTO_is_ADX_capable()) { // If BMI1, BMI2, and ADX are available, x86_64-mont5.pl is faster. See the // .Lmulx4x_enter and .Lpowerx5_enter branches. return 0; } - return CRYPTO_is_AVX2_capable(); + return bssl::CRYPTO_is_AVX2_capable(); } @@ -59,48 +62,48 @@ inline int rsaz_avx2_preferred(void) { // // See crypto/bn/asm/rsaz-avx2.pl for further details. -// rsaz_1024_norm2red_avx2 converts |norm| from |BIGNUM| to RSAZ representation -// and writes the result to |red|. -void rsaz_1024_norm2red_avx2(BN_ULONG red[40], const BN_ULONG norm[16]); +// rsaz_1024_norm2red_avx2 converts `norm` from `BIGNUM` to RSAZ representation +// and writes the result to `red`. +extern "C" void rsaz_1024_norm2red_avx2(BN_ULONG red[40], + const BN_ULONG norm[16]); -// rsaz_1024_mul_avx2 computes |a| * |b| mod |n| and writes the result to |ret|. -// Inputs and outputs are in Montgomery form, using RSAZ's representation. |k| -// is -|n|^-1 mod 2^64 or |n0| from |BN_MONT_CTX|. -void rsaz_1024_mul_avx2(BN_ULONG ret[40], const BN_ULONG a[40], - const BN_ULONG b[40], const BN_ULONG n[40], BN_ULONG k); +// rsaz_1024_mul_avx2 computes `a` * `b` mod `n` and writes the result to `ret`. +// Inputs and outputs are in Montgomery form, using RSAZ's representation. `k` +// is -`n`^-1 mod 2^64 or `n0` from `BN_MONT_CTX`. +extern "C" void rsaz_1024_mul_avx2(BN_ULONG ret[40], const BN_ULONG a[40], + const BN_ULONG b[40], const BN_ULONG n[40], + BN_ULONG k); -// rsaz_1024_mul_avx2 computes |a|^(2*|count|) mod |n| and writes the result to -// |ret|. Inputs and outputs are in Montgomery form, using RSAZ's -// representation. |k| is -|n|^-1 mod 2^64 or |n0| from |BN_MONT_CTX|. -void rsaz_1024_sqr_avx2(BN_ULONG ret[40], const BN_ULONG a[40], - const BN_ULONG n[40], BN_ULONG k, int count); +// rsaz_1024_mul_avx2 computes `a`^(2*`count`) mod `n` and writes the result to +// `ret`. Inputs and outputs are in Montgomery form, using RSAZ's +// representation. `k` is -`n`^-1 mod 2^64 or `n0` from `BN_MONT_CTX`. +extern "C" void rsaz_1024_sqr_avx2(BN_ULONG ret[40], const BN_ULONG a[40], + const BN_ULONG n[40], BN_ULONG k, int count); -// rsaz_1024_scatter5_avx2 stores |val| at index |i| of |tbl|. |i| must be +// rsaz_1024_scatter5_avx2 stores `val` at index `i` of `tbl`. `i` must be // positive and at most 31. It is treated as public. Note the table only uses 18 -// |BN_ULONG|s per entry instead of 40. It packs two 29-bit limbs into each -// |BN_ULONG| and only stores 36 limbs rather than the padded 40. -void rsaz_1024_scatter5_avx2(BN_ULONG tbl[32 * 18], const BN_ULONG val[40], - int i); +// `BN_ULONG`s per entry instead of 40. It packs two 29-bit limbs into each +// `BN_ULONG` and only stores 36 limbs rather than the padded 40. +extern "C" void rsaz_1024_scatter5_avx2(BN_ULONG tbl[32 * 18], + const BN_ULONG val[40], int i); -// rsaz_1024_gather5_avx2 loads index |i| of |tbl| and writes it to |val|. |i| -// must be positive and at most 31. It is treated as secret. |tbl| must be +// rsaz_1024_gather5_avx2 loads index `i` of `tbl` and writes it to `val`. `i` +// must be positive and at most 31. It is treated as secret. `tbl` must be // aligned to 32 bytes. -void rsaz_1024_gather5_avx2(BN_ULONG val[40], const BN_ULONG tbl[32 * 18], - int i); +extern "C" void rsaz_1024_gather5_avx2(BN_ULONG val[40], + const BN_ULONG tbl[32 * 18], int i); -// rsaz_1024_red2norm_avx2 converts |red| from RSAZ to |BIGNUM| representation -// and writes the result to |norm|. The result will be <= the modulus. +// rsaz_1024_red2norm_avx2 converts `red` from RSAZ to `BIGNUM` representation +// and writes the result to `norm`. The result will be <= the modulus. // -// WARNING: The result of this operation may not be fully reduced. |norm| may be +// WARNING: The result of this operation may not be fully reduced. `norm` may be // the modulus instead of zero. This function should be followed by a call to -// |bn_reduce_once|. -void rsaz_1024_red2norm_avx2(BN_ULONG norm[16], const BN_ULONG red[40]); - +// `bn_reduce_once`. +extern "C" void rsaz_1024_red2norm_avx2(BN_ULONG norm[16], + const BN_ULONG red[40]); #endif // !OPENSSL_NO_ASM && OPENSSL_X86_64 -#if defined(__cplusplus) -} // extern "C" -#endif +BSSL_NAMESPACE_END -#endif // OPENSSL_HEADER_BN_RSAZ_EXP_H +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_BN_RSAZ_EXP_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/shift.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/shift.cc.inc index b2088517..983d31d9 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/shift.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/shift.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,6 +22,8 @@ #include "internal.h" +using namespace bssl; + int BN_lshift(BIGNUM *r, const BIGNUM *a, int n) { int i, nw, lb, rb; BN_ULONG *t, *f; @@ -86,8 +93,8 @@ int BN_lshift1(BIGNUM *r, const BIGNUM *a) { return 1; } -void bn_rshift_words(BN_ULONG *r, const BN_ULONG *a, unsigned shift, - size_t num) { +void bssl::bn_rshift_words(BN_ULONG *r, const BN_ULONG *a, unsigned shift, + size_t num) { unsigned shift_bits = shift % BN_BITS2; size_t shift_words = shift / BN_BITS2; if (shift_words >= num) { @@ -122,14 +129,13 @@ int BN_rshift(BIGNUM *r, const BIGNUM *a, int n) { return 1; } -int bn_rshift_secret_shift(BIGNUM *r, const BIGNUM *a, unsigned n, - BN_CTX *ctx) { - int ret = 0; - BN_CTX_start(ctx); +int bssl::bn_rshift_secret_shift(BIGNUM *r, const BIGNUM *a, unsigned n, + BN_CTX *ctx) { + BN_CTXScope scope(ctx); BIGNUM *tmp = BN_CTX_get(ctx); unsigned max_bits; - if (tmp == NULL || !BN_copy(r, a) || !bn_wexpand(tmp, r->width)) { - goto err; + if (tmp == nullptr || !BN_copy(r, a) || !bn_wexpand(tmp, r->width)) { + return 0; } // Shift conditionally by powers of two. @@ -142,14 +148,10 @@ int bn_rshift_secret_shift(BIGNUM *r, const BIGNUM *a, unsigned n, r->d /* ignore shift */, r->width); } - ret = 1; - -err: - BN_CTX_end(ctx); - return ret; + return 1; } -void bn_rshift1_words(BN_ULONG *r, const BN_ULONG *a, size_t num) { +void bssl::bn_rshift1_words(BN_ULONG *r, const BN_ULONG *a, size_t num) { if (num == 0) { return; } @@ -210,7 +212,7 @@ int BN_clear_bit(BIGNUM *a, int n) { return 1; } -int bn_is_bit_set_words(const BN_ULONG *a, size_t num, size_t bit) { +int bssl::bn_is_bit_set_words(const BN_ULONG *a, size_t num, size_t bit) { size_t i = bit / BN_BITS2; size_t j = bit % BN_BITS2; if (i >= num) { @@ -261,7 +263,7 @@ static int bn_count_low_zero_bits_word(BN_ULONG l) { int bits = 0; #if BN_BITS2 > 32 - // Check if the lower half of |x| are all zero. + // Check if the lower half of `x` are all zero. mask = constant_time_is_zero_w(l << (BN_BITS2 - 32)); // If the lower half is all zeros, it is included in the bit count and we // count the upper half. Otherwise, we count the lower half. @@ -309,7 +311,7 @@ int BN_count_low_zero_bits(const BIGNUM *bn) { ret |= first_nonzero & (i * BN_BITS2 + bits); } - // If got to the end of |bn| and saw no non-zero words, |bn| is zero. |ret| + // If got to the end of `bn` and saw no non-zero words, `bn` is zero. `ret` // will then remain zero. return ret; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/sqrt.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/sqrt.cc.inc index 0f946a8c..219d1518 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/sqrt.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/bn/sqrt.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,6 +19,8 @@ #include "internal.h" +using namespace bssl; + BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { // Compute a square root of |a| mod |p| using the Tonelli/Shanks algorithm // (cf. Henri Cohen, "A Course in Algebraic Computational Number Theory", @@ -27,52 +34,50 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { if (!BN_is_odd(p) || BN_abs_is_word(p, 1)) { if (BN_abs_is_word(p, 2)) { - if (ret == NULL) { + if (ret == nullptr) { ret = BN_new(); } - if (ret == NULL || - !BN_set_word(ret, BN_is_bit_set(a, 0))) { + if (ret == nullptr || !BN_set_word(ret, BN_is_bit_set(a, 0))) { if (ret != in) { BN_free(ret); } - return NULL; + return nullptr; } return ret; } OPENSSL_PUT_ERROR(BN, BN_R_P_IS_NOT_PRIME); - return NULL; + return nullptr; } if (BN_is_zero(a) || BN_is_one(a)) { - if (ret == NULL) { + if (ret == nullptr) { ret = BN_new(); } - if (ret == NULL || - !BN_set_word(ret, BN_is_one(a))) { + if (ret == nullptr || !BN_set_word(ret, BN_is_one(a))) { if (ret != in) { BN_free(ret); } - return NULL; + return nullptr; } return ret; } - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); A = BN_CTX_get(ctx); b = BN_CTX_get(ctx); q = BN_CTX_get(ctx); t = BN_CTX_get(ctx); x = BN_CTX_get(ctx); y = BN_CTX_get(ctx); - if (y == NULL) { + if (y == nullptr) { goto end; } - if (ret == NULL) { + if (ret == nullptr) { ret = BN_new(); } - if (ret == NULL) { + if (ret == nullptr) { goto end; } @@ -81,7 +86,7 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { goto end; } - // now write |p| - 1 as 2^e*q where q is odd + // now write |p| - 1 as 2ᵉ⋅q where q is odd e = 1; while (!BN_is_bit_set(p, e)) { e++; @@ -99,8 +104,7 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { goto end; } q->neg = 0; - if (!BN_add_word(q, 1) || - !BN_mod_exp_mont(ret, A, q, p, ctx, NULL)) { + if (!BN_add_word(q, 1) || !BN_mod_exp_mont(ret, A, q, p, ctx, nullptr)) { goto end; } err = 0; @@ -111,23 +115,23 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { // |p| == 5 (mod 8) // // In this case 2 is always a non-square since - // Legendre(2,p) = (-1)^((p^2-1)/8) for any odd prime. - // So if a really is a square, then 2*a is a non-square. + // Legendre(2,p) = (-1)^((p²-1)/8) for any odd prime. + // So if a really is a square, then 2⋅a is a non-square. // Thus for - // b := (2*a)^((|p|-5)/8), - // i := (2*a)*b^2 + // b := (2⋅a)^((|p|-5)/8), + // i := (2⋅a)⋅b² // we have - // i^2 = (2*a)^((1 + (|p|-5)/4)*2) - // = (2*a)^((p-1)/2) - // = -1; + // i² = (2⋅a)^((1 + (|p|-5)/4)⋅2) + // = (2⋅a)^((p-1)/2) + // = -1; // so if we set - // x := a*b*(i-1), + // x := a⋅b⋅(i-1), // then - // x^2 = a^2 * b^2 * (i^2 - 2*i + 1) - // = a^2 * b^2 * (-2*i) - // = a*(-i)*(2*a*b^2) - // = a*(-i)*i - // = a. + // x² = a² ⋅ b² ⋅ (i² - 2⋅i + 1) + // = a² ⋅ b² ⋅ (-2⋅i) + // = a⋅(-i)⋅(2⋅a⋅b²) + // = a⋅(-i)⋅i + // = a. // // (This is due to A.O.L. Atkin, // neg = 0; - if (!BN_mod_exp_mont(b, t, q, p, ctx, NULL)) { + if (!BN_mod_exp_mont(b, t, q, p, ctx, nullptr)) { goto end; } - // y := b^2 + // y := b² if (!BN_mod_sqr(y, b, p, ctx)) { goto end; } - // t := (2*a)*b^2 - 1 + // t := (2*a)*b² - 1 if (!BN_mod_mul(t, t, y, p, ctx) || !BN_sub_word(t, 1)) { goto end; @@ -187,20 +191,9 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { goto end; } } else { - if (!BN_pseudo_rand(y, BN_num_bits(p), 0, 0)) { + if (!BN_rand_range_ex(y, 22, p)) { goto end; } - if (BN_ucmp(y, p) >= 0) { - if (BN_usub(y, y, p)) { - goto end; - } - } - // now 0 <= y < |p| - if (BN_is_zero(y)) { - if (!BN_set_word(y, i)) { - goto end; - } - } } r = bn_jacobi(y, q, ctx); // here 'q' is |p| @@ -229,8 +222,8 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { } // Now that we have some non-square, we can find an element - // of order 2^e by computing its q'th power. - if (!BN_mod_exp_mont(y, y, q, p, ctx, NULL)) { + // of order 2ᵉ by computing its q'th power. + if (!BN_mod_exp_mont(y, y, q, p, ctx, nullptr)) { goto end; } if (BN_is_one(y)) { @@ -239,7 +232,7 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { } // Now we know that (if p is indeed prime) there is an integer - // k, 0 <= k < 2^e, such that + // k, 0 <= k < 2ᵉ, such that // // a^q * y^k == 1 (mod p). // @@ -250,7 +243,7 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { // // and it satisfies // - // X^2 = a^q * a * y^k + // X² = a^q * a * y^k // = a, // // so it is the square root that we are looking for. @@ -261,7 +254,7 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { } // x := a^((q-1)/2) - if (BN_is_zero(t)) { // special case: p = 2^e + 1 + if (BN_is_zero(t)) { // special case: p = 2ᵉ + 1 if (!BN_nnmod(t, A, p, ctx)) { goto end; } @@ -274,7 +267,7 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { goto end; } } else { - if (!BN_mod_exp_mont(x, A, t, p, ctx, NULL)) { + if (!BN_mod_exp_mont(x, A, t, p, ctx, nullptr)) { goto end; } if (BN_is_zero(x)) { @@ -285,7 +278,7 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { } } - // b := a*x^2 (= a^q) + // b := a*x² (= a^q) if (!BN_mod_sqr(b, x, p, ctx) || !BN_mod_mul(b, b, A, p, ctx)) { goto end; @@ -371,84 +364,7 @@ end: if (ret != in) { BN_clear_free(ret); } - ret = NULL; + ret = nullptr; } - BN_CTX_end(ctx); return ret; } - -int BN_sqrt(BIGNUM *out_sqrt, const BIGNUM *in, BN_CTX *ctx) { - BIGNUM *estimate, *tmp, *delta, *last_delta, *tmp2; - int ok = 0, last_delta_valid = 0; - - if (in->neg) { - OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER); - return 0; - } - if (BN_is_zero(in)) { - BN_zero(out_sqrt); - return 1; - } - - BN_CTX_start(ctx); - if (out_sqrt == in) { - estimate = BN_CTX_get(ctx); - } else { - estimate = out_sqrt; - } - tmp = BN_CTX_get(ctx); - last_delta = BN_CTX_get(ctx); - delta = BN_CTX_get(ctx); - if (estimate == NULL || tmp == NULL || last_delta == NULL || delta == NULL) { - goto err; - } - - // We estimate that the square root of an n-bit number is 2^{n/2}. - if (!BN_lshift(estimate, BN_value_one(), BN_num_bits(in)/2)) { - goto err; - } - - // This is Newton's method for finding a root of the equation |estimate|^2 - - // |in| = 0. - for (;;) { - // |estimate| = 1/2 * (|estimate| + |in|/|estimate|) - if (!BN_div(tmp, NULL, in, estimate, ctx) || - !BN_add(tmp, tmp, estimate) || - !BN_rshift1(estimate, tmp) || - // |tmp| = |estimate|^2 - !BN_sqr(tmp, estimate, ctx) || - // |delta| = |in| - |tmp| - !BN_sub(delta, in, tmp)) { - OPENSSL_PUT_ERROR(BN, ERR_R_BN_LIB); - goto err; - } - - delta->neg = 0; - // The difference between |in| and |estimate| squared is required to always - // decrease. This ensures that the loop always terminates, but I don't have - // a proof that it always finds the square root for a given square. - if (last_delta_valid && BN_cmp(delta, last_delta) >= 0) { - break; - } - - last_delta_valid = 1; - - tmp2 = last_delta; - last_delta = delta; - delta = tmp2; - } - - if (BN_cmp(tmp, in) != 0) { - OPENSSL_PUT_ERROR(BN, BN_R_NOT_A_SQUARE); - goto err; - } - - ok = 1; - -err: - if (ok && out_sqrt == in && !BN_copy(out_sqrt, estimate)) { - ok = 0; - } - BN_CTX_end(ctx); - return ok; -} diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/aead.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/aead.cc.inc index e5e008f3..d14fe7f9 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/aead.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/aead.cc.inc @@ -1,30 +1,36 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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 "../../internal.h" +#include "../../mem_internal.h" #include "internal.h" +using namespace bssl; + size_t EVP_AEAD_key_length(const EVP_AEAD *aead) { return aead->key_len; } size_t EVP_AEAD_nonce_length(const EVP_AEAD *aead) { return aead->nonce_len; } @@ -39,27 +45,26 @@ void EVP_AEAD_CTX_zero(EVP_AEAD_CTX *ctx) { EVP_AEAD_CTX *EVP_AEAD_CTX_new(const EVP_AEAD *aead, const uint8_t *key, size_t key_len, size_t tag_len) { - EVP_AEAD_CTX *ctx = - reinterpret_cast(OPENSSL_malloc(sizeof(EVP_AEAD_CTX))); + EVP_AEAD_CTX *ctx = New(); if (!ctx) { - return NULL; + return nullptr; } EVP_AEAD_CTX_zero(ctx); - if (EVP_AEAD_CTX_init(ctx, aead, key, key_len, tag_len, NULL)) { + if (EVP_AEAD_CTX_init(ctx, aead, key, key_len, tag_len, nullptr)) { return ctx; } EVP_AEAD_CTX_free(ctx); - return NULL; + return nullptr; } void EVP_AEAD_CTX_free(EVP_AEAD_CTX *ctx) { - if (ctx == NULL) { + if (ctx == nullptr) { return; } EVP_AEAD_CTX_cleanup(ctx); - OPENSSL_free(ctx); + Delete(ctx); } int EVP_AEAD_CTX_init(EVP_AEAD_CTX *ctx, const EVP_AEAD *aead, @@ -67,7 +72,7 @@ int EVP_AEAD_CTX_init(EVP_AEAD_CTX *ctx, const EVP_AEAD *aead, ENGINE *impl) { if (!aead->init) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_NO_DIRECTION_SET); - ctx->aead = NULL; + ctx->aead = nullptr; return 0; } return EVP_AEAD_CTX_init_with_direction(ctx, aead, key, key_len, tag_len, @@ -80,7 +85,7 @@ int EVP_AEAD_CTX_init_with_direction(EVP_AEAD_CTX *ctx, const EVP_AEAD *aead, enum evp_aead_direction_t dir) { if (key_len != aead->key_len) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_KEY_SIZE); - ctx->aead = NULL; + ctx->aead = nullptr; return 0; } @@ -94,22 +99,22 @@ int EVP_AEAD_CTX_init_with_direction(EVP_AEAD_CTX *ctx, const EVP_AEAD *aead, } if (!ok) { - ctx->aead = NULL; + ctx->aead = nullptr; } return ok; } void EVP_AEAD_CTX_cleanup(EVP_AEAD_CTX *ctx) { - if (ctx->aead == NULL) { + if (ctx->aead == nullptr) { return; } ctx->aead->cleanup(ctx); - ctx->aead = NULL; + ctx->aead = nullptr; } -// check_alias returns 1 if |out| is compatible with |in| and 0 otherwise. If -// |in| and |out| alias, we require that |in| == |out|. +// check_alias returns 1 if `out` is compatible with `in` and 0 otherwise. If +// `in` and `out` alias, we require that `in` == `out`. static int check_alias(const uint8_t *in, size_t in_len, const uint8_t *out, size_t out_len) { if (!buffers_alias(in, in_len, out, out_len)) { @@ -123,35 +128,36 @@ int EVP_AEAD_CTX_seal(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len, size_t max_out_len, const uint8_t *nonce, size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *ad, size_t ad_len) { - if (in_len + ctx->aead->overhead < in_len /* overflow */) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); - goto error; - } + bool ok = false; + Cleanup cleanup([&] { + if (!ok) { + // In the event of an error, clear the output buffer so that a caller + // that doesn't check the return value doesn't send raw data. + OPENSSL_memset(out, 0, max_out_len); + *out_len = 0; + } + }); if (max_out_len < in_len) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); - goto error; + return 0; } - if (!check_alias(in, in_len, out, max_out_len)) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_OUTPUT_ALIASES_INPUT); - goto error; + CRYPTO_IOVEC iovec[1]; + iovec[0].in = in; + iovec[0].out = out; + iovec[0].len = in_len; + CRYPTO_IVEC aadvec[1]; + aadvec[0].in = ad; + aadvec[0].len = ad_len; + if (!EVP_AEAD_CTX_sealv(ctx, iovec, 1, out + in_len, out_len, + max_out_len - in_len, nonce, nonce_len, aadvec, 1)) { + *out_len = 0; + return 0; } - - size_t out_tag_len; - if (ctx->aead->seal_scatter(ctx, out, out + in_len, &out_tag_len, - max_out_len - in_len, nonce, nonce_len, in, - in_len, NULL, 0, ad, ad_len)) { - *out_len = in_len + out_tag_len; - return 1; - } - -error: - // In the event of an error, clear the output buffer so that a caller - // that doesn't check the return value doesn't send raw data. - OPENSSL_memset(out, 0, max_out_len); - *out_len = 0; - return 0; + *out_len += in_len; + ok = true; + return 1; } int EVP_AEAD_CTX_seal_scatter(const EVP_AEAD_CTX *ctx, uint8_t *out, @@ -161,31 +167,196 @@ int EVP_AEAD_CTX_seal_scatter(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t in_len, const uint8_t *extra_in, size_t extra_in_len, const uint8_t *ad, size_t ad_len) { - // |in| and |out| may alias exactly, |out_tag| may not alias. - if (!check_alias(in, in_len, out, in_len) || - buffers_alias(out, in_len, out_tag, max_out_tag_len) || - buffers_alias(in, in_len, out_tag, max_out_tag_len)) { + bool ok = false; + Cleanup cleanup([&] { + if (!ok) { + // In the event of an error, clear the output buffer so that a caller + // that doesn't check the return value doesn't send raw data. + OPENSSL_memset(out, 0, in_len); + OPENSSL_memset(out_tag, 0, max_out_tag_len); + *out_tag_len = 0; + } + }); + + // `out_tag` contains both the encryption of `extra_in` and the tag. + Span out_tag_span(out_tag, max_out_tag_len); + if (out_tag_span.size() < extra_in_len) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); + return 0; + } + Span extra_out = out_tag_span.first(extra_in_len); + Span tag_only_out = out_tag_span.subspan(extra_in_len); + + CRYPTO_IOVEC iovec[2]; + iovec[0].in = in; + iovec[0].out = out; + iovec[0].len = in_len; + iovec[1].in = extra_in; + iovec[1].out = extra_out.data(); + iovec[1].len = extra_in_len; + CRYPTO_IVEC aadvec[1]; + aadvec[0].in = ad; + aadvec[0].len = ad_len; + if (!EVP_AEAD_CTX_sealv(ctx, iovec, extra_in_len ? 2 : 1, tag_only_out.data(), + out_tag_len, tag_only_out.size(), nonce, nonce_len, + aadvec, 1)) { + *out_tag_len = 0; + return 0; + } + *out_tag_len += extra_in_len; + ok = true; + return 1; +} + +static bool check_iovec_internal_alias(Span iovecs) { + for (size_t i = 0; i < iovecs.size(); ++i) { + // Same index check. + if (!check_alias(iovecs[i].in, iovecs[i].len, iovecs[i].out, + iovecs[i].len)) { + return false; + } +#if !defined(NDEBUG) + // Unrealistic cases; they'd be harmful but also extremely unlikely anyone + // will ever get those wrong. Thus skip them in release builds. + for (size_t j = i + 1; j < iovecs.size(); ++j) { + if (buffers_alias(iovecs[i].in, iovecs[i].len, // + iovecs[j].out, iovecs[j].len) || + buffers_alias(iovecs[i].out, iovecs[i].len, // + iovecs[j].in, iovecs[j].len) || + buffers_alias(iovecs[i].out, iovecs[i].len, // + iovecs[j].out, iovecs[j].len)) { + return false; + } + } +#endif + } + return true; +} + +#if !defined(NDEBUG) +static bool check_ivec_buf_alias(Span ivecs, + const uint8_t *buf, size_t buf_len) { + for (const CRYPTO_IVEC &ivec : ivecs) { + if (buffers_alias(ivec.in, ivec.len, buf, buf_len)) { + return false; + } + } + return true; +} + +static bool check_iovec_out_ivec_alias(Span iovecs, + Span ivecs) { + for (const CRYPTO_IOVEC &iovec : iovecs) { + if (!check_ivec_buf_alias(ivecs, iovec.out, iovec.len)) { + return false; + } + } + return true; +} + +static bool check_iovec_buf_alias(Span iovecs, + const uint8_t *buf, size_t buf_len) { + for (const CRYPTO_IOVEC &iovec : iovecs) { + if (buffers_alias(iovec.in, iovec.len, buf, buf_len)) { + return false; + } + if (buffers_alias(iovec.out, iovec.len, buf, buf_len)) { + return false; + } + } + return true; +} + +static bool check_iovec_out_buf_alias(Span iovecs, + const uint8_t *buf, size_t buf_len) { + for (const CRYPTO_IOVEC &iovec : iovecs) { + if (buffers_alias(iovec.out, iovec.len, buf, buf_len)) { + return false; + } + } + return true; +} +#endif + +static bool check_iovec_alias(Span iovecs, + Span aadvecs, + const uint8_t *out, size_t out_len, + const uint8_t *in1, size_t in1_len, + const uint8_t *in2, size_t in2_len) { + return +#if !defined(NDEBUG) + // Unrealistic cases; they'd be harmful but also extremely unlikely anyone + // will ever get those wrong. Thus skip them in release builds. + // + // iovec.out <-> aadvec. + check_iovec_out_ivec_alias(iovecs, aadvecs) && + // iovec <-> out. + check_iovec_buf_alias(iovecs, out, out_len) && + // iovec.out <-> in1. + check_iovec_out_buf_alias(iovecs, in1, in1_len) && + // iovec.out <-> in2. + check_iovec_out_buf_alias(iovecs, in2, in2_len) && + // aadvec <-> out. + check_ivec_buf_alias(aadvecs, out, out_len) && + // out <-> in1. + !buffers_alias(out, out_len, in1, in1_len) && + // out <-> in2. + !buffers_alias(out, out_len, in2, in2_len) && +#endif + // iovec <-> iovec. + check_iovec_internal_alias(iovecs); +} + +static void clear_iovec(Span iovecs) { + for (const CRYPTO_IOVEC &iovec : iovecs) { + OPENSSL_memset(iovec.out, 0, iovec.len); + } +} + +int EVP_AEAD_CTX_sealv(const EVP_AEAD_CTX *ctx, const CRYPTO_IOVEC *iovec, + size_t num_iovec, uint8_t *out_tag, size_t *out_tag_len, + size_t max_out_tag_len, const uint8_t *nonce, + size_t nonce_len, const CRYPTO_IVEC *aadvec, + size_t num_aadvec) { + Span iovecs(iovec, num_iovec); + Span aadvecs(aadvec, num_aadvec); + + bool ok = false; + Cleanup cleanup([&] { + if (!ok) { + // In the event of an error, clear the output buffer so that a caller + // that doesn't check the return value doesn't send raw data. + clear_iovec(iovecs); + OPENSSL_memset(out_tag, 0, max_out_tag_len); + *out_tag_len = 0; + } + }); + + if (!bssl::iovec::IsValid(iovecs) || !bssl::iovec::IsValid(aadvecs)) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); + return 0; + } + + // Enforce aliasing rules: no output may alias any input, with the one + // exception that an iovec member's `in` and `out` pointers may be identical + // for in-place operation. + if (!check_iovec_alias(iovecs, aadvecs, out_tag, max_out_tag_len, nonce, + nonce_len, nullptr, 0)) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_OUTPUT_ALIASES_INPUT); - goto error; + return 0; } - if (!ctx->aead->seal_scatter_supports_extra_in && extra_in_len) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_OPERATION); - goto error; + if (!ctx->aead->sealv) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_CTRL_NOT_IMPLEMENTED); + return 0; } - if (ctx->aead->seal_scatter(ctx, out, out_tag, out_tag_len, max_out_tag_len, - nonce, nonce_len, in, in_len, extra_in, - extra_in_len, ad, ad_len)) { + if (ctx->aead->sealv(ctx, iovecs, Span(out_tag, max_out_tag_len), out_tag_len, + Span(nonce, nonce_len), aadvecs)) { + ok = true; return 1; } -error: - // In the event of an error, clear the output buffer so that a caller - // that doesn't check the return value doesn't send raw data. - OPENSSL_memset(out, 0, in_len); - OPENSSL_memset(out_tag, 0, max_out_tag_len); - *out_tag_len = 0; return 0; } @@ -193,47 +364,67 @@ int EVP_AEAD_CTX_open(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len, size_t max_out_len, const uint8_t *nonce, size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *ad, size_t ad_len) { - size_t plaintext_len; - if (!check_alias(in, in_len, out, max_out_len)) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_OUTPUT_ALIASES_INPUT); - goto error; - } - - if (ctx->aead->open) { - if (!ctx->aead->open(ctx, out, out_len, max_out_len, nonce, nonce_len, in, - in_len, ad, ad_len)) { - goto error; + bool ok = false; + Cleanup cleanup([&] { + if (!ok) { + // In the event of an error, clear the output buffer so that a caller + // that doesn't check the return value doesn't try and process bad + // data. + OPENSSL_memset(out, 0, max_out_len); + *out_len = 0; } - return 1; - } + }); - // AEADs that use the default implementation of open() must set |tag_len| at - // initialization time. - assert(ctx->tag_len); + if (ctx->tag_len) { + // If the tag length is known, the caller only needs to provide enough + // space for in_len - tag_len. + if (in_len < ctx->tag_len) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); + return 0; + } + size_t plaintext_len = in_len - ctx->tag_len; + if (max_out_len < plaintext_len) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); + return 0; + } - if (in_len < ctx->tag_len) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); - goto error; - } - - plaintext_len = in_len - ctx->tag_len; - if (max_out_len < plaintext_len) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); - goto error; - } - if (EVP_AEAD_CTX_open_gather(ctx, out, nonce, nonce_len, in, plaintext_len, - in + plaintext_len, ctx->tag_len, ad, ad_len)) { + CRYPTO_IOVEC iovec[1]; + iovec[0].in = in; + iovec[0].out = out; + iovec[0].len = plaintext_len; + CRYPTO_IVEC aadvec[1]; + aadvec[0].in = ad; + aadvec[0].len = ad_len; + if (!EVP_AEAD_CTX_openv_detached(ctx, iovec, 1, nonce, nonce_len, + in + plaintext_len, ctx->tag_len, aadvec, + 1)) { + return 0; + } *out_len = plaintext_len; + ok = true; return 1; } -error: - // In the event of an error, clear the output buffer so that a caller - // that doesn't check the return value doesn't try and process bad - // data. - OPENSSL_memset(out, 0, max_out_len); - *out_len = 0; - return 0; + if (max_out_len < in_len) { + // Variable tag length AEADs need to be able to decrypt the entire + // plaintext before they can split it up. So the caller has to provide + // sufficient max_out_len for temporary data. + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); + return 0; + } + CRYPTO_IOVEC iovec[1]; + iovec[0].in = in; + iovec[0].out = out; + iovec[0].len = in_len; + CRYPTO_IVEC aadvec[1]; + aadvec[0].in = ad; + aadvec[0].len = ad_len; + if (!EVP_AEAD_CTX_openv(ctx, iovec, 1, out_len, nonce, nonce_len, aadvec, + 1)) { + return 0; + } + ok = true; + return 1; } int EVP_AEAD_CTX_open_gather(const EVP_AEAD_CTX *ctx, uint8_t *out, @@ -241,26 +432,154 @@ int EVP_AEAD_CTX_open_gather(const EVP_AEAD_CTX *ctx, uint8_t *out, const uint8_t *in, size_t in_len, const uint8_t *in_tag, size_t in_tag_len, const uint8_t *ad, size_t ad_len) { - if (!check_alias(in, in_len, out, in_len)) { + bool ok = false; + Cleanup cleanup([&] { + if (!ok) { + // In the event of an error, clear the output buffer so that a caller + // that doesn't check the return value doesn't try and process bad + // data. + OPENSSL_memset(out, 0, in_len); + } + }); + + CRYPTO_IOVEC iovec[1]; + iovec[0].in = in; + iovec[0].out = out; + iovec[0].len = in_len; + CRYPTO_IVEC aadvec[1]; + aadvec[0].in = ad; + aadvec[0].len = ad_len; + if (!EVP_AEAD_CTX_openv_detached(ctx, iovec, 1, nonce, nonce_len, in_tag, + in_tag_len, aadvec, 1)) { + return 0; + } + ok = true; + return 1; +} + +int EVP_AEAD_CTX_openv(const EVP_AEAD_CTX *ctx, const CRYPTO_IOVEC *iovec, + size_t num_iovec, size_t *out_total_bytes, + const uint8_t *nonce, size_t nonce_len, + const CRYPTO_IVEC *aadvec, size_t num_aadvec) { + Span iovecs(iovec, num_iovec); + Span aadvecs(aadvec, num_aadvec); + + bool ok = false; + Cleanup cleanup([&] { + if (!ok) { + // In the event of an error, clear the output buffer so that a caller + // that doesn't check the return value doesn't try and process bad + // data. + clear_iovec(iovecs); + *out_total_bytes = 0; + } + }); + + if (!bssl::iovec::IsValid(iovecs) || !bssl::iovec::IsValid(aadvecs)) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); + return 0; + } + + // Enforce aliasing rules: no output may alias any input, with the one + // exception that an iovec member's `in` and `out` pointers may be identical + // for in-place operation. + if (!check_iovec_alias(iovecs, aadvecs, nullptr, 0, nonce, nonce_len, nullptr, + 0)) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_OUTPUT_ALIASES_INPUT); - goto error; + return 0; } - if (!ctx->aead->open_gather) { + if (!ctx->aead->openv) { + if (ctx->tag_len && ctx->aead->openv_detached) { + // Try with a detached tag. + bssl::iovec::MaybeInplaceArray detached_iovecs; + if (!detached_iovecs.CopyFrom(iovecs)) { + return 0; + } + + uint8_t tagbuf[EVP_AEAD_MAX_OVERHEAD]; + std::optional> tag = bssl::iovec::GetAndRemoveSuffix( + Span(tagbuf).first(ctx->tag_len), Span(detached_iovecs)); + + if (!tag.has_value()) { // I.e. no `ctx->tag_len` bytes available. + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); + return 0; + } + + if (ctx->aead->openv_detached(ctx, detached_iovecs, + Span(nonce, nonce_len), *tag, aadvecs)) { + ok = true; + *out_total_bytes = bssl::iovec::TotalLength(Span(detached_iovecs)); + return 1; + } + return 0; + } + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_CTRL_NOT_IMPLEMENTED); - goto error; + return 0; } - if (ctx->aead->open_gather(ctx, out, nonce, nonce_len, in, in_len, in_tag, - in_tag_len, ad, ad_len)) { + if (ctx->aead->openv(ctx, iovecs, out_total_bytes, Span(nonce, nonce_len), + aadvecs)) { + ok = true; + return 1; + } + + return 0; +} + +int EVP_AEAD_CTX_openv_detached(const EVP_AEAD_CTX *ctx, + const CRYPTO_IOVEC *iovec, size_t num_iovec, + const uint8_t *nonce, size_t nonce_len, + const uint8_t *in_tag, size_t in_tag_len, + const CRYPTO_IVEC *aadvec, size_t num_aadvec) { + Span iovecs(iovec, num_iovec); + Span aadvecs(aadvec, num_aadvec); + + bool ok = false; + Cleanup cleanup([&] { + if (!ok) { + // In the event of an error, clear the output buffer so that a caller + // that doesn't check the return value doesn't try and process bad + // data. + clear_iovec(iovecs); + } + }); + + if (!bssl::iovec::IsValid(iovecs) || !bssl::iovec::IsValid(aadvecs)) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); + return 0; + } + if (in_tag_len > EVP_AEAD_MAX_OPEN_OVERHEAD) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_TAG_SIZE); + return 0; + } + + // Enforce aliasing rules: no output may alias any input, with the one + // exception that an iovec member's `in` and `out` pointers may be identical + // for in-place operation. + if (!check_iovec_alias(iovecs, aadvecs, nullptr, 0, nonce, nonce_len, in_tag, + in_tag_len)) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_OUTPUT_ALIASES_INPUT); + return 0; + } + + if (!ctx->aead->openv_detached) { + // AEADs with variable overhead may provide openv instead of openv_detached. + // While one might call openv and then, on success, discard the result if + // the length was wrong, this requires callers to predict the plaintext + // length first. We do not expect callers to do this, especially in the TLS + // CBC construction, where this length is sensitive to the Lucky 13 attack. + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_CTRL_NOT_IMPLEMENTED); + return 0; + } + + if (ctx->aead->openv_detached(ctx, iovecs, Span(nonce, nonce_len), + Span(in_tag, in_tag_len), aadvecs)) { + ok = true; return 1; } -error: - // In the event of an error, clear the output buffer so that a caller - // that doesn't check the return value doesn't try and process bad - // data. - OPENSSL_memset(out, 0, in_len); return 0; } @@ -268,7 +587,7 @@ const EVP_AEAD *EVP_AEAD_CTX_aead(const EVP_AEAD_CTX *ctx) { return ctx->aead; } int EVP_AEAD_CTX_get_iv(const EVP_AEAD_CTX *ctx, const uint8_t **out_iv, size_t *out_len) { - if (ctx->aead->get_iv == NULL) { + if (ctx->aead->get_iv == nullptr) { OPENSSL_PUT_ERROR(CIPHER, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } @@ -278,18 +597,23 @@ int EVP_AEAD_CTX_get_iv(const EVP_AEAD_CTX *ctx, const uint8_t **out_iv, int EVP_AEAD_CTX_tag_len(const EVP_AEAD_CTX *ctx, size_t *out_tag_len, const size_t in_len, const size_t extra_in_len) { - assert(ctx->aead->seal_scatter_supports_extra_in || !extra_in_len); - + size_t tag_len; if (ctx->aead->tag_len) { - *out_tag_len = ctx->aead->tag_len(ctx, in_len, extra_in_len); - return 1; + if (in_len + extra_in_len < in_len) { + OPENSSL_PUT_ERROR(CIPHER, ERR_R_OVERFLOW); + *out_tag_len = 0; + return 0; + } + tag_len = ctx->aead->tag_len(ctx, in_len + extra_in_len); + } else { + tag_len = ctx->tag_len; } - if (extra_in_len + ctx->tag_len < extra_in_len) { + if (extra_in_len + tag_len < extra_in_len) { OPENSSL_PUT_ERROR(CIPHER, ERR_R_OVERFLOW); *out_tag_len = 0; return 0; } - *out_tag_len = extra_in_len + ctx->tag_len; + *out_tag_len = extra_in_len + tag_len; return 1; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/cipher.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/cipher.cc.inc index 8f3ce354..33b060b8 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/cipher.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/cipher.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,19 +21,22 @@ #include #include #include +#include #include "../../internal.h" +#include "../../mem_internal.h" #include "../service_indicator/internal.h" #include "internal.h" +using namespace bssl; + void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *ctx) { OPENSSL_memset(ctx, 0, sizeof(EVP_CIPHER_CTX)); } -EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void) { - EVP_CIPHER_CTX *ctx = reinterpret_cast( - OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))); +EVP_CIPHER_CTX *EVP_CIPHER_CTX_new() { + EVP_CIPHER_CTX *ctx = New(); if (ctx) { EVP_CIPHER_CTX_init(ctx); } @@ -36,7 +44,7 @@ EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void) { } int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *c) { - if (c->cipher != NULL && c->cipher->cleanup) { + if (c->cipher != nullptr && c->cipher->cleanup) { c->cipher->cleanup(c); } OPENSSL_free(c->cipher_data); @@ -48,35 +56,30 @@ int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *c) { void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx) { if (ctx) { EVP_CIPHER_CTX_cleanup(ctx); - OPENSSL_free(ctx); + Delete(ctx); } } int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in) { - if (in == NULL || in->cipher == NULL) { + if (in == nullptr || in->cipher == nullptr) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INPUT_NOT_INITIALIZED); return 0; } - if (in->poisoned) { - OPENSSL_PUT_ERROR(CIPHER, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); - return 0; - } - EVP_CIPHER_CTX_cleanup(out); OPENSSL_memcpy(out, in, sizeof(EVP_CIPHER_CTX)); if (in->cipher_data && in->cipher->ctx_size) { out->cipher_data = OPENSSL_memdup(in->cipher_data, in->cipher->ctx_size); if (!out->cipher_data) { - out->cipher = NULL; + out->cipher = nullptr; return 0; } } if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY) { if (!in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out)) { - out->cipher = NULL; + out->cipher = nullptr; return 0; } } @@ -116,19 +119,19 @@ int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, if (ctx->cipher->ctx_size) { ctx->cipher_data = OPENSSL_malloc(ctx->cipher->ctx_size); if (!ctx->cipher_data) { - ctx->cipher = NULL; + ctx->cipher = nullptr; return 0; } } else { - ctx->cipher_data = NULL; + ctx->cipher_data = nullptr; } ctx->key_len = cipher->key_len; ctx->flags = 0; if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) { - if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) { - ctx->cipher = NULL; + if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, nullptr)) { + ctx->cipher = nullptr; OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INITIALIZATION_ERROR); return 0; } @@ -182,9 +185,6 @@ int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ctx->buf_len = 0; ctx->final_used = 0; - // Clear the poisoned flag to permit re-use of a CTX that previously had a - // failed operation. - ctx->poisoned = 0; return 1; } @@ -198,307 +198,438 @@ int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0); } -// block_remainder returns the number of bytes to remove from |len| to get a -// multiple of |ctx|'s block size. -static int block_remainder(const EVP_CIPHER_CTX *ctx, int len) { - // |block_size| must be a power of two. +// block_remainder returns the number of bytes to remove from `len` to get a +// multiple of `ctx`'s block size. +static size_t block_remainder(const EVP_CIPHER_CTX *ctx, size_t len) { + // `block_size` must be a power of two. assert(ctx->cipher->block_size != 0); assert((ctx->cipher->block_size & (ctx->cipher->block_size - 1)) == 0); return len & (ctx->cipher->block_size - 1); } -int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len, - const uint8_t *in, int in_len) { - if (ctx->poisoned) { - OPENSSL_PUT_ERROR(CIPHER, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); +static size_t evp_cipher_ctx_max_encrypt_update(const EVP_CIPHER_CTX *ctx, + size_t in_len) { + if (in_len == 0) { return 0; } - // If the first call to |cipher| succeeds and the second fails, |ctx| may be - // left in an indeterminate state. We set a poison flag on failure to ensure - // callers do not continue to use the object in that case. - ctx->poisoned = 1; - // Ciphers that use blocks may write up to |bl| extra bytes. Ensure the output - // does not overflow |*out_len|. - int bl = ctx->cipher->block_size; - if (bl > 1 && in_len > INT_MAX - bl) { + size_t block_size = ctx->cipher->block_size; + // `block_size` must be a power of 2. + assert(block_size != 0 && (block_size & (block_size - 1)) == 0); + size_t buf_len = ctx->buf_len; + + // Any buffered input is combined with `in_len`, then we round down to a + // multiple of the block size. + return (in_len + buf_len) & ~(block_size - 1); +} + +size_t EVP_CIPHER_CTX_max_next_update(const EVP_CIPHER_CTX *ctx, + size_t in_len) { + if (in_len == 0) { + return 0; + } + + size_t ret = evp_cipher_ctx_max_encrypt_update(ctx, in_len); + size_t block_size = ctx->cipher->block_size; + size_t buf_len = ctx->buf_len; + if (!ctx->encrypt && block_size > 1 && !(ctx->flags & EVP_CIPH_NO_PADDING)) { + if (ctx->final_used) { + // There was a buffered decrypted block. Now that it is known to not have + // padding, DecryptUpdate will output it. + ret += block_size; + } + if (block_remainder(ctx, in_len + buf_len) == 0) { + // This call ends on a block boundary. The last block will be buffered in + // `ctx->final` until it is known to have padding. + assert(ret >= block_size); + ret -= block_size; + } + } + return ret; +} + +int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len, + const uint8_t *in, int in_len) { + *out_len = 0; + if (in_len < 0) { OPENSSL_PUT_ERROR(CIPHER, ERR_R_OVERFLOW); return 0; } - - if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { - int ret = ctx->cipher->cipher(ctx, out, in, in_len); - if (ret < 0) { + size_t in_len_sz = static_cast(in_len); + size_t out_len_sz; + if ((ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) && out == nullptr) { + if (!EVP_CipherUpdateAAD(ctx, in, in_len_sz)) { + return 0; + } + out_len_sz = in_len_sz; // Even though no output was written! + } else { + // in_len_sz is < INT_MAX which is no more than half of SIZE_MAX. + size_t max_out_len = + std::min(in_len_sz + ctx->cipher->block_size - 1, size_t{INT_MAX}); + if (!EVP_EncryptUpdate_ex(ctx, out, &out_len_sz, max_out_len, in, + in_len_sz)) { return 0; - } else { - *out_len = ret; } - ctx->poisoned = 0; - return 1; } + *out_len = static_cast(out_len_sz); + return 1; +} - if (in_len <= 0) { - *out_len = 0; - if (in_len == 0) { - ctx->poisoned = 0; - return 1; - } +int EVP_EncryptUpdate_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, size_t *out_len, + size_t max_out_len, const uint8_t *in, size_t in_len) { + *out_len = 0; + + // `evp_cipher_ctx_max_encrypt_update` is currently exact. Check bounds before + // performing any operations so that, if the output is too small, retrying the + // operation with a larger buffer is well-defined. This only matters when it + // takes two steps to process `in`. + size_t expected = evp_cipher_ctx_max_encrypt_update(ctx, in_len); + if (max_out_len < expected) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); return 0; } - if (ctx->buf_len == 0 && block_remainder(ctx, in_len) == 0) { - if (ctx->cipher->cipher(ctx, out, in, in_len)) { - *out_len = in_len; - ctx->poisoned = 0; - return 1; - } else { - *out_len = 0; - return 0; - } + // Ciphers that use blocks may write up to `block_size` extra bytes. Ensure + // the output does not overflow `*out_len`. + Span in_span(in, in_len); + size_t block_size = ctx->cipher->block_size; + + if (in_span.empty()) { + return 1; } - int i = ctx->buf_len; - assert(bl <= (int)sizeof(ctx->buf)); - if (i != 0) { - if (bl - i > in_len) { - OPENSSL_memcpy(&ctx->buf[i], in, in_len); - ctx->buf_len += in_len; - *out_len = 0; - ctx->poisoned = 0; + size_t buf_len = ctx->buf_len; + assert(block_size <= sizeof(ctx->buf)); + Span out_span(out, max_out_len); + if (buf_len != 0) { + if (block_size - buf_len > in_span.size()) { + CopyToPrefix(in_span, Span(ctx->buf).subspan(buf_len)); + ctx->buf_len += in_span.size(); return 1; } else { - int j = bl - i; - OPENSSL_memcpy(&ctx->buf[i], in, j); - if (!ctx->cipher->cipher(ctx, out, ctx->buf, bl)) { + size_t j = block_size - buf_len; + CopyToPrefix(in_span.first(j), Span(ctx->buf).subspan(buf_len)); + if (out_span.size() < block_size) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); return 0; } - in_len -= j; - in += j; - out += bl; - *out_len = bl; + if (!ctx->cipher->cipher_update(ctx, out_span.data(), ctx->buf, + block_size)) { + return 0; + } + in_span = in_span.subspan(j); + out_span = out_span.subspan(block_size); } - } else { - *out_len = 0; } - i = block_remainder(ctx, in_len); - in_len -= i; - if (in_len > 0) { - if (!ctx->cipher->cipher(ctx, out, in, in_len)) { + size_t whole_blocks = in_span.size() - block_remainder(ctx, in_span.size()); + if (whole_blocks > 0) { + if (out_span.size() < whole_blocks) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); return 0; } - *out_len += in_len; + if (!ctx->cipher->cipher_update(ctx, out_span.data(), in_span.data(), + whole_blocks)) { + return 0; + } + in_span = in_span.subspan(whole_blocks); + out_span = out_span.subspan(whole_blocks); } - if (i != 0) { - OPENSSL_memcpy(ctx->buf, &in[in_len], i); - } - ctx->buf_len = i; - ctx->poisoned = 0; + assert(in_span.size() < block_size); + CopyToPrefix(in_span, ctx->buf); + ctx->buf_len = in_span.size(); + + *out_len = max_out_len - out_span.size(); + assert(*out_len == expected); // See `EVP_CIPHER_CTX_max_next_update` check. return 1; } int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len) { - int n; - unsigned int i, b, bl; + size_t out_len_sz; + int ret = + EVP_EncryptFinal_ex2(ctx, out, &out_len_sz, ctx->cipher->block_size); + static_assert(EVP_MAX_BLOCK_LENGTH <= INT_MAX); + *out_len = static_cast(out_len_sz); + return ret; +} - if (ctx->poisoned) { - OPENSSL_PUT_ERROR(CIPHER, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); - return 0; - } +int EVP_EncryptFinal_ex2(EVP_CIPHER_CTX *ctx, uint8_t *out, size_t *out_len, + size_t max_out_len) { + *out_len = 0; - if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { - // When EVP_CIPH_FLAG_CUSTOM_CIPHER is set, the return value of |cipher| is - // the number of bytes written, or -1 on error. Otherwise the return value - // is one on success and zero on error. - const int num_bytes = ctx->cipher->cipher(ctx, out, NULL, 0); - if (num_bytes < 0) { - return 0; + size_t block_size = ctx->cipher->block_size; + assert(block_size <= sizeof(ctx->buf)); + if (block_size == 1) { + if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { + return ctx->cipher->cipher_final(ctx); } - *out_len = num_bytes; - goto out; + EVP_Cipher_verify_service_indicator(ctx); + return 1; } - b = ctx->cipher->block_size; - assert(b <= sizeof(ctx->buf)); - if (b == 1) { - *out_len = 0; - goto out; - } - - bl = ctx->buf_len; + size_t buf_len = ctx->buf_len; if (ctx->flags & EVP_CIPH_NO_PADDING) { - if (bl) { + if (buf_len) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH); return 0; } - *out_len = 0; - goto out; + EVP_Cipher_verify_service_indicator(ctx); + return 1; } - n = b - bl; - for (i = bl; i < b; i++) { - ctx->buf[i] = n; - } - if (!ctx->cipher->cipher(ctx, out, ctx->buf, b)) { + Span out_span(out, max_out_len); + if (out_span.size() < block_size) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); return 0; } - *out_len = b; -out: + size_t padding = block_size - buf_len; + for (size_t i = buf_len; i < block_size; i++) { + ctx->buf[i] = padding; + } + if (!ctx->cipher->cipher_update(ctx, out_span.data(), ctx->buf, block_size)) { + return 0; + } + out_span = out_span.subspan(block_size); + + *out_len = max_out_len - out_span.size(); EVP_Cipher_verify_service_indicator(ctx); return 1; } int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len, const uint8_t *in, int in_len) { - if (ctx->poisoned) { - OPENSSL_PUT_ERROR(CIPHER, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); - return 0; - } - - // Ciphers that use blocks may write up to |bl| extra bytes. Ensure the output - // does not overflow |*out_len|. - unsigned int b = ctx->cipher->block_size; - if (b > 1 && in_len > INT_MAX - (int)b) { + *out_len = 0; + if (in_len < 0) { OPENSSL_PUT_ERROR(CIPHER, ERR_R_OVERFLOW); return 0; } - - if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { - int r = ctx->cipher->cipher(ctx, out, in, in_len); - if (r < 0) { - *out_len = 0; + size_t in_len_sz = static_cast(in_len); + size_t out_len_sz; + if ((ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) && out == nullptr) { + if (!EVP_CipherUpdateAAD(ctx, in, in_len_sz)) { return 0; - } else { - *out_len = r; } - return 1; - } - - if (in_len <= 0) { - *out_len = 0; - return in_len == 0; - } - - if (ctx->flags & EVP_CIPH_NO_PADDING) { - return EVP_EncryptUpdate(ctx, out, out_len, in, in_len); - } - - assert(b <= sizeof(ctx->final)); - int fix_len = 0; - if (ctx->final_used) { - OPENSSL_memcpy(out, ctx->final, b); - out += b; - fix_len = 1; - } - - if (!EVP_EncryptUpdate(ctx, out, out_len, in, in_len)) { - return 0; - } - - // if we have 'decrypted' a multiple of block size, make sure - // we have a copy of this last block - if (b > 1 && !ctx->buf_len) { - *out_len -= b; - ctx->final_used = 1; - OPENSSL_memcpy(ctx->final, &out[*out_len], b); + out_len_sz = in_len_sz; } else { - ctx->final_used = 0; + // in_len_sz is < INT_MAX which is no more than half of SIZE_MAX. + size_t max_out_len = + std::min(in_len_sz + ctx->cipher->block_size - 1, size_t{INT_MAX}); + if (!EVP_DecryptUpdate_ex(ctx, out, &out_len_sz, max_out_len, in, + in_len_sz)) { + return 0; + } } - - if (fix_len) { - *out_len += b; - } - + *out_len = static_cast(out_len_sz); return 1; } -int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *out_len) { - int i, n; - unsigned int b; +int EVP_DecryptUpdate_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, size_t *out_len, + size_t max_out_len, const uint8_t *in, size_t in_len) { *out_len = 0; - if (ctx->poisoned) { - OPENSSL_PUT_ERROR(CIPHER, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + // Ciphers that use blocks may write up to `block_size` extra bytes. Ensure + // the output does not overflow `*out_len`. + Span in_span(in, in_len); + size_t block_size = ctx->cipher->block_size; + if (in_span.empty()) { + return 1; + } + + Span out_span(out, max_out_len); + if (ctx->flags & EVP_CIPH_NO_PADDING) { + // Use the shared block handling logic from encryption. + return EVP_EncryptUpdate_ex(ctx, out_span.data(), out_len, out_span.size(), + in_span.data(), in_span.size()); + } + + // `EVP_CIPHER_CTX_max_next_update` is currently exact. Check bounds before + // performing any operations so that, if the output is too small, retrying the + // operation with a larger buffer is well-defined. This only matters when it + // takes two steps to process `in`. + size_t expected = EVP_CIPHER_CTX_max_next_update(ctx, in_len); + if (max_out_len < expected) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); return 0; } - if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { - i = ctx->cipher->cipher(ctx, out, NULL, 0); - if (i < 0) { + assert(block_size <= sizeof(ctx->final)); + if (ctx->final_used) { + if (out_span.size() < block_size) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); return 0; - } else { - *out_len = i; } - goto out; + CopyToPrefix(Span(ctx->final).first(block_size), out_span); + ctx->final_used = 0; + out_span = out_span.subspan(block_size); } - b = ctx->cipher->block_size; + // Use the shared block handling logic from encryption. + if (block_size > 1 && + block_remainder(ctx, ctx->buf_len + in_span.size()) == 0) { + // Decryption would end on a block boundary. In this case, although we + // can decrypt up to the block boundary, we cannot output the final + // plaintext block yet. It may be the final block, with padding to + // remove. + // + // Instead, output all but the final block's decryption, then decrypt the + // final block into ctx->final, to be processed later. + + // NOTE: Not _really_ necessary, but let's try aligning the second + // EVP_EncryptUpdate_ex call to a block boundary to mess with the buffer + // less. + size_t head = in_span.size() > block_size ? in_span.size() - block_size : 0; + size_t head_out_len; + if (!EVP_EncryptUpdate_ex(ctx, out_span.data(), &head_out_len, + out_span.size(), in_span.data(), head)) { + return 0; + } + in_span = in_span.subspan(head); + out_span = out_span.subspan(head_out_len); + size_t final_size; + if (!EVP_EncryptUpdate_ex(ctx, ctx->final, &final_size, sizeof(ctx->final), + in_span.data(), in_span.size())) { + return 0; + } + ctx->final_used = 1; + assert(final_size == block_size); + assert(ctx->buf_len == 0); + } else { + // Buffer will be non-empty. + size_t written_out_len; + if (!EVP_EncryptUpdate_ex(ctx, out_span.data(), &written_out_len, + out_span.size(), in_span.data(), + in_span.size())) { + return 0; + } + assert(block_size == 1 || ctx->buf_len != 0); + out_span = out_span.subspan(written_out_len); + } + + *out_len = max_out_len - out_span.size(); + assert(*out_len == expected); // See `EVP_CIPHER_CTX_max_next_update` check. + return 1; +} + +int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len) { + size_t out_len_sz; + int ret = + EVP_DecryptFinal_ex2(ctx, out, &out_len_sz, ctx->cipher->block_size); + static_assert(EVP_MAX_BLOCK_LENGTH <= INT_MAX); + *out_len = static_cast(out_len_sz); + return ret; +} + +int EVP_DecryptFinal_ex2(EVP_CIPHER_CTX *ctx, uint8_t *out, size_t *out_len, + size_t max_out_len) { + *out_len = 0; + + size_t block_size = ctx->cipher->block_size; + assert(block_size <= sizeof(ctx->buf)); + if (block_size == 1) { + if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { + return ctx->cipher->cipher_final(ctx); + } + EVP_Cipher_verify_service_indicator(ctx); + return 1; + } + + size_t buf_len = ctx->buf_len; if (ctx->flags & EVP_CIPH_NO_PADDING) { - if (ctx->buf_len) { + if (buf_len) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH); return 0; } - *out_len = 0; - goto out; + EVP_Cipher_verify_service_indicator(ctx); + return 1; } - if (b > 1) { - if (ctx->buf_len || !ctx->final_used) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_WRONG_FINAL_BLOCK_LENGTH); - return 0; - } - assert(b <= sizeof(ctx->final)); + if (buf_len || !ctx->final_used) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_WRONG_FINAL_BLOCK_LENGTH); + return 0; + } + assert(block_size <= sizeof(ctx->final)); - // The following assumes that the ciphertext has been authenticated. - // Otherwise it provides a padding oracle. - n = ctx->final[b - 1]; - if (n == 0 || n > (int)b) { + // The following assumes that the ciphertext has been authenticated. Otherwise + // it provides a padding oracle. + size_t padding = ctx->final[block_size - 1]; + if (padding == 0 || padding > block_size) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); + return 0; + } + + for (size_t i = block_size - padding; i < block_size; i++) { + if (ctx->final[i] != padding) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } - - for (i = 0; i < n; i++) { - if (ctx->final[--b] != n) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); - return 0; - } - } - - n = ctx->cipher->block_size - n; - for (i = 0; i < n; i++) { - out[i] = ctx->final[i]; - } - *out_len = n; - } else { - *out_len = 0; } -out: + Span out_span(out, max_out_len); + size_t payload = ctx->cipher->block_size - padding; + if (out_span.size() < payload) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); + return 0; + } + CopyToPrefix(Span(ctx->final).first(payload), out_span); + out_span = out_span.subspan(payload); + + *out_len = max_out_len - out_span.size(); EVP_Cipher_verify_service_indicator(ctx); return 1; } int EVP_Cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, size_t in_len) { - const int ret = ctx->cipher->cipher(ctx, out, in, in_len); + const int kError = + (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) ? -1 : 0; - // |EVP_CIPH_FLAG_CUSTOM_CIPHER| never sets the FIPS indicator via - // |EVP_Cipher| because it's complicated whether the operation has completed - // or not. E.g. AES-GCM with a non-NULL |in| argument hasn't completed an - // operation. Callers should use the |EVP_AEAD| API or, at least, - // |EVP_CipherUpdate| etc. + if ((ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) && + in_len > size_t{INT_MAX}) { + // Can't represent the return value? That'd be bad. + OPENSSL_PUT_ERROR(CIPHER, ERR_R_OVERFLOW); + return kError; + } + + size_t out_len; + if ((ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) && in == nullptr) { + if (!ctx->cipher->cipher_final(ctx)) { + return kError; + } + out_len = 0; + } else if ((ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) && + out == nullptr) { + if (!ctx->cipher->update_aad(ctx, in, in_len)) { + return kError; + } + out_len = in_len; // Yes, even though no output was written! + } else { + if (!ctx->cipher->cipher_update(ctx, out, in, in_len)) { + return kError; + } + out_len = in_len; + } + + // `EVP_CIPH_FLAG_CUSTOM_CIPHER` never sets the FIPS indicator via + // `EVP_Cipher` because it's complicated whether the operation has completed + // or not. E.g. AES-GCM with a non-NULL `in` argument hasn't completed an + // operation. Callers should use the `EVP_AEAD` API or, at least, + // `EVP_CipherUpdate` etc. // - // This call can't be pushed into |EVP_Cipher_verify_service_indicator| - // because whether |ret| indicates success or not depends on whether - // |EVP_CIPH_FLAG_CUSTOM_CIPHER| is set. (This unreasonable, but matches + // This call can't be pushed into `EVP_Cipher_verify_service_indicator` + // because whether `ret` indicates success or not depends on whether + // `EVP_CIPH_FLAG_CUSTOM_CIPHER` is set. (This unreasonable, but matches // OpenSSL.) - if (!(ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) && ret) { + if (!(ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER)) { EVP_Cipher_verify_service_indicator(ctx); } - return ret; + // Custom ciphers return byte count; regular ciphers return boolean. + if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { + return static_cast(out_len); + } + return 1; } int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len, @@ -510,6 +641,23 @@ int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len, } } +int EVP_CipherUpdate_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, size_t *out_len, + size_t max_out_len, const uint8_t *in, size_t in_len) { + if (ctx->encrypt) { + return EVP_EncryptUpdate_ex(ctx, out, out_len, max_out_len, in, in_len); + } else { + return EVP_DecryptUpdate_ex(ctx, out, out_len, max_out_len, in, in_len); + } +} + +int EVP_CipherUpdateAAD(EVP_CIPHER_CTX *ctx, const uint8_t *in, size_t in_len) { + if (!(ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER)) { + OPENSSL_PUT_ERROR(CIPHER, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return 0; + } + return ctx->cipher->update_aad(ctx, in, in_len); +} + int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len) { if (ctx->encrypt) { return EVP_EncryptFinal_ex(ctx, out, out_len); @@ -518,6 +666,28 @@ int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len) { } } +int EVP_CipherFinal_ex2(EVP_CIPHER_CTX *ctx, uint8_t *out, size_t *out_len, + size_t max_out_len) { + if (ctx->encrypt) { + return EVP_EncryptFinal_ex2(ctx, out, out_len, max_out_len); + } else { + return EVP_DecryptFinal_ex2(ctx, out, out_len, max_out_len); + } +} + +size_t EVP_CIPHER_CTX_max_final(const EVP_CIPHER_CTX *ctx) { + size_t block_size = ctx->cipher->block_size; + if (block_size == 1 || (ctx->flags & EVP_CIPH_NO_PADDING)) { + return 0; + } + if (ctx->encrypt) { + return block_size; + } else { + // At least one byte will be removed when processing padding. + return block_size - 1; + } +} + const EVP_CIPHER *EVP_CIPHER_CTX_cipher(const EVP_CIPHER_CTX *ctx) { return ctx->cipher; } @@ -637,7 +807,7 @@ int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, if (cipher) { EVP_CIPHER_CTX_init(ctx); } - return EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, enc); + return EVP_CipherInit_ex(ctx, cipher, nullptr, key, iv, enc); } int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/e_aes.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/e_aes.cc.inc index 554cff4a..59d0898b 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/e_aes.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/e_aes.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,6 +22,7 @@ #include #include #include +#include #include "../../internal.h" #include "../aes/internal.h" @@ -26,8 +32,7 @@ #include "internal.h" -OPENSSL_MSVC_PRAGMA(warning(push)) -OPENSSL_MSVC_PRAGMA(warning(disable : 4702)) // Unreachable code. +using namespace bssl; #define AES_GCM_NONCE_LENGTH 12 @@ -77,23 +82,25 @@ static int aes_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, if (hwaes_capable()) { ret = aes_hw_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks); dat->block = aes_hw_decrypt; - dat->stream.cbc = NULL; + dat->stream.cbc = nullptr; if (mode == EVP_CIPH_CBC_MODE) { dat->stream.cbc = aes_hw_cbc_encrypt; } +#if defined(BSAES) } else if (bsaes_capable() && mode == EVP_CIPH_CBC_MODE) { assert(vpaes_capable()); ret = vpaes_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks); if (ret == 0) { vpaes_decrypt_key_to_bsaes(&dat->ks.ks, &dat->ks.ks); } - // If |dat->stream.cbc| is provided, |dat->block| is never used. - dat->block = NULL; + // If `dat->stream.cbc` is provided, `dat->block` is never used. + dat->block = nullptr; dat->stream.cbc = bsaes_cbc_encrypt; +#endif } else if (vpaes_capable()) { ret = vpaes_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks); dat->block = vpaes_decrypt; - dat->stream.cbc = NULL; + dat->stream.cbc = nullptr; #if defined(VPAES_CBC) if (mode == EVP_CIPH_CBC_MODE) { dat->stream.cbc = vpaes_cbc_encrypt; @@ -102,7 +109,7 @@ static int aes_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, } else { ret = aes_nohw_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks); dat->block = aes_nohw_decrypt; - dat->stream.cbc = NULL; + dat->stream.cbc = nullptr; if (mode == EVP_CIPH_CBC_MODE) { dat->stream.cbc = aes_nohw_cbc_encrypt; } @@ -110,7 +117,7 @@ static int aes_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, } else if (hwaes_capable()) { ret = aes_hw_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks); dat->block = aes_hw_encrypt; - dat->stream.cbc = NULL; + dat->stream.cbc = nullptr; if (mode == EVP_CIPH_CBC_MODE) { dat->stream.cbc = aes_hw_cbc_encrypt; } else if (mode == EVP_CIPH_CTR_MODE) { @@ -119,7 +126,7 @@ static int aes_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, } else if (vpaes_capable()) { ret = vpaes_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks); dat->block = vpaes_encrypt; - dat->stream.cbc = NULL; + dat->stream.cbc = nullptr; #if defined(VPAES_CBC) if (mode == EVP_CIPH_CBC_MODE) { dat->stream.cbc = vpaes_cbc_encrypt; @@ -136,7 +143,7 @@ static int aes_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, } else { ret = aes_nohw_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks); dat->block = aes_nohw_encrypt; - dat->stream.cbc = NULL; + dat->stream.cbc = nullptr; if (mode == EVP_CIPH_CBC_MODE) { dat->stream.cbc = aes_nohw_cbc_encrypt; } else if (mode == EVP_CIPH_CTR_MODE) { @@ -152,8 +159,8 @@ static int aes_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, return 1; } -static int aes_cbc_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, - size_t len) { +static int aes_cbc_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out, + const uint8_t *in, size_t len) { EVP_AES_KEY *dat = (EVP_AES_KEY *)ctx->cipher_data; if (dat->stream.cbc) { @@ -167,8 +174,8 @@ static int aes_cbc_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, return 1; } -static int aes_ecb_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, - size_t len) { +static int aes_ecb_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out, + const uint8_t *in, size_t len) { size_t bl = ctx->cipher->block_size; EVP_AES_KEY *dat = (EVP_AES_KEY *)ctx->cipher_data; @@ -184,16 +191,16 @@ static int aes_ecb_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, return 1; } -static int aes_ctr_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, - size_t len) { +static int aes_ctr_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out, + const uint8_t *in, size_t len) { EVP_AES_KEY *dat = (EVP_AES_KEY *)ctx->cipher_data; CRYPTO_ctr128_encrypt_ctr32(in, out, len, &dat->ks.ks, ctx->iv, ctx->buf, &ctx->num, dat->stream.ctr); return 1; } -static int aes_ofb_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, - size_t len) { +static int aes_ofb_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out, + const uint8_t *in, size_t len) { EVP_AES_KEY *dat = (EVP_AES_KEY *)ctx->cipher_data; CRYPTO_ofb128_encrypt(in, out, len, &dat->ks.ks, ctx->iv, &ctx->num, @@ -214,7 +221,7 @@ static int aes_gcm_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, OPENSSL_memset(&gctx->gcm, 0, sizeof(gctx->gcm)); CRYPTO_gcm128_init_aes_key(&gctx->key, key, ctx->key_len); // Use the IV if specified. Otherwise, use the saved IV, if any. - if (iv == NULL && gctx->iv_set) { + if (iv == nullptr && gctx->iv_set) { iv = gctx->iv; } if (iv) { @@ -260,16 +267,32 @@ static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { if (arg <= 0) { return 0; } + if (arg == gctx->ivlen) { + // Some applications set the IV and then do a no-op length change, + // expecting the IV to remain set. + return 1; + } - // Allocate memory for IV if needed - if (arg > EVP_MAX_IV_LENGTH && arg > gctx->ivlen) { + // Clear any existing IV or partial IV that may have previously been set. + gctx->iv_set = 0; + gctx->iv_gen = 0; + + if (arg <= EVP_MAX_IV_LENGTH) { + // IVs less than EVP_MAX_IV_LENGTH are stored in the built-in buffer. + if (gctx->iv != c->iv) { + OPENSSL_free(gctx->iv); + gctx->iv = c->iv; + } + } else if (arg > gctx->ivlen) { + // The existing buffer isn't large enough. + uint8_t *new_iv = static_cast(OPENSSL_malloc(arg)); + if (new_iv == nullptr) { + return 0; + } if (gctx->iv != c->iv) { OPENSSL_free(gctx->iv); } - gctx->iv = reinterpret_cast(OPENSSL_malloc(arg)); - if (!gctx->iv) { - return 0; - } + gctx->iv = new_iv; } gctx->ivlen = arg; return 1; @@ -300,14 +323,14 @@ static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { gctx->iv_gen = 1; return 1; } - // Fixed field must be at least 4 bytes and invocation field - // at least 8. + // The fixed field must be at least 4 bytes and the invocation field at + // least 8. if (arg < 4 || (gctx->ivlen - arg) < 8) { return 0; } OPENSSL_memcpy(gctx->iv, ptr, arg); if (c->encrypt) { - // |BCM_rand_bytes| calls within the fipsmodule should be wrapped with + // `BCM_rand_bytes` calls within the fipsmodule should be wrapped with // state lock functions to avoid updating the service indicator with the // DRBG functions. FIPS_service_indicator_lock_state(); @@ -318,7 +341,7 @@ 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) { + if (gctx->iv_gen == 0 || gctx->key_set == 0 || gctx->ivlen < 8) { return 0; } CRYPTO_gcm128_init_ctx(&gctx->key, &gctx->gcm, gctx->iv, gctx->ivlen); @@ -326,8 +349,6 @@ static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { arg = gctx->ivlen; } OPENSSL_memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg); - // Invocation field will be at least 8 bytes in size, so no need to check - // wrap around or increment more than last 8 bytes. uint8_t *ctr = gctx->iv + gctx->ivlen - 8; CRYPTO_store_u64_be(ctr, CRYPTO_load_u64_be(ctr) + 1); gctx->iv_set = 1; @@ -335,7 +356,8 @@ static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { } case EVP_CTRL_GCM_SET_IV_INV: - if (gctx->iv_gen == 0 || gctx->key_set == 0 || c->encrypt) { + if (gctx->iv_gen == 0 || gctx->key_set == 0 || c->encrypt || arg < 0 || + arg > gctx->ivlen) { return 0; } OPENSSL_memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg); @@ -364,56 +386,55 @@ static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { } } -static int aes_gcm_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, - size_t len) { +static int aes_gcm_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out, + const uint8_t *in, size_t len) { EVP_AES_GCM_CTX *gctx = reinterpret_cast(ctx->cipher_data); // If not set up, return error - if (!gctx->key_set) { - return -1; - } - if (!gctx->iv_set) { - return -1; - } - - if (len > INT_MAX) { - // This function signature can only express up to |INT_MAX| bytes encrypted. - // - // TODO(https://crbug.com/boringssl/494): Make the internal |EVP_CIPHER| - // calling convention |size_t|-clean. - return -1; - } - - if (in) { - if (out == NULL) { - if (!CRYPTO_gcm128_aad(&gctx->key, &gctx->gcm, in, len)) { - return -1; - } - } else if (ctx->encrypt) { - if (!CRYPTO_gcm128_encrypt(&gctx->key, &gctx->gcm, in, out, len)) { - return -1; - } - } else { - if (!CRYPTO_gcm128_decrypt(&gctx->key, &gctx->gcm, in, out, len)) { - return -1; - } - } - return (int)len; - } else { - if (!ctx->encrypt) { - if (gctx->taglen < 0 || !CRYPTO_gcm128_finish(&gctx->key, &gctx->gcm, - ctx->buf, gctx->taglen)) { - return -1; - } - gctx->iv_set = 0; - return 0; - } - CRYPTO_gcm128_tag(&gctx->key, &gctx->gcm, ctx->buf, 16); - gctx->taglen = 16; - // Don't reuse the IV - gctx->iv_set = 0; + if (!gctx->key_set || !gctx->iv_set) { return 0; } + + if (ctx->encrypt) { + return CRYPTO_gcm128_encrypt(&gctx->key, &gctx->gcm, in, out, len); + } else { + return CRYPTO_gcm128_decrypt(&gctx->key, &gctx->gcm, in, out, len); + } +} + +static int aes_gcm_cipher_final(EVP_CIPHER_CTX *ctx) { + EVP_AES_GCM_CTX *gctx = reinterpret_cast(ctx->cipher_data); + + // If not set up, return error + if (!gctx->key_set || !gctx->iv_set) { + return 0; + } + + if (!ctx->encrypt) { + if (gctx->taglen < 0 || + !CRYPTO_gcm128_finish(&gctx->key, &gctx->gcm, ctx->buf, gctx->taglen)) { + return 0; + } + gctx->iv_set = 0; + return 1; + } + CRYPTO_gcm128_tag(&gctx->key, &gctx->gcm, ctx->buf, 16); + gctx->taglen = 16; + // Don't reuse the IV + gctx->iv_set = 0; + return 1; +} + +static int aes_gcm_update_aad(EVP_CIPHER_CTX *ctx, const uint8_t *in, + size_t len) { + EVP_AES_GCM_CTX *gctx = reinterpret_cast(ctx->cipher_data); + + // If not set up, return error + if (!gctx->key_set || !gctx->iv_set) { + return 0; + } + + return CRYPTO_gcm128_aad(&gctx->key, &gctx->gcm, in, len); } DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_128_cbc) { @@ -426,7 +447,7 @@ DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_128_cbc) { out->ctx_size = sizeof(EVP_AES_KEY); out->flags = EVP_CIPH_CBC_MODE; out->init = aes_init_key; - out->cipher = aes_cbc_cipher; + out->cipher_update = aes_cbc_cipher_update; } DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_128_ctr) { @@ -439,7 +460,7 @@ DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_128_ctr) { out->ctx_size = sizeof(EVP_AES_KEY); out->flags = EVP_CIPH_CTR_MODE; out->init = aes_init_key; - out->cipher = aes_ctr_cipher; + out->cipher_update = aes_ctr_cipher_update; } DEFINE_LOCAL_DATA(EVP_CIPHER, aes_128_ecb_generic) { @@ -451,7 +472,7 @@ DEFINE_LOCAL_DATA(EVP_CIPHER, aes_128_ecb_generic) { out->ctx_size = sizeof(EVP_AES_KEY); out->flags = EVP_CIPH_ECB_MODE; out->init = aes_init_key; - out->cipher = aes_ecb_cipher; + out->cipher_update = aes_ecb_cipher_update; } DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_128_ofb) { @@ -464,7 +485,7 @@ DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_128_ofb) { out->ctx_size = sizeof(EVP_AES_KEY); out->flags = EVP_CIPH_OFB_MODE; out->init = aes_init_key; - out->cipher = aes_ofb_cipher; + out->cipher_update = aes_ofb_cipher_update; } DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_128_gcm) { @@ -479,7 +500,9 @@ DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_128_gcm) { EVP_CIPH_FLAG_CUSTOM_CIPHER | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT | EVP_CIPH_FLAG_AEAD_CIPHER; out->init = aes_gcm_init_key; - out->cipher = aes_gcm_cipher; + out->cipher_update = aes_gcm_cipher_update; + out->cipher_final = aes_gcm_cipher_final; + out->update_aad = aes_gcm_update_aad; out->cleanup = aes_gcm_cleanup; out->ctrl = aes_gcm_ctrl; } @@ -494,7 +517,7 @@ DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_192_cbc) { out->ctx_size = sizeof(EVP_AES_KEY); out->flags = EVP_CIPH_CBC_MODE; out->init = aes_init_key; - out->cipher = aes_cbc_cipher; + out->cipher_update = aes_cbc_cipher_update; } DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_192_ctr) { @@ -507,7 +530,7 @@ DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_192_ctr) { out->ctx_size = sizeof(EVP_AES_KEY); out->flags = EVP_CIPH_CTR_MODE; out->init = aes_init_key; - out->cipher = aes_ctr_cipher; + out->cipher_update = aes_ctr_cipher_update; } DEFINE_LOCAL_DATA(EVP_CIPHER, aes_192_ecb_generic) { @@ -519,7 +542,7 @@ DEFINE_LOCAL_DATA(EVP_CIPHER, aes_192_ecb_generic) { out->ctx_size = sizeof(EVP_AES_KEY); out->flags = EVP_CIPH_ECB_MODE; out->init = aes_init_key; - out->cipher = aes_ecb_cipher; + out->cipher_update = aes_ecb_cipher_update; } DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_192_ofb) { @@ -532,7 +555,7 @@ DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_192_ofb) { out->ctx_size = sizeof(EVP_AES_KEY); out->flags = EVP_CIPH_OFB_MODE; out->init = aes_init_key; - out->cipher = aes_ofb_cipher; + out->cipher_update = aes_ofb_cipher_update; } DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_192_gcm) { @@ -547,7 +570,9 @@ DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_192_gcm) { EVP_CIPH_FLAG_CUSTOM_CIPHER | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT | EVP_CIPH_FLAG_AEAD_CIPHER; out->init = aes_gcm_init_key; - out->cipher = aes_gcm_cipher; + out->cipher_update = aes_gcm_cipher_update; + out->cipher_final = aes_gcm_cipher_final; + out->update_aad = aes_gcm_update_aad; out->cleanup = aes_gcm_cleanup; out->ctrl = aes_gcm_ctrl; } @@ -562,7 +587,7 @@ DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_256_cbc) { out->ctx_size = sizeof(EVP_AES_KEY); out->flags = EVP_CIPH_CBC_MODE; out->init = aes_init_key; - out->cipher = aes_cbc_cipher; + out->cipher_update = aes_cbc_cipher_update; } DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_256_ctr) { @@ -575,7 +600,7 @@ DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_256_ctr) { out->ctx_size = sizeof(EVP_AES_KEY); out->flags = EVP_CIPH_CTR_MODE; out->init = aes_init_key; - out->cipher = aes_ctr_cipher; + out->cipher_update = aes_ctr_cipher_update; } DEFINE_LOCAL_DATA(EVP_CIPHER, aes_256_ecb_generic) { @@ -587,7 +612,7 @@ DEFINE_LOCAL_DATA(EVP_CIPHER, aes_256_ecb_generic) { out->ctx_size = sizeof(EVP_AES_KEY); out->flags = EVP_CIPH_ECB_MODE; out->init = aes_init_key; - out->cipher = aes_ecb_cipher; + out->cipher_update = aes_ecb_cipher_update; } DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_256_ofb) { @@ -600,7 +625,7 @@ DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_256_ofb) { out->ctx_size = sizeof(EVP_AES_KEY); out->flags = EVP_CIPH_OFB_MODE; out->init = aes_init_key; - out->cipher = aes_ofb_cipher; + out->cipher_update = aes_ofb_cipher_update; } DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_256_gcm) { @@ -615,15 +640,17 @@ DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_aes_256_gcm) { EVP_CIPH_FLAG_CUSTOM_CIPHER | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT | EVP_CIPH_FLAG_AEAD_CIPHER; out->init = aes_gcm_init_key; - out->cipher = aes_gcm_cipher; + out->cipher_update = aes_gcm_cipher_update; + out->cipher_final = aes_gcm_cipher_final; + out->update_aad = aes_gcm_update_aad; out->cleanup = aes_gcm_cleanup; out->ctrl = aes_gcm_ctrl; } #if defined(HWAES_ECB) -static int aes_hw_ecb_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, - const uint8_t *in, size_t len) { +static int aes_hw_ecb_cipher_update(EVP_CIPHER_CTX *ctx, uint8_t *out, + const uint8_t *in, size_t len) { size_t bl = ctx->cipher->block_size; if (len < bl) { @@ -646,7 +673,7 @@ DEFINE_LOCAL_DATA(EVP_CIPHER, aes_hw_128_ecb) { out->ctx_size = sizeof(EVP_AES_KEY); out->flags = EVP_CIPH_ECB_MODE; out->init = aes_init_key; - out->cipher = aes_hw_ecb_cipher; + out->cipher_update = aes_hw_ecb_cipher_update; } DEFINE_LOCAL_DATA(EVP_CIPHER, aes_hw_192_ecb) { @@ -658,7 +685,7 @@ DEFINE_LOCAL_DATA(EVP_CIPHER, aes_hw_192_ecb) { out->ctx_size = sizeof(EVP_AES_KEY); out->flags = EVP_CIPH_ECB_MODE; out->init = aes_init_key; - out->cipher = aes_hw_ecb_cipher; + out->cipher_update = aes_hw_ecb_cipher_update; } DEFINE_LOCAL_DATA(EVP_CIPHER, aes_hw_256_ecb) { @@ -670,22 +697,22 @@ DEFINE_LOCAL_DATA(EVP_CIPHER, aes_hw_256_ecb) { out->ctx_size = sizeof(EVP_AES_KEY); out->flags = EVP_CIPH_ECB_MODE; out->init = aes_init_key; - out->cipher = aes_hw_ecb_cipher; + out->cipher_update = aes_hw_ecb_cipher_update; } -#define EVP_ECB_CIPHER_FUNCTION(keybits) \ - const EVP_CIPHER *EVP_aes_##keybits##_ecb(void) { \ - if (hwaes_capable()) { \ - return aes_hw_##keybits##_ecb(); \ - } \ - return aes_##keybits##_ecb_generic(); \ +#define EVP_ECB_CIPHER_FUNCTION(keybits) \ + const EVP_CIPHER *EVP_aes_##keybits##_ecb() { \ + if (hwaes_capable()) { \ + return aes_hw_##keybits##_ecb(); \ + } \ + return aes_##keybits##_ecb_generic(); \ } #else -#define EVP_ECB_CIPHER_FUNCTION(keybits) \ - const EVP_CIPHER *EVP_aes_##keybits##_ecb(void) { \ - return aes_##keybits##_ecb_generic(); \ +#define EVP_ECB_CIPHER_FUNCTION(keybits) \ + const EVP_CIPHER *EVP_aes_##keybits##_ecb() { \ + return aes_##keybits##_ecb_generic(); \ } #endif // HWAES_ECB @@ -726,7 +753,7 @@ static int aead_aes_gcm_init_impl(struct aead_aes_gcm_ctx *gcm_ctx, return 1; } -static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) >= +static_assert(sizeof(((EVP_AEAD_CTX *)nullptr)->state) >= sizeof(struct aead_aes_gcm_ctx), "AEAD state is too small"); static_assert(alignof(union evp_aead_ctx_st_state) >= @@ -749,91 +776,89 @@ static int aead_aes_gcm_init(EVP_AEAD_CTX *ctx, const uint8_t *key, static void aead_aes_gcm_cleanup(EVP_AEAD_CTX *ctx) {} -static int aead_aes_gcm_seal_scatter_impl( - const struct aead_aes_gcm_ctx *gcm_ctx, uint8_t *out, uint8_t *out_tag, - size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *extra_in, - size_t extra_in_len, const uint8_t *ad, size_t ad_len, size_t tag_len) { - if (extra_in_len + tag_len < tag_len) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); - return 0; - } - if (max_out_tag_len < extra_in_len + tag_len) { +static int aead_aes_gcm_sealv_impl(const struct aead_aes_gcm_ctx *gcm_ctx, + Span iovecs, + Span out_tag, size_t *out_tag_len, + Span nonce, + Span aadvecs, + size_t tag_len) { + if (out_tag.size() < tag_len) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); return 0; } - if (nonce_len == 0) { + + if (nonce.size() == 0) { 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, nonce_len); + CRYPTO_gcm128_init_ctx(key, &gcm, nonce.data(), nonce.size()); - if (ad_len > 0 && !CRYPTO_gcm128_aad(key, &gcm, ad, ad_len)) { - return 0; + for (const CRYPTO_IVEC &aadvec : aadvecs) { + if (!CRYPTO_gcm128_aad(key, &gcm, aadvec.in, aadvec.len)) { + return 0; + } } - if (!CRYPTO_gcm128_encrypt(key, &gcm, in, out, in_len)) { - return 0; + for (const CRYPTO_IOVEC &iovec : iovecs) { + if (!CRYPTO_gcm128_encrypt(key, &gcm, iovec.in, iovec.out, iovec.len)) { + return 0; + } } - if (extra_in_len > 0 && - !CRYPTO_gcm128_encrypt(key, &gcm, extra_in, out_tag, extra_in_len)) { - return 0; - } - - CRYPTO_gcm128_tag(key, &gcm, out_tag + extra_in_len, tag_len); - *out_tag_len = tag_len + extra_in_len; + CRYPTO_gcm128_tag(key, &gcm, out_tag.data(), tag_len); + *out_tag_len = tag_len; return 1; } -static int aead_aes_gcm_seal_scatter( - const EVP_AEAD_CTX *ctx, uint8_t *out, uint8_t *out_tag, - size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *extra_in, - size_t extra_in_len, const uint8_t *ad, size_t ad_len) { +static int aead_aes_gcm_sealv(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span out_tag, size_t *out_tag_len, + Span nonce, + Span aadvecs) { const struct aead_aes_gcm_ctx *gcm_ctx = (const struct aead_aes_gcm_ctx *)&ctx->state; - return aead_aes_gcm_seal_scatter_impl( - gcm_ctx, out, out_tag, out_tag_len, max_out_tag_len, nonce, nonce_len, in, - in_len, extra_in, extra_in_len, ad, ad_len, ctx->tag_len); + return aead_aes_gcm_sealv_impl(gcm_ctx, iovecs, out_tag, out_tag_len, nonce, + aadvecs, ctx->tag_len); } -static int aead_aes_gcm_open_gather_impl(const struct aead_aes_gcm_ctx *gcm_ctx, - uint8_t *out, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, - size_t in_len, const uint8_t *in_tag, - size_t in_tag_len, const uint8_t *ad, - size_t ad_len, size_t tag_len) { +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_len == 0) { + if (nonce.size() == 0) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE_SIZE); return 0; } - if (in_tag_len != tag_len) { + if (in_tag.size() != tag_len) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } const GCM128_KEY *key = &gcm_ctx->key; GCM128_CONTEXT gcm; - CRYPTO_gcm128_init_ctx(key, &gcm, nonce, nonce_len); + CRYPTO_gcm128_init_ctx(key, &gcm, nonce.data(), nonce.size()); - if (!CRYPTO_gcm128_aad(key, &gcm, ad, ad_len)) { - return 0; + for (const CRYPTO_IVEC &aadvec : aadvecs) { + if (!CRYPTO_gcm128_aad(key, &gcm, aadvec.in, aadvec.len)) { + return 0; + } } - if (!CRYPTO_gcm128_decrypt(key, &gcm, in, out, in_len)) { - return 0; + for (const CRYPTO_IOVEC &iovec : iovecs) { + if (!CRYPTO_gcm128_decrypt(key, &gcm, iovec.in, iovec.out, iovec.len)) { + return 0; + } } CRYPTO_gcm128_tag(key, &gcm, tag, tag_len); - if (CRYPTO_memcmp(tag, in_tag, tag_len) != 0) { + if (CRYPTO_memcmp(tag, in_tag.data(), tag_len) != 0) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } @@ -841,15 +866,14 @@ static int aead_aes_gcm_open_gather_impl(const struct aead_aes_gcm_ctx *gcm_ctx, return 1; } -static int aead_aes_gcm_open_gather(const EVP_AEAD_CTX *ctx, uint8_t *out, - const uint8_t *nonce, size_t nonce_len, - const uint8_t *in, size_t in_len, - const uint8_t *in_tag, size_t in_tag_len, - const uint8_t *ad, size_t ad_len) { +static int aead_aes_gcm_openv_detached(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span nonce, + Span in_tag, + Span aadvecs) { struct aead_aes_gcm_ctx *gcm_ctx = (struct aead_aes_gcm_ctx *)&ctx->state; - if (!aead_aes_gcm_open_gather_impl(gcm_ctx, out, nonce, nonce_len, in, in_len, - in_tag, in_tag_len, ad, ad_len, - ctx->tag_len)) { + if (!aead_aes_gcm_openv_detached_impl(gcm_ctx, iovecs, nonce, in_tag, aadvecs, + ctx->tag_len)) { return 0; } @@ -864,12 +888,11 @@ DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_128_gcm) { out->nonce_len = AES_GCM_NONCE_LENGTH; out->overhead = EVP_AEAD_AES_GCM_TAG_LEN; out->max_tag_len = EVP_AEAD_AES_GCM_TAG_LEN; - out->seal_scatter_supports_extra_in = 1; out->init = aead_aes_gcm_init; out->cleanup = aead_aes_gcm_cleanup; - out->seal_scatter = aead_aes_gcm_seal_scatter; - out->open_gather = aead_aes_gcm_open_gather; + out->sealv = aead_aes_gcm_sealv; + out->openv_detached = aead_aes_gcm_openv_detached; } DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_192_gcm) { @@ -879,12 +902,11 @@ DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_192_gcm) { out->nonce_len = AES_GCM_NONCE_LENGTH; out->overhead = EVP_AEAD_AES_GCM_TAG_LEN; out->max_tag_len = EVP_AEAD_AES_GCM_TAG_LEN; - out->seal_scatter_supports_extra_in = 1; out->init = aead_aes_gcm_init; out->cleanup = aead_aes_gcm_cleanup; - out->seal_scatter = aead_aes_gcm_seal_scatter; - out->open_gather = aead_aes_gcm_open_gather; + out->sealv = aead_aes_gcm_sealv; + out->openv_detached = aead_aes_gcm_openv_detached; } DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_256_gcm) { @@ -894,12 +916,11 @@ DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_256_gcm) { out->nonce_len = AES_GCM_NONCE_LENGTH; out->overhead = EVP_AEAD_AES_GCM_TAG_LEN; out->max_tag_len = EVP_AEAD_AES_GCM_TAG_LEN; - out->seal_scatter_supports_extra_in = 1; out->init = aead_aes_gcm_init; out->cleanup = aead_aes_gcm_cleanup; - out->seal_scatter = aead_aes_gcm_seal_scatter; - out->open_gather = aead_aes_gcm_open_gather; + out->sealv = aead_aes_gcm_sealv; + out->openv_detached = aead_aes_gcm_openv_detached; } static int aead_aes_gcm_init_randnonce(EVP_AEAD_CTX *ctx, const uint8_t *key, @@ -921,24 +942,24 @@ static int aead_aes_gcm_init_randnonce(EVP_AEAD_CTX *ctx, const uint8_t *key, return 1; } -static int aead_aes_gcm_seal_scatter_randnonce( - const EVP_AEAD_CTX *ctx, uint8_t *out, uint8_t *out_tag, - size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *external_nonce, - size_t external_nonce_len, const uint8_t *in, size_t in_len, - const uint8_t *extra_in, size_t extra_in_len, const uint8_t *ad, - size_t ad_len) { - if (external_nonce_len != 0) { +static int aead_aes_gcm_sealv_randnonce(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span out_tag, + size_t *out_tag_len, + Span external_nonce, + Span aadvecs) { + if (external_nonce.size() != 0) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE_SIZE); return 0; } uint8_t nonce[AES_GCM_NONCE_LENGTH]; - if (max_out_tag_len < sizeof(nonce)) { + if (out_tag.size() < sizeof(nonce)) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); return 0; } - // |BCM_rand_bytes| calls within the fipsmodule should be wrapped with state + // `BCM_rand_bytes` calls within the fipsmodule should be wrapped with state // lock functions to avoid updating the service indicator with the DRBG // functions. FIPS_service_indicator_lock_state(); @@ -947,43 +968,39 @@ static int aead_aes_gcm_seal_scatter_randnonce( const struct aead_aes_gcm_ctx *gcm_ctx = (const struct aead_aes_gcm_ctx *)&ctx->state; - if (!aead_aes_gcm_seal_scatter_impl(gcm_ctx, out, out_tag, out_tag_len, - max_out_tag_len - AES_GCM_NONCE_LENGTH, - nonce, sizeof(nonce), in, in_len, - extra_in, extra_in_len, ad, ad_len, - ctx->tag_len - AES_GCM_NONCE_LENGTH)) { + if (!aead_aes_gcm_sealv_impl( + gcm_ctx, iovecs, out_tag.first(out_tag.size() - AES_GCM_NONCE_LENGTH), + out_tag_len, nonce, aadvecs, ctx->tag_len - AES_GCM_NONCE_LENGTH)) { return 0; } - assert(*out_tag_len + sizeof(nonce) <= max_out_tag_len); - memcpy(out_tag + *out_tag_len, nonce, sizeof(nonce)); + assert(*out_tag_len + sizeof(nonce) <= out_tag.size()); + CopyToPrefix(nonce, out_tag.subspan(*out_tag_len)); *out_tag_len += sizeof(nonce); AEAD_GCM_verify_service_indicator(ctx); return 1; } -static int aead_aes_gcm_open_gather_randnonce( - const EVP_AEAD_CTX *ctx, uint8_t *out, const uint8_t *external_nonce, - size_t external_nonce_len, const uint8_t *in, size_t in_len, - const uint8_t *in_tag, size_t in_tag_len, const uint8_t *ad, - size_t ad_len) { - if (external_nonce_len != 0) { +static int aead_aes_gcm_openv_detached_randnonce( + const EVP_AEAD_CTX *ctx, Span iovecs, + Span external_nonce, Span in_tag, + Span aadvecs) { + if (external_nonce.size() != 0) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE_SIZE); return 0; } - if (in_tag_len < AES_GCM_NONCE_LENGTH) { + if (in_tag.size() < AES_GCM_NONCE_LENGTH) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } - const uint8_t *nonce = in_tag + in_tag_len - AES_GCM_NONCE_LENGTH; const struct aead_aes_gcm_ctx *gcm_ctx = (const struct aead_aes_gcm_ctx *)&ctx->state; - if (!aead_aes_gcm_open_gather_impl( - gcm_ctx, out, nonce, AES_GCM_NONCE_LENGTH, in, in_len, in_tag, - in_tag_len - AES_GCM_NONCE_LENGTH, ad, ad_len, + if (!aead_aes_gcm_openv_detached_impl( + gcm_ctx, iovecs, in_tag.last(AES_GCM_NONCE_LENGTH), + in_tag.first(in_tag.size() - AES_GCM_NONCE_LENGTH), aadvecs, ctx->tag_len - AES_GCM_NONCE_LENGTH)) { return 0; } @@ -999,12 +1016,11 @@ DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_128_gcm_randnonce) { out->nonce_len = 0; out->overhead = EVP_AEAD_AES_GCM_TAG_LEN + AES_GCM_NONCE_LENGTH; out->max_tag_len = EVP_AEAD_AES_GCM_TAG_LEN + AES_GCM_NONCE_LENGTH; - out->seal_scatter_supports_extra_in = 1; out->init = aead_aes_gcm_init_randnonce; out->cleanup = aead_aes_gcm_cleanup; - out->seal_scatter = aead_aes_gcm_seal_scatter_randnonce; - out->open_gather = aead_aes_gcm_open_gather_randnonce; + out->sealv = aead_aes_gcm_sealv_randnonce; + out->openv_detached = aead_aes_gcm_openv_detached_randnonce; } DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_256_gcm_randnonce) { @@ -1014,12 +1030,11 @@ DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_256_gcm_randnonce) { out->nonce_len = 0; out->overhead = EVP_AEAD_AES_GCM_TAG_LEN + AES_GCM_NONCE_LENGTH; out->max_tag_len = EVP_AEAD_AES_GCM_TAG_LEN + AES_GCM_NONCE_LENGTH; - out->seal_scatter_supports_extra_in = 1; out->init = aead_aes_gcm_init_randnonce; out->cleanup = aead_aes_gcm_cleanup; - out->seal_scatter = aead_aes_gcm_seal_scatter_randnonce; - out->open_gather = aead_aes_gcm_open_gather_randnonce; + out->sealv = aead_aes_gcm_sealv_randnonce; + out->openv_detached = aead_aes_gcm_openv_detached_randnonce; } namespace { @@ -1029,7 +1044,7 @@ struct aead_aes_gcm_tls12_ctx { }; } // namespace -static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) >= +static_assert(sizeof(((EVP_AEAD_CTX *)nullptr)->state) >= sizeof(struct aead_aes_gcm_tls12_ctx), "AEAD state is too small"); static_assert(alignof(union evp_aead_ctx_st_state) >= @@ -1053,22 +1068,22 @@ static int aead_aes_gcm_tls12_init(EVP_AEAD_CTX *ctx, const uint8_t *key, return 1; } -static int aead_aes_gcm_tls12_seal_scatter( - const EVP_AEAD_CTX *ctx, uint8_t *out, uint8_t *out_tag, - size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *extra_in, - size_t extra_in_len, const uint8_t *ad, size_t ad_len) { +static int aead_aes_gcm_tls12_sealv(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span out_tag, size_t *out_tag_len, + Span nonce, + Span aadvecs) { struct aead_aes_gcm_tls12_ctx *gcm_ctx = (struct aead_aes_gcm_tls12_ctx *)&ctx->state; - if (nonce_len != AES_GCM_NONCE_LENGTH) { + if (nonce.size() != AES_GCM_NONCE_LENGTH) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE); return 0; } // The given nonces must be strictly monotonically increasing. uint64_t given_counter = - CRYPTO_load_u64_be(nonce + nonce_len - sizeof(uint64_t)); + CRYPTO_load_u64_be(nonce.last(sizeof(uint64_t)).data()); if (given_counter == UINT64_MAX || given_counter < gcm_ctx->min_next_nonce) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE); return 0; @@ -1076,9 +1091,7 @@ static int aead_aes_gcm_tls12_seal_scatter( gcm_ctx->min_next_nonce = given_counter + 1; - if (!aead_aes_gcm_seal_scatter(ctx, out, out_tag, out_tag_len, - max_out_tag_len, nonce, nonce_len, in, in_len, - extra_in, extra_in_len, ad, ad_len)) { + if (!aead_aes_gcm_sealv(ctx, iovecs, out_tag, out_tag_len, nonce, aadvecs)) { return 0; } @@ -1093,12 +1106,11 @@ DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_128_gcm_tls12) { out->nonce_len = AES_GCM_NONCE_LENGTH; out->overhead = EVP_AEAD_AES_GCM_TAG_LEN; out->max_tag_len = EVP_AEAD_AES_GCM_TAG_LEN; - out->seal_scatter_supports_extra_in = 1; out->init = aead_aes_gcm_tls12_init; out->cleanup = aead_aes_gcm_cleanup; - out->seal_scatter = aead_aes_gcm_tls12_seal_scatter; - out->open_gather = aead_aes_gcm_open_gather; + out->sealv = aead_aes_gcm_tls12_sealv; + out->openv_detached = aead_aes_gcm_openv_detached; } DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_256_gcm_tls12) { @@ -1108,12 +1120,11 @@ DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_256_gcm_tls12) { out->nonce_len = AES_GCM_NONCE_LENGTH; out->overhead = EVP_AEAD_AES_GCM_TAG_LEN; out->max_tag_len = EVP_AEAD_AES_GCM_TAG_LEN; - out->seal_scatter_supports_extra_in = 1; out->init = aead_aes_gcm_tls12_init; out->cleanup = aead_aes_gcm_cleanup; - out->seal_scatter = aead_aes_gcm_tls12_seal_scatter; - out->open_gather = aead_aes_gcm_open_gather; + out->sealv = aead_aes_gcm_tls12_sealv; + out->openv_detached = aead_aes_gcm_openv_detached; } namespace { @@ -1121,11 +1132,10 @@ struct aead_aes_gcm_tls13_ctx { struct aead_aes_gcm_ctx gcm_ctx; uint64_t min_next_nonce; uint64_t mask; - uint8_t first; }; } // namespace -static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) >= +static_assert(sizeof(((EVP_AEAD_CTX *)nullptr)->state) >= sizeof(struct aead_aes_gcm_tls13_ctx), "AEAD state is too small"); static_assert(alignof(union evp_aead_ctx_st_state) >= @@ -1138,7 +1148,6 @@ static int aead_aes_gcm_tls13_init(EVP_AEAD_CTX *ctx, const uint8_t *key, (struct aead_aes_gcm_tls13_ctx *)&ctx->state; gcm_ctx->min_next_nonce = 0; - gcm_ctx->first = 1; size_t actual_tag_len; if (!aead_aes_gcm_init_impl(&gcm_ctx->gcm_ctx, &actual_tag_len, key, key_len, @@ -1150,15 +1159,15 @@ static int aead_aes_gcm_tls13_init(EVP_AEAD_CTX *ctx, const uint8_t *key, return 1; } -static int aead_aes_gcm_tls13_seal_scatter( - const EVP_AEAD_CTX *ctx, uint8_t *out, uint8_t *out_tag, - size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *extra_in, - size_t extra_in_len, const uint8_t *ad, size_t ad_len) { +static int aead_aes_gcm_tls13_sealv(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span out_tag, size_t *out_tag_len, + Span nonce, + Span aadvecs) { struct aead_aes_gcm_tls13_ctx *gcm_ctx = (struct aead_aes_gcm_tls13_ctx *)&ctx->state; - if (nonce_len != AES_GCM_NONCE_LENGTH) { + if (nonce.size() != AES_GCM_NONCE_LENGTH) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE); return 0; } @@ -1167,26 +1176,24 @@ static int aead_aes_gcm_tls13_seal_scatter( // https://tools.ietf.org/html/rfc8446#section-5.3 for details of the TLS 1.3 // nonce construction. uint64_t given_counter = - CRYPTO_load_u64_be(nonce + nonce_len - sizeof(uint64_t)); + CRYPTO_load_u64_be(nonce.last(sizeof(uint64_t)).data()); - if (gcm_ctx->first) { + if (gcm_ctx->min_next_nonce == 0) { // In the first call the sequence number will be zero and therefore the // given nonce will be 0 ^ mask = mask. gcm_ctx->mask = given_counter; - gcm_ctx->first = 0; - } - given_counter ^= gcm_ctx->mask; - - if (given_counter == UINT64_MAX || given_counter < gcm_ctx->min_next_nonce) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE); - return 0; + gcm_ctx->min_next_nonce = 1; + } else { + given_counter ^= gcm_ctx->mask; + if (given_counter == UINT64_MAX || + given_counter < gcm_ctx->min_next_nonce) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE); + return 0; + } + gcm_ctx->min_next_nonce = given_counter + 1; } - gcm_ctx->min_next_nonce = given_counter + 1; - - if (!aead_aes_gcm_seal_scatter(ctx, out, out_tag, out_tag_len, - max_out_tag_len, nonce, nonce_len, in, in_len, - extra_in, extra_in_len, ad, ad_len)) { + if (!aead_aes_gcm_sealv(ctx, iovecs, out_tag, out_tag_len, nonce, aadvecs)) { return 0; } @@ -1201,12 +1208,11 @@ DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_128_gcm_tls13) { out->nonce_len = AES_GCM_NONCE_LENGTH; out->overhead = EVP_AEAD_AES_GCM_TAG_LEN; out->max_tag_len = EVP_AEAD_AES_GCM_TAG_LEN; - out->seal_scatter_supports_extra_in = 1; out->init = aead_aes_gcm_tls13_init; out->cleanup = aead_aes_gcm_cleanup; - out->seal_scatter = aead_aes_gcm_tls13_seal_scatter; - out->open_gather = aead_aes_gcm_open_gather; + out->sealv = aead_aes_gcm_tls13_sealv; + out->openv_detached = aead_aes_gcm_openv_detached; } DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_256_gcm_tls13) { @@ -1216,15 +1222,14 @@ DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_256_gcm_tls13) { out->nonce_len = AES_GCM_NONCE_LENGTH; out->overhead = EVP_AEAD_AES_GCM_TAG_LEN; out->max_tag_len = EVP_AEAD_AES_GCM_TAG_LEN; - out->seal_scatter_supports_extra_in = 1; out->init = aead_aes_gcm_tls13_init; out->cleanup = aead_aes_gcm_cleanup; - out->seal_scatter = aead_aes_gcm_tls13_seal_scatter; - out->open_gather = aead_aes_gcm_open_gather; + out->sealv = aead_aes_gcm_tls13_sealv; + out->openv_detached = aead_aes_gcm_openv_detached; } -int EVP_has_aes_hardware(void) { +int EVP_has_aes_hardware() { #if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) return hwaes_capable() && crypto_gcm_clmul_enabled(); #elif defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64) @@ -1233,5 +1238,3 @@ int EVP_has_aes_hardware(void) { return 0; #endif } - -OPENSSL_MSVC_PRAGMA(warning(pop)) diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/e_aesccm.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/e_aesccm.cc.inc index da7d8b1b..f5f2bc19 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/e_aesccm.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/e_aesccm.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,6 +19,7 @@ #include #include #include +#include #include "../aes/internal.h" #include "../delocate.h" @@ -21,6 +27,8 @@ #include "internal.h" +using namespace bssl; + struct ccm128_context { block128_f block; ctr128_f ctr; @@ -52,26 +60,31 @@ static size_t CRYPTO_ccm128_max_input(const struct ccm128_context *ctx) { static int ccm128_init_state(const struct ccm128_context *ctx, struct ccm128_state *state, const AES_KEY *key, - const uint8_t *nonce, size_t nonce_len, - const uint8_t *aad, size_t aad_len, + Span nonce, + Span aadvecs, size_t plaintext_len) { const block128_f block = ctx->block; const unsigned M = ctx->M; const unsigned L = ctx->L; - // |L| determines the expected |nonce_len| and the limit for |plaintext_len|. - if (plaintext_len > CRYPTO_ccm128_max_input(ctx) // - || nonce_len != 15 - L) { + // `L` determines the expected `nonce_len` and the limit for `plaintext_len`. + if (plaintext_len > CRYPTO_ccm128_max_input(ctx)) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); + return 0; + } + if (nonce.size() != 15 - L) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE_SIZE); return 0; } // Assemble the first block for computing the MAC. OPENSSL_memset(state, 0, sizeof(*state)); state->nonce[0] = (uint8_t)((L - 1) | ((M - 2) / 2) << 3); + size_t aad_len = bssl::iovec::TotalLength(aadvecs); if (aad_len != 0) { state->nonce[0] |= 0x40; // Set AAD Flag } - OPENSSL_memcpy(&state->nonce[1], nonce, nonce_len); + OPENSSL_memcpy(&state->nonce[1], nonce.data(), nonce.size()); for (unsigned i = 0; i < L; i++) { state->nonce[15 - i] = (uint8_t)(plaintext_len >> (8 * i)); } @@ -109,16 +122,26 @@ static int ccm128_init_state(const struct ccm128_context *ctx, i = 10; } - do { - for (; i < 16 && aad_len != 0; i++) { - state->cmac[i] ^= *aad; - aad++; - aad_len--; + while (!aadvecs.empty() && aadvecs.front().len == 0) { + aadvecs = aadvecs.subspan(1); + } + size_t offset = 0; + while (!aadvecs.empty()) { + for (; i < 16 && !aadvecs.empty(); i++) { + state->cmac[i] ^= aadvecs.front().in[offset]; + ++offset; + if (offset >= aadvecs.front().len) { + aadvecs = aadvecs.subspan(1); + while (!aadvecs.empty() && aadvecs.front().len == 0) { + aadvecs = aadvecs.subspan(1); + } + offset = 0; + } } (*block)(state->cmac, state->cmac, key); blocks++; i = 0; - } while (aad_len != 0); + } } // Per RFC 3610, section 2.6, the total number of block cipher operations done @@ -128,11 +151,12 @@ static int ccm128_init_state(const struct ccm128_context *ctx, if (plaintext_len + 15 < plaintext_len || remaining_blocks + blocks < blocks || (uint64_t)remaining_blocks + blocks > UINT64_C(1) << 61) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); return 0; } - // Assemble the first block for encrypting and decrypting. The bottom |L| - // bytes are replaced with a counter and all bit the encoding of |L| is + // Assemble the first block for encrypting and decrypting. The bottom `L` + // bytes are replaced with a counter and all bit the encoding of `L` is // cleared in the first byte. state->nonce[0] &= 7; return 1; @@ -140,7 +164,7 @@ static int ccm128_init_state(const struct ccm128_context *ctx, static int ccm128_encrypt(const struct ccm128_context *ctx, struct ccm128_state *state, const AES_KEY *key, - uint8_t *out, const uint8_t *in, size_t len) { + Span iovecs) { // The counter for encryption begins at one. for (unsigned i = 0; i < ctx->L; i++) { state->nonce[15 - i] = 0; @@ -149,32 +173,44 @@ static int ccm128_encrypt(const struct ccm128_context *ctx, uint8_t partial_buf[16]; unsigned num = 0; - CRYPTO_ctr128_encrypt_ctr32(in, out, len, key, state->nonce, partial_buf, - &num, ctx->ctr); + for (const CRYPTO_IOVEC &iovec : iovecs) { + CRYPTO_ctr128_encrypt_ctr32(iovec.in, iovec.out, iovec.len, key, + state->nonce, partial_buf, &num, ctx->ctr); + } return 1; } static int ccm128_compute_mac(const struct ccm128_context *ctx, struct ccm128_state *state, const AES_KEY *key, - uint8_t *out_tag, size_t tag_len, - const uint8_t *in, size_t len) { + Span out_tag, + Span iovecs, bool encrypt) { block128_f block = ctx->block; - if (tag_len != ctx->M) { + if (out_tag.size() != ctx->M) { + OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TAG_TOO_LARGE); return 0; } - // Incorporate |in| into the MAC. - while (len >= 16) { - CRYPTO_xor16(state->cmac, state->cmac, in); - (*block)(state->cmac, state->cmac, key); - in += 16; - len -= 16; - } - if (len > 0) { - for (size_t i = 0; i < len; i++) { - state->cmac[i] ^= in[i]; + auto update_mac = [&](const uint8_t *in, size_t len) { + while (len >= 16) { + CRYPTO_xor16(state->cmac, state->cmac, in); + (*block)(state->cmac, state->cmac, key); + in += 16; + len -= 16; } - (*block)(state->cmac, state->cmac, key); + if (len != 0) { + for (size_t i = 0; i < len; i++) { + state->cmac[i] ^= in[i]; + } + (*block)(state->cmac, state->cmac, key); + } + return true; + }; + + // Incorporate the plaintext into the MAC. + if (encrypt) { + bssl::iovec::ForEachBlockRange<16>(iovecs, update_mac, update_mac); + } else { + bssl::iovec::ForEachOutBlockRange<16>(iovecs, update_mac, update_mac); } // Encrypt the MAC with counter zero. @@ -185,34 +221,36 @@ static int ccm128_compute_mac(const struct ccm128_context *ctx, (*block)(state->nonce, tmp, key); CRYPTO_xor16(state->cmac, state->cmac, tmp); - OPENSSL_memcpy(out_tag, state->cmac, tag_len); + CopySpan(Span(state->cmac).first(out_tag.size()), out_tag); return 1; } static int CRYPTO_ccm128_encrypt(const struct ccm128_context *ctx, - const AES_KEY *key, uint8_t *out, - uint8_t *out_tag, size_t tag_len, - const uint8_t *nonce, size_t nonce_len, - const uint8_t *in, size_t len, - const uint8_t *aad, size_t aad_len) { + const AES_KEY *key, + Span iovecs, + Span out_tag, + Span nonce, + Span aadvecs) { struct ccm128_state state; - return ccm128_init_state(ctx, &state, key, nonce, nonce_len, aad, aad_len, - len) && - ccm128_compute_mac(ctx, &state, key, out_tag, tag_len, in, len) && - ccm128_encrypt(ctx, &state, key, out, in, len); + return ccm128_init_state(ctx, &state, key, nonce, aadvecs, + bssl::iovec::TotalLength(iovecs)) && + ccm128_compute_mac(ctx, &state, key, out_tag, iovecs, + /*encrypt=*/true) && + ccm128_encrypt(ctx, &state, key, iovecs); } static int CRYPTO_ccm128_decrypt(const struct ccm128_context *ctx, - const AES_KEY *key, uint8_t *out, - uint8_t *out_tag, size_t tag_len, - const uint8_t *nonce, size_t nonce_len, - const uint8_t *in, size_t len, - const uint8_t *aad, size_t aad_len) { + const AES_KEY *key, + Span iovecs, + Span out_tag, + Span nonce, + Span aadvecs) { struct ccm128_state state; - return ccm128_init_state(ctx, &state, key, nonce, nonce_len, aad, aad_len, - len) && - ccm128_encrypt(ctx, &state, key, out, in, len) && - ccm128_compute_mac(ctx, &state, key, out_tag, tag_len, out, len); + return ccm128_init_state(ctx, &state, key, nonce, aadvecs, + bssl::iovec::TotalLength(iovecs)) && + ccm128_encrypt(ctx, &state, key, iovecs) && + ccm128_compute_mac(ctx, &state, key, out_tag, iovecs, + /*encrypt=*/false); } #define EVP_AEAD_AES_CCM_MAX_TAG_LEN 16 @@ -227,7 +265,7 @@ struct aead_aes_ccm_ctx { }; } // namespace -static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) >= +static_assert(sizeof(((EVP_AEAD_CTX *)nullptr)->state) >= sizeof(struct aead_aes_ccm_ctx), "AEAD state is too small"); static_assert(alignof(union evp_aead_ctx_st_state) >= @@ -258,7 +296,8 @@ static int aead_aes_ccm_init(EVP_AEAD_CTX *ctx, const uint8_t *key, struct aead_aes_ccm_ctx *ccm_ctx = (struct aead_aes_ccm_ctx *)&ctx->state; block128_f block; - ctr128_f ctr = aes_ctr_set_key(&ccm_ctx->ks.ks, NULL, &block, key, key_len); + ctr128_f ctr = + aes_ctr_set_key(&ccm_ctx->ks.ks, nullptr, &block, key, key_len); ctx->tag_len = tag_len; if (!CRYPTO_ccm128_init(&ccm_ctx->ccm, &ccm_ctx->ks.ks, block, ctr, M, L)) { OPENSSL_PUT_ERROR(CIPHER, ERR_R_INTERNAL_ERROR); @@ -270,33 +309,32 @@ static int aead_aes_ccm_init(EVP_AEAD_CTX *ctx, const uint8_t *key, static void aead_aes_ccm_cleanup(EVP_AEAD_CTX *ctx) {} -static int aead_aes_ccm_seal_scatter( - const EVP_AEAD_CTX *ctx, uint8_t *out, uint8_t *out_tag, - size_t *out_tag_len, size_t max_out_tag_len, const uint8_t *nonce, - size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *extra_in, - size_t extra_in_len, const uint8_t *ad, size_t ad_len) { +static int aead_aes_ccm_sealv(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span out_tag, size_t *out_tag_len, + Span nonce, + Span aadvecs) { const struct aead_aes_ccm_ctx *ccm_ctx = (struct aead_aes_ccm_ctx *)&ctx->state; - if (in_len > CRYPTO_ccm128_max_input(&ccm_ctx->ccm)) { + if (bssl::iovec::TotalLength(iovecs) > + CRYPTO_ccm128_max_input(&ccm_ctx->ccm)) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); return 0; } - if (max_out_tag_len < ctx->tag_len) { + if (out_tag.size() < ctx->tag_len) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL); return 0; } - if (nonce_len != EVP_AEAD_nonce_length(ctx->aead)) { + if (nonce.size() != EVP_AEAD_nonce_length(ctx->aead)) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE_SIZE); return 0; } - if (!CRYPTO_ccm128_encrypt(&ccm_ctx->ccm, &ccm_ctx->ks.ks, out, out_tag, - ctx->tag_len, nonce, nonce_len, in, in_len, ad, - ad_len)) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); + if (!CRYPTO_ccm128_encrypt(&ccm_ctx->ccm, &ccm_ctx->ks.ks, iovecs, + out_tag.first(ctx->tag_len), nonce, aadvecs)) { return 0; } @@ -305,39 +343,37 @@ static int aead_aes_ccm_seal_scatter( return 1; } -static int aead_aes_ccm_open_gather(const EVP_AEAD_CTX *ctx, uint8_t *out, - const uint8_t *nonce, size_t nonce_len, - const uint8_t *in, size_t in_len, - const uint8_t *in_tag, size_t in_tag_len, - const uint8_t *ad, size_t ad_len) { +static int aead_aes_ccm_openv_detached(const EVP_AEAD_CTX *ctx, + Span iovecs, + Span nonce, + Span in_tag, + Span aadvecs) { const struct aead_aes_ccm_ctx *ccm_ctx = (struct aead_aes_ccm_ctx *)&ctx->state; - if (in_len > CRYPTO_ccm128_max_input(&ccm_ctx->ccm)) { + if (bssl::iovec::TotalLength(iovecs) > + CRYPTO_ccm128_max_input(&ccm_ctx->ccm)) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); return 0; } - if (nonce_len != EVP_AEAD_nonce_length(ctx->aead)) { + if (nonce.size() != EVP_AEAD_nonce_length(ctx->aead)) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_NONCE_SIZE); return 0; } - if (in_tag_len != ctx->tag_len) { + if (in_tag.size() != ctx->tag_len) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } uint8_t tag[EVP_AEAD_AES_CCM_MAX_TAG_LEN]; - assert(ctx->tag_len <= EVP_AEAD_AES_CCM_MAX_TAG_LEN); - if (!CRYPTO_ccm128_decrypt(&ccm_ctx->ccm, &ccm_ctx->ks.ks, out, tag, - ctx->tag_len, nonce, nonce_len, in, in_len, ad, - ad_len)) { - OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE); + if (!CRYPTO_ccm128_decrypt(&ccm_ctx->ccm, &ccm_ctx->ks.ks, iovecs, + Span(tag).first(ctx->tag_len), nonce, aadvecs)) { return 0; } - if (CRYPTO_memcmp(tag, in_tag, ctx->tag_len) != 0) { + if (CRYPTO_memcmp(tag, in_tag.data(), ctx->tag_len) != 0) { OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT); return 0; } @@ -361,8 +397,8 @@ DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_128_ccm_bluetooth) { out->init = aead_aes_ccm_bluetooth_init; out->cleanup = aead_aes_ccm_cleanup; - out->seal_scatter = aead_aes_ccm_seal_scatter; - out->open_gather = aead_aes_ccm_open_gather; + out->sealv = aead_aes_ccm_sealv; + out->openv_detached = aead_aes_ccm_openv_detached; } static int aead_aes_ccm_bluetooth_8_init(EVP_AEAD_CTX *ctx, const uint8_t *key, @@ -380,8 +416,8 @@ DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_128_ccm_bluetooth_8) { out->init = aead_aes_ccm_bluetooth_8_init; out->cleanup = aead_aes_ccm_cleanup; - out->seal_scatter = aead_aes_ccm_seal_scatter; - out->open_gather = aead_aes_ccm_open_gather; + out->sealv = aead_aes_ccm_sealv; + out->openv_detached = aead_aes_ccm_openv_detached; } static int aead_aes_ccm_matter_init(EVP_AEAD_CTX *ctx, const uint8_t *key, @@ -399,6 +435,6 @@ DEFINE_METHOD_FUNCTION(EVP_AEAD, EVP_aead_aes_128_ccm_matter) { out->init = aead_aes_ccm_matter_init; out->cleanup = aead_aes_ccm_cleanup; - out->seal_scatter = aead_aes_ccm_seal_scatter; - out->open_gather = aead_aes_ccm_open_gather; + out->sealv = aead_aes_ccm_sealv; + out->openv_detached = aead_aes_ccm_openv_detached; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/internal.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/internal.h index e297facf..8e0db28f 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/internal.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/cipher/internal.h @@ -1,29 +1,39 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. -#ifndef OPENSSL_HEADER_CIPHER_INTERNAL_H -#define OPENSSL_HEADER_CIPHER_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_CIPHER_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_CIPHER_INTERNAL_H #include #include #include +#include #include "../../internal.h" +#include "../../mem_internal.h" #include "../aes/internal.h" -#if defined(__cplusplus) +#include +#include +#include +#include + extern "C" { -#endif -// EVP_CIPH_MODE_MASK contains the bits of |flags| that represent the mode. +// EVP_CIPH_MODE_MASK contains the bits of `flags` that represent the mode. #define EVP_CIPH_MODE_MASK 0x3f // EVP_AEAD represents a specific AEAD algorithm. @@ -32,37 +42,39 @@ struct evp_aead_st { uint8_t nonce_len; uint8_t overhead; uint8_t max_tag_len; - int seal_scatter_supports_extra_in; - // init initialises an |EVP_AEAD_CTX|. If this call returns zero then - // |cleanup| will not be called for that context. + // init initialises an `EVP_AEAD_CTX`. If this call returns zero then + // `cleanup` will not be called for that context. int (*init)(EVP_AEAD_CTX *, const uint8_t *key, size_t key_len, size_t tag_len); int (*init_with_direction)(EVP_AEAD_CTX *, const uint8_t *key, size_t key_len, size_t tag_len, enum evp_aead_direction_t dir); void (*cleanup)(EVP_AEAD_CTX *); - int (*open)(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len, - size_t max_out_len, const uint8_t *nonce, size_t nonce_len, - const uint8_t *in, size_t in_len, const uint8_t *ad, - size_t ad_len); + // AEADs need to provide one of the following sets of methods: + // + // - openv + sealv: variable tag length AEAD. + // - openv_detached + sealv: fixed tag length AEAD. - int (*seal_scatter)(const EVP_AEAD_CTX *ctx, uint8_t *out, uint8_t *out_tag, - size_t *out_tag_len, size_t max_out_tag_len, - const uint8_t *nonce, size_t nonce_len, const uint8_t *in, - size_t in_len, const uint8_t *extra_in, - size_t extra_in_len, const uint8_t *ad, size_t ad_len); + int (*openv)(const EVP_AEAD_CTX *ctx, bssl::Span iovecs, + size_t *out_total_bytes, bssl::Span nonce, + bssl::Span aadvecs); - int (*open_gather)(const EVP_AEAD_CTX *ctx, uint8_t *out, - const uint8_t *nonce, size_t nonce_len, const uint8_t *in, - size_t in_len, const uint8_t *in_tag, size_t in_tag_len, - const uint8_t *ad, size_t ad_len); + int (*sealv)(const EVP_AEAD_CTX *ctx, bssl::Span iovecs, + bssl::Span out_tag, size_t *out_tag_len, + bssl::Span nonce, + bssl::Span aadvecs); + + int (*openv_detached)(const EVP_AEAD_CTX *ctx, + bssl::Span iovecs, + bssl::Span nonce, + bssl::Span in_tag, + bssl::Span aadvecs); int (*get_iv)(const EVP_AEAD_CTX *ctx, const uint8_t **out_iv, size_t *out_len); - size_t (*tag_len)(const EVP_AEAD_CTX *ctx, size_t in_Len, - size_t extra_in_len); + size_t (*tag_len)(const EVP_AEAD_CTX *ctx, size_t in_len); }; struct evp_cipher_st { @@ -84,25 +96,366 @@ struct evp_cipher_st { // cipher. unsigned ctx_size; - // flags contains the OR of a number of flags. See |EVP_CIPH_*|. + // flags contains the OR of a number of flags. See `EVP_CIPH_*`. uint32_t flags; int (*init)(EVP_CIPHER_CTX *ctx, const uint8_t *key, const uint8_t *iv, int enc); - int (*cipher)(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, - size_t inl); + // cipher encrypts/decrypts `in`, write output to `out`. Writes exactly `len` + // bytes, which must be a multiple of the `block_size`. + // + // For ciphers where encryption and decryption operations differ, `init` + // shall set an internal state for this. + // + // Returns 1 on success, or 0 on error. + int (*cipher_update)(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, + size_t len); + + // cipher_final finalizes the cipher, performing possible final + // authentication checks. + // + // Only used for `EVP_CIPH_FLAG_CUSTOM_CIPHER` ciphers. + // + // Returns 1 on success, or 0 on error. When decrypting, if an error is + // returned, the decrypted data must not be used. + int (*cipher_final)(EVP_CIPHER_CTX *ctx); + + // update_aad adds `in` (of length `inl`) to the authenticated data for the + // encryption operation. + // + // Only used for `EVP_CIPH_FLAG_CUSTOM_CIPHER` ciphers. + // + // Returns 1 on success, or 0 on error. + int (*update_aad)(EVP_CIPHER_CTX *ctx, const uint8_t *in, size_t inl); // cleanup, if non-NULL, releases memory associated with the context. It is - // called if |EVP_CTRL_INIT| succeeds. Note that |init| may not have been + // called if `EVP_CTRL_INIT` succeeds. Note that `init` may not have been // called at this point. void (*cleanup)(EVP_CIPHER_CTX *); int (*ctrl)(EVP_CIPHER_CTX *, int type, int arg, void *ptr); }; -#if defined(__cplusplus) } // extern C -#endif -#endif // OPENSSL_HEADER_CIPHER_INTERNAL_H +BSSL_NAMESPACE_BEGIN + +// CopySpan copies an entire span of bytes from `from` to `to`. +// +// The spans need to have the same length. +inline void CopySpan(Span from, Span to) { + BSSL_CHECK(from.size() == to.size()); + std::copy(from.begin(), from.end(), to.begin()); +} + +// CopyToPrefix copies a span of bytes from `from` into `to`. It aborts +// if there is not enough space. +// +// TODO(crbug.com/404286922): Can we simplify this in a C++20 world (e.g. +// std::ranges::copy)? Must preserve range checking on the destination span. +inline void CopyToPrefix(Span from, Span to) { + CopySpan(from, to.first(from.size())); +} + +// Generic CRYPTO_IOVEC/CRYPTO_IVEC helpers. +namespace iovec { + +// IsValid returns whether the given `CRYPTO_IVEC` or `CRYPTO_IOVEC` is +// valid for use with public APIs, i.e. does not contain more than `SIZE_MAX` +// bytes. Note that the `EVP_AEAD` methods need to accept an arbitrary number +// of chunks. +template +inline bool IsValid(Span ivecs) { + size_t allowed = SIZE_MAX; + for (const IVec &ivec : ivecs) { + size_t len = ivec.len; + if (len > allowed) { + return false; + } + allowed -= len; + } + return true; +} + +// Length returns the total length in bytes of a given `CRYPTO_IVEC` or +// `CRYPTO_IOVEC`. +template +inline size_t TotalLength(Span ivecs) { + size_t total = 0; + for (const IVec &ivec : ivecs) { + total += ivec.len; + } + return total; +} + +// GetAndRemoveSuffix takes `suffix_buf.size()` final bytes from the given +// `CRYPTO_IVEC` or `CRYPTO_IOVEC` (mutating said iovec to no longer contain +// those bytes) and returns them. +// +// If the byte range is contained in a single chunk of `ivecs`, it will just +// return that span pointing into `ivecs`; otherwise, it will copy the bytes +// into `out` and return that. +// +// If `ivecs` is too short, returns `nullopt`. +template +inline std::optional> GetAndRemoveSuffix( + Span suffix_buf, Span ivecs) { + // Get the trivial case out. + if (suffix_buf.empty()) { + return suffix_buf; + } + // Strip trailing zero length chunks. + while (!ivecs.empty() && ivecs.back().len == 0) { + ivecs = ivecs.first(ivecs.size() - 1); + } + if (ivecs.empty()) { + return std::nullopt; + } + // Is the requested chunk entirely contained? If so, just return it. + if (ivecs.back().len >= suffix_buf.size()) { + ivecs.back().len -= suffix_buf.size(); + return Span(ivecs.back().*ReadFrom + ivecs.back().len, suffix_buf.size()); + } + // Otherwise, collect it into the buffer while trimming `ivecs`. + Span remaining = suffix_buf; + while (!ivecs.empty()) { + Span src(ivecs.back().*ReadFrom, ivecs.back().len); + if (src.size() >= remaining.size()) { + CopySpan(src.last(remaining.size()), remaining); + ivecs.back().len -= remaining.size(); + return suffix_buf; + } + CopySpan(src, remaining.last(src.size())); + remaining = remaining.first(remaining.size() - src.size()); + ivecs.back().len = 0; + ivecs = ivecs.first(ivecs.size() - 1); + } + return std::nullopt; +} + +// GetAndRemoveOutSuffix is like `GetAndRemoveSuffix` but takes from a +// `CRYPTO_IOVEC`'s `out` member instead. +inline std::optional> GetAndRemoveOutSuffix( + Span out, Span iovecs) { + return GetAndRemoveSuffix(out, iovecs); +} + +namespace internal { +inline void CopySpanToIOVec(Span out, CRYPTO_IOVEC head, + Span rest) { + for (;;) { + size_t to_copy = std::min(head.len, out.size()); + CopySpan(out.first(to_copy), Span(head.out, to_copy)); + out = out.subspan(to_copy); + if (out.empty()) { + break; + } + head = rest.front(); // Checkfails if insufficient space in CRYPTO_IOVEC. + rest = rest.subspan(1); + } +} +} // namespace internal + +// ForEachBlockRange iterates over the `ivecs` as follows: +// +// - `f_whole` gets called on whole blocks crossing `ivecs` chunk boundaries, or +// ranges of whole blocks that are entirely in chunks. +// - `f` gets called exactly once, on the last block range which may +// end up with a partial block. +// - Both functions receive an `in` pointer that either points into `ivecs` or +// into a chunk assembly buffer and a `len` which indicates the number of +// bytes from `in` that can be accessed. If the function returns 0, +// iteration stops. +// - If `WriteOut` is set, `f_whole` and `f` receive an extra `out` +// argument to which they can write output. This output will be placed into +// the `ivecs`'s `out` members either during or after the call. If iteration +// was stopped, the contents of `out` are indeterminate. +// - The return value is true if iteration was not stopped by the callbacks. +template < + size_t BlockSize, bool WriteOut = false, typename IVec, + typename ReadFromT = const uint8_t *, ReadFromT IVec::*ReadFrom = &IVec::in, + typename /* bool(const uint8_t *in, [uint8_t *out,] size_t len) */ FWhole, + typename /* bool(const uint8_t *in, [uint8_t *out,] size_t len) */ + FFinal> +inline bool ForEachBlockRange(Span ivecs, const FWhole &f_whole, + const FFinal &f_final) { + using MutableIVec = std::remove_const_t; + // Helper to make the function calls simpler. + auto call_func = [&](const auto &f, const IVec &ivec) { + if constexpr (WriteOut) { + return f(ivec.*ReadFrom, ivec.out, ivec.len); + } else { + return f(ivec.*ReadFrom, ivec.len); + } + }; + // Helper to cut from the start of an IVec. + auto remove_prefix = [&](MutableIVec &ivec, size_t by) { + ivec.*ReadFrom += by; + if constexpr (WriteOut) { + ivec.out += by; + } + ivec.len -= by; + }; + // Helper to copy a range to an iovec list. + auto maybe_copy_to_iovec = [&](Span out, MutableIVec head, + Span rest) { + if constexpr (WriteOut) { + internal::CopySpanToIOVec(out, head, rest); + } + }; + + // Ensure the last item in `ivecs` is nonempty. This is necessary for + // detecting being at the end and calling `f_final` at the appropriate time. + Span ivecs_trimmed = ivecs; + while (!ivecs_trimmed.empty() && ivecs_trimmed.back().len == 0) { + ivecs_trimmed = ivecs_trimmed.first(ivecs_trimmed.size() - 1); + } + if (ivecs_trimmed.empty()) { + return call_func(f_final, IVec{}); + } + + // Now there are at least two non-empty `ivecs`, and neither the first nor the + // last can be empty. + + MutableIVec current_range_head = ivecs_trimmed.front(); + Span current_range_rest = ivecs_trimmed.subspan(1); + while (!current_range_rest.empty()) { + // Process as many whole blocks as possible. + size_t whole_blocks_len = (current_range_head.len / BlockSize) * BlockSize; + if (whole_blocks_len != 0) { + MutableIVec whole_part = current_range_head; + whole_part.len = whole_blocks_len; + if (!call_func(f_whole, whole_part)) { + return false; + } + remove_prefix(current_range_head, whole_blocks_len); + } + + if (current_range_head.len == 0) { + current_range_head = current_range_rest.front(); + current_range_rest = current_range_rest.subspan(1); + continue; + } + + // Collect a whole block. + alignas(BlockSize) InplaceVector in; + alignas(BlockSize) uint8_t out[BlockSize]; + MutableIVec collect_from_head = current_range_head; + Span collect_from_rest = current_range_rest; + while (in.size() <= BlockSize) { + size_t remaining = BlockSize - in.size(); + if (remaining < collect_from_head.len) { + // Got enough to complete the block _and more_. + in.Append(Span(collect_from_head.*ReadFrom, remaining)); + remove_prefix(collect_from_head, remaining); + break; + } + // Consume all of `ivec` and advance. + in.Append(Span(collect_from_head.*ReadFrom, collect_from_head.len)); + if (collect_from_rest.empty()) { + // Nothing left - so this is the final block. + auto finalout = Span(out).first(in.size()); + MutableIVec finalvec = {}; + finalvec.len = in.size(); + finalvec.*ReadFrom = in.data(); + if constexpr (WriteOut) { + finalvec.out = finalout.data(); + } + if (!call_func(f_final, finalvec)) { + return false; + } + maybe_copy_to_iovec(finalout, current_range_head, current_range_rest); + return true; + } + collect_from_head = collect_from_rest.front(); + collect_from_rest = collect_from_rest.subspan(1); + } + assert(in.size() == BlockSize); + + // The above loop ensures this condition by the `break` only happening if + // `collect_from_head` has at least one byte remaining, and the loop + // otherwise ensuring as an invariant that the final chunk - which is + // nonempty - is among `collect_from_head` and `collect_from_rest`. + // + // As such, at least one byte is remaining, and thus calling `f_whole` is + // appropriate. + assert(collect_from_head.len != 0 || !collect_from_rest.empty()); + + // Process the block. + MutableIVec wholevec = {}; + wholevec.len = in.size(); + wholevec.*ReadFrom = in.data(); + if constexpr (WriteOut) { + wholevec.out = out; + } + if (!call_func(f_whole, wholevec)) { + return false; + } + maybe_copy_to_iovec(Span(out).first(in.size()), current_range_head, + current_range_rest); + + // Set the new position. + current_range_head = collect_from_head; + current_range_rest = collect_from_rest; + } + + // If current_range_head.len is zero, then the last item of ivecs is empty. + // That however was excluded at the start of the function to ensure `f_final` + // is always used for the last call. + assert(current_range_head.len != 0); + + return call_func(f_final, current_range_head); +} + +// MaybeInplaceArray can hold a copy of a CRYPTO_IOVEC. If it is a low +// amount of entries, it will be stored on the stack, otherwise on the heap. +using MaybeInplaceArray = bssl::MaybeInplaceArray; + +// ForEachOutBlockRange is like `ForEachBlockRange` but reads from a +// `CRYPTO_IOVEC`'s `out` member instead. +template < + size_t BlockSize, + typename /* int(const uint8_t *in, [uint8_t *out,] size_t len) */ FWhole, + typename /* int(const uint8_t *in, [uint8_t *out,] size_t len) */ + FFinal> +inline int ForEachOutBlockRange(Span iovecs, + const FWhole &f_whole, const FFinal &f_final) { + return ForEachBlockRange(iovecs, f_whole, + f_final); +} + +// ForEachBlockRange_Dynamic is simply `ForEachBlockRange` with a +// runtime dispatch on the block size. +template < + bool WriteOut = false, typename IVec, typename ReadFromT = const uint8_t *, + ReadFromT IVec::*ReadFrom = &IVec::in, + typename /* int(const uint8_t *in, uint8_t *out, size_t len) */ FWhole, + typename /* int(const uint8_t *in, uint8_t *out, size_t len) */ + FFinal> +inline int ForEachBlockRange_Dynamic(size_t block_size, Span ivecs, + const FWhole &f_whole, + const FFinal &f_final) { + switch (block_size) { + case 8: + return ForEachBlockRange<8, WriteOut, IVec, ReadFromT, ReadFrom>( + ivecs, f_whole, f_final); + break; + case 16: + return ForEachBlockRange<16, WriteOut, IVec, ReadFromT, ReadFrom>( + ivecs, f_whole, f_final); + break; + default: + return 0; + } +} + +} // namespace iovec + +BSSL_NAMESPACE_END + +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_CIPHER_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/cmac/cmac.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/cmac/cmac.cc.inc index d52b840b..095412d2 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/cmac/cmac.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/cmac/cmac.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2010-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2010-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -18,9 +23,12 @@ #include #include "../../internal.h" +#include "../../mem_internal.h" #include "../service_indicator/internal.h" +using namespace bssl; + struct cmac_ctx_st { EVP_CIPHER_CTX cipher_ctx; // k1 and k2 are the CMAC subkeys. See @@ -29,7 +37,7 @@ struct cmac_ctx_st { uint8_t k2[AES_BLOCK_SIZE]; // Last (possibly partial) scratch uint8_t block[AES_BLOCK_SIZE]; - // block_used contains the number of valid bytes in |block|. + // block_used contains the number of valid bytes in `block`. unsigned block_used; }; @@ -67,7 +75,7 @@ int AES_CMAC(uint8_t out[16], const uint8_t *key, size_t key_len, // We have to verify that all the CMAC services actually succeed before // updating the indicator state, so we lock the state here. FIPS_service_indicator_lock_state(); - const int ok = CMAC_Init(&ctx, key, key_len, cipher, NULL /* engine */) && + const int ok = CMAC_Init(&ctx, key, key_len, cipher, nullptr /* engine */) && CMAC_Update(&ctx, in, in_len) && CMAC_Final(&ctx, out, &scratch_out_len); FIPS_service_indicator_unlock_state(); @@ -79,21 +87,21 @@ int AES_CMAC(uint8_t out[16], const uint8_t *key, size_t key_len, return ok; } -CMAC_CTX *CMAC_CTX_new(void) { - CMAC_CTX *ctx = reinterpret_cast(OPENSSL_malloc(sizeof(*ctx))); - if (ctx != NULL) { +CMAC_CTX *CMAC_CTX_new() { + CMAC_CTX *ctx = New(); + if (ctx != nullptr) { CMAC_CTX_init(ctx); } return ctx; } void CMAC_CTX_free(CMAC_CTX *ctx) { - if (ctx == NULL) { + if (ctx == nullptr) { return; } CMAC_CTX_cleanup(ctx); - OPENSSL_free(ctx); + Delete(ctx); } int CMAC_CTX_copy(CMAC_CTX *out, const CMAC_CTX *in) { @@ -107,14 +115,14 @@ int CMAC_CTX_copy(CMAC_CTX *out, const CMAC_CTX *in) { return 1; } -// binary_field_mul_x_128 treats the 128 bits at |in| as an element of GF(2¹²⁸) -// with a hard-coded reduction polynomial and sets |out| as x times the input. +// binary_field_mul_x_128 treats the 128 bits at `in` as an element of GF(2¹²⁸) +// with a hard-coded reduction polynomial and sets `out` as x times the input. // // See https://tools.ietf.org/html/rfc4493#section-2.3 static void binary_field_mul_x_128(uint8_t out[16], const uint8_t in[16]) { unsigned i; - // Shift |in| to left, including carry. + // Shift `in` to left, including carry. for (i = 0; i < 15; i++) { out[i] = (in[i] << 1) | (in[i + 1] >> 7); } @@ -124,14 +132,14 @@ static void binary_field_mul_x_128(uint8_t out[16], const uint8_t in[16]) { out[i] = (in[i] << 1) ^ ((0 - carry) & 0x87); } -// binary_field_mul_x_64 behaves like |binary_field_mul_x_128| but acts on an +// binary_field_mul_x_64 behaves like `binary_field_mul_x_128` but acts on an // element of GF(2⁶⁴). // // See https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38b.pdf static void binary_field_mul_x_64(uint8_t out[8], const uint8_t in[8]) { unsigned i; - // Shift |in| to left, including carry. + // Shift `in` to left, including carry. for (i = 0; i < 7; i++) { out[i] = (in[i] << 1) | (in[i + 1] >> 7); } @@ -148,18 +156,19 @@ int CMAC_Init(CMAC_CTX *ctx, const void *key, size_t key_len, int ret = 0; uint8_t scratch[AES_BLOCK_SIZE]; - // We have to avoid the underlying AES-CBC |EVP_CIPHER| services updating the + // We have to avoid the underlying AES-CBC `EVP_CIPHER` services updating the // indicator state, so we lock the state here. FIPS_service_indicator_lock_state(); size_t block_size = EVP_CIPHER_block_size(cipher); if ((block_size != AES_BLOCK_SIZE && block_size != 8 /* 3-DES */) || EVP_CIPHER_key_length(cipher) != key_len || - !EVP_EncryptInit_ex(&ctx->cipher_ctx, cipher, NULL, + !EVP_EncryptInit_ex(&ctx->cipher_ctx, cipher, nullptr, reinterpret_cast(key), kZeroIV) || !EVP_Cipher(&ctx->cipher_ctx, scratch, kZeroIV, block_size) || // Reset context again ready for first data. - !EVP_EncryptInit_ex(&ctx->cipher_ctx, NULL, NULL, NULL, kZeroIV)) { + !EVP_EncryptInit_ex(&ctx->cipher_ctx, nullptr, nullptr, nullptr, + kZeroIV)) { goto out; } @@ -180,13 +189,14 @@ out: int CMAC_Reset(CMAC_CTX *ctx) { ctx->block_used = 0; - return EVP_EncryptInit_ex(&ctx->cipher_ctx, NULL, NULL, NULL, kZeroIV); + return EVP_EncryptInit_ex(&ctx->cipher_ctx, nullptr, nullptr, nullptr, + kZeroIV); } int CMAC_Update(CMAC_CTX *ctx, const uint8_t *in, size_t in_len) { int ret = 0; - // We have to avoid the underlying AES-CBC |EVP_Cipher| services updating the + // We have to avoid the underlying AES-CBC `EVP_Cipher` services updating the // indicator state, so we lock the state here. FIPS_service_indicator_lock_state(); @@ -205,9 +215,9 @@ int CMAC_Update(CMAC_CTX *ctx, const uint8_t *in, size_t in_len) { in_len -= todo; ctx->block_used += todo; - // If |in_len| is zero then either |ctx->block_used| is less than - // |block_size|, in which case we can stop here, or |ctx->block_used| is - // exactly |block_size| but there's no more data to process. In the latter + // If `in_len` is zero then either `ctx->block_used` is less than + // `block_size`, in which case we can stop here, or `ctx->block_used` is + // exactly `block_size` but there's no more data to process. In the latter // case we don't want to process this block now because it might be the last // block and that block is treated specially. if (in_len == 0) { @@ -232,7 +242,7 @@ int CMAC_Update(CMAC_CTX *ctx, const uint8_t *in, size_t in_len) { } OPENSSL_memcpy(ctx->block, in, in_len); - // |in_len| is bounded by |block_size|, which fits in |unsigned|. + // `in_len` is bounded by `block_size`, which fits in `unsigned`. static_assert(EVP_MAX_BLOCK_LENGTH < UINT_MAX, "EVP_MAX_BLOCK_LENGTH is too large"); ctx->block_used = (unsigned)in_len; @@ -248,13 +258,13 @@ int CMAC_Final(CMAC_CTX *ctx, uint8_t *out, size_t *out_len) { size_t block_size = EVP_CIPHER_CTX_block_size(&ctx->cipher_ctx); assert(block_size <= AES_BLOCK_SIZE); - // We have to avoid the underlying AES-CBC |EVP_Cipher| services updating the + // We have to avoid the underlying AES-CBC `EVP_Cipher` services updating the // indicator state, so we lock the state here. FIPS_service_indicator_lock_state(); *out_len = block_size; const uint8_t *mask = ctx->k1; - if (out == NULL) { + if (out == nullptr) { ret = 1; goto out; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/delocate.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/delocate.h index e7ba4597..7d773b31 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/delocate.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/delocate.h @@ -1,75 +1,78 @@ -/* Copyright 2017 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2017 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. -#ifndef OPENSSL_HEADER_FIPSMODULE_DELOCATE_H -#define OPENSSL_HEADER_FIPSMODULE_DELOCATE_H +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_DELOCATE_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_DELOCATE_H #include #include "../internal.h" -#if !defined(BORINGSSL_SHARED_LIBRARY) && defined(BORINGSSL_FIPS) && \ - !defined(OPENSSL_ASAN) && !defined(OPENSSL_MSAN) -#define DEFINE_BSS_GET(type, name, init_value) \ - static type name __attribute__((used)) = init_value; \ - extern "C" { \ - type *name##_bss_get(void) __attribute__((const)); \ - } -// For FIPS builds we require that CRYPTO_ONCE_INIT be zero. -#define DEFINE_STATIC_ONCE(name) \ - DEFINE_BSS_GET(CRYPTO_once_t, name, CRYPTO_ONCE_INIT) -// For FIPS builds we require that CRYPTO_MUTEX_INIT be zero. -#define DEFINE_STATIC_MUTEX(name) \ - DEFINE_BSS_GET(CRYPTO_MUTEX, name, CRYPTO_MUTEX_INIT) -// For FIPS builds we require that CRYPTO_EX_DATA_CLASS_INIT be zero. -#define DEFINE_STATIC_EX_DATA_CLASS(name) \ - DEFINE_BSS_GET(CRYPTO_EX_DATA_CLASS, name, CRYPTO_EX_DATA_CLASS_INIT) +#if defined(BORINGSSL_PREFIX) +#define BCM_ADD_PREFIX(name) BORINGSSL_ADD_PREFIX(bcm_##name) #else -#define DEFINE_BSS_GET(type, name, init_value) \ - static type name = init_value; \ - static type *name##_bss_get(void) { return &name; } -#define DEFINE_STATIC_ONCE(name) \ - static CRYPTO_once_t name = CRYPTO_ONCE_INIT; \ - static CRYPTO_once_t *name##_bss_get(void) { return &name; } -#define DEFINE_STATIC_MUTEX(name) \ - static CRYPTO_MUTEX name = CRYPTO_MUTEX_INIT; \ - static CRYPTO_MUTEX *name##_bss_get(void) { return &name; } -#define DEFINE_STATIC_EX_DATA_CLASS(name) \ - static CRYPTO_EX_DATA_CLASS name = CRYPTO_EX_DATA_CLASS_INIT; \ - static CRYPTO_EX_DATA_CLASS *name##_bss_get(void) { return &name; } +#define BCM_ADD_PREFIX(name) bcm_##name #endif -#define DEFINE_DATA(type, name, accessor_decorations) \ - DEFINE_BSS_GET(type, name##_storage, {}) \ - DEFINE_STATIC_ONCE(name##_once) \ - static void name##_do_init(type *out); \ - static void name##_init(void) { name##_do_init(name##_storage_bss_get()); } \ - accessor_decorations type *name(void) { \ - CRYPTO_once(name##_once_bss_get(), name##_init); \ - /* See http://c-faq.com/ansi/constmismatch.html for why the following \ - * cast is needed. */ \ - return (const type *)name##_storage_bss_get(); \ - } \ +#if !defined(BORINGSSL_SHARED_LIBRARY) && defined(BORINGSSL_FIPS) && \ + !defined(OPENSSL_ASAN) && !defined(OPENSSL_MSAN) +#define DEFINE_BSS_GET(type, name, init_expr) \ + /* delocate needs C linkage and for `name` to be unique across BCM. */ \ + extern "C" { \ + extern type BCM_ADD_PREFIX(name); \ + type BCM_ADD_PREFIX(name) init_expr; \ + type *BCM_ADD_PREFIX(name##_bss_get)() __attribute__((const)); \ + } /* extern "C" */ \ + \ + /* The getter functions are exported, but static variables are usually named \ + * with short names. Define a static wrapper function so the caller can use \ + * a short name, while the symbol itself is prefixed. */ \ + static type *name##_bss_get() { return BCM_ADD_PREFIX(name##_bss_get)(); } +#else +#define DEFINE_BSS_GET(type, name, init_expr) \ + static type name init_expr; \ + static type *name##_bss_get() { return &name; } +#endif + +// For FIPS builds we require each of these objects be all zero. +#define DEFINE_STATIC_ONCE(name) \ + DEFINE_BSS_GET(bssl::CRYPTO_once_t, name, = CRYPTO_ONCE_INIT) +#define DEFINE_STATIC_MUTEX(name) \ + DEFINE_BSS_GET(bssl::StaticMutex, name, /* default ctor */) +#define DEFINE_STATIC_EX_DATA_CLASS(name) \ + DEFINE_BSS_GET(bssl::ExDataClass, name, /* default ctor */) + +#define DEFINE_DATA(type, name, accessor_decorations) \ + DEFINE_BSS_GET(type, name##_storage, {}) \ + DEFINE_STATIC_ONCE(name##_once) \ + static void name##_do_init(type *out); \ + static void name##_init() { name##_do_init(name##_storage_bss_get()); } \ + accessor_decorations type *name() { \ + bssl::CRYPTO_once(name##_once_bss_get(), name##_init); \ + /* See http://c-faq.com/ansi/constmismatch.html for why the following \ + * cast is needed. */ \ + return (const type *)name##_storage_bss_get(); \ + } \ static void name##_do_init(type *out) -// DEFINE_METHOD_FUNCTION defines a function named |name| which returns a -// method table of type const |type|*. In FIPS mode, to avoid rel.ro data, it +// DEFINE_METHOD_FUNCTION defines a function named `name` which returns a +// method table of type const `type`*. In FIPS mode, to avoid rel.ro data, it // is split into a CRYPTO_once_t-guarded initializer in the module and // unhashed, non-module accessor functions to space reserved in the BSS. The // method table is initialized by a caller-supplied function which takes a -// parameter named |out| of type |type|*. The caller should follow the macro +// parameter named `out` of type `type`*. The caller should follow the macro // invocation with the body of this function: // // DEFINE_METHOD_FUNCTION(EVP_MD, EVP_md4) { @@ -89,4 +92,4 @@ #define DEFINE_LOCAL_DATA(type, name) DEFINE_DATA(type, name, static const) -#endif // OPENSSL_HEADER_FIPSMODULE_DELOCATE_H +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_DELOCATE_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/dh/check.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/dh/check.cc.inc index 3590b47f..73abdae4 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/dh/check.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/dh/check.cc.inc @@ -1,37 +1,51 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../bn/internal.h" #include "internal.h" -int dh_check_params_fast(const DH *dh) { +using namespace bssl; + +static_assert(OPENSSL_DH_MAX_MODULUS_BITS <= BN_MONTGOMERY_MAX_WORDS * BN_BITS2, + "Max DH size too big for Montgomery arithmetic"); + +int bssl::dh_check_params_fast(const DH *dh) { + auto *impl = FromOpaque(dh); + // Most operations scale with p and q. - if (BN_is_negative(dh->p) || !BN_is_odd(dh->p) || - BN_num_bits(dh->p) > OPENSSL_DH_MAX_MODULUS_BITS) { + if (BN_is_negative(impl->p.get()) || !BN_is_odd(impl->p.get()) || + BN_num_bits(impl->p.get()) > OPENSSL_DH_MAX_MODULUS_BITS) { OPENSSL_PUT_ERROR(DH, DH_R_INVALID_PARAMETERS); return 0; } // q must be bounded by p. - if (dh->q != NULL && (BN_is_negative(dh->q) || BN_ucmp(dh->q, dh->p) > 0)) { + if (impl->q != nullptr && (BN_is_negative(impl->q.get()) || + BN_ucmp(impl->q.get(), impl->p.get()) > 0)) { OPENSSL_PUT_ERROR(DH, DH_R_INVALID_PARAMETERS); return 0; } // g must be an element of p's multiplicative group. - if (BN_is_negative(dh->g) || BN_is_zero(dh->g) || - BN_ucmp(dh->g, dh->p) >= 0) { + if (BN_is_negative(impl->g.get()) || BN_is_zero(impl->g.get()) || + BN_ucmp(impl->g.get(), impl->p.get()) >= 0) { OPENSSL_PUT_ERROR(DH, DH_R_INVALID_PARAMETERS); return 0; } @@ -40,57 +54,52 @@ int dh_check_params_fast(const DH *dh) { } int DH_check_pub_key(const DH *dh, const BIGNUM *pub_key, int *out_flags) { + auto *impl = FromOpaque(dh); + *out_flags = 0; if (!dh_check_params_fast(dh)) { return 0; } - BN_CTX *ctx = BN_CTX_new(); - if (ctx == NULL) { + UniquePtr ctx(BN_CTX_new()); + if (ctx == nullptr) { return 0; } - BN_CTX_start(ctx); + BN_CTXScope scope(ctx.get()); - int ok = 0; - - // Check |pub_key| is greater than 1. + // Check `pub_key` is greater than 1. if (BN_cmp(pub_key, BN_value_one()) <= 0) { *out_flags |= DH_CHECK_PUBKEY_TOO_SMALL; } - // Check |pub_key| is less than |dh->p| - 1. - BIGNUM *tmp = BN_CTX_get(ctx); - if (tmp == NULL || - !BN_copy(tmp, dh->p) || - !BN_sub_word(tmp, 1)) { - goto err; + // Check `pub_key` is less than `impl->p` - 1. + BIGNUM *tmp = BN_CTX_get(ctx.get()); + if (tmp == nullptr || !BN_copy(tmp, impl->p.get()) || !BN_sub_word(tmp, 1)) { + return 0; } if (BN_cmp(pub_key, tmp) >= 0) { *out_flags |= DH_CHECK_PUBKEY_TOO_LARGE; } - if (dh->q != NULL) { - // Check |pub_key|^|dh->q| is 1 mod |dh->p|. This is necessary for RFC 5114 - // groups which are not safe primes but pick a generator on a prime-order - // subgroup of size |dh->q|. - if (!BN_mod_exp_mont(tmp, pub_key, dh->q, dh->p, ctx, NULL)) { - goto err; + if (impl->q != nullptr) { + // Check `pub_key`^`impl->q` is 1 mod `impl->p`. This is necessary for RFC + // 5114 groups which are not safe primes but pick a generator on a + // prime-order subgroup of size `impl->q`. + if (!BN_mod_exp_mont(tmp, pub_key, impl->q.get(), impl->p.get(), ctx.get(), + nullptr)) { + return 0; } if (!BN_is_one(tmp)) { *out_flags |= DH_CHECK_PUBKEY_INVALID; } } - ok = 1; - -err: - BN_CTX_end(ctx); - BN_CTX_free(ctx); - return ok; + return 1; } - int DH_check(const DH *dh, int *out_flags) { + auto *impl = FromOpaque(dh); + *out_flags = 0; if (!dh_check_params_fast(dh)) { return 0; @@ -102,65 +111,62 @@ int DH_check(const DH *dh, int *out_flags) { // for 3, p mod 12 == 5 // for 5, p mod 10 == 3 or 7 // should hold. - int ok = 0, r; - BN_CTX *ctx = NULL; - BN_ULONG l; - BIGNUM *t1 = NULL, *t2 = NULL; - - ctx = BN_CTX_new(); - if (ctx == NULL) { - goto err; + UniquePtr ctx(BN_CTX_new()); + if (ctx == nullptr) { + return 0; } - BN_CTX_start(ctx); - t1 = BN_CTX_get(ctx); - if (t1 == NULL) { - goto err; + BN_CTXScope scope(ctx.get()); + BIGNUM *t1 = BN_CTX_get(ctx.get()); + if (t1 == nullptr) { + return 0; } - t2 = BN_CTX_get(ctx); - if (t2 == NULL) { - goto err; + BIGNUM *t2 = BN_CTX_get(ctx.get()); + if (t2 == nullptr) { + return 0; } - if (dh->q) { - if (BN_cmp(dh->g, BN_value_one()) <= 0) { + if (impl->q) { + if (BN_cmp(impl->g.get(), BN_value_one()) <= 0) { *out_flags |= DH_CHECK_NOT_SUITABLE_GENERATOR; - } else if (BN_cmp(dh->g, dh->p) >= 0) { + } else if (BN_cmp(impl->g.get(), impl->p.get()) >= 0) { *out_flags |= DH_CHECK_NOT_SUITABLE_GENERATOR; } else { // Check g^q == 1 mod p - if (!BN_mod_exp_mont(t1, dh->g, dh->q, dh->p, ctx, NULL)) { - goto err; + if (!BN_mod_exp_mont(t1, impl->g.get(), impl->q.get(), impl->p.get(), + ctx.get(), nullptr)) { + return 0; } if (!BN_is_one(t1)) { *out_flags |= DH_CHECK_NOT_SUITABLE_GENERATOR; } } - r = BN_is_prime_ex(dh->q, BN_prime_checks_for_validation, ctx, NULL); + int r = BN_is_prime_ex(impl->q.get(), BN_prime_checks_for_validation, + ctx.get(), nullptr); if (r < 0) { - goto err; + return 0; } if (!r) { *out_flags |= DH_CHECK_Q_NOT_PRIME; } // Check p == 1 mod q i.e. q divides p - 1 - if (!BN_div(t1, t2, dh->p, dh->q, ctx)) { - goto err; + if (!BN_div(t1, t2, impl->p.get(), impl->q.get(), ctx.get())) { + return 0; } if (!BN_is_one(t2)) { *out_flags |= DH_CHECK_INVALID_Q_VALUE; } - } else if (BN_is_word(dh->g, DH_GENERATOR_2)) { - l = BN_mod_word(dh->p, 24); + } else if (BN_is_word(impl->g.get(), DH_GENERATOR_2)) { + BN_ULONG l = BN_mod_word(impl->p.get(), 24); if (l == (BN_ULONG)-1) { - goto err; + return 0; } if (l != 11) { *out_flags |= DH_CHECK_NOT_SUITABLE_GENERATOR; } - } else if (BN_is_word(dh->g, DH_GENERATOR_5)) { - l = BN_mod_word(dh->p, 10); + } else if (BN_is_word(impl->g.get(), DH_GENERATOR_5)) { + BN_ULONG l = BN_mod_word(impl->p.get(), 10); if (l == (BN_ULONG)-1) { - goto err; + return 0; } if (l != 3 && l != 7) { *out_flags |= DH_CHECK_NOT_SUITABLE_GENERATOR; @@ -169,30 +175,24 @@ int DH_check(const DH *dh, int *out_flags) { *out_flags |= DH_CHECK_UNABLE_TO_CHECK_GENERATOR; } - r = BN_is_prime_ex(dh->p, BN_prime_checks_for_validation, ctx, NULL); + int r = BN_is_prime_ex(impl->p.get(), BN_prime_checks_for_validation, + ctx.get(), nullptr); if (r < 0) { - goto err; + return 0; } if (!r) { *out_flags |= DH_CHECK_P_NOT_PRIME; - } else if (!dh->q) { - if (!BN_rshift1(t1, dh->p)) { - goto err; + } else if (!impl->q) { + if (!BN_rshift1(t1, impl->p.get())) { + return 0; } - r = BN_is_prime_ex(t1, BN_prime_checks_for_validation, ctx, NULL); + r = BN_is_prime_ex(t1, BN_prime_checks_for_validation, ctx.get(), nullptr); if (r < 0) { - goto err; + return 0; } if (!r) { *out_flags |= DH_CHECK_P_NOT_SAFE_PRIME; } } - ok = 1; - -err: - if (ctx != NULL) { - BN_CTX_end(ctx); - BN_CTX_free(ctx); - } - return ok; + return 1; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/dh/dh.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/dh/dh.cc.inc index 130f7447..b10a8180 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/dh/dh.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/dh/dh.cc.inc @@ -1,90 +1,80 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../../internal.h" +#include "../../mem_internal.h" #include "../bn/internal.h" #include "../service_indicator/internal.h" #include "internal.h" -DH *DH_new(void) { - DH *dh = reinterpret_cast(OPENSSL_zalloc(sizeof(DH))); - if (dh == NULL) { - return NULL; - } +using namespace bssl; - CRYPTO_MUTEX_init(&dh->method_mont_p_lock); - dh->references = 1; - return dh; -} +DH *DH_new() { return New(); } void DH_free(DH *dh) { - if (dh == NULL) { - return; + if (dh != nullptr) { + FromOpaque(dh)->DecRefInternal(); } - - if (!CRYPTO_refcount_dec_and_test_zero(&dh->references)) { - return; - } - - BN_MONT_CTX_free(dh->method_mont_p); - BN_clear_free(dh->p); - BN_clear_free(dh->g); - BN_clear_free(dh->q); - BN_clear_free(dh->pub_key); - BN_clear_free(dh->priv_key); - CRYPTO_MUTEX_cleanup(&dh->method_mont_p_lock); - - OPENSSL_free(dh); } -unsigned DH_bits(const DH *dh) { return BN_num_bits(dh->p); } +unsigned DH_bits(const DH *dh) { return BN_num_bits(FromOpaque(dh)->p.get()); } -const BIGNUM *DH_get0_pub_key(const DH *dh) { return dh->pub_key; } +const BIGNUM *DH_get0_pub_key(const DH *dh) { + return FromOpaque(dh)->pub_key.get(); +} -const BIGNUM *DH_get0_priv_key(const DH *dh) { return dh->priv_key; } +const BIGNUM *DH_get0_priv_key(const DH *dh) { + return FromOpaque(dh)->priv_key.get(); +} -const BIGNUM *DH_get0_p(const DH *dh) { return dh->p; } +const BIGNUM *DH_get0_p(const DH *dh) { return FromOpaque(dh)->p.get(); } -const BIGNUM *DH_get0_q(const DH *dh) { return dh->q; } +const BIGNUM *DH_get0_q(const DH *dh) { return FromOpaque(dh)->q.get(); } -const BIGNUM *DH_get0_g(const DH *dh) { return dh->g; } +const BIGNUM *DH_get0_g(const DH *dh) { return FromOpaque(dh)->g.get(); } void DH_get0_key(const DH *dh, const BIGNUM **out_pub_key, const BIGNUM **out_priv_key) { - if (out_pub_key != NULL) { - *out_pub_key = dh->pub_key; + auto *impl = FromOpaque(dh); + if (out_pub_key != nullptr) { + *out_pub_key = impl->pub_key.get(); } - if (out_priv_key != NULL) { - *out_priv_key = dh->priv_key; + if (out_priv_key != nullptr) { + *out_priv_key = impl->priv_key.get(); } } int DH_set0_key(DH *dh, BIGNUM *pub_key, BIGNUM *priv_key) { - if (pub_key != NULL) { - BN_free(dh->pub_key); - dh->pub_key = pub_key; + auto *impl = FromOpaque(dh); + if (pub_key != nullptr) { + impl->pub_key.reset(pub_key); } - if (priv_key != NULL) { - BN_free(dh->priv_key); - dh->priv_key = priv_key; + if (priv_key != nullptr) { + impl->priv_key.reset(priv_key); } return 1; @@ -92,45 +82,45 @@ int DH_set0_key(DH *dh, BIGNUM *pub_key, BIGNUM *priv_key) { void DH_get0_pqg(const DH *dh, const BIGNUM **out_p, const BIGNUM **out_q, const BIGNUM **out_g) { - if (out_p != NULL) { - *out_p = dh->p; + auto *impl = FromOpaque(dh); + if (out_p != nullptr) { + *out_p = impl->p.get(); } - if (out_q != NULL) { - *out_q = dh->q; + if (out_q != nullptr) { + *out_q = impl->q.get(); } - if (out_g != NULL) { - *out_g = dh->g; + if (out_g != nullptr) { + *out_g = impl->g.get(); } } int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g) { - if ((dh->p == NULL && p == NULL) || (dh->g == NULL && g == NULL)) { + auto *impl = FromOpaque(dh); + if ((impl->p == nullptr && p == nullptr) || + (impl->g == nullptr && g == nullptr)) { return 0; } - if (p != NULL) { - BN_free(dh->p); - dh->p = p; + if (p != nullptr) { + impl->p.reset(p); } - if (q != NULL) { - BN_free(dh->q); - dh->q = q; + if (q != nullptr) { + impl->q.reset(q); } - if (g != NULL) { - BN_free(dh->g); - dh->g = g; + if (g != nullptr) { + impl->g.reset(g); } // Invalidate the cached Montgomery parameters. - BN_MONT_CTX_free(dh->method_mont_p); - dh->method_mont_p = NULL; + impl->method_mont_p = nullptr; return 1; } int DH_set_length(DH *dh, unsigned priv_length) { - dh->priv_length = priv_length; + auto *impl = FromOpaque(dh); + impl->priv_length = priv_length; return 1; } @@ -141,117 +131,105 @@ int DH_generate_key(DH *dh) { return 0; } - int ok = 0; - int generate_new_key = 0; - BN_CTX *ctx = NULL; - BIGNUM *pub_key = NULL, *priv_key = NULL, *priv_key_limit = NULL; - - ctx = BN_CTX_new(); - if (ctx == NULL) { - goto err; + auto *impl = FromOpaque(dh); + UniquePtr ctx(BN_CTX_new()); + if (ctx == nullptr) { + OPENSSL_PUT_ERROR(DH, ERR_R_BN_LIB); + return 0; } - if (dh->priv_key == NULL) { - priv_key = BN_new(); - if (priv_key == NULL) { - goto err; + if (!BN_MONT_CTX_set_locked(&impl->method_mont_p, &impl->method_mont_p_lock, + impl->p.get(), ctx.get())) { + OPENSSL_PUT_ERROR(DH, ERR_R_BN_LIB); + return 0; + } + + // Only generate a private key if there's already one. Otherwise, + // `DH_generate_key` recomputes the public key. + const BIGNUM *priv_key = impl->priv_key.get(); + UniquePtr new_priv_key; + if (priv_key == nullptr) { + new_priv_key.reset(BN_new()); + if (new_priv_key == nullptr) { + OPENSSL_PUT_ERROR(DH, ERR_R_BN_LIB); + return 0; } - generate_new_key = 1; - } else { - priv_key = dh->priv_key; - } - - if (dh->pub_key == NULL) { - pub_key = BN_new(); - if (pub_key == NULL) { - goto err; - } - } else { - pub_key = dh->pub_key; - } - - if (!BN_MONT_CTX_set_locked(&dh->method_mont_p, &dh->method_mont_p_lock, - dh->p, ctx)) { - goto err; - } - - if (generate_new_key) { - if (dh->q) { + if (impl->q) { // Section 5.6.1.1.4 of SP 800-56A Rev3 generates a private key uniformly - // from [1, min(2^N-1, q-1)]. + // from [1, min(2ᴺ-1, q-1)]. // // Although SP 800-56A Rev3 now permits a private key length N, - // |dh->priv_length| historically was ignored when q is available. We + // `impl->priv_length` historically was ignored when q is available. We // continue to ignore it and interpret such a configuration as N = len(q). - if (!BN_rand_range_ex(priv_key, 1, dh->q)) { - goto err; + if (!BN_rand_range_ex(new_priv_key.get(), 1, impl->q.get())) { + OPENSSL_PUT_ERROR(DH, ERR_R_BN_LIB); + return 0; } } else { // If q is unspecified, we expect p to be a safe prime, with g generating // the (p-1)/2 subgroup. So, we use q = (p-1)/2. (If g generates a smaller // prime-order subgroup, q will still divide (p-1)/2.) // - // We set N from |dh->priv_length|. Section 5.6.1.1.4 of SP 800-56A Rev3 + // We set N from `impl->priv_length`. Section 5.6.1.1.4 of SP 800-56A Rev3 // says to reject N > len(q), or N > num_bits(p) - 1. However, this logic // originally aligned with PKCS#3, which allows num_bits(p). Instead, we - // clamp |dh->priv_length| before invoking the algorithm. + // clamp `impl->priv_length` before invoking the algorithm. - // Compute M = min(2^N, q). - priv_key_limit = BN_new(); - if (priv_key_limit == NULL) { - goto err; + // Compute M = min(2ᴺ, q). + UniquePtr priv_key_limit(BN_new()); + if (priv_key_limit == nullptr) { + OPENSSL_PUT_ERROR(DH, ERR_R_BN_LIB); + return 0; } - if (dh->priv_length == 0 || dh->priv_length >= BN_num_bits(dh->p) - 1) { + if (impl->priv_length == 0 || + impl->priv_length >= BN_num_bits(impl->p.get()) - 1) { // M = q = (p - 1) / 2. - if (!BN_rshift1(priv_key_limit, dh->p)) { - goto err; + if (!BN_rshift1(priv_key_limit.get(), impl->p.get())) { + OPENSSL_PUT_ERROR(DH, ERR_R_BN_LIB); + return 0; } } else { - // M = 2^N. - if (!BN_set_bit(priv_key_limit, dh->priv_length)) { - goto err; + // M = 2ᴺ. + if (!BN_set_bit(priv_key_limit.get(), impl->priv_length)) { + OPENSSL_PUT_ERROR(DH, ERR_R_BN_LIB); + return 0; } } // Choose a private key uniformly from [1, M-1]. - if (!BN_rand_range_ex(priv_key, 1, priv_key_limit)) { - goto err; + if (!BN_rand_range_ex(new_priv_key.get(), 1, priv_key_limit.get())) { + OPENSSL_PUT_ERROR(DH, ERR_R_BN_LIB); + return 0; } } + priv_key = new_priv_key.get(); } - if (!BN_mod_exp_mont_consttime(pub_key, dh->g, priv_key, dh->p, ctx, - dh->method_mont_p)) { - goto err; - } - - dh->pub_key = pub_key; - dh->priv_key = priv_key; - ok = 1; - -err: - if (ok != 1) { + UniquePtr new_pub_key(BN_new()); + if (new_pub_key == nullptr || + !BN_mod_exp_mont_consttime(new_pub_key.get(), impl->g.get(), priv_key, + impl->p.get(), ctx.get(), + impl->method_mont_p.get())) { OPENSSL_PUT_ERROR(DH, ERR_R_BN_LIB); + return 0; } - if (dh->pub_key == NULL) { - BN_free(pub_key); + impl->pub_key = std::move(new_pub_key); + if (new_priv_key != nullptr) { + impl->priv_key = std::move(new_priv_key); } - if (dh->priv_key == NULL) { - BN_free(priv_key); - } - BN_free(priv_key_limit); - BN_CTX_free(ctx); - return ok; + return 1; } static int dh_compute_key(DH *dh, BIGNUM *out_shared_key, const BIGNUM *peers_key, BN_CTX *ctx) { + auto *impl = FromOpaque(dh); + if (!dh_check_params_fast(dh)) { return 0; } - if (dh->priv_key == NULL) { + if (impl->priv_key == nullptr) { OPENSSL_PUT_ERROR(DH, DH_R_NO_PRIVATE_VALUE); return 0; } @@ -262,56 +240,47 @@ static int dh_compute_key(DH *dh, BIGNUM *out_shared_key, return 0; } - int ret = 0; - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *p_minus_1 = BN_CTX_get(ctx); - if (!p_minus_1 || - !BN_MONT_CTX_set_locked(&dh->method_mont_p, &dh->method_mont_p_lock, - dh->p, ctx)) { - goto err; + !BN_MONT_CTX_set_locked(&impl->method_mont_p, &impl->method_mont_p_lock, + impl->p.get(), ctx)) { + return 0; } - if (!BN_mod_exp_mont_consttime(out_shared_key, peers_key, dh->priv_key, dh->p, - ctx, dh->method_mont_p) || - !BN_copy(p_minus_1, dh->p) || !BN_sub_word(p_minus_1, 1)) { + if (!BN_mod_exp_mont_consttime(out_shared_key, peers_key, + impl->priv_key.get(), impl->p.get(), ctx, + impl->method_mont_p.get()) || + !BN_copy(p_minus_1, impl->p.get()) || !BN_sub_word(p_minus_1, 1)) { OPENSSL_PUT_ERROR(DH, ERR_R_BN_LIB); - goto err; + return 0; } // This performs the check required by SP 800-56Ar3 section 5.7.1.1 step two. if (BN_cmp_word(out_shared_key, 1) <= 0 || BN_cmp(out_shared_key, p_minus_1) == 0) { OPENSSL_PUT_ERROR(DH, DH_R_INVALID_PUBKEY); - goto err; + return 0; } - ret = 1; - -err: - BN_CTX_end(ctx); - return ret; + return 1; } -int dh_compute_key_padded_no_self_test(unsigned char *out, - const BIGNUM *peers_key, DH *dh) { - BN_CTX *ctx = BN_CTX_new(); - if (ctx == NULL) { +int bssl::dh_compute_key_padded_no_self_test(unsigned char *out, + const BIGNUM *peers_key, DH *dh) { + UniquePtr ctx(BN_CTX_new()); + if (ctx == nullptr) { return -1; } - BN_CTX_start(ctx); - + BN_CTXScope scope(ctx.get()); int dh_size = DH_size(dh); - int ret = -1; - BIGNUM *shared_key = BN_CTX_get(ctx); - if (shared_key && dh_compute_key(dh, shared_key, peers_key, ctx) && - BN_bn2bin_padded(out, dh_size, shared_key)) { - ret = dh_size; + BIGNUM *shared_key = BN_CTX_get(ctx.get()); + if (shared_key == nullptr || + !dh_compute_key(dh, shared_key, peers_key, ctx.get()) || + !BN_bn2bin_padded(out, dh_size, shared_key)) { + return -1; } - - BN_CTX_end(ctx); - BN_CTX_free(ctx); - return ret; + return dh_size; } int DH_compute_key_padded(unsigned char *out, const BIGNUM *peers_key, DH *dh) { @@ -323,22 +292,18 @@ int DH_compute_key_padded(unsigned char *out, const BIGNUM *peers_key, DH *dh) { int DH_compute_key(unsigned char *out, const BIGNUM *peers_key, DH *dh) { boringssl_ensure_ffdh_self_test(); - BN_CTX *ctx = BN_CTX_new(); - if (ctx == NULL) { + UniquePtr ctx(BN_CTX_new()); + if (ctx == nullptr) { return -1; } - BN_CTX_start(ctx); - - int ret = -1; - BIGNUM *shared_key = BN_CTX_get(ctx); - if (shared_key && dh_compute_key(dh, shared_key, peers_key, ctx)) { - // A |BIGNUM|'s byte count fits in |int|. - ret = (int)BN_bn2bin(shared_key, out); + BN_CTXScope scope(ctx.get()); + BIGNUM *shared_key = BN_CTX_get(ctx.get()); + if (shared_key == nullptr || + !dh_compute_key(dh, shared_key, peers_key, ctx.get())) { + return -1; } - - BN_CTX_end(ctx); - BN_CTX_free(ctx); - return ret; + // A `BIGNUM`'s byte count fits in `int`. + return static_cast(BN_bn2bin(shared_key, out)); } int DH_compute_key_hashed(DH *dh, uint8_t *out, size_t *out_len, @@ -365,7 +330,8 @@ int DH_compute_key_hashed(DH *dh, uint8_t *out, size_t *out_len, // Also, padded output avoids side-channels, so is always strongly // advisable. DH_compute_key_padded(shared_bytes, peers_key, dh) != (int)dh_len || - !EVP_Digest(shared_bytes, dh_len, out, &out_len_unsigned, digest, NULL) || + !EVP_Digest(shared_bytes, dh_len, out, &out_len_unsigned, digest, + nullptr) || out_len_unsigned != digest_len) { goto err; } @@ -379,16 +345,15 @@ err: return ret; } -int DH_size(const DH *dh) { return BN_num_bytes(dh->p); } - -unsigned DH_num_bits(const DH *dh) { return BN_num_bits(dh->p); } +int DH_size(const DH *dh) { return BN_num_bytes(FromOpaque(dh)->p.get()); } int DH_up_ref(DH *dh) { - CRYPTO_refcount_inc(&dh->references); + auto *impl = FromOpaque(dh); + impl->UpRefInternal(); return 1; } -DH *DH_get_rfc7919_2048(void) { +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. static const BN_ULONG kFFDHE2048Data[] = { @@ -410,29 +375,27 @@ DH *DH_get_rfc7919_2048(void) { TOBN(0xadf85458, 0xa2bb4a9a), TOBN(0xffffffff, 0xffffffff), }; - BIGNUM *const ffdhe2048_p = BN_new(); - BIGNUM *const ffdhe2048_q = BN_new(); - BIGNUM *const ffdhe2048_g = BN_new(); - DH *const dh = DH_new(); - + UniquePtr ffdhe2048_p(BN_new()); + UniquePtr ffdhe2048_q(BN_new()); + UniquePtr ffdhe2048_g(BN_new()); + UniquePtr dh(DH_new()); if (!ffdhe2048_p || !ffdhe2048_q || !ffdhe2048_g || !dh) { - goto err; + return nullptr; } - bn_set_static_words(ffdhe2048_p, kFFDHE2048Data, - OPENSSL_ARRAY_SIZE(kFFDHE2048Data)); + bn_set_static_words(ffdhe2048_p.get(), kFFDHE2048Data, + std::size(kFFDHE2048Data)); - if (!BN_rshift1(ffdhe2048_q, ffdhe2048_p) || !BN_set_word(ffdhe2048_g, 2) || - !DH_set0_pqg(dh, ffdhe2048_p, ffdhe2048_q, ffdhe2048_g)) { - goto err; + if (!BN_rshift1(ffdhe2048_q.get(), ffdhe2048_p.get()) || + !BN_set_word(ffdhe2048_g.get(), 2) || + !DH_set0_pqg(dh.get(), ffdhe2048_p.get(), ffdhe2048_q.get(), + ffdhe2048_g.get())) { + return nullptr; } + // `DH_set0_pqg` takes ownership on success. + ffdhe2048_p.release(); + ffdhe2048_q.release(); + ffdhe2048_g.release(); - return dh; - -err: - BN_free(ffdhe2048_p); - BN_free(ffdhe2048_q); - BN_free(ffdhe2048_g); - DH_free(dh); - return NULL; + return dh.release(); } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/dh/internal.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/dh/internal.h index fbc8d089..9de9ba83 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/dh/internal.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/dh/internal.h @@ -1,63 +1,63 @@ -/* Copyright 2022 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2022 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. #ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_DH_INTERNAL_H #define OPENSSL_HEADER_CRYPTO_FIPSMODULE_DH_INTERNAL_H #include -#include - #include "../../internal.h" - -#if defined(__cplusplus) -extern "C" { -#endif +#include "../../mem_internal.h" -struct dh_st { - BIGNUM *p; - BIGNUM *g; - BIGNUM *q; - BIGNUM *pub_key; // g^x mod p - BIGNUM *priv_key; // x +DECLARE_OPAQUE_STRUCT(dh_st, DHImpl) + +BSSL_NAMESPACE_BEGIN + +class DHImpl : public dh_st, public RefCounted { + public: + DHImpl() : RefCounted(CheckSubClass()) {} + + UniquePtr p; + UniquePtr g; + UniquePtr q; + UniquePtr pub_key; // gˣ mod p + UniquePtr priv_key; // x // priv_length contains the length, in bits, of the private value. If zero, - // the private value will be the same length as |p|. - unsigned priv_length; + // the private value will be the same length as `p`. + unsigned priv_length = 0; - CRYPTO_MUTEX method_mont_p_lock; - BN_MONT_CTX *method_mont_p; + mutable Mutex method_mont_p_lock; + mutable UniquePtr method_mont_p; - int flags; - CRYPTO_refcount_t references; + private: + friend RefCounted; + ~DHImpl() = default; }; -// dh_check_params_fast checks basic invariants on |dh|'s domain parameters. It -// does not check that |dh| forms a valid group, only that the sizes are within +// dh_check_params_fast checks basic invariants on `dh`'s domain parameters. It +// does not check that `dh` forms a valid group, only that the sizes are within // DoS bounds. int dh_check_params_fast(const DH *dh); -// dh_compute_key_padded_no_self_test does the same as |DH_compute_key_padded|, +// dh_compute_key_padded_no_self_test does the same as `DH_compute_key_padded`, // but doesn't try to run the self-test first. This is for use in the self tests // themselves, to prevent an infinite loop. int dh_compute_key_padded_no_self_test(unsigned char *out, const BIGNUM *peers_key, DH *dh); - -#if defined(__cplusplus) -} -#endif +BSSL_NAMESPACE_END #endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_DH_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/digest.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/digest.cc.inc index eae66552..c643d021 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/digest.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/digest.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,9 +21,12 @@ #include #include "../../internal.h" +#include "../../mem_internal.h" #include "internal.h" +using namespace bssl; + int EVP_MD_type(const EVP_MD *md) { return md->type; } int EVP_MD_nid(const EVP_MD *md) { return EVP_MD_type(md); } @@ -31,12 +39,13 @@ size_t EVP_MD_block_size(const EVP_MD *md) { return md->block_size; } void EVP_MD_CTX_init(EVP_MD_CTX *ctx) { - OPENSSL_memset(ctx, 0, sizeof(EVP_MD_CTX)); + ctx->digest = nullptr; + ctx->pctx = nullptr; + ctx->pctx_ops = nullptr; } -EVP_MD_CTX *EVP_MD_CTX_new(void) { - EVP_MD_CTX *ctx = - reinterpret_cast(OPENSSL_malloc(sizeof(EVP_MD_CTX))); +EVP_MD_CTX *EVP_MD_CTX_new() { + EVP_MD_CTX *ctx = New(); if (ctx) { EVP_MD_CTX_init(ctx); @@ -45,12 +54,10 @@ EVP_MD_CTX *EVP_MD_CTX_new(void) { return ctx; } -EVP_MD_CTX *EVP_MD_CTX_create(void) { return EVP_MD_CTX_new(); } +EVP_MD_CTX *EVP_MD_CTX_create() { return EVP_MD_CTX_new(); } int EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx) { - OPENSSL_free(ctx->md_data); - - assert(ctx->pctx == NULL || ctx->pctx_ops != NULL); + assert(ctx->pctx == nullptr || ctx->pctx_ops != nullptr); if (ctx->pctx_ops) { ctx->pctx_ops->free(ctx->pctx); } @@ -61,7 +68,7 @@ int EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx) { } void EVP_MD_CTX_cleanse(EVP_MD_CTX *ctx) { - OPENSSL_cleanse(ctx->md_data, ctx->digest->ctx_size); + OPENSSL_cleanse(ctx->md_data, sizeof(ctx->md_data)); EVP_MD_CTX_cleanup(ctx); } @@ -71,7 +78,7 @@ void EVP_MD_CTX_free(EVP_MD_CTX *ctx) { } EVP_MD_CTX_cleanup(ctx); - OPENSSL_free(ctx); + Delete(ctx); } void EVP_MD_CTX_destroy(EVP_MD_CTX *ctx) { EVP_MD_CTX_free(ctx); } @@ -86,15 +93,19 @@ uint32_t EVP_MD_meth_get_flags(const EVP_MD *md) { return EVP_MD_flags(md); } void EVP_MD_CTX_set_flags(EVP_MD_CTX *ctx, int flags) {} int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in) { - // |in->digest| may be NULL if this is a signing |EVP_MD_CTX| for, e.g., - // Ed25519 which does not hash with |EVP_MD_CTX|. - if (in == NULL || (in->pctx == NULL && in->digest == NULL)) { + // `in->digest` may be NULL if this is a signing `EVP_MD_CTX` for, e.g., + // Ed25519 which does not hash with `EVP_MD_CTX`. + if (in == nullptr || (in->pctx == nullptr && in->digest == nullptr)) { OPENSSL_PUT_ERROR(DIGEST, DIGEST_R_INPUT_NOT_INITIALIZED); return 0; } + if (out == in) { + OPENSSL_PUT_ERROR(DIGEST, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return 0; + } - EVP_PKEY_CTX *pctx = NULL; - assert(in->pctx == NULL || in->pctx_ops != NULL); + EVP_PKEY_CTX *pctx = nullptr; + assert(in->pctx == nullptr || in->pctx_ops != nullptr); if (in->pctx) { pctx = in->pctx_ops->dup(in->pctx); if (!pctx) { @@ -102,46 +113,24 @@ int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in) { } } - uint8_t *tmp_buf = NULL; - if (in->digest != NULL) { - if (out->digest != in->digest) { - assert(in->digest->ctx_size != 0); - tmp_buf = - reinterpret_cast(OPENSSL_malloc(in->digest->ctx_size)); - if (tmp_buf == NULL) { - if (pctx) { - in->pctx_ops->free(pctx); - } - return 0; - } - } else { - // |md_data| will be the correct size in this case. It's removed from - // |out| so that |EVP_MD_CTX_cleanup| doesn't free it, and then it's - // reused. - tmp_buf = reinterpret_cast(out->md_data); - out->md_data = NULL; - } - } - EVP_MD_CTX_cleanup(out); out->digest = in->digest; - out->md_data = tmp_buf; - if (in->digest != NULL) { + if (in->digest != nullptr) { OPENSSL_memcpy(out->md_data, in->md_data, in->digest->ctx_size); } out->pctx = pctx; out->pctx_ops = in->pctx_ops; - assert(out->pctx == NULL || out->pctx_ops != NULL); + assert(out->pctx == nullptr || out->pctx_ops != nullptr); return 1; } void EVP_MD_CTX_move(EVP_MD_CTX *out, EVP_MD_CTX *in) { EVP_MD_CTX_cleanup(out); - // While not guaranteed, |EVP_MD_CTX| is currently safe to move with |memcpy|. + // While not guaranteed, `EVP_MD_CTX` is currently safe to move with `memcpy`. // bssl-crypto currently relies on this, however, so if we change this, we - // need to box the |HMAC_CTX|. (Relying on this is only fine because we assume + // need to box the `HMAC_CTX`. (Relying on this is only fine because we assume // BoringSSL and bssl-crypto will always be updated atomically. We do not // allow any version skew between the two.) OPENSSL_memcpy(out, in, sizeof(EVP_MD_CTX)); @@ -160,28 +149,19 @@ int EVP_MD_CTX_reset(EVP_MD_CTX *ctx) { } int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *engine) { - if (ctx->digest != type) { - assert(type->ctx_size != 0); - uint8_t *md_data = - reinterpret_cast(OPENSSL_malloc(type->ctx_size)); - if (md_data == NULL) { - return 0; - } - - OPENSSL_free(ctx->md_data); - ctx->md_data = md_data; - ctx->digest = type; - } - - assert(ctx->pctx == NULL || ctx->pctx_ops != NULL); + EVP_MD_CTX_cleanup(ctx); + assert(ctx->pctx == nullptr); + assert(type->ctx_size != 0); + assert(type->ctx_size <= sizeof(ctx->md_data)); + ctx->digest = type; ctx->digest->init(ctx); return 1; } int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type) { EVP_MD_CTX_init(ctx); - return EVP_DigestInit_ex(ctx, type, NULL); + return EVP_DigestInit_ex(ctx, type, nullptr); } int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, size_t len) { @@ -192,7 +172,7 @@ int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, size_t len) { int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, uint8_t *md_out, unsigned int *size) { assert(ctx->digest->md_size <= EVP_MAX_MD_SIZE); ctx->digest->final(ctx, md_out); - if (size != NULL) { + if (size != nullptr) { *size = ctx->digest->md_size; } OPENSSL_cleanse(ctx->md_data, ctx->digest->ctx_size); @@ -207,21 +187,15 @@ int EVP_DigestFinal(EVP_MD_CTX *ctx, uint8_t *md, unsigned int *size) { int EVP_Digest(const void *data, size_t count, uint8_t *out_md, unsigned int *out_size, const EVP_MD *type, ENGINE *impl) { - EVP_MD_CTX ctx; - int ret; - - EVP_MD_CTX_init(&ctx); - ret = EVP_DigestInit_ex(&ctx, type, impl) && - EVP_DigestUpdate(&ctx, data, count) && - EVP_DigestFinal_ex(&ctx, out_md, out_size); - EVP_MD_CTX_cleanup(&ctx); - - return ret; + ScopedEVP_MD_CTX ctx; + return EVP_DigestInit_ex(ctx.get(), type, impl) && + EVP_DigestUpdate(ctx.get(), data, count) && + EVP_DigestFinal_ex(ctx.get(), out_md, out_size); } const EVP_MD *EVP_MD_CTX_get0_md(const EVP_MD_CTX *ctx) { - if (ctx == NULL) { - return NULL; + if (ctx == nullptr) { + return nullptr; } return ctx->digest; } @@ -242,4 +216,6 @@ int EVP_MD_CTX_type(const EVP_MD_CTX *ctx) { return EVP_MD_type(EVP_MD_CTX_get0_md(ctx)); } +EVP_PKEY_CTX *EVP_MD_CTX_pkey_ctx(const EVP_MD_CTX *ctx) { return ctx->pctx; } + int EVP_add_digest(const EVP_MD *digest) { return 1; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/digests.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/digests.cc.inc index ba02cdb7..a7474b5b 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/digests.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/digests.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -19,13 +24,15 @@ #include "../delocate.h" #include "internal.h" + +using namespace bssl; + #if defined(NDEBUG) #define CHECK(x) (void)(x) #else #define CHECK(x) assert(x) #endif - static void sha1_init(EVP_MD_CTX *ctx) { BCM_sha1_init(reinterpret_cast(ctx->md_data)); } @@ -40,7 +47,7 @@ static void sha1_final(EVP_MD_CTX *ctx, uint8_t *md) { DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha1) { out->type = NID_sha1; - out->md_size = BCM_SHA_DIGEST_LENGTH; + out->md_size = SHA_DIGEST_LENGTH; out->flags = 0; out->init = sha1_init; out->update = sha1_update; @@ -49,6 +56,8 @@ DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha1) { out->ctx_size = sizeof(SHA_CTX); } +static_assert(sizeof(SHA_CTX) <= EVP_MAX_MD_DATA_SIZE); + static void sha224_init(EVP_MD_CTX *ctx) { BCM_sha224_init(reinterpret_cast(ctx->md_data)); @@ -64,7 +73,7 @@ static void sha224_final(EVP_MD_CTX *ctx, uint8_t *md) { DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha224) { out->type = NID_sha224; - out->md_size = BCM_SHA224_DIGEST_LENGTH; + out->md_size = SHA224_DIGEST_LENGTH; out->flags = 0; out->init = sha224_init; out->update = sha224_update; @@ -73,6 +82,7 @@ DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha224) { out->ctx_size = sizeof(SHA256_CTX); } +static_assert(sizeof(SHA256_CTX) <= EVP_MAX_MD_DATA_SIZE); static void sha256_init(EVP_MD_CTX *ctx) { BCM_sha256_init(reinterpret_cast(ctx->md_data)); @@ -88,7 +98,7 @@ static void sha256_final(EVP_MD_CTX *ctx, uint8_t *md) { DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha256) { out->type = NID_sha256; - out->md_size = BCM_SHA256_DIGEST_LENGTH; + out->md_size = SHA256_DIGEST_LENGTH; out->flags = 0; out->init = sha256_init; out->update = sha256_update; @@ -112,7 +122,7 @@ static void sha384_final(EVP_MD_CTX *ctx, uint8_t *md) { DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha384) { out->type = NID_sha384; - out->md_size = BCM_SHA384_DIGEST_LENGTH; + out->md_size = SHA384_DIGEST_LENGTH; out->flags = 0; out->init = sha384_init; out->update = sha384_update; @@ -121,6 +131,7 @@ DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha384) { out->ctx_size = sizeof(SHA512_CTX); } +static_assert(sizeof(SHA512_CTX) <= EVP_MAX_MD_DATA_SIZE); static void sha512_init(EVP_MD_CTX *ctx) { BCM_sha512_init(reinterpret_cast(ctx->md_data)); @@ -136,7 +147,7 @@ static void sha512_final(EVP_MD_CTX *ctx, uint8_t *md) { DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha512) { out->type = NID_sha512; - out->md_size = BCM_SHA512_DIGEST_LENGTH; + out->md_size = SHA512_DIGEST_LENGTH; out->flags = 0; out->init = sha512_init; out->update = sha512_update; @@ -161,7 +172,7 @@ static void sha512_256_final(EVP_MD_CTX *ctx, uint8_t *md) { DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha512_256) { out->type = NID_sha512_256; - out->md_size = BCM_SHA512_256_DIGEST_LENGTH; + out->md_size = SHA512_256_DIGEST_LENGTH; out->flags = 0; out->init = sha512_256_init; out->update = sha512_256_update; diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/internal.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/internal.h index 1feb296c..498d527b 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/internal.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/internal.h @@ -1,14 +1,19 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. -#ifndef OPENSSL_HEADER_DIGEST_INTERNAL_H -#define OPENSSL_HEADER_DIGEST_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_DIGEST_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_DIGEST_INTERNAL_H #include @@ -17,24 +22,26 @@ extern "C" { #endif +// env_md_st is typoed ("evp" -> "env"), but the typo comes from OpenSSL and +// some consumers forward-declare these structures so we're leaving it alone. struct env_md_st { - // type contains a NID identifing the digest function. (For example, + // type contains a NID identifying the digest function. (For example, // NID_md5.) int type; // md_size contains the size, in bytes, of the resulting digest. unsigned md_size; - // flags contains the OR of |EVP_MD_FLAG_*| values. + // flags contains the OR of `EVP_MD_FLAG_*` values. uint32_t flags; - // init initialises the state in |ctx->md_data|. + // init initialises the state in `ctx->md_data`. void (*init)(EVP_MD_CTX *ctx); - // update hashes |len| bytes of |data| into the state in |ctx->md_data|. + // update hashes `len` bytes of `data` into the state in `ctx->md_data`. void (*update)(EVP_MD_CTX *ctx, const void *data, size_t count); - // final completes the hash and writes |md_size| bytes of digest to |out|. + // final completes the hash and writes `md_size` bytes of digest to `out`. void (*final)(EVP_MD_CTX *ctx, uint8_t *out); // block_size contains the hash's native block size. @@ -44,17 +51,17 @@ struct env_md_st { unsigned ctx_size; }; -// evp_md_pctx_ops contains function pointers to allow the |pctx| member of -// |EVP_MD_CTX| to be manipulated without breaking layering by calling EVP +// evp_md_pctx_ops contains function pointers to allow the `pctx` member of +// `EVP_MD_CTX` to be manipulated without breaking layering by calling EVP // functions. struct evp_md_pctx_ops { - // free is called when an |EVP_MD_CTX| is being freed and the |pctx| also + // free is called when an `EVP_MD_CTX` is being freed and the `pctx` also // needs to be freed. - void (*free) (EVP_PKEY_CTX *pctx); + void (*free)(EVP_PKEY_CTX *pctx); - // dup is called when an |EVP_MD_CTX| is copied and so the |pctx| also needs + // dup is called when an `EVP_MD_CTX` is copied and so the `pctx` also needs // to be copied. - EVP_PKEY_CTX* (*dup) (EVP_PKEY_CTX *pctx); + EVP_PKEY_CTX *(*dup)(EVP_PKEY_CTX *pctx); }; @@ -62,4 +69,4 @@ struct evp_md_pctx_ops { } // extern C #endif -#endif // OPENSSL_HEADER_DIGEST_INTERNAL +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_DIGEST_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/md32_common.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/md32_common.h index b6a6ef3b..ba8a7f79 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/md32_common.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/digest/md32_common.h @@ -1,24 +1,28 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. -#ifndef OPENSSL_HEADER_DIGEST_MD32_COMMON_H -#define OPENSSL_HEADER_DIGEST_MD32_COMMON_H +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_DIGEST_MD32_COMMON_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_DIGEST_MD32_COMMON_H #include +#include #include #include "../../internal.h" -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN // This is a generic 32-bit "collector" for message digest algorithms. It @@ -40,117 +44,123 @@ extern "C" { // any truncation (e.g. 64 for SHA-224 and SHA-256, 128 for SHA-384 and // SHA-512). // -// |h| is the hash state and is updated by a function of type -// |crypto_md32_block_func|. |data| is the partial unprocessed block and has -// |num| bytes. |Nl| and |Nh| maintain the number of bits processed so far. +// `h` is the hash state and is updated by a function of type +// `crypto_md32_block_func`. `data` is the partial unprocessed block and has +// `num` bytes. `Nl` and `Nh` maintain the number of bits processed so far. +// +// The template parameter is then a traits struct defined as follows: +// +// struct HashTraits { +// // HashContext is the hash type defined above. +// using HashContext = _CTX; +// +// // kBlockSize is the block size of the hash function. +// static constexpr size_t kBlockSize = ; +// +// // kLengthIsBigEndian determines whether the final length is encoded in +// // big or little endian. +// static constexpr bool kLengthIsBigEndian = ...; +// +// // HashBlocks incorporates `num_blocks` blocks of input from `data` +// // into `state`. It is assumed the caller has sized `state` and `data` +// // for the hash function. +// static void HashBlocks(uint32_t *state, const uint8_t *data, +// size_t num_blocks) { +// _block_data_order(state, data, num_blocks); +// } +// }; +// +// The reason for this formulation is to encourage the compiler to specialize +// all the code for the block size and block function. -// A crypto_md32_block_func should incorporate |num_blocks| of input from |data| -// into |state|. It is assumed the caller has sized |state| and |data| for the -// hash function. -typedef void (*crypto_md32_block_func)(uint32_t *state, const uint8_t *data, - size_t num_blocks); - -// crypto_md32_update adds |len| bytes from |in| to the digest. |data| must be a -// buffer of length |block_size| with the first |*num| bytes containing a -// partial block. This function combines the partial block with |in| and -// incorporates any complete blocks into the digest state |h|. It then updates -// |data| and |*num| with the new partial block and updates |*Nh| and |*Nl| with -// the data consumed. -static inline void crypto_md32_update(crypto_md32_block_func block_func, - uint32_t *h, uint8_t *data, - size_t block_size, unsigned *num, - uint32_t *Nh, uint32_t *Nl, - const uint8_t *in, size_t len) { - if (len == 0) { +// crypto_md32_update hashes `in` to `ctx`. +template +inline void crypto_md32_update(typename Traits::HashContext *ctx, + Span in) { + static_assert(Traits::kBlockSize == sizeof(ctx->data), "block size is wrong"); + if (in.empty()) { return; } - uint32_t l = *Nl + (((uint32_t)len) << 3); - if (l < *Nl) { + uint32_t l = ctx->Nl + ((static_cast(in.size())) << 3); + if (l < ctx->Nl) { // Handle carries. - (*Nh)++; + ctx->Nh++; } - *Nh += (uint32_t)(len >> 29); - *Nl = l; + ctx->Nh += static_cast(in.size() >> 29); + ctx->Nl = l; - size_t n = *num; + size_t n = ctx->num; if (n != 0) { - if (len >= block_size || len + n >= block_size) { - OPENSSL_memcpy(data + n, in, block_size - n); - block_func(h, data, 1); - n = block_size - n; - in += n; - len -= n; - *num = 0; - // Keep |data| zeroed when unused. - OPENSSL_memset(data, 0, block_size); + if (in.size() >= Traits::kBlockSize || + in.size() + n >= Traits::kBlockSize) { + OPENSSL_memcpy(ctx->data + n, in.data(), Traits::kBlockSize - n); + Traits::HashBlocks(ctx->h, ctx->data, 1); + in = in.subspan(Traits::kBlockSize - n); + ctx->num = 0; + // Keep `data` zeroed when unused. + OPENSSL_memset(ctx->data, 0, Traits::kBlockSize); } else { - OPENSSL_memcpy(data + n, in, len); - *num += (unsigned)len; + OPENSSL_memcpy(ctx->data + n, in.data(), in.size()); + ctx->num += static_cast(in.size()); return; } } - n = len / block_size; + n = in.size() / Traits::kBlockSize; if (n > 0) { - block_func(h, in, n); - n *= block_size; - in += n; - len -= n; + Traits::HashBlocks(ctx->h, in.data(), n); + in = in.subspan(n * Traits::kBlockSize); } - if (len != 0) { - *num = (unsigned)len; - OPENSSL_memcpy(data, in, len); + if (!in.empty()) { + ctx->num = static_cast(in.size()); + OPENSSL_memcpy(ctx->data, in.data(), in.size()); } } // crypto_md32_final incorporates the partial block and trailing length into the -// digest state |h|. The trailing length is encoded in little-endian if -// |is_big_endian| is zero and big-endian otherwise. |data| must be a buffer of -// length |block_size| with the first |*num| bytes containing a partial block. -// |Nh| and |Nl| contain the total number of bits processed. On return, this -// function clears the partial block in |data| and -// |*num|. +// digest state in `ctx`. The trailing length is encoded in little-endian if +// `is_big_endian` is zero and big-endian otherwise. `data` must be a buffer of +// length `block_size` with the first `*num` bytes containing a partial block. +// `Nh` and `Nl` contain the total number of bits processed. On return, this +// function clears the partial block in `data` and +// `*num`. // -// This function does not serialize |h| into a final digest. This is the +// This function does not serialize `h` into a final digest. This is the // responsibility of the caller. -static inline void crypto_md32_final(crypto_md32_block_func block_func, - uint32_t *h, uint8_t *data, - size_t block_size, unsigned *num, - uint32_t Nh, uint32_t Nl, - int is_big_endian) { - // |data| always has room for at least one byte. A full block would have +template +inline void crypto_md32_final(typename Traits::HashContext *ctx) { + static_assert(Traits::kBlockSize == sizeof(ctx->data), "block size is wrong"); + // `data` always has room for at least one byte. A full block would have // been consumed. - size_t n = *num; - assert(n < block_size); - data[n] = 0x80; + size_t n = ctx->num; + assert(n < Traits::kBlockSize); + ctx->data[n] = 0x80; n++; // Fill the block with zeros if there isn't room for a 64-bit length. - if (n > block_size - 8) { - OPENSSL_memset(data + n, 0, block_size - n); + if (n > Traits::kBlockSize - 8) { + OPENSSL_memset(ctx->data + n, 0, Traits::kBlockSize - n); n = 0; - block_func(h, data, 1); + Traits::HashBlocks(ctx->h, ctx->data, 1); } - OPENSSL_memset(data + n, 0, block_size - 8 - n); + OPENSSL_memset(ctx->data + n, 0, Traits::kBlockSize - 8 - n); // Append a 64-bit length to the block and process it. - if (is_big_endian) { - CRYPTO_store_u32_be(data + block_size - 8, Nh); - CRYPTO_store_u32_be(data + block_size - 4, Nl); + if constexpr (Traits::kLengthIsBigEndian) { + CRYPTO_store_u32_be(ctx->data + Traits::kBlockSize - 8, ctx->Nh); + CRYPTO_store_u32_be(ctx->data + Traits::kBlockSize - 4, ctx->Nl); } else { - CRYPTO_store_u32_le(data + block_size - 8, Nl); - CRYPTO_store_u32_le(data + block_size - 4, Nh); + CRYPTO_store_u32_le(ctx->data + Traits::kBlockSize - 8, ctx->Nl); + CRYPTO_store_u32_le(ctx->data + Traits::kBlockSize - 4, ctx->Nh); } - block_func(h, data, 1); - *num = 0; - OPENSSL_memset(data, 0, block_size); + Traits::HashBlocks(ctx->h, ctx->data, 1); + ctx->num = 0; + OPENSSL_memset(ctx->data, 0, Traits::kBlockSize); } -#if defined(__cplusplus) -} // extern C -#endif +BSSL_NAMESPACE_END -#endif // OPENSSL_HEADER_DIGEST_MD32_COMMON_H +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_DIGEST_MD32_COMMON_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/digestsign/digestsign.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/digestsign/digestsign.cc.inc index 66da910e..72a06d51 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/digestsign/digestsign.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/digestsign/digestsign.cc.inc @@ -1,15 +1,21 @@ -/* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../../evp/internal.h" #include "../delocate.h" @@ -17,6 +23,8 @@ #include "../service_indicator/internal.h" +using namespace bssl; + enum evp_sign_verify_t { evp_sign, evp_verify, @@ -27,49 +35,50 @@ DEFINE_LOCAL_DATA(struct evp_md_pctx_ops, md_pctx_ops) { out->dup = EVP_PKEY_CTX_dup; } -static int uses_prehash(EVP_MD_CTX *ctx, enum evp_sign_verify_t op) { - return (op == evp_sign) ? (ctx->pctx->pmeth->sign != NULL) - : (ctx->pctx->pmeth->verify != NULL); +static int uses_prehash(EVP_PKEY_CTX *pctx, enum evp_sign_verify_t op) { + return (op == evp_sign) ? (FromOpaque(pctx)->pmeth->sign != nullptr) + : (FromOpaque(pctx)->pmeth->verify != nullptr); } -static int do_sigver_init(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, +static int do_sigver_init(EVP_MD_CTX *ctx, EVP_PKEY_CTX **out_pctx, const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey, enum evp_sign_verify_t op) { - if (ctx->pctx == NULL) { - ctx->pctx = EVP_PKEY_CTX_new(pkey, e); - } - if (ctx->pctx == NULL) { + UniquePtr pctx(EVP_PKEY_CTX_new(pkey, e)); + if (pctx == nullptr) { return 0; } - ctx->pctx_ops = md_pctx_ops(); if (op == evp_verify) { - if (!EVP_PKEY_verify_init(ctx->pctx)) { + if (!EVP_PKEY_verify_init(pctx.get())) { return 0; } } else { - if (!EVP_PKEY_sign_init(ctx->pctx)) { + if (!EVP_PKEY_sign_init(pctx.get())) { return 0; } } - if (type != NULL && - !EVP_PKEY_CTX_set_signature_md(ctx->pctx, type)) { + if (type != nullptr && !EVP_PKEY_CTX_set_signature_md(pctx.get(), type)) { return 0; } - if (uses_prehash(ctx, op)) { - if (type == NULL) { + if (uses_prehash(pctx.get(), op)) { + if (type == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_NO_DEFAULT_DIGEST); return 0; } if (!EVP_DigestInit_ex(ctx, type, e)) { return 0; } + } else { + EVP_MD_CTX_reset(ctx); } - if (pctx) { - *pctx = ctx->pctx; + assert(ctx->pctx == nullptr); + ctx->pctx_ops = md_pctx_ops(); + ctx->pctx = pctx.release(); + if (out_pctx) { + *out_pctx = ctx->pctx; } return 1; } @@ -85,7 +94,7 @@ int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, } int EVP_DigestSignUpdate(EVP_MD_CTX *ctx, const void *data, size_t len) { - if (!uses_prehash(ctx, evp_sign)) { + if (!uses_prehash(ctx->pctx, evp_sign)) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } @@ -94,7 +103,7 @@ int EVP_DigestSignUpdate(EVP_MD_CTX *ctx, const void *data, size_t len) { } int EVP_DigestVerifyUpdate(EVP_MD_CTX *ctx, const void *data, size_t len) { - if (!uses_prehash(ctx, evp_verify)) { + if (!uses_prehash(ctx->pctx, evp_verify)) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } @@ -104,7 +113,7 @@ int EVP_DigestVerifyUpdate(EVP_MD_CTX *ctx, const void *data, size_t len) { int EVP_DigestSignFinal(EVP_MD_CTX *ctx, uint8_t *out_sig, size_t *out_sig_len) { - if (!uses_prehash(ctx, evp_sign)) { + if (!uses_prehash(ctx->pctx, evp_sign)) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } @@ -130,13 +139,13 @@ int EVP_DigestSignFinal(EVP_MD_CTX *ctx, uint8_t *out_sig, return ret; } else { size_t s = EVP_MD_size(ctx->digest); - return EVP_PKEY_sign(ctx->pctx, out_sig, out_sig_len, NULL, s); + return EVP_PKEY_sign(ctx->pctx, out_sig, out_sig_len, nullptr, s); } } int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const uint8_t *sig, size_t sig_len) { - if (!uses_prehash(ctx, evp_verify)) { + if (!uses_prehash(ctx->pctx, evp_verify)) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } @@ -166,11 +175,10 @@ int EVP_DigestSign(EVP_MD_CTX *ctx, uint8_t *out_sig, size_t *out_sig_len, FIPS_service_indicator_lock_state(); int ret = 0; - if (uses_prehash(ctx, evp_sign)) { - // If |out_sig| is NULL, the caller is only querying the maximum output - // length. |data| should only be incorporated in the final call. - if (out_sig != NULL && - !EVP_DigestSignUpdate(ctx, data, data_len)) { + if (uses_prehash(ctx->pctx, evp_sign)) { + // If `out_sig` is NULL, the caller is only querying the maximum output + // length. `data` should only be incorporated in the final call. + if (out_sig != nullptr && !EVP_DigestSignUpdate(ctx, data, data_len)) { goto end; } @@ -178,13 +186,13 @@ int EVP_DigestSign(EVP_MD_CTX *ctx, uint8_t *out_sig, size_t *out_sig_len, goto end; } - if (ctx->pctx->pmeth->sign_message == NULL) { + if (FromOpaque(ctx->pctx)->pmeth->sign_message == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); goto end; } - ret = ctx->pctx->pmeth->sign_message(ctx->pctx, out_sig, out_sig_len, data, - data_len); + ret = FromOpaque(ctx->pctx)->pmeth->sign_message( + FromOpaque(ctx->pctx), out_sig, out_sig_len, data, data_len); end: FIPS_service_indicator_unlock_state(); @@ -199,18 +207,19 @@ int EVP_DigestVerify(EVP_MD_CTX *ctx, const uint8_t *sig, size_t sig_len, FIPS_service_indicator_lock_state(); int ret = 0; - if (uses_prehash(ctx, evp_verify)) { + if (uses_prehash(ctx->pctx, evp_verify)) { ret = EVP_DigestVerifyUpdate(ctx, data, len) && EVP_DigestVerifyFinal(ctx, sig, sig_len); goto end; } - if (ctx->pctx->pmeth->verify_message == NULL) { + if (FromOpaque(ctx->pctx)->pmeth->verify_message == nullptr) { OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); goto end; } - ret = ctx->pctx->pmeth->verify_message(ctx->pctx, sig, sig_len, data, len); + ret = FromOpaque(ctx->pctx)->pmeth->verify_message(FromOpaque(ctx->pctx), sig, + sig_len, data, len); end: FIPS_service_indicator_unlock_state(); diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/builtin_curves.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/builtin_curves.h index b5fdabcd..bc5cbb47 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/builtin_curves.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/builtin_curves.h @@ -1,16 +1,16 @@ -/* Copyright 2023 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2023 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. // This file is generated by make_tables.go. diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/ec.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/ec.cc.inc index ce780765..12568f3e 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/ec.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/ec.cc.inc @@ -1,24 +1,32 @@ -/* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. - * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. +// +// 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 "../../internal.h" +#include "../../mem_internal.h" #include "../bn/internal.h" #include "../delocate.h" #include "internal.h" @@ -26,6 +34,8 @@ #include "builtin_curves.h" +using namespace bssl; + static void ec_point_free(EC_POINT *point, int free_group); static void ec_group_init_static_mont(BN_MONT_CTX *mont, size_t num_words, @@ -45,7 +55,7 @@ static void ec_group_init_static_mont(BN_MONT_CTX *mont, size_t num_words, static void ec_group_set_a_minus3(EC_GROUP *group) { const EC_FELEM *one = ec_felem_one(group); - group->a_is_minus3 = 1; + group->a_is_minus3 = true; ec_felem_neg(group, &group->a, one); ec_felem_sub(group, &group->a, &group->a, one); ec_felem_sub(group, &group->a, &group->a, one); @@ -54,49 +64,41 @@ static void ec_group_set_a_minus3(EC_GROUP *group) { DEFINE_METHOD_FUNCTION(EC_GROUP, EC_group_p224) { out->curve_name = NID_secp224r1; out->comment = "NIST P-224"; - // 1.3.132.0.33 - static const uint8_t kOIDP224[] = {0x2b, 0x81, 0x04, 0x00, 0x21}; + static const uint8_t kOIDP224[] = {OBJ_ENC_secp224r1}; + static_assert(sizeof(kOIDP224) <= sizeof(out->oid)); OPENSSL_memcpy(out->oid, kOIDP224, sizeof(kOIDP224)); out->oid_len = sizeof(kOIDP224); - ec_group_init_static_mont(&out->field, OPENSSL_ARRAY_SIZE(kP224Field), - kP224Field, kP224FieldRR, kP224FieldN0); - ec_group_init_static_mont(&out->order, OPENSSL_ARRAY_SIZE(kP224Order), - kP224Order, kP224OrderRR, kP224OrderN0); + ec_group_init_static_mont(&out->field, std::size(kP224Field), kP224Field, + kP224FieldRR, kP224FieldN0); + ec_group_init_static_mont(&out->order, std::size(kP224Order), kP224Order, + kP224OrderRR, kP224OrderN0); -#if defined(BORINGSSL_HAS_UINT128) && !defined(OPENSSL_SMALL) - out->meth = EC_GFp_nistp224_method(); - OPENSSL_memcpy(out->generator.raw.X.words, kP224GX, sizeof(kP224GX)); - OPENSSL_memcpy(out->generator.raw.Y.words, kP224GY, sizeof(kP224GY)); - out->generator.raw.Z.words[0] = 1; - OPENSSL_memcpy(out->b.words, kP224B, sizeof(kP224B)); -#else out->meth = EC_GFp_mont_method(); OPENSSL_memcpy(out->generator.raw.X.words, kP224MontGX, sizeof(kP224MontGX)); OPENSSL_memcpy(out->generator.raw.Y.words, kP224MontGY, sizeof(kP224MontGY)); OPENSSL_memcpy(out->generator.raw.Z.words, kP224FieldR, sizeof(kP224FieldR)); OPENSSL_memcpy(out->b.words, kP224MontB, sizeof(kP224MontB)); -#endif out->generator.group = out; ec_group_set_a_minus3(out); - out->has_order = 1; - out->field_greater_than_order = 1; + out->field_is_3_mod_4 = false; + out->has_order = true; + out->field_greater_than_order = true; } DEFINE_METHOD_FUNCTION(EC_GROUP, EC_group_p256) { out->curve_name = NID_X9_62_prime256v1; out->comment = "NIST P-256"; - // 1.2.840.10045.3.1.7 - static const uint8_t kOIDP256[] = {0x2a, 0x86, 0x48, 0xce, - 0x3d, 0x03, 0x01, 0x07}; + static const uint8_t kOIDP256[] = {OBJ_ENC_X9_62_prime256v1}; + static_assert(sizeof(kOIDP256) <= sizeof(out->oid)); OPENSSL_memcpy(out->oid, kOIDP256, sizeof(kOIDP256)); out->oid_len = sizeof(kOIDP256); - ec_group_init_static_mont(&out->field, OPENSSL_ARRAY_SIZE(kP256Field), - kP256Field, kP256FieldRR, kP256FieldN0); - ec_group_init_static_mont(&out->order, OPENSSL_ARRAY_SIZE(kP256Order), - kP256Order, kP256OrderRR, kP256OrderN0); + ec_group_init_static_mont(&out->field, std::size(kP256Field), kP256Field, + kP256FieldRR, kP256FieldN0); + ec_group_init_static_mont(&out->order, std::size(kP256Order), kP256Order, + kP256OrderRR, kP256OrderN0); #if !defined(OPENSSL_NO_ASM) && \ (defined(OPENSSL_X86_64) || defined(OPENSSL_AARCH64)) && \ @@ -112,22 +114,23 @@ DEFINE_METHOD_FUNCTION(EC_GROUP, EC_group_p256) { OPENSSL_memcpy(out->b.words, kP256MontB, sizeof(kP256MontB)); ec_group_set_a_minus3(out); - out->has_order = 1; - out->field_greater_than_order = 1; + out->field_is_3_mod_4 = true; + out->has_order = true; + out->field_greater_than_order = true; } DEFINE_METHOD_FUNCTION(EC_GROUP, EC_group_p384) { out->curve_name = NID_secp384r1; out->comment = "NIST P-384"; - // 1.3.132.0.34 - static const uint8_t kOIDP384[] = {0x2b, 0x81, 0x04, 0x00, 0x22}; + static const uint8_t kOIDP384[] = {OBJ_ENC_secp384r1}; + static_assert(sizeof(kOIDP384) <= sizeof(out->oid)); OPENSSL_memcpy(out->oid, kOIDP384, sizeof(kOIDP384)); out->oid_len = sizeof(kOIDP384); - ec_group_init_static_mont(&out->field, OPENSSL_ARRAY_SIZE(kP384Field), - kP384Field, kP384FieldRR, kP384FieldN0); - ec_group_init_static_mont(&out->order, OPENSSL_ARRAY_SIZE(kP384Order), - kP384Order, kP384OrderRR, kP384OrderN0); + ec_group_init_static_mont(&out->field, std::size(kP384Field), kP384Field, + kP384FieldRR, kP384FieldN0); + ec_group_init_static_mont(&out->order, std::size(kP384Order), kP384Order, + kP384OrderRR, kP384OrderN0); out->meth = EC_GFp_mont_method(); out->generator.group = out; @@ -137,22 +140,23 @@ DEFINE_METHOD_FUNCTION(EC_GROUP, EC_group_p384) { OPENSSL_memcpy(out->b.words, kP384MontB, sizeof(kP384MontB)); ec_group_set_a_minus3(out); - out->has_order = 1; - out->field_greater_than_order = 1; + out->field_is_3_mod_4 = true; + out->has_order = true; + out->field_greater_than_order = true; } DEFINE_METHOD_FUNCTION(EC_GROUP, EC_group_p521) { out->curve_name = NID_secp521r1; out->comment = "NIST P-521"; - // 1.3.132.0.35 - static const uint8_t kOIDP521[] = {0x2b, 0x81, 0x04, 0x00, 0x23}; + static const uint8_t kOIDP521[] = {OBJ_ENC_secp521r1}; + static_assert(sizeof(kOIDP521) <= sizeof(out->oid)); OPENSSL_memcpy(out->oid, kOIDP521, sizeof(kOIDP521)); out->oid_len = sizeof(kOIDP521); - ec_group_init_static_mont(&out->field, OPENSSL_ARRAY_SIZE(kP521Field), - kP521Field, kP521FieldRR, kP521FieldN0); - ec_group_init_static_mont(&out->order, OPENSSL_ARRAY_SIZE(kP521Order), - kP521Order, kP521OrderRR, kP521OrderN0); + ec_group_init_static_mont(&out->field, std::size(kP521Field), kP521Field, + kP521FieldRR, kP521FieldN0); + ec_group_init_static_mont(&out->order, std::size(kP521Order), kP521Order, + kP521OrderRR, kP521OrderN0); out->meth = EC_GFp_mont_method(); out->generator.group = out; @@ -162,65 +166,57 @@ DEFINE_METHOD_FUNCTION(EC_GROUP, EC_group_p521) { OPENSSL_memcpy(out->b.words, kP521MontB, sizeof(kP521MontB)); ec_group_set_a_minus3(out); - out->has_order = 1; - out->field_greater_than_order = 1; + out->field_is_3_mod_4 = true; + out->has_order = true; + out->field_greater_than_order = true; } EC_GROUP *EC_GROUP_new_curve_GFp(const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { if (BN_num_bytes(p) > EC_MAX_BYTES) { OPENSSL_PUT_ERROR(EC, EC_R_INVALID_FIELD); - return NULL; + return nullptr; } - BN_CTX *new_ctx = NULL; - if (ctx == NULL) { - ctx = new_ctx = BN_CTX_new(); - if (ctx == NULL) { - return NULL; + UniquePtr new_ctx; + if (ctx == nullptr) { + new_ctx.reset(BN_CTX_new()); + if (new_ctx == nullptr) { + return nullptr; } + ctx = new_ctx.get(); } - // Historically, |a| and |b| were not required to be fully reduced. + // Historically, `a` and `b` were not required to be fully reduced. // TODO(davidben): Can this be removed? - EC_GROUP *ret = NULL; - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *a_reduced = BN_CTX_get(ctx); BIGNUM *b_reduced = BN_CTX_get(ctx); - if (a_reduced == NULL || b_reduced == NULL || - !BN_nnmod(a_reduced, a, p, ctx) || !BN_nnmod(b_reduced, b, p, ctx)) { - goto err; + if (a_reduced == nullptr || b_reduced == nullptr || + !BN_nnmod(a_reduced, a, p, ctx) || // + !BN_nnmod(b_reduced, b, p, ctx)) { + return nullptr; } - ret = reinterpret_cast(OPENSSL_zalloc(sizeof(EC_GROUP))); - if (ret == NULL) { - return NULL; + UniquePtr ret(New(EC_GFp_mont_method())); + if (ret == nullptr) { + return nullptr; } - ret->references = 1; - ret->meth = EC_GFp_mont_method(); - bn_mont_ctx_init(&ret->field); - bn_mont_ctx_init(&ret->order); - ret->generator.group = ret; - if (!ec_GFp_simple_group_set_curve(ret, p, a_reduced, b_reduced, ctx)) { - EC_GROUP_free(ret); - ret = NULL; - goto err; + if (!ec_GFp_simple_group_set_curve(ret.get(), p, a_reduced, b_reduced, ctx)) { + return nullptr; } -err: - BN_CTX_end(ctx); - BN_CTX_free(new_ctx); - return ret; + return ret.release(); } int EC_GROUP_set_generator(EC_GROUP *group, const EC_POINT *generator, const BIGNUM *order, const BIGNUM *cofactor) { if (group->curve_name != NID_undef || group->has_order || generator->group != group) { - // |EC_GROUP_set_generator| may only be used with |EC_GROUP|s returned by - // |EC_GROUP_new_curve_GFp| and may only used once on each group. - // |generator| must have been created from |EC_GROUP_new_curve_GFp|, not a - // copy, so that |generator->group->generator| is set correctly. + // `EC_GROUP_set_generator` may only be used with `EC_GROUP`s returned by + // `EC_GROUP_new_curve_GFp` and may only used once on each group. + // `generator` must have been created from `EC_GROUP_new_curve_GFp`, not a + // copy, so that `generator->group->generator` is set correctly. OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } @@ -239,34 +235,29 @@ int EC_GROUP_set_generator(EC_GROUP *group, const EC_POINT *generator, // Require that p < 2×order. This simplifies some ECDSA operations. // // Note any curve which did not satisfy this must have been invalid or use a - // tiny prime (less than 17). See the proof in |field_element_to_scalar| in + // tiny prime (less than 17). See the proof in `field_element_to_scalar` in // the ECDSA implementation. - int ret = 0; - BIGNUM *tmp = BN_new(); - if (tmp == NULL || !BN_lshift1(tmp, order)) { - goto err; + UniquePtr tmp(BN_new()); + if (tmp == nullptr || !BN_lshift1(tmp.get(), order)) { + return 0; } - if (BN_cmp(tmp, &group->field.N) <= 0) { + if (BN_cmp(tmp.get(), &group->field.N) <= 0) { OPENSSL_PUT_ERROR(EC, EC_R_INVALID_GROUP_ORDER); - goto err; + return 0; } EC_AFFINE affine; if (!ec_jacobian_to_affine(group, &affine, &generator->raw) || - !BN_MONT_CTX_set(&group->order, order, NULL)) { - goto err; + !BN_MONT_CTX_set(&group->order, order, nullptr)) { + return 0; } group->field_greater_than_order = BN_cmp(&group->field.N, order) > 0; group->generator.raw.X = affine.X; group->generator.raw.Y = affine.Y; - // |raw.Z| was set to 1 by |EC_GROUP_new_curve_GFp|. - group->has_order = 1; - ret = 1; - -err: - BN_free(tmp); - return ret; + // `raw.Z` was set to 1 by `EC_GROUP_new_curve_GFp`. + group->has_order = true; + return 1; } EC_GROUP *EC_GROUP_new_by_curve_name(int nid) { @@ -281,34 +272,45 @@ EC_GROUP *EC_GROUP_new_by_curve_name(int nid) { return (EC_GROUP *)EC_group_p521(); default: OPENSSL_PUT_ERROR(EC, EC_R_UNKNOWN_GROUP); - return NULL; + return nullptr; } } +ECCustomGroup::ECCustomGroup(const EC_METHOD *m) + : ec_group_st({}), RefCounted(CheckSubClass()) { + meth = m; + bn_mont_ctx_init(&field); + bn_mont_ctx_init(&order); + generator.group = this; +} + +ECCustomGroup::~ECCustomGroup() { + bn_mont_ctx_cleanup(&order); + bn_mont_ctx_cleanup(&field); +} + void EC_GROUP_free(EC_GROUP *group) { - if (group == NULL || + if (group == nullptr || // Built-in curves are static. - group->curve_name != NID_undef || - !CRYPTO_refcount_dec_and_test_zero(&group->references)) { + group->curve_name != NID_undef) { return; } - - bn_mont_ctx_cleanup(&group->order); - bn_mont_ctx_cleanup(&group->field); - OPENSSL_free(group); + auto *custom = static_cast(group); + custom->DecRefInternal(); } EC_GROUP *EC_GROUP_dup(const EC_GROUP *a) { - if (a == NULL || + if (a == nullptr || // Built-in curves are static. a->curve_name != NID_undef) { return (EC_GROUP *)a; } + auto *custom = static_cast(a); - // Groups are logically immutable (but for |EC_GROUP_set_generator| which must + // Groups are logically immutable (but for `EC_GROUP_set_generator` which must // be called early on), so we simply take a reference. - EC_GROUP *group = (EC_GROUP *)a; - CRYPTO_refcount_inc(&group->references); + ECCustomGroup *group = const_cast(custom); + group->UpRefInternal(); return group; } @@ -325,8 +327,8 @@ int EC_GROUP_cmp(const EC_GROUP *a, const EC_GROUP *b, BN_CTX *ignored) { return 0; } - // |a| and |b| are both custom curves. We compare the entire curve - // structure. If |a| or |b| is incomplete (due to legacy OpenSSL mistakes, + // `a` and `b` are both custom curves. We compare the entire curve + // structure. If `a` or `b` is incomplete (due to legacy OpenSSL mistakes, // custom curve construction is sadly done in two parts) but otherwise not the // same object, we consider them always unequal. return a->meth != b->meth || // @@ -339,7 +341,7 @@ int EC_GROUP_cmp(const EC_GROUP *a, const EC_GROUP *b, BN_CTX *ignored) { } const EC_POINT *EC_GROUP_get0_generator(const EC_GROUP *group) { - return group->has_order ? &group->generator : NULL; + return group->has_order ? &group->generator : nullptr; } const BIGNUM *EC_GROUP_get0_order(const EC_GROUP *group) { @@ -348,7 +350,7 @@ const BIGNUM *EC_GROUP_get0_order(const EC_GROUP *group) { } int EC_GROUP_get_order(const EC_GROUP *group, BIGNUM *order, BN_CTX *ctx) { - if (BN_copy(order, EC_GROUP_get0_order(group)) == NULL) { + if (BN_copy(order, EC_GROUP_get0_order(group)) == nullptr) { return 0; } return 1; @@ -360,7 +362,7 @@ int EC_GROUP_order_bits(const EC_GROUP *group) { int EC_GROUP_get_cofactor(const EC_GROUP *group, BIGNUM *cofactor, BN_CTX *ctx) { - // All |EC_GROUP|s have cofactor 1. + // All `EC_GROUP`s have cofactor 1. return BN_set_word(cofactor, 1); } @@ -386,7 +388,7 @@ const char *EC_curve_nid2nist(int nid) { case NID_secp521r1: return "P-521"; } - return NULL; + return nullptr; } int EC_curve_nist2nid(const char *name) { @@ -406,14 +408,14 @@ int EC_curve_nist2nid(const char *name) { } EC_POINT *EC_POINT_new(const EC_GROUP *group) { - if (group == NULL) { + if (group == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); - return NULL; + return nullptr; } - EC_POINT *ret = reinterpret_cast(OPENSSL_malloc(sizeof *ret)); - if (ret == NULL) { - return NULL; + EC_POINT *ret = New(); + if (ret == nullptr) { + return nullptr; } ret->group = EC_GROUP_dup(group); @@ -428,7 +430,7 @@ static void ec_point_free(EC_POINT *point, int free_group) { if (free_group) { EC_GROUP_free(point->group); } - OPENSSL_free(point); + Delete(point); } void EC_POINT_free(EC_POINT *point) { @@ -438,7 +440,7 @@ void EC_POINT_free(EC_POINT *point) { void EC_POINT_clear_free(EC_POINT *point) { EC_POINT_free(point); } int EC_POINT_copy(EC_POINT *dest, const EC_POINT *src) { - if (EC_GROUP_cmp(dest->group, src->group, NULL) != 0) { + if (EC_GROUP_cmp(dest->group, src->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } @@ -450,21 +452,21 @@ int EC_POINT_copy(EC_POINT *dest, const EC_POINT *src) { } EC_POINT *EC_POINT_dup(const EC_POINT *a, const EC_GROUP *group) { - if (a == NULL) { - return NULL; + if (a == nullptr) { + return nullptr; } EC_POINT *ret = EC_POINT_new(group); - if (ret == NULL || !EC_POINT_copy(ret, a)) { + if (ret == nullptr || !EC_POINT_copy(ret, a)) { EC_POINT_free(ret); - return NULL; + return nullptr; } return ret; } int EC_POINT_set_to_infinity(const EC_GROUP *group, EC_POINT *point) { - if (EC_GROUP_cmp(group, point->group, NULL) != 0) { + if (EC_GROUP_cmp(group, point->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } @@ -473,7 +475,7 @@ int EC_POINT_set_to_infinity(const EC_GROUP *group, EC_POINT *point) { } int EC_POINT_is_at_infinity(const EC_GROUP *group, const EC_POINT *point) { - if (EC_GROUP_cmp(group, point->group, NULL) != 0) { + if (EC_GROUP_cmp(group, point->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } @@ -482,7 +484,7 @@ int EC_POINT_is_at_infinity(const EC_GROUP *group, const EC_POINT *point) { int EC_POINT_is_on_curve(const EC_GROUP *group, const EC_POINT *point, BN_CTX *ctx) { - if (EC_GROUP_cmp(group, point->group, NULL) != 0) { + if (EC_GROUP_cmp(group, point->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } @@ -491,33 +493,33 @@ int EC_POINT_is_on_curve(const EC_GROUP *group, const EC_POINT *point, int EC_POINT_cmp(const EC_GROUP *group, const EC_POINT *a, const EC_POINT *b, BN_CTX *ctx) { - if (EC_GROUP_cmp(group, a->group, NULL) != 0 || - EC_GROUP_cmp(group, b->group, NULL) != 0) { + if (EC_GROUP_cmp(group, a->group, nullptr) != 0 || + EC_GROUP_cmp(group, b->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return -1; } - // Note |EC_POINT_cmp| returns zero for equality and non-zero for inequality. + // Note `EC_POINT_cmp` returns zero for equality and non-zero for inequality. return ec_GFp_simple_points_equal(group, &a->raw, &b->raw) ? 0 : 1; } int EC_POINT_get_affine_coordinates_GFp(const EC_GROUP *group, const EC_POINT *point, BIGNUM *x, BIGNUM *y, BN_CTX *ctx) { - if (group->meth->point_get_affine_coordinates == 0) { + if (group->meth->point_get_affine_coordinates == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } - if (EC_GROUP_cmp(group, point->group, NULL) != 0) { + if (EC_GROUP_cmp(group, point->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } EC_FELEM x_felem, y_felem; - if (!group->meth->point_get_affine_coordinates(group, &point->raw, - x == NULL ? NULL : &x_felem, - y == NULL ? NULL : &y_felem) || - (x != NULL && !ec_felem_to_bignum(group, x, &x_felem)) || - (y != NULL && !ec_felem_to_bignum(group, y, &y_felem))) { + if (!group->meth->point_get_affine_coordinates( + group, &point->raw, x == nullptr ? nullptr : &x_felem, + y == nullptr ? nullptr : &y_felem) || + (x != nullptr && !ec_felem_to_bignum(group, x, &x_felem)) || + (y != nullptr && !ec_felem_to_bignum(group, y, &y_felem))) { return 0; } return 1; @@ -529,41 +531,42 @@ int EC_POINT_get_affine_coordinates(const EC_GROUP *group, return EC_POINT_get_affine_coordinates_GFp(group, point, x, y, ctx); } -void ec_affine_to_jacobian(const EC_GROUP *group, EC_JACOBIAN *out, - const EC_AFFINE *p) { +void bssl::ec_affine_to_jacobian(const EC_GROUP *group, EC_JACOBIAN *out, + const EC_AFFINE *p) { out->X = p->X; out->Y = p->Y; out->Z = *ec_felem_one(group); } -int ec_jacobian_to_affine(const EC_GROUP *group, EC_AFFINE *out, - const EC_JACOBIAN *p) { +int bssl::ec_jacobian_to_affine(const EC_GROUP *group, EC_AFFINE *out, + const EC_JACOBIAN *p) { return group->meth->point_get_affine_coordinates(group, p, &out->X, &out->Y); } -int ec_jacobian_to_affine_batch(const EC_GROUP *group, EC_AFFINE *out, - const EC_JACOBIAN *in, size_t num) { - if (group->meth->jacobian_to_affine_batch == NULL) { +int bssl::ec_jacobian_to_affine_batch(const EC_GROUP *group, EC_AFFINE *out, + const EC_JACOBIAN *in, size_t num) { + if (group->meth->jacobian_to_affine_batch == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } return group->meth->jacobian_to_affine_batch(group, out, in, num); } -int ec_point_set_affine_coordinates(const EC_GROUP *group, EC_AFFINE *out, - const EC_FELEM *x, const EC_FELEM *y) { - void (*const felem_mul)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a, - const EC_FELEM *b) = group->meth->felem_mul; - void (*const felem_sqr)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a) = - group->meth->felem_sqr; +void bssl::ec_y_sqr_from_x(const EC_GROUP *group, EC_FELEM *out, + const EC_FELEM *x) { + ec_felem_sqr(group, out, x); // out = x² + ec_felem_add(group, out, out, &group->a); // out = x² + a + ec_felem_mul(group, out, out, x); // out = x³ + ax + ec_felem_add(group, out, out, &group->b); // out = x³ + ax + b +} +int bssl::ec_point_set_affine_coordinates(const EC_GROUP *group, EC_AFFINE *out, + const EC_FELEM *x, + const EC_FELEM *y) { // Check if the point is on the curve. EC_FELEM lhs, rhs; - felem_sqr(group, &lhs, y); // lhs = y^2 - felem_sqr(group, &rhs, x); // rhs = x^2 - ec_felem_add(group, &rhs, &rhs, &group->a); // rhs = x^2 + a - felem_mul(group, &rhs, &rhs, x); // rhs = x^3 + ax - ec_felem_add(group, &rhs, &rhs, &group->b); // rhs = x^3 + ax + b + ec_felem_sqr(group, &lhs, y); // lhs = y² + ec_y_sqr_from_x(group, &rhs, x); // rhs = x³ + ax + b if (!ec_felem_equal(group, &lhs, &rhs)) { OPENSSL_PUT_ERROR(EC, EC_R_POINT_IS_NOT_ON_CURVE); // In the event of an error, defend against the caller not checking the @@ -582,15 +585,38 @@ int ec_point_set_affine_coordinates(const EC_GROUP *group, EC_AFFINE *out, return 1; } +int bssl::ec_point_set_compressed_coordinates(const EC_GROUP *group, + EC_AFFINE *out, const EC_FELEM *x, + crypto_word_t y_bit) { + EC_FELEM y2, y; + ec_y_sqr_from_x(group, &y2, x); + if (!ec_felem_sqrt(group, &y, &y2, y_bit)) { + OPENSSL_PUT_ERROR(EC, EC_R_POINT_IS_NOT_ON_CURVE); + // In the event of an error, defend against the caller not checking the + // return value by setting a known safe value. Note this may not be possible + // if the caller is in the process of constructing an arbitrary group and + // the generator is missing. + if (group->has_order) { + out->X = group->generator.raw.X; + out->Y = group->generator.raw.Y; + } + return 0; + } + + out->X = *x; + out->Y = y; + return 1; +} + int EC_POINT_set_affine_coordinates_GFp(const EC_GROUP *group, EC_POINT *point, const BIGNUM *x, const BIGNUM *y, BN_CTX *ctx) { - if (EC_GROUP_cmp(group, point->group, NULL) != 0) { + if (EC_GROUP_cmp(group, point->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } - if (x == NULL || y == NULL) { + if (x == nullptr || y == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } @@ -616,11 +642,33 @@ int EC_POINT_set_affine_coordinates(const EC_GROUP *group, EC_POINT *point, return EC_POINT_set_affine_coordinates_GFp(group, point, x, y, ctx); } +int EC_POINT_set_compressed_coordinates_GFp(const EC_GROUP *group, + EC_POINT *point, const BIGNUM *x, + int y_bit, BN_CTX *ctx) { + if (EC_GROUP_cmp(group, point->group, nullptr) != 0) { + OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); + return 0; + } + + EC_FELEM x_felem; + EC_AFFINE affine; + if (!ec_bignum_to_felem(group, &x_felem, x) || + !ec_point_set_compressed_coordinates(group, &affine, &x_felem, y_bit)) { + // In the event of an error, defend against the caller not checking the + // return value by setting a known safe value. + ec_set_to_safe_point(group, &point->raw); + return 0; + } + + ec_affine_to_jacobian(group, &point->raw, &affine); + return 1; +} + int EC_POINT_add(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a, const EC_POINT *b, BN_CTX *ctx) { - if (EC_GROUP_cmp(group, r->group, NULL) != 0 || - EC_GROUP_cmp(group, a->group, NULL) != 0 || - EC_GROUP_cmp(group, b->group, NULL) != 0) { + if (EC_GROUP_cmp(group, r->group, nullptr) != 0 || + EC_GROUP_cmp(group, a->group, nullptr) != 0 || + EC_GROUP_cmp(group, b->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } @@ -630,8 +678,8 @@ int EC_POINT_add(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a, int EC_POINT_dbl(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a, BN_CTX *ctx) { - if (EC_GROUP_cmp(group, r->group, NULL) != 0 || - EC_GROUP_cmp(group, a->group, NULL) != 0) { + if (EC_GROUP_cmp(group, r->group, nullptr) != 0 || + EC_GROUP_cmp(group, a->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } @@ -641,7 +689,7 @@ int EC_POINT_dbl(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a, int EC_POINT_invert(const EC_GROUP *group, EC_POINT *a, BN_CTX *ctx) { - if (EC_GROUP_cmp(group, a->group, NULL) != 0) { + if (EC_GROUP_cmp(group, a->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } @@ -658,44 +706,41 @@ static int arbitrary_bignum_to_scalar(const EC_GROUP *group, EC_SCALAR *out, ERR_clear_error(); // This is an unusual input, so we do not guarantee constant-time processing. - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *tmp = BN_CTX_get(ctx); - int ok = tmp != NULL && BN_nnmod(tmp, in, EC_GROUP_get0_order(group), ctx) && - ec_bignum_to_scalar(group, out, tmp); - BN_CTX_end(ctx); - return ok; + return tmp != nullptr && BN_nnmod(tmp, in, EC_GROUP_get0_order(group), ctx) && + ec_bignum_to_scalar(group, out, tmp); } -int ec_point_mul_no_self_test(const EC_GROUP *group, EC_POINT *r, - const BIGNUM *g_scalar, const EC_POINT *p, - const BIGNUM *p_scalar, BN_CTX *ctx) { - // Previously, this function set |r| to the point at infinity if there was +int bssl::ec_point_mul_no_self_test(const EC_GROUP *group, EC_POINT *r, + const BIGNUM *g_scalar, const EC_POINT *p, + const BIGNUM *p_scalar, BN_CTX *ctx) { + // Previously, this function set `r` to the point at infinity if there was // nothing to multiply. But, nobody should be calling this function with // nothing to multiply in the first place. - if ((g_scalar == NULL && p_scalar == NULL) || - (p == NULL) != (p_scalar == NULL)) { + if ((g_scalar == nullptr && p_scalar == nullptr) || + (p == nullptr) != (p_scalar == nullptr)) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } - if (EC_GROUP_cmp(group, r->group, NULL) != 0 || - (p != NULL && EC_GROUP_cmp(group, p->group, NULL) != 0)) { + if (EC_GROUP_cmp(group, r->group, nullptr) != 0 || + (p != nullptr && EC_GROUP_cmp(group, p->group, nullptr) != 0)) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } - int ret = 0; - BN_CTX *new_ctx = NULL; - if (ctx == NULL) { - new_ctx = BN_CTX_new(); - if (new_ctx == NULL) { - goto err; + UniquePtr new_ctx; + if (ctx == nullptr) { + new_ctx.reset(BN_CTX_new()); + if (new_ctx == nullptr) { + return 0; } - ctx = new_ctx; + ctx = new_ctx.get(); } - // If both |g_scalar| and |p_scalar| are non-NULL, - // |ec_point_mul_scalar_public| would share the doublings between the two + // If both `g_scalar` and `p_scalar` are non-NULL, + // `ec_point_mul_scalar_public` would share the doublings between the two // products, which would be more efficient. However, we conservatively assume // the caller needs a constant-time operation. (ECDSA verification does not // use this function.) @@ -705,33 +750,29 @@ int ec_point_mul_no_self_test(const EC_GROUP *group, EC_POINT *r, // which combined the two multiplications did not avoid the doubling case // in the incomplete addition formula and were not constant-time. - if (g_scalar != NULL) { + if (g_scalar != nullptr) { EC_SCALAR scalar; if (!arbitrary_bignum_to_scalar(group, &scalar, g_scalar, ctx) || !ec_point_mul_scalar_base(group, &r->raw, &scalar)) { - goto err; + return 0; } } - if (p_scalar != NULL) { + if (p_scalar != nullptr) { EC_SCALAR scalar; EC_JACOBIAN tmp; if (!arbitrary_bignum_to_scalar(group, &scalar, p_scalar, ctx) || !ec_point_mul_scalar(group, &tmp, &p->raw, &scalar)) { - goto err; + return 0; } - if (g_scalar == NULL) { + if (g_scalar == nullptr) { OPENSSL_memcpy(&r->raw, &tmp, sizeof(EC_JACOBIAN)); } else { group->meth->add(group, &r->raw, &r->raw, &tmp); } } - ret = 1; - -err: - BN_CTX_free(new_ctx); - return ret; + return 1; } int EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *g_scalar, @@ -741,15 +782,16 @@ int EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *g_scalar, return ec_point_mul_no_self_test(group, r, g_scalar, p, p_scalar, ctx); } -int ec_point_mul_scalar_public(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_SCALAR *g_scalar, const EC_JACOBIAN *p, - const EC_SCALAR *p_scalar) { - if (g_scalar == NULL || p_scalar == NULL || p == NULL) { +int bssl::ec_point_mul_scalar_public(const EC_GROUP *group, EC_JACOBIAN *r, + const EC_SCALAR *g_scalar, + const EC_JACOBIAN *p, + const EC_SCALAR *p_scalar) { + if (g_scalar == nullptr || p_scalar == nullptr || p == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } - if (group->meth->mul_public == NULL) { + if (group->meth->mul_public == nullptr) { return group->meth->mul_public_batch(group, r, g_scalar, p, p_scalar, 1); } @@ -757,11 +799,10 @@ int ec_point_mul_scalar_public(const EC_GROUP *group, EC_JACOBIAN *r, return 1; } -int ec_point_mul_scalar_public_batch(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_SCALAR *g_scalar, - const EC_JACOBIAN *points, - const EC_SCALAR *scalars, size_t num) { - if (group->meth->mul_public_batch == NULL) { +int bssl::ec_point_mul_scalar_public_batch( + const EC_GROUP *group, EC_JACOBIAN *r, const EC_SCALAR *g_scalar, + const EC_JACOBIAN *points, const EC_SCALAR *scalars, size_t num) { + if (group->meth->mul_public_batch == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } @@ -770,9 +811,9 @@ int ec_point_mul_scalar_public_batch(const EC_GROUP *group, EC_JACOBIAN *r, num); } -int ec_point_mul_scalar(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_JACOBIAN *p, const EC_SCALAR *scalar) { - if (p == NULL || scalar == NULL) { +int bssl::ec_point_mul_scalar(const EC_GROUP *group, EC_JACOBIAN *r, + const EC_JACOBIAN *p, const EC_SCALAR *scalar) { + if (p == nullptr || scalar == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } @@ -781,7 +822,7 @@ int ec_point_mul_scalar(const EC_GROUP *group, EC_JACOBIAN *r, // Check the result is on the curve to defend against fault attacks or bugs. // This has negligible cost compared to the multiplication. - if (!ec_GFp_simple_is_on_curve(group, r)) { + if (!constant_time_declassify_int(ec_GFp_simple_is_on_curve(group, r))) { OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR); return 0; } @@ -789,9 +830,9 @@ int ec_point_mul_scalar(const EC_GROUP *group, EC_JACOBIAN *r, return 1; } -int ec_point_mul_scalar_base(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_SCALAR *scalar) { - if (scalar == NULL) { +int bssl::ec_point_mul_scalar_base(const EC_GROUP *group, EC_JACOBIAN *r, + const EC_SCALAR *scalar) { + if (scalar == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } @@ -810,11 +851,11 @@ int ec_point_mul_scalar_base(const EC_GROUP *group, EC_JACOBIAN *r, return 1; } -int ec_point_mul_scalar_batch(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_JACOBIAN *p0, const EC_SCALAR *scalar0, - const EC_JACOBIAN *p1, const EC_SCALAR *scalar1, - const EC_JACOBIAN *p2, const EC_SCALAR *scalar2) { - if (group->meth->mul_batch == NULL) { +int bssl::ec_point_mul_scalar_batch( + const EC_GROUP *group, EC_JACOBIAN *r, const EC_JACOBIAN *p0, + const EC_SCALAR *scalar0, const EC_JACOBIAN *p1, const EC_SCALAR *scalar1, + const EC_JACOBIAN *p2, const EC_SCALAR *scalar2) { + if (group->meth->mul_batch == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } @@ -823,7 +864,7 @@ int ec_point_mul_scalar_batch(const EC_GROUP *group, EC_JACOBIAN *r, // Check the result is on the curve to defend against fault attacks or bugs. // This has negligible cost compared to the multiplication. - if (!ec_GFp_simple_is_on_curve(group, r)) { + if (!constant_time_declassify_int(ec_GFp_simple_is_on_curve(group, r))) { OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR); return 0; } @@ -831,9 +872,9 @@ int ec_point_mul_scalar_batch(const EC_GROUP *group, EC_JACOBIAN *r, return 1; } -int ec_init_precomp(const EC_GROUP *group, EC_PRECOMP *out, - const EC_JACOBIAN *p) { - if (group->meth->init_precomp == NULL) { +int bssl::ec_init_precomp(const EC_GROUP *group, EC_PRECOMP *out, + const EC_JACOBIAN *p) { + if (group->meth->init_precomp == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } @@ -841,12 +882,11 @@ int ec_init_precomp(const EC_GROUP *group, EC_PRECOMP *out, return group->meth->init_precomp(group, out, p); } -int ec_point_mul_scalar_precomp(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_PRECOMP *p0, const EC_SCALAR *scalar0, - const EC_PRECOMP *p1, const EC_SCALAR *scalar1, - const EC_PRECOMP *p2, - const EC_SCALAR *scalar2) { - if (group->meth->mul_precomp == NULL) { +int bssl::ec_point_mul_scalar_precomp( + const EC_GROUP *group, EC_JACOBIAN *r, const EC_PRECOMP *p0, + const EC_SCALAR *scalar0, const EC_PRECOMP *p1, const EC_SCALAR *scalar1, + const EC_PRECOMP *p2, const EC_SCALAR *scalar2) { + if (group->meth->mul_precomp == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } @@ -855,7 +895,7 @@ int ec_point_mul_scalar_precomp(const EC_GROUP *group, EC_JACOBIAN *r, // Check the result is on the curve to defend against fault attacks or bugs. // This has negligible cost compared to the multiplication. - if (!ec_GFp_simple_is_on_curve(group, r)) { + if (!constant_time_declassify_int(ec_GFp_simple_is_on_curve(group, r))) { OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR); return 0; } @@ -863,35 +903,38 @@ int ec_point_mul_scalar_precomp(const EC_GROUP *group, EC_JACOBIAN *r, return 1; } -void ec_point_select(const EC_GROUP *group, EC_JACOBIAN *out, BN_ULONG mask, - const EC_JACOBIAN *a, const EC_JACOBIAN *b) { +void bssl::ec_point_select(const EC_GROUP *group, EC_JACOBIAN *out, + BN_ULONG mask, const EC_JACOBIAN *a, + const EC_JACOBIAN *b) { ec_felem_select(group, &out->X, mask, &a->X, &b->X); ec_felem_select(group, &out->Y, mask, &a->Y, &b->Y); ec_felem_select(group, &out->Z, mask, &a->Z, &b->Z); } -void ec_affine_select(const EC_GROUP *group, EC_AFFINE *out, BN_ULONG mask, - const EC_AFFINE *a, const EC_AFFINE *b) { +void bssl::ec_affine_select(const EC_GROUP *group, EC_AFFINE *out, + BN_ULONG mask, const EC_AFFINE *a, + const EC_AFFINE *b) { ec_felem_select(group, &out->X, mask, &a->X, &b->X); ec_felem_select(group, &out->Y, mask, &a->Y, &b->Y); } -void ec_precomp_select(const EC_GROUP *group, EC_PRECOMP *out, BN_ULONG mask, - const EC_PRECOMP *a, const EC_PRECOMP *b) { +void bssl::ec_precomp_select(const EC_GROUP *group, EC_PRECOMP *out, + BN_ULONG mask, const EC_PRECOMP *a, + const EC_PRECOMP *b) { static_assert(sizeof(out->comb) == sizeof(*out), "out->comb does not span the entire structure"); - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(out->comb); i++) { + for (size_t i = 0; i < std::size(out->comb); i++) { ec_affine_select(group, &out->comb[i], mask, &a->comb[i], &b->comb[i]); } } -int ec_cmp_x_coordinate(const EC_GROUP *group, const EC_JACOBIAN *p, - const EC_SCALAR *r) { +int bssl::ec_cmp_x_coordinate(const EC_GROUP *group, const EC_JACOBIAN *p, + const EC_SCALAR *r) { return group->meth->cmp_x_coordinate(group, p, r); } -int ec_get_x_coordinate_as_scalar(const EC_GROUP *group, EC_SCALAR *out, - const EC_JACOBIAN *p) { +int bssl::ec_get_x_coordinate_as_scalar(const EC_GROUP *group, EC_SCALAR *out, + const EC_JACOBIAN *p) { uint8_t bytes[EC_MAX_BYTES]; size_t len; if (!ec_get_x_coordinate_as_bytes(group, bytes, &len, sizeof(bytes), p)) { @@ -902,7 +945,7 @@ int ec_get_x_coordinate_as_scalar(const EC_GROUP *group, EC_SCALAR *out, // order. These may not have the same size. However, we must have p < 2×order, // assuming p is not tiny (p >= 17). // - // Thus |bytes| will fit in |order.width + 1| words, and we can reduce by + // Thus `bytes` will fit in `order.width + 1` words, and we can reduce by // performing at most one subtraction. // // Proof: We only work with prime order curves, so the number of points on @@ -916,7 +959,7 @@ int ec_get_x_coordinate_as_scalar(const EC_GROUP *group, EC_SCALAR *out, // p < 2×order // // Additionally, one can manually check this property for built-in curves. It - // is enforced for legacy custom curves in |EC_GROUP_set_generator|. + // is enforced for legacy custom curves in `EC_GROUP_set_generator`. const BIGNUM *order = EC_GROUP_get0_order(group); BN_ULONG words[EC_MAX_WORDS + 1] = {0}; bn_big_endian_to_words(words, order->width + 1, bytes, len); @@ -925,9 +968,9 @@ int ec_get_x_coordinate_as_scalar(const EC_GROUP *group, EC_SCALAR *out, return 1; } -int ec_get_x_coordinate_as_bytes(const EC_GROUP *group, uint8_t *out, - size_t *out_len, size_t max_out, - const EC_JACOBIAN *p) { +int bssl::ec_get_x_coordinate_as_bytes(const EC_GROUP *group, uint8_t *out, + size_t *out_len, size_t max_out, + const EC_JACOBIAN *p) { size_t len = BN_num_bytes(&group->field.N); assert(len <= EC_MAX_BYTES); if (max_out < len) { @@ -936,7 +979,7 @@ int ec_get_x_coordinate_as_bytes(const EC_GROUP *group, uint8_t *out, } EC_FELEM x; - if (!group->meth->point_get_affine_coordinates(group, p, &x, NULL)) { + if (!group->meth->point_get_affine_coordinates(group, p, &x, nullptr)) { return 0; } @@ -945,7 +988,7 @@ int ec_get_x_coordinate_as_bytes(const EC_GROUP *group, uint8_t *out, return 1; } -void ec_set_to_safe_point(const EC_GROUP *group, EC_JACOBIAN *out) { +void bssl::ec_set_to_safe_point(const EC_GROUP *group, EC_JACOBIAN *out) { if (group->has_order) { ec_GFp_simple_point_copy(out, &group->generator.raw); } else { @@ -964,7 +1007,7 @@ int EC_GROUP_get_asn1_flag(const EC_GROUP *group) { const EC_METHOD *EC_GROUP_method_of(const EC_GROUP *group) { // This function exists purely to give callers a way to call - // |EC_METHOD_get_field_type|. cryptography.io crashes if |EC_GROUP_method_of| + // `EC_METHOD_get_field_type`. cryptography.io crashes if `EC_GROUP_method_of` // returns NULL, so return some other garbage pointer. return (const EC_METHOD *)0x12340000; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/ec_key.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/ec_key.cc.inc index 3d6a9683..5a4e0d61 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/ec_key.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/ec_key.cc.inc @@ -1,12 +1,17 @@ -/* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. - * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. +// +// 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 @@ -18,9 +23,9 @@ #include #include #include -#include #include "../../internal.h" +#include "../../mem_internal.h" #include "../bcm_interface.h" #include "../delocate.h" #include "../ecdsa/internal.h" @@ -28,13 +33,14 @@ #include "internal.h" +using namespace bssl; + DEFINE_STATIC_EX_DATA_CLASS(g_ec_ex_data_class) -static EC_WRAPPED_SCALAR *ec_wrapped_scalar_new(const EC_GROUP *group) { - EC_WRAPPED_SCALAR *wrapped = reinterpret_cast( - OPENSSL_zalloc(sizeof(EC_WRAPPED_SCALAR))); - if (wrapped == NULL) { - return NULL; +static bssl::EC_WRAPPED_SCALAR *ec_wrapped_scalar_new(const EC_GROUP *group) { + EC_WRAPPED_SCALAR *wrapped = New(); + if (wrapped == nullptr) { + return nullptr; } wrapped->bignum.d = wrapped->scalar.words; @@ -45,207 +51,225 @@ static EC_WRAPPED_SCALAR *ec_wrapped_scalar_new(const EC_GROUP *group) { } static void ec_wrapped_scalar_free(EC_WRAPPED_SCALAR *scalar) { - OPENSSL_free(scalar); + Delete(scalar); } -EC_KEY *EC_KEY_new(void) { return EC_KEY_new_method(NULL); } +ECKey::ECKey(const ENGINE *engine) + : RefCounted(CheckSubClass()), + ecdsa_meth(engine ? ENGINE_get_ECDSA_method(engine) : nullptr) { + if (ecdsa_meth) { + METHOD_ref(ecdsa_meth); + } + CRYPTO_new_ex_data(&ex_data); +} + +EC_KEY *EC_KEY_new() { return EC_KEY_new_method(nullptr); } EC_KEY *EC_KEY_new_method(const ENGINE *engine) { - EC_KEY *ret = reinterpret_cast(OPENSSL_zalloc(sizeof(EC_KEY))); - if (ret == NULL) { - return NULL; + UniquePtr ret(New(engine)); + if (ret == nullptr) { + return nullptr; } - - if (engine) { - ret->ecdsa_meth = ENGINE_get_ECDSA_method(engine); + if (ret->ecdsa_meth && ret->ecdsa_meth->init && + !ret->ecdsa_meth->init(ret.get())) { + METHOD_unref(ret->ecdsa_meth); + ret->ecdsa_meth = nullptr; + return nullptr; } - if (ret->ecdsa_meth) { - METHOD_ref(ret->ecdsa_meth); - } - - ret->conv_form = POINT_CONVERSION_UNCOMPRESSED; - ret->references = 1; - - CRYPTO_new_ex_data(&ret->ex_data); - - if (ret->ecdsa_meth && ret->ecdsa_meth->init && !ret->ecdsa_meth->init(ret)) { - CRYPTO_free_ex_data(g_ec_ex_data_class_bss_get(), ret, &ret->ex_data); - if (ret->ecdsa_meth) { - METHOD_unref(ret->ecdsa_meth); - } - OPENSSL_free(ret); - return NULL; - } - - return ret; + return ret.release(); } EC_KEY *EC_KEY_new_by_curve_name(int nid) { - EC_KEY *ret = EC_KEY_new(); - if (ret == NULL) { - return NULL; + ECKey *ret = FromOpaque(EC_KEY_new()); + if (ret == nullptr) { + return nullptr; } ret->group = EC_GROUP_new_by_curve_name(nid); - if (ret->group == NULL) { + if (ret->group == nullptr) { EC_KEY_free(ret); - return NULL; + return nullptr; } return ret; } +ECKey::~ECKey() { + if (ecdsa_meth) { + if (ecdsa_meth->finish) { + ecdsa_meth->finish(this); + } + METHOD_unref(ecdsa_meth); + } + + CRYPTO_free_ex_data(g_ec_ex_data_class_bss_get(), &ex_data); + + EC_GROUP_free(group); + EC_POINT_free(pub_key); + ec_wrapped_scalar_free(priv_key); +} + void EC_KEY_free(EC_KEY *r) { - if (r == NULL) { + if (r == nullptr) { return; } - if (!CRYPTO_refcount_dec_and_test_zero(&r->references)) { - return; - } - - if (r->ecdsa_meth) { - if (r->ecdsa_meth->finish) { - r->ecdsa_meth->finish(r); - } - METHOD_unref(r->ecdsa_meth); - } - - CRYPTO_free_ex_data(g_ec_ex_data_class_bss_get(), r, &r->ex_data); - - EC_GROUP_free(r->group); - EC_POINT_free(r->pub_key); - ec_wrapped_scalar_free(r->priv_key); - - OPENSSL_free(r); + auto *impl = FromOpaque(r); + impl->DecRefInternal(); } EC_KEY *EC_KEY_dup(const EC_KEY *src) { - if (src == NULL) { + if (src == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); - return NULL; + return nullptr; } - EC_KEY *ret = EC_KEY_new(); - if (ret == NULL) { - return NULL; + UniquePtr ret(FromOpaque(EC_KEY_new())); + if (ret == nullptr) { + return nullptr; } - if ((src->group != NULL && !EC_KEY_set_group(ret, src->group)) || - (src->pub_key != NULL && !EC_KEY_set_public_key(ret, src->pub_key)) || - (src->priv_key != NULL && - !EC_KEY_set_private_key(ret, EC_KEY_get0_private_key(src)))) { - EC_KEY_free(ret); - return NULL; + auto *impl = FromOpaque(src); + if ((impl->group != nullptr && !EC_KEY_set_group(ret.get(), impl->group)) || + (impl->pub_key != nullptr && + !EC_KEY_set_public_key(ret.get(), impl->pub_key)) || + (impl->priv_key != nullptr && + !EC_KEY_set_private_key(ret.get(), EC_KEY_get0_private_key(impl)))) { + return nullptr; } - ret->enc_flag = src->enc_flag; - ret->conv_form = src->conv_form; - return ret; + ret->enc_flag = impl->enc_flag; + ret->conv_form = impl->conv_form; + return ret.release(); } int EC_KEY_up_ref(EC_KEY *r) { - CRYPTO_refcount_inc(&r->references); + auto *impl = FromOpaque(r); + impl->UpRefInternal(); return 1; } int EC_KEY_is_opaque(const EC_KEY *key) { - return key->ecdsa_meth && (key->ecdsa_meth->flags & ECDSA_FLAG_OPAQUE); + auto *impl = FromOpaque(key); + return impl->ecdsa_meth && (impl->ecdsa_meth->flags & ECDSA_FLAG_OPAQUE); } -const EC_GROUP *EC_KEY_get0_group(const EC_KEY *key) { return key->group; } +const EC_GROUP *EC_KEY_get0_group(const EC_KEY *key) { + auto *impl = FromOpaque(key); + return impl->group; +} int EC_KEY_set_group(EC_KEY *key, const EC_GROUP *group) { - // If |key| already has a group, it is an error to switch to another one. - if (key->group != NULL) { - if (EC_GROUP_cmp(key->group, group, NULL) != 0) { + auto *impl = FromOpaque(key); + + // If `impl` already has a group, it is an error to switch to another one. + if (impl->group != nullptr) { + if (EC_GROUP_cmp(impl->group, group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH); return 0; } return 1; } - assert(key->priv_key == NULL); - assert(key->pub_key == NULL); + assert(impl->priv_key == nullptr); + assert(impl->pub_key == nullptr); - EC_GROUP_free(key->group); - key->group = EC_GROUP_dup(group); - return key->group != NULL; + EC_GROUP_free(impl->group); + impl->group = EC_GROUP_dup(group); + return impl->group != nullptr; } const BIGNUM *EC_KEY_get0_private_key(const EC_KEY *key) { - return key->priv_key != NULL ? &key->priv_key->bignum : NULL; + auto *impl = FromOpaque(key); + return impl->priv_key != nullptr ? &impl->priv_key->bignum : nullptr; } int EC_KEY_set_private_key(EC_KEY *key, const BIGNUM *priv_key) { - if (key->group == NULL) { + auto *impl = FromOpaque(key); + if (impl->group == nullptr) { OPENSSL_PUT_ERROR(EC, EC_R_MISSING_PARAMETERS); return 0; } - EC_WRAPPED_SCALAR *scalar = ec_wrapped_scalar_new(key->group); - if (scalar == NULL) { + EC_WRAPPED_SCALAR *scalar = ec_wrapped_scalar_new(impl->group); + if (scalar == nullptr) { return 0; } - if (!ec_bignum_to_scalar(key->group, &scalar->scalar, priv_key) || + if (!ec_bignum_to_scalar(impl->group, &scalar->scalar, priv_key) || // Zero is not a valid private key, so it is safe to leak the result of // this comparison. constant_time_declassify_int( - ec_scalar_is_zero(key->group, &scalar->scalar))) { + ec_scalar_is_zero(impl->group, &scalar->scalar))) { OPENSSL_PUT_ERROR(EC, EC_R_INVALID_PRIVATE_KEY); ec_wrapped_scalar_free(scalar); return 0; } - ec_wrapped_scalar_free(key->priv_key); - key->priv_key = scalar; + ec_wrapped_scalar_free(impl->priv_key); + impl->priv_key = scalar; return 1; } const EC_POINT *EC_KEY_get0_public_key(const EC_KEY *key) { - return key->pub_key; + auto *impl = FromOpaque(key); + return impl->pub_key; } int EC_KEY_set_public_key(EC_KEY *key, const EC_POINT *pub_key) { - if (key->group == NULL) { + auto *impl = FromOpaque(key); + if (impl->group == nullptr) { OPENSSL_PUT_ERROR(EC, EC_R_MISSING_PARAMETERS); return 0; } - if (pub_key != NULL && EC_GROUP_cmp(key->group, pub_key->group, NULL) != 0) { + if (pub_key != nullptr && EC_POINT_is_at_infinity(pub_key->group, pub_key)) { + OPENSSL_PUT_ERROR(EC, EC_R_POINT_AT_INFINITY); + return 0; + } + + if (pub_key != nullptr && + EC_GROUP_cmp(impl->group, pub_key->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH); return 0; } - EC_POINT_free(key->pub_key); - key->pub_key = EC_POINT_dup(pub_key, key->group); - return (key->pub_key == NULL) ? 0 : 1; + EC_POINT_free(impl->pub_key); + impl->pub_key = EC_POINT_dup(pub_key, impl->group); + return (impl->pub_key == nullptr) ? 0 : 1; } -unsigned int EC_KEY_get_enc_flags(const EC_KEY *key) { return key->enc_flag; } +unsigned int EC_KEY_get_enc_flags(const EC_KEY *key) { + auto *impl = FromOpaque(key); + return impl->enc_flag; +} void EC_KEY_set_enc_flags(EC_KEY *key, unsigned int flags) { - key->enc_flag = flags; + auto *impl = FromOpaque(key); + impl->enc_flag = flags; } point_conversion_form_t EC_KEY_get_conv_form(const EC_KEY *key) { - return key->conv_form; + auto *impl = FromOpaque(key); + return impl->conv_form; } void EC_KEY_set_conv_form(EC_KEY *key, point_conversion_form_t cform) { - key->conv_form = cform; + auto *impl = FromOpaque(key); + impl->conv_form = cform; } int EC_KEY_check_key(const EC_KEY *eckey) { - if (!eckey || !eckey->group || !eckey->pub_key) { + auto *impl = FromOpaque(eckey); + + if (!eckey || !impl->group || !impl->pub_key) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } - if (EC_POINT_is_at_infinity(eckey->group, eckey->pub_key)) { + if (EC_POINT_is_at_infinity(impl->group, impl->pub_key)) { OPENSSL_PUT_ERROR(EC, EC_R_POINT_AT_INFINITY); return 0; } // Test whether the public key is on the elliptic curve. - if (!EC_POINT_is_on_curve(eckey->group, eckey->pub_key, NULL)) { + if (!EC_POINT_is_on_curve(impl->group, impl->pub_key, nullptr)) { OPENSSL_PUT_ERROR(EC, EC_R_POINT_IS_NOT_ON_CURVE); return 0; } @@ -254,17 +278,17 @@ int EC_KEY_check_key(const EC_KEY *eckey) { // // NOTE: this is a FIPS pair-wise consistency check for the ECDH case. See SP // 800-56Ar3, page 36. - if (eckey->priv_key != NULL) { + if (impl->priv_key != nullptr) { EC_JACOBIAN point; - if (!ec_point_mul_scalar_base(eckey->group, &point, - &eckey->priv_key->scalar)) { + if (!ec_point_mul_scalar_base(impl->group, &point, + &impl->priv_key->scalar)) { OPENSSL_PUT_ERROR(EC, ERR_R_EC_LIB); return 0; } - // Leaking this comparison only leaks whether |eckey|'s public key was + // Leaking this comparison only leaks whether `eckey`'s public key was // correct. if (!constant_time_declassify_int(ec_GFp_simple_points_equal( - eckey->group, &point, &eckey->pub_key->raw))) { + impl->group, &point, &impl->pub_key->raw))) { OPENSSL_PUT_ERROR(EC, EC_R_INVALID_PRIVATE_KEY); return 0; } @@ -274,25 +298,27 @@ int EC_KEY_check_key(const EC_KEY *eckey) { } int EC_KEY_check_fips(const EC_KEY *key) { + auto *impl = FromOpaque(key); + int ret = 0; FIPS_service_indicator_lock_state(); - if (!EC_KEY_check_key(key)) { + if (!EC_KEY_check_key(impl)) { goto end; } - if (key->priv_key) { - uint8_t digest[BCM_SHA256_DIGEST_LENGTH] = {0}; + if (impl->priv_key) { + uint8_t digest[SHA256_DIGEST_LENGTH] = {0}; uint8_t sig[ECDSA_MAX_FIXED_LEN]; size_t sig_len; if (!ecdsa_sign_fixed(digest, sizeof(digest), sig, &sig_len, sizeof(sig), - key)) { + impl)) { goto end; } if (boringssl_fips_break_test("ECDSA_PWCT")) { digest[0] = ~digest[0]; } - if (!ecdsa_verify_fixed(digest, sizeof(digest), sig, sig_len, key)) { + if (!ecdsa_verify_fixed(digest, sizeof(digest), sig, sig_len, impl)) { OPENSSL_PUT_ERROR(EC, EC_R_PUBLIC_KEY_VALIDATION_FAILED); goto end; } @@ -303,7 +329,7 @@ int EC_KEY_check_fips(const EC_KEY *key) { end: FIPS_service_indicator_unlock_state(); if (ret) { - EC_KEY_keygen_verify_service_indicator(key); + EC_KEY_keygen_verify_service_indicator(impl); } return ret; @@ -311,78 +337,81 @@ end: int EC_KEY_set_public_key_affine_coordinates(EC_KEY *key, const BIGNUM *x, const BIGNUM *y) { - EC_POINT *point = NULL; - int ok = 0; + auto *impl = FromOpaque(key); - if (!key || !key->group || !x || !y) { + if (!key || !impl->group || !x || !y) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } - point = EC_POINT_new(key->group); - if (point == NULL || - !EC_POINT_set_affine_coordinates_GFp(key->group, point, x, y, NULL) || - !EC_KEY_set_public_key(key, point) || !EC_KEY_check_key(key)) { - goto err; + UniquePtr point(EC_POINT_new(impl->group)); + if (point == nullptr || + !EC_POINT_set_affine_coordinates_GFp(impl->group, point.get(), x, y, + nullptr) || + !EC_KEY_set_public_key(key, point.get()) || // + !EC_KEY_check_key(key)) { + return 0; } - ok = 1; - -err: - EC_POINT_free(point); - return ok; + return 1; } int EC_KEY_oct2key(EC_KEY *key, const uint8_t *in, size_t len, BN_CTX *ctx) { - if (key->group == NULL) { + auto *impl = FromOpaque(key); + + if (impl->group == nullptr) { OPENSSL_PUT_ERROR(EC, EC_R_MISSING_PARAMETERS); return 0; } - EC_POINT *point = EC_POINT_new(key->group); - int ok = point != NULL && - EC_POINT_oct2point(key->group, point, in, len, ctx) && - EC_KEY_set_public_key(key, point); - EC_POINT_free(point); - return ok; + UniquePtr point(EC_POINT_new(impl->group)); + return point != nullptr && + EC_POINT_oct2point(impl->group, point.get(), in, len, ctx) && + EC_KEY_set_public_key(key, point.get()); } size_t EC_KEY_key2buf(const EC_KEY *key, point_conversion_form_t form, uint8_t **out_buf, BN_CTX *ctx) { - if (key == NULL || key->pub_key == NULL || key->group == NULL) { + auto *impl = FromOpaque(key); + + if (impl == nullptr || impl->pub_key == nullptr || impl->group == nullptr) { OPENSSL_PUT_ERROR(EC, EC_R_MISSING_PARAMETERS); return 0; } - return EC_POINT_point2buf(key->group, key->pub_key, form, out_buf, ctx); + return EC_POINT_point2buf(impl->group, impl->pub_key, form, out_buf, ctx); } int EC_KEY_oct2priv(EC_KEY *key, const uint8_t *in, size_t len) { - if (key->group == NULL) { + auto *impl = FromOpaque(key); + + if (impl->group == nullptr) { OPENSSL_PUT_ERROR(EC, EC_R_MISSING_PARAMETERS); return 0; } - if (len != BN_num_bytes(EC_GROUP_get0_order(key->group))) { + if (len != BN_num_bytes(EC_GROUP_get0_order(impl->group))) { OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR); return 0; } - BIGNUM *priv_key = BN_bin2bn(in, len, NULL); - int ok = priv_key != NULL && // + BIGNUM *priv_key = BN_bin2bn(in, len, nullptr); + int ok = priv_key != nullptr && // EC_KEY_set_private_key(key, priv_key); BN_free(priv_key); return ok; } size_t EC_KEY_priv2oct(const EC_KEY *key, uint8_t *out, size_t max_out) { - if (key->group == NULL || key->priv_key == NULL) { + auto *impl = FromOpaque(key); + + if (impl->group == nullptr || impl->priv_key == nullptr) { OPENSSL_PUT_ERROR(EC, EC_R_MISSING_PARAMETERS); return 0; } - size_t len = BN_num_bytes(EC_GROUP_get0_order(key->group)); - if (out == NULL) { + size_t len = BN_num_bytes(EC_GROUP_get0_order(impl->group)); + if (out == nullptr) { return len; } @@ -392,20 +421,20 @@ size_t EC_KEY_priv2oct(const EC_KEY *key, uint8_t *out, size_t max_out) { } size_t bytes_written; - ec_scalar_to_bytes(key->group, out, &bytes_written, &key->priv_key->scalar); + ec_scalar_to_bytes(impl->group, out, &bytes_written, &impl->priv_key->scalar); assert(bytes_written == len); return len; } size_t EC_KEY_priv2buf(const EC_KEY *key, uint8_t **out_buf) { - *out_buf = NULL; - size_t len = EC_KEY_priv2oct(key, NULL, 0); + *out_buf = nullptr; + size_t len = EC_KEY_priv2oct(key, nullptr, 0); if (len == 0) { return 0; } uint8_t *buf = reinterpret_cast(OPENSSL_malloc(len)); - if (buf == NULL) { + if (buf == nullptr) { return 0; } @@ -420,25 +449,30 @@ size_t EC_KEY_priv2buf(const EC_KEY *key, uint8_t **out_buf) { } int EC_KEY_generate_key(EC_KEY *key) { - if (key == NULL || key->group == NULL) { + auto *impl = FromOpaque(key); + + if (impl == nullptr || impl->group == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } - // Check that the group order is FIPS compliant (FIPS 186-4 B.4.2). - if (EC_GROUP_order_bits(key->group) < 160) { + // Generate an ECDSA key pair via rejection sampling. This function implements + // FIPS 186-5, A.2.2, repeating the process on failure. + + // Check the group order is large enough. See step 1 of FIPS 186-5, A.2.2. + if (EC_GROUP_order_bits(impl->group) < 224) { OPENSSL_PUT_ERROR(EC, EC_R_INVALID_GROUP_ORDER); return 0; } static const uint8_t kDefaultAdditionalData[32] = {0}; - EC_WRAPPED_SCALAR *priv_key = ec_wrapped_scalar_new(key->group); - EC_POINT *pub_key = EC_POINT_new(key->group); - if (priv_key == NULL || pub_key == NULL || - // Generate the private key by testing candidates (FIPS 186-4 B.4.2). - !ec_random_nonzero_scalar(key->group, &priv_key->scalar, + EC_WRAPPED_SCALAR *priv_key = ec_wrapped_scalar_new(impl->group); + EC_POINT *pub_key = EC_POINT_new(impl->group); + if (priv_key == nullptr || pub_key == nullptr || + !ec_random_nonzero_scalar(impl->group, &priv_key->scalar, kDefaultAdditionalData) || - !ec_point_mul_scalar_base(key->group, &pub_key->raw, &priv_key->scalar)) { + !ec_point_mul_scalar_base(impl->group, &pub_key->raw, + &priv_key->scalar)) { EC_POINT_free(pub_key); ec_wrapped_scalar_free(priv_key); return 0; @@ -446,35 +480,37 @@ int EC_KEY_generate_key(EC_KEY *key) { // The public key is derived from the private key, but it is public. // - // TODO(crbug.com/boringssl/677): This isn't quite right. While |pub_key| + // TODO(crbug.com/boringssl/677): This isn't quite right. While `pub_key` // represents a public point, it is still in Jacobian form and the exact // Jacobian representation is secret. We need to make it affine first. See // discussion in the bug. CONSTTIME_DECLASSIFY(&pub_key->raw, sizeof(pub_key->raw)); - ec_wrapped_scalar_free(key->priv_key); - key->priv_key = priv_key; - EC_POINT_free(key->pub_key); - key->pub_key = pub_key; + ec_wrapped_scalar_free(impl->priv_key); + impl->priv_key = priv_key; + EC_POINT_free(impl->pub_key); + impl->pub_key = pub_key; return 1; } int EC_KEY_generate_key_fips(EC_KEY *eckey) { - if (eckey == NULL || eckey->group == NULL) { + auto *impl = FromOpaque(eckey); + + if (impl == nullptr || impl->group == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } boringssl_ensure_ecc_self_test(); - if (EC_KEY_generate_key(eckey) && EC_KEY_check_fips(eckey)) { + if (EC_KEY_generate_key(impl) && EC_KEY_check_fips(impl)) { return 1; } - EC_POINT_free(eckey->pub_key); - ec_wrapped_scalar_free(eckey->priv_key); - eckey->pub_key = NULL; - eckey->priv_key = NULL; + EC_POINT_free(impl->pub_key); + ec_wrapped_scalar_free(impl->priv_key); + impl->pub_key = nullptr; + impl->priv_key = nullptr; return 0; } @@ -486,11 +522,15 @@ int EC_KEY_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused, } int EC_KEY_set_ex_data(EC_KEY *d, int idx, void *arg) { - return CRYPTO_set_ex_data(&d->ex_data, idx, arg); + auto *impl = FromOpaque(d); + + return CRYPTO_set_ex_data(&impl->ex_data, idx, arg); } void *EC_KEY_get_ex_data(const EC_KEY *d, int idx) { - return CRYPTO_get_ex_data(&d->ex_data, idx); + auto *impl = FromOpaque(d); + + return CRYPTO_get_ex_data(&impl->ex_data, idx); } void EC_KEY_set_asn1_flag(EC_KEY *key, int flag) {} diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/ec_montgomery.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/ec_montgomery.cc.inc index 31bb11ea..807eca32 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/ec_montgomery.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/ec_montgomery.cc.inc @@ -1,12 +1,17 @@ -/* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. - * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. +// +// 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 @@ -19,18 +24,7 @@ #include "internal.h" -static void ec_GFp_mont_felem_to_montgomery(const EC_GROUP *group, - EC_FELEM *out, const EC_FELEM *in) { - bn_to_montgomery_small(out->words, in->words, group->field.N.width, - &group->field); -} - -static void ec_GFp_mont_felem_from_montgomery(const EC_GROUP *group, - EC_FELEM *out, - const EC_FELEM *in) { - bn_from_montgomery_small(out->words, group->field.N.width, in->words, - group->field.N.width, &group->field); -} +using namespace bssl; static void ec_GFp_mont_felem_inv0(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a) { @@ -38,53 +32,6 @@ static void ec_GFp_mont_felem_inv0(const EC_GROUP *group, EC_FELEM *out, &group->field); } -void ec_GFp_mont_felem_mul(const EC_GROUP *group, EC_FELEM *r, - const EC_FELEM *a, const EC_FELEM *b) { - bn_mod_mul_montgomery_small(r->words, a->words, b->words, - group->field.N.width, &group->field); -} - -void ec_GFp_mont_felem_sqr(const EC_GROUP *group, EC_FELEM *r, - const EC_FELEM *a) { - bn_mod_mul_montgomery_small(r->words, a->words, a->words, - group->field.N.width, &group->field); -} - -void ec_GFp_mont_felem_to_bytes(const EC_GROUP *group, uint8_t *out, - size_t *out_len, const EC_FELEM *in) { - EC_FELEM tmp; - ec_GFp_mont_felem_from_montgomery(group, &tmp, in); - ec_GFp_simple_felem_to_bytes(group, out, out_len, &tmp); -} - -int ec_GFp_mont_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out, - const uint8_t *in, size_t len) { - if (!ec_GFp_simple_felem_from_bytes(group, out, in, len)) { - return 0; - } - - ec_GFp_mont_felem_to_montgomery(group, out, out); - return 1; -} - -void ec_GFp_mont_felem_reduce(const EC_GROUP *group, EC_FELEM *out, - const BN_ULONG *words, size_t num) { - // Convert "from" Montgomery form so the value is reduced mod p. - bn_from_montgomery_small(out->words, group->field.N.width, words, num, - &group->field); - // Convert "to" Montgomery form to remove the R^-1 factor added. - ec_GFp_mont_felem_to_montgomery(group, out, out); - // Convert to Montgomery form to match this implementation's representation. - ec_GFp_mont_felem_to_montgomery(group, out, out); -} - -void ec_GFp_mont_felem_exp(const EC_GROUP *group, EC_FELEM *out, - const EC_FELEM *a, const BN_ULONG *exp, - size_t num_exp) { - bn_mod_exp_mont_small(out->words, a->words, group->field.N.width, exp, - num_exp, &group->field); -} - static int ec_GFp_mont_point_get_affine_coordinates(const EC_GROUP *group, const EC_JACOBIAN *point, EC_FELEM *x, EC_FELEM *y) { @@ -94,19 +41,19 @@ static int ec_GFp_mont_point_get_affine_coordinates(const EC_GROUP *group, return 0; } - // Transform (X, Y, Z) into (x, y) := (X/Z^2, Y/Z^3). Note the check above - // ensures |point->Z| is non-zero, so the inverse always exists. + // Transform (X, Y, Z) into (x, y) := (X/Z², Y/Z³). Note the check above + // ensures `point->Z` is non-zero, so the inverse always exists. EC_FELEM z1, z2; ec_GFp_mont_felem_inv0(group, &z2, &point->Z); - ec_GFp_mont_felem_sqr(group, &z1, &z2); + ec_felem_sqr(group, &z1, &z2); - if (x != NULL) { - ec_GFp_mont_felem_mul(group, x, &point->X, &z1); + if (x != nullptr) { + ec_felem_mul(group, x, &point->X, &z1); } - if (y != NULL) { - ec_GFp_mont_felem_mul(group, &z1, &z1, &z2); - ec_GFp_mont_felem_mul(group, y, &point->Y, &z1); + if (y != nullptr) { + ec_felem_mul(group, &z1, &z1, &z2); + ec_felem_mul(group, y, &point->Y, &z1); } return 1; @@ -120,11 +67,11 @@ static int ec_GFp_mont_jacobian_to_affine_batch(const EC_GROUP *group, return 1; } - // Compute prefix products of all Zs. Use |out[i].X| as scratch space + // Compute prefix products of all Zs. Use `out[i].X` as scratch space // to store these values. out[0].X = in[0].Z; for (size_t i = 1; i < num; i++) { - ec_GFp_mont_felem_mul(group, &out[i].X, &out[i - 1].X, &in[i].Z); + ec_felem_mul(group, &out[i].X, &out[i - 1].X, &in[i].Z); } // Some input was infinity iff the product of all Zs is zero. @@ -137,29 +84,29 @@ static int ec_GFp_mont_jacobian_to_affine_batch(const EC_GROUP *group, EC_FELEM zinvprod; ec_GFp_mont_felem_inv0(group, &zinvprod, &out[num - 1].X); for (size_t i = num - 1; i < num; i--) { - // Our loop invariant is that |zinvprod| is Z0^-1 * Z1^-1 * ... * Zi^-1. + // Our loop invariant is that `zinvprod` is Z0^-1 * Z1^-1 * ... * Zi^-1. // Recover Zi^-1 by multiplying by the previous product. EC_FELEM zinv, zinv2; if (i == 0) { zinv = zinvprod; } else { - ec_GFp_mont_felem_mul(group, &zinv, &zinvprod, &out[i - 1].X); + ec_felem_mul(group, &zinv, &zinvprod, &out[i - 1].X); // Maintain the loop invariant for the next iteration. - ec_GFp_mont_felem_mul(group, &zinvprod, &zinvprod, &in[i].Z); + ec_felem_mul(group, &zinvprod, &zinvprod, &in[i].Z); } // Compute affine coordinates: x = X * Z^-2 and y = Y * Z^-3. - ec_GFp_mont_felem_sqr(group, &zinv2, &zinv); - ec_GFp_mont_felem_mul(group, &out[i].X, &in[i].X, &zinv2); - ec_GFp_mont_felem_mul(group, &out[i].Y, &in[i].Y, &zinv2); - ec_GFp_mont_felem_mul(group, &out[i].Y, &out[i].Y, &zinv); + ec_felem_sqr(group, &zinv2, &zinv); + ec_felem_mul(group, &out[i].X, &in[i].X, &zinv2); + ec_felem_mul(group, &out[i].Y, &in[i].Y, &zinv2); + ec_felem_mul(group, &out[i].Y, &out[i].Y, &zinv); } return 1; } -void ec_GFp_mont_add(const EC_GROUP *group, EC_JACOBIAN *out, - const EC_JACOBIAN *a, const EC_JACOBIAN *b) { +void bssl::ec_GFp_mont_add(const EC_GROUP *group, EC_JACOBIAN *out, + const EC_JACOBIAN *a, const EC_JACOBIAN *b) { if (a == b) { ec_GFp_mont_dbl(group, out, a); return; @@ -177,31 +124,31 @@ void ec_GFp_mont_add(const EC_GROUP *group, EC_JACOBIAN *out, // z1z1 = z1z1 = z1**2 EC_FELEM z1z1; - ec_GFp_mont_felem_sqr(group, &z1z1, &a->Z); + ec_felem_sqr(group, &z1z1, &a->Z); // z2z2 = z2**2 EC_FELEM z2z2; - ec_GFp_mont_felem_sqr(group, &z2z2, &b->Z); + ec_felem_sqr(group, &z2z2, &b->Z); // u1 = x1*z2z2 EC_FELEM u1; - ec_GFp_mont_felem_mul(group, &u1, &a->X, &z2z2); + ec_felem_mul(group, &u1, &a->X, &z2z2); // two_z1z2 = (z1 + z2)**2 - (z1z1 + z2z2) = 2z1z2 EC_FELEM two_z1z2; ec_felem_add(group, &two_z1z2, &a->Z, &b->Z); - ec_GFp_mont_felem_sqr(group, &two_z1z2, &two_z1z2); + ec_felem_sqr(group, &two_z1z2, &two_z1z2); ec_felem_sub(group, &two_z1z2, &two_z1z2, &z1z1); ec_felem_sub(group, &two_z1z2, &two_z1z2, &z2z2); // s1 = y1 * z2**3 EC_FELEM s1; - ec_GFp_mont_felem_mul(group, &s1, &b->Z, &z2z2); - ec_GFp_mont_felem_mul(group, &s1, &s1, &a->Y); + ec_felem_mul(group, &s1, &b->Z, &z2z2); + ec_felem_mul(group, &s1, &s1, &a->Y); // u2 = x2*z1z1 EC_FELEM u2; - ec_GFp_mont_felem_mul(group, &u2, &b->X, &z1z1); + ec_felem_mul(group, &u2, &b->X, &z1z1); // h = u2 - u1 EC_FELEM h; @@ -210,15 +157,15 @@ void ec_GFp_mont_add(const EC_GROUP *group, EC_JACOBIAN *out, BN_ULONG xneq = ec_felem_non_zero_mask(group, &h); // z_out = two_z1z2 * h - ec_GFp_mont_felem_mul(group, &z_out, &h, &two_z1z2); + ec_felem_mul(group, &z_out, &h, &two_z1z2); // z1z1z1 = z1 * z1z1 EC_FELEM z1z1z1; - ec_GFp_mont_felem_mul(group, &z1z1z1, &a->Z, &z1z1); + ec_felem_mul(group, &z1z1z1, &a->Z, &z1z1); // s2 = y2 * z1**3 EC_FELEM s2; - ec_GFp_mont_felem_mul(group, &s2, &b->Y, &z1z1z1); + ec_felem_mul(group, &s2, &b->Y, &z1z1z1); // r = (s2 - s1)*2 EC_FELEM r; @@ -227,7 +174,7 @@ void ec_GFp_mont_add(const EC_GROUP *group, EC_JACOBIAN *out, BN_ULONG yneq = ec_felem_non_zero_mask(group, &r); - // This case will never occur in the constant-time |ec_GFp_mont_mul|. + // This case will never occur in the constant-time `ec_GFp_mont_mul`. BN_ULONG is_nontrivial_double = ~xneq & ~yneq & z1nz & z2nz; if (constant_time_declassify_w(is_nontrivial_double)) { ec_GFp_mont_dbl(group, out, a); @@ -237,27 +184,27 @@ void ec_GFp_mont_add(const EC_GROUP *group, EC_JACOBIAN *out, // I = (2h)**2 EC_FELEM i; ec_felem_add(group, &i, &h, &h); - ec_GFp_mont_felem_sqr(group, &i, &i); + ec_felem_sqr(group, &i, &i); // J = h * I EC_FELEM j; - ec_GFp_mont_felem_mul(group, &j, &h, &i); + ec_felem_mul(group, &j, &h, &i); // V = U1 * I EC_FELEM v; - ec_GFp_mont_felem_mul(group, &v, &u1, &i); + ec_felem_mul(group, &v, &u1, &i); // x_out = r**2 - J - 2V - ec_GFp_mont_felem_sqr(group, &x_out, &r); + ec_felem_sqr(group, &x_out, &r); ec_felem_sub(group, &x_out, &x_out, &j); ec_felem_sub(group, &x_out, &x_out, &v); ec_felem_sub(group, &x_out, &x_out, &v); // y_out = r(V-x_out) - 2 * s1 * J ec_felem_sub(group, &y_out, &v, &x_out); - ec_GFp_mont_felem_mul(group, &y_out, &y_out, &r); + ec_felem_mul(group, &y_out, &y_out, &r); EC_FELEM s1j; - ec_GFp_mont_felem_mul(group, &s1j, &s1, &j); + ec_felem_mul(group, &s1j, &s1, &j); ec_felem_sub(group, &y_out, &y_out, &s1j); ec_felem_sub(group, &y_out, &y_out, &s1j); @@ -269,8 +216,8 @@ void ec_GFp_mont_add(const EC_GROUP *group, EC_JACOBIAN *out, ec_felem_select(group, &out->Z, z2nz, &z_out, &a->Z); } -void ec_GFp_mont_dbl(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_JACOBIAN *a) { +void bssl::ec_GFp_mont_dbl(const EC_GROUP *group, EC_JACOBIAN *r, + const EC_JACOBIAN *a) { if (group->a_is_minus3) { // The method is taken from: // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b @@ -279,12 +226,12 @@ void ec_GFp_mont_dbl(const EC_GROUP *group, EC_JACOBIAN *r, // // EC_FELEM delta, gamma, beta, ftmp, ftmp2, tmptmp, alpha, fourbeta; - // delta = z^2 - ec_GFp_mont_felem_sqr(group, &delta, &a->Z); - // gamma = y^2 - ec_GFp_mont_felem_sqr(group, &gamma, &a->Y); + // delta = z² + ec_felem_sqr(group, &delta, &a->Z); + // gamma = y² + ec_felem_sqr(group, &gamma, &a->Y); // beta = x*gamma - ec_GFp_mont_felem_mul(group, &beta, &a->X, &gamma); + ec_felem_mul(group, &beta, &a->X, &gamma); // alpha = 3*(x-delta)*(x+delta) ec_felem_sub(group, &ftmp, &a->X, &delta); @@ -292,26 +239,26 @@ void ec_GFp_mont_dbl(const EC_GROUP *group, EC_JACOBIAN *r, ec_felem_add(group, &tmptmp, &ftmp2, &ftmp2); ec_felem_add(group, &ftmp2, &ftmp2, &tmptmp); - ec_GFp_mont_felem_mul(group, &alpha, &ftmp, &ftmp2); + ec_felem_mul(group, &alpha, &ftmp, &ftmp2); - // x' = alpha^2 - 8*beta - ec_GFp_mont_felem_sqr(group, &r->X, &alpha); + // x' = alpha² - 8*beta + ec_felem_sqr(group, &r->X, &alpha); ec_felem_add(group, &fourbeta, &beta, &beta); ec_felem_add(group, &fourbeta, &fourbeta, &fourbeta); ec_felem_add(group, &tmptmp, &fourbeta, &fourbeta); ec_felem_sub(group, &r->X, &r->X, &tmptmp); - // z' = (y + z)^2 - gamma - delta + // z' = (y + z)² - gamma - delta ec_felem_add(group, &delta, &gamma, &delta); ec_felem_add(group, &ftmp, &a->Y, &a->Z); - ec_GFp_mont_felem_sqr(group, &r->Z, &ftmp); + ec_felem_sqr(group, &r->Z, &ftmp); ec_felem_sub(group, &r->Z, &r->Z, &delta); - // y' = alpha*(4*beta - x') - 8*gamma^2 + // y' = alpha*(4*beta - x') - 8*gamma² ec_felem_sub(group, &r->Y, &fourbeta, &r->X); ec_felem_add(group, &gamma, &gamma, &gamma); - ec_GFp_mont_felem_sqr(group, &gamma, &gamma); - ec_GFp_mont_felem_mul(group, &r->Y, &alpha, &r->Y); + ec_felem_sqr(group, &gamma, &gamma); + ec_felem_mul(group, &r->Y, &alpha, &r->Y); ec_felem_add(group, &gamma, &gamma, &gamma); ec_felem_sub(group, &r->Y, &r->Y, &gamma); } else { @@ -322,35 +269,35 @@ void ec_GFp_mont_dbl(const EC_GROUP *group, EC_JACOBIAN *r, // // EC_FELEM xx, yy, yyyy, zz; - ec_GFp_mont_felem_sqr(group, &xx, &a->X); - ec_GFp_mont_felem_sqr(group, &yy, &a->Y); - ec_GFp_mont_felem_sqr(group, &yyyy, &yy); - ec_GFp_mont_felem_sqr(group, &zz, &a->Z); + ec_felem_sqr(group, &xx, &a->X); + ec_felem_sqr(group, &yy, &a->Y); + ec_felem_sqr(group, &yyyy, &yy); + ec_felem_sqr(group, &zz, &a->Z); - // s = 2*((x_in + yy)^2 - xx - yyyy) + // s = 2*((x_in + yy)² - xx - yyyy) EC_FELEM s; ec_felem_add(group, &s, &a->X, &yy); - ec_GFp_mont_felem_sqr(group, &s, &s); + ec_felem_sqr(group, &s, &s); ec_felem_sub(group, &s, &s, &xx); ec_felem_sub(group, &s, &s, &yyyy); ec_felem_add(group, &s, &s, &s); - // m = 3*xx + a*zz^2 + // m = 3*xx + a*zz² EC_FELEM m; - ec_GFp_mont_felem_sqr(group, &m, &zz); - ec_GFp_mont_felem_mul(group, &m, &group->a, &m); + ec_felem_sqr(group, &m, &zz); + ec_felem_mul(group, &m, &group->a, &m); ec_felem_add(group, &m, &m, &xx); ec_felem_add(group, &m, &m, &xx); ec_felem_add(group, &m, &m, &xx); - // x_out = m^2 - 2*s - ec_GFp_mont_felem_sqr(group, &r->X, &m); + // x_out = m² - 2*s + ec_felem_sqr(group, &r->X, &m); ec_felem_sub(group, &r->X, &r->X, &s); ec_felem_sub(group, &r->X, &r->X, &s); - // z_out = (y_in + z_in)^2 - yy - zz + // z_out = (y_in + z_in)² - yy - zz ec_felem_add(group, &r->Z, &a->Y, &a->Z); - ec_GFp_mont_felem_sqr(group, &r->Z, &r->Z); + ec_felem_sqr(group, &r->Z, &r->Z); ec_felem_sub(group, &r->Z, &r->Z, &yy); ec_felem_sub(group, &r->Z, &r->Z, &zz); @@ -359,7 +306,7 @@ void ec_GFp_mont_dbl(const EC_GROUP *group, EC_JACOBIAN *r, ec_felem_add(group, &yyyy, &yyyy, &yyyy); ec_felem_add(group, &yyyy, &yyyy, &yyyy); ec_felem_sub(group, &r->Y, &s, &r->X); - ec_GFp_mont_felem_mul(group, &r->Y, &r->Y, &m); + ec_felem_mul(group, &r->Y, &r->Y, &m); ec_felem_sub(group, &r->Y, &r->Y, &yyyy); } } @@ -378,15 +325,15 @@ static int ec_GFp_mont_cmp_x_coordinate(const EC_GROUP *group, return 0; } - // We wish to compare X/Z^2 with r. This is equivalent to comparing X with - // r*Z^2. Note that X and Z are represented in Montgomery form, while r is + // We wish to compare X/Z² with r. This is equivalent to comparing X with + // r⋅Z². Note that X and Z are represented in Montgomery form, while r is // not. EC_FELEM r_Z2, Z2_mont, X; - ec_GFp_mont_felem_mul(group, &Z2_mont, &p->Z, &p->Z); + ec_felem_sqr(group, &Z2_mont, &p->Z); // r < order < p, so this is valid. OPENSSL_memcpy(r_Z2.words, r->words, group->field.N.width * sizeof(BN_ULONG)); - ec_GFp_mont_felem_mul(group, &r_Z2, &r_Z2, &Z2_mont); - ec_GFp_mont_felem_from_montgomery(group, &X, &p->X); + ec_felem_mul(group, &r_Z2, &r_Z2, &Z2_mont); + ec_felem_from_montgomery(group, &X, &p->X); if (ec_felem_equal(group, &r_Z2, &X)) { return 1; @@ -394,14 +341,14 @@ static int ec_GFp_mont_cmp_x_coordinate(const EC_GROUP *group, // During signing the x coefficient is reduced modulo the group order. // Therefore there is a small possibility, less than 1/2^128, that group_order - // < p.x < P. in that case we need not only to compare against |r| but also to + // < p.x < P. in that case we need not only to compare against `r` but also to // compare against r+group_order. BN_ULONG carry = bn_add_words(r_Z2.words, r->words, group->order.N.d, group->field.N.width); if (carry == 0 && bn_less_than_words(r_Z2.words, group->field.N.d, group->field.N.width)) { - // r + group_order < p, so compare (r + group_order) * Z^2 against X. - ec_GFp_mont_felem_mul(group, &r_Z2, &r_Z2, &Z2_mont); + // r + group_order < p, so compare (r + group_order) ⋅ Z² against X. + ec_felem_mul(group, &r_Z2, &r_Z2, &Z2_mont); if (ec_felem_equal(group, &r_Z2, &X)) { return 1; } @@ -410,6 +357,8 @@ static int ec_GFp_mont_cmp_x_coordinate(const EC_GROUP *group, return 0; } +BSSL_NAMESPACE_BEGIN + DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_mont_method) { out->point_get_affine_coordinates = ec_GFp_mont_point_get_affine_coordinates; out->jacobian_to_affine_batch = ec_GFp_mont_jacobian_to_affine_batch; @@ -421,14 +370,10 @@ DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_mont_method) { out->mul_public_batch = ec_GFp_mont_mul_public_batch; out->init_precomp = ec_GFp_mont_init_precomp; out->mul_precomp = ec_GFp_mont_mul_precomp; - out->felem_mul = ec_GFp_mont_felem_mul; - out->felem_sqr = ec_GFp_mont_felem_sqr; - out->felem_to_bytes = ec_GFp_mont_felem_to_bytes; - out->felem_from_bytes = ec_GFp_mont_felem_from_bytes; - out->felem_reduce = ec_GFp_mont_felem_reduce; - out->felem_exp = ec_GFp_mont_felem_exp; out->scalar_inv0_montgomery = ec_simple_scalar_inv0_montgomery; out->scalar_to_montgomery_inv_vartime = ec_simple_scalar_to_montgomery_inv_vartime; out->cmp_x_coordinate = ec_GFp_mont_cmp_x_coordinate; } + +BSSL_NAMESPACE_END diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/felem.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/felem.cc.inc index 0fa18b2d..5e0cef7c 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/felem.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/felem.cc.inc @@ -1,28 +1,31 @@ -/* Copyright 2018 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2018 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 "internal.h" -#include "../bn/internal.h" #include "../../internal.h" +#include "../bn/internal.h" +#include "internal.h" +BSSL_NAMESPACE_BEGIN + const EC_FELEM *ec_felem_one(const EC_GROUP *group) { // We reuse generator.Z as a cache for 1 in the field. return &group->generator.raw.Z; @@ -45,17 +48,51 @@ int ec_felem_to_bignum(const EC_GROUP *group, BIGNUM *out, const EC_FELEM *in) { uint8_t bytes[EC_MAX_BYTES]; size_t len; ec_felem_to_bytes(group, bytes, &len, in); - return BN_bin2bn(bytes, len, out) != NULL; + return BN_bin2bn(bytes, len, out) != nullptr; } void ec_felem_to_bytes(const EC_GROUP *group, uint8_t *out, size_t *out_len, const EC_FELEM *in) { - group->meth->felem_to_bytes(group, out, out_len, in); + EC_FELEM tmp; + ec_felem_from_montgomery(group, &tmp, in); + size_t len = BN_num_bytes(&group->field.N); + bn_words_to_big_endian(out, len, tmp.words, group->field.N.width); + *out_len = len; } int ec_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out, const uint8_t *in, size_t len) { - return group->meth->felem_from_bytes(group, out, in, len); + if (len != BN_num_bytes(&group->field.N)) { + OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR); + return 0; + } + + bn_big_endian_to_words(out->words, group->field.N.width, in, len); + if (!bn_less_than_words(out->words, group->field.N.d, group->field.N.width)) { + OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR); + return 0; + } + + ec_felem_to_montgomery(group, out, out); + return 1; +} + +crypto_word_t ec_felem_from_bytes_or_placeholder(const EC_GROUP *group, + EC_FELEM *out, + const uint8_t *in, + size_t len) { + const BIGNUM *field = &group->field.N; + BSSL_CHECK(len == BN_num_bytes(field)); + bn_big_endian_to_words(out->words, field->width, in, len); + BN_ULONG ok = + BN_ULONG{0} - bn_less_than_words(out->words, field->d, field->width); + // Replace `out->words` with an arbitrary valid field element if out of range. + // This avoids breaking preconditions of later operations. + for (int i = 0; i < field->width; i++) { + out->words[i] &= ok; + } + ec_felem_to_montgomery(group, out, out); + return ok; } void ec_felem_neg(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a) { @@ -102,3 +139,112 @@ int ec_felem_equal(const EC_GROUP *group, const EC_FELEM *a, return CRYPTO_memcmp(a->words, b->words, group->field.N.width * sizeof(BN_ULONG)) == 0; } + +void ec_felem_mul(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a, + const EC_FELEM *b) { + bn_mod_mul_montgomery_small(out->words, a->words, b->words, + group->field.N.width, &group->field); +} + +void ec_felem_sqr(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a) { + bn_mod_mul_montgomery_small(out->words, a->words, a->words, + group->field.N.width, &group->field); +} + +void ec_felem_to_montgomery(const EC_GROUP *group, EC_FELEM *out, + const EC_FELEM *a) { + bn_to_montgomery_small(out->words, a->words, group->field.N.width, + &group->field); +} + +void ec_felem_from_montgomery(const EC_GROUP *group, EC_FELEM *out, + const EC_FELEM *a) { + bn_from_montgomery_small(out->words, group->field.N.width, a->words, + group->field.N.width, &group->field); +} + +void ec_felem_reduce(const EC_GROUP *group, EC_FELEM *out, + const BN_ULONG *words, size_t num) { + // Convert "from" Montgomery form so the value is reduced mod p. + bn_from_montgomery_small(out->words, group->field.N.width, words, num, + &group->field); + // Convert "to" Montgomery form to remove the R^-1 factor added. + ec_felem_to_montgomery(group, out, out); + // Convert to Montgomery form to match this implementation's representation. + ec_felem_to_montgomery(group, out, out); +} + +void ec_felem_exp(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a, + const BN_ULONG *exp, size_t num_exp) { + bn_mod_exp_mont_small(out->words, a->words, group->field.N.width, exp, + num_exp, &group->field); +} + +// adjust_y negates `y` if its LSB (when converted out of Montgomery form) was +// not `y_bit`. +static void adjust_y(const EC_GROUP *group, EC_FELEM *y, crypto_word_t y_bit) { + EC_FELEM y_from_mont, neg_y; + // `y` is stored in the Montgomery domain. Convert back out to sample the LSB. + ec_felem_from_montgomery(group, &y_from_mont, y); + BN_ULONG lsb_mismatch = (y_bit ^ y_from_mont.words[0]) & 1; + lsb_mismatch = 0u - lsb_mismatch; // All ones or all zeros. + ec_felem_neg(group, &neg_y, y); + ec_felem_select(group, y, lsb_mismatch, &neg_y, y); +} + +int ec_felem_sqrt(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a, + crypto_word_t y_bit) { + if (group->field_is_3_mod_4) { + if (!ec_felem_sqrt_secret(group, out, a, y_bit)) { + OPENSSL_PUT_ERROR(EC, EC_R_INVALID_COMPRESSED_POINT); + return 0; + } + return 1; + } + + // Curves that are not 3 mod 4 are messy to implement modular square root. For + // now, fall back to BIGNUM. This case comes up for P-224 and custom curves. + // P-224's prime is particularly inconvenient for compressed coordinates. See + // https://cr.yp.to/papers/sqroot.pdf + UniquePtr ctx(BN_CTX_new()); + UniquePtr bn(BN_new()); + if (ctx == nullptr || bn == nullptr || + !ec_felem_to_bignum(group, bn.get(), a)) { + return 0; + } + + UniquePtr sqrt( + BN_mod_sqrt(nullptr, bn.get(), &group->field.N, ctx.get())); + if (sqrt == nullptr || !ec_bignum_to_felem(group, out, sqrt.get())) { + return 0; + } + + adjust_y(group, out, y_bit); + return 1; +} + +crypto_word_t ec_felem_sqrt_secret(const EC_GROUP *group, EC_FELEM *out, + const EC_FELEM *a, crypto_word_t y_bit) { + BSSL_CHECK(group->field_is_3_mod_4); + + // If `a` is a square, then a^(p+1)/4 is a square root. By Euler's criterion, + // a^(p-1)/2 = 1 for squares, so a^(p+1)/2 = a. p is 3 mod 4, so that exponent + // is even, so we can halve it to find a square root. + const size_t num_exp = group->field.N.width; + BN_ULONG exp[EC_MAX_WORDS]; + bn_rshift_words(exp, group->field.N.d, 2, num_exp); // exp = (p-3)/4 + bn_add_carry_words(exp, exp, /*carry=*/1, num_exp); // exp = (p+1)/4 + ec_felem_exp(group, out, a, exp, num_exp); // out = sqrt(a) + + // Pick the correct (possible) square root. + adjust_y(group, out, y_bit); + + // Check `out^2 = a`. If `a` had a square root, `out` must be one and the + // check will pass. If not, the check cannot pass. + EC_FELEM check; + ec_felem_sqr(group, &check, out); // check = out^2 + ec_felem_sub(group, &check, &check, a); // check = out^2 - a + return ~ec_felem_non_zero_mask(group, &check); +} + +BSSL_NAMESPACE_END diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/internal.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/internal.h index 0b452c7d..2ad932a8 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/internal.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/internal.h @@ -1,15 +1,20 @@ -/* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. - * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. +// +// 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. -#ifndef OPENSSL_HEADER_EC_INTERNAL_H -#define OPENSSL_HEADER_EC_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_EC_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_EC_INTERNAL_H #include @@ -19,12 +24,13 @@ #include #include +#include "../../mem_internal.h" #include "../bn/internal.h" -#if defined(__cplusplus) -extern "C" { -#endif +DECLARE_OPAQUE_STRUCT(ec_key_st, ECKey) + +BSSL_NAMESPACE_BEGIN // EC internals. @@ -44,157 +50,217 @@ static_assert(EC_MAX_WORDS <= BN_SMALL_MAX_WORDS, // Scalars. // An EC_SCALAR is an integer fully reduced modulo the order. Only the first -// |order->width| words are used. An |EC_SCALAR| is specific to an |EC_GROUP| +// `order->width` words are used. An `EC_SCALAR` is specific to an `EC_GROUP` // and must not be mixed between groups. typedef struct { BN_ULONG words[EC_MAX_WORDS]; } EC_SCALAR; -// ec_bignum_to_scalar converts |in| to an |EC_SCALAR| and writes it to -// |*out|. It returns one on success and zero if |in| is out of range. -OPENSSL_EXPORT int ec_bignum_to_scalar(const EC_GROUP *group, EC_SCALAR *out, - const BIGNUM *in); +// ec_bignum_to_scalar converts `in` to an `EC_SCALAR` and writes it to +// `*out`. It returns one on success and zero if `in` is out of range. +int ec_bignum_to_scalar(const EC_GROUP *group, EC_SCALAR *out, + const BIGNUM *in); -// ec_scalar_to_bytes serializes |in| as a big-endian bytestring to |out| and -// sets |*out_len| to the number of bytes written. The number of bytes written -// is |BN_num_bytes(&group->order)|, which is at most |EC_MAX_BYTES|. -OPENSSL_EXPORT void ec_scalar_to_bytes(const EC_GROUP *group, uint8_t *out, - size_t *out_len, const EC_SCALAR *in); +// ec_scalar_to_bytes serializes `in` as a big-endian bytestring to `out` and +// sets `*out_len` to the number of bytes written. The number of bytes written +// is `BN_num_bytes(&group->order)`, which is at most `EC_MAX_BYTES`. +void ec_scalar_to_bytes(const EC_GROUP *group, uint8_t *out, size_t *out_len, + const EC_SCALAR *in); -// ec_scalar_from_bytes deserializes |in| and stores the resulting scalar over -// group |group| to |out|. It returns one on success and zero if |in| is +// ec_scalar_from_bytes deserializes `in` and stores the resulting scalar over +// group `group` to `out`. It returns one on success and zero if `in` is // invalid. -OPENSSL_EXPORT int ec_scalar_from_bytes(const EC_GROUP *group, EC_SCALAR *out, - const uint8_t *in, size_t len); +int ec_scalar_from_bytes(const EC_GROUP *group, EC_SCALAR *out, + const uint8_t *in, size_t len); -// ec_scalar_reduce sets |out| to |words|, reduced modulo the group order. -// |words| must be less than order^2. |num| must be at most twice the width of -// group order. This function treats |words| as secret. +// ec_scalar_reduce sets `out` to `words`, reduced modulo the group order. +// `words` must be less than order². `num` must be at most twice the width of +// group order. This function treats `words` as secret. void ec_scalar_reduce(const EC_GROUP *group, EC_SCALAR *out, const BN_ULONG *words, size_t num); -// ec_random_nonzero_scalar sets |out| to a uniformly selected random value from -// zero to |group->order| - 1. It returns one on success and zero on error. +// ec_random_nonzero_scalar sets `out` to a uniformly selected random value from +// zero to `group->order` - 1. It returns one on success and zero on error. int ec_random_scalar(const EC_GROUP *group, EC_SCALAR *out, const uint8_t additional_data[32]); -// ec_random_nonzero_scalar sets |out| to a uniformly selected random value from -// 1 to |group->order| - 1. It returns one on success and zero on error. +// ec_random_nonzero_scalar sets `out` to a uniformly selected random value from +// 1 to `group->order` - 1. It returns one on success and zero on error. int ec_random_nonzero_scalar(const EC_GROUP *group, EC_SCALAR *out, const uint8_t additional_data[32]); -// ec_scalar_equal_vartime returns one if |a| and |b| are equal and zero +// ec_scalar_equal_vartime returns one if `a` and `b` are equal and zero // otherwise. Both values are treated as public. int ec_scalar_equal_vartime(const EC_GROUP *group, const EC_SCALAR *a, const EC_SCALAR *b); -// ec_scalar_is_zero returns one if |a| is zero and zero otherwise. +// ec_scalar_is_zero returns one if `a` is zero and zero otherwise. int ec_scalar_is_zero(const EC_GROUP *group, const EC_SCALAR *a); -// ec_scalar_add sets |r| to |a| + |b|. +// ec_scalar_add sets `r` to `a` + `b`. void ec_scalar_add(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a, const EC_SCALAR *b); -// ec_scalar_sub sets |r| to |a| - |b|. +// ec_scalar_sub sets `r` to `a` - `b`. void ec_scalar_sub(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a, const EC_SCALAR *b); -// ec_scalar_neg sets |r| to -|a|. +// ec_scalar_neg sets `r` to -`a`. void ec_scalar_neg(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a); -// ec_scalar_to_montgomery sets |r| to |a| in Montgomery form. +// ec_scalar_to_montgomery sets `r` to `a` in Montgomery form. void ec_scalar_to_montgomery(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a); -// ec_scalar_to_montgomery sets |r| to |a| converted from Montgomery form. +// ec_scalar_to_montgomery sets `r` to `a` converted from Montgomery form. void ec_scalar_from_montgomery(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a); -// ec_scalar_mul_montgomery sets |r| to |a| * |b| where inputs and outputs are +// ec_scalar_mul_montgomery sets `r` to `a` * `b` where inputs and outputs are // in Montgomery form. void ec_scalar_mul_montgomery(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a, const EC_SCALAR *b); -// ec_scalar_inv0_montgomery sets |r| to |a|^-1 where inputs and outputs are in -// Montgomery form. If |a| is zero, |r| is set to zero. +// ec_scalar_inv0_montgomery sets `r` to `a`^-1 where inputs and outputs are in +// Montgomery form. If `a` is zero, `r` is set to zero. void ec_scalar_inv0_montgomery(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a); -// ec_scalar_to_montgomery_inv_vartime sets |r| to |a|^-1 R. That is, it takes -// in |a| not in Montgomery form and computes the inverse in Montgomery form. It -// returns one on success and zero if |a| has no inverse. This function assumes -// |a| is public and may leak information about it via timing. +// ec_scalar_to_montgomery_inv_vartime sets `r` to `a`^-1 R. That is, it takes +// in `a` not in Montgomery form and computes the inverse in Montgomery form. It +// returns one on success and zero if `a` has no inverse. This function assumes +// `a` is public and may leak information about it via timing. // -// Note this is not the same operation as |ec_scalar_inv0_montgomery|. +// Note this is not the same operation as `ec_scalar_inv0_montgomery`. int ec_scalar_to_montgomery_inv_vartime(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a); -// ec_scalar_select, in constant time, sets |out| to |a| if |mask| is all ones -// and |b| if |mask| is all zeros. +// ec_scalar_select, in constant time, sets `out` to `a` if `mask` is all ones +// and `b` if `mask` is all zeros. void ec_scalar_select(const EC_GROUP *group, EC_SCALAR *out, BN_ULONG mask, const EC_SCALAR *a, const EC_SCALAR *b); // Field elements. -// An EC_FELEM represents a field element. Only the first |field->width| words -// are used. An |EC_FELEM| is specific to an |EC_GROUP| and must not be mixed -// between groups. Additionally, the representation (whether or not elements are -// represented in Montgomery-form) may vary between |EC_METHOD|s. +// An EC_FELEM represents a field element. Only the first `field->width` words +// are used. An `EC_FELEM` is specific to an `EC_GROUP` and must not be mixed +// between groups. Unless otherwise stated, all inputs and outputs are in +// Montgomery form. typedef struct { BN_ULONG words[EC_MAX_WORDS]; } EC_FELEM; -// ec_felem_one returns one in |group|'s field. +// ec_felem_one returns one in `group`'s field. const EC_FELEM *ec_felem_one(const EC_GROUP *group); -// ec_bignum_to_felem converts |in| to an |EC_FELEM|. It returns one on success -// and zero if |in| is out of range. +// ec_bignum_to_felem converts `in` to an `EC_FELEM`. It returns one on success +// and zero if `in` is out of range. int ec_bignum_to_felem(const EC_GROUP *group, EC_FELEM *out, const BIGNUM *in); -// ec_felem_to_bignum converts |in| to a |BIGNUM|. It returns one on success and +// ec_felem_to_bignum converts `in` to a `BIGNUM`. It returns one on success and // zero on allocation failure. int ec_felem_to_bignum(const EC_GROUP *group, BIGNUM *out, const EC_FELEM *in); -// ec_felem_to_bytes serializes |in| as a big-endian bytestring to |out| and -// sets |*out_len| to the number of bytes written. The number of bytes written -// is |BN_num_bytes(&group->order)|, which is at most |EC_MAX_BYTES|. +// ec_felem_to_bytes serializes `in` as a big-endian bytestring to `out` and +// sets `*out_len` to the number of bytes written. The number of bytes written +// is `BN_num_bytes(&group->order)`, which is at most `EC_MAX_BYTES`. void ec_felem_to_bytes(const EC_GROUP *group, uint8_t *out, size_t *out_len, const EC_FELEM *in); -// ec_felem_from_bytes deserializes |in| and stores the resulting field element -// to |out|. It returns one on success and zero if |in| is invalid. +// ec_felem_from_bytes deserializes `in` as a big-endian field element and +// stores the result to `out`. It returns one on success and zero if `in` is +// invalid. int ec_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out, const uint8_t *in, size_t len); -// ec_felem_neg sets |out| to -|a|. +// ec_felem_from_bytes_or_placeholder deserializes `in` as a big-endian field +// element. On success, it stores the resulting field element to `out` and +// returns `CONSTTIME_TRUE_W`. If `in` is out of range, it sets `out` to an +// arbitrary field element and returns `CONSTTIME_FALSE_W`. Both `in`, and +// whether it was in range, are treated as secret. `len` must be equal to +// `BN_num_words(field)` or the function will abort. +crypto_word_t ec_felem_from_bytes_or_placeholder(const EC_GROUP *group, + EC_FELEM *out, + const uint8_t *in, size_t len); + +// ec_felem_neg sets `out` to -`a`. void ec_felem_neg(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a); -// ec_felem_add sets |out| to |a| + |b|. +// ec_felem_add sets `out` to `a` + `b`. void ec_felem_add(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a, const EC_FELEM *b); -// ec_felem_add sets |out| to |a| - |b|. +// ec_felem_add sets `out` to `a` - `b`. void ec_felem_sub(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a, const EC_FELEM *b); -// ec_felem_non_zero_mask returns all ones if |a| is non-zero and all zeros +// ec_felem_non_zero_mask returns all ones if `a` is non-zero and all zeros // otherwise. BN_ULONG ec_felem_non_zero_mask(const EC_GROUP *group, const EC_FELEM *a); -// ec_felem_select, in constant time, sets |out| to |a| if |mask| is all ones -// and |b| if |mask| is all zeros. +// ec_felem_select, in constant time, sets `out` to `a` if `mask` is all ones +// and `b` if `mask` is all zeros. void ec_felem_select(const EC_GROUP *group, EC_FELEM *out, BN_ULONG mask, const EC_FELEM *a, const EC_FELEM *b); -// ec_felem_equal returns one if |a| and |b| are equal and zero otherwise. +// ec_felem_equal returns one if `a` and `b` are equal and zero otherwise. int ec_felem_equal(const EC_GROUP *group, const EC_FELEM *a, const EC_FELEM *b); +// ec_felem_mul sets `out` to `a` * `b`. +void ec_felem_mul(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a, + const EC_FELEM *b); + +// ec_felem_sqr sets `out` to `a`². +void ec_felem_sqr(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a); + +// ec_felem_to_montgomery sets `out` to `a` converted to Montgomery form. +void ec_felem_to_montgomery(const EC_GROUP *group, EC_FELEM *out, + const EC_FELEM *a); + +// ec_felem_from_montgomery sets `out` to `a` converted from Montgomery form. +void ec_felem_from_montgomery(const EC_GROUP *group, EC_FELEM *out, + const EC_FELEM *a); + +// ec_felem_reduce sets `out` to `words`, reduced modulo the field size, p. +// `words` must be less than p². `num` must be at most twice the width of p. +// This function treats `words` as secret. +void ec_felem_reduce(const EC_GROUP *group, EC_FELEM *out, + const BN_ULONG *words, size_t num); + +// ec_felem_exp sets `out` to `a`^`exp`. It treats `a` is secret but `exp` as +// public. +// +// TODO(crbug.com/42290435): hash-to-curve uses this as part of computing a +// square root, which is what compressed coordinates ultimately needs to avoid +// `BIGNUM`. Can we unify this a bit? By generalizing to arbitrary +// exponentiation, we also miss an opportunity to use a specialized addition +// chain. We also miss our specialized field arithmetic for P-256. +void ec_felem_exp(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a, + const BN_ULONG *exp, size_t num_exp); + +// ec_felem_sqrt sets `out` to the square root of `a` whose least significant +// bit is `y_bit`. It returns one on success and zero on error or if `a` is not +// a square. +int ec_felem_sqrt(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a, + crypto_word_t y_bit); + +// ec_felem_sqrt_secret sets `out` to the square root of `a` whose least +// significant bit is `y_bit`. It returns `CONSTTIME_TRUE_W` on success and +// `CONSTTIME_FALSE_W` if `a` is not a square. +// +// This function treats `a`, `y_bit`, and whether `a` is a square, as secret. If +// `a` is not a square, `out` will be set to some arbitrary field element. This +// function is only implemented for curves whose field is 3 mod 4. (In +// particular, it is *not* implemented for P-224.) It aborts on invalid group. +crypto_word_t ec_felem_sqrt_secret(const EC_GROUP *group, EC_FELEM *out, + const EC_FELEM *a, crypto_word_t y_bit); + // Points. // -// Points may represented in affine coordinates as |EC_AFFINE| or Jacobian -// coordinates as |EC_JACOBIAN|. Affine coordinates directly represent a +// Points may represented in affine coordinates as `EC_AFFINE` or Jacobian +// coordinates as `EC_JACOBIAN`. Affine coordinates directly represent a // point on the curve, but point addition over affine coordinates requires // costly field inversions, so arithmetic is done in Jacobian coordinates. // Converting from affine to Jacobian is cheap, while converting from Jacobian @@ -202,8 +268,8 @@ int ec_felem_equal(const EC_GROUP *group, const EC_FELEM *a, const EC_FELEM *b); // inversions needed in a sequence of point operations.) // An EC_JACOBIAN represents an elliptic curve point in Jacobian coordinates. -// Unlike |EC_POINT|, it is a plain struct which can be stack-allocated and -// needs no cleanup. It is specific to an |EC_GROUP| and must not be mixed +// Unlike `EC_POINT`, it is a plain struct which can be stack-allocated and +// needs no cleanup. It is specific to an `EC_GROUP` and must not be mixed // between groups. typedef struct { // X, Y, and Z are Jacobian projective coordinates. They represent @@ -218,23 +284,23 @@ typedef struct { EC_FELEM X, Y; } EC_AFFINE; -// ec_affine_to_jacobian converts |p| to Jacobian form and writes the result to -// |*out|. This operation is very cheap and only costs a few copies. +// ec_affine_to_jacobian converts `p` to Jacobian form and writes the result to +// `*out`. This operation is very cheap and only costs a few copies. void ec_affine_to_jacobian(const EC_GROUP *group, EC_JACOBIAN *out, const EC_AFFINE *p); -// ec_jacobian_to_affine converts |p| to affine form and writes the result to -// |*out|. It returns one on success and zero if |p| was the point at infinity. +// ec_jacobian_to_affine converts `p` to affine form and writes the result to +// `*out`. It returns one on success and zero if `p` was the point at infinity. // This operation performs a field inversion and should only be done once per // point. // -// If only extracting the x-coordinate, use |ec_get_x_coordinate_*| which is +// If only extracting the x-coordinate, use `ec_get_x_coordinate_*` which is // slightly faster. -OPENSSL_EXPORT int ec_jacobian_to_affine(const EC_GROUP *group, EC_AFFINE *out, - const EC_JACOBIAN *p); +int ec_jacobian_to_affine(const EC_GROUP *group, EC_AFFINE *out, + const EC_JACOBIAN *p); -// ec_jacobian_to_affine_batch converts |num| points in |in| from Jacobian -// coordinates to affine coordinates and writes the results to |out|. It returns +// ec_jacobian_to_affine_batch converts `num` points in `in` from Jacobian +// coordinates to affine coordinates and writes the results to `out`. It returns // one on success and zero if any of the input points were infinity. // // This function is not implemented for all curves. Add implementations as @@ -242,36 +308,45 @@ OPENSSL_EXPORT int ec_jacobian_to_affine(const EC_GROUP *group, EC_AFFINE *out, int ec_jacobian_to_affine_batch(const EC_GROUP *group, EC_AFFINE *out, const EC_JACOBIAN *in, size_t num); -// ec_point_set_affine_coordinates sets |out|'s to a point with affine -// coordinates |x| and |y|. It returns one if the point is on the curve and -// zero otherwise. If the point is not on the curve, the value of |out| is -// undefined. +// ec_y_sqr_from_x sets `out` to `x^3 + ax + b`, the expected value of y^2. +void ec_y_sqr_from_x(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *x); + +// ec_point_set_affine_coordinates sets `out` to a point with affine coordinates +// `x` and `y`. It returns one if the point is on the curve and zero otherwise. +// If the point is not on the curve, the value of `out` is undefined. int ec_point_set_affine_coordinates(const EC_GROUP *group, EC_AFFINE *out, const EC_FELEM *x, const EC_FELEM *y); -// ec_point_mul_no_self_test does the same as |EC_POINT_mul|, but doesn't try to +// ec_point_set_compressed_coordinates sets `out` to a point with compressed +// coordinates `x` and `y_bit`. It returns one if the point is on the curve and +// zero otherwise. If the point is not on the curve, the value of `out` is +// undefined. +int ec_point_set_compressed_coordinates(const EC_GROUP *group, EC_AFFINE *out, + const EC_FELEM *x, crypto_word_t y_bit); + +// ec_point_mul_no_self_test does the same as `EC_POINT_mul`, but doesn't try to // run the self-test first. This is for use in the self tests themselves, to // prevent an infinite loop. int ec_point_mul_no_self_test(const EC_GROUP *group, EC_POINT *r, const BIGNUM *g_scalar, const EC_POINT *p, const BIGNUM *p_scalar, BN_CTX *ctx); -// ec_point_mul_scalar sets |r| to |p| * |scalar|. Both inputs are considered +// ec_point_mul_scalar sets `r` to `p` * `scalar`. Both inputs are considered // secret. int ec_point_mul_scalar(const EC_GROUP *group, EC_JACOBIAN *r, const EC_JACOBIAN *p, const EC_SCALAR *scalar); -// ec_point_mul_scalar_base sets |r| to generator * |scalar|. |scalar| is +// ec_point_mul_scalar_base sets `r` to generator * `scalar`. `scalar` is // treated as secret. int ec_point_mul_scalar_base(const EC_GROUP *group, EC_JACOBIAN *r, const EC_SCALAR *scalar); -// ec_point_mul_scalar_batch sets |r| to |p0| * |scalar0| + |p1| * |scalar1| + -// |p2| * |scalar2|. |p2| may be NULL to skip that term. +// ec_point_mul_scalar_batch sets `r` to `p0` * `scalar0` + `p1` * `scalar1` + +// `p2` * `scalar2`. `p2` may be NULL to skip that term. // // The inputs are treated as secret, however, this function leaks information // about whether intermediate computations add a point to itself. Callers must -// ensure that discrete logs between |p0|, |p1|, and |p2| are uniformly +// ensure that discrete logs between `p0`, `p1`, and `p2` are uniformly // distributed and independent of the scalars, which should be uniformly // selected and not under the attackers control. This ensures the doubling case // will occur with negligible probability. @@ -280,7 +355,7 @@ int ec_point_mul_scalar_base(const EC_GROUP *group, EC_JACOBIAN *r, // needed. // // TODO(davidben): This function does not use base point tables. For now, it is -// only used with the generic |EC_GFp_mont_method| implementation which has +// only used with the generic `EC_GFp_mont_method` implementation which has // none. If generalizing to tuned curves, this may be useful. However, we still // must double up to the least efficient input, so precomputed tables can only // save table setup and allow a wider window size. @@ -291,16 +366,16 @@ int ec_point_mul_scalar_batch(const EC_GROUP *group, EC_JACOBIAN *r, #define EC_MONT_PRECOMP_COMB_SIZE 5 -// An |EC_PRECOMP| stores precomputed information about a point, to optimize +// An `EC_PRECOMP` stores precomputed information about a point, to optimize // repeated multiplications involving it. It is a union so different -// |EC_METHOD|s can store different information in it. +// `EC_METHOD`s can store different information in it. typedef union { EC_AFFINE comb[(1 << EC_MONT_PRECOMP_COMB_SIZE) - 1]; } EC_PRECOMP; -// ec_init_precomp precomputes multiples of |p| and writes the result to |out|. +// ec_init_precomp precomputes multiples of `p` and writes the result to `out`. // It returns one on success and zero on error. The resulting table may be used -// with |ec_point_mul_scalar_precomp|. This function will fail if |p| is the +// with `ec_point_mul_scalar_precomp`. This function will fail if `p` is the // point at infinity. // // This function is not implemented for all curves. Add implementations as @@ -308,16 +383,16 @@ typedef union { int ec_init_precomp(const EC_GROUP *group, EC_PRECOMP *out, const EC_JACOBIAN *p); -// ec_point_mul_scalar_precomp sets |r| to |p0| * |scalar0| + |p1| * |scalar1| + -// |p2| * |scalar2|. |p1| or |p2| may be NULL to skip the corresponding term. -// The points are represented as |EC_PRECOMP| and must be initialized with -// |ec_init_precomp|. This function runs faster than |ec_point_mul_scalar_batch| +// ec_point_mul_scalar_precomp sets `r` to `p0` * `scalar0` + `p1` * `scalar1` + +// `p2` * `scalar2`. `p1` or `p2` may be NULL to skip the corresponding term. +// The points are represented as `EC_PRECOMP` and must be initialized with +// `ec_init_precomp`. This function runs faster than `ec_point_mul_scalar_batch` // but requires setup work per input point, so it is only appropriate for points // which are used frequently. // // The inputs are treated as secret, however, this function leaks information // about whether intermediate computations add a point to itself. Callers must -// ensure that discrete logs between |p0|, |p1|, and |p2| are uniformly +// ensure that discrete logs between `p0`, `p1`, and `p2` are uniformly // distributed and independent of the scalars, which should be uniformly // selected and not under the attackers control. This ensures the doubling case // will occur with negligible probability. @@ -326,7 +401,7 @@ int ec_init_precomp(const EC_GROUP *group, EC_PRECOMP *out, // needed. // // TODO(davidben): This function does not use base point tables. For now, it is -// only used with the generic |EC_GFp_mont_method| implementation which has +// only used with the generic `EC_GFp_mont_method` implementation which has // none. If generalizing to tuned curves, we should add a parameter for the base // point and arrange for the generic implementation to have base point tables // available. @@ -335,19 +410,17 @@ int ec_point_mul_scalar_precomp(const EC_GROUP *group, EC_JACOBIAN *r, const EC_PRECOMP *p1, const EC_SCALAR *scalar1, const EC_PRECOMP *p2, const EC_SCALAR *scalar2); -// ec_point_mul_scalar_public sets |r| to -// generator * |g_scalar| + |p| * |p_scalar|. It assumes that the inputs are +// ec_point_mul_scalar_public sets `r` to +// generator * `g_scalar` + `p` * `p_scalar`. It assumes that the inputs are // public so there is no concern about leaking their values through timing. -OPENSSL_EXPORT int ec_point_mul_scalar_public(const EC_GROUP *group, - EC_JACOBIAN *r, - const EC_SCALAR *g_scalar, - const EC_JACOBIAN *p, - const EC_SCALAR *p_scalar); +int ec_point_mul_scalar_public(const EC_GROUP *group, EC_JACOBIAN *r, + const EC_SCALAR *g_scalar, const EC_JACOBIAN *p, + const EC_SCALAR *p_scalar); -// ec_point_mul_scalar_public_batch sets |r| to the sum of generator * -// |g_scalar| and |points[i]| * |scalars[i]| where |points| and |scalars| have -// |num| elements. It assumes that the inputs are public so there is no concern -// about leaking their values through timing. |g_scalar| may be NULL to skip +// ec_point_mul_scalar_public_batch sets `r` to the sum of generator * +// `g_scalar` and `points[i]` * `scalars[i]` where `points` and `scalars` have +// `num` elements. It assumes that the inputs are public so there is no concern +// about leaking their values through timing. `g_scalar` may be NULL to skip // that term. // // This function is not implemented for all curves. Add implementations as @@ -357,33 +430,33 @@ int ec_point_mul_scalar_public_batch(const EC_GROUP *group, EC_JACOBIAN *r, const EC_JACOBIAN *points, const EC_SCALAR *scalars, size_t num); -// ec_point_select, in constant time, sets |out| to |a| if |mask| is all ones -// and |b| if |mask| is all zeros. +// ec_point_select, in constant time, sets `out` to `a` if `mask` is all ones +// and `b` if `mask` is all zeros. void ec_point_select(const EC_GROUP *group, EC_JACOBIAN *out, BN_ULONG mask, const EC_JACOBIAN *a, const EC_JACOBIAN *b); -// ec_affine_select behaves like |ec_point_select| but acts on affine points. +// ec_affine_select behaves like `ec_point_select` but acts on affine points. void ec_affine_select(const EC_GROUP *group, EC_AFFINE *out, BN_ULONG mask, const EC_AFFINE *a, const EC_AFFINE *b); -// ec_precomp_select behaves like |ec_point_select| but acts on |EC_PRECOMP|. +// ec_precomp_select behaves like `ec_point_select` but acts on `EC_PRECOMP`. void ec_precomp_select(const EC_GROUP *group, EC_PRECOMP *out, BN_ULONG mask, const EC_PRECOMP *a, const EC_PRECOMP *b); -// ec_cmp_x_coordinate compares the x (affine) coordinate of |p|, mod the group -// order, with |r|. It returns one if the values match and zero if |p| is the -// point at infinity of the values do not match. |p| is treated as public. +// ec_cmp_x_coordinate compares the x (affine) coordinate of `p`, mod the group +// order, with `r`. It returns one if the values match and zero if `p` is the +// point at infinity of the values do not match. `p` is treated as public. int ec_cmp_x_coordinate(const EC_GROUP *group, const EC_JACOBIAN *p, const EC_SCALAR *r); -// ec_get_x_coordinate_as_scalar sets |*out| to |p|'s x-coordinate, modulo -// |group->order|. It returns one on success and zero if |p| is the point at +// ec_get_x_coordinate_as_scalar sets `*out` to `p`'s x-coordinate, modulo +// `group->order`. It returns one on success and zero if `p` is the point at // infinity. int ec_get_x_coordinate_as_scalar(const EC_GROUP *group, EC_SCALAR *out, const EC_JACOBIAN *p); -// ec_get_x_coordinate_as_bytes writes |p|'s affine x-coordinate to |out|, which -// must have at must |max_out| bytes. It sets |*out_len| to the number of bytes +// ec_get_x_coordinate_as_bytes writes `p`'s affine x-coordinate to `out`, which +// must have at must `max_out` bytes. It sets `*out_len` to the number of bytes // written. The value is written big-endian and zero-padded to the size of the // field. This function returns one on success and zero on failure. int ec_get_x_coordinate_as_bytes(const EC_GROUP *group, uint8_t *out, @@ -391,195 +464,188 @@ int ec_get_x_coordinate_as_bytes(const EC_GROUP *group, uint8_t *out, const EC_JACOBIAN *p); // ec_point_byte_len returns the number of bytes in the byte representation of -// a non-infinity point in |group|, encoded according to |form|, or zero if -// |form| is invalid. +// a non-infinity point in `group`, encoded according to `form`, or zero if +// `form` is invalid. size_t ec_point_byte_len(const EC_GROUP *group, point_conversion_form_t form); -// ec_point_to_bytes encodes |point| according to |form| and writes the result -// |buf|. It returns the size of the output on success or zero on error. At most -// |max_out| bytes will be written. The buffer should be at least -// |ec_point_byte_len| long to guarantee success. +// ec_point_to_bytes encodes `point` according to `form` and writes the result +// `buf`. It returns the size of the output on success or zero on error. At most +// `max_out` bytes will be written. The buffer should be at least +// `ec_point_byte_len` long to guarantee success. size_t ec_point_to_bytes(const EC_GROUP *group, const EC_AFFINE *point, point_conversion_form_t form, uint8_t *buf, size_t max_out); -// ec_point_from_uncompressed parses |in| as a point in uncompressed form and -// sets the result to |out|. It returns one on success and zero if the input was +// ec_point_from_uncompressed parses `in` as a point in uncompressed form and +// sets `out` to the result. It returns one on success and zero if the input was // invalid. int ec_point_from_uncompressed(const EC_GROUP *group, EC_AFFINE *out, const uint8_t *in, size_t len); -// ec_set_to_safe_point sets |out| to an arbitrary point on |group|, either the +// ec_point_from_compressed parses `in` as a point in compressed form and sets +// `out` to the result`. It returns one on success and zero if the input was +// invalid. +int ec_point_from_compressed(const EC_GROUP *group, EC_AFFINE *out, + const uint8_t *in, size_t len); + +// ec_set_to_safe_point sets `out` to an arbitrary point on `group`, either the // generator or the point at infinity. This is used to guard against callers of // external APIs not checking the return value. void ec_set_to_safe_point(const EC_GROUP *group, EC_JACOBIAN *out); -// ec_affine_jacobian_equal returns one if |a| and |b| represent the same point +// ec_affine_jacobian_equal returns one if `a` and `b` represent the same point // and zero otherwise. It treats both inputs as secret. int ec_affine_jacobian_equal(const EC_GROUP *group, const EC_AFFINE *a, const EC_JACOBIAN *b); +BSSL_NAMESPACE_END // Implementation details. struct ec_method_st { - // point_get_affine_coordinates sets |*x| and |*y| to the affine coordinates - // of |p|. Either |x| or |y| may be NULL to omit it. It returns one on success - // and zero if |p| is the point at infinity. It leaks whether |p| was the - // point at infinity, but otherwise treats |p| as secret. - int (*point_get_affine_coordinates)(const EC_GROUP *, const EC_JACOBIAN *p, - EC_FELEM *x, EC_FELEM *y); + // point_get_affine_coordinates sets `*x` and `*y` to the affine coordinates + // of `p`. Either `x` or `y` may be NULL to omit it. It returns one on success + // and zero if `p` is the point at infinity. It leaks whether `p` was the + // point at infinity, but otherwise treats `p` as secret. + int (*point_get_affine_coordinates)(const EC_GROUP *, + const bssl::EC_JACOBIAN *p, + bssl::EC_FELEM *x, bssl::EC_FELEM *y); - // jacobian_to_affine_batch implements |ec_jacobian_to_affine_batch|. - int (*jacobian_to_affine_batch)(const EC_GROUP *group, EC_AFFINE *out, - const EC_JACOBIAN *in, size_t num); + // jacobian_to_affine_batch implements `ec_jacobian_to_affine_batch`. + int (*jacobian_to_affine_batch)(const EC_GROUP *group, bssl::EC_AFFINE *out, + const bssl::EC_JACOBIAN *in, size_t num); - // add sets |r| to |a| + |b|. - void (*add)(const EC_GROUP *group, EC_JACOBIAN *r, const EC_JACOBIAN *a, - const EC_JACOBIAN *b); - // dbl sets |r| to |a| + |a|. - void (*dbl)(const EC_GROUP *group, EC_JACOBIAN *r, const EC_JACOBIAN *a); + // add sets `r` to `a` + `b`. + void (*add)(const EC_GROUP *group, bssl::EC_JACOBIAN *r, + const bssl::EC_JACOBIAN *a, const bssl::EC_JACOBIAN *b); + // dbl sets `r` to `a` + `a`. + void (*dbl)(const EC_GROUP *group, bssl::EC_JACOBIAN *r, + const bssl::EC_JACOBIAN *a); - // mul sets |r| to |scalar|*|p|. - void (*mul)(const EC_GROUP *group, EC_JACOBIAN *r, const EC_JACOBIAN *p, - const EC_SCALAR *scalar); - // mul_base sets |r| to |scalar|*generator. - void (*mul_base)(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_SCALAR *scalar); - // mul_batch implements |ec_mul_scalar_batch|. - void (*mul_batch)(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_JACOBIAN *p0, const EC_SCALAR *scalar0, - const EC_JACOBIAN *p1, const EC_SCALAR *scalar1, - const EC_JACOBIAN *p2, const EC_SCALAR *scalar2); - // mul_public sets |r| to |g_scalar|*generator + |p_scalar|*|p|. It assumes + // mul sets `r` to `scalar`*`p`. + void (*mul)(const EC_GROUP *group, bssl::EC_JACOBIAN *r, + const bssl::EC_JACOBIAN *p, const bssl::EC_SCALAR *scalar); + // mul_base sets `r` to `scalar`*generator. + void (*mul_base)(const EC_GROUP *group, bssl::EC_JACOBIAN *r, + const bssl::EC_SCALAR *scalar); + // mul_batch implements `ec_mul_scalar_batch`. + void (*mul_batch)(const EC_GROUP *group, bssl::EC_JACOBIAN *r, + const bssl::EC_JACOBIAN *p0, const bssl::EC_SCALAR *scalar0, + const bssl::EC_JACOBIAN *p1, const bssl::EC_SCALAR *scalar1, + const bssl::EC_JACOBIAN *p2, + const bssl::EC_SCALAR *scalar2); + // mul_public sets `r` to `g_scalar`*generator + `p_scalar`*`p`. It assumes // that the inputs are public so there is no concern about leaking their // values through timing. // - // This function may be omitted if |mul_public_batch| is provided. - void (*mul_public)(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_SCALAR *g_scalar, const EC_JACOBIAN *p, - const EC_SCALAR *p_scalar); - // mul_public_batch implements |ec_point_mul_scalar_public_batch|. - int (*mul_public_batch)(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_SCALAR *g_scalar, const EC_JACOBIAN *points, - const EC_SCALAR *scalars, size_t num); + // This function may be omitted if `mul_public_batch` is provided. + void (*mul_public)(const EC_GROUP *group, bssl::EC_JACOBIAN *r, + const bssl::EC_SCALAR *g_scalar, + const bssl::EC_JACOBIAN *p, + const bssl::EC_SCALAR *p_scalar); + // mul_public_batch implements `ec_point_mul_scalar_public_batch`. + int (*mul_public_batch)(const EC_GROUP *group, bssl::EC_JACOBIAN *r, + const bssl::EC_SCALAR *g_scalar, + const bssl::EC_JACOBIAN *points, + const bssl::EC_SCALAR *scalars, size_t num); - // init_precomp implements |ec_init_precomp|. - int (*init_precomp)(const EC_GROUP *group, EC_PRECOMP *out, - const EC_JACOBIAN *p); - // mul_precomp implements |ec_point_mul_scalar_precomp|. - void (*mul_precomp)(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_PRECOMP *p0, const EC_SCALAR *scalar0, - const EC_PRECOMP *p1, const EC_SCALAR *scalar1, - const EC_PRECOMP *p2, const EC_SCALAR *scalar2); + // init_precomp implements `ec_init_precomp`. + int (*init_precomp)(const EC_GROUP *group, bssl::EC_PRECOMP *out, + const bssl::EC_JACOBIAN *p); + // mul_precomp implements `ec_point_mul_scalar_precomp`. + void (*mul_precomp)(const EC_GROUP *group, bssl::EC_JACOBIAN *r, + const bssl::EC_PRECOMP *p0, + const bssl::EC_SCALAR *scalar0, + const bssl::EC_PRECOMP *p1, + const bssl::EC_SCALAR *scalar1, + const bssl::EC_PRECOMP *p2, + const bssl::EC_SCALAR *scalar2); - // felem_mul and felem_sqr implement multiplication and squaring, - // respectively, so that the generic |EC_POINT_add| and |EC_POINT_dbl| - // implementations can work both with |EC_GFp_mont_method| and the tuned - // operations. - // - // TODO(davidben): This constrains |EC_FELEM|'s internal representation, adds - // many indirect calls in the middle of the generic code, and a bunch of - // conversions. If p224-64.c were easily convertable to Montgomery form, we - // could say |EC_FELEM| is always in Montgomery form. If we routed the rest of - // simple.c to |EC_METHOD|, we could give |EC_POINT| an |EC_METHOD|-specific - // representation and say |EC_FELEM| is purely a |EC_GFp_mont_method| type. - void (*felem_mul)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a, - const EC_FELEM *b); - void (*felem_sqr)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a); - - void (*felem_to_bytes)(const EC_GROUP *group, uint8_t *out, size_t *out_len, - const EC_FELEM *in); - int (*felem_from_bytes)(const EC_GROUP *group, EC_FELEM *out, - const uint8_t *in, size_t len); - - // felem_reduce sets |out| to |words|, reduced modulo the field size, p. - // |words| must be less than p^2. |num| must be at most twice the width of p. - // This function treats |words| as secret. - // - // This function is only used in hash-to-curve and may be omitted in curves - // that do not support it. - void (*felem_reduce)(const EC_GROUP *group, EC_FELEM *out, - const BN_ULONG *words, size_t num); - - // felem_exp sets |out| to |a|^|exp|. It treats |a| is secret but |exp| as - // public. - // - // This function is used in hash-to-curve and may be NULL in curves not used - // with hash-to-curve. - // - // TODO(https://crbug.com/boringssl/567): hash-to-curve uses this as part of - // computing a square root, which is what compressed coordinates ultimately - // needs to avoid |BIGNUM|. Can we unify this a bit? By generalizing to - // arbitrary exponentiation, we also miss an opportunity to use a specialized - // addition chain. - void (*felem_exp)(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a, - const BN_ULONG *exp, size_t num_exp); - - // scalar_inv0_montgomery implements |ec_scalar_inv0_montgomery|. - void (*scalar_inv0_montgomery)(const EC_GROUP *group, EC_SCALAR *out, - const EC_SCALAR *in); + // scalar_inv0_montgomery implements `ec_scalar_inv0_montgomery`. + void (*scalar_inv0_montgomery)(const EC_GROUP *group, bssl::EC_SCALAR *out, + const bssl::EC_SCALAR *in); // scalar_to_montgomery_inv_vartime implements - // |ec_scalar_to_montgomery_inv_vartime|. - int (*scalar_to_montgomery_inv_vartime)(const EC_GROUP *group, EC_SCALAR *out, - const EC_SCALAR *in); + // `ec_scalar_to_montgomery_inv_vartime`. + int (*scalar_to_montgomery_inv_vartime)(const EC_GROUP *group, + bssl::EC_SCALAR *out, + const bssl::EC_SCALAR *in); - // cmp_x_coordinate compares the x (affine) coordinate of |p|, mod the group - // order, with |r|. It returns one if the values match and zero if |p| is the + // cmp_x_coordinate compares the x (affine) coordinate of `p`, mod the group + // order, with `r`. It returns one if the values match and zero if `p` is the // point at infinity of the values do not match. - int (*cmp_x_coordinate)(const EC_GROUP *group, const EC_JACOBIAN *p, - const EC_SCALAR *r); + int (*cmp_x_coordinate)(const EC_GROUP *group, const bssl::EC_JACOBIAN *p, + const bssl::EC_SCALAR *r); } /* EC_METHOD */; -const EC_METHOD *EC_GFp_mont_method(void); +BSSL_NAMESPACE_BEGIN + +const EC_METHOD *EC_GFp_mont_method(); + +BSSL_NAMESPACE_END struct ec_point_st { - // group is an owning reference to |group|, unless this is - // |group->generator|. + // group is an owning reference to `group`, unless this is + // `group->generator`. EC_GROUP *group; - // raw is the group-specific point data. Functions that take |EC_POINT| - // typically check consistency with |EC_GROUP| while functions that take - // |EC_JACOBIAN| do not. Thus accesses to this field should be externally + // raw is the group-specific point data. Functions that take `EC_POINT` + // typically check consistency with `EC_GROUP` while functions that take + // `EC_JACOBIAN` do not. Thus accesses to this field should be externally // checked for consistency. - EC_JACOBIAN raw; + bssl::EC_JACOBIAN raw; } /* EC_POINT */; struct ec_group_st { const EC_METHOD *meth; - // Unlike all other |EC_POINT|s, |generator| does not own |generator->group| + // Unlike all other `EC_POINT`s, `generator` does not own `generator->group` // to avoid a reference cycle. Additionally, Z is guaranteed to be one, so X - // and Y are suitable for use as an |EC_AFFINE|. Before |has_order| is set, Z + // and Y are suitable for use as an `EC_AFFINE`. Before `has_order` is set, Z // is one, but X and Y are uninitialized. EC_POINT generator; BN_MONT_CTX order; BN_MONT_CTX field; - EC_FELEM a, b; // Curve coefficients. + bssl::EC_FELEM a, b; // Curve coefficients. // comment is a human-readable string describing the curve. const char *comment; - int curve_name; // optional NID for named curve + // curve_name is the optional NID for named curve. + // + // If curve_name is NID_undef, the actual type is ECCustomGroup and the + // refcount must be respected when allocating/freeing. + int curve_name; + uint8_t oid[9]; uint8_t oid_len; - // a_is_minus3 is one if |a| is -3 mod |field| and zero otherwise. Point - // arithmetic is optimized for -3. - int a_is_minus3; + // a_is_minus3 is whether `a` is -3 mod `field`. Point arithmetic is optimized + // for -3. + bool a_is_minus3; - // has_order is one if |generator| and |order| have been initialized. - int has_order; + // field_is_3_mod_4 is whether `field` is 3 mod 4. + bool field_is_3_mod_4; - // field_greater_than_order is one if |field| is greate than |order| and zero - // otherwise. - int field_greater_than_order; + // has_order is whether `generator` and `order` have been initialized. + bool has_order; - CRYPTO_refcount_t references; + // field_greater_than_order is whether `field` is greater than `order`. + bool field_greater_than_order; } /* EC_GROUP */; +BSSL_NAMESPACE_BEGIN + +class ECCustomGroup : public ec_group_st, public RefCounted { + public: + explicit ECCustomGroup(const EC_METHOD *meth); + + private: + ~ECCustomGroup(); + friend RefCounted; +}; + EC_GROUP *ec_group_new(const EC_METHOD *meth, const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); @@ -597,14 +663,9 @@ void ec_GFp_mont_mul_precomp(const EC_GROUP *group, EC_JACOBIAN *r, const EC_PRECOMP *p0, const EC_SCALAR *scalar0, const EC_PRECOMP *p1, const EC_SCALAR *scalar1, const EC_PRECOMP *p2, const EC_SCALAR *scalar2); -void ec_GFp_mont_felem_reduce(const EC_GROUP *group, EC_FELEM *out, - const BN_ULONG *words, size_t num); -void ec_GFp_mont_felem_exp(const EC_GROUP *group, EC_FELEM *out, - const EC_FELEM *a, const BN_ULONG *exp, - size_t num_exp); // ec_compute_wNAF writes the modified width-(w+1) Non-Adjacent Form (wNAF) of -// |scalar| to |out|. |out| must have room for |bits| + 1 elements, each of +// `scalar` to `out`. `out` must have room for `bits` + 1 elements, each of // which will be either zero or odd with an absolute value less than 2^w // satisfying // scalar = \sum_j out[j]*2^j @@ -645,60 +706,47 @@ int ec_simple_scalar_to_montgomery_inv_vartime(const EC_GROUP *group, int ec_GFp_simple_cmp_x_coordinate(const EC_GROUP *group, const EC_JACOBIAN *p, const EC_SCALAR *r); -void ec_GFp_simple_felem_to_bytes(const EC_GROUP *group, uint8_t *out, - size_t *out_len, const EC_FELEM *in); -int ec_GFp_simple_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out, - const uint8_t *in, size_t len); - -// method functions in montgomery.c -void ec_GFp_mont_felem_mul(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a, - const EC_FELEM *b); -void ec_GFp_mont_felem_sqr(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a); - -void ec_GFp_mont_felem_to_bytes(const EC_GROUP *group, uint8_t *out, - size_t *out_len, const EC_FELEM *in); -int ec_GFp_mont_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out, - const uint8_t *in, size_t len); - void ec_GFp_nistp_recode_scalar_bits(crypto_word_t *sign, crypto_word_t *digit, crypto_word_t in); -const EC_METHOD *EC_GFp_nistp224_method(void); -const EC_METHOD *EC_GFp_nistp256_method(void); +const EC_METHOD *EC_GFp_nistp256_method(); // EC_GFp_nistz256_method is a GFp method using montgomery multiplication, with // x86-64 optimized P256. See http://eprint.iacr.org/2013/816. -const EC_METHOD *EC_GFp_nistz256_method(void); +const EC_METHOD *EC_GFp_nistz256_method(); -// An EC_WRAPPED_SCALAR is an |EC_SCALAR| with a parallel |BIGNUM| -// representation. It exists to support the |EC_KEY_get0_private_key| API. +// An EC_WRAPPED_SCALAR is an `EC_SCALAR` with a parallel `BIGNUM` +// representation. It exists to support the `EC_KEY_get0_private_key` API. typedef struct { BIGNUM bignum; EC_SCALAR scalar; } EC_WRAPPED_SCALAR; -struct ec_key_st { - EC_GROUP *group; +class ECKey : public ec_key_st, public RefCounted { + public: + explicit ECKey(const ENGINE *engine); - // Ideally |pub_key| would be an |EC_AFFINE| so serializing it does not pay an - // inversion each time, but the |EC_KEY_get0_public_key| API implies public - // keys are stored in an |EC_POINT|-compatible form. - EC_POINT *pub_key; - EC_WRAPPED_SCALAR *priv_key; + EC_GROUP *group = nullptr; - unsigned int enc_flag; - point_conversion_form_t conv_form; + // Ideally `pub_key` would be an `EC_AFFINE` so serializing it does not pay an + // inversion each time, but the `EC_KEY_get0_public_key` API implies public + // keys are stored in an `EC_POINT`-compatible form. + EC_POINT *pub_key = nullptr; + bssl::EC_WRAPPED_SCALAR *priv_key = nullptr; - CRYPTO_refcount_t references; + unsigned int enc_flag = 0; + point_conversion_form_t conv_form = POINT_CONVERSION_UNCOMPRESSED; - ECDSA_METHOD *ecdsa_meth; + ECDSA_METHOD *ecdsa_meth = nullptr; - CRYPTO_EX_DATA ex_data; + CRYPTO_EX_DATA ex_data = {}; + + private: + ~ECKey(); + friend RefCounted; } /* EC_KEY */; +BSSL_NAMESPACE_END -#if defined(__cplusplus) -} // extern C -#endif -#endif // OPENSSL_HEADER_EC_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_EC_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/oct.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/oct.cc.inc index 8e221baa..278435cb 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/oct.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/oct.cc.inc @@ -1,12 +1,17 @@ -/* - * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. - * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. +// +// 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 @@ -16,7 +21,10 @@ #include "internal.h" -size_t ec_point_byte_len(const EC_GROUP *group, point_conversion_form_t form) { +using namespace bssl; + +size_t bssl::ec_point_byte_len(const EC_GROUP *group, + point_conversion_form_t form) { if (form != POINT_CONVERSION_COMPRESSED && form != POINT_CONVERSION_UNCOMPRESSED) { OPENSSL_PUT_ERROR(EC, EC_R_INVALID_FORM); @@ -32,9 +40,9 @@ size_t ec_point_byte_len(const EC_GROUP *group, point_conversion_form_t form) { return output_len; } -size_t ec_point_to_bytes(const EC_GROUP *group, const EC_AFFINE *point, - point_conversion_form_t form, uint8_t *buf, - size_t max_out) { +size_t bssl::ec_point_to_bytes(const EC_GROUP *group, const EC_AFFINE *point, + point_conversion_form_t form, uint8_t *buf, + size_t max_out) { size_t output_len = ec_point_byte_len(group, form); if (max_out < output_len) { OPENSSL_PUT_ERROR(EC, EC_R_BUFFER_TOO_SMALL); @@ -58,22 +66,34 @@ size_t ec_point_to_bytes(const EC_GROUP *group, const EC_AFFINE *point, return output_len; } -int ec_point_from_uncompressed(const EC_GROUP *group, EC_AFFINE *out, - const uint8_t *in, size_t len) { +int bssl::ec_point_from_uncompressed(const EC_GROUP *group, EC_AFFINE *out, + const uint8_t *in, size_t len) { const size_t field_len = BN_num_bytes(&group->field.N); - if (len != 1 + 2 * field_len || in[0] != POINT_CONVERSION_UNCOMPRESSED) { + if (len != 1 /* form */ + 2 * field_len || + in[0] != POINT_CONVERSION_UNCOMPRESSED) { OPENSSL_PUT_ERROR(EC, EC_R_INVALID_ENCODING); return 0; } EC_FELEM x, y; - if (!ec_felem_from_bytes(group, &x, in + 1, field_len) || - !ec_felem_from_bytes(group, &y, in + 1 + field_len, field_len) || - !ec_point_set_affine_coordinates(group, out, &x, &y)) { + return ec_felem_from_bytes(group, &x, in + 1, field_len) && + ec_felem_from_bytes(group, &y, in + 1 + field_len, field_len) && + ec_point_set_affine_coordinates(group, out, &x, &y); +} + +int bssl::ec_point_from_compressed(const EC_GROUP *group, EC_AFFINE *out, + const uint8_t *in, size_t len) { + const size_t field_len = BN_num_bytes(&group->field.N); + if (len != 1 /* form */ + field_len || + (in[0] & ~1u) != POINT_CONVERSION_COMPRESSED) { + OPENSSL_PUT_ERROR(EC, EC_R_INVALID_ENCODING); return 0; } - return 1; + crypto_word_t y_bit = in[0] & 1; + EC_FELEM x; + return ec_felem_from_bytes(group, &x, in + 1, field_len) && + ec_point_set_compressed_coordinates(group, out, &x, y_bit); } static int ec_GFp_simple_oct2point(const EC_GROUP *group, EC_POINT *point, @@ -84,67 +104,24 @@ static int ec_GFp_simple_oct2point(const EC_GROUP *group, EC_POINT *point, return 0; } - uint8_t form = buf[0]; - if (form == static_cast(POINT_CONVERSION_UNCOMPRESSED)) { - EC_AFFINE affine; - if (!ec_point_from_uncompressed(group, &affine, buf, len)) { - // In the event of an error, defend against the caller not checking the - // return value by setting a known safe value. - ec_set_to_safe_point(group, &point->raw); - return 0; - } - ec_affine_to_jacobian(group, &point->raw, &affine); - return 1; - } - - const int y_bit = form & 1; - const size_t field_len = BN_num_bytes(&group->field.N); - form = form & ~1u; - if (form != static_cast(POINT_CONVERSION_COMPRESSED) || - len != 1 /* type byte */ + field_len) { - OPENSSL_PUT_ERROR(EC, EC_R_INVALID_ENCODING); + const uint8_t form = buf[0]; + EC_AFFINE affine; + bool ok = form == static_cast(POINT_CONVERSION_UNCOMPRESSED) + ? ec_point_from_uncompressed(group, &affine, buf, len) + : ec_point_from_compressed(group, &affine, buf, len); + if (!ok) { + // In the event of an error, defend against the caller not checking the + // return value by setting a known safe value. + ec_set_to_safe_point(group, &point->raw); return 0; } - - // TODO(davidben): Integrate compressed coordinates with the lower-level EC - // abstractions. This requires a way to compute square roots, which is tricky - // for primes which are not 3 (mod 4), namely P-224 and custom curves. P-224's - // prime is particularly inconvenient for compressed coordinates. See - // https://cr.yp.to/papers/sqroot.pdf - BN_CTX *new_ctx = NULL; - if (ctx == NULL) { - ctx = new_ctx = BN_CTX_new(); - if (ctx == NULL) { - return 0; - } - } - - int ret = 0; - BN_CTX_start(ctx); - BIGNUM *x = BN_CTX_get(ctx); - if (x == NULL || !BN_bin2bn(buf + 1, field_len, x)) { - goto err; - } - if (BN_ucmp(x, &group->field.N) >= 0) { - OPENSSL_PUT_ERROR(EC, EC_R_INVALID_ENCODING); - goto err; - } - - if (!EC_POINT_set_compressed_coordinates_GFp(group, point, x, y_bit, ctx)) { - goto err; - } - - ret = 1; - -err: - BN_CTX_end(ctx); - BN_CTX_free(new_ctx); - return ret; + ec_affine_to_jacobian(group, &point->raw, &affine); + return 1; } int EC_POINT_oct2point(const EC_GROUP *group, EC_POINT *point, const uint8_t *buf, size_t len, BN_CTX *ctx) { - if (EC_GROUP_cmp(group, point->group, NULL) != 0) { + if (EC_GROUP_cmp(group, point->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } @@ -154,14 +131,15 @@ int EC_POINT_oct2point(const EC_GROUP *group, EC_POINT *point, size_t EC_POINT_point2oct(const EC_GROUP *group, const EC_POINT *point, point_conversion_form_t form, uint8_t *buf, size_t max_out, BN_CTX *ctx) { - if (EC_GROUP_cmp(group, point->group, NULL) != 0) { + if (EC_GROUP_cmp(group, point->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } - if (buf == NULL) { - // When |buf| is NULL, just return the number of bytes that would be + if (buf == nullptr) { + // When `buf` is NULL, just return the number of bytes that would be // written, without doing an expensive Jacobian-to-affine conversion. - if (ec_GFp_simple_is_at_infinity(group, &point->raw)) { + if (constant_time_declassify_int( + ec_GFp_simple_is_at_infinity(group, &point->raw))) { OPENSSL_PUT_ERROR(EC, EC_R_POINT_AT_INFINITY); return 0; } @@ -177,13 +155,13 @@ size_t EC_POINT_point2oct(const EC_GROUP *group, const EC_POINT *point, size_t EC_POINT_point2buf(const EC_GROUP *group, const EC_POINT *point, point_conversion_form_t form, uint8_t **out_buf, BN_CTX *ctx) { - *out_buf = NULL; - size_t len = EC_POINT_point2oct(group, point, form, NULL, 0, ctx); + *out_buf = nullptr; + size_t len = EC_POINT_point2oct(group, point, form, nullptr, 0, ctx); if (len == 0) { return 0; } uint8_t *buf = reinterpret_cast(OPENSSL_malloc(len)); - if (buf == NULL) { + if (buf == nullptr) { return 0; } len = EC_POINT_point2oct(group, point, form, buf, len, ctx); @@ -194,108 +172,3 @@ size_t EC_POINT_point2buf(const EC_GROUP *group, const EC_POINT *point, *out_buf = buf; return len; } - -int EC_POINT_set_compressed_coordinates_GFp(const EC_GROUP *group, - EC_POINT *point, const BIGNUM *x, - int y_bit, BN_CTX *ctx) { - if (EC_GROUP_cmp(group, point->group, NULL) != 0) { - OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); - return 0; - } - - const BIGNUM *field = &group->field.N; - if (BN_is_negative(x) || BN_cmp(x, field) >= 0) { - OPENSSL_PUT_ERROR(EC, EC_R_INVALID_COMPRESSED_POINT); - return 0; - } - - BN_CTX *new_ctx = NULL; - int ret = 0; - - ERR_clear_error(); - - if (ctx == NULL) { - ctx = new_ctx = BN_CTX_new(); - if (ctx == NULL) { - return 0; - } - } - - y_bit = (y_bit != 0); - - BN_CTX_start(ctx); - BIGNUM *tmp1 = BN_CTX_get(ctx); - BIGNUM *tmp2 = BN_CTX_get(ctx); - BIGNUM *a = BN_CTX_get(ctx); - BIGNUM *b = BN_CTX_get(ctx); - BIGNUM *y = BN_CTX_get(ctx); - if (y == NULL || !EC_GROUP_get_curve_GFp(group, NULL, a, b, ctx)) { - goto err; - } - - // Recover y. We have a Weierstrass equation - // y^2 = x^3 + a*x + b, - // so y is one of the square roots of x^3 + a*x + b. - - // tmp1 := x^3 - if (!BN_mod_sqr(tmp2, x, field, ctx) || - !BN_mod_mul(tmp1, tmp2, x, field, ctx)) { - goto err; - } - - // tmp1 := tmp1 + a*x - if (group->a_is_minus3) { - if (!bn_mod_lshift1_consttime(tmp2, x, field, ctx) || - !bn_mod_add_consttime(tmp2, tmp2, x, field, ctx) || - !bn_mod_sub_consttime(tmp1, tmp1, tmp2, field, ctx)) { - goto err; - } - } else { - if (!BN_mod_mul(tmp2, a, x, field, ctx) || - !bn_mod_add_consttime(tmp1, tmp1, tmp2, field, ctx)) { - goto err; - } - } - - // tmp1 := tmp1 + b - if (!bn_mod_add_consttime(tmp1, tmp1, b, field, ctx)) { - goto err; - } - - if (!BN_mod_sqrt(y, tmp1, field, ctx)) { - uint32_t err = ERR_peek_last_error(); - if (ERR_GET_LIB(err) == ERR_LIB_BN && - ERR_GET_REASON(err) == BN_R_NOT_A_SQUARE) { - ERR_clear_error(); - OPENSSL_PUT_ERROR(EC, EC_R_INVALID_COMPRESSED_POINT); - } else { - OPENSSL_PUT_ERROR(EC, ERR_R_BN_LIB); - } - goto err; - } - - if (y_bit != BN_is_odd(y)) { - if (BN_is_zero(y)) { - OPENSSL_PUT_ERROR(EC, EC_R_INVALID_COMPRESSION_BIT); - goto err; - } - if (!BN_usub(y, field, y)) { - goto err; - } - } - if (y_bit != BN_is_odd(y)) { - OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR); - goto err; - } - - if (!EC_POINT_set_affine_coordinates_GFp(group, point, x, y, ctx)) { - goto err; - } - - ret = 1; - -err: - BN_CTX_end(ctx); - BN_CTX_free(new_ctx); - return ret; -} diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p224-64.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p224-64.cc.inc deleted file mode 100644 index 3fd1b036..00000000 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p224-64.cc.inc +++ /dev/null @@ -1,1163 +0,0 @@ -/* Copyright 2015 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -// A 64-bit implementation of the NIST P-224 elliptic curve point multiplication -// -// Inspired by Daniel J. Bernstein's public domain nistp224 implementation -// and Adam Langley's public domain 64-bit C implementation of curve25519. - -#include - -#include -#include -#include -#include - -#include -#include - -#include "internal.h" -#include "../delocate.h" -#include "../../internal.h" - - -#if defined(BORINGSSL_HAS_UINT128) && !defined(OPENSSL_SMALL) - -// Field elements are represented as a_0 + 2^56*a_1 + 2^112*a_2 + 2^168*a_3 -// using 64-bit coefficients called 'limbs', and sometimes (for multiplication -// results) as b_0 + 2^56*b_1 + 2^112*b_2 + 2^168*b_3 + 2^224*b_4 + 2^280*b_5 + -// 2^336*b_6 using 128-bit coefficients called 'widelimbs'. A 4-p224_limb -// representation is an 'p224_felem'; a 7-p224_widelimb representation is a -// 'p224_widefelem'. Even within felems, bits of adjacent limbs overlap, and we -// don't always reduce the representations: we ensure that inputs to each -// p224_felem multiplication satisfy a_i < 2^60, so outputs satisfy b_i < -// 4*2^60*2^60, and fit into a 128-bit word without overflow. The coefficients -// are then again partially reduced to obtain an p224_felem satisfying a_i < -// 2^57. We only reduce to the unique minimal representation at the end of the -// computation. - -typedef uint64_t p224_limb; -typedef uint128_t p224_widelimb; - -typedef p224_limb p224_felem[4]; -typedef p224_widelimb p224_widefelem[7]; - -// Precomputed multiples of the standard generator -// Points are given in coordinates (X, Y, Z) where Z normally is 1 -// (0 for the point at infinity). -// For each field element, slice a_0 is word 0, etc. -// -// The table has 2 * 16 elements, starting with the following: -// index | bits | point -// ------+---------+------------------------------ -// 0 | 0 0 0 0 | 0G -// 1 | 0 0 0 1 | 1G -// 2 | 0 0 1 0 | 2^56G -// 3 | 0 0 1 1 | (2^56 + 1)G -// 4 | 0 1 0 0 | 2^112G -// 5 | 0 1 0 1 | (2^112 + 1)G -// 6 | 0 1 1 0 | (2^112 + 2^56)G -// 7 | 0 1 1 1 | (2^112 + 2^56 + 1)G -// 8 | 1 0 0 0 | 2^168G -// 9 | 1 0 0 1 | (2^168 + 1)G -// 10 | 1 0 1 0 | (2^168 + 2^56)G -// 11 | 1 0 1 1 | (2^168 + 2^56 + 1)G -// 12 | 1 1 0 0 | (2^168 + 2^112)G -// 13 | 1 1 0 1 | (2^168 + 2^112 + 1)G -// 14 | 1 1 1 0 | (2^168 + 2^112 + 2^56)G -// 15 | 1 1 1 1 | (2^168 + 2^112 + 2^56 + 1)G -// followed by a copy of this with each element multiplied by 2^28. -// -// The reason for this is so that we can clock bits into four different -// locations when doing simple scalar multiplies against the base point, -// and then another four locations using the second 16 elements. -static const p224_felem g_p224_pre_comp[2][16][3] = { - {{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, - {{0x3280d6115c1d21, 0xc1d356c2112234, 0x7f321390b94a03, 0xb70e0cbd6bb4bf}, - {0xd5819985007e34, 0x75a05a07476444, 0xfb4c22dfe6cd43, 0xbd376388b5f723}, - {1, 0, 0, 0}}, - {{0xfd9675666ebbe9, 0xbca7664d40ce5e, 0x2242df8d8a2a43, 0x1f49bbb0f99bc5}, - {0x29e0b892dc9c43, 0xece8608436e662, 0xdc858f185310d0, 0x9812dd4eb8d321}, - {1, 0, 0, 0}}, - {{0x6d3e678d5d8eb8, 0x559eed1cb362f1, 0x16e9a3bbce8a3f, 0xeedcccd8c2a748}, - {0xf19f90ed50266d, 0xabf2b4bf65f9df, 0x313865468fafec, 0x5cb379ba910a17}, - {1, 0, 0, 0}}, - {{0x0641966cab26e3, 0x91fb2991fab0a0, 0xefec27a4e13a0b, 0x0499aa8a5f8ebe}, - {0x7510407766af5d, 0x84d929610d5450, 0x81d77aae82f706, 0x6916f6d4338c5b}, - {1, 0, 0, 0}}, - {{0xea95ac3b1f15c6, 0x086000905e82d4, 0xdd323ae4d1c8b1, 0x932b56be7685a3}, - {0x9ef93dea25dbbf, 0x41665960f390f0, 0xfdec76dbe2a8a7, 0x523e80f019062a}, - {1, 0, 0, 0}}, - {{0x822fdd26732c73, 0xa01c83531b5d0f, 0x363f37347c1ba4, 0xc391b45c84725c}, - {0xbbd5e1b2d6ad24, 0xddfbcde19dfaec, 0xc393da7e222a7f, 0x1efb7890ede244}, - {1, 0, 0, 0}}, - {{0x4c9e90ca217da1, 0xd11beca79159bb, 0xff8d33c2c98b7c, 0x2610b39409f849}, - {0x44d1352ac64da0, 0xcdbb7b2c46b4fb, 0x966c079b753c89, 0xfe67e4e820b112}, - {1, 0, 0, 0}}, - {{0xe28cae2df5312d, 0xc71b61d16f5c6e, 0x79b7619a3e7c4c, 0x05c73240899b47}, - {0x9f7f6382c73e3a, 0x18615165c56bda, 0x641fab2116fd56, 0x72855882b08394}, - {1, 0, 0, 0}}, - {{0x0469182f161c09, 0x74a98ca8d00fb5, 0xb89da93489a3e0, 0x41c98768fb0c1d}, - {0xe5ea05fb32da81, 0x3dce9ffbca6855, 0x1cfe2d3fbf59e6, 0x0e5e03408738a7}, - {1, 0, 0, 0}}, - {{0xdab22b2333e87f, 0x4430137a5dd2f6, 0xe03ab9f738beb8, 0xcb0c5d0dc34f24}, - {0x764a7df0c8fda5, 0x185ba5c3fa2044, 0x9281d688bcbe50, 0xc40331df893881}, - {1, 0, 0, 0}}, - {{0xb89530796f0f60, 0xade92bd26909a3, 0x1a0c83fb4884da, 0x1765bf22a5a984}, - {0x772a9ee75db09e, 0x23bc6c67cec16f, 0x4c1edba8b14e2f, 0xe2a215d9611369}, - {1, 0, 0, 0}}, - {{0x571e509fb5efb3, 0xade88696410552, 0xc8ae85fada74fe, 0x6c7e4be83bbde3}, - {0xff9f51160f4652, 0xb47ce2495a6539, 0xa2946c53b582f4, 0x286d2db3ee9a60}, - {1, 0, 0, 0}}, - {{0x40bbd5081a44af, 0x0995183b13926c, 0xbcefba6f47f6d0, 0x215619e9cc0057}, - {0x8bc94d3b0df45e, 0xf11c54a3694f6f, 0x8631b93cdfe8b5, 0xe7e3f4b0982db9}, - {1, 0, 0, 0}}, - {{0xb17048ab3e1c7b, 0xac38f36ff8a1d8, 0x1c29819435d2c6, 0xc813132f4c07e9}, - {0x2891425503b11f, 0x08781030579fea, 0xf5426ba5cc9674, 0x1e28ebf18562bc}, - {1, 0, 0, 0}}, - {{0x9f31997cc864eb, 0x06cd91d28b5e4c, 0xff17036691a973, 0xf1aef351497c58}, - {0xdd1f2d600564ff, 0xdead073b1402db, 0x74a684435bd693, 0xeea7471f962558}, - {1, 0, 0, 0}}}, - {{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, - {{0x9665266dddf554, 0x9613d78b60ef2d, 0xce27a34cdba417, 0xd35ab74d6afc31}, - {0x85ccdd22deb15e, 0x2137e5783a6aab, 0xa141cffd8c93c6, 0x355a1830e90f2d}, - {1, 0, 0, 0}}, - {{0x1a494eadaade65, 0xd6da4da77fe53c, 0xe7992996abec86, 0x65c3553c6090e3}, - {0xfa610b1fb09346, 0xf1c6540b8a4aaf, 0xc51a13ccd3cbab, 0x02995b1b18c28a}, - {1, 0, 0, 0}}, - {{0x7874568e7295ef, 0x86b419fbe38d04, 0xdc0690a7550d9a, 0xd3966a44beac33}, - {0x2b7280ec29132f, 0xbeaa3b6a032df3, 0xdc7dd88ae41200, 0xd25e2513e3a100}, - {1, 0, 0, 0}}, - {{0x924857eb2efafd, 0xac2bce41223190, 0x8edaa1445553fc, 0x825800fd3562d5}, - {0x8d79148ea96621, 0x23a01c3dd9ed8d, 0xaf8b219f9416b5, 0xd8db0cc277daea}, - {1, 0, 0, 0}}, - {{0x76a9c3b1a700f0, 0xe9acd29bc7e691, 0x69212d1a6b0327, 0x6322e97fe154be}, - {0x469fc5465d62aa, 0x8d41ed18883b05, 0x1f8eae66c52b88, 0xe4fcbe9325be51}, - {1, 0, 0, 0}}, - {{0x825fdf583cac16, 0x020b857c7b023a, 0x683c17744b0165, 0x14ffd0a2daf2f1}, - {0x323b36184218f9, 0x4944ec4e3b47d4, 0xc15b3080841acf, 0x0bced4b01a28bb}, - {1, 0, 0, 0}}, - {{0x92ac22230df5c4, 0x52f33b4063eda8, 0xcb3f19870c0c93, 0x40064f2ba65233}, - {0xfe16f0924f8992, 0x012da25af5b517, 0x1a57bb24f723a6, 0x06f8bc76760def}, - {1, 0, 0, 0}}, - {{0x4a7084f7817cb9, 0xbcab0738ee9a78, 0x3ec11e11d9c326, 0xdc0fe90e0f1aae}, - {0xcf639ea5f98390, 0x5c350aa22ffb74, 0x9afae98a4047b7, 0x956ec2d617fc45}, - {1, 0, 0, 0}}, - {{0x4306d648c1be6a, 0x9247cd8bc9a462, 0xf5595e377d2f2e, 0xbd1c3caff1a52e}, - {0x045e14472409d0, 0x29f3e17078f773, 0x745a602b2d4f7d, 0x191837685cdfbb}, - {1, 0, 0, 0}}, - {{0x5b6ee254a8cb79, 0x4953433f5e7026, 0xe21faeb1d1def4, 0xc4c225785c09de}, - {0x307ce7bba1e518, 0x31b125b1036db8, 0x47e91868839e8f, 0xc765866e33b9f3}, - {1, 0, 0, 0}}, - {{0x3bfece24f96906, 0x4794da641e5093, 0xde5df64f95db26, 0x297ecd89714b05}, - {0x701bd3ebb2c3aa, 0x7073b4f53cb1d5, 0x13c5665658af16, 0x9895089d66fe58}, - {1, 0, 0, 0}}, - {{0x0fef05f78c4790, 0x2d773633b05d2e, 0x94229c3a951c94, 0xbbbd70df4911bb}, - {0xb2c6963d2c1168, 0x105f47a72b0d73, 0x9fdf6111614080, 0x7b7e94b39e67b0}, - {1, 0, 0, 0}}, - {{0xad1a7d6efbe2b3, 0xf012482c0da69d, 0x6b3bdf12438345, 0x40d7558d7aa4d9}, - {0x8a09fffb5c6d3d, 0x9a356e5d9ffd38, 0x5973f15f4f9b1c, 0xdcd5f59f63c3ea}, - {1, 0, 0, 0}}, - {{0xacf39f4c5ca7ab, 0x4c8071cc5fd737, 0xc64e3602cd1184, 0x0acd4644c9abba}, - {0x6c011a36d8bf6e, 0xfecd87ba24e32a, 0x19f6f56574fad8, 0x050b204ced9405}, - {1, 0, 0, 0}}, - {{0xed4f1cae7d9a96, 0x5ceef7ad94c40a, 0x778e4a3bf3ef9b, 0x7405783dc3b55e}, - {0x32477c61b6e8c6, 0xb46a97570f018b, 0x91176d0a7e95d1, 0x3df90fbc4c7d0e}, - {1, 0, 0, 0}}}}; - - -// Helper functions to convert field elements to/from internal representation - -static void p224_generic_to_felem(p224_felem out, const EC_FELEM *in) { - // |p224_felem|'s minimal representation uses four 56-bit words. |EC_FELEM| - // uses four 64-bit words. (The top-most word only has 32 bits.) - out[0] = in->words[0] & 0x00ffffffffffffff; - out[1] = ((in->words[0] >> 56) | (in->words[1] << 8)) & 0x00ffffffffffffff; - out[2] = ((in->words[1] >> 48) | (in->words[2] << 16)) & 0x00ffffffffffffff; - out[3] = ((in->words[2] >> 40) | (in->words[3] << 24)) & 0x00ffffffffffffff; -} - -// Requires 0 <= in < 2*p (always call p224_felem_reduce first) -static void p224_felem_to_generic(EC_FELEM *out, const p224_felem in) { - // Reduce to unique minimal representation. - static const int64_t two56 = ((p224_limb)1) << 56; - // 0 <= in < 2*p, p = 2^224 - 2^96 + 1 - // if in > p , reduce in = in - 2^224 + 2^96 - 1 - int64_t tmp[4], a; - tmp[0] = in[0]; - tmp[1] = in[1]; - tmp[2] = in[2]; - tmp[3] = in[3]; - // Case 1: a = 1 iff in >= 2^224 - a = (in[3] >> 56); - tmp[0] -= a; - tmp[1] += a << 40; - tmp[3] &= 0x00ffffffffffffff; - // Case 2: a = 0 iff p <= in < 2^224, i.e., the high 128 bits are all 1 and - // the lower part is non-zero - a = ((in[3] & in[2] & (in[1] | 0x000000ffffffffff)) + 1) | - (((int64_t)(in[0] + (in[1] & 0x000000ffffffffff)) - 1) >> 63); - a &= 0x00ffffffffffffff; - // turn a into an all-one mask (if a = 0) or an all-zero mask - a = (a - 1) >> 63; - // subtract 2^224 - 2^96 + 1 if a is all-one - tmp[3] &= a ^ 0xffffffffffffffff; - tmp[2] &= a ^ 0xffffffffffffffff; - tmp[1] &= (a ^ 0xffffffffffffffff) | 0x000000ffffffffff; - tmp[0] -= 1 & a; - - // eliminate negative coefficients: if tmp[0] is negative, tmp[1] must - // be non-zero, so we only need one step - a = tmp[0] >> 63; - tmp[0] += two56 & a; - tmp[1] -= 1 & a; - - // carry 1 -> 2 -> 3 - tmp[2] += tmp[1] >> 56; - tmp[1] &= 0x00ffffffffffffff; - - tmp[3] += tmp[2] >> 56; - tmp[2] &= 0x00ffffffffffffff; - - // Now 0 <= tmp < p - p224_felem tmp2; - tmp2[0] = tmp[0]; - tmp2[1] = tmp[1]; - tmp2[2] = tmp[2]; - tmp2[3] = tmp[3]; - - // |p224_felem|'s minimal representation uses four 56-bit words. |EC_FELEM| - // uses four 64-bit words. (The top-most word only has 32 bits.) - out->words[0] = tmp2[0] | (tmp2[1] << 56); - out->words[1] = (tmp2[1] >> 8) | (tmp2[2] << 48); - out->words[2] = (tmp2[2] >> 16) | (tmp2[3] << 40); - out->words[3] = tmp2[3] >> 24; -} - - -// Field operations, using the internal representation of field elements. -// NB! These operations are specific to our point multiplication and cannot be -// expected to be correct in general - e.g., multiplication with a large scalar -// will cause an overflow. - -static void p224_felem_assign(p224_felem out, const p224_felem in) { - out[0] = in[0]; - out[1] = in[1]; - out[2] = in[2]; - out[3] = in[3]; -} - -// Sum two field elements: out += in -static void p224_felem_sum(p224_felem out, const p224_felem in) { - out[0] += in[0]; - out[1] += in[1]; - out[2] += in[2]; - out[3] += in[3]; -} - -// Subtract field elements: out -= in -// Assumes in[i] < 2^57 -static void p224_felem_diff(p224_felem out, const p224_felem in) { - static const p224_limb two58p2 = - (((p224_limb)1) << 58) + (((p224_limb)1) << 2); - static const p224_limb two58m2 = - (((p224_limb)1) << 58) - (((p224_limb)1) << 2); - static const p224_limb two58m42m2 = - (((p224_limb)1) << 58) - (((p224_limb)1) << 42) - (((p224_limb)1) << 2); - - // Add 0 mod 2^224-2^96+1 to ensure out > in - out[0] += two58p2; - out[1] += two58m42m2; - out[2] += two58m2; - out[3] += two58m2; - - out[0] -= in[0]; - out[1] -= in[1]; - out[2] -= in[2]; - out[3] -= in[3]; -} - -// Subtract in unreduced 128-bit mode: out -= in -// Assumes in[i] < 2^119 -static void p224_widefelem_diff(p224_widefelem out, const p224_widefelem in) { - static const p224_widelimb two120 = ((p224_widelimb)1) << 120; - static const p224_widelimb two120m64 = - (((p224_widelimb)1) << 120) - (((p224_widelimb)1) << 64); - static const p224_widelimb two120m104m64 = (((p224_widelimb)1) << 120) - - (((p224_widelimb)1) << 104) - - (((p224_widelimb)1) << 64); - - // Add 0 mod 2^224-2^96+1 to ensure out > in - out[0] += two120; - out[1] += two120m64; - out[2] += two120m64; - out[3] += two120; - out[4] += two120m104m64; - out[5] += two120m64; - out[6] += two120m64; - - out[0] -= in[0]; - out[1] -= in[1]; - out[2] -= in[2]; - out[3] -= in[3]; - out[4] -= in[4]; - out[5] -= in[5]; - out[6] -= in[6]; -} - -// Subtract in mixed mode: out128 -= in64 -// in[i] < 2^63 -static void p224_felem_diff_128_64(p224_widefelem out, const p224_felem in) { - static const p224_widelimb two64p8 = - (((p224_widelimb)1) << 64) + (((p224_widelimb)1) << 8); - static const p224_widelimb two64m8 = - (((p224_widelimb)1) << 64) - (((p224_widelimb)1) << 8); - static const p224_widelimb two64m48m8 = (((p224_widelimb)1) << 64) - - (((p224_widelimb)1) << 48) - - (((p224_widelimb)1) << 8); - - // Add 0 mod 2^224-2^96+1 to ensure out > in - out[0] += two64p8; - out[1] += two64m48m8; - out[2] += two64m8; - out[3] += two64m8; - - out[0] -= in[0]; - out[1] -= in[1]; - out[2] -= in[2]; - out[3] -= in[3]; -} - -// Multiply a field element by a scalar: out = out * scalar -// The scalars we actually use are small, so results fit without overflow -static void p224_felem_scalar(p224_felem out, const p224_limb scalar) { - out[0] *= scalar; - out[1] *= scalar; - out[2] *= scalar; - out[3] *= scalar; -} - -// Multiply an unreduced field element by a scalar: out = out * scalar -// The scalars we actually use are small, so results fit without overflow -static void p224_widefelem_scalar(p224_widefelem out, - const p224_widelimb scalar) { - out[0] *= scalar; - out[1] *= scalar; - out[2] *= scalar; - out[3] *= scalar; - out[4] *= scalar; - out[5] *= scalar; - out[6] *= scalar; -} - -// Square a field element: out = in^2 -static void p224_felem_square(p224_widefelem out, const p224_felem in) { - p224_limb tmp0, tmp1, tmp2; - tmp0 = 2 * in[0]; - tmp1 = 2 * in[1]; - tmp2 = 2 * in[2]; - out[0] = ((p224_widelimb)in[0]) * in[0]; - out[1] = ((p224_widelimb)in[0]) * tmp1; - out[2] = ((p224_widelimb)in[0]) * tmp2 + ((p224_widelimb)in[1]) * in[1]; - out[3] = ((p224_widelimb)in[3]) * tmp0 + ((p224_widelimb)in[1]) * tmp2; - out[4] = ((p224_widelimb)in[3]) * tmp1 + ((p224_widelimb)in[2]) * in[2]; - out[5] = ((p224_widelimb)in[3]) * tmp2; - out[6] = ((p224_widelimb)in[3]) * in[3]; -} - -// Multiply two field elements: out = in1 * in2 -static void p224_felem_mul(p224_widefelem out, const p224_felem in1, - const p224_felem in2) { - out[0] = ((p224_widelimb)in1[0]) * in2[0]; - out[1] = ((p224_widelimb)in1[0]) * in2[1] + ((p224_widelimb)in1[1]) * in2[0]; - out[2] = ((p224_widelimb)in1[0]) * in2[2] + ((p224_widelimb)in1[1]) * in2[1] + - ((p224_widelimb)in1[2]) * in2[0]; - out[3] = ((p224_widelimb)in1[0]) * in2[3] + ((p224_widelimb)in1[1]) * in2[2] + - ((p224_widelimb)in1[2]) * in2[1] + ((p224_widelimb)in1[3]) * in2[0]; - out[4] = ((p224_widelimb)in1[1]) * in2[3] + ((p224_widelimb)in1[2]) * in2[2] + - ((p224_widelimb)in1[3]) * in2[1]; - out[5] = ((p224_widelimb)in1[2]) * in2[3] + ((p224_widelimb)in1[3]) * in2[2]; - out[6] = ((p224_widelimb)in1[3]) * in2[3]; -} - -// Reduce seven 128-bit coefficients to four 64-bit coefficients. -// Requires in[i] < 2^126, -// ensures out[0] < 2^56, out[1] < 2^56, out[2] < 2^56, out[3] <= 2^56 + 2^16 -static void p224_felem_reduce(p224_felem out, const p224_widefelem in) { - static const p224_widelimb two127p15 = - (((p224_widelimb)1) << 127) + (((p224_widelimb)1) << 15); - static const p224_widelimb two127m71 = - (((p224_widelimb)1) << 127) - (((p224_widelimb)1) << 71); - static const p224_widelimb two127m71m55 = (((p224_widelimb)1) << 127) - - (((p224_widelimb)1) << 71) - - (((p224_widelimb)1) << 55); - p224_widelimb output[5]; - - // Add 0 mod 2^224-2^96+1 to ensure all differences are positive - output[0] = in[0] + two127p15; - output[1] = in[1] + two127m71m55; - output[2] = in[2] + two127m71; - output[3] = in[3]; - output[4] = in[4]; - - // Eliminate in[4], in[5], in[6] - output[4] += in[6] >> 16; - output[3] += (in[6] & 0xffff) << 40; - output[2] -= in[6]; - - output[3] += in[5] >> 16; - output[2] += (in[5] & 0xffff) << 40; - output[1] -= in[5]; - - output[2] += output[4] >> 16; - output[1] += (output[4] & 0xffff) << 40; - output[0] -= output[4]; - - // Carry 2 -> 3 -> 4 - output[3] += output[2] >> 56; - output[2] &= 0x00ffffffffffffff; - - output[4] = output[3] >> 56; - output[3] &= 0x00ffffffffffffff; - - // Now output[2] < 2^56, output[3] < 2^56, output[4] < 2^72 - - // Eliminate output[4] - output[2] += output[4] >> 16; - // output[2] < 2^56 + 2^56 = 2^57 - output[1] += (output[4] & 0xffff) << 40; - output[0] -= output[4]; - - // Carry 0 -> 1 -> 2 -> 3 - output[1] += output[0] >> 56; - out[0] = output[0] & 0x00ffffffffffffff; - - output[2] += output[1] >> 56; - // output[2] < 2^57 + 2^72 - out[1] = output[1] & 0x00ffffffffffffff; - output[3] += output[2] >> 56; - // output[3] <= 2^56 + 2^16 - out[2] = output[2] & 0x00ffffffffffffff; - - // out[0] < 2^56, out[1] < 2^56, out[2] < 2^56, - // out[3] <= 2^56 + 2^16 (due to final carry), - // so out < 2*p - out[3] = output[3]; -} - -// Get negative value: out = -in -// Requires in[i] < 2^63, -// ensures out[0] < 2^56, out[1] < 2^56, out[2] < 2^56, out[3] <= 2^56 + 2^16 -static void p224_felem_neg(p224_felem out, const p224_felem in) { - p224_widefelem tmp = {0}; - p224_felem_diff_128_64(tmp, in); - p224_felem_reduce(out, tmp); -} - -// Zero-check: returns 1 if input is 0, and 0 otherwise. We know that field -// elements are reduced to in < 2^225, so we only need to check three cases: 0, -// 2^224 - 2^96 + 1, and 2^225 - 2^97 + 2 -static p224_limb p224_felem_is_zero(const p224_felem in) { - p224_limb zero = in[0] | in[1] | in[2] | in[3]; - zero = (((int64_t)(zero)-1) >> 63) & 1; - - p224_limb two224m96p1 = (in[0] ^ 1) | (in[1] ^ 0x00ffff0000000000) | - (in[2] ^ 0x00ffffffffffffff) | - (in[3] ^ 0x00ffffffffffffff); - two224m96p1 = (((int64_t)(two224m96p1)-1) >> 63) & 1; - p224_limb two225m97p2 = (in[0] ^ 2) | (in[1] ^ 0x00fffe0000000000) | - (in[2] ^ 0x00ffffffffffffff) | - (in[3] ^ 0x01ffffffffffffff); - two225m97p2 = (((int64_t)(two225m97p2)-1) >> 63) & 1; - return (zero | two224m96p1 | two225m97p2); -} - -// Invert a field element -// Computation chain copied from djb's code -static void p224_felem_inv(p224_felem out, const p224_felem in) { - p224_felem ftmp, ftmp2, ftmp3, ftmp4; - p224_widefelem tmp; - - p224_felem_square(tmp, in); - p224_felem_reduce(ftmp, tmp); // 2 - p224_felem_mul(tmp, in, ftmp); - p224_felem_reduce(ftmp, tmp); // 2^2 - 1 - p224_felem_square(tmp, ftmp); - p224_felem_reduce(ftmp, tmp); // 2^3 - 2 - p224_felem_mul(tmp, in, ftmp); - p224_felem_reduce(ftmp, tmp); // 2^3 - 1 - p224_felem_square(tmp, ftmp); - p224_felem_reduce(ftmp2, tmp); // 2^4 - 2 - p224_felem_square(tmp, ftmp2); - p224_felem_reduce(ftmp2, tmp); // 2^5 - 4 - p224_felem_square(tmp, ftmp2); - p224_felem_reduce(ftmp2, tmp); // 2^6 - 8 - p224_felem_mul(tmp, ftmp2, ftmp); - p224_felem_reduce(ftmp, tmp); // 2^6 - 1 - p224_felem_square(tmp, ftmp); - p224_felem_reduce(ftmp2, tmp); // 2^7 - 2 - for (size_t i = 0; i < 5; ++i) { // 2^12 - 2^6 - p224_felem_square(tmp, ftmp2); - p224_felem_reduce(ftmp2, tmp); - } - p224_felem_mul(tmp, ftmp2, ftmp); - p224_felem_reduce(ftmp2, tmp); // 2^12 - 1 - p224_felem_square(tmp, ftmp2); - p224_felem_reduce(ftmp3, tmp); // 2^13 - 2 - for (size_t i = 0; i < 11; ++i) { // 2^24 - 2^12 - p224_felem_square(tmp, ftmp3); - p224_felem_reduce(ftmp3, tmp); - } - p224_felem_mul(tmp, ftmp3, ftmp2); - p224_felem_reduce(ftmp2, tmp); // 2^24 - 1 - p224_felem_square(tmp, ftmp2); - p224_felem_reduce(ftmp3, tmp); // 2^25 - 2 - for (size_t i = 0; i < 23; ++i) { // 2^48 - 2^24 - p224_felem_square(tmp, ftmp3); - p224_felem_reduce(ftmp3, tmp); - } - p224_felem_mul(tmp, ftmp3, ftmp2); - p224_felem_reduce(ftmp3, tmp); // 2^48 - 1 - p224_felem_square(tmp, ftmp3); - p224_felem_reduce(ftmp4, tmp); // 2^49 - 2 - for (size_t i = 0; i < 47; ++i) { // 2^96 - 2^48 - p224_felem_square(tmp, ftmp4); - p224_felem_reduce(ftmp4, tmp); - } - p224_felem_mul(tmp, ftmp3, ftmp4); - p224_felem_reduce(ftmp3, tmp); // 2^96 - 1 - p224_felem_square(tmp, ftmp3); - p224_felem_reduce(ftmp4, tmp); // 2^97 - 2 - for (size_t i = 0; i < 23; ++i) { // 2^120 - 2^24 - p224_felem_square(tmp, ftmp4); - p224_felem_reduce(ftmp4, tmp); - } - p224_felem_mul(tmp, ftmp2, ftmp4); - p224_felem_reduce(ftmp2, tmp); // 2^120 - 1 - for (size_t i = 0; i < 6; ++i) { // 2^126 - 2^6 - p224_felem_square(tmp, ftmp2); - p224_felem_reduce(ftmp2, tmp); - } - p224_felem_mul(tmp, ftmp2, ftmp); - p224_felem_reduce(ftmp, tmp); // 2^126 - 1 - p224_felem_square(tmp, ftmp); - p224_felem_reduce(ftmp, tmp); // 2^127 - 2 - p224_felem_mul(tmp, ftmp, in); - p224_felem_reduce(ftmp, tmp); // 2^127 - 1 - for (size_t i = 0; i < 97; ++i) { // 2^224 - 2^97 - p224_felem_square(tmp, ftmp); - p224_felem_reduce(ftmp, tmp); - } - p224_felem_mul(tmp, ftmp, ftmp3); - p224_felem_reduce(out, tmp); // 2^224 - 2^96 - 1 -} - -// Copy in constant time: -// if icopy == 1, copy in to out, -// if icopy == 0, copy out to itself. -static void p224_copy_conditional(p224_felem out, const p224_felem in, - p224_limb icopy) { - // icopy is a (64-bit) 0 or 1, so copy is either all-zero or all-one - const p224_limb copy = -icopy; - for (size_t i = 0; i < 4; ++i) { - const p224_limb tmp = copy & (in[i] ^ out[i]); - out[i] ^= tmp; - } -} - -// ELLIPTIC CURVE POINT OPERATIONS -// -// Points are represented in Jacobian projective coordinates: -// (X, Y, Z) corresponds to the affine point (X/Z^2, Y/Z^3), -// or to the point at infinity if Z == 0. - -// Double an elliptic curve point: -// (X', Y', Z') = 2 * (X, Y, Z), where -// X' = (3 * (X - Z^2) * (X + Z^2))^2 - 8 * X * Y^2 -// Y' = 3 * (X - Z^2) * (X + Z^2) * (4 * X * Y^2 - X') - 8 * Y^2 -// Z' = (Y + Z)^2 - Y^2 - Z^2 = 2 * Y * Z -// Outputs can equal corresponding inputs, i.e., x_out == x_in is allowed, -// while x_out == y_in is not (maybe this works, but it's not tested). -static void p224_point_double(p224_felem x_out, p224_felem y_out, - p224_felem z_out, const p224_felem x_in, - const p224_felem y_in, const p224_felem z_in) { - p224_widefelem tmp, tmp2; - p224_felem delta, gamma, beta, alpha, ftmp, ftmp2; - - p224_felem_assign(ftmp, x_in); - p224_felem_assign(ftmp2, x_in); - - // delta = z^2 - p224_felem_square(tmp, z_in); - p224_felem_reduce(delta, tmp); - - // gamma = y^2 - p224_felem_square(tmp, y_in); - p224_felem_reduce(gamma, tmp); - - // beta = x*gamma - p224_felem_mul(tmp, x_in, gamma); - p224_felem_reduce(beta, tmp); - - // alpha = 3*(x-delta)*(x+delta) - p224_felem_diff(ftmp, delta); - // ftmp[i] < 2^57 + 2^58 + 2 < 2^59 - p224_felem_sum(ftmp2, delta); - // ftmp2[i] < 2^57 + 2^57 = 2^58 - p224_felem_scalar(ftmp2, 3); - // ftmp2[i] < 3 * 2^58 < 2^60 - p224_felem_mul(tmp, ftmp, ftmp2); - // tmp[i] < 2^60 * 2^59 * 4 = 2^121 - p224_felem_reduce(alpha, tmp); - - // x' = alpha^2 - 8*beta - p224_felem_square(tmp, alpha); - // tmp[i] < 4 * 2^57 * 2^57 = 2^116 - p224_felem_assign(ftmp, beta); - p224_felem_scalar(ftmp, 8); - // ftmp[i] < 8 * 2^57 = 2^60 - p224_felem_diff_128_64(tmp, ftmp); - // tmp[i] < 2^116 + 2^64 + 8 < 2^117 - p224_felem_reduce(x_out, tmp); - - // z' = (y + z)^2 - gamma - delta - p224_felem_sum(delta, gamma); - // delta[i] < 2^57 + 2^57 = 2^58 - p224_felem_assign(ftmp, y_in); - p224_felem_sum(ftmp, z_in); - // ftmp[i] < 2^57 + 2^57 = 2^58 - p224_felem_square(tmp, ftmp); - // tmp[i] < 4 * 2^58 * 2^58 = 2^118 - p224_felem_diff_128_64(tmp, delta); - // tmp[i] < 2^118 + 2^64 + 8 < 2^119 - p224_felem_reduce(z_out, tmp); - - // y' = alpha*(4*beta - x') - 8*gamma^2 - p224_felem_scalar(beta, 4); - // beta[i] < 4 * 2^57 = 2^59 - p224_felem_diff(beta, x_out); - // beta[i] < 2^59 + 2^58 + 2 < 2^60 - p224_felem_mul(tmp, alpha, beta); - // tmp[i] < 4 * 2^57 * 2^60 = 2^119 - p224_felem_square(tmp2, gamma); - // tmp2[i] < 4 * 2^57 * 2^57 = 2^116 - p224_widefelem_scalar(tmp2, 8); - // tmp2[i] < 8 * 2^116 = 2^119 - p224_widefelem_diff(tmp, tmp2); - // tmp[i] < 2^119 + 2^120 < 2^121 - p224_felem_reduce(y_out, tmp); -} - -// Add two elliptic curve points: -// (X_1, Y_1, Z_1) + (X_2, Y_2, Z_2) = (X_3, Y_3, Z_3), where -// X_3 = (Z_1^3 * Y_2 - Z_2^3 * Y_1)^2 - (Z_1^2 * X_2 - Z_2^2 * X_1)^3 - -// 2 * Z_2^2 * X_1 * (Z_1^2 * X_2 - Z_2^2 * X_1)^2 -// Y_3 = (Z_1^3 * Y_2 - Z_2^3 * Y_1) * (Z_2^2 * X_1 * (Z_1^2 * X_2 - Z_2^2 * -// X_1)^2 - X_3) - -// Z_2^3 * Y_1 * (Z_1^2 * X_2 - Z_2^2 * X_1)^3 -// Z_3 = (Z_1^2 * X_2 - Z_2^2 * X_1) * (Z_1 * Z_2) -// -// This runs faster if 'mixed' is set, which requires Z_2 = 1 or Z_2 = 0. - -// This function is not entirely constant-time: it includes a branch for -// checking whether the two input points are equal, (while not equal to the -// point at infinity). This case never happens during single point -// multiplication, so there is no timing leak for ECDH or ECDSA signing. -static void p224_point_add(p224_felem x3, p224_felem y3, p224_felem z3, - const p224_felem x1, const p224_felem y1, - const p224_felem z1, const int mixed, - const p224_felem x2, const p224_felem y2, - const p224_felem z2) { - p224_felem ftmp, ftmp2, ftmp3, ftmp4, ftmp5, x_out, y_out, z_out; - p224_widefelem tmp, tmp2; - p224_limb z1_is_zero, z2_is_zero, x_equal, y_equal; - - if (!mixed) { - // ftmp2 = z2^2 - p224_felem_square(tmp, z2); - p224_felem_reduce(ftmp2, tmp); - - // ftmp4 = z2^3 - p224_felem_mul(tmp, ftmp2, z2); - p224_felem_reduce(ftmp4, tmp); - - // ftmp4 = z2^3*y1 - p224_felem_mul(tmp2, ftmp4, y1); - p224_felem_reduce(ftmp4, tmp2); - - // ftmp2 = z2^2*x1 - p224_felem_mul(tmp2, ftmp2, x1); - p224_felem_reduce(ftmp2, tmp2); - } else { - // We'll assume z2 = 1 (special case z2 = 0 is handled later) - - // ftmp4 = z2^3*y1 - p224_felem_assign(ftmp4, y1); - - // ftmp2 = z2^2*x1 - p224_felem_assign(ftmp2, x1); - } - - // ftmp = z1^2 - p224_felem_square(tmp, z1); - p224_felem_reduce(ftmp, tmp); - - // ftmp3 = z1^3 - p224_felem_mul(tmp, ftmp, z1); - p224_felem_reduce(ftmp3, tmp); - - // tmp = z1^3*y2 - p224_felem_mul(tmp, ftmp3, y2); - // tmp[i] < 4 * 2^57 * 2^57 = 2^116 - - // ftmp3 = z1^3*y2 - z2^3*y1 - p224_felem_diff_128_64(tmp, ftmp4); - // tmp[i] < 2^116 + 2^64 + 8 < 2^117 - p224_felem_reduce(ftmp3, tmp); - - // tmp = z1^2*x2 - p224_felem_mul(tmp, ftmp, x2); - // tmp[i] < 4 * 2^57 * 2^57 = 2^116 - - // ftmp = z1^2*x2 - z2^2*x1 - p224_felem_diff_128_64(tmp, ftmp2); - // tmp[i] < 2^116 + 2^64 + 8 < 2^117 - p224_felem_reduce(ftmp, tmp); - - // The formulae are incorrect if the points are equal, so we check for this - // and do doubling if this happens. - x_equal = p224_felem_is_zero(ftmp); - y_equal = p224_felem_is_zero(ftmp3); - z1_is_zero = p224_felem_is_zero(z1); - z2_is_zero = p224_felem_is_zero(z2); - // In affine coordinates, (X_1, Y_1) == (X_2, Y_2) - p224_limb is_nontrivial_double = - x_equal & y_equal & (1 - z1_is_zero) & (1 - z2_is_zero); - if (constant_time_declassify_w(is_nontrivial_double)) { - p224_point_double(x3, y3, z3, x1, y1, z1); - return; - } - - // ftmp5 = z1*z2 - if (!mixed) { - p224_felem_mul(tmp, z1, z2); - p224_felem_reduce(ftmp5, tmp); - } else { - // special case z2 = 0 is handled later - p224_felem_assign(ftmp5, z1); - } - - // z_out = (z1^2*x2 - z2^2*x1)*(z1*z2) - p224_felem_mul(tmp, ftmp, ftmp5); - p224_felem_reduce(z_out, tmp); - - // ftmp = (z1^2*x2 - z2^2*x1)^2 - p224_felem_assign(ftmp5, ftmp); - p224_felem_square(tmp, ftmp); - p224_felem_reduce(ftmp, tmp); - - // ftmp5 = (z1^2*x2 - z2^2*x1)^3 - p224_felem_mul(tmp, ftmp, ftmp5); - p224_felem_reduce(ftmp5, tmp); - - // ftmp2 = z2^2*x1*(z1^2*x2 - z2^2*x1)^2 - p224_felem_mul(tmp, ftmp2, ftmp); - p224_felem_reduce(ftmp2, tmp); - - // tmp = z2^3*y1*(z1^2*x2 - z2^2*x1)^3 - p224_felem_mul(tmp, ftmp4, ftmp5); - // tmp[i] < 4 * 2^57 * 2^57 = 2^116 - - // tmp2 = (z1^3*y2 - z2^3*y1)^2 - p224_felem_square(tmp2, ftmp3); - // tmp2[i] < 4 * 2^57 * 2^57 < 2^116 - - // tmp2 = (z1^3*y2 - z2^3*y1)^2 - (z1^2*x2 - z2^2*x1)^3 - p224_felem_diff_128_64(tmp2, ftmp5); - // tmp2[i] < 2^116 + 2^64 + 8 < 2^117 - - // ftmp5 = 2*z2^2*x1*(z1^2*x2 - z2^2*x1)^2 - p224_felem_assign(ftmp5, ftmp2); - p224_felem_scalar(ftmp5, 2); - // ftmp5[i] < 2 * 2^57 = 2^58 - - /* x_out = (z1^3*y2 - z2^3*y1)^2 - (z1^2*x2 - z2^2*x1)^3 - - 2*z2^2*x1*(z1^2*x2 - z2^2*x1)^2 */ - p224_felem_diff_128_64(tmp2, ftmp5); - // tmp2[i] < 2^117 + 2^64 + 8 < 2^118 - p224_felem_reduce(x_out, tmp2); - - // ftmp2 = z2^2*x1*(z1^2*x2 - z2^2*x1)^2 - x_out - p224_felem_diff(ftmp2, x_out); - // ftmp2[i] < 2^57 + 2^58 + 2 < 2^59 - - // tmp2 = (z1^3*y2 - z2^3*y1)*(z2^2*x1*(z1^2*x2 - z2^2*x1)^2 - x_out) - p224_felem_mul(tmp2, ftmp3, ftmp2); - // tmp2[i] < 4 * 2^57 * 2^59 = 2^118 - - /* y_out = (z1^3*y2 - z2^3*y1)*(z2^2*x1*(z1^2*x2 - z2^2*x1)^2 - x_out) - - z2^3*y1*(z1^2*x2 - z2^2*x1)^3 */ - p224_widefelem_diff(tmp2, tmp); - // tmp2[i] < 2^118 + 2^120 < 2^121 - p224_felem_reduce(y_out, tmp2); - - // the result (x_out, y_out, z_out) is incorrect if one of the inputs is - // the point at infinity, so we need to check for this separately - - // if point 1 is at infinity, copy point 2 to output, and vice versa - p224_copy_conditional(x_out, x2, z1_is_zero); - p224_copy_conditional(x_out, x1, z2_is_zero); - p224_copy_conditional(y_out, y2, z1_is_zero); - p224_copy_conditional(y_out, y1, z2_is_zero); - p224_copy_conditional(z_out, z2, z1_is_zero); - p224_copy_conditional(z_out, z1, z2_is_zero); - p224_felem_assign(x3, x_out); - p224_felem_assign(y3, y_out); - p224_felem_assign(z3, z_out); -} - -// p224_select_point selects the |idx|th point from a precomputation table and -// copies it to out. -static void p224_select_point(const uint64_t idx, size_t size, - const p224_felem pre_comp[/*size*/][3], - p224_felem out[3]) { - p224_limb *outlimbs = &out[0][0]; - OPENSSL_memset(outlimbs, 0, 3 * sizeof(p224_felem)); - - for (size_t i = 0; i < size; i++) { - const p224_limb *inlimbs = &pre_comp[i][0][0]; - static_assert(sizeof(uint64_t) <= sizeof(crypto_word_t), - "crypto_word_t too small"); - static_assert(sizeof(size_t) <= sizeof(crypto_word_t), - "crypto_word_t too small"); - // Without a value barrier, Clang adds a branch here. - uint64_t mask = value_barrier_w(constant_time_eq_w(i, idx)); - for (size_t j = 0; j < 4 * 3; j++) { - outlimbs[j] |= inlimbs[j] & mask; - } - } -} - -// p224_get_bit returns the |i|th bit in |in|. -static crypto_word_t p224_get_bit(const EC_SCALAR *in, size_t i) { - if (i >= 224) { - return 0; - } - static_assert(sizeof(in->words[0]) == 8, "BN_ULONG is not 64-bit"); - return (in->words[i >> 6] >> (i & 63)) & 1; -} - -// Takes the Jacobian coordinates (X, Y, Z) of a point and returns -// (X', Y') = (X/Z^2, Y/Z^3) -static int ec_GFp_nistp224_point_get_affine_coordinates( - const EC_GROUP *group, const EC_JACOBIAN *point, EC_FELEM *x, - EC_FELEM *y) { - if (constant_time_declassify_int( - ec_GFp_simple_is_at_infinity(group, point))) { - OPENSSL_PUT_ERROR(EC, EC_R_POINT_AT_INFINITY); - return 0; - } - - p224_felem z1, z2; - p224_widefelem tmp; - p224_generic_to_felem(z1, &point->Z); - p224_felem_inv(z2, z1); - p224_felem_square(tmp, z2); - p224_felem_reduce(z1, tmp); - - if (x != NULL) { - p224_felem x_in, x_out; - p224_generic_to_felem(x_in, &point->X); - p224_felem_mul(tmp, x_in, z1); - p224_felem_reduce(x_out, tmp); - p224_felem_to_generic(x, x_out); - } - - if (y != NULL) { - p224_felem y_in, y_out; - p224_generic_to_felem(y_in, &point->Y); - p224_felem_mul(tmp, z1, z2); - p224_felem_reduce(z1, tmp); - p224_felem_mul(tmp, y_in, z1); - p224_felem_reduce(y_out, tmp); - p224_felem_to_generic(y, y_out); - } - - return 1; -} - -static void ec_GFp_nistp224_add(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_JACOBIAN *a, const EC_JACOBIAN *b) { - p224_felem x1, y1, z1, x2, y2, z2; - p224_generic_to_felem(x1, &a->X); - p224_generic_to_felem(y1, &a->Y); - p224_generic_to_felem(z1, &a->Z); - p224_generic_to_felem(x2, &b->X); - p224_generic_to_felem(y2, &b->Y); - p224_generic_to_felem(z2, &b->Z); - p224_point_add(x1, y1, z1, x1, y1, z1, 0 /* both Jacobian */, x2, y2, z2); - // The outputs are already reduced, but still need to be contracted. - p224_felem_to_generic(&r->X, x1); - p224_felem_to_generic(&r->Y, y1); - p224_felem_to_generic(&r->Z, z1); -} - -static void ec_GFp_nistp224_dbl(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_JACOBIAN *a) { - p224_felem x, y, z; - p224_generic_to_felem(x, &a->X); - p224_generic_to_felem(y, &a->Y); - p224_generic_to_felem(z, &a->Z); - p224_point_double(x, y, z, x, y, z); - // The outputs are already reduced, but still need to be contracted. - p224_felem_to_generic(&r->X, x); - p224_felem_to_generic(&r->Y, y); - p224_felem_to_generic(&r->Z, z); -} - -static void ec_GFp_nistp224_make_precomp(p224_felem out[17][3], - const EC_JACOBIAN *p) { - OPENSSL_memset(out[0], 0, sizeof(p224_felem) * 3); - - p224_generic_to_felem(out[1][0], &p->X); - p224_generic_to_felem(out[1][1], &p->Y); - p224_generic_to_felem(out[1][2], &p->Z); - - for (size_t j = 2; j <= 16; ++j) { - if (j & 1) { - p224_point_add(out[j][0], out[j][1], out[j][2], out[1][0], out[1][1], - out[1][2], 0, out[j - 1][0], out[j - 1][1], out[j - 1][2]); - } else { - p224_point_double(out[j][0], out[j][1], out[j][2], out[j / 2][0], - out[j / 2][1], out[j / 2][2]); - } - } -} - -static void ec_GFp_nistp224_point_mul(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_JACOBIAN *p, - const EC_SCALAR *scalar) { - p224_felem p_pre_comp[17][3]; - ec_GFp_nistp224_make_precomp(p_pre_comp, p); - - // Set nq to the point at infinity. - p224_felem nq[3], tmp[4]; - OPENSSL_memset(nq, 0, 3 * sizeof(p224_felem)); - - int skip = 1; // Save two point operations in the first round. - for (size_t i = 220; i < 221; i--) { - if (!skip) { - p224_point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]); - } - - // Add every 5 doublings. - if (i % 5 == 0) { - crypto_word_t bits = p224_get_bit(scalar, i + 4) << 5; - bits |= p224_get_bit(scalar, i + 3) << 4; - bits |= p224_get_bit(scalar, i + 2) << 3; - bits |= p224_get_bit(scalar, i + 1) << 2; - bits |= p224_get_bit(scalar, i) << 1; - bits |= p224_get_bit(scalar, i - 1); - crypto_word_t sign, digit; - ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits); - - // Select the point to add or subtract. - p224_select_point(digit, 17, (const p224_felem(*)[3])p_pre_comp, tmp); - p224_felem_neg(tmp[3], tmp[1]); // (X, -Y, Z) is the negative point - p224_copy_conditional(tmp[1], tmp[3], sign); - - if (!skip) { - p224_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 0 /* mixed */, - tmp[0], tmp[1], tmp[2]); - } else { - OPENSSL_memcpy(nq, tmp, 3 * sizeof(p224_felem)); - skip = 0; - } - } - } - - // Reduce the output to its unique minimal representation. - p224_felem_to_generic(&r->X, nq[0]); - p224_felem_to_generic(&r->Y, nq[1]); - p224_felem_to_generic(&r->Z, nq[2]); -} - -static void ec_GFp_nistp224_point_mul_base(const EC_GROUP *group, - EC_JACOBIAN *r, - const EC_SCALAR *scalar) { - // Set nq to the point at infinity. - p224_felem nq[3], tmp[3]; - OPENSSL_memset(nq, 0, 3 * sizeof(p224_felem)); - - int skip = 1; // Save two point operations in the first round. - for (size_t i = 27; i < 28; i--) { - // double - if (!skip) { - p224_point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]); - } - - // First, look 28 bits upwards. - crypto_word_t bits = p224_get_bit(scalar, i + 196) << 3; - bits |= p224_get_bit(scalar, i + 140) << 2; - bits |= p224_get_bit(scalar, i + 84) << 1; - bits |= p224_get_bit(scalar, i + 28); - // Select the point to add, in constant time. - p224_select_point(bits, 16, g_p224_pre_comp[1], tmp); - - if (!skip) { - p224_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */, - tmp[0], tmp[1], tmp[2]); - } else { - OPENSSL_memcpy(nq, tmp, 3 * sizeof(p224_felem)); - skip = 0; - } - - // Second, look at the current position/ - bits = p224_get_bit(scalar, i + 168) << 3; - bits |= p224_get_bit(scalar, i + 112) << 2; - bits |= p224_get_bit(scalar, i + 56) << 1; - bits |= p224_get_bit(scalar, i); - // Select the point to add, in constant time. - p224_select_point(bits, 16, g_p224_pre_comp[0], tmp); - p224_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */, - tmp[0], tmp[1], tmp[2]); - } - - // Reduce the output to its unique minimal representation. - p224_felem_to_generic(&r->X, nq[0]); - p224_felem_to_generic(&r->Y, nq[1]); - p224_felem_to_generic(&r->Z, nq[2]); -} - -static void ec_GFp_nistp224_point_mul_public(const EC_GROUP *group, - EC_JACOBIAN *r, - const EC_SCALAR *g_scalar, - const EC_JACOBIAN *p, - const EC_SCALAR *p_scalar) { - // TODO(davidben): If P-224 ECDSA verify performance ever matters, using - // |ec_compute_wNAF| for |p_scalar| would likely be an easy improvement. - p224_felem p_pre_comp[17][3]; - ec_GFp_nistp224_make_precomp(p_pre_comp, p); - - // Set nq to the point at infinity. - p224_felem nq[3], tmp[3]; - OPENSSL_memset(nq, 0, 3 * sizeof(p224_felem)); - - // Loop over both scalars msb-to-lsb, interleaving additions of multiples of - // the generator (two in each of the last 28 rounds) and additions of p (every - // 5th round). - int skip = 1; // Save two point operations in the first round. - for (size_t i = 220; i < 221; i--) { - if (!skip) { - p224_point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]); - } - - // Add multiples of the generator. - if (i <= 27) { - // First, look 28 bits upwards. - crypto_word_t bits = p224_get_bit(g_scalar, i + 196) << 3; - bits |= p224_get_bit(g_scalar, i + 140) << 2; - bits |= p224_get_bit(g_scalar, i + 84) << 1; - bits |= p224_get_bit(g_scalar, i + 28); - - size_t index = (size_t)bits; - p224_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */, - g_p224_pre_comp[1][index][0], g_p224_pre_comp[1][index][1], - g_p224_pre_comp[1][index][2]); - assert(!skip); - - // Second, look at the current position. - bits = p224_get_bit(g_scalar, i + 168) << 3; - bits |= p224_get_bit(g_scalar, i + 112) << 2; - bits |= p224_get_bit(g_scalar, i + 56) << 1; - bits |= p224_get_bit(g_scalar, i); - index = (size_t)bits; - p224_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */, - g_p224_pre_comp[0][index][0], g_p224_pre_comp[0][index][1], - g_p224_pre_comp[0][index][2]); - } - - // Incorporate |p_scalar| every 5 doublings. - if (i % 5 == 0) { - crypto_word_t bits = p224_get_bit(p_scalar, i + 4) << 5; - bits |= p224_get_bit(p_scalar, i + 3) << 4; - bits |= p224_get_bit(p_scalar, i + 2) << 3; - bits |= p224_get_bit(p_scalar, i + 1) << 2; - bits |= p224_get_bit(p_scalar, i) << 1; - bits |= p224_get_bit(p_scalar, i - 1); - crypto_word_t sign, digit; - ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits); - - // Select the point to add or subtract. - OPENSSL_memcpy(tmp, p_pre_comp[digit], 3 * sizeof(p224_felem)); - if (sign) { - p224_felem_neg(tmp[1], tmp[1]); // (X, -Y, Z) is the negative point - } - - if (!skip) { - p224_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 0 /* mixed */, - tmp[0], tmp[1], tmp[2]); - } else { - OPENSSL_memcpy(nq, tmp, 3 * sizeof(p224_felem)); - skip = 0; - } - } - } - - // Reduce the output to its unique minimal representation. - p224_felem_to_generic(&r->X, nq[0]); - p224_felem_to_generic(&r->Y, nq[1]); - p224_felem_to_generic(&r->Z, nq[2]); -} - -static void ec_GFp_nistp224_felem_mul(const EC_GROUP *group, EC_FELEM *r, - const EC_FELEM *a, const EC_FELEM *b) { - p224_felem felem1, felem2; - p224_widefelem wide; - p224_generic_to_felem(felem1, a); - p224_generic_to_felem(felem2, b); - p224_felem_mul(wide, felem1, felem2); - p224_felem_reduce(felem1, wide); - p224_felem_to_generic(r, felem1); -} - -static void ec_GFp_nistp224_felem_sqr(const EC_GROUP *group, EC_FELEM *r, - const EC_FELEM *a) { - p224_felem felem; - p224_generic_to_felem(felem, a); - p224_widefelem wide; - p224_felem_square(wide, felem); - p224_felem_reduce(felem, wide); - p224_felem_to_generic(r, felem); -} - -DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistp224_method) { - out->point_get_affine_coordinates = - ec_GFp_nistp224_point_get_affine_coordinates; - out->add = ec_GFp_nistp224_add; - out->dbl = ec_GFp_nistp224_dbl; - out->mul = ec_GFp_nistp224_point_mul; - out->mul_base = ec_GFp_nistp224_point_mul_base; - out->mul_public = ec_GFp_nistp224_point_mul_public; - out->felem_mul = ec_GFp_nistp224_felem_mul; - out->felem_sqr = ec_GFp_nistp224_felem_sqr; - out->felem_to_bytes = ec_GFp_simple_felem_to_bytes; - out->felem_from_bytes = ec_GFp_simple_felem_from_bytes; - out->scalar_inv0_montgomery = ec_simple_scalar_inv0_montgomery; - out->scalar_to_montgomery_inv_vartime = - ec_simple_scalar_to_montgomery_inv_vartime; - out->cmp_x_coordinate = ec_GFp_simple_cmp_x_coordinate; -} - -#endif // BORINGSSL_HAS_UINT128 && !SMALL diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256-nistz-table.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256-nistz-table.h index bfe977fa..89739db4 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256-nistz-table.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256-nistz-table.h @@ -1,12 +1,17 @@ -/* - * Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. - * Copyright (c) 2015, Intel Inc. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright (c) 2015, Intel Inc. +// +// 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. // This is the precomputed constant time access table for the code in // p256-nistz.c, for the default generator. The table consists of 37 diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256-nistz.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256-nistz.cc.inc index 8d6975c0..b383cd4a 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256-nistz.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256-nistz.cc.inc @@ -1,20 +1,25 @@ -/* - * Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. - * Copyright (c) 2014, Intel Corporation. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - * - * Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) - * (1) Intel Corporation, Israel Development Center, Haifa, Israel - * (2) University of Haifa, Israel - * - * Reference: - * S.Gueron and V.Krasnov, "Fast Prime Field Elliptic Curve Cryptography with - * 256 Bit Primes" - */ +// Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright (c) 2014, Intel Corporation. All Rights Reserved. +// +// 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. +// +// Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) +// (1) Intel Corporation, Israel Development Center, Haifa, Israel +// (2) University of Haifa, Israel +// +// Reference: +// S.Gueron and V.Krasnov, "Fast Prime Field Elliptic Curve Cryptography with +// 256 Bit Primes" #include @@ -32,6 +37,9 @@ #include "internal.h" #include "p256-nistz.h" + +using namespace bssl; + #if !defined(OPENSSL_NO_ASM) && \ (defined(OPENSSL_X86_64) || defined(OPENSSL_AARCH64)) && \ !defined(OPENSSL_SMALL) @@ -49,7 +57,7 @@ static const BN_ULONG ONE_MONT[P256_LIMBS] = { // Precomputed tables for the default generator #include "p256-nistz-table.h" -// Recode window to a signed digit, see |ec_GFp_nistp_recode_scalar_bits| in +// Recode window to a signed digit, see `ec_GFp_nistp_recode_scalar_bits` in // util.c for details static crypto_word_t booth_recode_w5(crypto_word_t in) { crypto_word_t s, d; @@ -73,8 +81,8 @@ static crypto_word_t booth_recode_w7(crypto_word_t in) { return (d << 1) + (s & 1); } -// copy_conditional copies |src| to |dst| if |move| is one and leaves it as-is -// if |move| is zero. +// copy_conditional copies `src` to `dst` if `move` is one and leaves it as-is +// if `move` is zero. // // WARNING: this breaks the usual convention of constant-time functions // returning masks. @@ -207,7 +215,7 @@ static void ecp_nistz256_point_add_affine(P256_POINT *r, const P256_POINT *a, } #endif // OPENSSL_X86_64 -// ecp_nistz256_from_mont sets |res| to |in|, converted from Montgomery domain +// ecp_nistz256_from_mont sets `res` to `in`, converted from Montgomery domain // by multiplying with 1. static void ecp_nistz256_from_mont(BN_ULONG res[P256_LIMBS], const BN_ULONG in[P256_LIMBS]) { @@ -215,8 +223,8 @@ static void ecp_nistz256_from_mont(BN_ULONG res[P256_LIMBS], ecp_nistz256_mul_mont(res, in, ONE); } -// ecp_nistz256_mod_inverse_sqr_mont sets |r| to (|in| * 2^-256)^-2 * 2^256 mod -// p. That is, |r| is the modular inverse square of |in| for input and output in +// ecp_nistz256_mod_inverse_sqr_mont sets `r` to (`in` * 2^-256)^-2 * 2^256 mod +// p. That is, `r` is the modular inverse square of `in` for input and output in // the Montgomery domain. static void ecp_nistz256_mod_inverse_sqr_mont(BN_ULONG r[P256_LIMBS], const BN_ULONG in[P256_LIMBS]) { @@ -224,17 +232,17 @@ static void ecp_nistz256_mod_inverse_sqr_mont(BN_ULONG r[P256_LIMBS], // https://briansmith.org/ecc-inversion-addition-chains-01#p256_field_inversion BN_ULONG x2[P256_LIMBS], x3[P256_LIMBS], x6[P256_LIMBS], x12[P256_LIMBS], x15[P256_LIMBS], x30[P256_LIMBS], x32[P256_LIMBS]; - ecp_nistz256_sqr_mont(x2, in); // 2^2 - 2^1 - ecp_nistz256_mul_mont(x2, x2, in); // 2^2 - 2^0 + ecp_nistz256_sqr_mont(x2, in); // 2² - 2¹ + ecp_nistz256_mul_mont(x2, x2, in); // 2² - 2⁰ - ecp_nistz256_sqr_mont(x3, x2); // 2^3 - 2^1 - ecp_nistz256_mul_mont(x3, x3, in); // 2^3 - 2^0 + ecp_nistz256_sqr_mont(x3, x2); // 2³ - 2¹ + ecp_nistz256_mul_mont(x3, x3, in); // 2³ - 2⁰ ecp_nistz256_sqr_mont(x6, x3); for (int i = 1; i < 3; i++) { ecp_nistz256_sqr_mont(x6, x6); - } // 2^6 - 2^3 - ecp_nistz256_mul_mont(x6, x6, x3); // 2^6 - 2^0 + } // 2⁶ - 2³ + ecp_nistz256_mul_mont(x6, x6, x3); // 2⁶ - 2⁰ ecp_nistz256_sqr_mont(x12, x6); for (int i = 1; i < 6; i++) { @@ -288,15 +296,15 @@ static void ecp_nistz256_mod_inverse_sqr_mont(BN_ULONG r[P256_LIMBS], static void ecp_nistz256_windowed_mul(const EC_GROUP *group, P256_POINT *r, const EC_JACOBIAN *p, const EC_SCALAR *p_scalar) { - assert(p != NULL); - assert(p_scalar != NULL); + assert(p != nullptr); + assert(p_scalar != nullptr); assert(group->field.N.width == P256_LIMBS); static const size_t kWindowSize = 5; static const crypto_word_t kMask = (1 << (5 /* kWindowSize */ + 1)) - 1; - // A |P256_POINT| is (3 * 32) = 96 bytes, and the 64-byte alignment should - // add no more than 63 bytes of overhead. Thus, |table| should require + // A `P256_POINT` is (3 * 32) = 96 bytes, and the 64-byte alignment should + // add no more than 63 bytes of overhead. Thus, `table` should require // ~1599 ((96 * 16) + 63) bytes of stack space. alignas(64) P256_POINT table[16]; uint8_t p_str[33]; @@ -426,9 +434,9 @@ static void ecp_nistz256_point_mul_base(const EC_GROUP *group, EC_JACOBIAN *r, ecp_nistz256_neg(p.Z, t.Y); copy_conditional(t.Y, p.Z, wvalue & 1); - // Convert |t| from affine to Jacobian coordinates. We set Z to zero if |t| - // is infinity and |ONE_MONT| otherwise. |t| was computed from the table, so - // it is infinity iff |wvalue >> 1| is zero. + // Convert `t` from affine to Jacobian coordinates. We set Z to zero if `t` + // is infinity and `ONE_MONT` otherwise. `t` was computed from the table, so + // it is infinity iff `wvalue >> 1` is zero. OPENSSL_memcpy(p.X, t.X, sizeof(p.X)); OPENSSL_memcpy(p.Y, t.Y, sizeof(p.Y)); OPENSSL_memset(p.Z, 0, sizeof(p.Z)); @@ -443,7 +451,7 @@ static void ecp_nistz256_point_mul_base(const EC_GROUP *group, EC_JACOBIAN *r, ecp_nistz256_neg(neg_Y, t.Y); copy_conditional(t.Y, neg_Y, wvalue & 1); - // Note |ecp_nistz256_point_add_affine| does not work if |p| and |t| are the + // Note `ecp_nistz256_point_add_affine` does not work if `p` and `t` are the // same non-infinity point. ecp_nistz256_point_add_affine(&p, &p, &t); } @@ -459,7 +467,7 @@ static void ecp_nistz256_points_mul_public(const EC_GROUP *group, const EC_SCALAR *g_scalar, const EC_JACOBIAN *p_, const EC_SCALAR *p_scalar) { - assert(p_ != NULL && p_scalar != NULL && g_scalar != NULL); + assert(p_ != nullptr && p_scalar != nullptr && g_scalar != nullptr); alignas(32) P256_POINT p; uint8_t p_str[33]; @@ -470,9 +478,9 @@ static void ecp_nistz256_points_mul_public(const EC_GROUP *group, size_t index = 0; size_t wvalue = calc_first_wvalue(&index, p_str); - // Convert |p| from affine to Jacobian coordinates. We set Z to zero if |p| - // is infinity and |ONE_MONT| otherwise. |p| was computed from the table, so - // it is infinity iff |wvalue >> 1| is zero. + // Convert `p` from affine to Jacobian coordinates. We set Z to zero if `p` + // is infinity and `ONE_MONT` otherwise. `p` was computed from the table, so + // it is infinity iff `wvalue >> 1` is zero. if ((wvalue >> 1) != 0) { OPENSSL_memcpy(p.X, &ecp_nistz256_precomputed[0][(wvalue >> 1) - 1].X, sizeof(p.X)); @@ -502,9 +510,9 @@ static void ecp_nistz256_points_mul_public(const EC_GROUP *group, ecp_nistz256_neg(t.Y, t.Y); } - // Note |ecp_nistz256_point_add_affine| does not work if |p| and |t| are + // Note `ecp_nistz256_point_add_affine` does not work if `p` and `t` are // the same non-infinity point, so it is important that we compute the - // |g_scalar| term before the |p_scalar| term. + // `g_scalar` term before the `p_scalar` term. ecp_nistz256_point_add_affine(&p, &p, &t); } @@ -531,11 +539,11 @@ static int ecp_nistz256_get_affine(const EC_GROUP *group, assert(group->field.N.width == P256_LIMBS); ecp_nistz256_mod_inverse_sqr_mont(z_inv2, point->Z.words); - if (x != NULL) { + if (x != nullptr) { ecp_nistz256_mul_mont(x->words, z_inv2, point->X.words); } - if (y != NULL) { + if (y != nullptr) { ecp_nistz256_sqr_mont(z_inv2, z_inv2); // z^-4 ecp_nistz256_mul_mont(y->words, point->Y.words, point->Z.words); // y * z ecp_nistz256_mul_mont(y->words, y->words, z_inv2); // y * z^-3 @@ -573,7 +581,7 @@ static void ecp_nistz256_dbl(const EC_GROUP *group, EC_JACOBIAN *r, static void ecp_nistz256_inv0_mod_ord(const EC_GROUP *group, EC_SCALAR *out, const EC_SCALAR *in) { - // table[i] stores a power of |in| corresponding to the matching enum value. + // table[i] stores a power of `in` corresponding to the matching enum value. enum { // The following indices specify the power in binary. i_1 = 0, @@ -634,7 +642,7 @@ static void ecp_nistz256_inv0_mod_ord(const EC_GROUP *group, EC_SCALAR *out, ecp_nistz256_ord_sqr_mont(table[i_x32], table[i_x16], 16); ecp_nistz256_ord_mul_mont(table[i_x32], table[i_x32], table[i_x16]); - // Compute |in| raised to the order-2. + // Compute `in` raised to the order-2. ecp_nistz256_ord_sqr_mont(out->words, table[i_x32], 64); ecp_nistz256_ord_mul_mont(out->words, out->words, table[i_x32]); static const struct { @@ -646,9 +654,9 @@ static void ecp_nistz256_inv0_mod_ord(const EC_GROUP *group, EC_SCALAR *out, {4, i_111}, {5, i_111}, {5, i_101}, {3, i_11}, {10, i_101111}, {2, i_11}, {5, i_11}, {5, i_11}, {3, i_1}, {7, i_10101}, {6, i_1111}}; - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kChain); i++) { - ecp_nistz256_ord_sqr_mont(out->words, out->words, kChain[i].p); - ecp_nistz256_ord_mul_mont(out->words, out->words, table[kChain[i].i]); + for (const auto &step : kChain) { + ecp_nistz256_ord_sqr_mont(out->words, out->words, step.p); + ecp_nistz256_ord_mul_mont(out->words, out->words, table[step.i]); } } @@ -682,8 +690,8 @@ static int ecp_nistz256_cmp_x_coordinate(const EC_GROUP *group, assert(group->order.N.width == P256_LIMBS); assert(group->field.N.width == P256_LIMBS); - // We wish to compare X/Z^2 with r. This is equivalent to comparing X with - // r*Z^2. Note that X and Z are represented in Montgomery form, while r is + // We wish to compare X/Z² with r. This is equivalent to comparing X with + // r⋅Z². Note that X and Z are represented in Montgomery form, while r is // not. BN_ULONG r_Z2[P256_LIMBS], Z2_mont[P256_LIMBS], X[P256_LIMBS]; ecp_nistz256_mul_mont(Z2_mont, p->Z.words, p->Z.words); @@ -696,11 +704,11 @@ static int ecp_nistz256_cmp_x_coordinate(const EC_GROUP *group, // During signing the x coefficient is reduced modulo the group order. // Therefore there is a small possibility, less than 1/2^128, that group_order - // < p.x < P. in that case we need not only to compare against |r| but also to + // < p.x < P. in that case we need not only to compare against `r` but also to // compare against r+group_order. BN_ULONG carry = bn_add_words(r_Z2, r->words, group->order.N.d, P256_LIMBS); if (carry == 0 && bn_less_than_words(r_Z2, group->field.N.d, P256_LIMBS)) { - // r + group_order < p, so compare (r + group_order) * Z^2 against X. + // r + group_order < p, so compare (r + group_order) ⋅ Z² against X. ecp_nistz256_mul_mont(r_Z2, r_Z2, Z2_mont); if (OPENSSL_memcmp(r_Z2, X, sizeof(r_Z2)) == 0) { return 1; @@ -710,6 +718,8 @@ static int ecp_nistz256_cmp_x_coordinate(const EC_GROUP *group, return 0; } +BSSL_NAMESPACE_BEGIN + DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistz256_method) { out->point_get_affine_coordinates = ecp_nistz256_get_affine; out->add = ecp_nistz256_add; @@ -717,20 +727,14 @@ DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistz256_method) { out->mul = ecp_nistz256_point_mul; out->mul_base = ecp_nistz256_point_mul_base; out->mul_public = ecp_nistz256_points_mul_public; - out->felem_mul = ec_GFp_mont_felem_mul; - out->felem_sqr = ec_GFp_mont_felem_sqr; - out->felem_to_bytes = ec_GFp_mont_felem_to_bytes; - out->felem_from_bytes = ec_GFp_mont_felem_from_bytes; - out->felem_reduce = ec_GFp_mont_felem_reduce; - // TODO(davidben): This should use the specialized field arithmetic - // implementation, rather than the generic one. - out->felem_exp = ec_GFp_mont_felem_exp; out->scalar_inv0_montgomery = ecp_nistz256_inv0_mod_ord; out->scalar_to_montgomery_inv_vartime = ecp_nistz256_scalar_to_montgomery_inv_vartime; out->cmp_x_coordinate = ecp_nistz256_cmp_x_coordinate; } +BSSL_NAMESPACE_END + #endif /* !defined(OPENSSL_NO_ASM) && \ (defined(OPENSSL_X86_64) || defined(OPENSSL_AARCH64)) && \ !defined(OPENSSL_SMALL) */ diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256-nistz.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256-nistz.h index 1c542b0b..ab90df48 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256-nistz.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256-nistz.h @@ -1,23 +1,28 @@ -/* - * Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. - * Copyright (c) 2014, Intel Corporation. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - * - * Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) - * (1) Intel Corporation, Israel Development Center, Haifa, Israel - * (2) University of Haifa, Israel - * - * Reference: - * S.Gueron and V.Krasnov, "Fast Prime Field Elliptic Curve Cryptography with - * 256 Bit Primes" - */ +// Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright (c) 2014, Intel Corporation. All Rights Reserved. +// +// 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. +// +// Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) +// (1) Intel Corporation, Israel Development Center, Haifa, Israel +// (2) University of Haifa, Israel +// +// Reference: +// S.Gueron and V.Krasnov, "Fast Prime Field Elliptic Curve Cryptography with +// 256 Bit Primes" -#ifndef OPENSSL_HEADER_EC_P256_X86_64_H -#define OPENSSL_HEADER_EC_P256_X86_64_H +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_EC_P256_NISTZ_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_EC_P256_NISTZ_H #include @@ -37,17 +42,17 @@ extern "C" { // P-256 field operations. // // An element mod P in P-256 is represented as a little-endian array of -// |P256_LIMBS| |BN_ULONG|s, spanning the full range of values. +// `P256_LIMBS` `BN_ULONG`s, spanning the full range of values. // // The following functions take fully-reduced inputs mod P and give // fully-reduced outputs. They may be used in-place. #define P256_LIMBS (256 / BN_BITS2) -// ecp_nistz256_neg sets |res| to -|a| mod P. +// ecp_nistz256_neg sets `res` to -`a` mod P. 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. +// 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], @@ -61,7 +66,7 @@ void ecp_nistz256_mul_mont(BN_ULONG res[P256_LIMBS], const BN_ULONG b[P256_LIMBS]); #endif -// ecp_nistz256_sqr_mont sets |res| to |a| * |a| * 2^-256 mod P. +// 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]); @@ -78,8 +83,8 @@ void ecp_nistz256_sqr_mont(BN_ULONG res[P256_LIMBS], // The following functions compute modulo N, where N is the order of P-256. They // take fully-reduced inputs and give fully-reduced outputs. -// 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. +// 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], @@ -93,9 +98,9 @@ void ecp_nistz256_ord_mul_mont(BN_ULONG res[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. +// 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); @@ -132,8 +137,8 @@ typedef struct { BN_ULONG Y[P256_LIMBS]; } P256_POINT_AFFINE; -// ecp_nistz256_select_w5 sets |*val| to |in_t[index-1]| if 1 <= |index| <= 16 -// and all zeros (the point at infinity) if |index| is 0. This is done in +// ecp_nistz256_select_w5 sets `*val` to `in_t[index-1]` if 1 <= `index` <= 16 +// 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], @@ -145,8 +150,8 @@ 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 +// 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, @@ -158,7 +163,7 @@ 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. +// 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); @@ -166,7 +171,7 @@ void ecp_nistz256_point_double_adx(P256_POINT *r, const P256_POINT *a); 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|. +// 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); @@ -177,8 +182,8 @@ 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 +// 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, @@ -196,7 +201,7 @@ void ecp_nistz256_point_add_affine(P256_POINT *r, const P256_POINT *a, #if defined(__cplusplus) -} // extern C++ +} // extern C #endif -#endif // OPENSSL_HEADER_EC_P256_X86_64_H +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_EC_P256_NISTZ_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256.cc.inc index 02d474d3..a94fe6f7 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2020 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2020 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. // An implementation of the NIST P-256 elliptic curve point multiplication. // 256-bit Montgomery form for 64 and 32-bit. Field operations are generated by @@ -26,19 +26,18 @@ #include #include +#include + #include "../../internal.h" #include "../delocate.h" #include "./internal.h" -#if defined(BORINGSSL_HAS_UINT128) -#include "../../../third_party/fiat/p256_64.h" -#elif defined(OPENSSL_64_BIT) -#include "../../../third_party/fiat/p256_64_msvc.h" -#else -#include "../../../third_party/fiat/p256_32.h" -#endif +#include "../../../third_party/fiat/p256_field.c.inc" +#include "../../../third_party/fiat/p256_point.br.c.inc" +using namespace bssl; + // utility functions, handwritten #if defined(OPENSSL_64_BIT) @@ -56,13 +55,6 @@ static const fiat_p256_felem fiat_p256_one = { #endif // 64BIT -static fiat_p256_limb_t fiat_p256_nz( - const fiat_p256_limb_t in1[FIAT_P256_NLIMBS]) { - fiat_p256_limb_t ret; - fiat_p256_nonzero(&ret, in1); - return ret; -} - static void fiat_p256_copy(fiat_p256_limb_t out[FIAT_P256_NLIMBS], const fiat_p256_limb_t in1[FIAT_P256_NLIMBS]) { for (size_t i = 0; i < FIAT_P256_NLIMBS; i++) { @@ -79,9 +71,9 @@ static void fiat_p256_cmovznz(fiat_p256_limb_t out[FIAT_P256_NLIMBS], static void fiat_p256_from_words(fiat_p256_felem out, const BN_ULONG in[32 / sizeof(BN_ULONG)]) { - // Typically, |BN_ULONG| and |fiat_p256_limb_t| will be the same type, but on - // 64-bit platforms without |uint128_t|, they are different. However, on - // little-endian systems, |uint64_t[4]| and |uint32_t[8]| have the same + // Typically, `BN_ULONG` and `fiat_p256_limb_t` will be the same type, but on + // 64-bit platforms without `uint128_t`, they are different. However, on + // little-endian systems, `uint64_t[4]` and `uint32_t[8]` have the same // layout. OPENSSL_memcpy(out, in, 32); } @@ -91,11 +83,11 @@ static void fiat_p256_from_generic(fiat_p256_felem out, const EC_FELEM *in) { } static void fiat_p256_to_generic(EC_FELEM *out, const fiat_p256_felem in) { - // See |fiat_p256_from_words|. + // See `fiat_p256_from_words`. OPENSSL_memcpy(out->words, in, 32); } -// fiat_p256_inv_square calculates |out| = |in|^{-2} +// fiat_p256_inv_square calculates `out` = `in`^{-2} // // Based on Fermat's Little Theorem: // a^p = a (mod p) @@ -106,17 +98,17 @@ static void fiat_p256_inv_square(fiat_p256_felem out, // This implements the addition chain described in // https://briansmith.org/ecc-inversion-addition-chains-01#p256_field_inversion fiat_p256_felem x2, x3, x6, x12, x15, x30, x32; - fiat_p256_square(x2, in); // 2^2 - 2^1 - fiat_p256_mul(x2, x2, in); // 2^2 - 2^0 + fiat_p256_square(x2, in); // 2² - 2¹ + fiat_p256_mul(x2, x2, in); // 2² - 2⁰ - fiat_p256_square(x3, x2); // 2^3 - 2^1 - fiat_p256_mul(x3, x3, in); // 2^3 - 2^0 + fiat_p256_square(x3, x2); // 2³ - 2¹ + fiat_p256_mul(x3, x3, in); // 2³ - 2⁰ fiat_p256_square(x6, x3); for (int i = 1; i < 3; i++) { fiat_p256_square(x6, x6); - } // 2^6 - 2^3 - fiat_p256_mul(x6, x6, x3); // 2^6 - 2^0 + } // 2⁶ - 2³ + fiat_p256_mul(x6, x6, x3); // 2⁶ - 2⁰ fiat_p256_square(x12, x6); for (int i = 1; i < 6; i++) { @@ -172,202 +164,48 @@ static void fiat_p256_inv_square(fiat_p256_felem out, // Building on top of the field operations we have the operations on the // elliptic curve group itself. Points on the curve are represented in Jacobian // coordinates. -// -// Both operations were transcribed to Coq and proven to correspond to naive -// implementations using Affine coordinates, for all suitable fields. In the -// Coq proofs, issues of constant-time execution and memory layout (aliasing) -// conventions were not considered. Specification of affine coordinates: -// -// As a sanity check, a proof that these points form a commutative group: -// -// fiat_p256_point_double calculates 2*(x_in, y_in, z_in) -// -// The method is taken from: -// http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b -// -// Coq transcription and correctness proof: -// -// -// -// Outputs can equal corresponding inputs, i.e., x_out == x_in is allowed. -// while x_out == y_in is not (maybe this works, but it's not tested). static void fiat_p256_point_double(fiat_p256_felem x_out, fiat_p256_felem y_out, fiat_p256_felem z_out, const fiat_p256_felem x_in, const fiat_p256_felem y_in, const fiat_p256_felem z_in) { - fiat_p256_felem delta, gamma, beta, ftmp, ftmp2, tmptmp, alpha, fourbeta; - // delta = z^2 - fiat_p256_square(delta, z_in); - // gamma = y^2 - fiat_p256_square(gamma, y_in); - // beta = x*gamma - fiat_p256_mul(beta, x_in, gamma); - - // alpha = 3*(x-delta)*(x+delta) - fiat_p256_sub(ftmp, x_in, delta); - fiat_p256_add(ftmp2, x_in, delta); - - fiat_p256_add(tmptmp, ftmp2, ftmp2); - fiat_p256_add(ftmp2, ftmp2, tmptmp); - fiat_p256_mul(alpha, ftmp, ftmp2); - - // x' = alpha^2 - 8*beta - fiat_p256_square(x_out, alpha); - fiat_p256_add(fourbeta, beta, beta); - fiat_p256_add(fourbeta, fourbeta, fourbeta); - fiat_p256_add(tmptmp, fourbeta, fourbeta); - fiat_p256_sub(x_out, x_out, tmptmp); - - // z' = (y + z)^2 - gamma - delta - fiat_p256_add(delta, gamma, delta); - fiat_p256_add(ftmp, y_in, z_in); - fiat_p256_square(z_out, ftmp); - fiat_p256_sub(z_out, z_out, delta); - - // y' = alpha*(4*beta - x') - 8*gamma^2 - fiat_p256_sub(y_out, fourbeta, x_out); - fiat_p256_add(gamma, gamma, gamma); - fiat_p256_square(gamma, gamma); - fiat_p256_mul(y_out, alpha, y_out); - fiat_p256_add(gamma, gamma, gamma); - fiat_p256_sub(y_out, y_out, gamma); + uint8_t out[3*32], in[3*32]; + static_assert(sizeof(fiat_p256_felem) == 32); + OPENSSL_memcpy(&in[0], x_in, 32); + OPENSSL_memcpy(&in[32], y_in, 32); + OPENSSL_memcpy(&in[64], z_in, 32); + p256_point_double((br_word_t)out, (br_word_t)in); + OPENSSL_memcpy(x_out, &out[0], 32); + OPENSSL_memcpy(y_out, &out[32], 32); + OPENSSL_memcpy(z_out, &out[64], 32); } -// fiat_p256_point_add calculates (x1, y1, z1) + (x2, y2, z2) -// -// The method is taken from: -// http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl, -// adapted for mixed addition (z2 = 1, or z2 = 0 for the point at infinity). -// -// Coq transcription and correctness proof: -// -// -// -// This function includes a branch for checking whether the two input points -// are equal, (while not equal to the point at infinity). This case never -// happens during single point multiplication, so there is no timing leak for -// ECDH or ECDSA signing. static void fiat_p256_point_add(fiat_p256_felem x3, fiat_p256_felem y3, fiat_p256_felem z3, const fiat_p256_felem x1, const fiat_p256_felem y1, - const fiat_p256_felem z1, const int mixed, + const fiat_p256_felem z1, const fiat_p256_felem x2, const fiat_p256_felem y2, const fiat_p256_felem z2) { - fiat_p256_felem x_out, y_out, z_out; - fiat_p256_limb_t z1nz = fiat_p256_nz(z1); - fiat_p256_limb_t z2nz = fiat_p256_nz(z2); - - // z1z1 = z1z1 = z1**2 - fiat_p256_felem z1z1; - fiat_p256_square(z1z1, z1); - - fiat_p256_felem u1, s1, two_z1z2; - if (!mixed) { - // z2z2 = z2**2 - fiat_p256_felem z2z2; - fiat_p256_square(z2z2, z2); - - // u1 = x1*z2z2 - fiat_p256_mul(u1, x1, z2z2); - - // two_z1z2 = (z1 + z2)**2 - (z1z1 + z2z2) = 2z1z2 - fiat_p256_add(two_z1z2, z1, z2); - fiat_p256_square(two_z1z2, two_z1z2); - fiat_p256_sub(two_z1z2, two_z1z2, z1z1); - fiat_p256_sub(two_z1z2, two_z1z2, z2z2); - - // s1 = y1 * z2**3 - fiat_p256_mul(s1, z2, z2z2); - fiat_p256_mul(s1, s1, y1); - } else { - // We'll assume z2 = 1 (special case z2 = 0 is handled later). - - // u1 = x1*z2z2 - fiat_p256_copy(u1, x1); - // two_z1z2 = 2z1z2 - fiat_p256_add(two_z1z2, z1, z1); - // s1 = y1 * z2**3 - fiat_p256_copy(s1, y1); - } - - // u2 = x2*z1z1 - fiat_p256_felem u2; - fiat_p256_mul(u2, x2, z1z1); - - // h = u2 - u1 - fiat_p256_felem h; - fiat_p256_sub(h, u2, u1); - - fiat_p256_limb_t xneq = fiat_p256_nz(h); - - // z_out = two_z1z2 * h - fiat_p256_mul(z_out, h, two_z1z2); - - // z1z1z1 = z1 * z1z1 - fiat_p256_felem z1z1z1; - fiat_p256_mul(z1z1z1, z1, z1z1); - - // s2 = y2 * z1**3 - fiat_p256_felem s2; - fiat_p256_mul(s2, y2, z1z1z1); - - // r = (s2 - s1)*2 - fiat_p256_felem r; - fiat_p256_sub(r, s2, s1); - fiat_p256_add(r, r, r); - - fiat_p256_limb_t yneq = fiat_p256_nz(r); - - fiat_p256_limb_t is_nontrivial_double = constant_time_is_zero_w(xneq | yneq) & - ~constant_time_is_zero_w(z1nz) & - ~constant_time_is_zero_w(z2nz); - if (constant_time_declassify_w(is_nontrivial_double)) { - fiat_p256_point_double(x3, y3, z3, x1, y1, z1); - return; - } - - // I = (2h)**2 - fiat_p256_felem i; - fiat_p256_add(i, h, h); - fiat_p256_square(i, i); - - // J = h * I - fiat_p256_felem j; - fiat_p256_mul(j, h, i); - - // V = U1 * I - fiat_p256_felem v; - fiat_p256_mul(v, u1, i); - - // x_out = r**2 - J - 2V - fiat_p256_square(x_out, r); - fiat_p256_sub(x_out, x_out, j); - fiat_p256_sub(x_out, x_out, v); - fiat_p256_sub(x_out, x_out, v); - - // y_out = r(V-x_out) - 2 * s1 * J - fiat_p256_sub(y_out, v, x_out); - fiat_p256_mul(y_out, y_out, r); - fiat_p256_felem s1j; - fiat_p256_mul(s1j, s1, j); - fiat_p256_sub(y_out, y_out, s1j); - fiat_p256_sub(y_out, y_out, s1j); - - fiat_p256_cmovznz(x_out, z1nz, x2, x_out); - fiat_p256_cmovznz(x3, z2nz, x1, x_out); - fiat_p256_cmovznz(y_out, z1nz, y2, y_out); - fiat_p256_cmovznz(y3, z2nz, y1, y_out); - fiat_p256_cmovznz(z_out, z1nz, z2, z_out); - fiat_p256_cmovznz(z3, z2nz, z1, z_out); + uint8_t out[3 * 32], in1[3 * 32], in2[3 * 32]; + static_assert(sizeof(fiat_p256_felem) == 32); + OPENSSL_memcpy(&in1[0], x1, 32); + OPENSSL_memcpy(&in1[32], y1, 32); + OPENSSL_memcpy(&in1[64], z1, 32); + OPENSSL_memcpy(&in2[0], x2, 32); + OPENSSL_memcpy(&in2[32], y2, 32); + OPENSSL_memcpy(&in2[64], z2, 32); + p256_point_add_vartime_if_doubling((br_word_t)out, (br_word_t)in1, + (br_word_t)in2); + OPENSSL_memcpy(x3, &out[0], 32); + OPENSSL_memcpy(y3, &out[32], 32); + OPENSSL_memcpy(z3, &out[64], 32); } - #include "./p256_table.h" -// fiat_p256_select_point_affine selects the |idx-1|th point from a -// precomputation table and copies it to out. If |idx| is zero, the output is +// fiat_p256_select_point_affine selects the `idx-1`th point from a +// precomputation table and copies it to out. If `idx` is zero, the output is // the point at infinity. static void fiat_p256_select_point_affine( const fiat_p256_limb_t idx, size_t size, @@ -381,7 +219,7 @@ static void fiat_p256_select_point_affine( fiat_p256_cmovznz(out[2], idx, out[2], fiat_p256_one); } -// fiat_p256_select_point selects the |idx|th point from a precomputation table +// fiat_p256_select_point selects the `idx`th point from a precomputation table // and copies it to out. static void fiat_p256_select_point(const fiat_p256_limb_t idx, size_t size, const fiat_p256_felem pre_comp[/*size*/][3], @@ -395,7 +233,7 @@ static void fiat_p256_select_point(const fiat_p256_limb_t idx, size_t size, } } -// fiat_p256_get_bit returns the |i|th bit in |in|. +// fiat_p256_get_bit returns the `i`th bit in `in`. static crypto_word_t fiat_p256_get_bit(const EC_SCALAR *in, int i) { if (i < 0 || i >= 256) { return 0; @@ -412,7 +250,7 @@ static crypto_word_t fiat_p256_get_bit(const EC_SCALAR *in, int i) { // OPENSSL EC_METHOD FUNCTIONS // Takes the Jacobian coordinates (X, Y, Z) of a point and returns (X', Y') = -// (X/Z^2, Y/Z^3). +// (X/Z², Y/Z³). static int ec_GFp_nistp256_point_get_affine_coordinates( const EC_GROUP *group, const EC_JACOBIAN *point, EC_FELEM *x_out, EC_FELEM *y_out) { @@ -426,14 +264,14 @@ static int ec_GFp_nistp256_point_get_affine_coordinates( fiat_p256_from_generic(z1, &point->Z); fiat_p256_inv_square(z2, z1); - if (x_out != NULL) { + if (x_out != nullptr) { fiat_p256_felem x; fiat_p256_from_generic(x, &point->X); fiat_p256_mul(x, x, z2); fiat_p256_to_generic(x_out, x); } - if (y_out != NULL) { + if (y_out != nullptr) { fiat_p256_felem y; fiat_p256_from_generic(y, &point->Y); fiat_p256_square(z2, z2); // z^-4 @@ -454,8 +292,7 @@ static void ec_GFp_nistp256_add(const EC_GROUP *group, EC_JACOBIAN *r, fiat_p256_from_generic(x2, &b->X); fiat_p256_from_generic(y2, &b->Y); fiat_p256_from_generic(z2, &b->Z); - fiat_p256_point_add(x1, y1, z1, x1, y1, z1, 0 /* both Jacobian */, x2, y2, - z2); + fiat_p256_point_add(x1, y1, z1, x1, y1, z1, x2, y2, z2); fiat_p256_to_generic(&r->X, x1); fiat_p256_to_generic(&r->Y, y1); fiat_p256_to_generic(&r->Z, z1); @@ -486,7 +323,7 @@ static void ec_GFp_nistp256_point_mul(const EC_GROUP *group, EC_JACOBIAN *r, if (j & 1) { fiat_p256_point_add(p_pre_comp[j][0], p_pre_comp[j][1], p_pre_comp[j][2], p_pre_comp[1][0], p_pre_comp[1][1], p_pre_comp[1][2], - 0, p_pre_comp[j - 1][0], p_pre_comp[j - 1][1], + p_pre_comp[j - 1][0], p_pre_comp[j - 1][1], p_pre_comp[j - 1][2]); } else { fiat_p256_point_double(p_pre_comp[j][0], p_pre_comp[j][1], @@ -498,7 +335,7 @@ static void ec_GFp_nistp256_point_mul(const EC_GROUP *group, EC_JACOBIAN *r, // Set nq to the point at infinity. fiat_p256_felem nq[3] = {{0}, {0}, {0}}, ftmp, tmp[3]; - // Loop over |scalar| msb-to-lsb, incorporating |p_pre_comp| every 5th round. + // Loop over `scalar` msb-to-lsb, incorporating `p_pre_comp` every 5th round. int skip = 1; // Save two point operations in the first round. for (size_t i = 255; i < 256; i--) { // double @@ -524,8 +361,8 @@ static void ec_GFp_nistp256_point_mul(const EC_GROUP *group, EC_JACOBIAN *r, fiat_p256_cmovznz(tmp[1], (fiat_p256_limb_t)sign, tmp[1], ftmp); if (!skip) { - fiat_p256_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], - 0 /* mixed */, tmp[0], tmp[1], tmp[2]); + fiat_p256_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], tmp[0], + tmp[1], tmp[2]); } else { fiat_p256_copy(nq[0], tmp[0]); fiat_p256_copy(nq[1], tmp[1]); @@ -562,8 +399,8 @@ static void ec_GFp_nistp256_point_mul_base(const EC_GROUP *group, fiat_p256_g_pre_comp[1], tmp); if (!skip) { - fiat_p256_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], - 1 /* mixed */, tmp[0], tmp[1], tmp[2]); + fiat_p256_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], tmp[0], + tmp[1], tmp[2]); } else { fiat_p256_copy(nq[0], tmp[0]); fiat_p256_copy(nq[1], tmp[1]); @@ -579,8 +416,8 @@ static void ec_GFp_nistp256_point_mul_base(const EC_GROUP *group, // Select the point to add, in constant time. fiat_p256_select_point_affine((fiat_p256_limb_t)bits, 15, fiat_p256_g_pre_comp[0], tmp); - fiat_p256_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */, - tmp[0], tmp[1], tmp[2]); + fiat_p256_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], tmp[0], + tmp[1], tmp[2]); } fiat_p256_to_generic(&r->X, nq[0]); @@ -594,7 +431,7 @@ static void ec_GFp_nistp256_point_mul_public(const EC_GROUP *group, const EC_JACOBIAN *p, const EC_SCALAR *p_scalar) { #define P256_WSIZE_PUBLIC 4 - // Precompute multiples of |p|. p_pre_comp[i] is (2*i+1) * |p|. + // Precompute multiples of `p`. p_pre_comp[i] is (2*i+1) * `p`. fiat_p256_felem p_pre_comp[1 << (P256_WSIZE_PUBLIC - 1)][3]; fiat_p256_from_generic(p_pre_comp[0][0], &p->X); fiat_p256_from_generic(p_pre_comp[0][1], &p->Y); @@ -602,18 +439,17 @@ static void ec_GFp_nistp256_point_mul_public(const EC_GROUP *group, fiat_p256_felem p2[3]; fiat_p256_point_double(p2[0], p2[1], p2[2], p_pre_comp[0][0], p_pre_comp[0][1], p_pre_comp[0][2]); - for (size_t i = 1; i < OPENSSL_ARRAY_SIZE(p_pre_comp); i++) { + for (size_t i = 1; i < std::size(p_pre_comp); i++) { fiat_p256_point_add(p_pre_comp[i][0], p_pre_comp[i][1], p_pre_comp[i][2], p_pre_comp[i - 1][0], p_pre_comp[i - 1][1], - p_pre_comp[i - 1][2], 0 /* not mixed */, p2[0], p2[1], - p2[2]); + p_pre_comp[i - 1][2], p2[0], p2[1], p2[2]); } - // Set up the coefficients for |p_scalar|. + // Set up the coefficients for `p_scalar`. int8_t p_wNAF[257]; ec_compute_wNAF(group, p_wNAF, p_scalar, 256, P256_WSIZE_PUBLIC); - // Set |ret| to the point at infinity. + // Set `ret` to the point at infinity. int skip = 1; // Save some point operations. fiat_p256_felem ret[3] = {{0}, {0}, {0}}; for (int i = 256; i >= 0; i--) { @@ -621,7 +457,7 @@ static void ec_GFp_nistp256_point_mul_public(const EC_GROUP *group, fiat_p256_point_double(ret[0], ret[1], ret[2], ret[0], ret[1], ret[2]); } - // For the |g_scalar|, we use the precomputed table without the + // For the `g_scalar`, we use the precomputed table without the // constant-time lookup. if (i <= 31) { // First, look 32 bits upwards. @@ -632,9 +468,8 @@ static void ec_GFp_nistp256_point_mul_public(const EC_GROUP *group, if (bits != 0) { size_t index = (size_t)(bits - 1); fiat_p256_point_add(ret[0], ret[1], ret[2], ret[0], ret[1], ret[2], - 1 /* mixed */, fiat_p256_g_pre_comp[1][index][0], - fiat_p256_g_pre_comp[1][index][1], - fiat_p256_one); + fiat_p256_g_pre_comp[1][index][0], + fiat_p256_g_pre_comp[1][index][1], fiat_p256_one); skip = 0; } @@ -646,9 +481,8 @@ static void ec_GFp_nistp256_point_mul_public(const EC_GROUP *group, if (bits != 0) { size_t index = (size_t)(bits - 1); fiat_p256_point_add(ret[0], ret[1], ret[2], ret[0], ret[1], ret[2], - 1 /* mixed */, fiat_p256_g_pre_comp[0][index][0], - fiat_p256_g_pre_comp[0][index][1], - fiat_p256_one); + fiat_p256_g_pre_comp[0][index][0], + fiat_p256_g_pre_comp[0][index][1], fiat_p256_one); skip = 0; } } @@ -664,8 +498,7 @@ static void ec_GFp_nistp256_point_mul_public(const EC_GROUP *group, } if (!skip) { fiat_p256_point_add(ret[0], ret[1], ret[2], ret[0], ret[1], ret[2], - 0 /* not mixed */, p_pre_comp[idx][0], *y, - p_pre_comp[idx][2]); + p_pre_comp[idx][0], *y, p_pre_comp[idx][2]); } else { fiat_p256_copy(ret[0], p_pre_comp[idx][0]); fiat_p256_copy(ret[1], *y); @@ -687,8 +520,8 @@ static int ec_GFp_nistp256_cmp_x_coordinate(const EC_GROUP *group, return 0; } - // We wish to compare X/Z^2 with r. This is equivalent to comparing X with - // r*Z^2. Note that X and Z are represented in Montgomery form, while r is + // We wish to compare X/Z² with r. This is equivalent to comparing X with + // r⋅Z². Note that X and Z are represented in Montgomery form, while r is // not. fiat_p256_felem Z2_mont; fiat_p256_from_generic(Z2_mont, &p->Z); @@ -708,7 +541,7 @@ static int ec_GFp_nistp256_cmp_x_coordinate(const EC_GROUP *group, // During signing the x coefficient is reduced modulo the group order. // Therefore there is a small possibility, less than 1/2^128, that group_order - // < p.x < P. in that case we need not only to compare against |r| but also to + // < p.x < P. in that case we need not only to compare against `r` but also to // compare against r+group_order. assert(group->field.N.width == group->order.N.width); EC_FELEM tmp; @@ -726,6 +559,8 @@ static int ec_GFp_nistp256_cmp_x_coordinate(const EC_GROUP *group, return 0; } +BSSL_NAMESPACE_BEGIN + DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistp256_method) { out->point_get_affine_coordinates = ec_GFp_nistp256_point_get_affine_coordinates; @@ -734,16 +569,10 @@ DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistp256_method) { out->mul = ec_GFp_nistp256_point_mul; out->mul_base = ec_GFp_nistp256_point_mul_base; out->mul_public = ec_GFp_nistp256_point_mul_public; - out->felem_mul = ec_GFp_mont_felem_mul; - out->felem_sqr = ec_GFp_mont_felem_sqr; - out->felem_to_bytes = ec_GFp_mont_felem_to_bytes; - out->felem_from_bytes = ec_GFp_mont_felem_from_bytes; - out->felem_reduce = ec_GFp_mont_felem_reduce; - // TODO(davidben): This should use the specialized field arithmetic - // implementation, rather than the generic one. - out->felem_exp = ec_GFp_mont_felem_exp; out->scalar_inv0_montgomery = ec_simple_scalar_inv0_montgomery; out->scalar_to_montgomery_inv_vartime = ec_simple_scalar_to_montgomery_inv_vartime; out->cmp_x_coordinate = ec_GFp_nistp256_cmp_x_coordinate; } + +BSSL_NAMESPACE_END diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256_table.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256_table.h index 04f8adb9..e16eabaa 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256_table.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/p256_table.h @@ -1,16 +1,16 @@ -/* Copyright 2020 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2020 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. // This file is generated by make_tables.go. diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/scalar.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/scalar.cc.inc index e1fc0122..94e8aa0c 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/scalar.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/scalar.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2018 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2018 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 @@ -21,8 +21,10 @@ #include "internal.h" -int ec_bignum_to_scalar(const EC_GROUP *group, EC_SCALAR *out, - const BIGNUM *in) { +using namespace bssl; + +int bssl::ec_bignum_to_scalar(const EC_GROUP *group, EC_SCALAR *out, + const BIGNUM *in) { // Scalars, which are often secret, must be reduced modulo the order. Those // that are not will be discarded, so leaking the result of the comparison is // safe. @@ -35,13 +37,13 @@ int ec_bignum_to_scalar(const EC_GROUP *group, EC_SCALAR *out, return 1; } -int ec_scalar_equal_vartime(const EC_GROUP *group, const EC_SCALAR *a, - const EC_SCALAR *b) { +int bssl::ec_scalar_equal_vartime(const EC_GROUP *group, const EC_SCALAR *a, + const EC_SCALAR *b) { return OPENSSL_memcmp(a->words, b->words, group->order.N.width * sizeof(BN_ULONG)) == 0; } -int ec_scalar_is_zero(const EC_GROUP *group, const EC_SCALAR *a) { +int bssl::ec_scalar_is_zero(const EC_GROUP *group, const EC_SCALAR *a) { BN_ULONG mask = 0; for (int i = 0; i < group->order.N.width; i++) { mask |= a->words[i]; @@ -49,27 +51,27 @@ int ec_scalar_is_zero(const EC_GROUP *group, const EC_SCALAR *a) { return mask == 0; } -int ec_random_scalar(const EC_GROUP *group, EC_SCALAR *out, - const uint8_t additional_data[32]) { +int bssl::ec_random_scalar(const EC_GROUP *group, EC_SCALAR *out, + const uint8_t additional_data[32]) { return bn_rand_range_words(out->words, 0, group->order.N.d, group->order.N.width, additional_data); } -int ec_random_nonzero_scalar(const EC_GROUP *group, EC_SCALAR *out, - const uint8_t additional_data[32]) { +int bssl::ec_random_nonzero_scalar(const EC_GROUP *group, EC_SCALAR *out, + const uint8_t additional_data[32]) { return bn_rand_range_words(out->words, 1, group->order.N.d, group->order.N.width, additional_data); } -void ec_scalar_to_bytes(const EC_GROUP *group, uint8_t *out, size_t *out_len, - const EC_SCALAR *in) { +void bssl::ec_scalar_to_bytes(const EC_GROUP *group, uint8_t *out, + size_t *out_len, const EC_SCALAR *in) { size_t len = BN_num_bytes(&group->order.N); bn_words_to_big_endian(out, len, in->words, group->order.N.width); *out_len = len; } -int ec_scalar_from_bytes(const EC_GROUP *group, EC_SCALAR *out, - const uint8_t *in, size_t len) { +int bssl::ec_scalar_from_bytes(const EC_GROUP *group, EC_SCALAR *out, + const uint8_t *in, size_t len) { if (len != BN_num_bytes(&group->order.N)) { OPENSSL_PUT_ERROR(EC, EC_R_INVALID_SCALAR); return 0; @@ -85,8 +87,8 @@ int ec_scalar_from_bytes(const EC_GROUP *group, EC_SCALAR *out, return 1; } -void ec_scalar_reduce(const EC_GROUP *group, EC_SCALAR *out, - const BN_ULONG *words, size_t num) { +void bssl::ec_scalar_reduce(const EC_GROUP *group, EC_SCALAR *out, + const BN_ULONG *words, size_t num) { // Convert "from" Montgomery form so the value is reduced modulo the order. bn_from_montgomery_small(out->words, group->order.N.width, words, num, &group->order); @@ -94,64 +96,66 @@ void ec_scalar_reduce(const EC_GROUP *group, EC_SCALAR *out, ec_scalar_to_montgomery(group, out, out); } -void ec_scalar_add(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a, - const EC_SCALAR *b) { +void bssl::ec_scalar_add(const EC_GROUP *group, EC_SCALAR *r, + const EC_SCALAR *a, const EC_SCALAR *b) { const BIGNUM *order = &group->order.N; BN_ULONG tmp[EC_MAX_WORDS]; bn_mod_add_words(r->words, a->words, b->words, order->d, tmp, order->width); OPENSSL_cleanse(tmp, sizeof(tmp)); } -void ec_scalar_sub(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a, - const EC_SCALAR *b) { +void bssl::ec_scalar_sub(const EC_GROUP *group, EC_SCALAR *r, + const EC_SCALAR *a, const EC_SCALAR *b) { const BIGNUM *order = &group->order.N; BN_ULONG tmp[EC_MAX_WORDS]; bn_mod_sub_words(r->words, a->words, b->words, order->d, tmp, order->width); OPENSSL_cleanse(tmp, sizeof(tmp)); } -void ec_scalar_neg(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a) { +void bssl::ec_scalar_neg(const EC_GROUP *group, EC_SCALAR *r, + const EC_SCALAR *a) { EC_SCALAR zero; OPENSSL_memset(&zero, 0, sizeof(EC_SCALAR)); ec_scalar_sub(group, r, &zero, a); } -void ec_scalar_select(const EC_GROUP *group, EC_SCALAR *out, BN_ULONG mask, - const EC_SCALAR *a, const EC_SCALAR *b) { +void bssl::ec_scalar_select(const EC_GROUP *group, EC_SCALAR *out, + BN_ULONG mask, const EC_SCALAR *a, + const EC_SCALAR *b) { const BIGNUM *order = &group->order.N; bn_select_words(out->words, mask, a->words, b->words, order->width); } -void ec_scalar_to_montgomery(const EC_GROUP *group, EC_SCALAR *r, - const EC_SCALAR *a) { +void bssl::ec_scalar_to_montgomery(const EC_GROUP *group, EC_SCALAR *r, + const EC_SCALAR *a) { const BIGNUM *order = &group->order.N; bn_to_montgomery_small(r->words, a->words, order->width, &group->order); } -void ec_scalar_from_montgomery(const EC_GROUP *group, EC_SCALAR *r, - const EC_SCALAR *a) { +void bssl::ec_scalar_from_montgomery(const EC_GROUP *group, EC_SCALAR *r, + const EC_SCALAR *a) { const BIGNUM *order = &group->order.N; bn_from_montgomery_small(r->words, order->width, a->words, order->width, &group->order); } -void ec_scalar_mul_montgomery(const EC_GROUP *group, EC_SCALAR *r, - const EC_SCALAR *a, const EC_SCALAR *b) { +void bssl::ec_scalar_mul_montgomery(const EC_GROUP *group, EC_SCALAR *r, + const EC_SCALAR *a, const EC_SCALAR *b) { const BIGNUM *order = &group->order.N; bn_mod_mul_montgomery_small(r->words, a->words, b->words, order->width, &group->order); } -void ec_simple_scalar_inv0_montgomery(const EC_GROUP *group, EC_SCALAR *r, - const EC_SCALAR *a) { +void bssl::ec_simple_scalar_inv0_montgomery(const EC_GROUP *group, EC_SCALAR *r, + const EC_SCALAR *a) { const BIGNUM *order = &group->order.N; bn_mod_inverse0_prime_mont_small(r->words, a->words, order->width, &group->order); } -int ec_simple_scalar_to_montgomery_inv_vartime(const EC_GROUP *group, - EC_SCALAR *r, - const EC_SCALAR *a) { +int bssl::ec_simple_scalar_to_montgomery_inv_vartime(const EC_GROUP *group, + EC_SCALAR *r, + const EC_SCALAR *a) { if (ec_scalar_is_zero(group, a)) { return 0; } @@ -160,20 +164,21 @@ int ec_simple_scalar_to_montgomery_inv_vartime(const EC_GROUP *group, // even though for this interface it is not mandatory. // r = a^-1 in the Montgomery domain. This is - // |ec_scalar_to_montgomery| followed by |ec_scalar_inv0_montgomery|, but - // |ec_scalar_inv0_montgomery| followed by |ec_scalar_from_montgomery| is + // `ec_scalar_to_montgomery` followed by `ec_scalar_inv0_montgomery`, but + // `ec_scalar_inv0_montgomery` followed by `ec_scalar_from_montgomery` is // equivalent and slightly more efficient. ec_scalar_inv0_montgomery(group, r, a); ec_scalar_from_montgomery(group, r, r); return 1; } -void ec_scalar_inv0_montgomery(const EC_GROUP *group, EC_SCALAR *r, - const EC_SCALAR *a) { +void bssl::ec_scalar_inv0_montgomery(const EC_GROUP *group, EC_SCALAR *r, + const EC_SCALAR *a) { group->meth->scalar_inv0_montgomery(group, r, a); } -int ec_scalar_to_montgomery_inv_vartime(const EC_GROUP *group, EC_SCALAR *r, - const EC_SCALAR *a) { +int bssl::ec_scalar_to_montgomery_inv_vartime(const EC_GROUP *group, + EC_SCALAR *r, + const EC_SCALAR *a) { return group->meth->scalar_to_montgomery_inv_vartime(group, r, a); } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/simple.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/simple.cc.inc index 6ecb4e98..79e79a1b 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/simple.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/simple.cc.inc @@ -1,12 +1,17 @@ -/* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. - * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. +// +// 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 @@ -16,13 +21,15 @@ #include #include -#include "internal.h" #include "../../internal.h" +#include "internal.h" +using namespace bssl; + // Most method functions in this file are designed to work with non-trivial -// representations of field elements if necessary (see ecp_mont.c): while -// standard modular addition and subtraction are used, the field_mul and +// representations of field elements if necessary (see ec_montgomery.cc.inc): +// while standard modular addition and subtraction are used, the field_mul and // field_sqr methods will be used for multiplication, and field_encode and // field_decode (if defined) will be used for converting between // representations. @@ -30,21 +37,23 @@ // Functions here specifically assume that if a non-trivial representation is // used, it is a Montgomery representation (i.e. 'encoding' means multiplying // by some factor R). +// +// TODO(crbug.com/505908440): ec_montgomery.cc.inc is now the only field element +// representation. Fold these files together. -int ec_GFp_simple_group_set_curve(EC_GROUP *group, const BIGNUM *p, - const BIGNUM *a, const BIGNUM *b, - BN_CTX *ctx) { +int bssl::ec_GFp_simple_group_set_curve(EC_GROUP *group, const BIGNUM *p, + const BIGNUM *a, const BIGNUM *b, + BN_CTX *ctx) { // p must be a prime > 3 if (BN_num_bits(p) <= 2 || !BN_is_odd(p)) { OPENSSL_PUT_ERROR(EC, EC_R_INVALID_FIELD); return 0; } - int ret = 0; - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *tmp = BN_CTX_get(ctx); - if (tmp == NULL) { - goto err; + if (tmp == nullptr) { + return 0; } if (!BN_MONT_CTX_set(&group->field, p, ctx) || @@ -52,108 +61,98 @@ int ec_GFp_simple_group_set_curve(EC_GROUP *group, const BIGNUM *p, !ec_bignum_to_felem(group, &group->b, b) || // Reuse Z from the generator to cache the value one. !ec_bignum_to_felem(group, &group->generator.raw.Z, BN_value_one())) { - goto err; + return 0; } - // group->a_is_minus3 - if (!BN_copy(tmp, a) || - !BN_add_word(tmp, 3)) { - goto err; + if (!BN_copy(tmp, a) || !BN_add_word(tmp, 3)) { + return 0; } group->a_is_minus3 = (0 == BN_cmp(tmp, &group->field.N)); + group->field_is_3_mod_4 = (group->field.N.d[0] & 3) == 3; - ret = 1; - -err: - BN_CTX_end(ctx); - return ret; + return 1; } -int ec_GFp_simple_group_get_curve(const EC_GROUP *group, BIGNUM *p, BIGNUM *a, - BIGNUM *b) { - if ((p != NULL && !BN_copy(p, &group->field.N)) || - (a != NULL && !ec_felem_to_bignum(group, a, &group->a)) || - (b != NULL && !ec_felem_to_bignum(group, b, &group->b))) { +int bssl::ec_GFp_simple_group_get_curve(const EC_GROUP *group, BIGNUM *p, + BIGNUM *a, BIGNUM *b) { + if ((p != nullptr && !BN_copy(p, &group->field.N)) || + (a != nullptr && !ec_felem_to_bignum(group, a, &group->a)) || + (b != nullptr && !ec_felem_to_bignum(group, b, &group->b))) { return 0; } return 1; } -void ec_GFp_simple_point_init(EC_JACOBIAN *point) { +void bssl::ec_GFp_simple_point_init(EC_JACOBIAN *point) { OPENSSL_memset(&point->X, 0, sizeof(EC_FELEM)); OPENSSL_memset(&point->Y, 0, sizeof(EC_FELEM)); OPENSSL_memset(&point->Z, 0, sizeof(EC_FELEM)); } -void ec_GFp_simple_point_copy(EC_JACOBIAN *dest, const EC_JACOBIAN *src) { +void bssl::ec_GFp_simple_point_copy(EC_JACOBIAN *dest, const EC_JACOBIAN *src) { OPENSSL_memcpy(&dest->X, &src->X, sizeof(EC_FELEM)); OPENSSL_memcpy(&dest->Y, &src->Y, sizeof(EC_FELEM)); OPENSSL_memcpy(&dest->Z, &src->Z, sizeof(EC_FELEM)); } -void ec_GFp_simple_point_set_to_infinity(const EC_GROUP *group, - EC_JACOBIAN *point) { +void bssl::ec_GFp_simple_point_set_to_infinity(const EC_GROUP *group, + EC_JACOBIAN *point) { // Although it is strictly only necessary to zero Z, we zero the entire point - // in case |point| was stack-allocated and yet to be initialized. + // in case `point` was stack-allocated and yet to be initialized. ec_GFp_simple_point_init(point); } -void ec_GFp_simple_invert(const EC_GROUP *group, EC_JACOBIAN *point) { +void bssl::ec_GFp_simple_invert(const EC_GROUP *group, EC_JACOBIAN *point) { ec_felem_neg(group, &point->Y, &point->Y); } -int ec_GFp_simple_is_at_infinity(const EC_GROUP *group, - const EC_JACOBIAN *point) { +int bssl::ec_GFp_simple_is_at_infinity(const EC_GROUP *group, + const EC_JACOBIAN *point) { return ec_felem_non_zero_mask(group, &point->Z) == 0; } -int ec_GFp_simple_is_on_curve(const EC_GROUP *group, - const EC_JACOBIAN *point) { +int bssl::ec_GFp_simple_is_on_curve(const EC_GROUP *group, + const EC_JACOBIAN *point) { // We have a curve defined by a Weierstrass equation - // y^2 = x^3 + a*x + b. + // y² = x³ + a⋅x + b. // The point to consider is given in Jacobian projective coordinates - // where (X, Y, Z) represents (x, y) = (X/Z^2, Y/Z^3). - // Substituting this and multiplying by Z^6 transforms the above equation + // where (X, Y, Z) represents (x, y) = (X/Z², Y/Z³). + // Substituting this and multiplying by Z⁶ transforms the above equation // into - // Y^2 = X^3 + a*X*Z^4 + b*Z^6. + // Y² = X³ + a⋅X⋅Z⁴ + b⋅Z⁶. // To test this, we add up the right-hand side in 'rh'. // // This function may be used when double-checking the secret result of a point // multiplication, so we proceed in constant-time. - void (*const felem_mul)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a, - const EC_FELEM *b) = group->meth->felem_mul; - void (*const felem_sqr)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a) = - group->meth->felem_sqr; - - // rh := X^2 + // rh := X² EC_FELEM rh; - felem_sqr(group, &rh, &point->X); + ec_felem_sqr(group, &rh, &point->X); EC_FELEM tmp, Z4, Z6; - felem_sqr(group, &tmp, &point->Z); - felem_sqr(group, &Z4, &tmp); - felem_mul(group, &Z6, &Z4, &tmp); + ec_felem_sqr(group, &tmp, &point->Z); + ec_felem_sqr(group, &Z4, &tmp); + ec_felem_mul(group, &Z6, &Z4, &tmp); - // rh := rh + a*Z^4 + // rh := rh + a⋅Z⁴ if (group->a_is_minus3) { ec_felem_add(group, &tmp, &Z4, &Z4); ec_felem_add(group, &tmp, &tmp, &Z4); ec_felem_sub(group, &rh, &rh, &tmp); } else { - felem_mul(group, &tmp, &Z4, &group->a); + ec_felem_mul(group, &tmp, &Z4, &group->a); ec_felem_add(group, &rh, &rh, &tmp); } - // rh := (rh + a*Z^4)*X - felem_mul(group, &rh, &rh, &point->X); + // rh := (rh + a⋅Z⁴)⋅X + ec_felem_mul(group, &rh, &rh, &point->X); - // rh := rh + b*Z^6 - felem_mul(group, &tmp, &group->b, &Z6); + // rh := rh + b⋅Z⁶ + ec_felem_mul(group, &tmp, &group->b, &Z6); ec_felem_add(group, &rh, &rh, &tmp); - // 'lh' := Y^2 - felem_sqr(group, &tmp, &point->Y); + // 'lh' := Y² + ec_felem_sqr(group, &tmp, &point->Y); ec_felem_sub(group, &tmp, &tmp, &rh); BN_ULONG not_equal = ec_felem_non_zero_mask(group, &tmp); @@ -164,8 +163,9 @@ int ec_GFp_simple_is_on_curve(const EC_GROUP *group, return 1 & ~(not_infinity & not_equal); } -int ec_GFp_simple_points_equal(const EC_GROUP *group, const EC_JACOBIAN *a, - const EC_JACOBIAN *b) { +int bssl::ec_GFp_simple_points_equal(const EC_GROUP *group, + const EC_JACOBIAN *a, + const EC_JACOBIAN *b) { // This function is implemented in constant-time for two reasons. First, // although EC points are usually public, their Jacobian Z coordinates may be // secret, or at least are not obviously public. Second, more complex @@ -176,28 +176,23 @@ int ec_GFp_simple_points_equal(const EC_GROUP *group, const EC_JACOBIAN *a, // restore this optimization by keeping better track of affine vs. Jacobian // forms. See https://crbug.com/boringssl/326. - // If neither |a| or |b| is infinity, we have to decide whether - // (X_a/Z_a^2, Y_a/Z_a^3) = (X_b/Z_b^2, Y_b/Z_b^3), + // If neither `a` or `b` is infinity, we have to decide whether + // (X_a/Z_a², Y_a/Z_a³) = (X_b/Z_b², Y_b/Z_b³), // or equivalently, whether - // (X_a*Z_b^2, Y_a*Z_b^3) = (X_b*Z_a^2, Y_b*Z_a^3). - - void (*const felem_mul)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a, - const EC_FELEM *b) = group->meth->felem_mul; - void (*const felem_sqr)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a) = - group->meth->felem_sqr; + // (X_a⋅Z_b², Y_a⋅Z_b³) = (X_b⋅Z_a², Y_b⋅Z_a³). EC_FELEM tmp1, tmp2, Za23, Zb23; - felem_sqr(group, &Zb23, &b->Z); // Zb23 = Z_b^2 - felem_mul(group, &tmp1, &a->X, &Zb23); // tmp1 = X_a * Z_b^2 - felem_sqr(group, &Za23, &a->Z); // Za23 = Z_a^2 - felem_mul(group, &tmp2, &b->X, &Za23); // tmp2 = X_b * Z_a^2 + ec_felem_sqr(group, &Zb23, &b->Z); // Zb23 = Z_b² + ec_felem_mul(group, &tmp1, &a->X, &Zb23); // tmp1 = X_a ⋅ Z_b² + ec_felem_sqr(group, &Za23, &a->Z); // Za23 = Z_a² + ec_felem_mul(group, &tmp2, &b->X, &Za23); // tmp2 = X_b ⋅ Z_a² ec_felem_sub(group, &tmp1, &tmp1, &tmp2); const BN_ULONG x_not_equal = ec_felem_non_zero_mask(group, &tmp1); - felem_mul(group, &Zb23, &Zb23, &b->Z); // Zb23 = Z_b^3 - felem_mul(group, &tmp1, &a->Y, &Zb23); // tmp1 = Y_a * Z_b^3 - felem_mul(group, &Za23, &Za23, &a->Z); // Za23 = Z_a^3 - felem_mul(group, &tmp2, &b->Y, &Za23); // tmp2 = Y_b * Z_a^3 + ec_felem_mul(group, &Zb23, &Zb23, &b->Z); // Zb23 = Z_b³ + ec_felem_mul(group, &tmp1, &a->Y, &Zb23); // tmp1 = Y_a ⋅ Z_b³ + ec_felem_mul(group, &Za23, &Za23, &a->Z); // Za23 = Z_a³ + ec_felem_mul(group, &tmp2, &b->Y, &Za23); // tmp2 = Y_b ⋅ Z_a³ ec_felem_sub(group, &tmp1, &tmp1, &tmp2); const BN_ULONG y_not_equal = ec_felem_non_zero_mask(group, &tmp1); const BN_ULONG x_and_y_equal = ~(x_not_equal | y_not_equal); @@ -211,26 +206,21 @@ int ec_GFp_simple_points_equal(const EC_GROUP *group, const EC_JACOBIAN *a, return equal & 1; } -int ec_affine_jacobian_equal(const EC_GROUP *group, const EC_AFFINE *a, - const EC_JACOBIAN *b) { - // If |b| is not infinity, we have to decide whether - // (X_a, Y_a) = (X_b/Z_b^2, Y_b/Z_b^3), +int bssl::ec_affine_jacobian_equal(const EC_GROUP *group, const EC_AFFINE *a, + const EC_JACOBIAN *b) { + // If `b` is not infinity, we have to decide whether + // (X_a, Y_a) = (X_b/Z_b², Y_b/Z_b³), // or equivalently, whether - // (X_a*Z_b^2, Y_a*Z_b^3) = (X_b, Y_b). - - void (*const felem_mul)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a, - const EC_FELEM *b) = group->meth->felem_mul; - void (*const felem_sqr)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a) = - group->meth->felem_sqr; + // (X_a⋅Z_b², Y_a⋅Z_b³) = (X_b, Y_b). EC_FELEM tmp, Zb2; - felem_sqr(group, &Zb2, &b->Z); // Zb2 = Z_b^2 - felem_mul(group, &tmp, &a->X, &Zb2); // tmp = X_a * Z_b^2 + ec_felem_sqr(group, &Zb2, &b->Z); // Zb2 = Z_b² + ec_felem_mul(group, &tmp, &a->X, &Zb2); // tmp = X_a ⋅ Z_b² ec_felem_sub(group, &tmp, &tmp, &b->X); const BN_ULONG x_not_equal = ec_felem_non_zero_mask(group, &tmp); - felem_mul(group, &tmp, &a->Y, &Zb2); // tmp = Y_a * Z_b^2 - felem_mul(group, &tmp, &tmp, &b->Z); // tmp = Y_a * Z_b^3 + ec_felem_mul(group, &tmp, &a->Y, &Zb2); // tmp = Y_a ⋅ Z_b² + ec_felem_mul(group, &tmp, &tmp, &b->Z); // tmp = Y_a ⋅ Z_b³ ec_felem_sub(group, &tmp, &tmp, &b->Y); const BN_ULONG y_not_equal = ec_felem_non_zero_mask(group, &tmp); const BN_ULONG x_and_y_equal = ~(x_not_equal | y_not_equal); @@ -241,10 +231,11 @@ int ec_affine_jacobian_equal(const EC_GROUP *group, const EC_AFFINE *a, return equal & 1; } -int ec_GFp_simple_cmp_x_coordinate(const EC_GROUP *group, const EC_JACOBIAN *p, - const EC_SCALAR *r) { +int bssl::ec_GFp_simple_cmp_x_coordinate(const EC_GROUP *group, + const EC_JACOBIAN *p, + const EC_SCALAR *r) { if (ec_GFp_simple_is_at_infinity(group, p)) { - // |ec_get_x_coordinate_as_scalar| will check this internally, but this way + // `ec_get_x_coordinate_as_scalar` will check this internally, but this way // we do not push to the error queue. return 0; } @@ -253,27 +244,3 @@ int ec_GFp_simple_cmp_x_coordinate(const EC_GROUP *group, const EC_JACOBIAN *p, return ec_get_x_coordinate_as_scalar(group, &x, p) && ec_scalar_equal_vartime(group, &x, r); } - -void ec_GFp_simple_felem_to_bytes(const EC_GROUP *group, uint8_t *out, - size_t *out_len, const EC_FELEM *in) { - size_t len = BN_num_bytes(&group->field.N); - bn_words_to_big_endian(out, len, in->words, group->field.N.width); - *out_len = len; -} - -int ec_GFp_simple_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out, - const uint8_t *in, size_t len) { - if (len != BN_num_bytes(&group->field.N)) { - OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR); - return 0; - } - - bn_big_endian_to_words(out->words, group->field.N.width, in, len); - - if (!bn_less_than_words(out->words, group->field.N.d, group->field.N.width)) { - OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR); - return 0; - } - - return 1; -} diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/simple_mul.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/simple_mul.cc.inc index 4ef7fb2c..01958bbe 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/simple_mul.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/simple_mul.cc.inc @@ -1,37 +1,42 @@ -/* Copyright 2018 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2018 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 "internal.h" #include "../bn/internal.h" #include "../../internal.h" -void ec_GFp_mont_mul(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_JACOBIAN *p, const EC_SCALAR *scalar) { +using namespace bssl; + +void bssl::ec_GFp_mont_mul(const EC_GROUP *group, EC_JACOBIAN *r, + const EC_JACOBIAN *p, const EC_SCALAR *scalar) { // This is a generic implementation for uncommon curves that not do not // warrant a tuned one. It uses unsigned digits so that the doubling case in - // |ec_GFp_mont_add| is always unreachable, erring on safety and simplicity. + // `ec_GFp_mont_add` is always unreachable, erring on safety and simplicity. - // Compute a table of the first 32 multiples of |p| (including infinity). + // Compute a table of the first 32 multiples of `p` (including infinity). EC_JACOBIAN precomp[32]; ec_GFp_simple_point_set_to_infinity(group, &precomp[0]); ec_GFp_simple_point_copy(&precomp[1], p); - for (size_t j = 2; j < OPENSSL_ARRAY_SIZE(precomp); j++) { + for (size_t j = 2; j < std::size(precomp); j++) { if (j & 1) { ec_GFp_mont_add(group, &precomp[j], &precomp[1], &precomp[j - 1]); } else { @@ -39,7 +44,7 @@ void ec_GFp_mont_mul(const EC_GROUP *group, EC_JACOBIAN *r, } } - // Divide bits in |scalar| into windows. + // Divide bits in `scalar` into windows. unsigned bits = EC_GROUP_order_bits(group); int r_is_at_infinity = 1; for (unsigned i = bits - 1; i < bits; i--) { @@ -58,7 +63,7 @@ void ec_GFp_mont_mul(const EC_GROUP *group, EC_JACOBIAN *r, // Select the entry in constant-time. EC_JACOBIAN tmp; OPENSSL_memset(&tmp, 0, sizeof(EC_JACOBIAN)); - for (size_t j = 0; j < OPENSSL_ARRAY_SIZE(precomp); j++) { + for (size_t j = 0; j < std::size(precomp); j++) { BN_ULONG mask = constant_time_eq_w(j, window); ec_point_select(group, &tmp, mask, &precomp[j], &tmp); } @@ -76,8 +81,8 @@ void ec_GFp_mont_mul(const EC_GROUP *group, EC_JACOBIAN *r, } } -void ec_GFp_mont_mul_base(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_SCALAR *scalar) { +void bssl::ec_GFp_mont_mul_base(const EC_GROUP *group, EC_JACOBIAN *r, + const EC_SCALAR *scalar) { ec_GFp_mont_mul(group, r, &group->generator.raw, scalar); } @@ -126,18 +131,18 @@ static void ec_GFp_mont_batch_get_window(const EC_GROUP *group, ec_felem_select(group, &out->Y, sign_mask, &neg_Y, &out->Y); } -void ec_GFp_mont_mul_batch(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_JACOBIAN *p0, const EC_SCALAR *scalar0, - const EC_JACOBIAN *p1, const EC_SCALAR *scalar1, - const EC_JACOBIAN *p2, const EC_SCALAR *scalar2) { +void bssl::ec_GFp_mont_mul_batch( + const EC_GROUP *group, EC_JACOBIAN *r, const EC_JACOBIAN *p0, + const EC_SCALAR *scalar0, const EC_JACOBIAN *p1, const EC_SCALAR *scalar1, + const EC_JACOBIAN *p2, const EC_SCALAR *scalar2) { EC_JACOBIAN precomp[3][17]; ec_GFp_mont_batch_precomp(group, precomp[0], 17, p0); ec_GFp_mont_batch_precomp(group, precomp[1], 17, p1); - if (p2 != NULL) { + if (p2 != nullptr) { ec_GFp_mont_batch_precomp(group, precomp[2], 17, p2); } - // Divide bits in |scalar| into windows. + // Divide bits in `scalar` into windows. unsigned bits = EC_GROUP_order_bits(group); int r_is_at_infinity = 1; for (unsigned i = bits; i <= bits; i--) { @@ -157,7 +162,7 @@ void ec_GFp_mont_mul_batch(const EC_GROUP *group, EC_JACOBIAN *r, ec_GFp_mont_batch_get_window(group, &tmp, precomp[1], scalar1, i); ec_GFp_mont_add(group, r, r, &tmp); - if (p2 != NULL) { + if (p2 != nullptr) { ec_GFp_mont_batch_get_window(group, &tmp, precomp[2], scalar2, i); ec_GFp_mont_add(group, r, r, &tmp); } @@ -173,12 +178,12 @@ static unsigned ec_GFp_mont_comb_stride(const EC_GROUP *group) { EC_MONT_PRECOMP_COMB_SIZE; } -int ec_GFp_mont_init_precomp(const EC_GROUP *group, EC_PRECOMP *out, - const EC_JACOBIAN *p) { +int bssl::ec_GFp_mont_init_precomp(const EC_GROUP *group, EC_PRECOMP *out, + const EC_JACOBIAN *p) { // comb[i - 1] stores the ith element of the comb. That is, if i is // b4 * 2^4 + b3 * 2^3 + ... + b0 * 2^0, it stores k * |p|, where k is // b4 * 2^(4*stride) + b3 * 2^(3*stride) + ... + b0 * 2^(0*stride). stride - // here is |ec_GFp_mont_comb_stride|. We store at index i - 1 because the 0th + // here is `ec_GFp_mont_comb_stride`. We store at index i - 1 because the 0th // comb entry is always infinity. EC_JACOBIAN comb[(1 << EC_MONT_PRECOMP_COMB_SIZE) - 1]; unsigned stride = ec_GFp_mont_comb_stride(group); @@ -187,7 +192,7 @@ int ec_GFp_mont_init_precomp(const EC_GROUP *group, EC_PRECOMP *out, // entries up to 2^0 are filled. comb[(1 << 0) - 1] = *p; for (unsigned i = 1; i < EC_MONT_PRECOMP_COMB_SIZE; i++) { - // Compute entry 2^i by doubling the entry for 2^(i-1) |stride| times. + // Compute entry 2^i by doubling the entry for 2^(i-1) `stride` times. unsigned bit = 1 << i; ec_GFp_mont_dbl(group, &comb[bit - 1], &comb[bit / 2 - 1]); for (unsigned j = 1; j < stride; j++) { @@ -202,10 +207,10 @@ int ec_GFp_mont_init_precomp(const EC_GROUP *group, EC_PRECOMP *out, // Store the comb in affine coordinates to shrink the table. (This reduces // cache pressure and makes the constant-time selects faster.) - static_assert(OPENSSL_ARRAY_SIZE(comb) == OPENSSL_ARRAY_SIZE(out->comb), - "comb sizes did not match"); - return ec_jacobian_to_affine_batch(group, out->comb, comb, - OPENSSL_ARRAY_SIZE(comb)); + static_assert( + std::extent_v == std::extent_vcomb)>, + "comb sizes did not match"); + return ec_jacobian_to_affine_batch(group, out->comb, comb, std::size(comb)); } static void ec_GFp_mont_get_comb_window(const EC_GROUP *group, @@ -214,17 +219,17 @@ static void ec_GFp_mont_get_comb_window(const EC_GROUP *group, const EC_SCALAR *scalar, unsigned i) { const size_t width = group->order.N.width; unsigned stride = ec_GFp_mont_comb_stride(group); - // Select the bits corresponding to the comb shifted up by |i|. + // Select the bits corresponding to the comb shifted up by `i`. unsigned window = 0; for (unsigned j = 0; j < EC_MONT_PRECOMP_COMB_SIZE; j++) { window |= bn_is_bit_set_words(scalar->words, width, j * stride + i) << j; } - // Select precomp->comb[window - 1]. If |window| is zero, |match| will always - // be zero, which will leave |out| at infinity. + // Select precomp->comb[window - 1]. If `window` is zero, `match` will always + // be zero, which will leave `out` at infinity. OPENSSL_memset(out, 0, sizeof(EC_JACOBIAN)); - for (unsigned j = 0; j < OPENSSL_ARRAY_SIZE(precomp->comb); j++) { + for (unsigned j = 0; j < std::size(precomp->comb); j++) { BN_ULONG match = constant_time_eq_w(window, j + 1); ec_felem_select(group, &out->X, match, &precomp->comb[j].X, &out->X); ec_felem_select(group, &out->Y, match, &precomp->comb[j].Y, &out->Y); @@ -233,10 +238,10 @@ static void ec_GFp_mont_get_comb_window(const EC_GROUP *group, ec_felem_select(group, &out->Z, is_infinity, &out->Z, ec_felem_one(group)); } -void ec_GFp_mont_mul_precomp(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_PRECOMP *p0, const EC_SCALAR *scalar0, - const EC_PRECOMP *p1, const EC_SCALAR *scalar1, - const EC_PRECOMP *p2, const EC_SCALAR *scalar2) { +void bssl::ec_GFp_mont_mul_precomp( + const EC_GROUP *group, EC_JACOBIAN *r, const EC_PRECOMP *p0, + const EC_SCALAR *scalar0, const EC_PRECOMP *p1, const EC_SCALAR *scalar1, + const EC_PRECOMP *p2, const EC_SCALAR *scalar2) { unsigned stride = ec_GFp_mont_comb_stride(group); int r_is_at_infinity = 1; for (unsigned i = stride - 1; i < stride; i--) { @@ -253,12 +258,12 @@ void ec_GFp_mont_mul_precomp(const EC_GROUP *group, EC_JACOBIAN *r, ec_GFp_mont_add(group, r, r, &tmp); } - if (p1 != NULL) { + if (p1 != nullptr) { ec_GFp_mont_get_comb_window(group, &tmp, p1, scalar1, i); ec_GFp_mont_add(group, r, r, &tmp); } - if (p2 != NULL) { + if (p2 != nullptr) { ec_GFp_mont_get_comb_window(group, &tmp, p2, scalar2, i); ec_GFp_mont_add(group, r, r, &tmp); } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/util.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/util.cc.inc index 62566251..3530e91f 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/util.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/util.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2015 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2015 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 @@ -19,6 +19,8 @@ #include "internal.h" +using namespace bssl; + // This function looks at 5+1 scalar bits (5 current, 1 adjacent less // significant bit), and recodes them into a signed digit for use in fast point // multiplication: the use of signed rather than unsigned digits means that @@ -108,7 +110,7 @@ // is a prime that is much larger than 2^w. It also only holds when windows // are applied from most significant to least significant, doubling between each // window. It does not apply to more complex table strategies such as -// |EC_GFp_nistz256_method|. +// `EC_GFp_nistz256_method`. // // PROOF: // @@ -240,8 +242,9 @@ // P-384: ...01110011; w = 2, 5, 6, 7 are okay // P-256: ...01010001; w = 5, 7 are okay // P-224: ...00111101; w = 3, 4, 5, 6 are okay -void ec_GFp_nistp_recode_scalar_bits(crypto_word_t *sign, crypto_word_t *digit, - crypto_word_t in) { +void bssl::ec_GFp_nistp_recode_scalar_bits(crypto_word_t *sign, + crypto_word_t *digit, + crypto_word_t in) { crypto_word_t s, d; s = ~((in >> 5) - 1); /* sets all bits to MSB(in), 'in' seen as diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/wnaf.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/wnaf.cc.inc index 0bc78a52..a3d5f30d 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/wnaf.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ec/wnaf.cc.inc @@ -1,35 +1,43 @@ -/* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. - * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. +// +// 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 "../../internal.h" #include "../bn/internal.h" #include "internal.h" +using namespace bssl; + // This file implements the wNAF-based interleaving multi-exponentiation method // at: // http://link.springer.com/chapter/10.1007%2F3-540-45537-X_13 // http://www.bmoeller.de/pdf/TI-01-08.multiexp.pdf -void ec_compute_wNAF(const EC_GROUP *group, int8_t *out, - const EC_SCALAR *scalar, size_t bits, int w) { +void bssl::ec_compute_wNAF(const EC_GROUP *group, int8_t *out, + const EC_SCALAR *scalar, size_t bits, int w) { // 'int8_t' can represent integers with absolute values less than 2^7. assert(0 < w && w <= 7); assert(bits != 0); @@ -77,8 +85,8 @@ void ec_compute_wNAF(const EC_GROUP *group, int8_t *out, out[j] = digit; - // Incorporate the next bit. Previously, |window_val| <= |next_bit|, so if - // we shift and add at most one copy of |bit|, this will continue to hold + // Incorporate the next bit. Previously, `window_val` <= `next_bit`, so if + // we shift and add at most one copy of `bit`, this will continue to hold // afterwards. window_val >>= 1; window_val += bit * bn_is_bit_set_words(scalar->words, group->order.N.width, @@ -90,7 +98,7 @@ void ec_compute_wNAF(const EC_GROUP *group, int8_t *out, assert(window_val == 0); } -// compute_precomp sets |out[i]| to (2*i+1)*p, for i from 0 to |len|. +// compute_precomp sets `out[i]` to (2*i+1)*p, for i from 0 to `len`. static void compute_precomp(const EC_GROUP *group, EC_JACOBIAN *out, const EC_JACOBIAN *p, size_t len) { ec_GFp_simple_point_copy(&out[0], p); @@ -112,20 +120,20 @@ static void lookup_precomp(const EC_GROUP *group, EC_JACOBIAN *out, } } -// EC_WNAF_WINDOW_BITS is the window size to use for |ec_GFp_mont_mul_public|. +// EC_WNAF_WINDOW_BITS is the window size to use for `ec_GFp_mont_mul_public`. #define EC_WNAF_WINDOW_BITS 4 -// EC_WNAF_TABLE_SIZE is the table size to use for |ec_GFp_mont_mul_public|. +// EC_WNAF_TABLE_SIZE is the table size to use for `ec_GFp_mont_mul_public`. #define EC_WNAF_TABLE_SIZE (1 << (EC_WNAF_WINDOW_BITS - 1)) // EC_WNAF_STACK is the number of points worth of data to stack-allocate and // avoid a malloc. #define EC_WNAF_STACK 3 -int ec_GFp_mont_mul_public_batch(const EC_GROUP *group, EC_JACOBIAN *r, - const EC_SCALAR *g_scalar, - const EC_JACOBIAN *points, - const EC_SCALAR *scalars, size_t num) { +int bssl::ec_GFp_mont_mul_public_batch(const EC_GROUP *group, EC_JACOBIAN *r, + const EC_SCALAR *g_scalar, + const EC_JACOBIAN *points, + const EC_SCALAR *scalars, size_t num) { size_t bits = EC_GROUP_order_bits(group); size_t wNAF_len = bits + 1; @@ -134,8 +142,8 @@ int ec_GFp_mont_mul_public_batch(const EC_GROUP *group, EC_JACOBIAN *r, EC_JACOBIAN precomp_stack[EC_WNAF_STACK][EC_WNAF_TABLE_SIZE]; // Allocated pointers, which will remain NULL unless needed. - EC_JACOBIAN(*precomp_alloc)[EC_WNAF_TABLE_SIZE] = NULL; - int8_t(*wNAF_alloc)[EC_MAX_BYTES * 8 + 1] = NULL; + EC_JACOBIAN(*precomp_alloc)[EC_WNAF_TABLE_SIZE] = nullptr; + int8_t (*wNAF_alloc)[EC_MAX_BYTES * 8 + 1] = nullptr; // These fields point either to the stack or heap buffers of the same name. int8_t(*wNAF)[EC_MAX_BYTES * 8 + 1]; @@ -147,12 +155,12 @@ int ec_GFp_mont_mul_public_batch(const EC_GROUP *group, EC_JACOBIAN *r, } else { wNAF_alloc = reinterpret_cast( OPENSSL_calloc(num, sizeof(wNAF_alloc[0]))); - if (wNAF_alloc == NULL) { + if (wNAF_alloc == nullptr) { return 0; } precomp_alloc = reinterpret_cast( OPENSSL_calloc(num, sizeof(precomp_alloc[0]))); - if (precomp_alloc == NULL) { + if (precomp_alloc == nullptr) { OPENSSL_free(wNAF_alloc); return 0; } @@ -163,15 +171,15 @@ int ec_GFp_mont_mul_public_batch(const EC_GROUP *group, EC_JACOBIAN *r, int8_t g_wNAF[EC_MAX_BYTES * 8 + 1]; EC_JACOBIAN g_precomp[EC_WNAF_TABLE_SIZE]; - assert(wNAF_len <= OPENSSL_ARRAY_SIZE(g_wNAF)); + assert(wNAF_len <= std::size(g_wNAF)); const EC_JACOBIAN *g = &group->generator.raw; - if (g_scalar != NULL) { + if (g_scalar != nullptr) { ec_compute_wNAF(group, g_wNAF, g_scalar, bits, EC_WNAF_WINDOW_BITS); compute_precomp(group, g_precomp, g, EC_WNAF_TABLE_SIZE); } for (size_t i = 0; i < num; i++) { - assert(wNAF_len <= OPENSSL_ARRAY_SIZE(wNAF[i])); + assert(wNAF_len <= std::size(wNAF[i])); ec_compute_wNAF(group, wNAF[i], &scalars[i], bits, EC_WNAF_WINDOW_BITS); compute_precomp(group, precomp[i], &points[i], EC_WNAF_TABLE_SIZE); } @@ -183,7 +191,7 @@ int ec_GFp_mont_mul_public_batch(const EC_GROUP *group, EC_JACOBIAN *r, ec_GFp_mont_dbl(group, r, r); } - if (g_scalar != NULL && g_wNAF[k] != 0) { + if (g_scalar != nullptr && g_wNAF[k] != 0) { lookup_precomp(group, &tmp, g_precomp, g_wNAF[k]); if (r_is_at_infinity) { ec_GFp_simple_point_copy(r, &tmp); diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ecdh/ecdh.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/ecdh/ecdh.cc.inc index 9cd8363e..c893641b 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ecdh/ecdh.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ecdh/ecdh.cc.inc @@ -1,12 +1,17 @@ -/* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. - * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. +// +// 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 @@ -18,21 +23,24 @@ #include #include "../../internal.h" +#include "../bcm_interface.h" #include "../ec/internal.h" #include "../service_indicator/internal.h" +using namespace bssl; + int ECDH_compute_key_fips(uint8_t *out, size_t out_len, const EC_POINT *pub_key, const EC_KEY *priv_key) { boringssl_ensure_ecc_self_test(); - if (priv_key->priv_key == NULL) { + if (FromOpaque(priv_key)->priv_key == nullptr) { OPENSSL_PUT_ERROR(ECDH, ECDH_R_NO_PRIVATE_VALUE); return 0; } - const EC_SCALAR *const priv = &priv_key->priv_key->scalar; + const EC_SCALAR *const priv = &FromOpaque(priv_key)->priv_key->scalar; const EC_GROUP *const group = EC_KEY_get0_group(priv_key); - if (EC_GROUP_cmp(group, pub_key->group, NULL) != 0) { + if (EC_GROUP_cmp(group, pub_key->group, nullptr) != 0) { OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ecdsa/ecdsa.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/ecdsa/ecdsa.cc.inc index 920cbec1..08946a60 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ecdsa/ecdsa.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ecdsa/ecdsa.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,13 +22,16 @@ #include #include "../../internal.h" +#include "../bcm_interface.h" #include "../bn/internal.h" #include "../ec/internal.h" #include "../service_indicator/internal.h" #include "internal.h" -// digest_to_scalar interprets |digest_len| bytes from |digest| as a scalar for +using namespace bssl; + +// digest_to_scalar interprets `digest_len` bytes from `digest` as a scalar for // ECDSA. static void digest_to_scalar(const EC_GROUP *group, EC_SCALAR *out, const uint8_t *digest, size_t digest_len) { @@ -41,8 +49,8 @@ static void digest_to_scalar(const EC_GROUP *group, EC_SCALAR *out, bn_rshift_words(out->words, out->words, 8 - (num_bits & 0x7), order->width); } - // |out| now has the same bit width as |order|, but this only bounds by - // 2*|order|. Subtract the order if out of range. + // `out` now has the same bit width as `order`, but this only bounds by + // 2*`order`. Subtract the order if out of range. // // Montgomery multiplication accepts the looser bounds, so this isn't strictly // necessary, but it is a cleaner abstraction and has no performance impact. @@ -51,12 +59,12 @@ static void digest_to_scalar(const EC_GROUP *group, EC_SCALAR *out, order->width); } -int ecdsa_verify_fixed_no_self_test(const uint8_t *digest, size_t digest_len, - const uint8_t *sig, size_t sig_len, - const EC_KEY *eckey) { +int bssl::ecdsa_verify_fixed_no_self_test(const uint8_t *digest, + size_t digest_len, const uint8_t *sig, + size_t sig_len, const EC_KEY *eckey) { const EC_GROUP *group = EC_KEY_get0_group(eckey); const EC_POINT *pub_key = EC_KEY_get0_public_key(eckey); - if (group == NULL || pub_key == NULL || sig == NULL) { + if (group == nullptr || pub_key == nullptr || sig == nullptr) { OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_MISSING_PARAMETERS); return 0; } @@ -81,8 +89,8 @@ int ecdsa_verify_fixed_no_self_test(const uint8_t *digest, size_t digest_len, // u1 = m * s^-1 mod order // u2 = r * s^-1 mod order // - // |s_inv_mont| is in Montgomery form while |m| and |r| are not, so |u1| and - // |u2| will be taken out of Montgomery form, as desired. + // `s_inv_mont` is in Montgomery form while `m` and `r` are not, so `u1` and + // `u2` will be taken out of Montgomery form, as desired. digest_to_scalar(group, &m, digest, digest_len); ec_scalar_mul_montgomery(group, &u1, &m, &s_inv_mont); ec_scalar_mul_montgomery(group, &u2, &r, &s_inv_mont); @@ -101,8 +109,9 @@ int ecdsa_verify_fixed_no_self_test(const uint8_t *digest, size_t digest_len, return 1; } -int ecdsa_verify_fixed(const uint8_t *digest, size_t digest_len, - const uint8_t *sig, size_t sig_len, const EC_KEY *key) { +int bssl::ecdsa_verify_fixed(const uint8_t *digest, size_t digest_len, + const uint8_t *sig, size_t sig_len, + const EC_KEY *key) { boringssl_ensure_ecc_self_test(); return ecdsa_verify_fixed_no_self_test(digest, digest_len, sig, sig_len, key); @@ -114,14 +123,7 @@ static int ecdsa_sign_impl(const EC_GROUP *group, int *out_retry, uint8_t *sig, const uint8_t *digest, size_t digest_len) { *out_retry = 0; - // Check that the size of the group order is FIPS compliant (FIPS 186-4 - // B.5.2). const BIGNUM *order = EC_GROUP_get0_order(group); - if (BN_num_bits(order) < 160) { - OPENSSL_PUT_ERROR(EC, EC_R_INVALID_GROUP_ORDER); - return 0; - } - size_t sig_len = 2 * BN_num_bytes(order); if (sig_len > max_sig_len) { OPENSSL_PUT_ERROR(EC, EC_R_BUFFER_TOO_SMALL); @@ -142,7 +144,7 @@ static int ecdsa_sign_impl(const EC_GROUP *group, int *out_retry, uint8_t *sig, } // s = priv_key * r. Note if only one parameter is in the Montgomery domain, - // |ec_scalar_mod_mul_montgomery| will compute the answer in the normal + // `ec_scalar_mod_mul_montgomery` will compute the answer in the normal // domain. EC_SCALAR s; ec_scalar_to_montgomery(group, &s, &r); @@ -154,13 +156,13 @@ static int ecdsa_sign_impl(const EC_GROUP *group, int *out_retry, uint8_t *sig, ec_scalar_add(group, &s, &s, &tmp); // s = k^-1 * (m + priv_key * r). First, we compute k^-1 in the Montgomery - // domain. This is |ec_scalar_to_montgomery| followed by - // |ec_scalar_inv0_montgomery|, but |ec_scalar_inv0_montgomery| followed by - // |ec_scalar_from_montgomery| is equivalent and slightly more efficient. + // domain. This is `ec_scalar_to_montgomery` followed by + // `ec_scalar_inv0_montgomery`, but `ec_scalar_inv0_montgomery` followed by + // `ec_scalar_from_montgomery` is equivalent and slightly more efficient. // Then, as above, only one parameter is in the Montgomery domain, so the // result is in the normal domain. Finally, note k is non-zero (or computing r // would fail), so the inverse must exist. - ec_scalar_inv0_montgomery(group, &tmp, k); // tmp = k^-1 R^2 + ec_scalar_inv0_montgomery(group, &tmp, k); // tmp = k^-1 R² ec_scalar_from_montgomery(group, &tmp, &tmp); // tmp = k^-1 R ec_scalar_mul_montgomery(group, &s, &s, &tmp); if (constant_time_declassify_int(ec_scalar_is_zero(group, &s))) { @@ -179,21 +181,23 @@ static int ecdsa_sign_impl(const EC_GROUP *group, int *out_retry, uint8_t *sig, return 1; } -int ecdsa_sign_fixed_with_nonce_for_known_answer_test( +int bssl::ecdsa_sign_fixed_with_nonce_for_known_answer_test( const uint8_t *digest, size_t digest_len, uint8_t *sig, size_t *out_sig_len, size_t max_sig_len, const EC_KEY *eckey, const uint8_t *nonce, size_t nonce_len) { - if (eckey->ecdsa_meth && eckey->ecdsa_meth->sign) { + const ECKey *impl = FromOpaque(eckey); + + if (impl->ecdsa_meth && impl->ecdsa_meth->sign) { OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_NOT_IMPLEMENTED); return 0; } - const EC_GROUP *group = EC_KEY_get0_group(eckey); - if (group == NULL || eckey->priv_key == NULL) { + const EC_GROUP *group = EC_KEY_get0_group(impl); + if (group == nullptr || impl->priv_key == nullptr) { OPENSSL_PUT_ERROR(ECDSA, ERR_R_PASSED_NULL_PARAMETER); return 0; } - const EC_SCALAR *priv_key = &eckey->priv_key->scalar; + const EC_SCALAR *priv_key = &impl->priv_key->scalar; EC_SCALAR k; if (!ec_scalar_from_bytes(group, &k, nonce, nonce_len)) { @@ -204,33 +208,44 @@ int ecdsa_sign_fixed_with_nonce_for_known_answer_test( priv_key, &k, digest, digest_len); } -int ecdsa_sign_fixed(const uint8_t *digest, size_t digest_len, uint8_t *sig, - size_t *out_sig_len, size_t max_sig_len, - const EC_KEY *eckey) { +int bssl::ecdsa_sign_fixed(const uint8_t *digest, size_t digest_len, + uint8_t *sig, size_t *out_sig_len, + size_t max_sig_len, const EC_KEY *eckey) { + const ECKey *impl = FromOpaque(eckey); + boringssl_ensure_ecc_self_test(); - if (eckey->ecdsa_meth && eckey->ecdsa_meth->sign) { + if (impl->ecdsa_meth && impl->ecdsa_meth->sign) { OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_NOT_IMPLEMENTED); return 0; } - const EC_GROUP *group = EC_KEY_get0_group(eckey); - if (group == NULL || eckey->priv_key == NULL) { + const EC_GROUP *group = EC_KEY_get0_group(impl); + if (group == nullptr || impl->priv_key == nullptr) { OPENSSL_PUT_ERROR(ECDSA, ERR_R_PASSED_NULL_PARAMETER); return 0; } const BIGNUM *order = EC_GROUP_get0_order(group); - const EC_SCALAR *priv_key = &eckey->priv_key->scalar; + const EC_SCALAR *priv_key = &impl->priv_key->scalar; + + // Generate the ECDSA per-message secret number by rejection sampling. This + // function implements FIPS 186-5, A.3.2, repeating the process on failure. + + // Check the group order is large enough. See step 1 of FIPS 186-5, A.3.2. + if (BN_num_bits(order) < 224) { + OPENSSL_PUT_ERROR(EC, EC_R_INVALID_GROUP_ORDER); + return 0; + } // Pass a SHA512 hash of the private key and digest as additional data // into the RBG. This is a hardening measure against entropy failure. - static_assert(BCM_SHA512_DIGEST_LENGTH >= 32, + static_assert(SHA512_DIGEST_LENGTH >= 32, "additional_data is too large for SHA-512"); FIPS_service_indicator_lock_state(); SHA512_CTX sha; - uint8_t additional_data[BCM_SHA512_DIGEST_LENGTH]; + uint8_t additional_data[SHA512_DIGEST_LENGTH]; BCM_sha512_init(&sha); BCM_sha512_update(&sha, priv_key->words, order->width * sizeof(BN_ULONG)); BCM_sha512_update(&sha, digest, digest_len); @@ -249,7 +264,7 @@ int ecdsa_sign_fixed(const uint8_t *digest, size_t digest_len, uint8_t *sig, goto out; } - // TODO(davidben): Move this inside |ec_random_nonzero_scalar| or lower, so + // TODO(davidben): Move this inside `ec_random_nonzero_scalar` or lower, so // that all scalars we generate are, by default, secret. CONSTTIME_SECRET(k.words, sizeof(k.words)); diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/ecdsa/internal.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/ecdsa/internal.h index 2b6527ee..02912bbd 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/ecdsa/internal.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/ecdsa/internal.h @@ -1,16 +1,16 @@ -/* Copyright 2021 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2021 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. #ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_ECDSA_INTERNAL_H #define OPENSSL_HEADER_CRYPTO_FIPSMODULE_ECDSA_INTERNAL_H @@ -19,30 +19,28 @@ #include "../ec/internal.h" -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN // ECDSA_MAX_FIXED_LEN is the maximum length of an ECDSA signature in the // fixed-width, big-endian format from IEEE P1363. #define ECDSA_MAX_FIXED_LEN (2 * EC_MAX_BYTES) -// ecdsa_sign_fixed behaves like |ECDSA_sign| but uses the fixed-width, +// ecdsa_sign_fixed behaves like `ECDSA_sign` but uses the fixed-width, // big-endian format from IEEE P1363. int ecdsa_sign_fixed(const uint8_t *digest, size_t digest_len, uint8_t *sig, size_t *out_sig_len, size_t max_sig_len, const EC_KEY *key); // ecdsa_sign_fixed_with_nonce_for_known_answer_test behaves like -// |ecdsa_sign_fixed| but takes a caller-supplied nonce. This function is used +// `ecdsa_sign_fixed` but takes a caller-supplied nonce. This function is used // as part of known-answer tests in the FIPS module. int ecdsa_sign_fixed_with_nonce_for_known_answer_test( const uint8_t *digest, size_t digest_len, uint8_t *sig, size_t *out_sig_len, size_t max_sig_len, const EC_KEY *key, const uint8_t *nonce, size_t nonce_len); -// ecdsa_verify_fixed behaves like |ECDSA_verify| but uses the fixed-width, +// ecdsa_verify_fixed behaves like `ECDSA_verify` but uses the fixed-width, // big-endian format from IEEE P1363. int ecdsa_verify_fixed(const uint8_t *digest, size_t digest_len, const uint8_t *sig, size_t sig_len, const EC_KEY *key); @@ -54,9 +52,6 @@ int ecdsa_verify_fixed_no_self_test(const uint8_t *digest, size_t digest_len, const uint8_t *sig, size_t sig_len, const EC_KEY *key); - -#if defined(__cplusplus) -} -#endif +BSSL_NAMESPACE_END #endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_ECDSA_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/entropy/internal.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/entropy/internal.h new file mode 100644 index 00000000..d27903fb --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/entropy/internal.h @@ -0,0 +1,38 @@ +// Copyright 2025 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. + +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_ENTROPY_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_ENTROPY_INTERNAL_H + +#include + +#if defined(OPENSSL_LINUX) || defined(OPENSSL_MACOS) + +BSSL_NAMESPACE_BEGIN +namespace entropy { + +// GetSeed fills `out` with random bytes from the jitter source. +OPENSSL_EXPORT bool GetSeed(uint8_t out[48]); + +// GetSamples fetches `n` raw delta time samples. +OPENSSL_EXPORT bool GetSamples(uint64_t *out, size_t n); + +// GetVersion returns the version of the entropy module. +int GetVersion(); + +} // namespace entropy +BSSL_NAMESPACE_END + +#endif // LINUX || MACOS +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_ENTROPY_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/entropy/jitter.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/entropy/jitter.cc.inc new file mode 100644 index 00000000..a71cad79 --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/entropy/jitter.cc.inc @@ -0,0 +1,463 @@ +// Copyright 2025 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. + +// BoringCrypto Jitter Entropy version 20250725. + +#include + +#if defined(OPENSSL_LINUX) || defined(OPENSSL_MACOS) + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include "internal.h" +#include "sha512.cc.inc" + +#if defined(__x86_64__) +#include +#endif + + +BSSL_NAMESPACE_BEGIN +namespace entropy { +namespace { + +#if defined(__x86_64__) +static uint64_t GetTimestamp() { return _rdtsc(); } +#elif defined(__aarch64__) +static uint64_t GetTimestamp() { + // Ideally this would use __arm_rsr64 from . Clang has supported + // it Clang 3.7 (2016), but GCC did not add it until GCC 14.1.0 (2024). See + // https://crbug.com/440670941. When our minimum GCC is past that point, + // switch this back to __arm_rsr64. + uint64_t ret; + __asm__ volatile("mrs %0, cntvct_el0" : "=r"(ret)); + return ret; +} +#else +static uint64_t GetTimestamp() { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC_RAW, &ts); + return ts.tv_sec * 1000000000ULL + ts.tv_nsec; +} +#endif + +class MemoryOffsetLCG { + public: + MemoryOffsetLCG() : state(GetTimestamp() & 0xFFFFFFFF) {} + uint32_t Next() { + state = state * 1664525 + 1013904223; + return state; + } + + private: + uint32_t state; +}; + +class MemoryAccessSampler { + public: + MemoryAccessSampler(size_t array_size, unsigned num_samples) + : array_size_(array_size), + num_samples_(num_samples), + array_(reinterpret_cast(OPENSSL_malloc(array_size_))) { + if (array_ == nullptr || // + array_size_ == 0 || // + array_size_ > (1u << 26) || // + array_size_ & (array_size_ - 1)) { + abort(); + } + } + + ~MemoryAccessSampler() { OPENSSL_free(const_cast(array_)); } + + MemoryAccessSampler(const MemoryAccessSampler &) = delete; + MemoryAccessSampler &operator=(const MemoryAccessSampler &) = delete; + + MemoryAccessSampler(MemoryAccessSampler &&other) + : array_size_(other.array_size_), + num_samples_(other.num_samples_), + lcg_(other.lcg_), + array_(other.array_) { + other.array_ = nullptr; + } + + 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; + } + + *out = GetTimestamp(); + return true; + } + + private: + const size_t array_size_; + const unsigned num_samples_; + MemoryOffsetLCG lcg_; + volatile uint8_t *array_; +}; + +template +class DeltaSampler { + public: + explicit DeltaSampler(T &&sub_sampler) + : sub_sampler_(std::forward(sub_sampler)) {} + + // Next function to return the delta between two subsequent samples + bool Next(uint64_t *out) { + uint64_t sample; + if (!sub_sampler_.Next(&sample)) { + return false; + } + + if (!initialized_) { + last_sample_ = sample; + if (!sub_sampler_.Next(&sample)) { + return false; + } + initialized_ = true; + } + + *out = sample - last_sample_; + last_sample_ = sample; + return true; + } + + private: + bool initialized_ = false; + T sub_sampler_; + uint64_t last_sample_ = 0; +}; + +template +DeltaSampler(U &&sub_sampler) -> DeltaSampler>; + +template +class MaskSampler { + public: + explicit MaskSampler(uint8_t mask, T &&sub_sampler) + : mask_(mask), sub_sampler_(std::forward(sub_sampler)) {} + + bool Next(uint8_t *out) { + uint64_t sample; + if (!sub_sampler_.Next(&sample)) { + return false; + } + + *out = sample & mask_; + return true; + } + + private: + const uint8_t mask_; + T sub_sampler_; +}; + +template +MaskSampler(uint8_t mask, U &&sub_sampler) -> MaskSampler>; + +// The estimated entropy per sample from MaskSampler. +constexpr float kH = 0.8; + +// kAlphaLog2 is log_2(alpha), where alpha is the standard false-positive +// probability from SP 800-90B. +static constexpr float kAlphaLog2 = -20; +// kAlpha is the variable of the same name from section 4.4.1 of SP 800-90B. +constexpr float kAlpha = 1.0 / (1 << static_cast(-kAlphaLog2)); + +// Ceil rounds up its non-negative argument to the next integer. (std::ceil +// isn't constexpr until C++23.) +constexpr unsigned Ceil(float val) { + auto truncated = static_cast(val); + if (val == static_cast(truncated)) { + return truncated; + } + if (val > 0) { + return truncated + 1; + } + __builtin_unreachable(); +} + +template +class RepetitionCountTest { + public: + static constexpr unsigned kThreshold = 1 + Ceil(-kAlphaLog2 / kH); + static_assert(kThreshold == 26); + + explicit RepetitionCountTest(T &&sub_sampler) + : sub_sampler_(std::forward(sub_sampler)) {} + + bool Next(uint8_t *out) { + uint8_t sample; + if (!sub_sampler_.Next(&sample)) { + return false; + } + if (sample == last_sample_) { + count_++; + } else { + count_ = 1; + last_sample_ = sample; + } + if (count_ >= kThreshold) { + return false; + } + *out = sample; + return true; + } + + private: + T sub_sampler_; + unsigned count_ = 0; + uint8_t last_sample_ = 0; +}; + +template +RepetitionCountTest(U &&sub_sampler) -> RepetitionCountTest>; + +constexpr double BinomialPMF(int64_t k, int64_t n, double p) { + if (k < 0 || k > n) { + return 0.0; + } + + double result = 1.0; + for (int64_t i = 0; i < k; ++i) { + result *= (n - i); + result /= (i + 1); + } + + for (int64_t i = 0; i < k; ++i) { + result *= p; + } + for (int64_t i = 0; i < n - k; ++i) { + result *= (1 - p); + } + + return result; +} + +// CritBinom implements the Excel function of the same name. +constexpr unsigned CritBinom(unsigned trials, double probability_s, + double alpha) { + if (probability_s < 0.0 || probability_s > 1.0 || alpha < 0.0 || + alpha > 1.0) { + __builtin_unreachable(); + } + + double cumulative = 0.0; + for (unsigned k = 0; k <= trials; ++k) { + cumulative += BinomialPMF(k, trials, probability_s); + if (cumulative >= alpha) { + return k; + } + } + + return trials; +} + +// ExpTaylor calculates eˣ using the Taylor series: eˣ = 1 + x + x²/2! + +// x³/3! + ... +constexpr double ExpTaylor(double x) { + double sum = 1.0; + double term = 1.0; + + for (int i = 1; i < 25; ++i) { + term *= x / i; + sum += term; + } + + return sum; +} + +// Power2 calculates 2^exp by calculating e^(ln(2) * exp) = e^(ln(2)) ^ exp = +// 2^exp. (std::pow isn't constexpr until C++26.) +constexpr double Power2(double exp) { + constexpr double ln2 = 0.693147180559945309417232121458; + return ExpTaylor(exp * ln2); +} + +// AdaptiveProportionTestCutoff implements the function from the footnote on +// page 27 of SP 800-90B. +constexpr unsigned AdaptiveProportionTestCutoff(unsigned W, float H, + float alpha) { + return 1 + CritBinom(W, Power2(-H), 1.0 - alpha); +} + +// These are the example values from table 2 of SP 800-90B, to show that +// we're calculating the values correctly. +static_assert(AdaptiveProportionTestCutoff(512, 0.5, kAlpha) == 410); +static_assert(AdaptiveProportionTestCutoff(512, 1, kAlpha) == 311); +static_assert(AdaptiveProportionTestCutoff(512, 2, kAlpha) == 177); +static_assert(AdaptiveProportionTestCutoff(512, 4, kAlpha) == 62); +static_assert(AdaptiveProportionTestCutoff(512, 8, kAlpha) == 13); + +template +class AdaptiveProportionTest { + public: + // The size of the sliding window, representing the number of recent samples + // to analyze. + static constexpr unsigned kWindowSize = 512; + + // The maximum number of times any single byte value is allowed to appear + // within the sliding window. + static constexpr unsigned kThreshold = + AdaptiveProportionTestCutoff(kWindowSize, kH, kAlpha); + static_assert(kThreshold == 348); + + explicit AdaptiveProportionTest(T &&sub_sampler) + : sub_sampler_(std::forward(sub_sampler)) { + counts_.fill(0); + } + + bool Next(uint8_t *out) { + uint8_t sample; + if (!sub_sampler_.Next(&sample)) { + return false; + } + *out = sample; + + if (samples_processed_ >= kWindowSize) { + const uint8_t evicted_sample = buffer_[buffer_idx_]; + counts_[evicted_sample]--; + } + + buffer_[buffer_idx_] = sample; + const uint16_t new_count = ++counts_[sample]; + + if (new_count > kThreshold) { + return false; + } + + buffer_idx_ = (buffer_idx_ + 1) % kWindowSize; + samples_processed_++; + + return true; + } + + private: + T sub_sampler_; + + // A circular buffer to store the most recent `kWindowSize` samples. + std::array buffer_{}; + + // An array to store the frequency counts of each possible byte value (0-255) + // within the current window. + std::array counts_{}; + + // The current index for writing into the circular buffer. + size_t buffer_idx_ = 0; + + // The total number of samples processed. Used to determine when the buffer + // is full and eviction should begin. + size_t samples_processed_ = 0; +}; + +template +AdaptiveProportionTest(U &&sub_sampler) + -> AdaptiveProportionTest>; + +template +class SeedSampler { + public: + // NIST requires 1024 samples at start-up time. This code is structured so + // that the entropy generator is considered to be starting afresh for each + // seed. + static constexpr unsigned kNumSamples = 1024; + + explicit SeedSampler(T &&sub_sampler) + : sub_sampler_(std::forward(sub_sampler)) {} + + bool Next(uint8_t out_seed[48]) { + // HMAC-SHA384 `kNumSamples` samples with an all-zero key: + SHA512_CTX ctx; + SHA384_Init(&ctx); + + uint8_t block[kSHA384Block]; + memset(block, 0x36, sizeof(block)); + SHA384_Update(&ctx, block, sizeof(block)); + + static_assert(kNumSamples % sizeof(block) == 0); + for (unsigned i = 0; i < kNumSamples / sizeof(block); i++) { + for (unsigned j = 0; j < sizeof(block); j++) { + if (!sub_sampler_.Next(&block[j])) { + return false; + } + } + SHA384_Update(&ctx, block, sizeof(block)); + } + + SHA384_Final(out_seed, &ctx); + + SHA384_Init(&ctx); + memset(block, 0x5c, sizeof(block)); + SHA384_Update(&ctx, block, sizeof(block)); + SHA384_Update(&ctx, out_seed, kSHA384DigestLength); + SHA384_Final(out_seed, &ctx); + + return true; + } + + private: + T sub_sampler_; +}; + +template +SeedSampler(U &&sub_sampler) -> SeedSampler>; + +constexpr size_t kMemorySize = 1u << 25; +constexpr size_t kMemoryAccessesPerSample = 16; +constexpr size_t kBitsPerSample = 8; +constexpr uint8_t kMask = (1u << kBitsPerSample) - 1; + +} // namespace + +int GetVersion() { return 20250725; } + +bool GetSeed(uint8_t out[48]) { + auto sampler(SeedSampler(AdaptiveProportionTest(RepetitionCountTest( + MaskSampler(kMask, DeltaSampler(MemoryAccessSampler( + kMemorySize, kMemoryAccessesPerSample))))))); + return sampler.Next(out); +} + +bool GetSamples(uint64_t *out, size_t n) { + auto sampler( + DeltaSampler(MemoryAccessSampler(kMemorySize, kMemoryAccessesPerSample))); + for (size_t i = 0; i < n; i++) { + if (!sampler.Next(&out[i])) { + return false; + } + } + return true; +} + +} // namespace entropy +BSSL_NAMESPACE_END + +#endif // LINUX || MACOS diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/entropy/sha512.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/entropy/sha512.cc.inc new file mode 100644 index 00000000..32fc4620 --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/entropy/sha512.cc.inc @@ -0,0 +1,329 @@ +// Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 + + +// This is a copy of the SHA-384 code for the purpose of isolating the jitter +// entropy source certification from any changes to the normal implementation. + +BSSL_NAMESPACE_BEGIN +namespace entropy { +namespace { + +constexpr size_t kSHA384Block = 128; +constexpr size_t kSHA384DigestLength = (384 / 8); + +struct SHA512_CTX { + uint64_t h[8]; + uint64_t Nl, Nh; + uint8_t p[kSHA384Block]; + unsigned num, md_len; +}; + +uint64_t CRYPTO_bswap8(uint64_t x) { return __builtin_bswap64(x); } + +uint64_t CRYPTO_load_u64_be(const void *ptr) { + uint64_t ret; + memcpy(&ret, ptr, sizeof(ret)); + return CRYPTO_bswap8(ret); +} + +void CRYPTO_store_u64_be(void *out, uint64_t v) { + v = CRYPTO_bswap8(v); + memcpy(out, &v, sizeof(v)); +} + +uint64_t CRYPTO_rotr_u64(uint64_t value, int shift) { + return (value >> shift) | (value << ((-shift) & 63)); +} + +void sha512_update(SHA512_CTX *c, const void *in_data, size_t len); +void sha512_final_impl(uint8_t *out, size_t md_len, SHA512_CTX *sha); + +void SHA384_Init(SHA512_CTX *sha) { + sha->h[0] = UINT64_C(0xcbbb9d5dc1059ed8); + sha->h[1] = UINT64_C(0x629a292a367cd507); + sha->h[2] = UINT64_C(0x9159015a3070dd17); + sha->h[3] = UINT64_C(0x152fecd8f70e5939); + sha->h[4] = UINT64_C(0x67332667ffc00b31); + sha->h[5] = UINT64_C(0x8eb44a8768581511); + sha->h[6] = UINT64_C(0xdb0c2e0d64f98fa7); + sha->h[7] = UINT64_C(0x47b5481dbefa4fa4); + + sha->Nl = 0; + sha->Nh = 0; + sha->num = 0; + sha->md_len = kSHA384DigestLength; + return; +} + +void SHA384_Final(uint8_t out[kSHA384DigestLength], SHA512_CTX *sha) { + // This function must be paired with `SHA384_Init`, which sets + // `sha->md_len` to `kSHA384DigestLength`. + sha512_final_impl(out, kSHA384DigestLength, sha); + return; +} + +void SHA384_Update(SHA512_CTX *sha, const void *data, size_t len) { + return sha512_update(sha, data, len); +} + +void sha512_block_data_order(uint64_t state[8], const uint8_t *in, + size_t num_blocks); + +void sha512_final_impl(uint8_t *out, size_t md_len, SHA512_CTX *sha) { + uint8_t *p = sha->p; + size_t n = sha->num; + + p[n] = 0x80; // There always is a room for one + n++; + if (n > (sizeof(sha->p) - 16)) { + memset(p + n, 0, sizeof(sha->p) - n); + n = 0; + sha512_block_data_order(sha->h, p, 1); + } + + memset(p + n, 0, sizeof(sha->p) - 16 - n); + CRYPTO_store_u64_be(p + sizeof(sha->p) - 16, sha->Nh); + CRYPTO_store_u64_be(p + sizeof(sha->p) - 8, sha->Nl); + + sha512_block_data_order(sha->h, p, 1); + + const size_t out_words = md_len / 8; + for (size_t i = 0; i < out_words; i++) { + CRYPTO_store_u64_be(out, sha->h[i]); + out += 8; + } +} + +const uint64_t K512[80] = { + UINT64_C(0x428a2f98d728ae22), UINT64_C(0x7137449123ef65cd), + UINT64_C(0xb5c0fbcfec4d3b2f), UINT64_C(0xe9b5dba58189dbbc), + UINT64_C(0x3956c25bf348b538), UINT64_C(0x59f111f1b605d019), + UINT64_C(0x923f82a4af194f9b), UINT64_C(0xab1c5ed5da6d8118), + UINT64_C(0xd807aa98a3030242), UINT64_C(0x12835b0145706fbe), + UINT64_C(0x243185be4ee4b28c), UINT64_C(0x550c7dc3d5ffb4e2), + UINT64_C(0x72be5d74f27b896f), UINT64_C(0x80deb1fe3b1696b1), + UINT64_C(0x9bdc06a725c71235), UINT64_C(0xc19bf174cf692694), + UINT64_C(0xe49b69c19ef14ad2), UINT64_C(0xefbe4786384f25e3), + UINT64_C(0x0fc19dc68b8cd5b5), UINT64_C(0x240ca1cc77ac9c65), + UINT64_C(0x2de92c6f592b0275), UINT64_C(0x4a7484aa6ea6e483), + UINT64_C(0x5cb0a9dcbd41fbd4), UINT64_C(0x76f988da831153b5), + UINT64_C(0x983e5152ee66dfab), UINT64_C(0xa831c66d2db43210), + UINT64_C(0xb00327c898fb213f), UINT64_C(0xbf597fc7beef0ee4), + UINT64_C(0xc6e00bf33da88fc2), UINT64_C(0xd5a79147930aa725), + UINT64_C(0x06ca6351e003826f), UINT64_C(0x142929670a0e6e70), + UINT64_C(0x27b70a8546d22ffc), UINT64_C(0x2e1b21385c26c926), + UINT64_C(0x4d2c6dfc5ac42aed), UINT64_C(0x53380d139d95b3df), + UINT64_C(0x650a73548baf63de), UINT64_C(0x766a0abb3c77b2a8), + UINT64_C(0x81c2c92e47edaee6), UINT64_C(0x92722c851482353b), + UINT64_C(0xa2bfe8a14cf10364), UINT64_C(0xa81a664bbc423001), + UINT64_C(0xc24b8b70d0f89791), UINT64_C(0xc76c51a30654be30), + UINT64_C(0xd192e819d6ef5218), UINT64_C(0xd69906245565a910), + UINT64_C(0xf40e35855771202a), UINT64_C(0x106aa07032bbd1b8), + UINT64_C(0x19a4c116b8d2d0c8), UINT64_C(0x1e376c085141ab53), + UINT64_C(0x2748774cdf8eeb99), UINT64_C(0x34b0bcb5e19b48a8), + UINT64_C(0x391c0cb3c5c95a63), UINT64_C(0x4ed8aa4ae3418acb), + UINT64_C(0x5b9cca4f7763e373), UINT64_C(0x682e6ff3d6b2b8a3), + UINT64_C(0x748f82ee5defb2fc), UINT64_C(0x78a5636f43172f60), + UINT64_C(0x84c87814a1f0ab72), UINT64_C(0x8cc702081a6439ec), + UINT64_C(0x90befffa23631e28), UINT64_C(0xa4506cebde82bde9), + UINT64_C(0xbef9a3f7b2c67915), UINT64_C(0xc67178f2e372532b), + UINT64_C(0xca273eceea26619c), UINT64_C(0xd186b8c721c0c207), + UINT64_C(0xeada7dd6cde0eb1e), UINT64_C(0xf57d4f7fee6ed178), + UINT64_C(0x06f067aa72176fba), UINT64_C(0x0a637dc5a2c898a6), + UINT64_C(0x113f9804bef90dae), UINT64_C(0x1b710b35131c471b), + UINT64_C(0x28db77f523047d84), UINT64_C(0x32caab7b40c72493), + UINT64_C(0x3c9ebe0a15c9bebc), UINT64_C(0x431d67c49c100d4c), + UINT64_C(0x4cc5d4becb3e42b6), UINT64_C(0x597f299cfc657e2a), + UINT64_C(0x5fcb6fab3ad6faec), UINT64_C(0x6c44198c4a475817), +}; + +#define Sigma0(x) \ + (CRYPTO_rotr_u64((x), 28) ^ CRYPTO_rotr_u64((x), 34) ^ \ + CRYPTO_rotr_u64((x), 39)) +#define Sigma1(x) \ + (CRYPTO_rotr_u64((x), 14) ^ CRYPTO_rotr_u64((x), 18) ^ \ + CRYPTO_rotr_u64((x), 41)) +#define sigma0(x) \ + (CRYPTO_rotr_u64((x), 1) ^ CRYPTO_rotr_u64((x), 8) ^ ((x) >> 7)) +#define sigma1(x) \ + (CRYPTO_rotr_u64((x), 19) ^ CRYPTO_rotr_u64((x), 61) ^ ((x) >> 6)) + +#define Ch(x, y, z) (((x) & (y)) ^ ((~(x)) & (z))) +#define Maj(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) + +#define ROUND_00_15(i, a, b, c, d, e, f, g, h) \ + do { \ + T1 += h + Sigma1(e) + Ch(e, f, g) + K512[i]; \ + h = Sigma0(a) + Maj(a, b, c); \ + d += T1; \ + h += T1; \ + } while (0) + +#define ROUND_16_80(i, j, a, b, c, d, e, f, g, h, X) \ + do { \ + s0 = X[(j + 1) & 0x0f]; \ + s0 = sigma0(s0); \ + s1 = X[(j + 14) & 0x0f]; \ + s1 = sigma1(s1); \ + T1 = X[(j) & 0x0f] += s0 + s1 + X[(j + 9) & 0x0f]; \ + ROUND_00_15(i + j, a, b, c, d, e, f, g, h); \ + } while (0) + +void sha512_block_data_order(uint64_t state[8], const uint8_t *in, size_t num) { + uint64_t a, b, c, d, e, f, g, h, s0, s1, T1; + uint64_t X[16]; + int i; + + while (num--) { + a = state[0]; + b = state[1]; + c = state[2]; + d = state[3]; + e = state[4]; + f = state[5]; + g = state[6]; + h = state[7]; + + T1 = X[0] = CRYPTO_load_u64_be(in); + ROUND_00_15(0, a, b, c, d, e, f, g, h); + T1 = X[1] = CRYPTO_load_u64_be(in + 8); + ROUND_00_15(1, h, a, b, c, d, e, f, g); + T1 = X[2] = CRYPTO_load_u64_be(in + 2 * 8); + ROUND_00_15(2, g, h, a, b, c, d, e, f); + T1 = X[3] = CRYPTO_load_u64_be(in + 3 * 8); + ROUND_00_15(3, f, g, h, a, b, c, d, e); + T1 = X[4] = CRYPTO_load_u64_be(in + 4 * 8); + ROUND_00_15(4, e, f, g, h, a, b, c, d); + T1 = X[5] = CRYPTO_load_u64_be(in + 5 * 8); + ROUND_00_15(5, d, e, f, g, h, a, b, c); + T1 = X[6] = CRYPTO_load_u64_be(in + 6 * 8); + ROUND_00_15(6, c, d, e, f, g, h, a, b); + T1 = X[7] = CRYPTO_load_u64_be(in + 7 * 8); + ROUND_00_15(7, b, c, d, e, f, g, h, a); + T1 = X[8] = CRYPTO_load_u64_be(in + 8 * 8); + ROUND_00_15(8, a, b, c, d, e, f, g, h); + T1 = X[9] = CRYPTO_load_u64_be(in + 9 * 8); + ROUND_00_15(9, h, a, b, c, d, e, f, g); + T1 = X[10] = CRYPTO_load_u64_be(in + 10 * 8); + ROUND_00_15(10, g, h, a, b, c, d, e, f); + T1 = X[11] = CRYPTO_load_u64_be(in + 11 * 8); + ROUND_00_15(11, f, g, h, a, b, c, d, e); + T1 = X[12] = CRYPTO_load_u64_be(in + 12 * 8); + ROUND_00_15(12, e, f, g, h, a, b, c, d); + T1 = X[13] = CRYPTO_load_u64_be(in + 13 * 8); + ROUND_00_15(13, d, e, f, g, h, a, b, c); + T1 = X[14] = CRYPTO_load_u64_be(in + 14 * 8); + ROUND_00_15(14, c, d, e, f, g, h, a, b); + T1 = X[15] = CRYPTO_load_u64_be(in + 15 * 8); + ROUND_00_15(15, b, c, d, e, f, g, h, a); + + for (i = 16; i < 80; i += 16) { + ROUND_16_80(i, 0, a, b, c, d, e, f, g, h, X); + ROUND_16_80(i, 1, h, a, b, c, d, e, f, g, X); + ROUND_16_80(i, 2, g, h, a, b, c, d, e, f, X); + ROUND_16_80(i, 3, f, g, h, a, b, c, d, e, X); + ROUND_16_80(i, 4, e, f, g, h, a, b, c, d, X); + ROUND_16_80(i, 5, d, e, f, g, h, a, b, c, X); + ROUND_16_80(i, 6, c, d, e, f, g, h, a, b, X); + ROUND_16_80(i, 7, b, c, d, e, f, g, h, a, X); + ROUND_16_80(i, 8, a, b, c, d, e, f, g, h, X); + ROUND_16_80(i, 9, h, a, b, c, d, e, f, g, X); + ROUND_16_80(i, 10, g, h, a, b, c, d, e, f, X); + ROUND_16_80(i, 11, f, g, h, a, b, c, d, e, X); + ROUND_16_80(i, 12, e, f, g, h, a, b, c, d, X); + ROUND_16_80(i, 13, d, e, f, g, h, a, b, c, X); + ROUND_16_80(i, 14, c, d, e, f, g, h, a, b, X); + ROUND_16_80(i, 15, b, c, d, e, f, g, h, a, X); + } + + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + state[4] += e; + state[5] += f; + state[6] += g; + state[7] += h; + + in += 16 * 8; + } +} + +#undef Sigma0 +#undef Sigma1 +#undef sigma0 +#undef sigma1 +#undef Ch +#undef Maj +#undef ROUND_00_15 +#undef ROUND_16_80 + +void sha512_update(SHA512_CTX *c, const void *in_data, size_t len) { + uint64_t l; + uint8_t *p = c->p; + const uint8_t *data = reinterpret_cast(in_data); + + if (len == 0) { + return; + } + + l = (c->Nl + (((uint64_t)len) << 3)) & UINT64_C(0xffffffffffffffff); + if (l < c->Nl) { + c->Nh++; + } + if (sizeof(len) >= 8) { + c->Nh += (((uint64_t)len) >> 61); + } + c->Nl = l; + + if (c->num != 0) { + size_t n = sizeof(c->p) - c->num; + + if (len < n) { + memcpy(p + c->num, data, len); + c->num += (unsigned int)len; + return; + } else { + memcpy(p + c->num, data, n), c->num = 0; + len -= n; + data += n; + sha512_block_data_order(c->h, p, 1); + } + } + + if (len >= sizeof(c->p)) { + sha512_block_data_order(c->h, data, len / sizeof(c->p)); + data += len; + len %= sizeof(c->p); + data -= len; + } + + if (len != 0) { + memcpy(p, data, len); + c->num = (int)len; + } + + return; +} + +} // namespace +} // namespace entropy +BSSL_NAMESPACE_END diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/fips_shared_support.cc b/Sources/CNIOBoringSSL/crypto/fipsmodule/fips_shared_support.cc index 0f396e92..ebc64ef3 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/fips_shared_support.cc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/fips_shared_support.cc @@ -1,25 +1,25 @@ -/* Copyright 2019 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2019 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 #if defined(BORINGSSL_FIPS) && defined(BORINGSSL_SHARED_LIBRARY) -// BORINGSSL_bcm_text_hash is is default hash value for the FIPS integrity check -// that must be replaced with the real value during the build process. This -// value need only be distinct, i.e. so that we can safely search-and-replace it -// in an object file. +// BORINGSSL_bcm_text_hash is the default hash value for the FIPS integrity +// check that must be replaced with the real value during the build process. +// This value need only be distinct, i.e. so that we can safely +// search-and-replace it in an object file. extern const uint8_t BORINGSSL_bcm_text_hash[32] = { 0xae, 0x2c, 0xea, 0x2a, 0xbd, 0xa6, 0xf3, 0xec, 0x97, 0x7f, 0x9b, 0xf6, 0x94, 0x9a, 0xfc, 0x83, 0x68, 0x27, 0xcb, 0xa0, 0xa0, 0x9f, diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/hkdf/hkdf.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/hkdf/hkdf.cc.inc index f03d8e20..a7e3fb92 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/hkdf/hkdf.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/hkdf/hkdf.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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 @@ -23,6 +23,8 @@ #include "../../internal.h" +using namespace bssl; + int HKDF(uint8_t *out_key, size_t out_len, const EVP_MD *digest, const uint8_t *secret, size_t secret_len, const uint8_t *salt, size_t salt_len, const uint8_t *info, size_t info_len) { @@ -47,7 +49,8 @@ int HKDF_extract(uint8_t *out_key, size_t *out_len, const EVP_MD *digest, // If salt is not given, HashLength zeros are used. However, HMAC does that // internally already so we can ignore it. unsigned len; - if (HMAC(digest, salt, salt_len, secret, secret_len, out_key, &len) == NULL) { + if (HMAC(digest, salt, salt_len, secret, secret_len, out_key, &len) == + nullptr) { OPENSSL_PUT_ERROR(HKDF, ERR_R_HMAC_LIB); return 0; } @@ -75,7 +78,7 @@ int HKDF_expand(uint8_t *out_key, size_t out_len, const EVP_MD *digest, } HMAC_CTX_init(&hmac); - if (!HMAC_Init_ex(&hmac, prk, prk_len, digest, NULL)) { + if (!HMAC_Init_ex(&hmac, prk, prk_len, digest, nullptr)) { goto out; } @@ -83,13 +86,12 @@ int HKDF_expand(uint8_t *out_key, size_t out_len, const EVP_MD *digest, uint8_t ctr = i + 1; size_t todo; - if (i != 0 && (!HMAC_Init_ex(&hmac, NULL, 0, NULL, NULL) || + if (i != 0 && (!HMAC_Init_ex(&hmac, nullptr, 0, nullptr, nullptr) || !HMAC_Update(&hmac, previous, digest_len))) { goto out; } - if (!HMAC_Update(&hmac, info, info_len) || - !HMAC_Update(&hmac, &ctr, 1) || - !HMAC_Final(&hmac, previous, NULL)) { + if (!HMAC_Update(&hmac, info, info_len) || !HMAC_Update(&hmac, &ctr, 1) || + !HMAC_Final(&hmac, previous, nullptr)) { goto out; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/hmac/hmac.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/hmac/hmac.cc.inc index bb5ac957..e4ea2930 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/hmac/hmac.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/hmac/hmac.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,9 +21,12 @@ #include #include "../../internal.h" +#include "../../mem_internal.h" #include "../service_indicator/internal.h" +using namespace bssl; + uint8_t *HMAC(const EVP_MD *evp_md, const void *key, size_t key_len, const uint8_t *data, size_t data_len, uint8_t *out, unsigned int *out_len) { @@ -28,7 +36,7 @@ uint8_t *HMAC(const EVP_MD *evp_md, const void *key, size_t key_len, // The underlying hash functions should not set the FIPS service indicator // until all operations have completed. FIPS_service_indicator_lock_state(); - const int ok = HMAC_Init_ex(&ctx, key, key_len, evp_md, NULL) && + const int ok = HMAC_Init_ex(&ctx, key, key_len, evp_md, nullptr) && HMAC_Update(&ctx, data, data_len) && HMAC_Final(&ctx, out, out_len); FIPS_service_indicator_unlock_state(); @@ -36,7 +44,7 @@ uint8_t *HMAC(const EVP_MD *evp_md, const void *key, size_t key_len, HMAC_CTX_cleanup(&ctx); if (!ok) { - return NULL; + return nullptr; } HMAC_verify_service_indicator(evp_md); @@ -44,16 +52,15 @@ uint8_t *HMAC(const EVP_MD *evp_md, const void *key, size_t key_len, } void HMAC_CTX_init(HMAC_CTX *ctx) { - ctx->md = NULL; + ctx->md = nullptr; EVP_MD_CTX_init(&ctx->i_ctx); EVP_MD_CTX_init(&ctx->o_ctx); EVP_MD_CTX_init(&ctx->md_ctx); } -HMAC_CTX *HMAC_CTX_new(void) { - HMAC_CTX *ctx = - reinterpret_cast(OPENSSL_malloc(sizeof(HMAC_CTX))); - if (ctx != NULL) { +HMAC_CTX *HMAC_CTX_new() { + HMAC_CTX *ctx = New(); + if (ctx != nullptr) { HMAC_CTX_init(ctx); } return ctx; @@ -74,12 +81,12 @@ void HMAC_CTX_cleanse(HMAC_CTX *ctx) { } void HMAC_CTX_free(HMAC_CTX *ctx) { - if (ctx == NULL) { + if (ctx == nullptr) { return; } HMAC_CTX_cleanup(ctx); - OPENSSL_free(ctx); + Delete(ctx); } int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, size_t key_len, @@ -87,18 +94,18 @@ int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, size_t key_len, int ret = 0; FIPS_service_indicator_lock_state(); - if (md == NULL) { + if (md == nullptr) { md = ctx->md; } - // If either |key| is non-NULL or |md| has changed, initialize with a new key + // If either `key` is non-NULL or `md` has changed, initialize with a new key // rather than rewinding the previous one. // - // TODO(davidben,eroman): Passing the previous |md| with a NULL |key| is + // TODO(davidben,eroman): Passing the previous `md` with a NULL `key` is // ambiguous between using the empty key and reusing the previous key. There // exist callers which intend the latter, but the former is an awkward edge // case. Fix to API to avoid this. - if (md != ctx->md || key != NULL) { + if (md != ctx->md || key != nullptr) { uint8_t pad[EVP_MAX_MD_BLOCK_SIZE]; uint8_t key_block[EVP_MAX_MD_BLOCK_SIZE]; unsigned key_block_len; @@ -158,12 +165,11 @@ int HMAC_Final(HMAC_CTX *ctx, uint8_t *out, unsigned int *out_len) { FIPS_service_indicator_lock_state(); // TODO(davidben): The only thing that can officially fail here is - // |EVP_MD_CTX_copy_ex|, but even that should be impossible in this case. + // `EVP_MD_CTX_copy_ex`, but even that should be impossible in this case. if (!EVP_DigestFinal_ex(&ctx->md_ctx, buf, &i) || !EVP_MD_CTX_copy_ex(&ctx->md_ctx, &ctx->o_ctx) || !EVP_DigestUpdate(&ctx->md_ctx, buf, i) || !EVP_DigestFinal_ex(&ctx->md_ctx, out, out_len)) { - *out_len = 0; goto out; } @@ -173,6 +179,8 @@ out: FIPS_service_indicator_unlock_state(); if (ret) { HMAC_verify_service_indicator(ctx->md); + } else if (out_len) { + *out_len = 0; } return ret; } @@ -201,7 +209,7 @@ int HMAC_Init(HMAC_CTX *ctx, const void *key, int key_len, const EVP_MD *md) { if (key && md) { HMAC_CTX_init(ctx); } - return HMAC_Init_ex(ctx, key, key_len, md, NULL); + return HMAC_Init_ex(ctx, key, key_len, md, nullptr); } int HMAC_CTX_copy(HMAC_CTX *dest, const HMAC_CTX *src) { diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/keccak/internal.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/keccak/internal.h index 482e9558..96c1efe3 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/keccak/internal.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/keccak/internal.h @@ -1,70 +1,165 @@ -/* Copyright 2023 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2023 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. -#ifndef OPENSSL_HEADER_CRYPTO_KECCAK_INTERNAL_H -#define OPENSSL_HEADER_CRYPTO_KECCAK_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_KECCAK_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_KECCAK_INTERNAL_H #include -#if defined(__cplusplus) -extern "C" { -#endif +#include "../../internal.h" -enum boringssl_keccak_config_t { +BSSL_NAMESPACE_BEGIN + +enum boringssl_keccak_config_t : int32_t { boringssl_sha3_256, boringssl_sha3_512, boringssl_shake128, boringssl_shake256, + boringssl_turboshake128, + boringssl_turboshake256, + boringssl_cshake128, + boringssl_cshake256, }; -enum boringssl_keccak_phase_t { +enum boringssl_keccak_phase_t : int32_t { boringssl_keccak_phase_absorb, boringssl_keccak_phase_squeeze, }; struct BORINGSSL_keccak_st { + // Note: the state with 64-bit integers comes first so that the size of this + // struct is easy to compute on all architectures without padding surprises + // due to alignment. + uint64_t state[25]; enum boringssl_keccak_config_t config; enum boringssl_keccak_phase_t phase; - uint64_t state[25]; + size_t required_out_len; size_t rate_bytes; size_t absorb_offset; size_t squeeze_offset; }; -// BORINGSSL_keccak hashes |in_len| bytes from |in| and writes |out_len| bytes -// of output to |out|. If the |config| specifies a fixed-output function, like -// SHA3-256, then |out_len| must be the correct length for that function. +// BORINGSSL_keccak hashes `in_len` bytes from `in` and writes `out_len` bytes +// of output to `out`. If the `config` specifies a fixed-output function, like +// SHA3-256, then `out_len` must be the correct length for that function. The +// cSHAKE configurations are only valid with the BORINGSSL_cshake functions. OPENSSL_EXPORT void BORINGSSL_keccak(uint8_t *out, size_t out_len, const uint8_t *in, size_t in_len, enum boringssl_keccak_config_t config); -// BORINGSSL_keccak_init prepares |ctx| for absorbing. The |config| must specify -// a SHAKE variant, otherwise callers should use |BORINGSSL_keccak|. +// BORINGSSL_keccak_init prepares `ctx` for absorbing. If the `config` specifies +// a fixed-output function, like SHA3-256, then the output must be squeezed in a +// single call to `BORINGSSL_keccak_squeeze`. In that case, it is recommended to +// use `BORINGSSL_keccak` if the input can be absorbed in a single call. OPENSSL_EXPORT void BORINGSSL_keccak_init( struct BORINGSSL_keccak_st *ctx, enum boringssl_keccak_config_t config); -// BORINGSSL_keccak_absorb absorbs |in_len| bytes from |in|. +// BORINGSSL_cshake_init prepares `ctx` for cSHAKE, including absorbing the +// function-name and customization strings. `config` must be +// `boringssl_cshake128` or `boringssl_cshake256`. The message may then be +// absorbed and output squeezed with the usual Keccak functions. +OPENSSL_EXPORT void BORINGSSL_cshake_init(struct BORINGSSL_keccak_st *ctx, + enum boringssl_keccak_config_t config, + const uint8_t *function_name, + size_t function_name_len, + const uint8_t *customization, + size_t customization_len); + +// BORINGSSL_cshake is the one-shot form of BORINGSSL_cshake_init. +OPENSSL_EXPORT void BORINGSSL_cshake(uint8_t *out, size_t out_len, + const uint8_t *in, size_t in_len, + enum boringssl_keccak_config_t config, + const uint8_t *function_name, + size_t function_name_len, + const uint8_t *customization, + size_t customization_len); + +// BORINGSSL_keccak_absorb absorbs `in_len` bytes from `in`. OPENSSL_EXPORT void BORINGSSL_keccak_absorb(struct BORINGSSL_keccak_st *ctx, const uint8_t *in, size_t in_len); -// BORINGSSL_keccak_squeeze writes |out_len| bytes to |out| from |ctx|. +// BORINGSSL_keccak_squeeze writes `out_len` bytes to `out` from `ctx`. If the +// configuration previously passed in `BORINGSSL_keccak_init` specifies a +// fixed-output function, then a single call to `BORINGSSL_keccak_squeeze` is +// allowed, where `out_len` must be the correct length for that function. OPENSSL_EXPORT void BORINGSSL_keccak_squeeze(struct BORINGSSL_keccak_st *ctx, uint8_t *out, size_t out_len); -#if defined(__cplusplus) -} +#if defined(__has_attribute) +#if __has_attribute(vector_size) + +#define HAVE_KECCAK_X2 + +#if defined(OPENSSL_AARCH64) +#define HAVE_KECCAK_X4 +#define KECCAK_X4_TARGET #endif -#endif // OPENSSL_HEADER_CRYPTO_KECCAK_INTERNAL_H +#if defined(OPENSSL_X86_64) +#define HAVE_KECCAK_X4 +#define KECCAK_X4_TARGET __attribute__((target("avx2"))) +#endif + +#endif // vector_size +#endif // __has_attribute + +#if defined(HAVE_KECCAK_X2) +// BORINGSSL_keccak_squeeze_x2 performs BORINGSSL_keccak_squeeze in parallel +// with two same-length outputs. The contexts must be in equivalent state (i.e. +// same config, same amount of bytes absorbed and squeezed). +// This function is not compatible with cSHAKE nor TurboSHAKE. +OPENSSL_EXPORT void BORINGSSL_keccak_squeeze_x2( + struct BORINGSSL_keccak_st ctx[2], uint8_t *outs[2], size_t out_len); + +// BORINGSSL_keccak_short_x2 performs BORINGSSL_keccak in parallel on two +// same-length strings with same-length outputs. `in_len` must be less than 72 +// (or actually `rate_bytes`). +// This function is not compatible with cSHAKE nor TurboSHAKE. +OPENSSL_EXPORT void BORINGSSL_keccak_short_x2( + uint8_t *outs[2], size_t out_len, const uint8_t *ins[2], size_t in_len, + enum boringssl_keccak_config_t config); +#endif + +#if defined(HAVE_KECCAK_X4) +// BORINGSSL_have_keccak_x4 needs to return true before using any of the _x4 +// variants here, as they may require additional CPU features. +// This function is not compatible with cSHAKE nor TurboSHAKE. +inline bool BORINGSSL_have_keccak_x4() { +#if defined(OPENSSL_X86_64) + return CRYPTO_is_AVX2_capable(); +#else + return true; +#endif +} + +// BORINGSSL_keccak_squeeze_x4 performs BORINGSSL_keccak_squeeze in parallel +// with four same-length outputs. The contexts must be in equivalent state (i.e. +// same config, same amount of bytes absorbed and squeezed). +// This function is not compatible with cSHAKE nor TurboSHAKE. +OPENSSL_EXPORT void BORINGSSL_keccak_squeeze_x4( + struct BORINGSSL_keccak_st ctx[4], uint8_t *outs[4], size_t out_len); + +// BORINGSSL_keccak_short_x4 performs BORINGSSL_keccak in parallel on four +// same-length strings with same-length outputs. in_len must be less than 72 +// (or actually `rate_bytes`). +// This function is not compatible with cSHAKE nor TurboSHAKE. +OPENSSL_EXPORT void BORINGSSL_keccak_short_x4( + uint8_t *outs[4], size_t out_len, const uint8_t *ins[4], size_t in_len, + enum boringssl_keccak_config_t config); +#endif + +BSSL_NAMESPACE_END + +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_KECCAK_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/keccak/keccak.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/keccak/keccak.cc.inc index ee938d7d..b53d5ab5 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/keccak/keccak.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/keccak/keccak.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2023 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2023 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 @@ -21,21 +21,46 @@ #include "./internal.h" -// keccak_f implements the Keccak-1600 permutation as described at +using namespace bssl; + +// A rotate-left function is needed for every type to use Keccak with. +// +// As argument passing may differ for AVX2 and non-AVX2 functions taking vector +// arguments by value, this function takes a pointer instead; however, thanks +// to `OPENSSL_ATTR_ALWAYS_INLINE`, this should not actually change generated +// code. +static inline OPENSSL_ATTR_ALWAYS_INLINE void rotl_u64(uint64_t *value, + int shift) { + *value = CRYPTO_rotl_u64(*value, shift); +} + +// keccak_f implements the last `num_rounds` of the Keccak-1600 permutation, +// i.e. Keccak-p[1600, num_rounds], as described at // https://keccak.team/keccak_specs_summary.html. Each lane is represented as a // 64-bit value and the 5×5 lanes are stored as an array in row-major order. -static void keccak_f(uint64_t state[25]) { +// +// To support vectorization, U64 shall either be uint64_t, or an uint64_t-based +// vector type. +// +// `OPENSSL_ATTR_ALWAYS_INLINE` is used here to ensure that AVX2 optimizations +// are used whenever the calling function is `KECCAK_X4_TARGET`, as target +// attributes are inherited into callees when inlining. +template +static inline OPENSSL_ATTR_ALWAYS_INLINE void keccak_f(U64 state[25], + int num_rounds = 24) { static const int kNumRounds = 24; - for (int round = 0; round < kNumRounds; round++) { + for (int round = kNumRounds - num_rounds; round < kNumRounds; round++) { // θ step - uint64_t c[5]; + U64 c[5]; for (int x = 0; x < 5; x++) { c[x] = state[x] ^ state[x + 5] ^ state[x + 10] ^ state[x + 15] ^ state[x + 20]; } for (int x = 0; x < 5; x++) { - const uint64_t d = c[(x + 4) % 5] ^ CRYPTO_rotl_u64(c[(x + 1) % 5], 1); + U64 next_value = c[(x + 1) % 5]; + rotl(&next_value, 1); + const U64 d = c[(x + 4) % 5] ^ next_value; for (int y = 0; y < 5; y++) { state[y * 5 + x] ^= d; } @@ -56,12 +81,13 @@ static void keccak_f(uint64_t state[25]) { // and the sequence will repeat. All that remains is to handle the element // at (0, 0), but the rotation for that element is zero, and it goes to (0, // 0), so we can ignore it. - uint64_t prev_value = state[1]; -#define PI_RHO_STEP(index, rotation) \ - do { \ - const uint64_t value = CRYPTO_rotl_u64(prev_value, rotation); \ - prev_value = state[index]; \ - state[index] = value; \ + U64 prev_value = state[1]; +#define PI_RHO_STEP(index, rotation) \ + do { \ + U64 value = prev_value; \ + rotl(&value, rotation); \ + prev_value = state[index]; \ + state[index] = value; \ } while (0) PI_RHO_STEP(10, 1); @@ -94,8 +120,8 @@ static void keccak_f(uint64_t state[25]) { // χ step for (int y = 0; y < 5; y++) { const int row_index = 5 * y; - const uint64_t orig_x0 = state[row_index]; - const uint64_t orig_x1 = state[row_index + 1]; + const U64 orig_x0 = state[row_index]; + const U64 orig_x1 = state[row_index + 1]; state[row_index] ^= ~orig_x1 & state[row_index + 2]; state[row_index + 1] ^= ~state[row_index + 2] & state[row_index + 3]; state[row_index + 2] ^= ~state[row_index + 3] & state[row_index + 4]; @@ -107,7 +133,7 @@ static void keccak_f(uint64_t state[25]) { // // From https://keccak.team/files/Keccak-reference-3.0.pdf, section // 1.2, the round constants are based on the output of a LFSR. Thus, as - // suggested in the appendix of of + // suggested in the appendix of // https://keccak.team/keccak_specs_summary.html, the values are // simply encoded here. static const uint64_t kRoundConstants[24] = { @@ -125,26 +151,75 @@ static void keccak_f(uint64_t state[25]) { } } +#if defined(HAVE_KECCAK_X2) +typedef uint64_t v2u64 __attribute__((vector_size(16))); + +static inline void v2_rotl(v2u64 *x, int shift) { + *x = (*x << shift) | (*x >> ((-shift) & 63)); +} + +static void keccak_f_x2(uint64_t state0[25], uint64_t state1[25]) { + v2u64 s[25]; + for (int i = 0; i < 25; i++) { + s[i] = (v2u64){state0[i], state1[i]}; + } + keccak_f(s); + for (int i = 0; i < 25; i++) { + state0[i] = s[i][0]; + state1[i] = s[i][1]; + } +} +#endif + +#if defined(HAVE_KECCAK_X4) +typedef uint64_t v4u64 __attribute__((vector_size(32))); + +KECCAK_X4_TARGET static inline void v4_rotl(v4u64 *x, int shift) { + *x = (*x << shift) | (*x >> ((-shift) & 63)); +} + +KECCAK_X4_TARGET static void keccak_f_x4(uint64_t state0[25], + uint64_t state1[25], + uint64_t state2[25], + uint64_t state3[25]) { + v4u64 s[25]; + for (int i = 0; i < 25; i++) { + s[i] = (v4u64){state0[i], state1[i], state2[i], state3[i]}; + } + keccak_f(s); + for (int i = 0; i < 25; i++) { + state0[i] = s[i][0]; + state1[i] = s[i][1]; + state2[i] = s[i][2]; + state3[i] = s[i][3]; + } +} +#endif + static void keccak_init(struct BORINGSSL_keccak_st *ctx, - size_t *out_required_out_len, enum boringssl_keccak_config_t config) { + size_t required_out_len; size_t capacity_bytes; switch (config) { case boringssl_sha3_256: capacity_bytes = 512 / 8; - *out_required_out_len = 32; + required_out_len = 32; break; case boringssl_sha3_512: capacity_bytes = 1024 / 8; - *out_required_out_len = 64; + required_out_len = 64; break; case boringssl_shake128: + case boringssl_turboshake128: + case boringssl_cshake128: capacity_bytes = 256 / 8; - *out_required_out_len = 0; + required_out_len = 0; break; case boringssl_shake256: + case boringssl_turboshake256: + case boringssl_cshake256: capacity_bytes = 512 / 8; - *out_required_out_len = 0; + required_out_len = 0; break; default: abort(); @@ -153,41 +228,100 @@ static void keccak_init(struct BORINGSSL_keccak_st *ctx, OPENSSL_memset(ctx, 0, sizeof(*ctx)); ctx->config = config; ctx->phase = boringssl_keccak_phase_absorb; + ctx->required_out_len = required_out_len; ctx->rate_bytes = 200 - capacity_bytes; assert(ctx->rate_bytes % 8 == 0); } -void BORINGSSL_keccak(uint8_t *out, size_t out_len, const uint8_t *in, - size_t in_len, enum boringssl_keccak_config_t config) { - struct BORINGSSL_keccak_st ctx; - size_t required_out_len; - keccak_init(&ctx, &required_out_len, config); - if (required_out_len != 0 && out_len != required_out_len) { - abort(); +[[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; +} + +static bool keccak_is_cshake(enum boringssl_keccak_config_t config) { + return config == boringssl_cshake128 || config == boringssl_cshake256; +} + +static int keccak_num_rounds(enum boringssl_keccak_config_t config) { + if (config == boringssl_turboshake128 || config == boringssl_turboshake256) { + return 12; } + return 24; +} + +void bssl::BORINGSSL_keccak(uint8_t *out, size_t out_len, const uint8_t *in, + size_t in_len, + enum boringssl_keccak_config_t config) { + struct BORINGSSL_keccak_st ctx; + BORINGSSL_keccak_init(&ctx, config); + BSSL_CHECK(ctx.required_out_len == 0 || out_len == ctx.required_out_len); BORINGSSL_keccak_absorb(&ctx, in, in_len); BORINGSSL_keccak_squeeze(&ctx, out, out_len); } -void BORINGSSL_keccak_init(struct BORINGSSL_keccak_st *ctx, - enum boringssl_keccak_config_t config) { - size_t required_out_len; - keccak_init(ctx, &required_out_len, config); - if (required_out_len != 0) { - abort(); +#if defined(HAVE_KECCAK_X2) +void bssl::BORINGSSL_keccak_short_x2(uint8_t *outs[2], size_t out_len, + const uint8_t *ins[2], size_t in_len, + enum boringssl_keccak_config_t config) { + assert(keccak_can_parallel(config)); + + struct BORINGSSL_keccak_st ctx[2]; + for (size_t i = 0; i < 2; ++i) { + BORINGSSL_keccak_init(&ctx[i], config); + BSSL_CHECK(ctx[i].required_out_len == 0 || + out_len == ctx[i].required_out_len); + + // NOTE: this implementation is only efficient if in_len < + // ctx->rate_bytes, as right now only keccak_f calls in + // BORINGSSL_keccak_squeeze and keccak_finalize are vectorized. So just + // fail in every other case for now. + BSSL_CHECK(in_len < ctx[i].rate_bytes); + + BORINGSSL_keccak_absorb(&ctx[i], ins[i], in_len); } + BORINGSSL_keccak_squeeze_x2(ctx, outs, out_len); +} +#endif + +#if defined(HAVE_KECCAK_X4) +KECCAK_X4_TARGET void bssl::BORINGSSL_keccak_short_x4( + uint8_t *outs[4], size_t out_len, const uint8_t *ins[4], size_t in_len, + enum boringssl_keccak_config_t config) { + assert(keccak_can_parallel(config)); + + struct BORINGSSL_keccak_st ctx[4]; + for (size_t i = 0; i < 4; ++i) { + BORINGSSL_keccak_init(&ctx[i], config); + BSSL_CHECK(ctx[i].required_out_len == 0 || + out_len == ctx[i].required_out_len); + + // NOTE: this implementation is only efficient if in_len < + // ctx->rate_bytes, as right now only keccak_f calls in + // BORINGSSL_keccak_squeeze and keccak_finalize are vectorized. So just + // fail in every other case for now. + BSSL_CHECK(in_len < ctx[i].rate_bytes); + + BORINGSSL_keccak_absorb(&ctx[i], ins[i], in_len); + } + BORINGSSL_keccak_squeeze_x4(ctx, outs, out_len); +} +#endif + +void bssl::BORINGSSL_keccak_init(struct BORINGSSL_keccak_st *ctx, + enum boringssl_keccak_config_t config) { + BSSL_CHECK(!keccak_is_cshake(config)); + keccak_init(ctx, config); } -void BORINGSSL_keccak_absorb(struct BORINGSSL_keccak_st *ctx, const uint8_t *in, - size_t in_len) { - if (ctx->phase == boringssl_keccak_phase_squeeze) { - // It's illegal to call absorb() again after calling squeeze(). - abort(); - } +void bssl::BORINGSSL_keccak_absorb(struct BORINGSSL_keccak_st *ctx, + const uint8_t *in, size_t in_len) { + // It's illegal to call absorb() again after calling squeeze(). + BSSL_CHECK(ctx->phase != boringssl_keccak_phase_squeeze); const size_t rate_words = ctx->rate_bytes / 8; - // XOR the input. Accessing |ctx->state| as a |uint8_t*| is allowed by strict - // aliasing because we require |uint8_t| to be a character type. + // XOR the input. Accessing `ctx->state` as a `uint8_t*` is allowed by + // strict aliasing because we require `uint8_t` to be a character type. uint8_t *state_bytes = (uint8_t *)ctx->state; // Absorb partial block. @@ -204,7 +338,7 @@ void BORINGSSL_keccak_absorb(struct BORINGSSL_keccak_st *ctx, const uint8_t *in, return; } - keccak_f(ctx->state); + keccak_f(ctx->state, keccak_num_rounds(ctx->config)); in += first_block_len; in_len -= first_block_len; } @@ -214,7 +348,7 @@ void BORINGSSL_keccak_absorb(struct BORINGSSL_keccak_st *ctx, const uint8_t *in, for (size_t i = 0; i < rate_words; i++) { ctx->state[i] ^= CRYPTO_load_u64_le(in + 8 * i); } - keccak_f(ctx->state); + keccak_f(ctx->state, keccak_num_rounds(ctx->config)); in += ctx->rate_bytes; in_len -= ctx->rate_bytes; } @@ -227,42 +361,146 @@ void BORINGSSL_keccak_absorb(struct BORINGSSL_keccak_st *ctx, const uint8_t *in, ctx->absorb_offset = in_len; } -static void keccak_finalize(struct BORINGSSL_keccak_st *ctx) { - uint8_t terminator; +// left_encode implements the integer encoding from NIST SP 800-185, section +// 2.3.1. +static size_t left_encode(uint8_t out[sizeof(size_t) + 1], size_t value) { + size_t num_bytes = 1; + for (size_t v = value; v > 0xff; v >>= 8) { + num_bytes++; + } + out[0] = (uint8_t)num_bytes; + for (size_t i = 0; i < num_bytes; i++) { + out[num_bytes - i] = (uint8_t)(value >> (8 * i)); + } + return num_bytes + 1; +} + +static void cshake_absorb_encode_string(struct BORINGSSL_keccak_st *ctx, + const uint8_t *in, size_t in_len) { + BSSL_CHECK(in_len <= SIZE_MAX / 8); + uint8_t encoded[sizeof(size_t) + 1]; + const size_t encoded_len = left_encode(encoded, in_len * 8); + BORINGSSL_keccak_absorb(ctx, encoded, encoded_len); + BORINGSSL_keccak_absorb(ctx, in, in_len); +} + +void bssl::BORINGSSL_cshake_init(struct BORINGSSL_keccak_st *ctx, + enum boringssl_keccak_config_t config, + const uint8_t *function_name, + size_t function_name_len, + const uint8_t *customization, + size_t customization_len) { + BSSL_CHECK(keccak_is_cshake(config)); + + // SP 800-185 defines cSHAKE with two empty strings to be SHAKE. + if (function_name_len == 0 && customization_len == 0) { + BORINGSSL_keccak_init(ctx, config == boringssl_cshake128 + ? boringssl_shake128 + : boringssl_shake256); + return; + } + + keccak_init(ctx, config); + uint8_t encoded[sizeof(size_t) + 1]; + const size_t encoded_len = left_encode(encoded, ctx->rate_bytes); + BORINGSSL_keccak_absorb(ctx, encoded, encoded_len); + cshake_absorb_encode_string(ctx, function_name, function_name_len); + cshake_absorb_encode_string(ctx, customization, customization_len); + + static const uint8_t kZeros[168] = {0}; + if (ctx->absorb_offset != 0) { + BORINGSSL_keccak_absorb(ctx, kZeros, ctx->rate_bytes - ctx->absorb_offset); + } +} + +void bssl::BORINGSSL_cshake(uint8_t *out, size_t out_len, const uint8_t *in, + size_t in_len, + enum boringssl_keccak_config_t config, + const uint8_t *function_name, + size_t function_name_len, + const uint8_t *customization, + size_t customization_len) { + struct BORINGSSL_keccak_st ctx; + BORINGSSL_cshake_init(&ctx, config, function_name, function_name_len, + customization, customization_len); + BORINGSSL_keccak_absorb(&ctx, in, in_len); + BORINGSSL_keccak_squeeze(&ctx, out, out_len); +} + +static uint8_t keccak_terminator(struct BORINGSSL_keccak_st *ctx) { switch (ctx->config) { case boringssl_sha3_256: case boringssl_sha3_512: - terminator = 0x06; - break; + return 0x06; case boringssl_shake128: case boringssl_shake256: - terminator = 0x1f; - break; + case boringssl_turboshake128: + case boringssl_turboshake256: + return 0x1f; + case boringssl_cshake128: + case boringssl_cshake256: + return 0x04; default: abort(); } - - // XOR the terminator. Accessing |ctx->state| as a |uint8_t*| is allowed by - // strict aliasing because we require |uint8_t| to be a character type. - uint8_t *state_bytes = (uint8_t *)ctx->state; - state_bytes[ctx->absorb_offset] ^= terminator; - state_bytes[ctx->rate_bytes - 1] ^= 0x80; - keccak_f(ctx->state); } -void BORINGSSL_keccak_squeeze(struct BORINGSSL_keccak_st *ctx, uint8_t *out, - size_t out_len) { +static void keccak_finalize(struct BORINGSSL_keccak_st *ctx) { + // XOR the terminator. Accessing `ctx->state` as a `uint8_t*` is allowed by + // strict aliasing because we require `uint8_t` to be a character type. + uint8_t *state_bytes = (uint8_t *)ctx->state; + state_bytes[ctx->absorb_offset] ^= keccak_terminator(ctx); + state_bytes[ctx->rate_bytes - 1] ^= 0x80; + keccak_f(ctx->state, keccak_num_rounds(ctx->config)); +} + +#if defined(HAVE_KECCAK_X2) +static void keccak_finalize_x2(struct BORINGSSL_keccak_st ctx[2]) { + for (size_t i = 0; i < 2; ++i) { + // XOR the terminator. Accessing `ctx->state` as a `uint8_t*` is allowed + // by strict aliasing because we require `uint8_t` to be a character type. + uint8_t *state_bytes = (uint8_t *)ctx[i].state; + state_bytes[ctx[i].absorb_offset] ^= keccak_terminator(&ctx[i]); + state_bytes[ctx[i].rate_bytes - 1] ^= 0x80; + } + keccak_f_x2(ctx[0].state, ctx[1].state); +} +#endif + +#if defined(HAVE_KECCAK_X4) +static void keccak_finalize_x4(struct BORINGSSL_keccak_st ctx[4]) { + assert(keccak_can_parallel(ctx[0].config)); + + for (size_t i = 0; i < 4; ++i) { + // XOR the terminator. Accessing `ctx->state` as a `uint8_t*` is allowed + // by strict aliasing because we require `uint8_t` to be a character type. + uint8_t *state_bytes = (uint8_t *)ctx[i].state; + state_bytes[ctx[i].absorb_offset] ^= keccak_terminator(&ctx[i]); + state_bytes[ctx[i].rate_bytes - 1] ^= 0x80; + } + keccak_f_x4(ctx[0].state, ctx[1].state, ctx[2].state, ctx[3].state); +} +#endif + +void bssl::BORINGSSL_keccak_squeeze(struct BORINGSSL_keccak_st *ctx, + uint8_t *out, size_t out_len) { + // The SHA-3 variants must be squeezed in a single call, to confirm that the + // output length is correct. + BSSL_CHECK(ctx->required_out_len == 0 || + (ctx->phase != boringssl_keccak_phase_squeeze && + out_len == ctx->required_out_len)); + if (ctx->phase == boringssl_keccak_phase_absorb) { keccak_finalize(ctx); ctx->phase = boringssl_keccak_phase_squeeze; } - // Accessing |ctx->state| as a |uint8_t*| is allowed by strict aliasing - // because we require |uint8_t| to be a character type. + // Accessing `ctx->state` as a `uint8_t*` is allowed by strict aliasing + // because we require `uint8_t` to be a character type. const uint8_t *state_bytes = (const uint8_t *)ctx->state; while (out_len) { if (ctx->squeeze_offset == ctx->rate_bytes) { - keccak_f(ctx->state); + keccak_f(ctx->state, keccak_num_rounds(ctx->config)); ctx->squeeze_offset = 0; } @@ -277,3 +515,133 @@ void BORINGSSL_keccak_squeeze(struct BORINGSSL_keccak_st *ctx, uint8_t *out, ctx->squeeze_offset += todo; } } + +#if defined(HAVE_KECCAK_X2) +void bssl::BORINGSSL_keccak_squeeze_x2(struct BORINGSSL_keccak_st ctx[2], + uint8_t *outs[2], size_t out_len) { + assert(keccak_can_parallel(ctx[0].config)); + + for (size_t i = 0; i < 2; ++i) { + // The SHA-3 variants must be squeezed in a single call, to confirm that + // the output length is correct. + BSSL_CHECK(ctx[i].required_out_len == 0 || + (ctx[i].phase != boringssl_keccak_phase_squeeze && + out_len == ctx[i].required_out_len)); + } + + // These fields are processed in parallel. Everything here uses ctx[0]; at + // the end changes are mirrored back to ctx[1] just in case. +#define FOR_COMMON_FIELDS(MACRO) \ + MACRO(phase) \ + MACRO(config) \ + MACRO(absorb_offset) \ + MACRO(squeeze_offset) \ + MACRO(rate_bytes) + +#define MUST_BE_EQUAL(field) BSSL_CHECK(ctx[0].field == ctx[1].field); + FOR_COMMON_FIELDS(MUST_BE_EQUAL) +#undef MUST_BE_EQUAL + + if (ctx->phase == boringssl_keccak_phase_absorb) { + keccak_finalize_x2(ctx); + ctx->phase = boringssl_keccak_phase_squeeze; + } + + // Accessing `ctx->state` as a `uint8_t*` is allowed by strict aliasing + // because we require `uint8_t` to be a character type. + uint8_t *optr[2] = {outs[0], outs[1]}; + while (out_len) { + if (ctx->squeeze_offset == ctx->rate_bytes) { + keccak_f_x2(ctx[0].state, ctx[1].state); + ctx->squeeze_offset = 0; + } + + size_t remaining = ctx->rate_bytes - ctx->squeeze_offset; + size_t todo = out_len; + if (todo > remaining) { + todo = remaining; + } + for (size_t i = 0; i < 2; ++i) { + const uint8_t *state_bytes = (const uint8_t *)ctx[i].state; + OPENSSL_memcpy(optr[i], &state_bytes[ctx->squeeze_offset], todo); + optr[i] += todo; + } + out_len -= todo; + ctx->squeeze_offset += todo; + } + +#define COPY_FIELD_VALUE(field) ctx[1].field = ctx[0].field; + FOR_COMMON_FIELDS(COPY_FIELD_VALUE) +#undef COPY_FIELD_VALUE + +#undef FOR_COMMON_FIELDS +} +#endif // HAVE_KECCAK_X2 + +#if defined(HAVE_KECCAK_X4) +KECCAK_X4_TARGET void bssl::BORINGSSL_keccak_squeeze_x4( + struct BORINGSSL_keccak_st ctx[4], uint8_t *outs[4], size_t out_len) { + assert(keccak_can_parallel(ctx[0].config)); + + for (size_t i = 0; i < 4; ++i) { + // The SHA-3 variants must be squeezed in a single call, to confirm that + // the output length is correct. + BSSL_CHECK(ctx[i].required_out_len == 0 || + (ctx[i].phase != boringssl_keccak_phase_squeeze && + out_len == ctx[i].required_out_len)); + } + + // These fields are processed in parallel. Everything here uses ctx[0]; at + // the end changes are mirrored back to ctx[1..3] just in case. +#define FOR_COMMON_FIELDS(MACRO) \ + MACRO(phase) \ + MACRO(config) \ + MACRO(absorb_offset) \ + MACRO(squeeze_offset) \ + MACRO(rate_bytes) + +#define MUST_BE_EQUAL(field) \ + BSSL_CHECK(ctx[0].field == ctx[1].field); \ + BSSL_CHECK(ctx[0].field == ctx[2].field); \ + BSSL_CHECK(ctx[0].field == ctx[3].field); + FOR_COMMON_FIELDS(MUST_BE_EQUAL) +#undef MUST_BE_EQUAL + + if (ctx->phase == boringssl_keccak_phase_absorb) { + keccak_finalize_x4(ctx); + ctx->phase = boringssl_keccak_phase_squeeze; + } + + // Accessing `ctx->state` as a `uint8_t*` is allowed by strict aliasing + // because we require `uint8_t` to be a character type. + uint8_t *optr[4] = {outs[0], outs[1], outs[2], outs[3]}; + while (out_len) { + if (ctx->squeeze_offset == ctx->rate_bytes) { + keccak_f_x4(ctx[0].state, ctx[1].state, ctx[2].state, ctx[3].state); + ctx->squeeze_offset = 0; + } + + size_t remaining = ctx->rate_bytes - ctx->squeeze_offset; + size_t todo = out_len; + if (todo > remaining) { + todo = remaining; + } + for (size_t i = 0; i < 4; ++i) { + const uint8_t *state_bytes = (const uint8_t *)ctx[i].state; + OPENSSL_memcpy(optr[i], &state_bytes[ctx->squeeze_offset], todo); + optr[i] += todo; + } + out_len -= todo; + ctx->squeeze_offset += todo; + } + +#define COPY_FIELD_VALUE(field) \ + ctx[1].field = ctx[0].field; \ + ctx[2].field = ctx[0].field; \ + ctx[3].field = ctx[0].field; + FOR_COMMON_FIELDS(COPY_FIELD_VALUE) +#undef COPY_FIELD_VALUE + +#undef FOR_COMMON_FIELDS +} +#endif // HAVE_KECCAK_X4 diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/mldsa/fips_known_values.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/mldsa/fips_known_values.inc new file mode 100644 index 00000000..dc639bd2 --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/mldsa/fips_known_values.inc @@ -0,0 +1,1345 @@ +const uint8_t kGenerateKeyEntropy[MLDSA_SEED_BYTES] = { + 0x47, 0x90, 0x52, 0x10, 0x30, 0x27, 0xbd, 0xf1, 0x7e, 0xb1, 0x22, + 0xd7, 0x84, 0xfb, 0x3c, 0xf0, 0x40, 0xd2, 0xf4, 0x97, 0x11, 0x7e, + 0x01, 0x38, 0xc4, 0xce, 0x9c, 0xac, 0x94, 0x71, 0xab, 0x39}; + +const uint8_t kExpectedPublicKey[MLDSA65_PUBLIC_KEY_BYTES] = { + 0x0c, 0x6f, 0x38, 0x7d, 0x2a, 0xb4, 0x33, 0x87, 0xf0, 0x21, 0xb0, 0xda, + 0x81, 0x6c, 0x71, 0xf0, 0xbc, 0x81, 0x5e, 0xf0, 0xb1, 0x6a, 0xf1, 0x12, + 0x4f, 0x35, 0x4c, 0x27, 0x3e, 0xed, 0xb4, 0x2f, 0xe5, 0x4a, 0x01, 0x9a, + 0x97, 0x9c, 0xfa, 0x12, 0xde, 0xca, 0xef, 0xe1, 0x56, 0x9a, 0x90, 0x6d, + 0x54, 0x21, 0x58, 0xa6, 0x59, 0x4c, 0x99, 0x28, 0x53, 0x79, 0xce, 0xb8, + 0x90, 0xc6, 0xed, 0x4a, 0x4c, 0xe5, 0x9b, 0x9c, 0x87, 0x41, 0xae, 0x95, + 0x26, 0x83, 0xca, 0x91, 0x38, 0x62, 0xc0, 0x32, 0x82, 0x42, 0x8e, 0xdf, + 0x92, 0xf5, 0xcf, 0xc7, 0xd5, 0x69, 0xfa, 0xfb, 0x1f, 0x18, 0x96, 0xc5, + 0x9f, 0xd8, 0xbb, 0xd6, 0xb7, 0xf4, 0x4f, 0x20, 0x12, 0x51, 0x2a, 0x08, + 0xba, 0xae, 0x5d, 0x87, 0xf9, 0x14, 0x8f, 0xb0, 0x76, 0xba, 0x1d, 0xae, + 0x38, 0x14, 0xad, 0x4f, 0x68, 0xf0, 0xc4, 0xf6, 0xdb, 0x32, 0x30, 0x9b, + 0xa3, 0x2f, 0xe3, 0x9b, 0x72, 0x5a, 0xee, 0xb0, 0x97, 0x4d, 0x01, 0xa3, + 0x70, 0x29, 0x9a, 0xd6, 0x08, 0xed, 0xbf, 0x0a, 0xa4, 0x17, 0x8d, 0x18, + 0x5f, 0x13, 0xef, 0xd2, 0x59, 0xbc, 0x50, 0x65, 0xf4, 0xef, 0xd1, 0xbb, + 0x74, 0x22, 0x38, 0xfb, 0x5d, 0x75, 0xc4, 0xe5, 0xf9, 0x8f, 0x39, 0xf2, + 0x6f, 0x93, 0xc4, 0x06, 0x1a, 0xff, 0x46, 0x7a, 0xa0, 0xaa, 0xfb, 0x1c, + 0x9c, 0xa2, 0xe0, 0x66, 0x74, 0xa1, 0x0f, 0xd5, 0x87, 0x7f, 0x45, 0x9d, + 0x5e, 0xcb, 0xec, 0xc6, 0xd0, 0x9f, 0x8a, 0x36, 0xd9, 0xce, 0x37, 0xf1, + 0x17, 0x5c, 0x7c, 0x15, 0x1d, 0x46, 0xa3, 0x5d, 0x97, 0x21, 0xbd, 0x93, + 0xf5, 0xe9, 0x8f, 0x77, 0xb4, 0xb2, 0xc2, 0x26, 0x82, 0xcb, 0xd4, 0x46, + 0xc2, 0x18, 0xa2, 0xa8, 0xfe, 0xee, 0xf5, 0x15, 0xc7, 0x03, 0x0c, 0xa3, + 0x46, 0xcf, 0x85, 0x61, 0x68, 0x8c, 0xaa, 0xd6, 0x83, 0x9f, 0xd8, 0xf4, + 0x8c, 0x0c, 0xc6, 0xe7, 0xef, 0x17, 0xe4, 0x47, 0x41, 0xcf, 0x35, 0x2a, + 0x6a, 0x19, 0xa0, 0x55, 0xc0, 0x16, 0x4f, 0xaa, 0xdc, 0x96, 0xc5, 0x34, + 0xfa, 0xee, 0xbf, 0x3f, 0x3d, 0x76, 0x06, 0x82, 0x86, 0x40, 0x7b, 0x85, + 0x7f, 0x76, 0x6d, 0x9f, 0x82, 0x9e, 0x21, 0x99, 0xd3, 0x61, 0x34, 0xf7, + 0x17, 0xf5, 0x46, 0x41, 0xad, 0x6c, 0x32, 0xd1, 0x33, 0xf8, 0x8f, 0x6e, + 0xc9, 0x13, 0xc5, 0xb3, 0x3e, 0xa7, 0x6f, 0xc9, 0x8d, 0xb0, 0x00, 0x9c, + 0x5e, 0x7b, 0xcb, 0x0b, 0x03, 0x85, 0x91, 0x4b, 0x8d, 0x74, 0xd1, 0x32, + 0x0e, 0x0b, 0x37, 0xc5, 0x80, 0x8c, 0x06, 0xd3, 0x4b, 0xab, 0xb3, 0xd4, + 0x3f, 0xb7, 0x4c, 0x46, 0xcd, 0x28, 0xde, 0x15, 0x9d, 0xf5, 0x95, 0x0c, + 0x57, 0x56, 0x7a, 0xf9, 0xde, 0x97, 0x47, 0x72, 0x95, 0xf7, 0x4a, 0x3a, + 0x1b, 0xbb, 0x51, 0xc6, 0x83, 0x7f, 0x37, 0x18, 0x6a, 0x79, 0x2c, 0xe3, + 0x82, 0x20, 0x53, 0x96, 0x10, 0xe4, 0x45, 0x32, 0xf2, 0x66, 0x35, 0x5e, + 0xb8, 0x2d, 0x8d, 0xf5, 0x90, 0x66, 0x09, 0xb2, 0xfa, 0x0e, 0xdd, 0x0b, + 0x19, 0x41, 0x4a, 0x58, 0xc0, 0x83, 0x9d, 0x6d, 0x05, 0x43, 0x84, 0x6e, + 0x5b, 0x6e, 0x7e, 0xd0, 0xc9, 0xb1, 0x55, 0x7f, 0xd0, 0x59, 0x40, 0x94, + 0x2d, 0x8c, 0xdb, 0xe1, 0xa4, 0xd8, 0x8a, 0x78, 0x3a, 0x0a, 0x50, 0x55, + 0x84, 0xc2, 0xd9, 0xd8, 0x55, 0x3a, 0xef, 0x93, 0xc2, 0xe9, 0x86, 0x43, + 0x30, 0x08, 0xd6, 0x54, 0x1f, 0xfd, 0x04, 0xac, 0x4c, 0x2d, 0x5f, 0xf5, + 0x4d, 0x4f, 0xe9, 0x70, 0x77, 0x0b, 0x9a, 0x07, 0x91, 0x1e, 0xdf, 0x9c, + 0x4e, 0xaa, 0xf5, 0x05, 0x51, 0xc9, 0x7b, 0x48, 0x35, 0xc9, 0x30, 0xd4, + 0x02, 0x14, 0x8b, 0xb4, 0x2c, 0x1f, 0x25, 0x6d, 0xf4, 0xa6, 0x52, 0x1b, + 0x63, 0x48, 0x85, 0x31, 0x82, 0xf8, 0xd5, 0xb3, 0x11, 0x77, 0x5a, 0xa3, + 0xfe, 0x2e, 0x31, 0xc7, 0xdb, 0xda, 0x0b, 0x35, 0x6f, 0x56, 0xb8, 0xb8, + 0x64, 0xb7, 0x8c, 0xde, 0x69, 0x2d, 0x88, 0x83, 0xbe, 0x2c, 0xc1, 0xc2, + 0x90, 0xd4, 0x19, 0xb7, 0x21, 0x3a, 0x71, 0x81, 0x64, 0x88, 0x7e, 0xed, + 0xc2, 0xb8, 0x92, 0xce, 0x36, 0xc0, 0x4d, 0x36, 0x66, 0x75, 0x35, 0xa0, + 0x6e, 0x1e, 0xef, 0xb1, 0x9e, 0xb1, 0x9c, 0x16, 0xf7, 0x3a, 0x7e, 0xf7, + 0x8a, 0x36, 0xd0, 0x8f, 0x9d, 0x13, 0x04, 0x4a, 0xac, 0x0d, 0x71, 0xd9, + 0x1f, 0x52, 0xa6, 0xb4, 0x52, 0xfd, 0x12, 0xd2, 0xa8, 0xc2, 0x38, 0xbf, + 0x14, 0x4b, 0x42, 0xcf, 0xfc, 0x2d, 0x72, 0xa3, 0x5d, 0xdb, 0x4e, 0xfd, + 0xbc, 0xa6, 0xde, 0x41, 0x21, 0x88, 0xe9, 0x05, 0xe5, 0x6a, 0x80, 0xf1, + 0x0e, 0xc6, 0x58, 0x24, 0x0a, 0x0b, 0xdd, 0x32, 0xef, 0x68, 0xf6, 0x5e, + 0x84, 0xba, 0xbb, 0xc4, 0x14, 0x10, 0x58, 0xcd, 0x8a, 0x00, 0xce, 0xd2, + 0x54, 0xfb, 0x9d, 0x75, 0x69, 0x2b, 0x68, 0x89, 0x4e, 0x71, 0xda, 0x6f, + 0x98, 0x88, 0x38, 0x96, 0xe6, 0x34, 0x99, 0x9f, 0x69, 0x2a, 0x9e, 0xa3, + 0xb8, 0xe7, 0x0c, 0x97, 0xb9, 0x96, 0x58, 0x2a, 0x79, 0x85, 0x8e, 0x4b, + 0xcd, 0x5e, 0xc5, 0x05, 0xbf, 0x44, 0x49, 0x60, 0x9c, 0xa5, 0x49, 0x9f, + 0x2f, 0x30, 0x07, 0x79, 0x54, 0x18, 0xc1, 0x84, 0x79, 0xc6, 0x79, 0xc5, + 0x83, 0x51, 0x44, 0x18, 0x33, 0xcb, 0xf5, 0xe6, 0x72, 0x13, 0x8e, 0x6d, + 0x3d, 0xbe, 0x1d, 0xce, 0x70, 0x31, 0x4b, 0x0d, 0x33, 0x8d, 0x9a, 0xac, + 0xbf, 0xf7, 0x17, 0xd5, 0x62, 0xe3, 0x2f, 0xc0, 0x60, 0x25, 0xf6, 0xc1, + 0x66, 0xd5, 0x49, 0x18, 0x64, 0x4f, 0x34, 0xca, 0xa9, 0xdd, 0x11, 0x81, + 0x36, 0x93, 0xdf, 0xc0, 0xc6, 0x5e, 0x21, 0xc8, 0xbd, 0x15, 0x1e, 0x92, + 0xc7, 0x8d, 0xa0, 0x85, 0xdc, 0x14, 0xb9, 0xa0, 0x6d, 0x93, 0x15, 0x2b, + 0xce, 0x8d, 0x1c, 0x37, 0x75, 0xbb, 0x5a, 0x5b, 0x41, 0x95, 0xb1, 0xff, + 0x82, 0xe9, 0xa0, 0xbb, 0x01, 0x03, 0x15, 0x4b, 0xa1, 0x4e, 0xc6, 0xc2, + 0xb2, 0x77, 0x78, 0x75, 0xd2, 0x13, 0x5e, 0xe0, 0x82, 0xee, 0x6c, 0xd9, + 0x6f, 0x1e, 0x7e, 0xc4, 0x5b, 0x89, 0x10, 0x0e, 0x0b, 0x85, 0x6f, 0xe0, + 0x86, 0xf2, 0x86, 0xc9, 0x20, 0xe0, 0xa5, 0x09, 0x3d, 0x30, 0xed, 0x50, + 0x5e, 0xb5, 0x2b, 0xb9, 0xbe, 0x55, 0x60, 0xa9, 0x25, 0x79, 0xed, 0x3f, + 0xfe, 0xce, 0xc2, 0x63, 0x5a, 0x17, 0xa0, 0xf9, 0x81, 0xe4, 0x79, 0x0b, + 0x0a, 0x8f, 0x32, 0x1f, 0x9b, 0x92, 0xf4, 0x88, 0x68, 0xf4, 0xd8, 0x06, + 0xa9, 0x01, 0x26, 0x6a, 0x5d, 0x67, 0xc7, 0x29, 0x67, 0xd3, 0x47, 0xd0, + 0x69, 0x76, 0xd8, 0x79, 0x43, 0x40, 0xaa, 0xdd, 0x82, 0x3e, 0xc9, 0x2b, + 0x1f, 0x90, 0xb9, 0x27, 0x74, 0x21, 0xb9, 0x29, 0xcd, 0x09, 0x12, 0xb9, + 0x72, 0x2c, 0x73, 0x3c, 0x0e, 0x94, 0x69, 0x37, 0xbd, 0xca, 0x54, 0x31, + 0x93, 0xce, 0x54, 0x21, 0x5b, 0x51, 0xa4, 0xc4, 0x0e, 0xf4, 0x37, 0xa1, + 0x6a, 0x9d, 0x05, 0x6b, 0xec, 0xfb, 0x88, 0x8d, 0xd1, 0x20, 0x33, 0x7d, + 0xbe, 0xf1, 0xda, 0x3b, 0xcf, 0x34, 0x9a, 0x1e, 0xbc, 0x18, 0x3a, 0x44, + 0xd3, 0x62, 0x0e, 0x2e, 0x18, 0x88, 0x05, 0x13, 0x97, 0x7f, 0x09, 0x3a, + 0xb3, 0x18, 0x86, 0x59, 0x1a, 0x9b, 0x15, 0xfc, 0x20, 0xcf, 0xe8, 0x88, + 0xf9, 0x75, 0x06, 0x3b, 0xf5, 0xac, 0x02, 0xd6, 0xee, 0x8c, 0x3c, 0x5c, + 0xda, 0x5b, 0x9e, 0x9b, 0x81, 0xff, 0x5c, 0x70, 0x1c, 0xb4, 0xe1, 0xb6, + 0x9f, 0xd5, 0x15, 0xe8, 0xc0, 0x24, 0xe7, 0x8d, 0xbd, 0x66, 0xd4, 0x82, + 0x97, 0x93, 0xf8, 0x95, 0x66, 0xc7, 0xe5, 0x3a, 0x02, 0x0d, 0xc5, 0x7d, + 0x0d, 0x4f, 0x9a, 0xb6, 0x41, 0xb8, 0x6f, 0x48, 0x68, 0x01, 0x84, 0xe8, + 0x0b, 0x2c, 0x77, 0x1d, 0x79, 0x16, 0x86, 0xc3, 0xf0, 0xa9, 0x41, 0xf1, + 0xda, 0xd5, 0x6f, 0x49, 0x8d, 0xb6, 0x6b, 0x53, 0xc1, 0x63, 0xff, 0x0a, + 0x95, 0xb8, 0x92, 0xf8, 0x21, 0xc2, 0x17, 0xc5, 0xd6, 0xcf, 0x18, 0xda, + 0x1a, 0xb9, 0x71, 0x7e, 0x03, 0x30, 0xfb, 0x40, 0xca, 0xc6, 0xd4, 0x18, + 0xe8, 0xe4, 0x8f, 0xe9, 0x23, 0xd1, 0x02, 0xb2, 0x8d, 0xa1, 0xe2, 0x0f, + 0x88, 0xc8, 0x88, 0x42, 0xb8, 0x32, 0xf7, 0x2d, 0x94, 0x2a, 0xa8, 0x99, + 0x7a, 0x25, 0x3f, 0x2b, 0xf1, 0xc1, 0xdb, 0x83, 0x53, 0xe6, 0x2f, 0x6f, + 0x58, 0x38, 0x18, 0x53, 0x6c, 0x50, 0x4f, 0xf8, 0xec, 0xe8, 0x19, 0x36, + 0x0f, 0xa8, 0xba, 0x9a, 0x2e, 0xb8, 0x8b, 0xab, 0xd7, 0x59, 0xa6, 0x81, + 0xd2, 0x34, 0x03, 0x57, 0x12, 0xaa, 0x2c, 0x92, 0x52, 0xe8, 0x90, 0x59, + 0x19, 0x20, 0xb5, 0x24, 0x1e, 0x0c, 0xa8, 0x66, 0xf9, 0x00, 0xeb, 0xa4, + 0xc5, 0x45, 0xfe, 0x94, 0x92, 0x92, 0x0e, 0xc9, 0x7b, 0x33, 0x11, 0xb0, + 0x92, 0x8e, 0xac, 0xf6, 0xa5, 0x3f, 0x49, 0xd5, 0x29, 0x3a, 0xcf, 0x4f, + 0xf6, 0x59, 0x68, 0x1d, 0x24, 0x1d, 0x67, 0xa0, 0x80, 0x72, 0x37, 0x6f, + 0xa8, 0x0c, 0x84, 0x09, 0xe0, 0x02, 0xa9, 0xa8, 0xcc, 0xc4, 0x01, 0xa2, + 0x50, 0x02, 0xc7, 0xa3, 0xf9, 0x42, 0xbe, 0x55, 0x40, 0xdb, 0xdf, 0x46, + 0x56, 0x5c, 0xd7, 0x9a, 0xe9, 0x28, 0xd4, 0xc7, 0xc7, 0x4e, 0x6b, 0x8e, + 0x5f, 0x52, 0xd4, 0x8d, 0x1b, 0x97, 0x9d, 0xad, 0x87, 0x1a, 0x5d, 0x79, + 0xfa, 0x47, 0xad, 0x3e, 0x70, 0x82, 0x3a, 0x87, 0x49, 0xd7, 0xc4, 0xb3, + 0xd5, 0xb8, 0x48, 0x9a, 0x30, 0x5e, 0x59, 0x88, 0xb4, 0xbf, 0xf9, 0x5a, + 0x7a, 0x11, 0xb3, 0x57, 0x27, 0x3c, 0x24, 0x22, 0x5a, 0x9d, 0x0c, 0x9a, + 0xd4, 0x0d, 0x26, 0xf6, 0xd2, 0x7b, 0x91, 0x68, 0xfe, 0x44, 0xff, 0x54, + 0xd0, 0xef, 0x87, 0xcb, 0x29, 0x4c, 0x23, 0xe2, 0xce, 0x4b, 0xf6, 0x36, + 0x10, 0x6d, 0x54, 0x2a, 0xf0, 0x21, 0xf9, 0x51, 0x25, 0x5f, 0x11, 0x93, + 0xc9, 0x3f, 0x2e, 0x40, 0xed, 0x28, 0x5e, 0x1a, 0xb8, 0x98, 0xc9, 0x63, + 0x94, 0xe7, 0x44, 0x11, 0x76, 0xb8, 0x3b, 0xfd, 0xc4, 0x20, 0x47, 0x26, + 0x62, 0x26, 0x86, 0x92, 0x3d, 0x2f, 0xdb, 0xed, 0xd0, 0x60, 0x0b, 0x2d, + 0x4d, 0xb9, 0xae, 0x76, 0x35, 0xb4, 0xfb, 0x22, 0x7f, 0xcb, 0x5d, 0x76, + 0xca, 0xe7, 0x07, 0xd7, 0x1b, 0xd8, 0x2b, 0x20, 0xf4, 0xad, 0xad, 0x8a, + 0x78, 0xc2, 0xb1, 0xc4, 0x9e, 0x08, 0x63, 0x98, 0x0f, 0xd8, 0x3b, 0xfc, + 0xfa, 0x7c, 0x88, 0x99, 0x50, 0x0c, 0x3b, 0x0f, 0x5a, 0x28, 0xd0, 0xa4, + 0x9f, 0x55, 0xc5, 0xf9, 0x18, 0xea, 0x76, 0x3b, 0xf5, 0x28, 0x61, 0x0e, + 0x0c, 0x17, 0x2b, 0x04, 0x19, 0x56, 0xa3, 0x83, 0xf5, 0xc6, 0x09, 0xb9, + 0x7e, 0xad, 0xa6, 0x63, 0xb1, 0x8d, 0x8d, 0x7f, 0x28, 0xdd, 0x10, 0x7a, + 0x38, 0xa9, 0xeb, 0x72, 0xd1, 0x85, 0x15, 0x93, 0xae, 0x86, 0xe6, 0x41, + 0xd8, 0xec, 0x57, 0x5b, 0x4e, 0x2f, 0x59, 0x93, 0x01, 0xac, 0x12, 0xd5, + 0x7f, 0x9d, 0x5d, 0xb3, 0x06, 0x3d, 0x80, 0xd3, 0x91, 0xd5, 0x90, 0x8b, + 0xa5, 0xef, 0x19, 0xb0, 0xf1, 0x33, 0x9e, 0x6d, 0x30, 0xbd, 0x24, 0x21, + 0x65, 0x87, 0x71, 0x0c, 0x8e, 0x27, 0x05, 0xee, 0x7d, 0xd0, 0x50, 0xf4, + 0x09, 0xf0, 0x24, 0x69, 0xf0, 0x15, 0x43, 0xa6, 0x47, 0xdd, 0x0a, 0x26, + 0x17, 0xa8, 0x1c, 0xad, 0x17, 0x9e, 0xbb, 0x3d, 0x84, 0xf3, 0x2f, 0x53, + 0xe8, 0x87, 0x28, 0x2d, 0xb1, 0xf6, 0xa3, 0xe2, 0x24, 0xa1, 0x2c, 0x35, + 0x9d, 0x1d, 0x48, 0xf0, 0xd4, 0x03, 0xde, 0x4a, 0x31, 0xda, 0x94, 0x7b, + 0x67, 0x6f, 0x97, 0x38, 0x59, 0xc6, 0xdc, 0x07, 0xd0, 0xf5, 0xe7, 0xec, + 0x33, 0x95, 0x0c, 0xf4, 0xb3, 0x6f, 0x9e, 0x71, 0x09, 0x59, 0x1d, 0x55, + 0x1b, 0x3d, 0xc8, 0x89, 0x55, 0xae, 0x95, 0x05, 0xe2, 0x09, 0x55, 0xa1, + 0x2d, 0xd3, 0x19, 0xd7, 0x89, 0x88, 0xf5, 0x3b, 0xae, 0xc5, 0xf2, 0x80, + 0x1d, 0xe4, 0x27, 0xcf, 0xbe, 0x90, 0x99, 0x8b, 0x01, 0xeb, 0xb3, 0xc8, + 0xfe, 0xf2, 0xdd, 0xd5, 0x95, 0x95, 0x9a, 0xa5, 0xe9, 0xec, 0x9f, 0x63, + 0x26, 0x20, 0xca, 0x98, 0x37, 0xe9, 0x5e, 0xcd, 0x95, 0x17, 0x4f, 0xbb, + 0xff, 0xdb, 0x8b, 0xc7, 0x80, 0xee, 0xb1, 0x5d, 0x27, 0x83, 0xd1, 0x9c, + 0x6d, 0xfd, 0x1a, 0x98, 0x99, 0x71, 0x4d, 0x06, 0xbc, 0x47, 0x34, 0xf9, + 0x23, 0x9a, 0xd4, 0x3e, 0x92, 0xd4, 0xd5, 0x6c, 0x6c, 0x5c, 0xab, 0xd0, + 0xaf, 0x19, 0xf9, 0x48, 0xfe, 0xbd, 0x62, 0x72, 0x1d, 0x1e, 0xbc, 0x8a, + 0xa6, 0x21, 0x59, 0xe6, 0xd9, 0xbc, 0x5e, 0xc9, 0x3b, 0x88, 0x38, 0x26, + 0xf4, 0x8e, 0xfc, 0x95, 0xbe, 0x6b, 0xf9, 0x1b, 0x7f, 0x37, 0xd0, 0xfc, + 0x00, 0x4d, 0x08, 0xfd, 0x75, 0xf8, 0x85, 0x48, 0x2e, 0x40, 0x91, 0x9a, + 0xa0, 0xfa, 0x9f, 0x78, 0x39, 0xde, 0x44, 0x73, 0xf9, 0xa4, 0xb7, 0x50, + 0x61, 0x9f, 0x93, 0x0a, 0x09, 0xb5, 0x47, 0x91, 0x0f, 0x21, 0x42, 0x7c, + 0xa5, 0x25, 0xdb, 0xa8, 0x4e, 0xa1, 0x77, 0x35, 0xf7, 0xb6, 0xb3, 0x0b, + 0x36, 0xeb, 0xcc, 0xb4, 0xb8, 0x70, 0xf9, 0xb2, 0xdd, 0x0b, 0x69, 0xaa, + 0xd3, 0x47, 0x03, 0xb9, 0x28, 0xba, 0x80, 0x48, 0xf5, 0xcd, 0x6a, 0x7f, + 0x16, 0x4d, 0xc5, 0xce, 0x8c, 0xbc, 0x95, 0x0f, 0x5a, 0x24, 0xb0, 0x8f, + 0x84, 0xd6, 0xed, 0x79, 0x8e, 0x46, 0x79, 0x82, 0x75, 0x0f, 0x10, 0x3f, + 0x51, 0x8e, 0xb0, 0xc9, 0x40, 0x5b, 0xa3, 0xe0, 0x35, 0xf8, 0x4a, 0xf9, + 0x7e, 0x38, 0x3f, 0xe9, 0x05, 0xb2, 0x44, 0x7d, 0x76, 0xfe, 0xfd, 0x1e, + 0x5b, 0xb7, 0xd6, 0x44, 0x13, 0x53, 0xd7, 0xa2, 0xb0, 0x00, 0xfa, 0xf1, + 0x0b, 0x4d, 0xed, 0x1b, 0x46, 0x97, 0x37, 0xa3, 0xbd, 0x90, 0x0c, 0xed, + 0xc3, 0x0c, 0x40, 0xcd, 0xba, 0x88, 0x09, 0x47, 0x0d, 0x63, 0xc5, 0xa3, + 0x33, 0x2c, 0x9a, 0xef, 0x50, 0xf9, 0xa7, 0xcb, 0x6c, 0xc9, 0xeb, 0xbe, + 0xff, 0x60, 0x88, 0x7e, 0x71, 0xa3, 0xea, 0x0a, 0x6d, 0x54, 0x8d, 0x3d, + 0x54, 0x6e, 0x15, 0xad, 0xaf, 0x4c, 0xbc, 0x62, 0x4b, 0x2e, 0x0e, 0xfb, + 0x07, 0xef, 0xab, 0x56, 0xae, 0xc3, 0xb0, 0xec, 0x11, 0xe5, 0x97, 0xc6, + 0x25, 0xd0, 0x03, 0xd5, 0xc5, 0x0e, 0x35, 0x2c, 0x7a, 0x73, 0xb9, 0x1a, + 0x81, 0xcb, 0x01, 0xf6, 0x01, 0xae, 0x35, 0x7f}; + +const uint8_t kExpectedPrivateKey[BCM_MLDSA65_PRIVATE_KEY_BYTES] = { + 0x0c, 0x6f, 0x38, 0x7d, 0x2a, 0xb4, 0x33, 0x87, 0xf0, 0x21, 0xb0, 0xda, + 0x81, 0x6c, 0x71, 0xf0, 0xbc, 0x81, 0x5e, 0xf0, 0xb1, 0x6a, 0xf1, 0x12, + 0x4f, 0x35, 0x4c, 0x27, 0x3e, 0xed, 0xb4, 0x2f, 0xbf, 0x0e, 0xfa, 0x56, + 0x57, 0x0f, 0xbe, 0xb6, 0x30, 0x07, 0x57, 0xe6, 0xc2, 0xf4, 0xc3, 0x35, + 0xbe, 0x49, 0x22, 0xba, 0xa2, 0xb7, 0x4f, 0x56, 0x52, 0xb5, 0x7c, 0x3a, + 0x45, 0x78, 0x0e, 0x2b, 0x63, 0xf6, 0xaf, 0x3b, 0x98, 0xd7, 0xa9, 0x79, + 0x3e, 0xa4, 0x2c, 0xb3, 0xf4, 0x21, 0xb4, 0x8f, 0xb8, 0x3e, 0x93, 0x20, + 0x5f, 0x61, 0x51, 0x07, 0x30, 0x25, 0x7f, 0xf9, 0x81, 0x7b, 0x77, 0x6b, + 0x9d, 0xb4, 0x05, 0x26, 0x15, 0x79, 0x8d, 0xda, 0x47, 0x6f, 0xd5, 0x45, + 0x4a, 0xe4, 0xe4, 0xfc, 0xb7, 0xeb, 0xe4, 0x40, 0x2d, 0x6b, 0xe1, 0xeb, + 0x5f, 0xcf, 0x52, 0xea, 0xfe, 0xf4, 0x38, 0x37, 0x36, 0x50, 0x31, 0x60, + 0x03, 0x68, 0x60, 0x26, 0x36, 0x50, 0x45, 0x16, 0x42, 0x22, 0x51, 0x23, + 0x54, 0x28, 0x60, 0x51, 0x32, 0x83, 0x06, 0x01, 0x63, 0x13, 0x86, 0x52, + 0x26, 0x32, 0x05, 0x86, 0x80, 0x01, 0x06, 0x74, 0x06, 0x86, 0x43, 0x87, + 0x28, 0x72, 0x85, 0x32, 0x14, 0x12, 0x71, 0x68, 0x76, 0x10, 0x32, 0x57, + 0x55, 0x27, 0x47, 0x38, 0x20, 0x50, 0x81, 0x22, 0x61, 0x67, 0x62, 0x64, + 0x51, 0x43, 0x01, 0x23, 0x38, 0x73, 0x77, 0x34, 0x02, 0x72, 0x83, 0x86, + 0x34, 0x28, 0x72, 0x64, 0x88, 0x68, 0x15, 0x86, 0x27, 0x16, 0x14, 0x02, + 0x45, 0x10, 0x43, 0x13, 0x41, 0x73, 0x45, 0x02, 0x55, 0x45, 0x06, 0x42, + 0x35, 0x28, 0x70, 0x22, 0x81, 0x48, 0x15, 0x36, 0x31, 0x82, 0x18, 0x33, + 0x46, 0x01, 0x64, 0x70, 0x32, 0x82, 0x14, 0x02, 0x41, 0x21, 0x28, 0x70, + 0x67, 0x55, 0x56, 0x44, 0x57, 0x40, 0x81, 0x05, 0x00, 0x66, 0x56, 0x81, + 0x42, 0x04, 0x34, 0x83, 0x77, 0x55, 0x05, 0x47, 0x64, 0x54, 0x36, 0x53, + 0x63, 0x63, 0x72, 0x46, 0x60, 0x12, 0x25, 0x25, 0x03, 0x25, 0x65, 0x64, + 0x84, 0x64, 0x83, 0x34, 0x30, 0x73, 0x11, 0x68, 0x32, 0x56, 0x06, 0x64, + 0x05, 0x40, 0x52, 0x47, 0x37, 0x51, 0x44, 0x06, 0x75, 0x57, 0x36, 0x22, + 0x63, 0x28, 0x25, 0x48, 0x64, 0x21, 0x38, 0x47, 0x01, 0x18, 0x18, 0x82, + 0x10, 0x00, 0x65, 0x33, 0x65, 0x70, 0x46, 0x76, 0x38, 0x63, 0x15, 0x11, + 0x31, 0x73, 0x08, 0x00, 0x37, 0x71, 0x41, 0x16, 0x21, 0x44, 0x72, 0x45, + 0x01, 0x71, 0x55, 0x05, 0x01, 0x87, 0x82, 0x14, 0x70, 0x52, 0x32, 0x00, + 0x76, 0x45, 0x74, 0x62, 0x22, 0x77, 0x47, 0x74, 0x56, 0x26, 0x56, 0x73, + 0x42, 0x84, 0x15, 0x03, 0x44, 0x64, 0x23, 0x73, 0x37, 0x28, 0x67, 0x15, + 0x76, 0x28, 0x81, 0x57, 0x52, 0x70, 0x12, 0x31, 0x13, 0x03, 0x32, 0x27, + 0x03, 0x05, 0x86, 0x27, 0x47, 0x68, 0x26, 0x75, 0x22, 0x38, 0x45, 0x04, + 0x87, 0x05, 0x46, 0x35, 0x51, 0x45, 0x37, 0x03, 0x06, 0x58, 0x78, 0x36, + 0x33, 0x07, 0x36, 0x08, 0x23, 0x41, 0x35, 0x30, 0x88, 0x25, 0x03, 0x72, + 0x26, 0x12, 0x60, 0x06, 0x62, 0x74, 0x51, 0x66, 0x41, 0x70, 0x87, 0x82, + 0x55, 0x22, 0x76, 0x26, 0x50, 0x03, 0x54, 0x03, 0x68, 0x70, 0x71, 0x61, + 0x76, 0x00, 0x45, 0x14, 0x64, 0x41, 0x00, 0x46, 0x44, 0x42, 0x62, 0x34, + 0x38, 0x28, 0x80, 0x06, 0x52, 0x20, 0x67, 0x88, 0x62, 0x75, 0x48, 0x07, + 0x87, 0x61, 0x40, 0x85, 0x55, 0x76, 0x48, 0x24, 0x04, 0x52, 0x00, 0x83, + 0x46, 0x54, 0x20, 0x66, 0x52, 0x55, 0x87, 0x50, 0x65, 0x40, 0x43, 0x65, + 0x01, 0x61, 0x87, 0x25, 0x30, 0x17, 0x72, 0x46, 0x73, 0x60, 0x74, 0x46, + 0x22, 0x76, 0x21, 0x51, 0x01, 0x30, 0x87, 0x38, 0x38, 0x57, 0x88, 0x55, + 0x22, 0x64, 0x80, 0x34, 0x83, 0x20, 0x01, 0x42, 0x04, 0x24, 0x08, 0x04, + 0x87, 0x34, 0x18, 0x26, 0x25, 0x03, 0x13, 0x02, 0x42, 0x81, 0x07, 0x47, + 0x55, 0x53, 0x51, 0x73, 0x07, 0x08, 0x72, 0x32, 0x32, 0x06, 0x13, 0x76, + 0x42, 0x61, 0x11, 0x10, 0x34, 0x22, 0x65, 0x80, 0x18, 0x05, 0x01, 0x64, + 0x44, 0x65, 0x13, 0x20, 0x81, 0x26, 0x03, 0x50, 0x15, 0x34, 0x76, 0x71, + 0x86, 0x52, 0x58, 0x87, 0x53, 0x84, 0x53, 0x57, 0x75, 0x43, 0x13, 0x71, + 0x85, 0x66, 0x41, 0x01, 0x52, 0x15, 0x60, 0x43, 0x24, 0x66, 0x42, 0x83, + 0x02, 0x37, 0x53, 0x44, 0x53, 0x88, 0x15, 0x20, 0x25, 0x77, 0x34, 0x66, + 0x23, 0x70, 0x06, 0x62, 0x81, 0x37, 0x32, 0x05, 0x16, 0x05, 0x26, 0x44, + 0x26, 0x21, 0x58, 0x85, 0x17, 0x75, 0x57, 0x70, 0x47, 0x14, 0x61, 0x21, + 0x26, 0x13, 0x00, 0x48, 0x47, 0x46, 0x27, 0x48, 0x52, 0x50, 0x67, 0x62, + 0x07, 0x27, 0x04, 0x38, 0x72, 0x60, 0x02, 0x74, 0x00, 0x60, 0x80, 0x13, + 0x58, 0x63, 0x74, 0x13, 0x47, 0x57, 0x84, 0x52, 0x18, 0x46, 0x36, 0x18, + 0x72, 0x65, 0x18, 0x20, 0x57, 0x68, 0x76, 0x11, 0x24, 0x02, 0x45, 0x06, + 0x16, 0x46, 0x78, 0x73, 0x86, 0x22, 0x25, 0x16, 0x12, 0x36, 0x66, 0x81, + 0x57, 0x82, 0x80, 0x33, 0x08, 0x74, 0x62, 0x48, 0x85, 0x27, 0x56, 0x01, + 0x88, 0x44, 0x35, 0x44, 0x01, 0x05, 0x38, 0x44, 0x60, 0x46, 0x67, 0x87, + 0x23, 0x43, 0x76, 0x66, 0x52, 0x71, 0x88, 0x87, 0x27, 0x23, 0x14, 0x78, + 0x16, 0x87, 0x80, 0x52, 0x56, 0x13, 0x17, 0x06, 0x07, 0x40, 0x86, 0x62, + 0x12, 0x72, 0x45, 0x25, 0x50, 0x03, 0x32, 0x14, 0x81, 0x70, 0x41, 0x01, + 0x32, 0x81, 0x13, 0x13, 0x13, 0x72, 0x77, 0x00, 0x48, 0x26, 0x64, 0x81, + 0x58, 0x07, 0x23, 0x85, 0x27, 0x13, 0x01, 0x60, 0x26, 0x65, 0x37, 0x61, + 0x84, 0x17, 0x38, 0x08, 0x10, 0x22, 0x01, 0x70, 0x58, 0x65, 0x68, 0x18, + 0x66, 0x40, 0x80, 0x46, 0x50, 0x87, 0x24, 0x70, 0x06, 0x88, 0x37, 0x66, + 0x15, 0x03, 0x31, 0x63, 0x05, 0x73, 0x32, 0x57, 0x72, 0x52, 0x12, 0x76, + 0x72, 0x67, 0x26, 0x13, 0x34, 0x18, 0x75, 0x20, 0x06, 0x83, 0x22, 0x26, + 0x68, 0x84, 0x44, 0x24, 0x47, 0x08, 0x84, 0x44, 0x13, 0x15, 0x86, 0x45, + 0x16, 0x58, 0x63, 0x51, 0x50, 0x34, 0x77, 0x00, 0x58, 0x81, 0x86, 0x32, + 0x78, 0x57, 0x10, 0x25, 0x58, 0x63, 0x48, 0x53, 0x78, 0x75, 0x42, 0x67, + 0x77, 0x52, 0x63, 0x03, 0x33, 0x51, 0x66, 0x11, 0x83, 0x40, 0x76, 0x01, + 0x11, 0x53, 0x64, 0x36, 0x30, 0x11, 0x71, 0x75, 0x76, 0x23, 0x26, 0x81, + 0x32, 0x27, 0x02, 0x56, 0x66, 0x75, 0x07, 0x14, 0x66, 0x35, 0x87, 0x64, + 0x62, 0x56, 0x33, 0x47, 0x82, 0x26, 0x54, 0x73, 0x38, 0x15, 0x41, 0x58, + 0x25, 0x84, 0x80, 0x04, 0x57, 0x83, 0x86, 0x83, 0x77, 0x83, 0x22, 0x83, + 0x65, 0x25, 0x34, 0x58, 0x82, 0x43, 0x33, 0x36, 0x66, 0x68, 0x60, 0x31, + 0x85, 0x48, 0x88, 0x13, 0x57, 0x24, 0x51, 0x34, 0x16, 0x48, 0x60, 0x37, + 0x24, 0x21, 0x62, 0x71, 0x06, 0x25, 0x60, 0x32, 0x82, 0x45, 0x52, 0x43, + 0x15, 0x11, 0x47, 0x77, 0x60, 0x07, 0x15, 0x04, 0x71, 0x53, 0x58, 0x82, + 0x17, 0x68, 0x40, 0x35, 0x21, 0x13, 0x88, 0x88, 0x61, 0x46, 0x24, 0x41, + 0x80, 0x10, 0x22, 0x80, 0x88, 0x37, 0x06, 0x30, 0x76, 0x67, 0x70, 0x03, + 0x18, 0x43, 0x10, 0x74, 0x46, 0x62, 0x21, 0x25, 0x45, 0x56, 0x63, 0x14, + 0x28, 0x11, 0x37, 0x26, 0x88, 0x86, 0x22, 0x35, 0x51, 0x48, 0x78, 0x78, + 0x48, 0x26, 0x40, 0x54, 0x82, 0x12, 0x70, 0x71, 0x78, 0x06, 0x05, 0x87, + 0x17, 0x41, 0x44, 0x00, 0x27, 0x84, 0x33, 0x81, 0x00, 0x16, 0x70, 0x67, + 0x20, 0x62, 0x78, 0x58, 0x46, 0x25, 0x88, 0x06, 0x50, 0x23, 0x44, 0x04, + 0x28, 0x44, 0x35, 0x17, 0x62, 0x61, 0x40, 0x41, 0x50, 0x75, 0x27, 0x50, + 0x76, 0x13, 0x40, 0x40, 0x50, 0x18, 0x22, 0x32, 0x23, 0x51, 0x34, 0x76, + 0x01, 0x25, 0x81, 0x75, 0x23, 0x66, 0x11, 0x48, 0x41, 0x34, 0x57, 0x36, + 0x21, 0x73, 0x75, 0x87, 0x01, 0x88, 0x75, 0x28, 0x72, 0x46, 0x13, 0x70, + 0x77, 0x14, 0x04, 0x80, 0x73, 0x50, 0x27, 0x56, 0x37, 0x22, 0x65, 0x76, + 0x47, 0x78, 0x41, 0x22, 0x38, 0x24, 0x26, 0x82, 0x18, 0x31, 0x10, 0x71, + 0x88, 0x62, 0x73, 0x05, 0x30, 0x27, 0x31, 0x76, 0x80, 0x78, 0x13, 0x21, + 0x31, 0x35, 0x21, 0x54, 0x64, 0x44, 0x86, 0x36, 0x52, 0x42, 0x02, 0x53, + 0x86, 0x07, 0x72, 0x04, 0x07, 0x70, 0x20, 0x80, 0x20, 0x71, 0x50, 0x03, + 0x52, 0x14, 0x24, 0x55, 0x52, 0x06, 0x20, 0x11, 0x40, 0x41, 0x14, 0x44, + 0x15, 0x23, 0x76, 0x00, 0x35, 0x41, 0x88, 0x11, 0x14, 0x57, 0x14, 0x24, + 0x11, 0x62, 0x18, 0x01, 0x23, 0x87, 0x12, 0x73, 0x54, 0x72, 0x32, 0x13, + 0x55, 0x04, 0x65, 0x26, 0x76, 0x22, 0x06, 0x51, 0x01, 0x53, 0x81, 0x08, + 0x24, 0x51, 0x11, 0x88, 0x14, 0x75, 0x37, 0x52, 0x57, 0x18, 0x34, 0x66, + 0x80, 0x78, 0x41, 0x00, 0x64, 0x57, 0x38, 0x28, 0x07, 0x30, 0x56, 0x13, + 0x37, 0x27, 0x68, 0x75, 0x01, 0x60, 0x47, 0x32, 0x40, 0x38, 0x71, 0x00, + 0x70, 0x83, 0x45, 0x32, 0x36, 0x66, 0x56, 0x61, 0x14, 0x28, 0x23, 0x46, + 0x67, 0x27, 0x41, 0x13, 0x06, 0x38, 0x68, 0x02, 0x08, 0x71, 0x68, 0x75, + 0x24, 0x51, 0x70, 0x16, 0x01, 0x61, 0x54, 0x75, 0x75, 0x76, 0x08, 0x77, + 0x76, 0x42, 0x68, 0x48, 0x31, 0x66, 0x16, 0x74, 0x84, 0x60, 0x52, 0x05, + 0x02, 0x47, 0x40, 0x26, 0x12, 0x75, 0x28, 0x73, 0x18, 0x86, 0x80, 0x78, + 0x66, 0x54, 0x28, 0x60, 0x30, 0x52, 0x76, 0x45, 0x66, 0x33, 0x52, 0x15, + 0x03, 0x44, 0x46, 0x62, 0x82, 0x67, 0x41, 0x25, 0x57, 0x84, 0x28, 0x67, + 0x62, 0x52, 0x34, 0x74, 0x53, 0x86, 0x40, 0x52, 0x62, 0x40, 0x37, 0x78, + 0x77, 0x45, 0x67, 0x88, 0x08, 0x53, 0x32, 0x21, 0x84, 0x13, 0x34, 0x01, + 0x41, 0x65, 0x62, 0x31, 0x68, 0x30, 0x07, 0x13, 0x04, 0x13, 0x84, 0x40, + 0x30, 0x77, 0x72, 0x73, 0x07, 0x86, 0x73, 0x34, 0x51, 0x52, 0x30, 0x28, + 0x18, 0x02, 0x21, 0x28, 0x61, 0x37, 0x76, 0x60, 0x11, 0x13, 0x01, 0x47, + 0x36, 0x18, 0x08, 0x10, 0x21, 0x17, 0x11, 0x20, 0x87, 0x72, 0x21, 0x04, + 0x42, 0x34, 0x58, 0x58, 0x04, 0x13, 0x58, 0x11, 0x84, 0x86, 0x75, 0x85, + 0x62, 0x73, 0x26, 0x10, 0x70, 0x37, 0x55, 0x45, 0x68, 0x06, 0x25, 0x41, + 0x53, 0x75, 0x81, 0x58, 0x84, 0x27, 0x83, 0x08, 0x37, 0x83, 0x13, 0x38, + 0x86, 0x42, 0x70, 0x82, 0x67, 0x61, 0x48, 0x54, 0x20, 0x41, 0x82, 0x32, + 0x57, 0x81, 0x64, 0x32, 0x12, 0x60, 0x53, 0x75, 0x48, 0x16, 0x22, 0x78, + 0x16, 0x21, 0x25, 0x36, 0x27, 0x37, 0x83, 0x24, 0x52, 0x82, 0x20, 0x74, + 0x74, 0x53, 0x76, 0x58, 0x46, 0x72, 0x88, 0x50, 0x23, 0x83, 0x36, 0x02, + 0x13, 0x12, 0x23, 0x37, 0x08, 0x54, 0x85, 0x11, 0x46, 0x52, 0x74, 0x85, + 0x41, 0x00, 0x06, 0x01, 0x36, 0x70, 0x51, 0x00, 0x16, 0x57, 0x05, 0x10, + 0x00, 0x86, 0x20, 0x06, 0x11, 0x05, 0x33, 0x05, 0x12, 0x08, 0x75, 0x10, + 0x19, 0x3a, 0x4a, 0xa5, 0x53, 0xcb, 0xe3, 0xe7, 0x69, 0xd3, 0x04, 0x28, + 0x29, 0x68, 0xf1, 0x94, 0x49, 0xcd, 0xee, 0xa9, 0x25, 0xe3, 0x95, 0x74, + 0x57, 0xa7, 0x1e, 0xac, 0xf1, 0x2f, 0xc5, 0xa6, 0x63, 0x2a, 0xa6, 0x15, + 0x98, 0x98, 0x6e, 0x15, 0x83, 0xc0, 0xab, 0x5d, 0x8e, 0xbf, 0x69, 0xe4, + 0x50, 0xb7, 0x47, 0x8a, 0x81, 0x63, 0x9b, 0xdf, 0x71, 0x61, 0x59, 0x62, + 0x77, 0xd1, 0x3e, 0xd2, 0xf0, 0xa3, 0xc9, 0xa4, 0xed, 0x0a, 0x28, 0xcf, + 0x5d, 0x8b, 0x3e, 0x29, 0xbc, 0x0e, 0x5c, 0x04, 0x10, 0x8d, 0x13, 0xcd, + 0x58, 0xc2, 0x02, 0x8d, 0xb8, 0x2e, 0xfa, 0x1a, 0x86, 0x12, 0x61, 0x4f, + 0x8b, 0xc7, 0x90, 0x01, 0x65, 0x61, 0x1c, 0xa5, 0x9a, 0x32, 0x32, 0x59, + 0x90, 0x56, 0xb6, 0x5c, 0xbd, 0x6a, 0x85, 0x8a, 0x14, 0xd6, 0x4d, 0xf2, + 0x68, 0xe9, 0x6b, 0x61, 0x66, 0x3a, 0x9c, 0x79, 0xed, 0xc4, 0x5f, 0x13, + 0xab, 0x8d, 0x71, 0xe4, 0x5d, 0x0d, 0xee, 0xd4, 0x11, 0xdf, 0x53, 0x21, + 0x75, 0x64, 0x61, 0x48, 0x6c, 0xf0, 0x30, 0xca, 0x60, 0x92, 0xf2, 0x02, + 0x5d, 0xc4, 0x11, 0x18, 0x14, 0xfb, 0xb4, 0xf2, 0xc2, 0x58, 0x99, 0xc8, + 0x73, 0x0b, 0xf9, 0xcf, 0x0b, 0xf7, 0x7a, 0x86, 0x36, 0xa0, 0xb5, 0x02, + 0x48, 0x5b, 0x42, 0x21, 0xf7, 0x82, 0x03, 0x16, 0x4d, 0x9f, 0x32, 0x2f, + 0xca, 0xfe, 0x06, 0x5a, 0xd4, 0xc9, 0x47, 0x73, 0x6e, 0xdc, 0x4d, 0x6a, + 0xc7, 0x70, 0x4c, 0xf9, 0x99, 0xba, 0x1c, 0xfe, 0xf4, 0xf3, 0x0d, 0x55, + 0x89, 0x74, 0x73, 0xd9, 0xef, 0x0f, 0x0b, 0xce, 0x3c, 0xc0, 0xd3, 0x50, + 0xf2, 0xc8, 0x1e, 0x64, 0x35, 0xb0, 0x3b, 0x50, 0xb0, 0x10, 0xb5, 0x6b, + 0x5b, 0x4f, 0xdd, 0xad, 0xd3, 0x41, 0x31, 0x40, 0x9b, 0x22, 0xbb, 0x7d, + 0xf5, 0x5f, 0x26, 0x23, 0x4c, 0x58, 0x3d, 0x12, 0x58, 0x5a, 0x60, 0x48, + 0x73, 0xff, 0x81, 0x4f, 0xa0, 0xaf, 0xa5, 0x86, 0xc9, 0xb3, 0xea, 0x33, + 0x00, 0x16, 0x6a, 0x8a, 0xff, 0x64, 0xcc, 0x2e, 0x6c, 0xae, 0x70, 0x2c, + 0x51, 0x4b, 0x7e, 0xea, 0x83, 0x46, 0xe4, 0x2f, 0x01, 0xfb, 0x85, 0x4c, + 0x6e, 0x37, 0x8f, 0x61, 0x1d, 0x73, 0xc9, 0x11, 0xf4, 0x2d, 0xec, 0xac, + 0x6e, 0x76, 0x0b, 0xe1, 0x03, 0xf0, 0xa0, 0x5c, 0x55, 0x81, 0xdc, 0xa7, + 0x27, 0x17, 0xcd, 0xad, 0xc7, 0x9c, 0x1a, 0x99, 0x20, 0x92, 0xb8, 0x25, + 0x05, 0x1b, 0x3f, 0x80, 0xbe, 0x35, 0x28, 0x98, 0x58, 0x47, 0x10, 0xc7, + 0xdc, 0x07, 0x2c, 0xe3, 0x22, 0x55, 0xff, 0xbc, 0x57, 0x23, 0xd5, 0x04, + 0xb0, 0x2c, 0x4e, 0x65, 0x1b, 0x60, 0xc9, 0x9b, 0xb6, 0x19, 0x7b, 0x6a, + 0xf3, 0xf6, 0xb6, 0xa5, 0x98, 0x18, 0xea, 0xe8, 0x47, 0xc5, 0x99, 0xe5, + 0x0f, 0xe5, 0x66, 0x32, 0x8e, 0x55, 0x6b, 0x61, 0x4d, 0xde, 0x30, 0x01, + 0x91, 0xc7, 0x82, 0xac, 0xc0, 0xe0, 0x17, 0x5b, 0x3f, 0xa4, 0xf3, 0x70, + 0x2d, 0x2c, 0xc5, 0x82, 0x1b, 0x6b, 0xae, 0x3e, 0xe4, 0x04, 0xa7, 0xce, + 0x36, 0x27, 0x47, 0xd1, 0xf2, 0xf8, 0xc3, 0x79, 0xce, 0xa1, 0xdf, 0xdc, + 0xc8, 0x32, 0x80, 0xb1, 0x3d, 0x39, 0xc0, 0xd4, 0x80, 0x9f, 0xcf, 0x7e, + 0x85, 0x76, 0x25, 0xcc, 0x57, 0xb1, 0xf1, 0xcf, 0x6c, 0xc5, 0x41, 0x11, + 0xac, 0x48, 0xfe, 0xd1, 0x52, 0xed, 0xde, 0xb9, 0xa4, 0x73, 0x6d, 0x85, + 0x54, 0x40, 0x5f, 0x6e, 0x5d, 0x7d, 0x1b, 0xc9, 0xcb, 0x5a, 0x1e, 0xc5, + 0xdd, 0x98, 0x94, 0x7d, 0xbe, 0x84, 0x8a, 0x40, 0x6a, 0x27, 0x45, 0x61, + 0x2c, 0x8a, 0x04, 0x9e, 0x0b, 0xa3, 0xc2, 0x95, 0xb0, 0x65, 0xf6, 0xb5, + 0xc8, 0xff, 0x13, 0x47, 0x10, 0xa9, 0xb4, 0xa1, 0x75, 0x94, 0xcd, 0x98, + 0xf4, 0x22, 0x3f, 0xa6, 0x1c, 0x9b, 0xd1, 0xaf, 0x33, 0x69, 0xcb, 0x9a, + 0x88, 0x67, 0x16, 0xf6, 0x90, 0x4e, 0xdd, 0x61, 0x91, 0x84, 0xe3, 0xf0, + 0x74, 0x73, 0x7e, 0x19, 0x4e, 0x75, 0xd7, 0x5a, 0xcb, 0x40, 0x13, 0x12, + 0x5f, 0x6f, 0xe5, 0x77, 0x0c, 0x5e, 0x3c, 0x6b, 0x87, 0xbf, 0xdf, 0x61, + 0xbe, 0x97, 0xbd, 0x38, 0xcd, 0xf7, 0x36, 0xee, 0x23, 0xcc, 0x7e, 0xd0, + 0x0a, 0xc2, 0xfe, 0x4e, 0xec, 0x9c, 0x9a, 0x07, 0xec, 0xd3, 0xb2, 0x1c, + 0x1c, 0x88, 0xfa, 0xfa, 0x26, 0x61, 0x97, 0x93, 0x87, 0xa4, 0xc8, 0xaa, + 0x4e, 0xf6, 0x8c, 0x22, 0xd4, 0xe8, 0x36, 0x97, 0x9c, 0x11, 0xe6, 0xf2, + 0x2b, 0x1c, 0x6c, 0x33, 0xea, 0xc4, 0xdc, 0xd6, 0x7b, 0xe7, 0x96, 0xe6, + 0xbc, 0x14, 0xa6, 0xc4, 0x7c, 0x78, 0x1f, 0xfa, 0x34, 0xd6, 0xaf, 0x28, + 0x29, 0xe6, 0x0a, 0xab, 0xca, 0x87, 0xaf, 0xb8, 0x2f, 0xab, 0x5f, 0x4a, + 0xc3, 0xfa, 0xd2, 0xa7, 0xef, 0xef, 0x21, 0xbd, 0xef, 0x9c, 0xb9, 0x59, + 0x1c, 0xa2, 0x8c, 0x1f, 0x0e, 0x86, 0xa5, 0xc9, 0x8b, 0x3d, 0xbe, 0x6e, + 0xba, 0x8c, 0xef, 0xa8, 0xb6, 0x0d, 0x54, 0x1e, 0x6f, 0x5d, 0x22, 0xf4, + 0x0c, 0x2e, 0x8b, 0x27, 0xaa, 0xc5, 0x9e, 0x43, 0x5a, 0xfd, 0x2f, 0x4b, + 0x49, 0x63, 0x69, 0x57, 0x02, 0x8b, 0xb2, 0xef, 0x21, 0xad, 0xdf, 0x3d, + 0x4a, 0x67, 0x0f, 0xad, 0xf7, 0x45, 0x17, 0xb3, 0x6e, 0xdd, 0x21, 0x9a, + 0xc2, 0x69, 0x3e, 0xc1, 0x9e, 0xe1, 0x96, 0x96, 0xad, 0xeb, 0x16, 0x69, + 0xa7, 0x8b, 0x14, 0x95, 0x6e, 0x47, 0xf9, 0x9f, 0x34, 0x3e, 0x66, 0x9d, + 0xcb, 0x0a, 0xb5, 0xff, 0xae, 0x2c, 0xff, 0x4e, 0x4d, 0xf5, 0x02, 0xa6, + 0xc9, 0xe8, 0x29, 0x56, 0xb3, 0xa8, 0x8c, 0xf5, 0xe6, 0x97, 0xa7, 0x00, + 0x1b, 0x98, 0x8f, 0xd3, 0xe9, 0x14, 0x0e, 0xf2, 0x85, 0x2f, 0xa9, 0xb7, + 0xb6, 0xca, 0x99, 0x06, 0x17, 0x1b, 0xf6, 0xce, 0x9e, 0x50, 0xf1, 0x33, + 0x62, 0xd0, 0xe5, 0xa0, 0x05, 0x01, 0x0d, 0xf8, 0x56, 0xf0, 0x35, 0x04, + 0xbd, 0xf2, 0x2c, 0x15, 0x75, 0x96, 0x89, 0xd9, 0x3c, 0xca, 0x84, 0x14, + 0x2b, 0x37, 0x64, 0x1b, 0x28, 0x62, 0xda, 0xb3, 0xc5, 0x2d, 0x26, 0x38, + 0x0f, 0x29, 0x39, 0x03, 0x3b, 0x75, 0x82, 0xeb, 0x6a, 0xd7, 0x1f, 0x57, + 0xb0, 0x66, 0x6f, 0xd3, 0xb6, 0xe5, 0xd2, 0x68, 0x14, 0x8f, 0xe8, 0xd7, + 0x09, 0x53, 0x98, 0xb6, 0xff, 0xa4, 0x85, 0x21, 0x7a, 0x07, 0x4a, 0xf3, + 0xe8, 0xe2, 0xc7, 0x20, 0x31, 0x77, 0x79, 0x37, 0xf3, 0x27, 0xe6, 0xd3, + 0xfb, 0x8b, 0xa8, 0xf4, 0x71, 0x27, 0xe4, 0xea, 0x63, 0xaf, 0xce, 0x9f, + 0x0b, 0x25, 0x01, 0x84, 0x31, 0x60, 0x30, 0x06, 0x11, 0x19, 0x31, 0x74, + 0xf2, 0xce, 0x17, 0x6a, 0x22, 0xfe, 0x62, 0x0e, 0xfb, 0x54, 0xdf, 0xe4, + 0xfd, 0x96, 0x69, 0x99, 0x1d, 0x95, 0xed, 0xcb, 0x9f, 0xb1, 0x89, 0xce, + 0x77, 0x84, 0x46, 0x87, 0x7d, 0x71, 0xb0, 0xd6, 0x35, 0xd1, 0x3d, 0xcd, + 0xb5, 0xa1, 0xaa, 0xee, 0xa2, 0x66, 0xb5, 0xf0, 0x1f, 0x4a, 0x12, 0x88, + 0xc8, 0x95, 0x02, 0x2c, 0x1a, 0xe8, 0x49, 0xda, 0x28, 0x10, 0x1a, 0xd0, + 0xc0, 0x33, 0x6c, 0xb6, 0x69, 0xb2, 0x1a, 0xa4, 0xf5, 0x47, 0xc8, 0x05, + 0x12, 0x22, 0xf3, 0xb5, 0xa4, 0x50, 0xa8, 0x1f, 0xab, 0x2c, 0xef, 0x5d, + 0x8d, 0xfe, 0x98, 0x9e, 0xdb, 0x1f, 0x63, 0xf3, 0x34, 0x1a, 0x82, 0xce, + 0xaf, 0x59, 0x61, 0xa5, 0x78, 0xfd, 0x5f, 0xef, 0xd9, 0xfe, 0xab, 0x06, + 0xd0, 0x14, 0xf1, 0x8a, 0x18, 0xbc, 0x32, 0xe2, 0xc0, 0x1b, 0x3d, 0xb1, + 0x72, 0x77, 0xa6, 0x94, 0x8c, 0x6e, 0x05, 0xa2, 0x6b, 0x80, 0xd0, 0x1b, + 0xd7, 0x59, 0xe3, 0x59, 0x5e, 0x6e, 0x10, 0x53, 0xd4, 0x2c, 0x68, 0x82, + 0x9a, 0xfc, 0x39, 0x9d, 0x19, 0xb3, 0x84, 0x3d, 0x4c, 0xaa, 0xe6, 0x71, + 0x59, 0x01, 0x29, 0x96, 0xcb, 0x96, 0xb2, 0x68, 0x5e, 0x8f, 0xdb, 0xc4, + 0x4e, 0xca, 0x20, 0x4b, 0xe5, 0x52, 0x37, 0xd6, 0xce, 0x36, 0xc0, 0x01, + 0xb7, 0xae, 0x7d, 0xe2, 0x2b, 0xd6, 0xcb, 0xb1, 0x9c, 0x66, 0xd9, 0x67, + 0xf8, 0x54, 0xcc, 0x2e, 0x2b, 0x2c, 0x58, 0xd0, 0x56, 0xba, 0x71, 0x62, + 0x1f, 0xda, 0xfc, 0xd2, 0xe5, 0xf2, 0xf7, 0xbd, 0x49, 0xcf, 0xa4, 0x7f, + 0x91, 0x53, 0xac, 0x08, 0x9e, 0xba, 0xd0, 0x85, 0x4d, 0x51, 0x30, 0xd1, + 0x58, 0x3c, 0x4c, 0xbe, 0x3d, 0x80, 0x7a, 0x5b, 0xe6, 0xb1, 0x49, 0x88, + 0xc6, 0xf8, 0xf7, 0xc6, 0xf4, 0xbc, 0xbb, 0x98, 0x59, 0x88, 0x61, 0xff, + 0xe1, 0x9e, 0x8a, 0xbc, 0x83, 0x11, 0xf0, 0xe0, 0x47, 0xa5, 0xea, 0x02, + 0x2e, 0xc6, 0xdd, 0x5a, 0xf5, 0x0d, 0x24, 0xf9, 0x00, 0x5f, 0xcc, 0xc9, + 0xe7, 0x16, 0x0d, 0xaa, 0x32, 0x34, 0xfe, 0x5c, 0x7b, 0x26, 0x47, 0x0a, + 0xb5, 0x61, 0xa2, 0x6c, 0x39, 0x46, 0x87, 0xca, 0xac, 0x75, 0xfe, 0x34, + 0x38, 0x92, 0x62, 0xbd, 0xfe, 0xa3, 0x75, 0x97, 0x2b, 0xf1, 0xc2, 0xbb, + 0x37, 0xf2, 0x52, 0xad, 0xdb, 0xc0, 0xfe, 0x76, 0x0f, 0x1f, 0x3a, 0xe6, + 0xae, 0xde, 0xb8, 0x67, 0x62, 0x94, 0xc4, 0x2f, 0xc8, 0x6a, 0xc8, 0x49, + 0x11, 0x90, 0x80, 0x0c, 0xca, 0x46, 0x66, 0x52, 0x7e, 0x51, 0x1d, 0x4d, + 0x19, 0x73, 0xf7, 0x10, 0xa0, 0x77, 0xdd, 0x0b, 0x38, 0x2c, 0x79, 0xa4, + 0x6e, 0xe3, 0xce, 0x5f, 0x1c, 0xf8, 0xcd, 0x96, 0x7a, 0xed, 0x48, 0x9e, + 0x14, 0x32, 0x69, 0x8a, 0xb3, 0xaf, 0xe1, 0x22, 0xb0, 0x29, 0xb3, 0x3b, + 0x61, 0x8f, 0xfc, 0xf4, 0xc3, 0xf8, 0x7d, 0x2a, 0x9c, 0x0a, 0x30, 0xe9, + 0x43, 0x56, 0xdc, 0xd8, 0xbf, 0xe3, 0x95, 0x6e, 0xa4, 0x25, 0x9b, 0x92, + 0xae, 0x30, 0xdc, 0x07, 0x76, 0x39, 0x08, 0x22, 0xe2, 0xd0, 0xf0, 0x4c, + 0xb6, 0x0b, 0xa5, 0x69, 0x2b, 0xe9, 0x58, 0x24, 0x85, 0x6b, 0x92, 0xb9, + 0x4b, 0xf7, 0x25, 0xdc, 0xbe, 0x77, 0x6c, 0xc0, 0xf3, 0xa9, 0x81, 0x01, + 0x8d, 0x95, 0x62, 0x5b, 0x8b, 0x78, 0x76, 0xb8, 0x75, 0x1f, 0xbe, 0x4e, + 0x19, 0xb1, 0x69, 0xb5, 0xdf, 0x96, 0x35, 0x51, 0x11, 0x05, 0x81, 0x29, + 0xd5, 0x20, 0x21, 0x48, 0xc2, 0xc5, 0x94, 0xdc, 0xf4, 0x2a, 0xc3, 0x45, + 0xc5, 0x88, 0xc0, 0x5f, 0x16, 0xd4, 0x42, 0x55, 0x84, 0xe9, 0x14, 0x85, + 0xe1, 0x7c, 0x01, 0x33, 0xd5, 0x6a, 0x9b, 0x56, 0x49, 0x8a, 0xd6, 0x79, + 0xc4, 0x2b, 0x3d, 0x0d, 0xce, 0x83, 0x48, 0xee, 0x92, 0x31, 0xec, 0xc0, + 0x6e, 0xf0, 0x05, 0xa9, 0xe3, 0x02, 0x8f, 0x5b, 0xdb, 0xc4, 0x1b, 0xff, + 0x55, 0x8f, 0x02, 0xbd, 0xfb, 0x37, 0xfa, 0x7c, 0x84, 0x22, 0x36, 0xd6, + 0x45, 0xf9, 0xf1, 0x95, 0xad, 0xe1, 0xb4, 0xee, 0xc2, 0x23, 0xba, 0xa6, + 0x8b, 0xbf, 0xe6, 0xa0, 0x72, 0x1b, 0x3e, 0x98, 0xed, 0x90, 0x4c, 0x33, + 0x2f, 0x90, 0x14, 0x9e, 0x45, 0x2f, 0xf6, 0x42, 0xfc, 0x99, 0xef, 0x8e, + 0xb3, 0x29, 0x37, 0x2a, 0x8a, 0xe3, 0xc0, 0xb9, 0x69, 0xcd, 0x7f, 0x9b, + 0x54, 0x37, 0x91, 0x46, 0x5a, 0xb5, 0x7a, 0x20, 0x9f, 0xff, 0x48, 0x08, + 0xc3, 0xa7, 0xf4, 0x4d, 0xa5, 0x84, 0x4e, 0x14, 0x08, 0x45, 0xa3, 0x09, + 0x03, 0x30, 0x9e, 0x7f, 0x83, 0xf4, 0x30, 0xe7, 0xfb, 0x8b, 0x49, 0xaf, + 0xe2, 0xde, 0x3c, 0x65, 0x16, 0x2d, 0xa1, 0x77, 0x53, 0xd1, 0x4b, 0xda, + 0x43, 0xcb, 0xbe, 0xaf, 0x5c, 0x47, 0x25, 0x47, 0x3a, 0x99, 0xb7, 0x1e, + 0x4e, 0x02, 0xf9, 0xba, 0x34, 0xe2, 0xb9, 0xbf, 0x48, 0x16, 0xba, 0x6f, + 0x42, 0xfa, 0xfa, 0x85, 0x9d, 0x02, 0x64, 0xd1, 0x8e, 0x8a, 0x93, 0x62, + 0x5e, 0x32, 0x35, 0x13, 0xdb, 0xb5, 0x55, 0x36, 0x29, 0x20, 0xc7, 0xf9, + 0x5b, 0x6b, 0xd1, 0x85, 0xc5, 0xcd, 0x10, 0x7a, 0x1d, 0x91, 0x83, 0x3d, + 0xc2, 0x7d, 0x23, 0x24, 0x13, 0xff, 0x9b, 0xa9, 0x00, 0x9d, 0x90, 0x3f, + 0xc6, 0xcc, 0xdf, 0x4b, 0x9f, 0xc8, 0x0f, 0x5a, 0xef, 0x4b, 0x39, 0x3b, + 0x5a, 0x46, 0x8d, 0x60, 0xb1, 0xa1, 0x22, 0xf3, 0xcc, 0x61, 0x3a, 0x77, + 0x69, 0x30, 0x02, 0x14, 0x78, 0xf4, 0xb8, 0x78, 0xce, 0x4e, 0x52, 0xaa, + 0x48, 0x39, 0xb2, 0x0f, 0x52, 0x3b, 0xb7, 0xca, 0x7a, 0x94, 0x50, 0x20, + 0x05, 0x37, 0x65, 0x21, 0x95, 0x7f, 0x99, 0x21, 0xdc, 0x76, 0xd7, 0x4d, + 0xed, 0x38, 0xb5, 0x87, 0x3a, 0xab, 0x53, 0x77, 0xf1, 0xf3, 0xfc, 0x5d, + 0x23, 0xe2, 0x09, 0x14, 0x60, 0x0b, 0x8a, 0xe6, 0x2c, 0xb4, 0x8b, 0x73, + 0x44, 0x82, 0x16, 0x58, 0x20, 0x77, 0x0b, 0xa1, 0xd0, 0x31, 0x23, 0x2b, + 0xf7, 0x5e, 0x9e, 0xc2, 0x50, 0x8e, 0x75, 0x28, 0x6a, 0x63, 0x4e, 0xed, + 0xac, 0x93, 0xdb, 0x08, 0x27, 0x50, 0x54, 0x47, 0x0d, 0xc4, 0x64, 0xc4, + 0x1d, 0x28, 0x58, 0xfc, 0xd8, 0x0e, 0x05, 0x89, 0xd0, 0x83, 0x11, 0x36, + 0x95, 0xdd, 0xcf, 0xc2, 0x4a, 0x8c, 0x47, 0xc4, 0x8a, 0xf5, 0xe2, 0x20, + 0x4a, 0x15, 0x50, 0xf1, 0xfc, 0xbe, 0xa0, 0x3e, 0xe6, 0xed, 0x7c, 0x33, + 0xd9, 0x93, 0x2b, 0xb8, 0x6b, 0xc9, 0x6c, 0x3a, 0x75, 0xd7, 0xd4, 0xd3, + 0x92, 0x9f, 0xa9, 0x58, 0x77, 0xd1, 0x23, 0x91, 0x6e, 0x5e, 0x21, 0x8b, + 0x05, 0x40, 0x6f, 0x16, 0x25, 0x5d, 0x13, 0xf3, 0x5a, 0xfc, 0x1b, 0xd0, + 0x4e, 0x43, 0x6b, 0x3f, 0x83, 0xfc, 0xb2, 0xe1, 0x8a, 0x50, 0x6a, 0xad, + 0x68, 0xe4, 0x11, 0x15, 0x77, 0x65, 0x47, 0xf8, 0x36, 0xba, 0x3a, 0x0f, + 0x97, 0x16, 0xcc, 0xaf, 0xc1, 0x84, 0x2e, 0x20, 0x40, 0x96, 0x56, 0xb9, + 0x36, 0x13, 0x9e, 0xcb, 0x0d, 0x68, 0xd0, 0xfe, 0x6c, 0x9d, 0xc3, 0x81, + 0xa0, 0xb9, 0x4b, 0x59, 0xfb, 0x13, 0xb9, 0xa4, 0xd5, 0xae, 0x32, 0x0a, + 0x5f, 0xac, 0x53, 0x83, 0x2b, 0x60, 0x57, 0x63, 0x22, 0xa8, 0x57, 0x18, + 0xbd, 0xb9, 0xe5, 0x4c, 0x3c, 0xb0, 0x4a, 0x70, 0x66, 0xc3, 0x90, 0xcf, + 0x46, 0x67, 0xaa, 0x9b, 0xbb, 0x7d, 0x48, 0x58, 0xbf, 0x22, 0x00, 0xf3, + 0x2a, 0xad, 0xe8, 0xb5, 0x80, 0xf7, 0x53, 0xf1, 0xf6, 0xd4, 0xe2, 0x2d, + 0xdf, 0xde, 0x76, 0x91, 0x45, 0x29, 0x65, 0x39, 0xfe, 0xba, 0x5b, 0xd8, + 0x77, 0x18, 0x3b, 0x89, 0xe2, 0x3a, 0xe5, 0x03, 0x79, 0xd5, 0x47, 0xa1, + 0x37, 0xb5, 0x86, 0x55, 0xef, 0x01, 0xcc, 0x35, 0x7f, 0x1b, 0x68, 0xc1, + 0xde, 0x36, 0xc9, 0x72, 0x5d, 0xf6, 0xa2, 0x04, 0x74, 0x62, 0xda, 0x30, + 0xe1, 0x7a, 0x37, 0xdd, 0x34, 0x77, 0x5b, 0x4b, 0xc3, 0xf8, 0xe9, 0x47, + 0xcf, 0x97, 0xd3, 0x4d, 0x30, 0xee, 0x20, 0x6b, 0x29, 0xd8, 0x9c, 0x7f, + 0x26, 0xab, 0x31, 0x57, 0x9d, 0xb9, 0x6a, 0xac, 0x42, 0x54, 0x99, 0x8c, + 0xa6, 0x04, 0x08, 0x73, 0x92, 0x0b, 0xf4, 0x92, 0x3f, 0x8a, 0x2f, 0xea, + 0x03, 0xdf, 0x8e, 0xa0, 0xcb, 0x99, 0x3a, 0x97, 0x18, 0xc5, 0xd2, 0x67, + 0x1b, 0xf0, 0x19, 0x63, 0xbd, 0x12, 0x89, 0x3f, 0x2c, 0xd5, 0xbe, 0x11, + 0x64, 0xdb, 0x1a, 0xe1, 0x23, 0x4a, 0x59, 0x67, 0xf3, 0x2f, 0xe1, 0x8e, + 0x4e, 0x97, 0x26, 0xbf, 0x04, 0xab, 0xe4, 0x08, 0x4e, 0x6e, 0x77, 0x3c, + 0xe0, 0x09, 0x65, 0x5e, 0xf0, 0xba, 0xac, 0x29, 0x6b, 0xf9, 0x1d, 0xea, + 0xe5, 0x8d, 0x5c, 0x96, 0x2a, 0x34, 0x32, 0x99, 0x59, 0x1e, 0xb6, 0x41, + 0x45, 0xfc, 0x42, 0x9b, 0x4a, 0x27, 0x2c, 0x29, 0x53, 0xc7, 0xa9, 0x85, + 0x5f, 0x07, 0xdd, 0xb0, 0x96, 0xbf, 0x55, 0x86, 0x1d, 0x04, 0xb3, 0x0e, + 0x32, 0x31, 0x34, 0xd6, 0x01, 0x82, 0x79, 0xb4, 0x9d, 0x48, 0xf3, 0x25, + 0x2f, 0xb4, 0xf9, 0x7d, 0xe7, 0xfa, 0x23, 0x92, 0x36, 0x87, 0x2f, 0xa2, + 0xf9, 0x99, 0x5c, 0x7e, 0x7c, 0xdb, 0x5b, 0x64, 0xcf, 0xb7, 0x74, 0x91, + 0xb7, 0x4a, 0x9f, 0xe7, 0x1f, 0x9a, 0x74, 0x1a, 0x6b, 0xdc, 0x7c, 0xa7, + 0x8a, 0x20, 0x94, 0x0a, 0x2d, 0xc7, 0xc6, 0xcf, 0x6e, 0x25, 0xe9, 0xa8, + 0x2c, 0xd9, 0xed, 0x78, 0x05, 0xa4, 0x65, 0x20, 0xa6, 0xa9, 0xed, 0x61, + 0xd9, 0xb7, 0xf8, 0x43, 0xf1, 0xcc, 0xff, 0x59, 0xcd, 0x6b, 0x9e, 0x7b, + 0x4c, 0x91, 0xe9, 0xab, 0x7a, 0x6f, 0x87, 0x7e, 0x66, 0x4a, 0xfb, 0xac, + 0xd6, 0xec, 0x95, 0xab, 0xa4, 0x4c, 0x68, 0x69, 0x4e, 0xb4, 0x80, 0xf5, + 0x32, 0x2b, 0xd4, 0xa5, 0x08, 0x88, 0x9f, 0x19, 0xf2, 0x12, 0x5c, 0xc1, + 0xcb, 0xcc, 0x46, 0xb5, 0xcc, 0x77, 0xbb, 0xc4, 0xc4, 0x01, 0xd9, 0xd6, + 0x49, 0x79, 0xe9, 0x62, 0x96, 0xe6, 0xc0, 0x43, 0xde, 0x00, 0x0d, 0xae, + 0x60, 0x06, 0x47, 0xb9, 0x5c, 0x81, 0x39, 0xa0, 0x06, 0x05, 0x2a, 0x62, + 0xab, 0xe5, 0x15, 0x47, 0xc9, 0x0a, 0xe3, 0x16, 0x6a, 0xfc, 0x4d, 0x73, + 0xbf, 0xee, 0x0b, 0x3f, 0x4d, 0x08, 0xee, 0x1c, 0x66, 0x03, 0x42, 0x56, + 0xd9, 0xfb, 0xe2, 0x8e, 0xd2, 0xf1, 0xc7, 0x41, 0x3d, 0x32, 0xa8, 0x64, + 0xa6, 0x81, 0x28, 0x7d, 0x0e, 0x6e, 0xb3, 0x2c, 0xb5, 0x64, 0xda, 0xda, + 0xf9, 0x0c, 0x4b, 0x77, 0x5a, 0xa2, 0xf3, 0xff, 0x96, 0xed, 0x47, 0x5b, + 0xe8, 0x03, 0xc1, 0x0a, 0x77, 0x25, 0x4b, 0x3c, 0xa1, 0x92, 0x30, 0xf0, + 0xa0, 0xfd, 0x3f, 0xac, 0x2d, 0xbd, 0x33, 0x05, 0x07, 0xfc, 0x48, 0x60, + 0xc2, 0xe7, 0x46, 0xc0, 0xf8, 0xcb, 0x4e, 0xed, 0xf5, 0x1e, 0xec, 0xd1, + 0x56, 0x6a, 0xcc, 0xfd, 0x4c, 0xb6, 0x18, 0xce, 0xa2, 0x79, 0xba, 0x81, + 0x3e, 0x8a, 0x41, 0x73, 0x76, 0xba, 0xde, 0xed, 0x44, 0x11, 0xd3, 0x62, + 0xa5, 0x99, 0xbc, 0x63, 0x32, 0xca, 0x42, 0xbf, 0xbf, 0x42, 0xc2, 0x70, + 0x64, 0x60, 0xd0, 0x4a, 0x9f, 0x33, 0x06, 0x0f, 0xed, 0x38, 0xa8, 0x3b, + 0xe7, 0xf6, 0x05, 0x46, 0x8d, 0x6f, 0x7b, 0x84, 0xb8, 0x90, 0x98, 0xd8, + 0x91, 0x93, 0xf8, 0x74, 0xee, 0xd6, 0x03, 0x96, 0x02, 0x15, 0x08, 0xcf, + 0x4a, 0xe4, 0xa0, 0x70, 0xa8, 0x5a, 0x3e, 0x77, 0x37, 0x20, 0xd9, 0xae, + 0x5e, 0x2e, 0x6f, 0xf7, 0xf9, 0x1a, 0x2d, 0xa9, 0x07, 0xa5, 0x48, 0x39, + 0x60, 0x95, 0x4e, 0x58, 0x6e, 0xff, 0xaa, 0x14, 0x50, 0x3a, 0x8f, 0x31, + 0x23, 0xb8, 0x54, 0x17, 0x78, 0xf2, 0x65, 0xcc, 0xf0, 0x7a, 0x8e, 0x60, + 0x35, 0x7e, 0x99, 0x89, 0x7f, 0x4f, 0xf7, 0xc2, 0x21, 0xc7, 0x11, 0xbf, + 0xf2, 0x20, 0xa3, 0x56, 0x91, 0xab, 0x26, 0xfe, 0x17, 0xf1, 0xa5, 0xf3}; + +const uint8_t kSignEntropy[MLDSA_SEED_BYTES] = { + 0x7c, 0xf6, 0x8e, 0x63, 0x14, 0x04, 0x0b, 0x08, 0x20, 0x9b, 0x00, + 0x8c, 0x31, 0x48, 0xee, 0xd3, 0xe1, 0x6d, 0x5f, 0x71, 0x3b, 0xc7, + 0x08, 0x78, 0x05, 0x4b, 0x12, 0x4f, 0xf1, 0xf3, 0x50, 0x07}; + +const uint8_t kExpectedCase1Signature[MLDSA65_SIGNATURE_BYTES] = { + 0xf8, 0xc7, 0x25, 0x84, 0x8b, 0x39, 0xd9, 0xd9, 0x80, 0xf0, 0x2f, 0xf7, + 0xa0, 0x24, 0x19, 0x08, 0x70, 0x65, 0xe2, 0xc8, 0x0a, 0xc4, 0xd3, 0xd5, + 0x97, 0x49, 0x31, 0xea, 0x7b, 0xd6, 0x64, 0xb6, 0x6e, 0x6b, 0xf3, 0xc7, + 0x5f, 0xcb, 0xe3, 0x42, 0xd5, 0x5e, 0xa2, 0xa8, 0x8a, 0x01, 0x9a, 0xfe, + 0x44, 0xe2, 0xa7, 0x87, 0xd7, 0x70, 0xab, 0x9d, 0xa8, 0xf0, 0x9c, 0x67, + 0xfb, 0x4c, 0x16, 0xa6, 0x86, 0x91, 0xe2, 0x26, 0x9b, 0xa2, 0xda, 0x94, + 0x96, 0x6d, 0xfc, 0x4e, 0xf2, 0x2f, 0x2b, 0xcf, 0xf3, 0xc2, 0x7e, 0xe5, + 0x73, 0x1a, 0xac, 0xa3, 0x2c, 0x4d, 0x82, 0x28, 0x82, 0xa5, 0x82, 0x40, + 0x3d, 0x9a, 0xf6, 0x4b, 0xee, 0xae, 0xb7, 0x37, 0xd8, 0x2d, 0x80, 0xdd, + 0xcb, 0x52, 0xce, 0xea, 0xde, 0x51, 0xb9, 0x3e, 0x34, 0x7a, 0xfd, 0x3d, + 0x79, 0x38, 0xf6, 0xe9, 0x48, 0x1c, 0x07, 0x5f, 0xb8, 0x02, 0xa5, 0xa4, + 0xab, 0x45, 0xe7, 0x66, 0xf5, 0x9a, 0x23, 0xfe, 0x72, 0xcb, 0xd0, 0xa0, + 0x18, 0x74, 0x75, 0xc2, 0x1c, 0xcf, 0xd6, 0x69, 0x62, 0xa0, 0xe3, 0xde, + 0xa7, 0x2b, 0x0a, 0xf0, 0x1c, 0xb3, 0x51, 0x41, 0xf9, 0xfe, 0x2c, 0xff, + 0x82, 0xa3, 0x46, 0x6f, 0xb5, 0x55, 0x0d, 0xaa, 0xd1, 0x0e, 0xc8, 0x31, + 0xc6, 0xdf, 0x61, 0xe8, 0x96, 0x78, 0x85, 0x08, 0xf4, 0x62, 0x48, 0xfd, + 0x1d, 0x82, 0xf7, 0x9b, 0x7b, 0xbe, 0xee, 0x47, 0xcf, 0x17, 0xf7, 0x5a, + 0xed, 0xfa, 0x89, 0x94, 0x3e, 0xc3, 0xba, 0x37, 0xa5, 0xe4, 0xfb, 0x72, + 0x32, 0x90, 0xc2, 0x46, 0xd3, 0x02, 0x3f, 0xf5, 0xb1, 0x73, 0xbd, 0x9f, + 0x09, 0xa8, 0x61, 0x13, 0x75, 0xf2, 0xa6, 0xfc, 0x19, 0x44, 0xe7, 0xfd, + 0x1c, 0xcf, 0xa2, 0x24, 0x79, 0x39, 0x3a, 0xf1, 0xe4, 0x96, 0xe0, 0xd8, + 0xcb, 0x9b, 0x1f, 0xab, 0x20, 0x7e, 0x21, 0xbb, 0xf7, 0xe2, 0x7e, 0xd0, + 0xaf, 0x2b, 0x04, 0xbf, 0x35, 0xad, 0x04, 0x09, 0x11, 0xfa, 0x45, 0xaa, + 0xee, 0x30, 0x62, 0xd4, 0x41, 0x39, 0xed, 0x00, 0xe3, 0x06, 0x7d, 0x0c, + 0x91, 0x2d, 0x4b, 0x8d, 0xdb, 0xf6, 0x98, 0x5b, 0x0b, 0x26, 0x9a, 0x79, + 0x19, 0x58, 0x2f, 0x3d, 0x80, 0xb7, 0x7a, 0x49, 0xc7, 0x6d, 0xfb, 0xd6, + 0xa6, 0x86, 0xef, 0x5b, 0xd2, 0x4d, 0xa6, 0x14, 0xb9, 0x01, 0xe9, 0x30, + 0xd1, 0xf1, 0xcf, 0x05, 0x93, 0xb1, 0x35, 0xdd, 0xa2, 0x6c, 0x99, 0x41, + 0x37, 0x61, 0xa4, 0x49, 0x72, 0xb2, 0x75, 0xe7, 0x2c, 0x16, 0xd1, 0x9e, + 0xc3, 0x57, 0x74, 0x23, 0x29, 0x66, 0x3f, 0xd2, 0xa3, 0x0f, 0xfe, 0xda, + 0xd2, 0xa8, 0x7a, 0xce, 0x18, 0x34, 0x1b, 0x15, 0xf8, 0x7d, 0x07, 0x9e, + 0x8e, 0x6b, 0x2c, 0x50, 0xa8, 0xfb, 0x81, 0x8e, 0x2b, 0xe5, 0x54, 0xb7, + 0xc9, 0x17, 0x26, 0xa5, 0xbf, 0x70, 0xf0, 0x45, 0xf0, 0xfb, 0x92, 0x55, + 0x94, 0x90, 0x53, 0x3a, 0xc3, 0x36, 0x4a, 0xe7, 0xa7, 0xae, 0x9f, 0x76, + 0x2b, 0x09, 0x12, 0xf2, 0xe6, 0x10, 0x98, 0xf1, 0x6d, 0x9f, 0x4e, 0x5d, + 0xdf, 0x79, 0x30, 0xf4, 0x1d, 0x6a, 0x21, 0xa0, 0x9b, 0xf7, 0x6c, 0x67, + 0xa5, 0x62, 0x55, 0x61, 0xa2, 0x31, 0xc9, 0xc9, 0x4b, 0x94, 0xd4, 0x91, + 0xc1, 0xba, 0xb0, 0x9d, 0x65, 0x68, 0xb9, 0x92, 0xcb, 0xd4, 0x2a, 0x86, + 0x81, 0x23, 0xff, 0x64, 0x7e, 0x70, 0xce, 0xfc, 0xab, 0x7f, 0x9f, 0xce, + 0xcb, 0x34, 0xff, 0xe7, 0xbc, 0xbb, 0x65, 0x45, 0x08, 0x7e, 0xc7, 0xa1, + 0x89, 0x89, 0x9c, 0x85, 0xbf, 0x05, 0x2e, 0x68, 0x7e, 0x33, 0x44, 0x7d, + 0x4e, 0xdb, 0xed, 0xf5, 0xe3, 0xee, 0x6a, 0x05, 0x11, 0x40, 0xad, 0xf0, + 0xa4, 0x3a, 0x92, 0xf1, 0x3b, 0x40, 0xa1, 0x61, 0xb9, 0x76, 0xc8, 0xd6, + 0x77, 0xf9, 0x9e, 0xb5, 0x95, 0x97, 0xdb, 0x1f, 0x5c, 0xbc, 0x31, 0x57, + 0x5b, 0xf4, 0x2d, 0x9a, 0x68, 0x2b, 0x1b, 0x44, 0xb3, 0xdc, 0xb6, 0x29, + 0xa5, 0x9a, 0xea, 0xcd, 0x28, 0xb0, 0xcf, 0xbc, 0xbd, 0xaf, 0x68, 0x81, + 0xd5, 0xd1, 0xfe, 0xb2, 0xd7, 0xfa, 0xd7, 0x76, 0xc8, 0xec, 0x01, 0xc4, + 0x7f, 0x73, 0xd4, 0x50, 0x30, 0xc6, 0x12, 0x3c, 0x9f, 0xa9, 0x88, 0xe9, + 0xdb, 0x6e, 0x8d, 0x1e, 0xeb, 0xa0, 0xfa, 0x46, 0x30, 0x2f, 0x84, 0x53, + 0x24, 0xe4, 0xeb, 0x4d, 0xdb, 0x83, 0xf5, 0x5b, 0x53, 0xc4, 0xeb, 0x02, + 0x39, 0xb5, 0x7f, 0x7e, 0x30, 0x53, 0x03, 0x48, 0xd3, 0x2f, 0x85, 0xf9, + 0xf8, 0x25, 0xf4, 0x80, 0x78, 0x7a, 0x7a, 0xf9, 0x95, 0x52, 0xb1, 0xc9, + 0x6b, 0x75, 0xc2, 0x55, 0x9d, 0xd2, 0xa5, 0x03, 0x54, 0x24, 0xec, 0xf3, + 0xef, 0x1b, 0x9c, 0xae, 0xde, 0xad, 0xd1, 0x7e, 0x9b, 0xdc, 0x7b, 0x7c, + 0x1b, 0x9b, 0xae, 0x00, 0x53, 0xba, 0xa0, 0x64, 0xb0, 0x16, 0xa6, 0xc8, + 0xe0, 0x24, 0xb0, 0xa1, 0x0d, 0xbd, 0xa0, 0x88, 0x49, 0x4d, 0x18, 0xd2, + 0x3d, 0xf2, 0x82, 0x3e, 0x5e, 0xbf, 0x08, 0x30, 0xa0, 0x6d, 0xa7, 0xd8, + 0xa5, 0x53, 0xd7, 0xa5, 0xaa, 0x3e, 0x63, 0xcc, 0xeb, 0x16, 0x97, 0xb9, + 0x2a, 0x4f, 0xcc, 0x92, 0x36, 0x70, 0xb9, 0xf2, 0xd3, 0xf6, 0x45, 0x90, + 0x41, 0x9e, 0x88, 0xc4, 0x28, 0x4c, 0x28, 0x72, 0x51, 0xdf, 0xd1, 0x97, + 0xa3, 0xe2, 0xe4, 0xa8, 0x6f, 0x79, 0x38, 0x56, 0x27, 0x17, 0xb5, 0x21, + 0x60, 0x3a, 0xd9, 0x21, 0x5c, 0x69, 0x41, 0xaa, 0x75, 0xa3, 0x98, 0x6c, + 0x2e, 0xb3, 0x79, 0xac, 0xd2, 0x16, 0x26, 0x09, 0x26, 0xc0, 0x05, 0x0a, + 0x6a, 0x60, 0xaf, 0x65, 0x78, 0xb2, 0x3f, 0xcd, 0xa5, 0x3b, 0xda, 0x7b, + 0x2d, 0x94, 0x66, 0xc1, 0x24, 0x4b, 0x52, 0xd8, 0x6b, 0xa5, 0x14, 0x8b, + 0xc3, 0x6d, 0xa6, 0x5c, 0xea, 0x4b, 0x32, 0x22, 0xad, 0x1d, 0xf3, 0x6b, + 0x7c, 0x89, 0xfa, 0xd6, 0xc4, 0x9e, 0x8a, 0x77, 0xef, 0x79, 0xcb, 0x59, + 0x4f, 0x2c, 0x3b, 0xba, 0xbd, 0xd9, 0xb3, 0x9d, 0x91, 0x29, 0xd5, 0xf6, + 0x57, 0xf8, 0x39, 0x7a, 0xf0, 0x0f, 0x1a, 0x89, 0xcb, 0xcb, 0x22, 0x15, + 0x08, 0x6d, 0xca, 0x01, 0x8a, 0x15, 0xb3, 0x47, 0xe6, 0x23, 0x7c, 0xe6, + 0xec, 0x10, 0xdc, 0x70, 0x16, 0xec, 0x53, 0x39, 0x1d, 0x77, 0x07, 0x8b, + 0xbf, 0x8b, 0x85, 0x92, 0x82, 0x3b, 0xf5, 0xe2, 0x8c, 0x80, 0x28, 0x4c, + 0xb8, 0x1e, 0xca, 0x57, 0x76, 0x95, 0xeb, 0x97, 0xfd, 0x3d, 0x47, 0x9a, + 0xf8, 0x3e, 0x0e, 0xda, 0xb2, 0x41, 0x09, 0xa8, 0x26, 0x1f, 0x11, 0x80, + 0xde, 0x18, 0xa5, 0x5c, 0x07, 0x54, 0x57, 0xe3, 0xd5, 0x3e, 0x3f, 0x78, + 0x3f, 0x5b, 0x2d, 0x77, 0x69, 0x15, 0x0b, 0xd6, 0x8c, 0xbc, 0x98, 0xf2, + 0x86, 0x53, 0x0b, 0x91, 0x46, 0x87, 0x03, 0xfc, 0x05, 0x7f, 0x5b, 0x40, + 0x39, 0xa8, 0xe7, 0xbf, 0xe6, 0x18, 0x09, 0xd5, 0x91, 0xa9, 0xec, 0x06, + 0x1f, 0x85, 0xc5, 0xf7, 0x94, 0xbe, 0x72, 0x03, 0x2e, 0xaa, 0xbc, 0xbb, + 0x4e, 0x8d, 0xfd, 0x27, 0x7c, 0xb4, 0x09, 0x63, 0x8d, 0xca, 0x33, 0x9e, + 0x51, 0xc3, 0xa3, 0x5c, 0xcd, 0x02, 0xe0, 0x62, 0x60, 0x53, 0xf2, 0x7f, + 0x4a, 0xa9, 0xcb, 0x46, 0xc1, 0xaf, 0x0e, 0x5e, 0x3f, 0xa9, 0x72, 0x14, + 0x99, 0x30, 0x0a, 0x81, 0x5c, 0xf3, 0x13, 0xbc, 0x61, 0xf2, 0xf5, 0x6d, + 0x89, 0xc1, 0x6f, 0x48, 0xeb, 0x43, 0xc3, 0x48, 0xcf, 0xb7, 0x18, 0x36, + 0x88, 0x9e, 0x1b, 0xc0, 0x1f, 0xa7, 0xea, 0x95, 0x12, 0xd3, 0x07, 0x4d, + 0xc6, 0xad, 0xb7, 0xef, 0x6c, 0x59, 0xb3, 0xee, 0x04, 0xec, 0x4b, 0xff, + 0x4a, 0xcc, 0x7c, 0x33, 0x7d, 0x8b, 0xd3, 0x29, 0x31, 0x77, 0xbd, 0x73, + 0x1e, 0x10, 0x53, 0x5a, 0x79, 0x70, 0xca, 0xb5, 0x9f, 0x20, 0x0b, 0x0b, + 0x31, 0xd5, 0x5d, 0xd9, 0x2b, 0x4a, 0xc4, 0x87, 0x55, 0xd9, 0xaa, 0x2e, + 0x8b, 0x65, 0xb0, 0xf4, 0x06, 0xc7, 0xf2, 0x9a, 0xa0, 0x65, 0xcc, 0x30, + 0x24, 0x8d, 0x1a, 0x61, 0x3f, 0xc7, 0x72, 0x3c, 0xf3, 0x17, 0xff, 0x0a, + 0x58, 0x82, 0xcf, 0x42, 0x96, 0x49, 0x67, 0x55, 0x79, 0x15, 0x12, 0x96, + 0xfa, 0x28, 0xfe, 0x77, 0xfc, 0x8f, 0x30, 0x96, 0x03, 0xf6, 0x79, 0x03, + 0x38, 0x49, 0x70, 0x48, 0x5c, 0xb8, 0x8e, 0x65, 0x67, 0xe1, 0x85, 0x6b, + 0x70, 0x3c, 0x69, 0xd0, 0x43, 0x0f, 0x4b, 0xa4, 0x04, 0x06, 0xd8, 0xec, + 0x26, 0xea, 0xac, 0xd5, 0xd9, 0x6c, 0x8b, 0xb4, 0x13, 0xd0, 0x07, 0xd3, + 0x41, 0x28, 0xa7, 0xbf, 0x0c, 0xe4, 0x5b, 0xa9, 0xb7, 0x3d, 0x2d, 0x5d, + 0x10, 0xbc, 0xbe, 0xa8, 0x26, 0xe0, 0x0a, 0x92, 0xae, 0xc2, 0x80, 0xd1, + 0x85, 0x94, 0x0e, 0x78, 0x24, 0xd6, 0xd5, 0x11, 0x87, 0xa3, 0xd4, 0x3c, + 0x63, 0x49, 0x12, 0x64, 0x3e, 0xee, 0xd9, 0x79, 0x2b, 0x84, 0xa1, 0x08, + 0x07, 0xcc, 0xa8, 0xc2, 0x8b, 0x91, 0x4c, 0xad, 0x39, 0x1b, 0xb7, 0x1d, + 0xa1, 0x22, 0x1a, 0x60, 0x5a, 0x5b, 0x9b, 0x5f, 0x5b, 0x10, 0x46, 0x25, + 0x34, 0xe1, 0x3f, 0x6c, 0xc2, 0xd9, 0xab, 0x32, 0x73, 0xa4, 0xde, 0xf1, + 0x34, 0x05, 0x04, 0x0a, 0x4c, 0x05, 0xa8, 0x7e, 0xad, 0x1d, 0x98, 0x50, + 0xf9, 0x11, 0xe1, 0x9a, 0x90, 0x7b, 0x3c, 0x39, 0xf9, 0x2d, 0x98, 0x28, + 0x9e, 0xf5, 0xc4, 0xa5, 0xc9, 0x4d, 0xa5, 0x74, 0xaf, 0x2f, 0x03, 0x97, + 0xd5, 0x20, 0x81, 0x40, 0xf3, 0x3e, 0x67, 0x18, 0xb9, 0x98, 0x57, 0xee, + 0xc0, 0x8e, 0x9b, 0x21, 0x4a, 0x87, 0xc2, 0x21, 0x9b, 0x42, 0xf7, 0xd1, + 0x51, 0x81, 0x23, 0x6c, 0x06, 0xa0, 0xcc, 0x09, 0x15, 0x1a, 0xa6, 0x7b, + 0xe9, 0xbe, 0x9f, 0xac, 0x8b, 0x08, 0x8b, 0xb8, 0xa3, 0x7d, 0x04, 0xb0, + 0xc0, 0x49, 0x62, 0x85, 0x7e, 0xb7, 0xd0, 0x3d, 0x1d, 0x78, 0xfc, 0x6a, + 0x76, 0xfb, 0x5c, 0x60, 0x22, 0xe4, 0xec, 0x09, 0xe0, 0x40, 0xde, 0x03, + 0xe5, 0xb1, 0x5e, 0xd7, 0x06, 0xc7, 0x06, 0xf6, 0x6c, 0x66, 0x4b, 0xb6, + 0x72, 0xaf, 0x59, 0xd7, 0x04, 0x34, 0xee, 0x64, 0xbe, 0x1b, 0xd2, 0xdf, + 0x74, 0x20, 0x05, 0xc8, 0x83, 0xf2, 0xfd, 0x62, 0xb4, 0xb6, 0x85, 0x46, + 0x14, 0x33, 0x23, 0x1d, 0xcc, 0xd3, 0x4b, 0x37, 0x96, 0xe4, 0x04, 0xb5, + 0x92, 0x0c, 0x6f, 0x52, 0xc9, 0xe2, 0xe7, 0xb2, 0xca, 0x01, 0x9e, 0xc6, + 0x51, 0x7a, 0x9e, 0xce, 0xb2, 0x76, 0xf8, 0x74, 0xa2, 0x4c, 0xaa, 0x66, + 0x9a, 0x7d, 0x64, 0x24, 0x4f, 0xe3, 0x33, 0xa4, 0xca, 0x26, 0xdd, 0x24, + 0xf0, 0xd0, 0x38, 0xf3, 0x81, 0x0a, 0xf1, 0x06, 0xd7, 0x07, 0xe9, 0x1a, + 0x85, 0x98, 0x9d, 0x3e, 0xb3, 0x80, 0x9d, 0xaf, 0xeb, 0x48, 0xee, 0xee, + 0x04, 0x6c, 0xb1, 0x6a, 0x81, 0x97, 0x26, 0x14, 0x60, 0x16, 0xfd, 0x0e, + 0x6a, 0xda, 0xb6, 0x0e, 0xff, 0xd5, 0x6c, 0x65, 0x1c, 0xd1, 0xe2, 0xfa, + 0xcc, 0x75, 0x6c, 0xb6, 0x10, 0x03, 0x5d, 0x41, 0xe6, 0x47, 0x95, 0x43, + 0xa5, 0x7a, 0xd1, 0xc5, 0xc5, 0xd9, 0xdd, 0x7f, 0x6c, 0xcb, 0x4d, 0x9c, + 0x77, 0x04, 0x57, 0x74, 0x90, 0x08, 0x03, 0x5f, 0x3a, 0xb1, 0x08, 0x3f, + 0x64, 0xaa, 0x7c, 0x75, 0x9e, 0xfa, 0x14, 0x8b, 0x3c, 0x76, 0xba, 0x20, + 0x8b, 0x9b, 0xee, 0x4d, 0xf1, 0x3a, 0x79, 0xdc, 0x97, 0xe6, 0x14, 0x28, + 0xee, 0x8b, 0xa4, 0x55, 0x9d, 0xe8, 0x08, 0x83, 0xa9, 0x27, 0x11, 0xd8, + 0x24, 0x5d, 0x0e, 0x0a, 0xab, 0x67, 0xfb, 0xd5, 0xda, 0x38, 0x36, 0x7b, + 0x25, 0x79, 0xef, 0xb1, 0x30, 0x50, 0x36, 0xf7, 0xfa, 0x8d, 0xc0, 0x82, + 0x7a, 0xec, 0x74, 0xde, 0x7a, 0x9d, 0xe4, 0x46, 0xe9, 0x23, 0x9e, 0xa9, + 0x90, 0x18, 0x6e, 0xbe, 0xc8, 0x37, 0xc7, 0x47, 0xb3, 0x17, 0x76, 0x2a, + 0x4a, 0x97, 0x75, 0x42, 0xee, 0x23, 0x7e, 0x98, 0x89, 0xd6, 0x86, 0x09, + 0x28, 0x9c, 0x24, 0xdf, 0x74, 0xa0, 0x2d, 0x3d, 0x17, 0x27, 0x9b, 0x90, + 0x51, 0xdd, 0xce, 0xc2, 0xef, 0x4f, 0xce, 0x38, 0x97, 0x69, 0x4e, 0xe9, + 0xb6, 0xdf, 0x0e, 0x5f, 0xcb, 0x1f, 0x3b, 0x31, 0xaa, 0xbf, 0xc7, 0x10, + 0x29, 0xea, 0xb7, 0x30, 0x9f, 0x43, 0x7d, 0x37, 0xcd, 0x72, 0x1c, 0x27, + 0x2b, 0xf7, 0x56, 0x9c, 0x94, 0xe7, 0xc8, 0x1a, 0x2a, 0xad, 0xa1, 0xfe, + 0x90, 0xe0, 0xdd, 0xb2, 0x75, 0xe4, 0xd9, 0x36, 0x55, 0xed, 0x9f, 0x5d, + 0x07, 0xa8, 0x5c, 0x63, 0x67, 0x8a, 0x12, 0x35, 0xa1, 0xef, 0x78, 0x85, + 0xf0, 0x37, 0x6f, 0x37, 0xce, 0x34, 0x75, 0x9a, 0x3c, 0x54, 0xcb, 0x36, + 0x8f, 0xfc, 0x41, 0x70, 0x23, 0x19, 0xd1, 0x15, 0xb3, 0x6c, 0xc5, 0x0b, + 0x51, 0x9d, 0xf2, 0x83, 0xc9, 0x4b, 0x62, 0x84, 0x12, 0xba, 0x6b, 0xee, + 0xd3, 0x4f, 0x80, 0xa7, 0xe3, 0x30, 0x19, 0xe3, 0x20, 0x44, 0xb1, 0x25, + 0xe2, 0x5a, 0xaa, 0xb0, 0x81, 0x1a, 0x6a, 0x6a, 0xd7, 0xb2, 0xc4, 0x64, + 0x87, 0x25, 0x7e, 0xe1, 0x5f, 0x82, 0x17, 0x1f, 0xce, 0x1a, 0x2d, 0x04, + 0x58, 0xad, 0x5f, 0x2a, 0x3d, 0xd2, 0xb8, 0xa9, 0xa2, 0x72, 0x19, 0x24, + 0x8d, 0x1b, 0x04, 0x89, 0x62, 0xf5, 0x6b, 0xdd, 0xb0, 0x66, 0x62, 0x59, + 0x0d, 0xb3, 0xa9, 0x03, 0x07, 0x11, 0x55, 0x51, 0xfa, 0x14, 0x49, 0x31, + 0xe6, 0x38, 0x66, 0x79, 0x07, 0xa8, 0xeb, 0xc5, 0x4b, 0x61, 0x8f, 0x59, + 0xb1, 0x18, 0x55, 0x28, 0x5c, 0x82, 0xff, 0x4a, 0xd3, 0x28, 0x47, 0xcc, + 0xc1, 0xba, 0xa4, 0xce, 0x2a, 0x9d, 0x28, 0x24, 0x69, 0x28, 0x13, 0x4f, + 0x06, 0x0f, 0xa3, 0x71, 0x6b, 0x17, 0x7b, 0xf4, 0x2c, 0x6d, 0xdb, 0xcc, + 0x6c, 0x4e, 0x8a, 0x04, 0x58, 0x20, 0x26, 0x54, 0xf9, 0x4d, 0x7c, 0x67, + 0xb8, 0x63, 0x55, 0x23, 0x94, 0xe6, 0x3c, 0xf7, 0x11, 0x61, 0x38, 0x9c, + 0x1a, 0x40, 0x5c, 0x3d, 0xb2, 0x35, 0xde, 0x35, 0x1f, 0x38, 0x48, 0xc5, + 0x15, 0x59, 0x2f, 0xa7, 0x81, 0xe8, 0x53, 0xe8, 0x46, 0x59, 0x3e, 0xf4, + 0xc8, 0x01, 0x33, 0xd6, 0xdd, 0xe6, 0xf3, 0xa5, 0x2a, 0x09, 0x54, 0x1a, + 0x92, 0x37, 0x3e, 0x9f, 0x54, 0xb6, 0x81, 0x5d, 0xf3, 0x74, 0x6b, 0x56, + 0x01, 0xc9, 0xfd, 0x4b, 0xa5, 0x54, 0x08, 0x27, 0x54, 0x21, 0xb2, 0xad, + 0x6c, 0x17, 0xdf, 0x4a, 0x29, 0x1e, 0xf8, 0xde, 0xc7, 0x51, 0x59, 0x55, + 0xa9, 0x3a, 0xf8, 0xe8, 0xa8, 0x56, 0x5c, 0x8a, 0x04, 0xff, 0x51, 0x8c, + 0x10, 0xd2, 0x22, 0xc7, 0x3b, 0x3c, 0xa4, 0xb1, 0x6d, 0x41, 0xb6, 0xaa, + 0x5b, 0x24, 0x17, 0x3b, 0x87, 0xb0, 0xa8, 0xd9, 0x93, 0x3f, 0x6b, 0xff, + 0x56, 0x83, 0xcc, 0x09, 0x5c, 0x15, 0xe8, 0x99, 0xa6, 0x17, 0xc3, 0xef, + 0xa1, 0x4b, 0xf7, 0x81, 0x7b, 0x62, 0x3a, 0x8a, 0x6a, 0x5c, 0x57, 0x4f, + 0x6d, 0xf4, 0x79, 0x7f, 0x69, 0xd9, 0xde, 0x40, 0xb8, 0xb0, 0x96, 0x70, + 0x1c, 0xaf, 0x94, 0xb5, 0x45, 0x02, 0xff, 0xf7, 0x23, 0x04, 0x7e, 0xc0, + 0xa1, 0x93, 0x2f, 0x9e, 0x7d, 0xc0, 0x81, 0x00, 0x4f, 0xed, 0xb5, 0xaa, + 0x7c, 0x25, 0x5f, 0x8b, 0x76, 0xd8, 0x45, 0xee, 0xf2, 0x9f, 0xc6, 0xb4, + 0x0c, 0x08, 0xd8, 0x7d, 0x1f, 0x25, 0xcc, 0x8f, 0x1e, 0x5b, 0xaa, 0x75, + 0x0b, 0xec, 0x61, 0xcf, 0xe2, 0x08, 0xc1, 0x45, 0x9d, 0x08, 0x7e, 0xc0, + 0xa8, 0x73, 0xc8, 0x2e, 0xcb, 0xa7, 0x5a, 0x71, 0xce, 0x8f, 0x7f, 0xe6, + 0xf6, 0x35, 0xe5, 0xcf, 0xac, 0x24, 0xf7, 0x71, 0x18, 0x27, 0x60, 0x3e, + 0xf8, 0x37, 0x3a, 0x81, 0x66, 0xee, 0x41, 0xf0, 0x72, 0x3b, 0x43, 0x40, + 0xa2, 0xd7, 0x99, 0x34, 0xda, 0xa3, 0xcc, 0xf4, 0xb7, 0x66, 0xd7, 0xad, + 0xab, 0x58, 0xee, 0x52, 0xa0, 0xb1, 0xbb, 0xd4, 0x3d, 0x30, 0x6d, 0x31, + 0xe5, 0xf8, 0x1e, 0xc8, 0x5d, 0x78, 0x35, 0x2a, 0xd5, 0x36, 0xd9, 0x08, + 0x20, 0x5f, 0x51, 0x07, 0x58, 0x02, 0x5f, 0x3a, 0x81, 0x90, 0x03, 0x35, + 0x74, 0xb4, 0x87, 0xae, 0x18, 0xe0, 0xeb, 0x73, 0x05, 0x63, 0xf1, 0x42, + 0x7e, 0x49, 0x26, 0xbd, 0xce, 0x8c, 0xab, 0x18, 0x70, 0xf7, 0x88, 0x22, + 0xc7, 0x6a, 0xe4, 0x55, 0xab, 0x31, 0x7e, 0xaa, 0x0b, 0x22, 0xff, 0xdd, + 0x4c, 0x80, 0x1f, 0x94, 0x64, 0xb0, 0x7d, 0x18, 0x69, 0x33, 0xf2, 0xc8, + 0x0a, 0x2e, 0x33, 0x8a, 0x0f, 0x47, 0x10, 0xeb, 0x6c, 0x5a, 0x6f, 0x4f, + 0x80, 0xb9, 0x29, 0x9f, 0x88, 0x88, 0x23, 0x75, 0x1e, 0xb8, 0xad, 0x76, + 0x75, 0x3a, 0x18, 0xbb, 0x9d, 0x92, 0x76, 0x53, 0x5b, 0x6d, 0x5b, 0x7a, + 0xc4, 0x34, 0x1c, 0x6e, 0xc7, 0xb4, 0x24, 0x7c, 0xd8, 0x27, 0x47, 0x74, + 0xb5, 0xf5, 0x5f, 0xcb, 0x90, 0x54, 0x00, 0x8e, 0xdd, 0xe1, 0x81, 0xf0, + 0xbb, 0xc5, 0xf9, 0x7d, 0x28, 0x07, 0x8d, 0xb2, 0x9b, 0x0c, 0x56, 0x80, + 0xa7, 0xa7, 0x2f, 0x84, 0x9a, 0xef, 0x70, 0xa9, 0x92, 0x40, 0xcc, 0xf9, + 0xd5, 0xee, 0xbe, 0x65, 0x8a, 0x79, 0xc8, 0xfb, 0x31, 0x4b, 0x6f, 0x79, + 0xfc, 0xc9, 0x52, 0x47, 0x38, 0xb9, 0x36, 0x08, 0xe7, 0xab, 0xb4, 0x60, + 0xe6, 0x9d, 0xc8, 0xb6, 0x77, 0x28, 0x53, 0x62, 0x70, 0x8a, 0x9a, 0xe1, + 0xbb, 0xc0, 0xa9, 0xae, 0x4f, 0xd5, 0x1b, 0x96, 0xdc, 0x7e, 0x8c, 0x4d, + 0x96, 0xe2, 0x23, 0x15, 0xaa, 0x6c, 0xf2, 0xca, 0x42, 0xae, 0xb8, 0xfa, + 0xea, 0x69, 0xcf, 0xe2, 0xcb, 0x95, 0x87, 0xa9, 0xfa, 0x27, 0x28, 0xdb, + 0xa4, 0xa2, 0xb2, 0x89, 0x6c, 0x8a, 0x8b, 0x70, 0x9c, 0xae, 0x45, 0xb1, + 0xce, 0x2a, 0xf4, 0x09, 0xeb, 0x52, 0x55, 0x67, 0xb8, 0x48, 0x60, 0xe2, + 0xae, 0x6d, 0x5b, 0x6f, 0xa4, 0x43, 0x08, 0xb6, 0x0b, 0x76, 0xce, 0x3c, + 0xbf, 0xb3, 0xc6, 0x09, 0x67, 0x18, 0xe6, 0x81, 0xea, 0x41, 0x13, 0x74, + 0x4a, 0x07, 0x95, 0x1f, 0xdb, 0x06, 0xa6, 0x45, 0x28, 0x0a, 0x65, 0x0e, + 0x4a, 0x4a, 0x55, 0x18, 0x9e, 0x0d, 0x22, 0x6c, 0xdb, 0x58, 0xde, 0x8f, + 0x5d, 0x56, 0xd3, 0xdf, 0xdc, 0xb9, 0x3c, 0x9e, 0xc9, 0xe5, 0x9a, 0xb1, + 0x33, 0xca, 0x09, 0x18, 0x89, 0x94, 0x08, 0xad, 0xa8, 0xc4, 0x97, 0x23, + 0x6c, 0xc4, 0x06, 0x44, 0xd7, 0xa2, 0x94, 0x88, 0x60, 0xfe, 0x56, 0x0e, + 0xd4, 0x71, 0xd8, 0xd5, 0xbf, 0x3d, 0x50, 0x92, 0xc4, 0x4a, 0xf0, 0x74, + 0x79, 0x70, 0x11, 0xaa, 0x49, 0xb7, 0x18, 0x83, 0xf7, 0xe6, 0x1b, 0x53, + 0xcd, 0x39, 0xf6, 0xe8, 0xed, 0x93, 0xa4, 0x36, 0xb9, 0x74, 0xee, 0x80, + 0x67, 0x0b, 0xa9, 0xd6, 0x0c, 0x8e, 0xdc, 0x54, 0x32, 0x81, 0x27, 0x95, + 0x9c, 0x5b, 0x5a, 0x44, 0x99, 0x0d, 0xb8, 0x89, 0xb0, 0xef, 0x01, 0x42, + 0x92, 0x6f, 0xb1, 0x28, 0x81, 0x5b, 0xd8, 0xd0, 0x54, 0xcf, 0x90, 0x4c, + 0xc7, 0x6c, 0xd3, 0x8b, 0x0f, 0xf4, 0x34, 0xca, 0x6e, 0xb0, 0x4e, 0xe8, + 0xb8, 0x1c, 0x14, 0x63, 0x91, 0x94, 0x3e, 0xcc, 0xa8, 0xbc, 0xb4, 0x28, + 0xb3, 0x78, 0x6b, 0xe3, 0x98, 0xfe, 0x80, 0xe8, 0xd9, 0xd7, 0x42, 0xd0, + 0x36, 0x1b, 0x3a, 0x22, 0xd3, 0x25, 0x64, 0x37, 0xb2, 0xa7, 0x56, 0x41, + 0xa0, 0xf3, 0xb3, 0x7f, 0x11, 0x0c, 0x0f, 0x41, 0x44, 0x92, 0xa5, 0xeb, + 0xf6, 0xd4, 0x56, 0x19, 0x41, 0xd4, 0x7e, 0x57, 0x57, 0xa3, 0xb6, 0x12, + 0x1d, 0xaf, 0xa6, 0xab, 0x62, 0xc3, 0x5d, 0x74, 0x4f, 0x44, 0xe1, 0xdc, + 0xcc, 0x45, 0xbd, 0x34, 0xce, 0x2e, 0x60, 0xcb, 0x21, 0x7d, 0x8b, 0xd8, + 0xfe, 0xbc, 0xdc, 0x2e, 0x72, 0xb8, 0xa7, 0x0e, 0x2f, 0x79, 0xc9, 0xc2, + 0xf7, 0xf1, 0xd4, 0xf4, 0x36, 0xec, 0x53, 0x31, 0x79, 0x18, 0x85, 0xa3, + 0xb4, 0xb0, 0x0e, 0xc1, 0xc9, 0x41, 0xdb, 0x7a, 0x7f, 0xd2, 0x34, 0x35, + 0x5c, 0x4b, 0x52, 0x83, 0x80, 0xe6, 0xf2, 0x18, 0x6f, 0xae, 0x37, 0x8c, + 0x95, 0x38, 0x8b, 0x44, 0x8d, 0x22, 0x84, 0xd1, 0xd5, 0xc1, 0x01, 0x9c, + 0xf0, 0x56, 0x8e, 0x48, 0x5d, 0xab, 0x2d, 0x70, 0x6a, 0x29, 0xca, 0x91, + 0x0c, 0x03, 0xaa, 0xaf, 0x8c, 0x28, 0xd2, 0x97, 0x4a, 0x60, 0xac, 0xf4, + 0x9c, 0x26, 0xc3, 0xe8, 0x7d, 0xac, 0xc0, 0xc8, 0xe4, 0xf4, 0xad, 0x94, + 0x01, 0xcc, 0x5f, 0x13, 0x83, 0x3a, 0x2c, 0xf2, 0xc8, 0xc0, 0xc6, 0x7d, + 0x1a, 0x00, 0x54, 0x7e, 0xee, 0xa1, 0xb0, 0x33, 0x21, 0x7f, 0x3f, 0x45, + 0xff, 0xdb, 0x6e, 0x9d, 0xca, 0x65, 0xe0, 0x60, 0x8f, 0x40, 0x56, 0x91, + 0x57, 0x75, 0x83, 0x8d, 0xd4, 0x03, 0x4a, 0x60, 0x0e, 0x46, 0x27, 0x02, + 0x4e, 0x9d, 0xfb, 0xfe, 0xf2, 0xbe, 0x44, 0xa2, 0x8a, 0xc3, 0x2e, 0x46, + 0x29, 0x59, 0x8d, 0xb9, 0x61, 0x5a, 0x18, 0x96, 0x1b, 0xaa, 0x7a, 0xea, + 0x45, 0xfe, 0x93, 0x17, 0xb8, 0xb8, 0x6c, 0x42, 0xb3, 0xc8, 0xf5, 0x70, + 0xe3, 0x98, 0x46, 0xf4, 0x73, 0x61, 0x32, 0xee, 0x8e, 0xb1, 0x9f, 0x12, + 0xf5, 0xeb, 0xf3, 0xb7, 0xbc, 0x94, 0x32, 0xa5, 0xc4, 0xd0, 0x60, 0x95, + 0x0d, 0xd8, 0x11, 0x15, 0xad, 0xde, 0xea, 0xb5, 0xcb, 0xdb, 0x27, 0xe4, + 0x0f, 0x55, 0x1f, 0x65, 0xff, 0x02, 0xa3, 0xb8, 0xfb, 0x38, 0xe9, 0x7e, + 0x3d, 0x1f, 0xb9, 0xce, 0x06, 0xa2, 0x57, 0xca, 0x7a, 0xd9, 0x18, 0x90, + 0xef, 0xc3, 0x52, 0x50, 0xfc, 0xa6, 0xbf, 0x84, 0x7b, 0x8e, 0xd8, 0xf7, + 0x9c, 0x6a, 0x53, 0xc9, 0x10, 0x81, 0x9c, 0xd4, 0x67, 0xef, 0x1c, 0xd2, + 0x58, 0x86, 0x66, 0x45, 0x00, 0x26, 0x78, 0x11, 0x61, 0x53, 0xce, 0x50, + 0xda, 0x0c, 0xd4, 0x1b, 0xf7, 0xa4, 0xda, 0xab, 0xe2, 0x93, 0xed, 0x8b, + 0x34, 0x42, 0x3a, 0xf4, 0xae, 0x3d, 0x46, 0x86, 0xea, 0xae, 0x5f, 0xc2, + 0x5a, 0xd8, 0xed, 0x63, 0xc4, 0xd6, 0x51, 0x57, 0x81, 0xea, 0x59, 0x68, + 0xf4, 0x58, 0x8c, 0x02, 0xfc, 0xe9, 0x0a, 0x96, 0xa7, 0x29, 0xac, 0xaf, + 0xf2, 0x39, 0x17, 0xc8, 0xe0, 0x6e, 0x2a, 0x6d, 0x21, 0xb8, 0xf4, 0xe9, + 0x02, 0xd7, 0xbf, 0xc7, 0xf6, 0x09, 0xa0, 0x67, 0x6c, 0x98, 0x83, 0xba, + 0x7b, 0x71, 0x4a, 0xea, 0x3d, 0x89, 0x0a, 0x0e, 0x86, 0x6b, 0xa0, 0x25, + 0xf1, 0x3a, 0xa3, 0x66, 0x54, 0xff, 0x83, 0x2b, 0xca, 0x1f, 0x74, 0x1d, + 0x31, 0x93, 0xfc, 0x84, 0xcd, 0x3c, 0xc9, 0xf0, 0x7e, 0x39, 0xb7, 0x95, + 0xf7, 0xa9, 0x9c, 0x67, 0xcf, 0x10, 0x0f, 0xef, 0xc7, 0xce, 0x6b, 0x46, + 0x4c, 0x2a, 0x07, 0xb4, 0x24, 0xc4, 0x0a, 0x66, 0xaa, 0x35, 0xbb, 0xe9, + 0xe5, 0xcf, 0xd4, 0x19, 0x6b, 0x37, 0x56, 0x54, 0x34, 0x73, 0xd2, 0x63, + 0x5f, 0x43, 0xb7, 0x6b, 0xa7, 0x6f, 0x96, 0x2a, 0x58, 0xfc, 0xcd, 0x4d, + 0x8c, 0x15, 0x6c, 0x4c, 0x28, 0x8b, 0x68, 0xd1, 0xa1, 0x73, 0xb2, 0x72, + 0xa8, 0x42, 0x82, 0x2f, 0x2c, 0xa3, 0xff, 0x02, 0x4d, 0x84, 0xce, 0xb6, + 0x13, 0x7b, 0xd3, 0x7a, 0xdc, 0x62, 0xe1, 0xdc, 0xdb, 0x6b, 0xb0, 0x08, + 0x69, 0xe6, 0xbc, 0x53, 0xb2, 0xb0, 0xf7, 0x57, 0xe9, 0x7f, 0x52, 0x97, + 0xcc, 0xbd, 0x65, 0x65, 0x77, 0xe0, 0x0a, 0x5a, 0xb0, 0xbb, 0xc7, 0x6e, + 0x11, 0x4a, 0x0b, 0x62, 0x0c, 0x9d, 0xaa, 0xff, 0x82, 0x1f, 0x0c, 0xd9, + 0xe4, 0xf1, 0x9c, 0x32, 0x9d, 0xdf, 0x48, 0xde, 0x14, 0xe9, 0xb1, 0x00, + 0xd9, 0xb4, 0xd4, 0xb5, 0xd4, 0x45, 0x59, 0xd6, 0x55, 0x8a, 0x28, 0xc6, + 0xf7, 0xdc, 0xe3, 0x73, 0x77, 0xec, 0xc0, 0xfa, 0x02, 0x0b, 0xd6, 0x62, + 0x87, 0x58, 0xfe, 0x3c, 0x2c, 0x8b, 0x2a, 0xaf, 0x58, 0x33, 0x93, 0x91, + 0x61, 0x9e, 0xf6, 0x35, 0x54, 0x70, 0x84, 0x22, 0x96, 0x64, 0x71, 0xd4, + 0xde, 0x8a, 0x18, 0xd5, 0x43, 0xa7, 0x6e, 0x31, 0xb2, 0x9f, 0x88, 0x41, + 0x93, 0x7d, 0x4e, 0x61, 0x17, 0x39, 0xe7, 0x1f, 0x4f, 0xa2, 0x21, 0x40, + 0x2d, 0x2b, 0x56, 0xb4, 0xbd, 0xf7, 0x7c, 0xef, 0x0a, 0x70, 0xa8, 0x56, + 0x71, 0x87, 0x6a, 0x26, 0xb9, 0xfe, 0xba, 0x9c, 0x72, 0x74, 0x7a, 0x8b, + 0xa3, 0xaa, 0x0e, 0x19, 0x29, 0x2d, 0x84, 0x8c, 0xa7, 0xd2, 0xd4, 0x27, + 0x30, 0x3b, 0x67, 0xb5, 0xb7, 0xc3, 0x02, 0x17, 0x30, 0x3b, 0x47, 0x6e, + 0xc2, 0xf3, 0xf7, 0xfd, 0x41, 0x76, 0x99, 0xec, 0x92, 0xb8, 0xbd, 0xf3, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x06, 0x0f, 0x16, 0x20, 0x24, 0x28}; +const uint8_t kExpectedCase2Signature[MLDSA65_SIGNATURE_BYTES] = { + 0xef, 0xbf, 0xd8, 0x29, 0xd3, 0x48, 0xaf, 0x86, 0x0d, 0xe5, 0x31, 0xde, + 0xfc, 0xe8, 0x90, 0xc3, 0x1d, 0x9a, 0xda, 0x49, 0xd4, 0xb2, 0xab, 0x5e, + 0x19, 0x8e, 0x31, 0x6f, 0x73, 0x3f, 0x7f, 0x77, 0xf8, 0xda, 0x71, 0x90, + 0xf9, 0xad, 0x47, 0xdd, 0x9f, 0xed, 0xb9, 0x79, 0xbc, 0x70, 0xf7, 0x80, + 0x43, 0xa1, 0xf1, 0x68, 0x71, 0x25, 0x05, 0x54, 0x1f, 0x91, 0xc3, 0xd9, + 0xc1, 0xad, 0xbc, 0xb9, 0xa2, 0xd9, 0x80, 0x8d, 0xf4, 0xe4, 0xd2, 0xa6, + 0x63, 0x6b, 0x94, 0x5f, 0x16, 0xf4, 0xe1, 0xe6, 0x28, 0x6d, 0x8a, 0xb9, + 0x58, 0x72, 0xb7, 0xda, 0x42, 0xbd, 0xa7, 0xaa, 0x85, 0x72, 0x1e, 0xa6, + 0xe9, 0xf0, 0x57, 0x13, 0x98, 0x13, 0x88, 0x23, 0x81, 0x41, 0xe4, 0x8b, + 0x8b, 0x77, 0x50, 0x98, 0x20, 0x28, 0xc5, 0x0b, 0x66, 0x16, 0x3b, 0xad, + 0xf5, 0xf4, 0xd5, 0xe7, 0xe5, 0x99, 0xab, 0x21, 0x9b, 0x0f, 0xbd, 0x02, + 0x4c, 0x46, 0x25, 0xc4, 0x2f, 0x14, 0x35, 0x52, 0x12, 0x70, 0xe3, 0x22, + 0xa9, 0xa1, 0x99, 0x44, 0x40, 0xeb, 0xb3, 0x8d, 0xc7, 0xec, 0x42, 0x55, + 0x10, 0xe9, 0x6b, 0xbb, 0x20, 0xb7, 0x1d, 0xc4, 0x23, 0x11, 0x91, 0x2b, + 0x41, 0x3c, 0xc7, 0xe2, 0xda, 0xdf, 0xb6, 0x0a, 0xac, 0x43, 0x2e, 0xfe, + 0x6e, 0x01, 0x8f, 0xb7, 0x75, 0x4f, 0xa6, 0x2e, 0x1e, 0xff, 0x04, 0xfe, + 0x06, 0x73, 0xed, 0xba, 0x96, 0xad, 0x9f, 0xff, 0xb1, 0xea, 0x89, 0xfa, + 0x9f, 0xc9, 0xae, 0x26, 0x68, 0xec, 0xe3, 0x93, 0xaa, 0x35, 0xe6, 0xc6, + 0x1b, 0x99, 0xf3, 0xc1, 0xef, 0x8f, 0x56, 0xf4, 0xd9, 0x1f, 0xf3, 0xe0, + 0x96, 0xe3, 0x77, 0x76, 0x90, 0xbc, 0xba, 0xcf, 0x3f, 0x2b, 0x24, 0xda, + 0x48, 0xf5, 0x7f, 0x1d, 0x58, 0xe9, 0x69, 0x3c, 0xd6, 0x0b, 0x21, 0x7f, + 0xad, 0x7e, 0xc7, 0xce, 0x08, 0x52, 0x6c, 0x7a, 0xb9, 0xaf, 0xdb, 0x4f, + 0xc4, 0x56, 0x05, 0x3a, 0x3d, 0x94, 0xa0, 0xdc, 0x92, 0x14, 0x20, 0x3c, + 0xf1, 0x2a, 0xf7, 0x9f, 0xab, 0x6f, 0x1b, 0x7a, 0xb1, 0x0e, 0x7d, 0x72, + 0xdc, 0x65, 0xb1, 0x10, 0xa5, 0x1f, 0x83, 0x9d, 0x4c, 0x2a, 0x37, 0x4a, + 0x0d, 0xaa, 0xd4, 0x35, 0x13, 0x3e, 0x68, 0x24, 0x12, 0x31, 0x80, 0xbc, + 0x9a, 0x1d, 0x4a, 0xea, 0x31, 0x50, 0x7d, 0x57, 0x95, 0x56, 0x3c, 0x6a, + 0x5e, 0xbf, 0x82, 0x47, 0x53, 0x5d, 0x38, 0xce, 0x2b, 0xac, 0x03, 0xe6, + 0x50, 0xfd, 0x6a, 0x6a, 0xbb, 0x79, 0x83, 0xee, 0xe2, 0x10, 0xef, 0xb1, + 0xc1, 0x2b, 0x01, 0x9d, 0xdc, 0xae, 0x2d, 0xaf, 0x18, 0x48, 0x6d, 0xd2, + 0x00, 0x62, 0x96, 0x9e, 0x9d, 0xf9, 0x1e, 0xa5, 0xbc, 0x8e, 0x5f, 0x10, + 0x08, 0x63, 0x87, 0x8d, 0x18, 0x4f, 0xd3, 0x8f, 0x99, 0xa7, 0xb6, 0x80, + 0x4d, 0xf2, 0x44, 0x22, 0x0b, 0x2e, 0x5c, 0x78, 0x36, 0x93, 0xcb, 0x68, + 0x17, 0x00, 0xfc, 0x85, 0x89, 0xd4, 0x3b, 0x1e, 0xed, 0x69, 0xa8, 0xa3, + 0x3d, 0xd1, 0x79, 0x7d, 0x18, 0xd8, 0xea, 0xde, 0xf8, 0x4f, 0xd7, 0x82, + 0x84, 0x3e, 0x57, 0xf7, 0x6e, 0x6c, 0x7a, 0xd7, 0xa2, 0x35, 0x9b, 0xe0, + 0x81, 0xfb, 0xcf, 0x3e, 0xd5, 0xbf, 0x13, 0x25, 0x9d, 0x1e, 0x0d, 0x85, + 0x69, 0x17, 0xbc, 0x45, 0xfd, 0xe1, 0xb9, 0x1c, 0xbb, 0x48, 0x46, 0x9d, + 0x4e, 0x99, 0x0c, 0x8c, 0xba, 0xb0, 0x3d, 0x6f, 0x6d, 0xea, 0x62, 0xb4, + 0x70, 0xfb, 0xf9, 0xae, 0x20, 0x44, 0xfc, 0x5d, 0x61, 0xce, 0x7d, 0x1b, + 0x44, 0xae, 0x20, 0xee, 0x0f, 0x9f, 0xaa, 0xa1, 0x3e, 0x6b, 0x53, 0xb4, + 0x2e, 0x44, 0x2b, 0xdc, 0x83, 0xa5, 0x2a, 0xd5, 0xda, 0x23, 0x10, 0xbf, + 0x3f, 0xb1, 0x3b, 0xa8, 0x0f, 0x01, 0x06, 0xcd, 0xff, 0x01, 0x3e, 0x33, + 0x98, 0xb8, 0xf7, 0x26, 0x31, 0x19, 0x07, 0x96, 0x83, 0x94, 0x67, 0x70, + 0xac, 0xeb, 0xb1, 0x2f, 0x42, 0x63, 0x36, 0xf2, 0xf4, 0x13, 0x61, 0x72, + 0x3e, 0x70, 0xbb, 0xfe, 0xe5, 0x11, 0xc5, 0x77, 0x2f, 0xa2, 0x12, 0xa3, + 0x19, 0xff, 0xea, 0x9c, 0xf2, 0xcf, 0x6a, 0x49, 0x09, 0x00, 0x54, 0x1e, + 0xae, 0x8c, 0xb3, 0xfe, 0x12, 0x68, 0x24, 0x04, 0x7c, 0x48, 0x84, 0x29, + 0xb3, 0x5f, 0x71, 0x45, 0xc7, 0x62, 0xcf, 0xaf, 0xca, 0xe2, 0x8c, 0xd5, + 0xb5, 0xc9, 0x82, 0x69, 0x98, 0x0d, 0x16, 0x58, 0x31, 0xb3, 0x38, 0x68, + 0x20, 0x82, 0xd5, 0x51, 0xb6, 0xb3, 0x57, 0xb0, 0xa6, 0x7c, 0x6d, 0xf3, + 0x82, 0x85, 0xc6, 0xf2, 0x06, 0x67, 0x40, 0x4f, 0x0c, 0x58, 0xfb, 0xc2, + 0xa2, 0x73, 0x00, 0x38, 0x00, 0xcc, 0x70, 0x93, 0x6d, 0x6c, 0x3b, 0xd4, + 0x4f, 0xcf, 0xb5, 0x1a, 0x26, 0x4e, 0xdb, 0x43, 0xf1, 0x02, 0x9c, 0xe9, + 0xe6, 0x0d, 0x1b, 0xa2, 0xae, 0xaf, 0xee, 0x48, 0x21, 0x50, 0x9c, 0xfe, + 0xe7, 0xa1, 0x0a, 0x14, 0xf2, 0x59, 0x15, 0x04, 0xd1, 0x8f, 0x37, 0xfa, + 0x22, 0x7c, 0xe0, 0x91, 0x83, 0xc8, 0x5d, 0x10, 0xcc, 0xaa, 0x38, 0x03, + 0x4b, 0xb4, 0xee, 0xea, 0x7b, 0x1b, 0x9a, 0xfd, 0x92, 0x1b, 0x35, 0x5a, + 0x0e, 0xa9, 0xfe, 0xa9, 0x11, 0x42, 0xc1, 0xc9, 0x3d, 0xb8, 0x06, 0xcb, + 0x39, 0x59, 0xb0, 0xb2, 0xf2, 0x2d, 0x25, 0x98, 0xf5, 0xde, 0x94, 0xd3, + 0x9e, 0xcd, 0x39, 0xbc, 0x6a, 0xae, 0x85, 0x62, 0x36, 0x33, 0x7b, 0xe1, + 0x2f, 0x0f, 0x77, 0x25, 0x7a, 0xe1, 0x88, 0xb4, 0xcb, 0x6a, 0x5f, 0x2a, + 0x15, 0x02, 0x0b, 0xbd, 0xe2, 0x0c, 0x7b, 0xeb, 0x15, 0xe3, 0x02, 0xd9, + 0x56, 0x78, 0xcb, 0x71, 0x07, 0xc9, 0x40, 0xa6, 0xe3, 0x96, 0x79, 0xa2, + 0xb3, 0xe5, 0xe0, 0xfe, 0x78, 0xf8, 0xa1, 0x2a, 0x5d, 0xa8, 0x5d, 0x43, + 0x08, 0x52, 0xf1, 0xcd, 0x4e, 0x13, 0xc5, 0x85, 0x8d, 0x81, 0xa3, 0x18, + 0x1a, 0x23, 0x03, 0x85, 0xf4, 0x13, 0x60, 0xf5, 0x31, 0x02, 0xfb, 0xb9, + 0x6c, 0xe5, 0x06, 0x6b, 0xf3, 0x78, 0xf9, 0x03, 0x9c, 0x62, 0xf1, 0xcc, + 0xeb, 0xe5, 0x97, 0xe8, 0xf7, 0xb2, 0x70, 0xbd, 0xca, 0x37, 0x7c, 0x15, + 0xa3, 0x2f, 0xce, 0x0b, 0xb8, 0xd2, 0xd7, 0x9d, 0xea, 0x96, 0xc7, 0x49, + 0xf6, 0xc1, 0x21, 0x7b, 0x7c, 0x41, 0x48, 0x71, 0x71, 0x21, 0xfa, 0x72, + 0x41, 0x48, 0x79, 0x80, 0x4e, 0x9a, 0xd6, 0xbc, 0x9e, 0x21, 0x76, 0x08, + 0x78, 0x33, 0xe3, 0x84, 0x5a, 0xcb, 0x0d, 0xc6, 0x59, 0x73, 0xc8, 0x9e, + 0x11, 0x55, 0x7b, 0x67, 0xff, 0x1d, 0xa5, 0x2a, 0x1f, 0x8c, 0x1d, 0x58, + 0x82, 0x1f, 0xde, 0x56, 0x79, 0x36, 0xe0, 0x80, 0x8a, 0xe2, 0xc0, 0xbc, + 0x56, 0x7d, 0xdd, 0xc1, 0x58, 0xae, 0x14, 0xe2, 0x50, 0x51, 0x8b, 0xc2, + 0xf8, 0xde, 0x6c, 0x81, 0xb2, 0x20, 0xfe, 0x09, 0x8d, 0x01, 0xb4, 0xf5, + 0xf0, 0xf6, 0x6c, 0xc9, 0x98, 0xcf, 0x86, 0x86, 0xf8, 0x9c, 0x7a, 0x0e, + 0x76, 0x38, 0xf3, 0x84, 0x48, 0xaf, 0x1f, 0x10, 0x08, 0x14, 0x43, 0xbb, + 0x04, 0x34, 0x8b, 0x72, 0x23, 0x9c, 0x81, 0x54, 0x36, 0x0f, 0x72, 0x7e, + 0xae, 0xac, 0xe9, 0x14, 0x11, 0x80, 0x40, 0xbd, 0x5d, 0xe0, 0xcd, 0xe9, + 0xea, 0x91, 0x63, 0x99, 0x22, 0x2e, 0x0a, 0x3a, 0x09, 0x06, 0xb7, 0xe5, + 0x01, 0x3d, 0xc2, 0xb7, 0x8f, 0xaf, 0x6e, 0x6a, 0xd1, 0xd5, 0x64, 0x54, + 0x69, 0x22, 0x9f, 0x4e, 0xb1, 0x7a, 0xd6, 0x7e, 0x2b, 0xb1, 0xac, 0x54, + 0xb6, 0x45, 0x70, 0x22, 0xa0, 0x7c, 0xdf, 0x59, 0xba, 0x9a, 0x80, 0x83, + 0xdd, 0x58, 0x16, 0xbc, 0x13, 0x23, 0xee, 0x14, 0x9d, 0x1c, 0xd0, 0x50, + 0x6d, 0x7f, 0x16, 0xab, 0x59, 0x54, 0xe4, 0xdb, 0x51, 0xbf, 0x7a, 0x33, + 0xf1, 0x58, 0xad, 0xd8, 0xcb, 0xe3, 0x16, 0xa5, 0x22, 0xc1, 0xe8, 0x5a, + 0x79, 0x09, 0x8a, 0x54, 0x86, 0x53, 0xd7, 0x20, 0x79, 0x30, 0x34, 0x5e, + 0x18, 0x66, 0x8e, 0x3f, 0x25, 0x02, 0x46, 0x31, 0x59, 0x1a, 0x97, 0x04, + 0x1f, 0x81, 0x2d, 0xdf, 0x11, 0xeb, 0xb0, 0xe2, 0x20, 0xcc, 0x24, 0x25, + 0x3a, 0x04, 0x06, 0x6d, 0xf5, 0x6a, 0xf0, 0x5d, 0x6f, 0xb6, 0x77, 0x47, + 0xf2, 0xfb, 0x50, 0x8d, 0xf8, 0xc4, 0xdf, 0x5d, 0x7d, 0xb2, 0x36, 0x95, + 0xe1, 0x63, 0x78, 0x29, 0x09, 0xce, 0xe1, 0x34, 0xaf, 0x8f, 0x87, 0x85, + 0x09, 0xd5, 0x0b, 0xc0, 0x25, 0x8c, 0x5f, 0x9a, 0xc8, 0xf0, 0xf7, 0x32, + 0x08, 0xae, 0x32, 0xbe, 0x9f, 0xf3, 0xc9, 0x64, 0x1f, 0x09, 0xe4, 0x9e, + 0x96, 0xbb, 0xed, 0x32, 0x0c, 0x43, 0xad, 0x86, 0x06, 0xc2, 0xb6, 0x52, + 0xce, 0xf0, 0x60, 0x4e, 0x53, 0xf7, 0x36, 0xa0, 0x37, 0x13, 0xcd, 0x9f, + 0xfc, 0xf2, 0x4b, 0x69, 0xf2, 0x3a, 0xa4, 0xa0, 0x7c, 0x4f, 0xbc, 0x1f, + 0xd0, 0x5a, 0xf6, 0x8e, 0x86, 0xe6, 0x4f, 0xe2, 0xc8, 0xb8, 0x4a, 0xb5, + 0xb5, 0xec, 0x5c, 0x5d, 0x06, 0xd2, 0xd8, 0xf0, 0xb9, 0x22, 0xd3, 0x6d, + 0x6a, 0x26, 0xae, 0x09, 0xbe, 0x1a, 0x9a, 0x80, 0xdf, 0x6c, 0x29, 0xa0, + 0xa2, 0xa2, 0xbc, 0xb9, 0xbf, 0xd9, 0xac, 0x10, 0xc5, 0x5d, 0x3d, 0xe4, + 0x89, 0x12, 0x99, 0x4e, 0xab, 0x7b, 0x6a, 0x1c, 0xd4, 0x60, 0x20, 0x20, + 0x91, 0xfe, 0xf4, 0x2f, 0x0f, 0xfa, 0x5a, 0x77, 0xd0, 0x4c, 0x72, 0x3e, + 0x20, 0x14, 0xbf, 0x40, 0xb4, 0x2d, 0x7f, 0x10, 0x93, 0x77, 0x73, 0xb7, + 0x5d, 0xce, 0x64, 0x01, 0xe8, 0x7c, 0xc3, 0xae, 0xdc, 0xc6, 0x91, 0x11, + 0xb0, 0x4c, 0x00, 0x2a, 0xdb, 0xa8, 0xbb, 0xa9, 0x3e, 0x0d, 0x2a, 0x8b, + 0x75, 0x93, 0x1b, 0xcb, 0xb6, 0xc1, 0xcd, 0x33, 0xf7, 0x5f, 0x64, 0xe7, + 0xb4, 0x07, 0x7d, 0xdf, 0x9d, 0x1b, 0x4e, 0x38, 0xc1, 0x4e, 0xe0, 0xa4, + 0x18, 0xab, 0xdc, 0x7c, 0x33, 0x50, 0xdb, 0xd5, 0x33, 0xbb, 0xb9, 0x74, + 0x6e, 0xa5, 0x9f, 0x93, 0x6a, 0x4b, 0x8a, 0xf6, 0x6f, 0x10, 0xfa, 0x85, + 0xe0, 0x72, 0xfa, 0x58, 0x25, 0x79, 0x38, 0xe0, 0xfa, 0x80, 0xde, 0x35, + 0xe7, 0x4e, 0x37, 0x54, 0x5a, 0xf8, 0xb9, 0x77, 0x15, 0xc7, 0xa1, 0x6f, + 0x91, 0x98, 0x1d, 0x3d, 0x8c, 0xd4, 0x5b, 0xe9, 0x56, 0x20, 0x87, 0x2a, + 0x6a, 0x6f, 0xd1, 0x88, 0x02, 0x16, 0x46, 0x7b, 0x96, 0x03, 0x99, 0x17, + 0x51, 0x1a, 0x74, 0x9d, 0x13, 0x5f, 0xb2, 0xa6, 0xf2, 0xf6, 0x6f, 0x8c, + 0xb8, 0xd7, 0x3c, 0x41, 0xd8, 0x51, 0xb4, 0x4d, 0x70, 0x22, 0xb6, 0x93, + 0x76, 0xab, 0x82, 0x49, 0x76, 0x8b, 0xe2, 0x99, 0x3d, 0x25, 0x97, 0x74, + 0x8b, 0x8b, 0xd6, 0xdd, 0xab, 0xf7, 0x0d, 0xa1, 0xc9, 0x96, 0xb8, 0xfa, + 0xcb, 0xfb, 0x2c, 0xb6, 0xe5, 0x60, 0x7d, 0x7f, 0x7c, 0x4b, 0x05, 0x5b, + 0xe6, 0xee, 0xc5, 0x7c, 0x60, 0xba, 0x66, 0x7a, 0xc1, 0xc6, 0x9c, 0xce, + 0xae, 0xa7, 0x93, 0xb7, 0x5a, 0xc8, 0x7f, 0x9d, 0xaa, 0xe2, 0xc0, 0x4b, + 0xb8, 0x05, 0x1d, 0x68, 0x00, 0x17, 0x2e, 0x8e, 0xad, 0xe4, 0x01, 0xa7, + 0x82, 0x96, 0xd3, 0x31, 0x0e, 0xd3, 0x8f, 0xae, 0x83, 0xd3, 0xab, 0xa4, + 0xd2, 0x5e, 0x45, 0x99, 0x47, 0x97, 0x8b, 0x88, 0xcf, 0x0f, 0xa2, 0x7b, + 0x11, 0xc3, 0xb5, 0x5a, 0x39, 0x2a, 0x39, 0x7a, 0x57, 0x09, 0x0b, 0x1e, + 0x3e, 0xe7, 0x08, 0x89, 0xee, 0xeb, 0x0c, 0xce, 0x14, 0x60, 0x33, 0x1e, + 0xa1, 0x51, 0xf2, 0x72, 0x3c, 0xe3, 0xb1, 0xd5, 0x2a, 0x11, 0x96, 0xe9, + 0x1c, 0x40, 0xcd, 0x65, 0x01, 0x2a, 0xc5, 0x75, 0xea, 0x28, 0xfd, 0x8b, + 0xf6, 0x45, 0xd6, 0x4c, 0xde, 0x31, 0x7f, 0xa4, 0xfc, 0x8f, 0x9c, 0xd9, + 0x4a, 0xf2, 0xbc, 0xf6, 0x76, 0xdd, 0xef, 0xc4, 0x44, 0xd4, 0x16, 0xac, + 0x79, 0x44, 0x63, 0xb2, 0x0b, 0x9e, 0x73, 0x49, 0x5f, 0x2b, 0xc5, 0x5a, + 0xc7, 0x0a, 0xe3, 0x18, 0xd0, 0x49, 0xf6, 0x4d, 0x8d, 0x23, 0x22, 0xa9, + 0xa7, 0x07, 0x37, 0xa0, 0x1b, 0xf3, 0x81, 0xf2, 0xb1, 0x03, 0x16, 0x5c, + 0x5a, 0x0a, 0xe6, 0xa5, 0x26, 0x5c, 0xaf, 0x03, 0x16, 0x89, 0x4b, 0xe3, + 0x93, 0xcc, 0x1d, 0xc5, 0x67, 0x30, 0x66, 0xbf, 0x3d, 0x1b, 0xc9, 0x80, + 0xdb, 0x7c, 0xfa, 0xeb, 0x79, 0x32, 0x69, 0x61, 0x90, 0x21, 0xbb, 0x35, + 0x2a, 0xb9, 0x94, 0xc2, 0xfa, 0x8a, 0xe2, 0x1c, 0xb2, 0xc5, 0x77, 0x7d, + 0xd0, 0x0e, 0x20, 0xa3, 0x39, 0xd1, 0x2b, 0x5f, 0x97, 0x82, 0xf0, 0x9e, + 0x67, 0xe3, 0x15, 0xc8, 0x36, 0x2e, 0x75, 0x20, 0x90, 0x24, 0x61, 0xd4, + 0x32, 0xc6, 0x97, 0x41, 0xf0, 0xb4, 0x0e, 0xa2, 0xa2, 0x1e, 0x2b, 0x77, + 0xc2, 0x4c, 0x17, 0x35, 0xe1, 0x1a, 0x15, 0x1e, 0x3f, 0xf7, 0xf1, 0x3b, + 0x91, 0x77, 0xe9, 0x84, 0x73, 0x2c, 0x61, 0xe9, 0x41, 0x45, 0x56, 0xd1, + 0x3b, 0xe4, 0x54, 0x79, 0x15, 0x75, 0x51, 0xe2, 0xbe, 0xed, 0x32, 0xd0, + 0xef, 0x34, 0xf1, 0x1f, 0x2e, 0xa8, 0x8e, 0x6b, 0x59, 0x65, 0xb1, 0x2a, + 0x54, 0xf7, 0x4c, 0x1a, 0x6b, 0x3c, 0x18, 0xeb, 0x97, 0x3b, 0x94, 0xd4, + 0xfe, 0xe4, 0xae, 0x76, 0x2c, 0xf0, 0xbb, 0x4a, 0x63, 0xd6, 0x87, 0xe0, + 0x94, 0xee, 0xc9, 0x5a, 0xba, 0x80, 0x28, 0x5e, 0x6b, 0x14, 0x73, 0x7b, + 0xe6, 0x4b, 0x0a, 0x81, 0x80, 0x87, 0x68, 0xe0, 0xcb, 0xb8, 0x20, 0x8e, + 0x47, 0x69, 0xd2, 0x39, 0x10, 0x8b, 0xc7, 0x29, 0x41, 0x6b, 0x8d, 0xe5, + 0x29, 0xd9, 0xad, 0xb1, 0x69, 0x8c, 0xc2, 0xa1, 0x50, 0xd2, 0xe3, 0x80, + 0xe4, 0x09, 0xa2, 0xd6, 0xae, 0x75, 0x65, 0xca, 0x45, 0x75, 0xe9, 0xab, + 0x2c, 0x99, 0xc6, 0xe9, 0x04, 0xd0, 0xcc, 0x9d, 0xea, 0xc7, 0x85, 0x4c, + 0xb2, 0xb1, 0x6f, 0x49, 0xf1, 0xe5, 0x51, 0xce, 0xa6, 0x7e, 0x68, 0xe5, + 0x2b, 0xbe, 0xed, 0x21, 0x12, 0x9f, 0x3b, 0x03, 0x6f, 0x84, 0xd6, 0x47, + 0x27, 0x76, 0x7f, 0x7b, 0xb8, 0x45, 0x8f, 0xa0, 0xff, 0xb1, 0xa8, 0x8e, + 0x4a, 0x33, 0x3b, 0xfe, 0x5a, 0x37, 0x90, 0xe7, 0x37, 0x7b, 0xfc, 0xf4, + 0xb3, 0x5f, 0x1c, 0xf7, 0x77, 0xb7, 0x09, 0x77, 0xa1, 0x4d, 0x4e, 0x59, + 0xcb, 0x8d, 0x61, 0x8f, 0xee, 0x5a, 0xfb, 0xc0, 0x0b, 0x4e, 0x05, 0x76, + 0xa0, 0xd0, 0xc8, 0x8e, 0x2c, 0xba, 0x11, 0xde, 0xa0, 0xc9, 0x69, 0xf4, + 0x53, 0xda, 0xc7, 0xda, 0x13, 0x62, 0x94, 0xe4, 0x2f, 0x73, 0x21, 0xca, + 0xaf, 0x3f, 0xd2, 0xaf, 0xbe, 0x8e, 0xea, 0x8f, 0xd6, 0x88, 0x74, 0x94, + 0x95, 0x42, 0x04, 0xb4, 0x4c, 0x9a, 0xad, 0xf6, 0x7f, 0xe0, 0xad, 0xf4, + 0x86, 0x52, 0x09, 0x36, 0x02, 0xb8, 0x61, 0x43, 0xe5, 0x2c, 0xd0, 0xd5, + 0x59, 0xc0, 0xf9, 0x99, 0x7c, 0x76, 0xc3, 0xb2, 0xb6, 0x59, 0x9a, 0x4f, + 0xd1, 0x0c, 0xc4, 0x76, 0x86, 0xfc, 0xd5, 0x23, 0x3e, 0x3c, 0x07, 0x9b, + 0x23, 0xac, 0x64, 0x58, 0x91, 0xb8, 0xd6, 0x96, 0xdc, 0x77, 0xaf, 0x32, + 0x32, 0x38, 0xda, 0xeb, 0xc5, 0x43, 0xb6, 0x96, 0x70, 0xbb, 0x63, 0x46, + 0x0b, 0xfd, 0xe5, 0x93, 0xdc, 0xb2, 0xaf, 0x80, 0x94, 0xb8, 0xd1, 0x94, + 0x59, 0x1e, 0xcb, 0x2d, 0xa5, 0xa2, 0xd6, 0xcd, 0x1a, 0x23, 0xd5, 0x61, + 0x03, 0xa7, 0x49, 0xc7, 0xb5, 0xd5, 0x1a, 0x16, 0x60, 0xc6, 0xc7, 0x94, + 0xbe, 0x79, 0x99, 0xf0, 0x11, 0x4f, 0x4b, 0x03, 0xdc, 0xfc, 0xb2, 0xd4, + 0x7a, 0xf8, 0xe0, 0xa4, 0x77, 0xd6, 0xa4, 0x01, 0xe2, 0x1f, 0xf1, 0x9b, + 0xdb, 0xba, 0x8b, 0x42, 0xe6, 0x5e, 0xa6, 0x89, 0x11, 0xab, 0xf1, 0xe9, + 0xad, 0x7b, 0x58, 0xfa, 0x68, 0x18, 0x17, 0xff, 0xe3, 0xe2, 0xa0, 0x94, + 0xb5, 0xf0, 0x72, 0x40, 0x65, 0x12, 0xfb, 0x11, 0xc9, 0x56, 0x56, 0xce, + 0xb1, 0x86, 0x5c, 0x50, 0x74, 0x49, 0x96, 0xf8, 0x43, 0x52, 0x9c, 0xaa, + 0xd2, 0x39, 0x84, 0xb3, 0x02, 0xc5, 0xa5, 0x8f, 0xbd, 0x6c, 0xc4, 0x74, + 0xf2, 0xc1, 0x0a, 0x08, 0xd0, 0xd9, 0x69, 0xff, 0xf2, 0x80, 0x50, 0x35, + 0x63, 0x88, 0x45, 0x0b, 0x8c, 0xd2, 0x48, 0x55, 0x0d, 0xba, 0xa9, 0x4c, + 0x7e, 0xd2, 0xaa, 0xb0, 0x7d, 0x46, 0x60, 0x15, 0x23, 0x4b, 0xa6, 0x4d, + 0x68, 0x85, 0x31, 0x12, 0xc5, 0x58, 0xdc, 0x2f, 0x26, 0x51, 0xf2, 0x96, + 0x7e, 0x2b, 0x67, 0xad, 0x66, 0x80, 0x33, 0x87, 0x33, 0x71, 0x52, 0x5d, + 0xd9, 0x4a, 0x1e, 0x23, 0x95, 0x70, 0xec, 0x85, 0x2d, 0x1d, 0x94, 0x33, + 0x40, 0xca, 0xef, 0x61, 0x3f, 0x77, 0x38, 0x65, 0x32, 0x9d, 0x94, 0x00, + 0xd6, 0x12, 0x4a, 0x37, 0x20, 0xe3, 0xc8, 0xc7, 0xdc, 0x59, 0x9b, 0x43, + 0xbe, 0x97, 0x33, 0x66, 0xc0, 0xc9, 0xa5, 0xbc, 0xfe, 0xec, 0x02, 0xf6, + 0x52, 0x18, 0x64, 0x24, 0x0c, 0x55, 0xc7, 0x0f, 0x62, 0x56, 0x45, 0xa2, + 0x7c, 0x93, 0xa3, 0xea, 0x0f, 0x87, 0xd1, 0xba, 0x23, 0x42, 0x80, 0xd9, + 0xc2, 0xb3, 0xd6, 0x25, 0x73, 0x10, 0x5b, 0x1a, 0xc1, 0xed, 0x4f, 0xa2, + 0x8d, 0x8e, 0x4d, 0x1b, 0x55, 0x64, 0xfd, 0xe3, 0x89, 0xab, 0xd6, 0xe6, + 0x45, 0x49, 0x6f, 0x91, 0x68, 0xb9, 0x26, 0xa4, 0xdd, 0x9f, 0x55, 0xa0, + 0x5f, 0x35, 0x69, 0x27, 0xd1, 0xb6, 0x5a, 0x3f, 0xcc, 0x52, 0x40, 0xad, + 0xda, 0x10, 0x8d, 0x2f, 0xd6, 0x8c, 0x01, 0xe1, 0x32, 0x73, 0xe1, 0x32, + 0xc3, 0xe7, 0x7e, 0xac, 0xba, 0x8c, 0xac, 0x38, 0x8f, 0x02, 0x0d, 0x67, + 0xa9, 0xc4, 0xab, 0x4e, 0xb5, 0x31, 0x77, 0xa2, 0x12, 0xd6, 0xaa, 0x58, + 0x57, 0xe7, 0xeb, 0xa6, 0x66, 0xd7, 0x36, 0xdc, 0x5c, 0x21, 0x86, 0xa4, + 0x76, 0x0a, 0x9c, 0x27, 0xb8, 0xeb, 0x0c, 0xc7, 0x2c, 0xf5, 0xe5, 0x49, + 0x8c, 0x62, 0x39, 0x82, 0xc0, 0xc4, 0x73, 0x8c, 0x74, 0x5d, 0xeb, 0xba, + 0xa5, 0x5a, 0xe2, 0x50, 0xdc, 0x06, 0xb7, 0x0b, 0x6c, 0xb9, 0x7e, 0x3d, + 0x01, 0xb7, 0x48, 0x2d, 0x4b, 0x90, 0xe7, 0x6d, 0x99, 0x58, 0xe1, 0xab, + 0x2b, 0xf1, 0x06, 0x5e, 0x25, 0x08, 0x9b, 0xc3, 0x79, 0xaf, 0xe0, 0x5e, + 0x01, 0xbb, 0x61, 0xb7, 0xc5, 0x22, 0x1c, 0xaf, 0x68, 0xef, 0x7f, 0xbb, + 0x41, 0x8b, 0x99, 0x19, 0xf0, 0x68, 0xe9, 0x94, 0x74, 0xe5, 0xda, 0xd4, + 0xf3, 0x8c, 0x4f, 0xdf, 0x09, 0x8f, 0x74, 0xd3, 0xbf, 0xe5, 0xee, 0x58, + 0xc0, 0x22, 0xa0, 0x91, 0x1e, 0xfa, 0x6b, 0x3b, 0x02, 0x2a, 0x03, 0xab, + 0x6a, 0xe2, 0xaa, 0xfe, 0x64, 0xbd, 0x77, 0xd0, 0x77, 0xc8, 0xbb, 0x75, + 0x9d, 0xb3, 0x3e, 0xe7, 0xc3, 0x57, 0x14, 0xb1, 0x75, 0x44, 0x98, 0x15, + 0x97, 0xef, 0x4c, 0xd2, 0x94, 0x50, 0x93, 0x89, 0x3a, 0x6f, 0xfa, 0x10, + 0x78, 0x90, 0xde, 0xef, 0xcb, 0x7d, 0x5d, 0xae, 0xbc, 0xfa, 0x48, 0x08, + 0x81, 0xc9, 0x0b, 0xdd, 0x90, 0x38, 0x34, 0x70, 0x66, 0x1a, 0x0e, 0xb1, + 0xe8, 0x99, 0x4e, 0x05, 0xf6, 0xa9, 0x88, 0x7f, 0xa6, 0x22, 0x19, 0x68, + 0xe1, 0xf5, 0x6b, 0xfc, 0xe7, 0xeb, 0xaa, 0x5b, 0xc4, 0x62, 0x8c, 0x19, + 0x45, 0xb9, 0x77, 0x8e, 0xcc, 0x31, 0xb4, 0xb3, 0x64, 0x43, 0xec, 0x95, + 0xe5, 0xd7, 0x63, 0x06, 0x29, 0xd8, 0x0c, 0xcb, 0xeb, 0x97, 0xa6, 0xad, + 0x37, 0x28, 0x7c, 0x8c, 0x28, 0xd6, 0x97, 0xa9, 0xc6, 0x3f, 0x9e, 0x1c, + 0x26, 0x0d, 0xf1, 0xba, 0xb1, 0x55, 0x96, 0xde, 0x86, 0xbf, 0x4e, 0x36, + 0x1f, 0x6c, 0x1c, 0xc6, 0xf5, 0x35, 0xb3, 0xb3, 0x74, 0xa0, 0x23, 0x86, + 0xda, 0x9e, 0x9a, 0xfd, 0xb7, 0xe8, 0x43, 0x67, 0x51, 0x26, 0x2d, 0xb3, + 0x72, 0x75, 0x6f, 0xd5, 0x2a, 0xae, 0xa3, 0xea, 0x04, 0xed, 0x83, 0x96, + 0xbb, 0xd1, 0x0d, 0x13, 0xdb, 0xc0, 0xb3, 0x26, 0x93, 0x54, 0x03, 0x2b, + 0x6e, 0x6a, 0x85, 0x8f, 0x50, 0x6f, 0xa3, 0xd3, 0x43, 0xda, 0x05, 0x1a, + 0x67, 0x86, 0x4e, 0xc5, 0x8f, 0xb2, 0x26, 0x71, 0xea, 0x4a, 0xcb, 0x24, + 0x4b, 0x00, 0x2e, 0xf0, 0xac, 0xaa, 0xae, 0x47, 0x0c, 0x01, 0x3b, 0x20, + 0xd0, 0x03, 0x58, 0xff, 0x4f, 0x00, 0xaf, 0xb0, 0xd1, 0x01, 0x41, 0xaf, + 0xfb, 0xdc, 0xcd, 0xa9, 0xe7, 0xa1, 0xeb, 0x81, 0x17, 0x41, 0x74, 0x6c, + 0x9b, 0xfb, 0x0d, 0xeb, 0x0c, 0x7a, 0xd0, 0x85, 0x6b, 0x0a, 0x30, 0x2b, + 0xa5, 0x1a, 0x67, 0xb2, 0x1a, 0x5e, 0x34, 0x89, 0x18, 0x37, 0x3e, 0xbe, + 0xd9, 0x81, 0x06, 0xd6, 0xcf, 0x8f, 0xdf, 0x4d, 0x94, 0x49, 0xc9, 0x12, + 0xe2, 0xb6, 0xc5, 0xc3, 0xdf, 0x05, 0xdb, 0x7c, 0xf0, 0x4a, 0xdf, 0x90, + 0xfa, 0x7e, 0xce, 0x89, 0x93, 0xf7, 0x28, 0x37, 0xd0, 0x1f, 0x3e, 0x7c, + 0x6d, 0x0e, 0x75, 0x5f, 0x55, 0xcb, 0xd1, 0x9e, 0x06, 0xed, 0xdd, 0x27, + 0xae, 0xb3, 0xce, 0xc0, 0x18, 0xce, 0x4a, 0x4f, 0x43, 0x81, 0x0d, 0x4c, + 0x29, 0x53, 0x91, 0xda, 0x5f, 0x22, 0x29, 0xed, 0x49, 0xbe, 0xed, 0x55, + 0x37, 0xf1, 0xa6, 0xfc, 0x7d, 0x10, 0xd7, 0xd0, 0xd3, 0xf2, 0xaf, 0x19, + 0xf3, 0x40, 0x2f, 0xfd, 0xe0, 0x16, 0x7e, 0x00, 0xb5, 0x4d, 0x57, 0x65, + 0xe6, 0x68, 0xef, 0xdb, 0x49, 0xe2, 0xaa, 0x39, 0xfc, 0x8d, 0x19, 0xa2, + 0x61, 0x6f, 0xdf, 0x43, 0xf4, 0x18, 0x5d, 0x16, 0xd9, 0x68, 0x92, 0x45, + 0x0d, 0x7f, 0x8d, 0x6f, 0xfd, 0x63, 0x26, 0x6d, 0x64, 0xfc, 0xf7, 0xa2, + 0x29, 0xda, 0x40, 0x65, 0x98, 0xfa, 0x2e, 0xba, 0x9f, 0x54, 0xfb, 0xc1, + 0xe4, 0x8f, 0xbc, 0x6e, 0x57, 0xe5, 0x9a, 0x9d, 0x1c, 0x63, 0x04, 0xc9, + 0x89, 0xf7, 0xe2, 0xdf, 0x3b, 0x83, 0xc8, 0x99, 0x65, 0xb7, 0x30, 0x7a, + 0x7b, 0x54, 0x95, 0x3f, 0x4e, 0x26, 0x05, 0xa6, 0x86, 0x40, 0x63, 0x4a, + 0xb8, 0x53, 0x33, 0x0c, 0x4e, 0x52, 0x26, 0x50, 0xf2, 0x81, 0x2f, 0x69, + 0xb0, 0x9d, 0x9e, 0x46, 0x2c, 0x1d, 0xfe, 0x79, 0x79, 0xff, 0x60, 0x83, + 0x05, 0x3f, 0xab, 0xcf, 0x04, 0x45, 0xe0, 0x19, 0xb7, 0xb3, 0x50, 0xc7, + 0x5e, 0x49, 0xe7, 0xed, 0x4c, 0x76, 0x60, 0x3e, 0xc9, 0x55, 0x11, 0xdc, + 0x54, 0xc7, 0x93, 0x13, 0xa8, 0x97, 0x0b, 0x46, 0xfb, 0xad, 0xa5, 0xeb, + 0xfc, 0xaa, 0x4a, 0x41, 0xc1, 0xc2, 0xee, 0xbd, 0x15, 0xb5, 0x91, 0x04, + 0x77, 0x93, 0xf1, 0x72, 0x38, 0x3f, 0x0b, 0x1e, 0x18, 0xdd, 0x93, 0x2c, + 0x1f, 0x32, 0x60, 0x12, 0x4f, 0x1b, 0x06, 0x34, 0xcb, 0xa5, 0x3a, 0x0f, + 0x07, 0xff, 0x9b, 0x39, 0xc0, 0x7c, 0xd8, 0xd7, 0x97, 0xe0, 0x08, 0x3b, + 0x55, 0xc7, 0x80, 0xc4, 0x07, 0xf6, 0x11, 0x9c, 0x5b, 0x25, 0x02, 0xc4, + 0x61, 0xb5, 0xa9, 0x8f, 0xec, 0x01, 0x5c, 0x17, 0xd8, 0x90, 0x48, 0xc5, + 0xd4, 0x2a, 0x0d, 0x8b, 0x40, 0x87, 0x46, 0x5e, 0xa2, 0x83, 0xf2, 0x64, + 0xf5, 0xb1, 0xeb, 0x52, 0xb2, 0x19, 0x9d, 0x2c, 0x29, 0x59, 0x3e, 0xde, + 0x6e, 0x33, 0xa3, 0x17, 0xd7, 0xf8, 0x58, 0x21, 0x42, 0x49, 0x7f, 0x5e, + 0x5c, 0xd9, 0x7f, 0x9f, 0xa0, 0x99, 0xa6, 0xfd, 0x66, 0x0c, 0x15, 0x64, + 0x5f, 0x1e, 0x01, 0x9d, 0x36, 0x20, 0xa9, 0xa4, 0x13, 0x2c, 0xc0, 0x80, + 0x92, 0x44, 0xd5, 0x61, 0xad, 0xd5, 0x9c, 0xf2, 0xdd, 0xc2, 0x0b, 0xc2, + 0x24, 0x1f, 0x69, 0x38, 0x48, 0x2c, 0x68, 0xf8, 0x19, 0xbe, 0x34, 0x21, + 0x38, 0xd0, 0x9c, 0xe5, 0xc0, 0xb8, 0x2b, 0x33, 0x24, 0x4c, 0x83, 0xe4, + 0x7d, 0xdb, 0x75, 0x7e, 0x60, 0xb4, 0x71, 0xaf, 0xb0, 0xc5, 0xb6, 0x4a, + 0xba, 0x9a, 0x83, 0x0b, 0x40, 0xf4, 0x96, 0x5a, 0xe2, 0x78, 0x20, 0x33, + 0xbb, 0x87, 0xba, 0x09, 0xf2, 0xd0, 0x24, 0x81, 0x23, 0xf5, 0x1b, 0x85, + 0x75, 0x12, 0x5d, 0x3e, 0xc5, 0x13, 0xc8, 0x03, 0xb7, 0xd5, 0x45, 0x70, + 0x64, 0x25, 0xfa, 0x58, 0xb5, 0x38, 0x11, 0x1f, 0xe7, 0x9e, 0x89, 0x5a, + 0x90, 0x59, 0xef, 0x7b, 0xd9, 0x14, 0x28, 0x2e, 0xf6, 0x30, 0x04, 0xf4, + 0xd0, 0x13, 0xba, 0xfc, 0x95, 0x39, 0x1a, 0xf4, 0xf4, 0xfd, 0x38, 0x83, + 0x46, 0x48, 0xc1, 0x31, 0x87, 0x0b, 0xa3, 0x1e, 0x67, 0x76, 0x83, 0xff, + 0x00, 0x52, 0x6b, 0xe8, 0xf4, 0x70, 0xa6, 0xba, 0xc0, 0xc4, 0x38, 0x9b, + 0xe0, 0x01, 0x07, 0x23, 0x3f, 0x58, 0x68, 0x7d, 0xbe, 0xdc, 0x0a, 0x4b, + 0xcc, 0xef, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x04, 0x09, 0x0e, 0x11, 0x1a, 0x1f}; + +const uint8_t kExpectedVerifySignature[] = { + 0x49, 0x23, 0xce, 0xa1, 0x29, 0x3b, 0x24, 0x00, 0xcc, 0xc3, 0xb1, 0x9f, + 0x1e, 0x80, 0x3e, 0xd8, 0x5a, 0x0d, 0x6e, 0x0b, 0xa6, 0x4f, 0x35, 0xf8, + 0x45, 0xf4, 0x20, 0xd8, 0x48, 0xe1, 0x85, 0x82, 0x05, 0x88, 0x3f, 0xdd, + 0xd4, 0xbd, 0xa0, 0xd9, 0xe3, 0x35, 0xca, 0x31, 0x02, 0x72, 0x95, 0x2c, + 0xd4, 0xfa, 0xf8, 0x76, 0x7a, 0xe1, 0x35, 0xcb, 0x7e, 0x93, 0xdd, 0x27, + 0xb9, 0x5d, 0x71, 0x0a, 0x08, 0xaf, 0xc2, 0x09, 0xbb, 0x74, 0xfa, 0xd9, + 0x46, 0x3b, 0x2f, 0x00, 0x53, 0xee, 0x74, 0x1c, 0x85, 0x15, 0xa8, 0x4b, + 0xa7, 0xf9, 0x0b, 0xbf, 0x9c, 0xde, 0x84, 0x03, 0xe3, 0x4f, 0x12, 0x21, + 0xe9, 0x1e, 0x7a, 0x06, 0x70, 0xd9, 0x68, 0x84, 0x53, 0x83, 0xcd, 0x72, + 0x4c, 0xe5, 0xcd, 0x6c, 0x30, 0x47, 0xd9, 0x28, 0x59, 0x64, 0x46, 0x57, + 0x93, 0xb5, 0x58, 0xe0, 0x8d, 0x92, 0x15, 0x16, 0xd0, 0x05, 0x09, 0x9f, + 0xdc, 0xcc, 0x2e, 0xfd, 0x8e, 0x13, 0x47, 0x41, 0x44, 0x15, 0x6c, 0x32, + 0x9f, 0x37, 0xfe, 0xe0, 0x31, 0xfb, 0xcb, 0x94, 0xec, 0x83, 0x37, 0x3e, + 0x72, 0x91, 0x0c, 0xab, 0xe0, 0x19, 0x57, 0xb8, 0xd0, 0xfb, 0x3f, 0x1c, + 0xe2, 0xb6, 0xf9, 0xc5, 0x9c, 0x91, 0x92, 0x1b, 0x2e, 0x0f, 0x6f, 0xf1, + 0xe6, 0x5a, 0xf1, 0x3c, 0x1a, 0x2c, 0xa6, 0xfb, 0x9d, 0x48, 0x86, 0x33, + 0xab, 0x94, 0xdf, 0x0b, 0x6b, 0xa8, 0xf0, 0x08, 0xb6, 0x59, 0xd4, 0xad, + 0xad, 0x9e, 0xe6, 0x07, 0x26, 0x00, 0x9a, 0x34, 0xc8, 0x2c, 0x7b, 0xd5, + 0x2e, 0xe0, 0x47, 0xd8, 0x0b, 0xd0, 0x34, 0x87, 0x62, 0xc5, 0x4d, 0x00, + 0xbc, 0x18, 0x62, 0x0b, 0x7f, 0xb7, 0xb6, 0x88, 0x43, 0x9f, 0x3f, 0x77, + 0x87, 0xec, 0xad, 0x21, 0xc2, 0xec, 0xfc, 0x99, 0x2f, 0xb6, 0x97, 0xab, + 0x40, 0xb3, 0xc2, 0x57, 0x33, 0x27, 0xde, 0x4b, 0xc6, 0x8e, 0x69, 0x47, + 0x59, 0x16, 0xe6, 0x49, 0xf7, 0x69, 0xe9, 0x3a, 0x08, 0xca, 0xd4, 0xd4, + 0x29, 0x44, 0x6d, 0xf3, 0x10, 0x56, 0x6f, 0x4b, 0x1d, 0x47, 0xb8, 0x9e, + 0x66, 0x5e, 0x11, 0x46, 0xec, 0xa8, 0x45, 0xc9, 0x66, 0xc1, 0x4a, 0x0c, + 0x62, 0x01, 0x2a, 0x05, 0xc6, 0xda, 0xb0, 0xd9, 0x95, 0x09, 0xc0, 0x97, + 0xe0, 0x33, 0xa2, 0x89, 0x36, 0xf6, 0xab, 0xa0, 0x7f, 0x65, 0xff, 0x2c, + 0xf5, 0xb9, 0x06, 0x74, 0x8b, 0xc2, 0x10, 0xc7, 0x7f, 0xdb, 0xfd, 0x6d, + 0xfe, 0xa8, 0xed, 0xd9, 0x41, 0x3b, 0x1d, 0x40, 0x96, 0xc8, 0xf5, 0x7c, + 0x23, 0x7b, 0xfc, 0x80, 0x5a, 0xb3, 0x1d, 0xfd, 0x29, 0x37, 0xfc, 0x12, + 0xa5, 0x64, 0x18, 0x93, 0xea, 0xc3, 0x15, 0xf6, 0x36, 0x3e, 0x92, 0xd6, + 0x31, 0x1c, 0xe2, 0x70, 0x89, 0xd9, 0x55, 0x4f, 0x42, 0x9e, 0x5e, 0xd2, + 0x80, 0x4a, 0x71, 0x31, 0xfc, 0x8f, 0xc2, 0x7f, 0xfc, 0xed, 0x8e, 0x48, + 0x8c, 0xc1, 0x7b, 0xa8, 0x73, 0xd3, 0x25, 0xd6, 0xe2, 0x1e, 0x14, 0x5e, + 0xbb, 0xd1, 0x3e, 0x44, 0x4c, 0x97, 0x99, 0xc4, 0xb9, 0xce, 0x42, 0xa1, + 0x0c, 0x0d, 0xa2, 0xd1, 0x60, 0xfe, 0x58, 0xf6, 0xf5, 0x4a, 0x27, 0x07, + 0xac, 0x49, 0x10, 0x71, 0x85, 0xc4, 0xdf, 0xab, 0x73, 0xde, 0x82, 0x17, + 0xb6, 0x0c, 0x97, 0x77, 0x8a, 0xd6, 0x88, 0x1e, 0x0b, 0xb5, 0x87, 0xa9, + 0xc5, 0xcb, 0x34, 0x48, 0x19, 0x86, 0xf1, 0x72, 0x68, 0xd9, 0xdc, 0x4b, + 0x6e, 0x06, 0x6c, 0x7d, 0x39, 0x47, 0xfe, 0xf9, 0x78, 0x23, 0x63, 0xa2, + 0x3c, 0xdc, 0xd0, 0x23, 0x44, 0x64, 0x49, 0x06, 0x12, 0x43, 0x35, 0xc6, + 0xcb, 0xd1, 0x87, 0x07, 0xaa, 0x9a, 0x03, 0x30, 0x93, 0xc7, 0xac, 0x92, + 0x28, 0xb5, 0xbd, 0x43, 0xc2, 0x86, 0xda, 0x36, 0xf1, 0xc1, 0x81, 0x68, + 0xd9, 0xcd, 0x00, 0x2d, 0x44, 0x16, 0xa7, 0x21, 0x37, 0x26, 0x87, 0xc8, + 0x0a, 0xf4, 0x8b, 0x40, 0x29, 0x84, 0xe8, 0x70, 0x56, 0xb4, 0x3f, 0xc6, + 0xc8, 0x96, 0xb5, 0xea, 0xc0, 0x7b, 0x4a, 0x67, 0x2b, 0x6d, 0xd0, 0x0d, + 0xd4, 0x79, 0x2d, 0xbd, 0xe1, 0xf1, 0xb3, 0x50, 0x2e, 0xac, 0x22, 0xf4, + 0x40, 0xec, 0x1b, 0xdc, 0xd5, 0x3d, 0xea, 0x7d, 0xa4, 0x53, 0x6a, 0x66, + 0x0b, 0x85, 0xa2, 0x57, 0xb6, 0x0d, 0xfe, 0x8f, 0xc5, 0x55, 0x1d, 0xcc, + 0xe1, 0x39, 0xc0, 0x32, 0xb5, 0x22, 0x35, 0x8b, 0x01, 0x0c, 0xb5, 0x4b, + 0xd5, 0x1a, 0xd7, 0x39, 0xa0, 0x32, 0x47, 0x50, 0x30, 0xef, 0x74, 0xf3, + 0x52, 0x53, 0x29, 0x8c, 0xaa, 0x24, 0x94, 0xb8, 0xc0, 0xb9, 0xc3, 0x18, + 0x5a, 0x49, 0x6d, 0x0e, 0xe4, 0xcc, 0xa0, 0xfb, 0xb9, 0x45, 0xe2, 0x2f, + 0x89, 0x00, 0x8c, 0x5a, 0xc8, 0x1c, 0x61, 0x21, 0x6c, 0x35, 0x05, 0xc9, + 0x83, 0x07, 0x32, 0x73, 0x73, 0xa6, 0x34, 0x89, 0x83, 0x86, 0xb1, 0xa8, + 0x49, 0xaa, 0xec, 0x0c, 0x9a, 0x32, 0xc6, 0x34, 0xbd, 0x9b, 0xbe, 0x74, + 0x06, 0x3d, 0x6d, 0x83, 0x7d, 0x47, 0x4b, 0xb3, 0x45, 0x78, 0x3d, 0x8b, + 0xbf, 0xca, 0xdc, 0x0c, 0xfb, 0xc5, 0x01, 0xe4, 0x0b, 0xcc, 0x9b, 0x05, + 0xbf, 0x16, 0x05, 0xff, 0x2b, 0xd8, 0x20, 0xbc, 0xe2, 0xd8, 0xa0, 0x4c, + 0xcd, 0x4f, 0xc3, 0xe7, 0x3b, 0xbd, 0x1d, 0x82, 0xf8, 0x6c, 0xce, 0x6f, + 0x62, 0x05, 0x37, 0x9c, 0xb8, 0x26, 0x6a, 0x9f, 0x76, 0xcc, 0x97, 0xac, + 0x1d, 0x8b, 0xde, 0x9b, 0x20, 0x52, 0x29, 0x3d, 0x96, 0x01, 0x31, 0x56, + 0x4a, 0xea, 0x14, 0xf1, 0xdd, 0x2f, 0x6b, 0x91, 0x46, 0x58, 0x0d, 0xa8, + 0xff, 0xcc, 0x4f, 0x95, 0xbc, 0x2e, 0x18, 0x9e, 0x55, 0xfc, 0x27, 0x6a, + 0x15, 0x64, 0x68, 0x33, 0x5f, 0xa9, 0xda, 0xe4, 0x10, 0xe1, 0x41, 0x3b, + 0x59, 0xd7, 0x61, 0x5c, 0xa4, 0x7b, 0x3d, 0x28, 0x09, 0x59, 0x45, 0x65, + 0x68, 0xe9, 0xc8, 0x09, 0x13, 0xa3, 0x61, 0xac, 0xba, 0x98, 0x6d, 0x98, + 0xe3, 0x03, 0xa1, 0xe6, 0xf3, 0x5f, 0xb0, 0x1e, 0x72, 0x0b, 0x46, 0xc8, + 0x51, 0x26, 0xbf, 0xf9, 0x3e, 0x55, 0xc0, 0x9b, 0x7e, 0x09, 0x63, 0x85, + 0x92, 0x18, 0xf2, 0xf4, 0x17, 0x2e, 0x7d, 0x05, 0x99, 0x5e, 0x1d, 0xb2, + 0x3e, 0xad, 0x68, 0x29, 0x6d, 0x21, 0xe9, 0xb1, 0x38, 0xd5, 0x3e, 0xcc, + 0x5f, 0xe5, 0xd1, 0x16, 0xa8, 0x33, 0x4f, 0xbc, 0x28, 0x21, 0x14, 0x38, + 0xdd, 0x45, 0x0d, 0xa7, 0x00, 0x41, 0x5d, 0x5f, 0x98, 0x42, 0x7c, 0x54, + 0x16, 0x4f, 0x25, 0xf1, 0x46, 0x76, 0xe4, 0x67, 0x58, 0x5b, 0x65, 0x73, + 0xdf, 0xfd, 0x1c, 0x52, 0x61, 0x4d, 0x95, 0xb7, 0x78, 0x47, 0x50, 0x2d, + 0xc9, 0xab, 0x14, 0x1c, 0xae, 0x9c, 0xdc, 0x17, 0xdd, 0xcc, 0xe2, 0x5c, + 0x03, 0x0e, 0xe0, 0x2a, 0x81, 0xf0, 0xa7, 0xb9, 0x23, 0x21, 0x04, 0xbe, + 0x5c, 0xc9, 0x55, 0x58, 0x17, 0x26, 0x0c, 0xb4, 0x52, 0x24, 0xb7, 0x5a, + 0xb7, 0x0d, 0x7b, 0xfe, 0xe9, 0xd3, 0xda, 0x16, 0x43, 0xfa, 0x3b, 0xb3, + 0xa1, 0x3e, 0x48, 0xe1, 0x68, 0xf5, 0x51, 0xb1, 0xf3, 0x62, 0x06, 0x93, + 0x26, 0xe8, 0xa2, 0x9d, 0x9a, 0x7d, 0xf7, 0xa2, 0x8f, 0xe0, 0xe7, 0xa9, + 0x6e, 0xa3, 0xce, 0x7f, 0xfb, 0x94, 0x56, 0xc8, 0x2d, 0x6b, 0xcd, 0x2f, + 0xa0, 0x1f, 0x9b, 0x7b, 0x7a, 0xd4, 0x35, 0xe6, 0xa0, 0xa9, 0x09, 0x1b, + 0x7c, 0x89, 0xc0, 0xd1, 0xd1, 0x34, 0x99, 0x59, 0xb5, 0x6b, 0xb3, 0x29, + 0x54, 0xbf, 0xf0, 0xe7, 0x81, 0xee, 0x86, 0x28, 0x6e, 0x68, 0xb2, 0x22, + 0xc2, 0x08, 0x84, 0xb7, 0x12, 0xfc, 0x14, 0x55, 0x61, 0xea, 0x36, 0x59, + 0x51, 0x14, 0x28, 0x21, 0x30, 0xc3, 0x87, 0x91, 0xad, 0x1b, 0x9d, 0x50, + 0x53, 0xf8, 0x1e, 0x2c, 0x90, 0x14, 0x54, 0x67, 0xcf, 0x39, 0x76, 0x4d, + 0xfb, 0x4c, 0x7e, 0x0c, 0x3d, 0xa5, 0x79, 0x8c, 0x03, 0x72, 0xcb, 0xf3, + 0xd0, 0x2f, 0x20, 0xc3, 0xc0, 0x00, 0x38, 0x90, 0x1d, 0x9f, 0x97, 0xd6, + 0xc2, 0x5c, 0xc8, 0xb5, 0x86, 0x94, 0x30, 0x9d, 0x7a, 0x06, 0xb4, 0x4d, + 0x40, 0x04, 0xa4, 0x67, 0xb1, 0x12, 0x38, 0xf9, 0x77, 0x45, 0xc0, 0x57, + 0x4c, 0xc3, 0x24, 0x96, 0xf6, 0xf0, 0x99, 0x97, 0x50, 0x2e, 0x78, 0xe3, + 0x61, 0x93, 0x32, 0x33, 0x43, 0x6c, 0x2b, 0x38, 0xa2, 0xd3, 0xe3, 0xc5, + 0xe1, 0x8a, 0xe1, 0xa5, 0x9a, 0x59, 0xa0, 0xdc, 0x49, 0x9c, 0x81, 0x69, + 0x24, 0x0b, 0xc6, 0xf7, 0x4e, 0x8c, 0xc7, 0x66, 0xd5, 0x98, 0xc1, 0x88, + 0x63, 0xa9, 0xeb, 0x4d, 0xaa, 0x9c, 0x6c, 0xfe, 0xb1, 0x3b, 0x69, 0x47, + 0x99, 0xc1, 0xbd, 0x8a, 0x4c, 0xf7, 0xad, 0x9c, 0x54, 0x5b, 0xca, 0x99, + 0x23, 0x3b, 0xef, 0x25, 0x77, 0xa1, 0x0f, 0x0a, 0x1c, 0xf9, 0x08, 0x7e, + 0xee, 0x26, 0xd8, 0x4d, 0x14, 0xc7, 0x62, 0xb9, 0x44, 0xb6, 0xbb, 0x3c, + 0xaa, 0x3b, 0x22, 0x48, 0xfb, 0x8e, 0x3b, 0xed, 0x08, 0x3d, 0x89, 0x9b, + 0xf8, 0x44, 0xca, 0xfa, 0x26, 0x78, 0x29, 0xde, 0xd6, 0xf1, 0x7b, 0x59, + 0x5a, 0xe6, 0xd1, 0x24, 0x27, 0x11, 0xd6, 0x7d, 0x07, 0x49, 0xdd, 0xff, + 0x6d, 0x62, 0x5b, 0x9d, 0x12, 0x81, 0x00, 0xd7, 0xda, 0x00, 0xfb, 0xf7, + 0x4f, 0x2d, 0xf4, 0x64, 0xf1, 0xfb, 0x07, 0x23, 0x97, 0xe9, 0x0b, 0x22, + 0x9a, 0x3d, 0xf6, 0x87, 0xd8, 0x23, 0xf8, 0x54, 0x36, 0xa0, 0xab, 0xb8, + 0x99, 0x8b, 0x83, 0x98, 0x67, 0x33, 0x79, 0x2f, 0x60, 0x99, 0x16, 0x26, + 0x50, 0xfc, 0x9d, 0xea, 0xdc, 0x92, 0xf4, 0x7c, 0x44, 0xef, 0xed, 0x23, + 0x5e, 0x11, 0x0c, 0x6a, 0xc9, 0xf5, 0x9b, 0x64, 0x65, 0x58, 0x34, 0xc0, + 0x18, 0xc2, 0x3c, 0xf4, 0x4f, 0x5c, 0x06, 0x71, 0x59, 0xa9, 0xcd, 0xad, + 0x8b, 0xfd, 0x93, 0x05, 0xfc, 0x48, 0x92, 0xa2, 0xed, 0x9d, 0xa5, 0x89, + 0x29, 0x35, 0x76, 0x16, 0x2a, 0x69, 0xeb, 0x0c, 0xef, 0xe6, 0x90, 0xa8, + 0x18, 0x8b, 0x7e, 0x0e, 0x2c, 0xed, 0x34, 0x37, 0x23, 0xc3, 0x24, 0x7b, + 0x67, 0x53, 0x84, 0xbe, 0x5c, 0xe9, 0x8c, 0x37, 0x8e, 0x0e, 0x53, 0xb9, + 0xaa, 0x60, 0x64, 0x5e, 0x67, 0x88, 0x88, 0x72, 0x27, 0xb6, 0x8a, 0x72, + 0x44, 0xdf, 0xe1, 0x69, 0xb7, 0x1c, 0x35, 0x79, 0xce, 0xab, 0x3a, 0x04, + 0x60, 0xa3, 0x60, 0xd8, 0x84, 0x81, 0x61, 0xbc, 0x95, 0xc6, 0x9d, 0x3f, + 0x7d, 0xbd, 0x4b, 0x1d, 0x40, 0x35, 0x97, 0x6f, 0xd9, 0x0c, 0x51, 0xa7, + 0xac, 0x5b, 0xe8, 0xa1, 0xa8, 0x9b, 0x4e, 0x3c, 0x88, 0x29, 0x23, 0xca, + 0x83, 0x1a, 0xc4, 0x5c, 0xec, 0x13, 0x1a, 0x07, 0x5d, 0xf3, 0x58, 0xa6, + 0x17, 0x1c, 0x09, 0xca, 0x5f, 0x14, 0x47, 0xf6, 0x94, 0x2f, 0xe8, 0x98, + 0x31, 0x51, 0xbe, 0x32, 0xaa, 0x8c, 0xb0, 0x79, 0x88, 0xfa, 0xa3, 0x9c, + 0xcc, 0xc1, 0xf6, 0x25, 0xa9, 0x5d, 0xa1, 0x46, 0xf1, 0x30, 0xd0, 0x41, + 0xf9, 0x5e, 0xca, 0x28, 0x06, 0x3c, 0xce, 0xb2, 0x40, 0xe3, 0xaf, 0x5e, + 0x53, 0x0e, 0xfc, 0x94, 0x9d, 0x6d, 0xc1, 0x90, 0x24, 0x00, 0x31, 0xcf, + 0x8d, 0x4a, 0xce, 0x81, 0xac, 0xe0, 0x88, 0x2e, 0xf0, 0x13, 0xac, 0x3c, + 0x48, 0xde, 0x0f, 0xdd, 0xc3, 0xcd, 0xa2, 0xc0, 0x5d, 0x67, 0x33, 0x2a, + 0xf8, 0x93, 0x25, 0x95, 0x76, 0x5f, 0x0c, 0xfc, 0x88, 0x4d, 0x9d, 0x99, + 0x69, 0x66, 0x89, 0xfe, 0x09, 0xb5, 0x78, 0xae, 0xa0, 0x22, 0x1e, 0x41, + 0xdc, 0xad, 0x8a, 0xef, 0x89, 0x74, 0x96, 0xc5, 0x83, 0x08, 0xe4, 0xec, + 0xb0, 0xaf, 0xd9, 0xdb, 0x83, 0x42, 0xea, 0x96, 0xf4, 0x3b, 0xa2, 0x9a, + 0x73, 0x04, 0x99, 0x59, 0xfe, 0x21, 0x35, 0xdc, 0xb3, 0xe8, 0x81, 0x5a, + 0xe5, 0x4e, 0x51, 0x9c, 0xc6, 0x5d, 0x81, 0xae, 0x00, 0x0a, 0xee, 0xbf, + 0xa2, 0x4d, 0xdf, 0xec, 0xcd, 0x86, 0x62, 0x9b, 0xd3, 0xee, 0x58, 0x8e, + 0x69, 0x0c, 0x7f, 0x83, 0xfc, 0xf1, 0x19, 0xde, 0x05, 0x81, 0x3d, 0xe0, + 0x46, 0x95, 0xaf, 0x39, 0x13, 0xbf, 0xac, 0xa0, 0x71, 0x00, 0xeb, 0xb8, + 0x92, 0xe7, 0x92, 0x86, 0x29, 0xf8, 0x78, 0x02, 0x19, 0xc5, 0x72, 0xe1, + 0x8f, 0xce, 0x62, 0x2a, 0x7b, 0x0f, 0xef, 0xa1, 0x79, 0xbf, 0xf9, 0x51, + 0x01, 0xc4, 0x3d, 0xbf, 0xbd, 0xcd, 0xf3, 0x62, 0x97, 0xf9, 0x68, 0x9c, + 0xb8, 0x60, 0x6d, 0xb3, 0x75, 0xb3, 0x41, 0xff, 0xb2, 0x94, 0x67, 0x6f, + 0x74, 0xbb, 0xaa, 0x3a, 0x41, 0x56, 0x0a, 0x16, 0x8c, 0xd9, 0xc5, 0xa6, + 0x22, 0x0d, 0xb5, 0x1e, 0x31, 0xf2, 0x87, 0xe3, 0xed, 0x3d, 0x5a, 0x38, + 0x59, 0x4f, 0x35, 0x99, 0xfe, 0x60, 0x94, 0xe2, 0x40, 0x90, 0xe3, 0x08, + 0x16, 0x8a, 0x19, 0x65, 0x3e, 0x1e, 0x16, 0x30, 0xe5, 0xba, 0x5e, 0x84, + 0xef, 0x76, 0x4a, 0x0e, 0x4e, 0x44, 0xd9, 0x3b, 0x6f, 0xb1, 0xe5, 0x89, + 0xf0, 0x7b, 0x09, 0x02, 0x8e, 0x61, 0xe9, 0xfd, 0xcb, 0x8f, 0x24, 0x90, + 0xde, 0x3c, 0x0d, 0xad, 0x1c, 0xa5, 0x28, 0xcf, 0x45, 0xf0, 0x12, 0x3e, + 0x64, 0x7f, 0x55, 0xa4, 0x21, 0x54, 0xff, 0x15, 0x07, 0xfe, 0xd0, 0x98, + 0x24, 0x0f, 0xf6, 0xe2, 0xa4, 0x51, 0x34, 0xdf, 0x14, 0x8e, 0x09, 0xaf, + 0x51, 0xe9, 0xa0, 0xb5, 0x59, 0x98, 0x07, 0x93, 0xfe, 0xb9, 0x57, 0x30, + 0x33, 0x68, 0xc7, 0xe9, 0x38, 0x61, 0xe1, 0x22, 0x3c, 0x1b, 0xac, 0x68, + 0x75, 0x51, 0x34, 0xcc, 0x74, 0x35, 0x1b, 0xc0, 0x2c, 0xaa, 0xf1, 0xd5, + 0xfe, 0x2e, 0x5f, 0x88, 0x59, 0x28, 0x5a, 0xfe, 0x70, 0x22, 0xb4, 0xfc, + 0x73, 0xe2, 0x62, 0x07, 0xd2, 0x8f, 0xbc, 0x5d, 0x1f, 0x61, 0xbb, 0xf2, + 0x2f, 0xc2, 0x21, 0x09, 0x58, 0x60, 0x22, 0x72, 0x92, 0xca, 0x04, 0xf8, + 0x56, 0x4e, 0x76, 0xec, 0xc4, 0x03, 0x33, 0xe1, 0x4b, 0xaa, 0x2e, 0x71, + 0x17, 0x2d, 0x71, 0xd3, 0x29, 0xf2, 0x78, 0x0f, 0xe7, 0xdf, 0x9f, 0xb1, + 0x75, 0x96, 0x17, 0x5f, 0xc0, 0x77, 0x3d, 0x6d, 0x50, 0xd1, 0x50, 0x40, + 0x1a, 0x17, 0xae, 0x93, 0xdd, 0x0f, 0x93, 0xa9, 0xb0, 0x9b, 0xc2, 0xab, + 0x7d, 0xa2, 0x8a, 0xf0, 0xe9, 0xc2, 0x5d, 0xc8, 0x33, 0xe5, 0xd9, 0x51, + 0xfc, 0x51, 0x5f, 0x26, 0x10, 0x15, 0x89, 0x12, 0x35, 0x42, 0xb3, 0x7a, + 0x10, 0x98, 0x69, 0xfa, 0xa2, 0xa0, 0x86, 0xa7, 0x25, 0x7d, 0x51, 0xcf, + 0xc3, 0xb3, 0x95, 0xfc, 0x96, 0x9f, 0x60, 0x42, 0x8c, 0x6c, 0x97, 0x18, + 0x0c, 0xfb, 0x49, 0xb7, 0x61, 0x25, 0xb8, 0xb1, 0xc9, 0x87, 0xf3, 0xf0, + 0xc5, 0xa1, 0x3d, 0x90, 0x24, 0xe5, 0xca, 0xe1, 0x0f, 0x6a, 0x76, 0x74, + 0xd5, 0x6f, 0x0e, 0x07, 0xdf, 0x0c, 0xeb, 0x0a, 0xb9, 0xfe, 0xd2, 0xa0, + 0xf5, 0x6d, 0x1d, 0xe1, 0xaa, 0x3a, 0xb8, 0x39, 0x30, 0x52, 0x8d, 0xe0, + 0x4e, 0x4e, 0xa0, 0x0e, 0x85, 0x1a, 0xdd, 0x0f, 0x14, 0xff, 0x8a, 0x6c, + 0x7b, 0x9c, 0xf2, 0x58, 0x6a, 0x62, 0x15, 0x39, 0x04, 0xf8, 0x39, 0xf4, + 0xe2, 0xad, 0x12, 0xd7, 0x28, 0x27, 0xc5, 0x49, 0xdf, 0x18, 0x59, 0xc0, + 0xa7, 0xcc, 0xe5, 0x56, 0x61, 0x99, 0xce, 0x31, 0x05, 0x0b, 0x06, 0x3a, + 0xb0, 0x92, 0x19, 0x22, 0x67, 0x77, 0xba, 0x34, 0x97, 0xdf, 0x5f, 0x9b, + 0x6e, 0xac, 0x44, 0xb6, 0xd1, 0x57, 0xac, 0xa1, 0x2b, 0x5e, 0xf1, 0x27, + 0x58, 0xba, 0xfe, 0x05, 0xd7, 0x41, 0xa6, 0x88, 0xc6, 0xbc, 0x93, 0xff, + 0x2a, 0x62, 0x0b, 0x35, 0x1b, 0xb9, 0xd9, 0x2d, 0x02, 0xc2, 0x41, 0xdc, + 0x8c, 0x7b, 0x9e, 0xda, 0xfd, 0xb3, 0x36, 0x1f, 0xc4, 0x26, 0xcb, 0x75, + 0xec, 0xcd, 0xc5, 0xe7, 0xb3, 0x1e, 0x2f, 0x30, 0x17, 0x22, 0x95, 0x7b, + 0xdd, 0xfe, 0xa9, 0xe7, 0x63, 0x3b, 0xb0, 0xcc, 0x4d, 0x8a, 0x46, 0x70, + 0x77, 0xbf, 0xe6, 0x2e, 0x3f, 0xd6, 0x1f, 0xe9, 0x86, 0xf2, 0x63, 0x09, + 0x0b, 0xa0, 0xc4, 0xfa, 0x08, 0x65, 0x99, 0x5d, 0x79, 0x4c, 0x11, 0xe6, + 0x3f, 0xd7, 0x94, 0xc3, 0x41, 0x0c, 0x47, 0xc0, 0x64, 0xe2, 0xdc, 0x88, + 0x20, 0x50, 0x25, 0xc9, 0x4b, 0xae, 0x06, 0x24, 0x4c, 0xaf, 0x33, 0x26, + 0x62, 0xe2, 0xf9, 0xaf, 0xcf, 0x48, 0xe1, 0x16, 0xaa, 0x64, 0x01, 0x70, + 0xd8, 0xc3, 0xef, 0x01, 0x6a, 0x64, 0xf0, 0xf5, 0x4a, 0xd0, 0xdd, 0x21, + 0xd5, 0x57, 0x28, 0x65, 0x3b, 0x04, 0x3e, 0xc9, 0x94, 0x59, 0x42, 0xac, + 0x9b, 0xdf, 0x4e, 0x33, 0xae, 0xd1, 0xda, 0xfc, 0xf3, 0xe6, 0xa1, 0x4a, + 0xb4, 0xa4, 0x24, 0x57, 0x5a, 0x34, 0x6f, 0x6f, 0x94, 0xe9, 0x88, 0x42, + 0xc5, 0x0d, 0xdf, 0x42, 0x44, 0x08, 0x7b, 0x99, 0x69, 0x59, 0xb6, 0x54, + 0x67, 0x7d, 0x83, 0xb8, 0xea, 0x53, 0x9b, 0x1c, 0xb2, 0xd7, 0x44, 0x20, + 0x30, 0xb3, 0x72, 0x10, 0x86, 0x87, 0x82, 0x58, 0xb4, 0xf4, 0x08, 0xd1, + 0xd9, 0x8a, 0x84, 0xcc, 0xb0, 0x3a, 0xf1, 0xde, 0x24, 0x16, 0x18, 0x7e, + 0xd0, 0x92, 0xb8, 0x72, 0x15, 0x08, 0x0c, 0xac, 0xa1, 0x96, 0x24, 0xcf, + 0x47, 0x31, 0x3b, 0xc7, 0x28, 0x11, 0xf0, 0x42, 0xe6, 0x40, 0x63, 0xa9, + 0xeb, 0xff, 0x80, 0x58, 0x0f, 0xee, 0x4e, 0xc5, 0xc0, 0xe9, 0xb5, 0xc2, + 0x18, 0x71, 0x97, 0xfe, 0x1a, 0x53, 0x93, 0xe4, 0x77, 0x92, 0x25, 0xa4, + 0x27, 0x03, 0xf6, 0x64, 0xf1, 0x63, 0x37, 0x7b, 0xb7, 0x3a, 0xe2, 0xcb, + 0x0c, 0x83, 0x0b, 0x52, 0x3f, 0xee, 0x41, 0x9a, 0x55, 0x8e, 0x85, 0x4a, + 0x23, 0x64, 0xea, 0x68, 0xe8, 0x5e, 0xd7, 0xf3, 0x9e, 0xbc, 0x6d, 0x78, + 0xba, 0xd2, 0xe5, 0xe8, 0x35, 0xfa, 0x74, 0x0f, 0x33, 0x2a, 0x0e, 0xcc, + 0xb2, 0x01, 0xaf, 0x53, 0x04, 0x70, 0x8a, 0xdd, 0x9e, 0x95, 0xcb, 0x3a, + 0x81, 0x25, 0x2f, 0x77, 0xb4, 0x31, 0xc7, 0x0b, 0x14, 0xc4, 0xd6, 0x20, + 0xa7, 0x80, 0xb1, 0xd5, 0x3d, 0x90, 0x04, 0xaf, 0x59, 0x20, 0xac, 0x6c, + 0x5e, 0xfc, 0xda, 0x7f, 0x9e, 0x70, 0x08, 0xe2, 0x5c, 0x02, 0x9c, 0x95, + 0x7d, 0xf9, 0xab, 0x2c, 0x15, 0x90, 0xc6, 0xab, 0x49, 0x21, 0x74, 0xcb, + 0x93, 0xb0, 0x44, 0x03, 0xfa, 0xc5, 0x35, 0x54, 0xb3, 0x4e, 0x10, 0x25, + 0x25, 0x94, 0x7d, 0x45, 0x74, 0xb5, 0x58, 0x85, 0xac, 0xb2, 0xc2, 0xd7, + 0xb5, 0xbe, 0xf0, 0xc8, 0x53, 0xdc, 0x62, 0xf8, 0x9b, 0x88, 0x98, 0xa7, + 0xda, 0x5a, 0x83, 0x22, 0xe4, 0x26, 0x83, 0x45, 0x41, 0x6f, 0x42, 0x61, + 0xcb, 0xc0, 0x89, 0x56, 0x2a, 0xef, 0x1f, 0xbb, 0xb2, 0xc9, 0xa1, 0xc8, + 0x16, 0x2d, 0x43, 0xc1, 0x13, 0x29, 0x76, 0xfa, 0x64, 0x4e, 0xe0, 0x66, + 0x5a, 0x9d, 0x35, 0x8f, 0x42, 0xd4, 0xe6, 0xea, 0x1d, 0xaf, 0x63, 0x73, + 0xb3, 0xff, 0x62, 0xd3, 0xdb, 0x60, 0x01, 0x7b, 0xf9, 0x03, 0xf2, 0x89, + 0x29, 0xe8, 0x48, 0xac, 0x2a, 0x71, 0x71, 0xdc, 0x80, 0xb1, 0x96, 0x5e, + 0xdd, 0x23, 0xea, 0xac, 0x44, 0xbc, 0xf3, 0x70, 0xf4, 0x40, 0x92, 0x94, + 0x8a, 0x89, 0x27, 0x02, 0xe7, 0x7f, 0x59, 0x27, 0x12, 0x11, 0xf1, 0x14, + 0x2d, 0x1c, 0x35, 0x89, 0xd6, 0xca, 0xa7, 0xe5, 0xba, 0x3c, 0x2b, 0x91, + 0x50, 0x2f, 0x87, 0x1f, 0x89, 0x12, 0x3e, 0x7e, 0x69, 0x47, 0x1e, 0x86, + 0xaf, 0x4d, 0xe6, 0x27, 0x04, 0x11, 0x61, 0x15, 0xdd, 0x0f, 0xe0, 0xe6, + 0x3f, 0x9f, 0x83, 0x13, 0x52, 0x41, 0x72, 0xba, 0x9e, 0xe2, 0x2e, 0x9c, + 0x98, 0xf5, 0x16, 0x17, 0x2a, 0xa7, 0xe5, 0x74, 0x26, 0x93, 0x88, 0xda, + 0x7f, 0x9b, 0x2e, 0x38, 0x4c, 0x73, 0x86, 0x98, 0xc6, 0xef, 0xb6, 0x34, + 0x02, 0x8c, 0x70, 0xbe, 0x81, 0x02, 0x3a, 0xa0, 0xb7, 0x33, 0x40, 0x6a, + 0x7b, 0x2c, 0xe6, 0xdc, 0x00, 0xb6, 0x86, 0x83, 0xbd, 0x8b, 0x75, 0xff, + 0xaa, 0xa0, 0x4a, 0x14, 0xf2, 0xed, 0xd0, 0xa3, 0xe3, 0x46, 0x1f, 0x63, + 0x04, 0xe6, 0xd5, 0x35, 0x14, 0xb2, 0xf4, 0x49, 0x06, 0x92, 0x94, 0x01, + 0x29, 0x32, 0x35, 0x43, 0x98, 0xdd, 0xc9, 0x58, 0x16, 0x19, 0x38, 0x7f, + 0xf1, 0x03, 0x0e, 0x9b, 0xfc, 0xc9, 0xaf, 0x4a, 0xee, 0x58, 0x66, 0xd0, + 0x8b, 0x34, 0x49, 0xfe, 0x4b, 0x08, 0xf2, 0xbe, 0xdb, 0x6e, 0x9c, 0xe8, + 0x1d, 0x99, 0xdd, 0xfc, 0x3b, 0x29, 0x95, 0x90, 0x58, 0xd7, 0x6f, 0x1a, + 0x07, 0x2d, 0x18, 0xee, 0x05, 0x15, 0x23, 0x3b, 0xce, 0x1f, 0xdf, 0x97, + 0x1c, 0x95, 0x29, 0xf2, 0x07, 0x7c, 0x5c, 0x3a, 0x3e, 0x1b, 0x4c, 0x0e, + 0xde, 0x8e, 0x59, 0x72, 0x82, 0x00, 0xd7, 0x26, 0x4b, 0xb7, 0x2f, 0xb0, + 0x8e, 0x19, 0x53, 0xdf, 0xf6, 0x58, 0xbe, 0x0d, 0xd1, 0x0c, 0x59, 0x2c, + 0xf0, 0xe0, 0xb7, 0xdf, 0x82, 0x90, 0x11, 0x26, 0x02, 0x08, 0x3e, 0xb4, + 0x50, 0x48, 0x75, 0x5e, 0x54, 0x29, 0xff, 0x2b, 0x70, 0xa4, 0x16, 0x10, + 0xcc, 0x3e, 0x40, 0x3c, 0xf0, 0xda, 0x54, 0xe6, 0x36, 0x0c, 0x5a, 0xde, + 0x12, 0x82, 0x4f, 0x1d, 0xa8, 0x58, 0x1c, 0xc3, 0x99, 0x6f, 0x1b, 0x53, + 0x91, 0x3e, 0xb8, 0xbf, 0x3b, 0x37, 0x66, 0xa7, 0xff, 0xe6, 0x46, 0x60, + 0x72, 0xc3, 0x6e, 0x56, 0xc0, 0x36, 0x66, 0x2e, 0x6d, 0xf8, 0x33, 0xfa, + 0x23, 0xfa, 0xff, 0x55, 0xa2, 0x4b, 0xb6, 0xc1, 0x2b, 0x8d, 0xc1, 0x9f, + 0x3c, 0xf2, 0xb2, 0x66, 0xd6, 0x66, 0x0f, 0x53, 0x75, 0x5f, 0x69, 0x7f, + 0xc9, 0x33, 0xce, 0x3b, 0x86, 0x43, 0x0f, 0x92, 0xdc, 0x2d, 0xb6, 0xcc, + 0x3a, 0x5d, 0xbb, 0xe8, 0xc5, 0x0c, 0x41, 0x44, 0x75, 0xb3, 0xdd, 0xf1, + 0x34, 0x8b, 0xc1, 0x37, 0x1f, 0xfc, 0x18, 0x5a, 0x2d, 0x78, 0x13, 0x13, + 0xff, 0x75, 0x70, 0x18, 0x86, 0x5a, 0x60, 0xc3, 0xd2, 0x9d, 0xeb, 0xe7, + 0x59, 0xd8, 0x3b, 0xc9, 0x5d, 0xe7, 0x32, 0xbb, 0x43, 0x59, 0xc8, 0x99, + 0xf4, 0xa3, 0x07, 0x8c, 0x0e, 0xa1, 0x99, 0x57, 0x6a, 0x5c, 0x7f, 0xcd, + 0xa6, 0x63, 0x38, 0x7d, 0xcf, 0xb8, 0x27, 0xf1, 0xc5, 0x3d, 0x38, 0xf9, + 0xc5, 0x6b, 0xba, 0x18, 0xb5, 0xb2, 0x08, 0x70, 0x92, 0xe6, 0xe1, 0xd9, + 0x1b, 0xa5, 0xec, 0x83, 0xb2, 0x12, 0x5f, 0x73, 0x31, 0x08, 0xf2, 0x70, + 0x8f, 0xb2, 0x40, 0xd6, 0xef, 0x19, 0x8f, 0x78, 0xa2, 0x05, 0xaa, 0x48, + 0xad, 0x84, 0xb6, 0x0a, 0x19, 0x2e, 0x6f, 0x22, 0x9a, 0x3d, 0x8a, 0x80, + 0x49, 0xfe, 0xff, 0xa0, 0xec, 0x99, 0xdb, 0x89, 0x38, 0x60, 0xf5, 0x56, + 0x4d, 0x03, 0x20, 0x0c, 0x96, 0x04, 0xfc, 0x63, 0xbd, 0xa4, 0x59, 0xab, + 0x1e, 0x43, 0x84, 0x04, 0xd8, 0x42, 0xe1, 0xc8, 0x03, 0xbd, 0x0e, 0x52, + 0x36, 0xa1, 0x00, 0xfe, 0xc0, 0x42, 0xf9, 0x47, 0x1f, 0x98, 0xde, 0x39, + 0x1e, 0xd0, 0x85, 0xdb, 0x70, 0x8e, 0x06, 0x39, 0xb0, 0x09, 0x2a, 0xb9, + 0xb9, 0xa8, 0x50, 0x28, 0x1a, 0x26, 0x05, 0x7f, 0xdc, 0x56, 0xcf, 0x63, + 0xf6, 0x0b, 0xfb, 0x46, 0x0f, 0x6d, 0x00, 0xec, 0x22, 0xa8, 0xe2, 0x21, + 0x5e, 0xfd, 0x4c, 0xa2, 0xd7, 0x35, 0x37, 0xd5, 0xa7, 0xad, 0xf9, 0xf3, + 0x03, 0xdf, 0xf1, 0x35, 0x63, 0x25, 0xb8, 0xba, 0x23, 0xb7, 0xd2, 0xc3, + 0xaa, 0x4d, 0x59, 0x23, 0xc8, 0xf0, 0x64, 0x15, 0x96, 0xf5, 0xac, 0x7b, + 0x7e, 0x95, 0x2d, 0xf3, 0xfe, 0x9b, 0xe9, 0x5c, 0x82, 0x61, 0xe9, 0xbc, + 0x4f, 0x80, 0x07, 0x07, 0xb5, 0x85, 0xf8, 0x65, 0xac, 0xdf, 0xf5, 0x1b, + 0x8c, 0x49, 0x7d, 0x96, 0xf6, 0xd5, 0xba, 0x6e, 0x3a, 0x3c, 0x18, 0x6c, + 0x18, 0xa1, 0xaa, 0xfd, 0x9f, 0x56, 0x01, 0x4a, 0x96, 0xe3, 0xf7, 0x73, + 0x35, 0x39, 0x62, 0xcb, 0x74, 0x8c, 0x4f, 0x4b, 0x59, 0xfc, 0x42, 0x1a, + 0x7f, 0xe2, 0x12, 0x44, 0x26, 0xbb, 0x4e, 0xd5, 0xef, 0xda, 0x1d, 0xbe, + 0xe5, 0x57, 0x94, 0x01, 0x49, 0xd7, 0xe7, 0xd6, 0x37, 0xf2, 0x01, 0xaa, + 0xeb, 0x45, 0x52, 0x93, 0xec, 0x0f, 0xd2, 0xa1, 0x10, 0xa1, 0x63, 0x06, + 0xdc, 0xb6, 0xf7, 0xb9, 0x27, 0x5f, 0x34, 0x66, 0xba, 0xfc, 0x49, 0x66, + 0x75, 0x7c, 0xc1, 0xcf, 0xdc, 0xf2, 0x28, 0x5c, 0x62, 0x7e, 0x93, 0x99, + 0xbf, 0x1c, 0x27, 0x50, 0x71, 0x96, 0x9b, 0xbc, 0xd6, 0xea, 0x12, 0x18, + 0x26, 0x70, 0x76, 0x89, 0xa3, 0x05, 0x2b, 0x2f, 0x40, 0x59, 0x5c, 0x64, + 0x6c, 0xad, 0xec, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x02, 0x0a, 0x11, 0x1a, 0x21, 0x2b}; diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/mldsa/mldsa.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/mldsa/mldsa.cc.inc index 6598f11c..c8718efd 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/mldsa/mldsa.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/mldsa/mldsa.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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 @@ -24,12 +24,30 @@ #include #include "../../internal.h" +#include "../../mem_internal.h" #include "../bcm_interface.h" #include "../keccak/internal.h" + +using namespace bssl; + +#if defined(BORINGSSL_FIPS) + +DEFINE_STATIC_ONCE(g_mldsa_keygen_self_test_once) +DEFINE_STATIC_ONCE(g_mldsa_sign_self_test_once) +DEFINE_STATIC_ONCE(g_mldsa_verify_self_test_once) + +#endif + 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; constexpr int kRhoBytes = 32; constexpr int kSigmaBytes = 64; @@ -44,9 +62,9 @@ constexpr uint32_t kPrime = 8380417; constexpr uint32_t kPrimeNegInverse = 4236238847; constexpr int kDroppedBits = 13; constexpr uint32_t kHalfPrime = (kPrime - 1) / 2; -constexpr uint32_t kGamma2 = (kPrime - 1) / 32; -// 256^-1 mod kPrime, in Montgomery form. -constexpr uint32_t kInverseDegreeMontgomery = 41978; +// 256^-1 ⋅ R² mod kPrime. This is not 256^-1 in Montgomery form, but 256^-1 +// doubly-converted to Montgomery form. +constexpr uint32_t kInverseDegreeDoubleMontgomery = 41978; // Constants that vary depending on ML-DSA size. // @@ -56,18 +74,22 @@ constexpr uint32_t kInverseDegreeMontgomery = 41978; template constexpr size_t public_key_bytes() { if constexpr (K == 6) { - return BCM_MLDSA65_PUBLIC_KEY_BYTES; + return MLDSA65_PUBLIC_KEY_BYTES; } else if constexpr (K == 8) { - return BCM_MLDSA87_PUBLIC_KEY_BYTES; + return MLDSA87_PUBLIC_KEY_BYTES; + } else if constexpr (K == 4) { + return MLDSA44_PUBLIC_KEY_BYTES; } } template constexpr size_t signature_bytes() { if constexpr (K == 6) { - return BCM_MLDSA65_SIGNATURE_BYTES; + return MLDSA65_SIGNATURE_BYTES; } else if constexpr (K == 8) { - return BCM_MLDSA87_SIGNATURE_BYTES; + return MLDSA87_SIGNATURE_BYTES; + } else if constexpr (K == 4) { + return MLDSA44_SIGNATURE_BYTES; } } @@ -77,6 +99,8 @@ constexpr int tau() { return 49; } else if constexpr (K == 8) { return 60; + } else if constexpr (K == 4) { + return 39; } } @@ -86,22 +110,71 @@ constexpr int lambda_bytes() { return 192 / 8; } else if constexpr (K == 8) { return 256 / 8; + } else if constexpr (K == 4) { + return 128 / 8; + } +} + +template +constexpr int gamma1_bits() { + if constexpr (K == 6 || K == 8) { + return 19; + } else if constexpr (K == 4) { + return 17; } } template constexpr int gamma1() { + return 1 << gamma1_bits(); +} + +template +constexpr int scalar_le_gamma1_bytes() { + return ((gamma1_bits() + 1) * kDegree) / 8; +} + +template +constexpr uint32_t w1_coeffs_bits() { if constexpr (K == 6 || K == 8) { - return 1 << 19; + return 4; + } else if constexpr (K == 4) { + return 6; } } +template +constexpr uint32_t w1_scalar_bytes() { + return (w1_coeffs_bits() * kDegree) / 8; +} + +template +constexpr uint32_t w1_bytes() { + return w1_scalar_bytes() * K; +} + +template +constexpr uint32_t prime_minus_one_over_gamma2() { + if constexpr (K == 6 || K == 8) { + return 32; + } else if constexpr (K == 4) { + return 88; + } +} + +template +constexpr uint32_t gamma2() { + return (kPrime - 1) / prime_minus_one_over_gamma2(); +} + template constexpr int beta() { if constexpr (K == 6) { return 196; } else if constexpr (K == 8) { return 120; + } else if constexpr (K == 4) { + return 78; } } @@ -111,6 +184,8 @@ constexpr int omega() { return 55; } else if constexpr (K == 8) { return 75; + } else if constexpr (K == 4) { + return 80; } } @@ -118,7 +193,7 @@ template constexpr int eta() { if constexpr (K == 6) { return 4; - } else if constexpr (K == 8) { + } else if constexpr (K == 8 || K == 4) { return 2; } } @@ -127,16 +202,16 @@ template constexpr int plus_minus_eta_bitlen() { if constexpr (K == 6) { return 4; - } else if constexpr (K == 8) { + } else if constexpr (K == 8 || K == 4) { return 3; } } // Fundamental types. -typedef struct scalar { +struct scalar { uint32_t c[kDegree]; -} scalar; +}; template struct vector { @@ -216,64 +291,110 @@ static const uint32_t kNTTRootsMontgomery[256] = { 7826001, 3919660, 8332111, 7018208, 3937738, 1400424, 7534263, 1976782}; // Reduces x mod kPrime in constant time, where 0 <= x < 2*kPrime. -uint32_t reduce_once(uint32_t x) { +inline uint32_t reduce_once(uint32_t x) { declassify_assert(x < 2 * kPrime); // return x < kPrime ? x : x - kPrime; - return constant_time_select_int(constant_time_lt_w(x, kPrime), x, x - kPrime); + const uint32_t subtracted = x - kPrime; + uint32_t mask = 0u - (subtracted >> 31); + // Although this is a constant-time select, we omit a value barrier here. + // Value barriers impede auto-vectorization (likely because it forces the + // value to transit through a general-purpose register). This is a difference + // of 1.4x to 1.5x in signing performance. + // + // We usually add value barriers to selects because Clang turns consecutive + // 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); } -// Returns the absolute value in constant time. -uint32_t abs_signed(uint32_t x) { - // return is_positive(x) ? x : -x; - // Note: MSVC doesn't like applying the unary minus operator to unsigned types - // (warning C4146), so we write the negation as a bitwise not plus one - // (assuming two's complement representation). - return constant_time_select_int(constant_time_lt_w(x, 0x80000000), x, 0u - x); +// reduce_from_u32 returns `x mod kPrime`. `x` can be any `uint32_t`. +inline uint32_t reduce_from_u32(uint32_t x) { + // kPrime is 2^23 - 2^13 + 1. We first split `x` into the upper 9 bits and the + // lower 23 bits: + uint32_t hi = x >> 23, lo = x & ((uint32_t{1} << 23) - 1); + // 2^23 = 2^13 - 1 mod kPrime + // x = hi * 2^23 + lo + // = hi * 2^13 - hi + lo mod kPrime + // + // This value does not overflow and is below 2 * kPrime. We can `reduce_once`. + static constexpr uint32_t kMaxHi = UINT32_MAX >> 23; + static constexpr uint32_t kMaxLo = (uint32_t{1} << 23) - 1; + static_assert((kMaxHi << 13) - kMaxHi + kMaxLo < 2 * kPrime); + return reduce_once((hi << 13) - hi + lo); +} + +// Returns the absolute value in constant time, interpreting the high bit as a +// sign bit. +inline uint32_t abs_signed(uint32_t x) { + // return is_negative(x) ? -x : x; + uint32_t mask = 0u - (x >> 31); + return constant_time_select_32(mask, 0u - x, x); } // Returns the absolute value modulo kPrime. -uint32_t abs_mod_prime(uint32_t x) { +inline uint32_t abs_mod_prime(uint32_t x) { declassify_assert(x < kPrime); - // return x > kHalfPrime ? kPrime - x : x; - return constant_time_select_int(constant_time_lt_w(kHalfPrime, x), kPrime - x, - x); + // return x <= kHalfPrime ? x : kPrime - x; + uint32_t mask = x - kHalfPrime - 1; + mask = 0u - (mask >> 31); + return constant_time_select_32(mask, x, kPrime - x); } -// Returns the maximum of two values in constant time. -uint32_t maximum(uint32_t x, uint32_t y) { +// Returns the maximum of two values in constant time. Each value must be less +// than kPrime. +inline uint32_t maximum_reduced(uint32_t x, uint32_t y) { + declassify_assert(x < kPrime); + declassify_assert(y < kPrime); // return x < y ? y : x; - return constant_time_select_int(constant_time_lt_w(x, y), y, x); + uint32_t mask = x - y; + mask = 0u - (mask >> 31); + return constant_time_select_32(mask, y, x); } -uint32_t mod_sub(uint32_t a, uint32_t b) { +inline uint32_t mod_sub(uint32_t a, uint32_t b) { declassify_assert(a < kPrime); declassify_assert(b < kPrime); - return reduce_once(kPrime + a - b); + uint32_t r = a - 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); } -void scalar_add(scalar *out, const scalar *lhs, const scalar *rhs) { +inline void scalar_add(scalar *out, const scalar *lhs, const scalar *rhs) { for (int i = 0; i < kDegree; i++) { out->c[i] = reduce_once(lhs->c[i] + rhs->c[i]); } } -void scalar_sub(scalar *out, const scalar *lhs, const scalar *rhs) { +inline void scalar_sub(scalar *out, const scalar *lhs, const scalar *rhs) { for (int i = 0; i < kDegree; i++) { out->c[i] = mod_sub(lhs->c[i], rhs->c[i]); } } -uint32_t reduce_montgomery(uint64_t x) { +// reduce_montgomery_partial returns a number equivalent to x * R^-1 mod kPrime. +// The output is less than 2 * kPrime. `x` must be at most kPrime * 2^32. +inline uint32_t reduce_montgomery_partial(uint64_t x) { declassify_assert(x <= ((uint64_t)kPrime << 32)); uint64_t a = (uint32_t)x * kPrimeNegInverse; uint64_t b = x + a * kPrime; declassify_assert((b & 0xffffffff) == 0); - uint32_t c = b >> 32; - return reduce_once(c); + return b >> 32; } -// Multiply two scalars in the number theoretically transformed state. -void scalar_mult(scalar *out, const scalar *lhs, const scalar *rhs) { +// reduce_montgomery returns x * R^-1 mod kPrime, fully reduced. `x` must be at +// most kPrime * 2^32. +inline uint32_t reduce_montgomery(uint64_t x) { + return reduce_once(reduce_montgomery_partial(x)); +} + +// Montgomery-multiply two scalars in the number theoretically transformed +// state. Each term gains an extra R^-1 term, which is expected to be canceled +// by `scalar_inverse_ntt_montgomery`. +inline void scalar_mult_montgomery(scalar *out, const scalar *lhs, + const scalar *rhs) { for (int i = 0; i < kDegree; i++) { out->c[i] = reduce_montgomery((uint64_t)lhs->c[i] * (uint64_t)rhs->c[i]); } @@ -282,115 +403,155 @@ void scalar_mult(scalar *out, const scalar *lhs, const scalar *rhs) { // In place number theoretic transform of a given scalar. // // FIPS 204, Algorithm 41 (`NTT`). -static void scalar_ntt(scalar *s) { - // Step: 1, 2, 4, 8, ..., 128 - // Offset: 128, 64, 32, 16, ..., 1 - int offset = kDegree; - for (int step = 1; step < kDegree; step <<= 1) { - offset >>= 1; - int k = 0; - for (int i = 0; i < step; i++) { - assert(k == 2 * offset * i); - const uint32_t step_root = kNTTRootsMontgomery[step + i]; - for (int j = k; j < k + offset; j++) { - uint32_t even = s->c[j]; - // |reduce_montgomery| works on values up to kPrime*R and R > 2*kPrime. - // |step_root| < kPrime because it's static data. |s->c[...]| is < - // kPrime by the invariants of that struct. - uint32_t odd = - reduce_montgomery((uint64_t)step_root * (uint64_t)s->c[j + offset]); - s->c[j] = reduce_once(odd + even); - s->c[j + offset] = mod_sub(even, odd); - } - k += 2 * offset; - } +inline void scalar_ntt(scalar *s) { + // Manually unrolled loop to maximize vectorization. + // + // Intermediate values of `s` are not fully reduced. `ITER` writes to every + // element of `s` exactly once. Each write adds less than 2*kPrime to some + // value from the previous iteration. After eight iterations, each element + // will be less than 17*kPrime. This fits in `uint32_t`, so we never overflow. +#define ITER(step, offset) \ + { \ + int k = 0; \ + for (int i = 0; i < step; i++) { \ + const uint32_t step_root = kNTTRootsMontgomery[step + i]; \ + for (int j = k; j < k + offset; j++) { \ + uint32_t even = s->c[j]; \ + /* `reduce_montgomery_partial` works on values up to kPrime*R. \ + * `step_root < kPrime` because it's static data. `s->c[...] < R` \ + * because it's 32-bit. */ \ + uint32_t odd = reduce_montgomery_partial(uint64_t{step_root} * \ + uint64_t{s->c[j + offset]}); \ + s->c[j] = even + odd; \ + s->c[j + offset] = even + 2 * kPrime - odd; \ + } \ + k += 2 * offset; \ + } \ + } + + ITER(1, 128) + ITER(2, 64) + ITER(4, 32) + ITER(8, 16) + ITER(16, 8) + ITER(32, 4) + ITER(64, 2) + ITER(128, 1) + static_assert(kDegree == 256); +#undef ITER + + // Now `s` is correct but the elements are not fully reduced. Reduce them. + for (int i = 0; i < kDegree; i++) { + s->c[i] = reduce_from_u32(s->c[i]); } } -// In place inverse number theoretic transform of a given scalar. +// In place inverse number theoretic transform of a given scalar, but with each +// term multiplied by an extra factor of R. This is function is intended to be +// used with products that have gone through `reduce_montgomery` one extra time, +// so the extra R^-1 term is canceled out. // // FIPS 204, Algorithm 42 (`NTT^-1`). -void scalar_inverse_ntt(scalar *s) { - // Step: 128, 64, 32, 16, ..., 1 - // Offset: 1, 2, 4, 8, ..., 128 - int step = kDegree; - for (int offset = 1; offset < kDegree; offset <<= 1) { - step >>= 1; - int k = 0; - for (int i = 0; i < step; i++) { - assert(k == 2 * offset * i); - const uint32_t step_root = - kPrime - kNTTRootsMontgomery[step + (step - 1 - i)]; - for (int j = k; j < k + offset; j++) { - uint32_t even = s->c[j]; - uint32_t odd = s->c[j + offset]; - s->c[j] = reduce_once(odd + even); - - // |reduce_montgomery| works on values up to kPrime*R and R > 2*kPrime. - // kPrime + even < 2*kPrime because |even| < kPrime, by the invariants - // of that structure. Thus kPrime + even - odd < 2*kPrime because odd >= - // 0, because it's unsigned and less than kPrime. Lastly step_root < - // kPrime, because |kNTTRootsMontgomery| is static data. - s->c[j + offset] = reduce_montgomery((uint64_t)step_root * - (uint64_t)(kPrime + even - odd)); - } - k += 2 * offset; - } +inline void scalar_inverse_ntt_montgomery(scalar *s) { + // Manually unrolled loop to maximize vectorization. + // + // Intermediate values of `s` are not fully reduced. `ITER` writes + // to every element of `s` exactly once. Each write either adds two values + // from the previous iteration, or is at most 2 * kPrime. After eight + // iterations, each element will be less than 2⁸ * kPrime = 256 * kPrime. + // This fits in `uint32_t`, so we never overflow. +#define ITER(step, offset) \ + { \ + int k = 0; \ + for (int i = 0; i < step; i++) { \ + const uint32_t step_root = \ + kPrime - kNTTRootsMontgomery[step + (step - 1 - i)]; \ + for (int j = k; j < k + offset; j++) { \ + uint32_t even = s->c[j]; \ + uint32_t odd = s->c[j + offset]; \ + s->c[j] = odd + even; \ + /* `reduce_montgomery_partial` works on values up to kPrime*R. \ + * `step_root < kPrime` because it's static data. The other term is \ + * less than R because it's 32-bit, and does not overflow because \ + * `odd` is at most 128 * kPrime per the above. */ \ + s->c[j + offset] = reduce_montgomery_partial( \ + uint64_t{step_root} * uint64_t{128 * kPrime + even - odd}); \ + } \ + k += 2 * offset; \ + } \ } + + ITER(128, 1) + ITER(64, 2) + ITER(32, 4) + ITER(16, 8) + ITER(8, 16) + ITER(4, 32) + ITER(2, 64) + ITER(1, 128) + static_assert(kDegree == 256); +#undef ITER + + // `kInverseDegreeDoubleMontgomery` has been double-converted to Montgomery + // form, so the result is an extra R term in the final result. This also fully + // reduces the partially-reduced values above. for (int i = 0; i < kDegree; i++) { - s->c[i] = reduce_montgomery((uint64_t)s->c[i] * - (uint64_t)kInverseDegreeMontgomery); + s->c[i] = reduce_montgomery(uint64_t{s->c[i]} * + uint64_t{kInverseDegreeDoubleMontgomery}); } } template -void vector_zero(vector *out) { +inline void vector_zero(vector *out) { OPENSSL_memset(out, 0, sizeof(*out)); } template -void vector_add(vector *out, const vector *lhs, const vector *rhs) { +inline void vector_add(vector *out, const vector *lhs, + const vector *rhs) { for (int i = 0; i < X; i++) { scalar_add(&out->v[i], &lhs->v[i], &rhs->v[i]); } } template -void vector_sub(vector *out, const vector *lhs, const vector *rhs) { +inline void vector_sub(vector *out, const vector *lhs, + const vector *rhs) { for (int i = 0; i < X; i++) { scalar_sub(&out->v[i], &lhs->v[i], &rhs->v[i]); } } template -void vector_mult_scalar(vector *out, const vector *lhs, - const scalar *rhs) { +inline void vector_mult_scalar_montgomery(vector *out, const vector *lhs, + const scalar *rhs) { for (int i = 0; i < X; i++) { - scalar_mult(&out->v[i], &lhs->v[i], rhs); + scalar_mult_montgomery(&out->v[i], &lhs->v[i], rhs); } } template -void vector_ntt(vector *a) { +inline void vector_ntt(vector *a) { for (int i = 0; i < X; i++) { scalar_ntt(&a->v[i]); } } template -void vector_inverse_ntt(vector *a) { +inline void vector_inverse_ntt_montgomery(vector *a) { for (int i = 0; i < X; i++) { - scalar_inverse_ntt(&a->v[i]); + scalar_inverse_ntt_montgomery(&a->v[i]); } } template -void matrix_mult(vector *out, const matrix *m, const vector *a) { +inline void matrix_mult_montgomery(vector *out, const matrix *m, + const vector *a) { vector_zero(out); for (int i = 0; i < K; i++) { for (int j = 0; j < L; j++) { scalar product; - scalar_mult(&product, &m->v[i][j], &a->v[j]); + scalar_mult_montgomery(&product, &m->v[i][j], &a->v[j]); scalar_add(&out->v[i], &out->v[i], &product); } } @@ -399,7 +560,7 @@ void matrix_mult(vector *out, const matrix *m, const vector *a) { /* Rounding & hints */ // FIPS 204, Algorithm 35 (`Power2Round`). -void power2_round(uint32_t *r1, uint32_t *r0, uint32_t r) { +inline void power2_round(uint32_t *r1, uint32_t *r0, uint32_t r) { *r1 = r >> kDroppedBits; *r0 = r - (*r1 << kDroppedBits); @@ -410,59 +571,71 @@ void power2_round(uint32_t *r1, uint32_t *r0, uint32_t r) { crypto_word_t mask = constant_time_lt_w((uint32_t)(1 << (kDroppedBits - 1)), *r0); // r0 = mask ? r0_adjusted : r0 - *r0 = constant_time_select_int(mask, r0_adjusted, *r0); + *r0 = constant_time_select_32(mask, r0_adjusted, *r0); // r1 = mask ? r1_adjusted : r1 - *r1 = constant_time_select_int(mask, r1_adjusted, *r1); + *r1 = constant_time_select_32(mask, r1_adjusted, *r1); } // Scale back previously rounded value. -void scale_power2_round(uint32_t *out, uint32_t r1) { - // Pre-condition: 0 <= r1 <= 2^10 - 1 +inline void scale_power2_round(uint32_t *out, uint32_t r1) { + // Pre-condition: 0 ≤ r1 ≤ 2^10 - 1 assert(r1 < (1u << 10)); *out = r1 << kDroppedBits; - // Post-condition: 0 <= out <= 2^23 - 2^13 = kPrime - 1 + // Post-condition: 0 ≤ out ≤ 2^23 - 2^13 = kPrime - 1 assert(*out < kPrime); } // FIPS 204, Algorithm 37 (`HighBits`). -uint32_t high_bits(uint32_t x) { +template +inline uint32_t high_bits(uint32_t x) { // Reference description (given 0 <= x < q): // // ``` - // int32_t r0 = x mod+- (2 * kGamma2); + // int32_t r0 = x mod+- (2 * gamma2); // if (x - r0 == q - 1) { // return 0; // } else { - // return (x - r0) / (2 * kGamma2); + // return (x - r0) / (2 * gamma2); // } // ``` // - // Below is the formula taken from the reference implementation. - // - // Here, kGamma2 == 2^18 - 2^8 - // This returns ((ceil(x / 2^7) * (2^10 + 1) + 2^21) / 2^22) mod 2^4 uint32_t r1 = (x + 127) >> 7; - r1 = (r1 * 1025 + (1 << 21)) >> 22; - r1 &= 15; + if constexpr (prime_minus_one_over_gamma2() == 32) { + // Below is the formula taken from the reference implementation. + // + // Here, Gamma2 == 2^18 - 2^8 + // This returns ((ceil(x / 2^7) ⋅ (2^10 + 1) + 2^21) / 2^22) mod 2^4 + r1 = (r1 * 1025 + (1 << 21)) >> 22; + r1 &= 15; + } else if constexpr (prime_minus_one_over_gamma2() == 88) { + // 1488/2^24 is close enough to 1/1488 so that r1 becomes x/(2 gamma2) + // rounded down. + 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; + } return r1; } // FIPS 204, Algorithm 36 (`Decompose`). -void decompose(uint32_t *r1, int32_t *r0, uint32_t r) { - *r1 = high_bits(r); +template +inline void decompose(uint32_t *r1, int32_t *r0, uint32_t r) { + *r1 = high_bits(r); *r0 = r; - *r0 -= *r1 * 2 * (int32_t)kGamma2; + *r0 -= *r1 * 2 * (int32_t)gamma2(); *r0 -= (((int32_t)kHalfPrime - *r0) >> 31) & (int32_t)kPrime; } // FIPS 204, Algorithm 38 (`LowBits`). -int32_t low_bits(uint32_t x) { +template +inline int32_t low_bits(uint32_t x) { uint32_t r1; int32_t r0; - decompose(&r1, &r0, x); + decompose(&r1, &r0, x); return r0; } @@ -474,110 +647,137 @@ int32_t low_bits(uint32_t x) { // // It then computes HighBits (algorithm 37) of z and z+r. But z+r is just w - // cs2, so this takes three arguments and saves an addition. -int32_t make_hint(uint32_t ct0, uint32_t cs2, uint32_t w) { +template +inline int32_t make_hint(uint32_t ct0, uint32_t cs2, uint32_t w) { uint32_t r_plus_z = mod_sub(w, cs2); uint32_t r = reduce_once(r_plus_z + ct0); - return high_bits(r) != high_bits(r_plus_z); + return high_bits(r) != high_bits(r_plus_z); } // FIPS 204, Algorithm 40 (`UseHint`). -uint32_t use_hint_vartime(uint32_t h, uint32_t r) { +template +inline uint32_t use_hint_vartime(uint32_t h, uint32_t r) { uint32_t r1; int32_t r0; - decompose(&r1, &r0, r); + decompose(&r1, &r0, r); if (h) { - if (r0 > 0) { - // m = 16, thus |mod m| in the spec turns into |& 15|. - return (r1 + 1) & 15; + if constexpr (prime_minus_one_over_gamma2() == 32) { + if (r0 > 0) { + // (Q-1)/(2 gamma2) = m = 16, thus `mod m` in the spec turns into + // `& 15`. + return (r1 + 1) & 15; + } else { + return (r1 - 1) & 15; + } } else { - return (r1 - 1) & 15; + // m = 44 + static_assert(prime_minus_one_over_gamma2() == 88); + if (r0 > 0) { + if (r1 == 43) { + return 0; + } else { + return r1 + 1; + } + } else { + if (r1 == 0) { + return 43; + } else { + return r1 - 1; + } + } } } return r1; } -void scalar_power2_round(scalar *s1, scalar *s0, const scalar *s) { +inline void scalar_power2_round(scalar *s1, scalar *s0, const scalar *s) { for (int i = 0; i < kDegree; i++) { power2_round(&s1->c[i], &s0->c[i], s->c[i]); } } -void scalar_scale_power2_round(scalar *out, const scalar *in) { +inline void scalar_scale_power2_round(scalar *out, const scalar *in) { for (int i = 0; i < kDegree; i++) { scale_power2_round(&out->c[i], in->c[i]); } } -void scalar_high_bits(scalar *out, const scalar *in) { +template +inline void scalar_high_bits(scalar *out, const scalar *in) { for (int i = 0; i < kDegree; i++) { - out->c[i] = high_bits(in->c[i]); + out->c[i] = high_bits(in->c[i]); } } -void scalar_low_bits(scalar *out, const scalar *in) { +template +inline void scalar_low_bits(scalar *out, const scalar *in) { for (int i = 0; i < kDegree; i++) { - out->c[i] = low_bits(in->c[i]); + out->c[i] = low_bits(in->c[i]); } } -void scalar_max(uint32_t *max, const scalar *s) { +inline void scalar_max(uint32_t *max, const scalar *s) { for (int i = 0; i < kDegree; i++) { uint32_t abs = abs_mod_prime(s->c[i]); - *max = maximum(*max, abs); + *max = maximum_reduced(*max, abs); } } -void scalar_max_signed(uint32_t *max, const scalar *s) { +inline void scalar_max_signed(uint32_t *max, const scalar *s) { for (int i = 0; i < kDegree; i++) { uint32_t abs = abs_signed(s->c[i]); - *max = maximum(*max, abs); + *max = maximum_reduced(*max, abs); } } -void scalar_make_hint(scalar *out, const scalar *ct0, const scalar *cs2, - const scalar *w) { +template +inline void scalar_make_hint(scalar *out, const scalar *ct0, const scalar *cs2, + const scalar *w) { for (int i = 0; i < kDegree; i++) { - out->c[i] = make_hint(ct0->c[i], cs2->c[i], w->c[i]); + out->c[i] = make_hint(ct0->c[i], cs2->c[i], w->c[i]); } } -void scalar_use_hint_vartime(scalar *out, const scalar *h, const scalar *r) { +template +inline void scalar_use_hint_vartime(scalar *out, const scalar *h, + const scalar *r) { for (int i = 0; i < kDegree; i++) { - out->c[i] = use_hint_vartime(h->c[i], r->c[i]); + out->c[i] = use_hint_vartime(h->c[i], r->c[i]); } } template -void vector_power2_round(vector *t1, vector *t0, const vector *t) { +inline void vector_power2_round(vector *t1, vector *t0, + const vector *t) { for (int i = 0; i < X; i++) { scalar_power2_round(&t1->v[i], &t0->v[i], &t->v[i]); } } template -void vector_scale_power2_round(vector *out, const vector *in) { +inline void vector_scale_power2_round(vector *out, const vector *in) { for (int i = 0; i < X; i++) { scalar_scale_power2_round(&out->v[i], &in->v[i]); } } -template -void vector_high_bits(vector *out, const vector *in) { - for (int i = 0; i < X; i++) { - scalar_high_bits(&out->v[i], &in->v[i]); +template +inline void vector_high_bits(vector *out, const vector *in) { + for (int i = 0; i < K; i++) { + scalar_high_bits(&out->v[i], &in->v[i]); + } +} + +template +inline void vector_low_bits(vector *out, const vector *in) { + for (int i = 0; i < K; i++) { + scalar_low_bits(&out->v[i], &in->v[i]); } } template -void vector_low_bits(vector *out, const vector *in) { - for (int i = 0; i < X; i++) { - scalar_low_bits(&out->v[i], &in->v[i]); - } -} - -template -uint32_t vector_max(const vector *a) { +inline uint32_t vector_max(const vector *a) { uint32_t max = 0; for (int i = 0; i < X; i++) { scalar_max(&max, &a->v[i]); @@ -586,7 +786,7 @@ uint32_t vector_max(const vector *a) { } template -uint32_t vector_max_signed(const vector *a) { +inline uint32_t vector_max_signed(const vector *a) { uint32_t max = 0; for (int i = 0; i < X; i++) { scalar_max_signed(&max, &a->v[i]); @@ -596,7 +796,7 @@ uint32_t vector_max_signed(const vector *a) { // The input vector contains only zeroes and ones. template -size_t vector_count_ones(const vector *a) { +inline size_t vector_count_ones(const vector *a) { size_t count = 0; for (int i = 0; i < X; i++) { for (int j = 0; j < kDegree; j++) { @@ -606,26 +806,30 @@ size_t vector_count_ones(const vector *a) { return count; } -template -void vector_make_hint(vector *out, const vector *ct0, - const vector *cs2, const vector *w) { - for (int i = 0; i < X; i++) { - scalar_make_hint(&out->v[i], &ct0->v[i], &cs2->v[i], &w->v[i]); +template +inline void vector_make_hint(vector *out, const vector *ct0, + const vector *cs2, const vector *w) { + for (int i = 0; i < K; i++) { + scalar_make_hint(&out->v[i], &ct0->v[i], &cs2->v[i], &w->v[i]); } } -template -void vector_use_hint_vartime(vector *out, const vector *h, - const vector *r) { - for (int i = 0; i < X; i++) { - scalar_use_hint_vartime(&out->v[i], &h->v[i], &r->v[i]); +template +inline void vector_use_hint_vartime(vector *out, const vector *h, + const vector *r) { + for (int i = 0; i < K; i++) { + scalar_use_hint_vartime(&out->v[i], &h->v[i], &r->v[i]); } } /* Bit packing */ +template +inline void scalar_encode(uint8_t *out, const scalar *s); + // FIPS 204, Algorithm 16 (`SimpleBitPack`). Specialized to bitlen(b) = 4. -static void scalar_encode_4(uint8_t out[128], const scalar *s) { +template <> +inline void scalar_encode<4>(uint8_t out[128], const scalar *s) { // Every two elements lands on a byte boundary. static_assert(kDegree % 2 == 0, "kDegree must be a multiple of 2"); for (int i = 0; i < kDegree / 2; i++) { @@ -637,8 +841,29 @@ static void scalar_encode_4(uint8_t out[128], const scalar *s) { } } +// FIPS 204, Algorithm 16 (`SimpleBitPack`). Specialized to bitlen(b) = 6. +template <> +inline void scalar_encode<6>(uint8_t out[192], const scalar *s) { + // Every four elements lands on a byte boundary. + static_assert(kDegree % 4 == 0, "kDegree must be a multiple of 4"); + for (int i = 0; i < kDegree / 4; i++) { + uint32_t a = s->c[4 * i]; + uint32_t b = s->c[4 * i + 1]; + uint32_t c = s->c[4 * i + 2]; + uint32_t d = s->c[4 * i + 3]; + declassify_assert(a < 64); + declassify_assert(b < 64); + declassify_assert(c < 64); + declassify_assert(d < 64); + out[3 * i] = a | (b << 6); + out[3 * i + 1] = (b >> 2) | (c << 4); + out[3 * i + 2] = (c >> 4) | (d << 2); + } +} + // FIPS 204, Algorithm 16 (`SimpleBitPack`). Specialized to bitlen(b) = 10. -void scalar_encode_10(uint8_t out[320], const scalar *s) { +template <> +inline void scalar_encode<10>(uint8_t out[320], const scalar *s) { // Every four elements lands on a byte boundary. static_assert(kDegree % 4 == 0, "kDegree must be a multiple of 4"); for (int i = 0; i < kDegree / 4; i++) { @@ -658,8 +883,12 @@ void scalar_encode_10(uint8_t out[320], const scalar *s) { } } +template +inline void scalar_encode_signed(uint8_t *out, const scalar *s); + // FIPS 204, Algorithm 17 (`BitPack`). Specialized to bitlen(a+b) = 4 and b = 4. -void scalar_encode_signed_4_4(uint8_t out[128], const scalar *s) { +template <> +inline void scalar_encode_signed<4, 4>(uint8_t out[128], const scalar *s) { // Every two elements lands on a byte boundary. static_assert(kDegree % 2 == 0, "kDegree must be a multiple of 2"); for (int i = 0; i < kDegree / 2; i++) { @@ -672,7 +901,8 @@ void scalar_encode_signed_4_4(uint8_t out[128], const scalar *s) { } // FIPS 204, Algorithm 17 (`BitPack`). Specialized to bitlen(a+b) = 3 and b = 2. -static void scalar_encode_signed_3_2(uint8_t out[96], const scalar *s) { +template <> +inline void scalar_encode_signed<3, 2>(uint8_t out[96], const scalar *s) { static_assert(kDegree % 8 == 0, "kDegree must be a multiple of 8"); for (int i = 0; i < kDegree / 8; i++) { uint32_t a = mod_sub(2, s->c[8 * i]); @@ -693,7 +923,9 @@ static void scalar_encode_signed_3_2(uint8_t out[96], const scalar *s) { // FIPS 204, Algorithm 17 (`BitPack`). Specialized to bitlen(a+b) = 13 and b = // 2^12. -void scalar_encode_signed_13_12(uint8_t out[416], const scalar *s) { +template <> +inline void scalar_encode_signed<13, (1u << 12)>(uint8_t out[416], + const scalar *s) { static const uint32_t kMax = 1u << 12; // Every two elements lands on a byte boundary. static_assert(kDegree % 8 == 0, "kDegree must be a multiple of 8"); @@ -724,16 +956,18 @@ void scalar_encode_signed_13_12(uint8_t out[416], const scalar *s) { e |= g << 14; e |= h << 27; h >>= 5; - OPENSSL_memcpy(&out[13 * i], &a, sizeof(a)); - OPENSSL_memcpy(&out[13 * i + 4], &c, sizeof(c)); - OPENSSL_memcpy(&out[13 * i + 8], &e, sizeof(e)); - OPENSSL_memcpy(&out[13 * i + 12], &h, 1); + CRYPTO_store_u32_le(&out[13 * i], a); + CRYPTO_store_u32_le(&out[13 * i + 4], c); + CRYPTO_store_u32_le(&out[13 * i + 8], e); + out[13 * i + 12] = static_cast(h); } } // FIPS 204, Algorithm 17 (`BitPack`). Specialized to bitlen(a+b) = 20 and b = // 2^19. -void scalar_encode_signed_20_19(uint8_t out[640], const scalar *s) { +template <> +inline void scalar_encode_signed<20, (1u << 19)>(uint8_t out[640], + const scalar *s) { static const uint32_t kMax = 1u << 19; // Every two elements lands on a byte boundary. static_assert(kDegree % 4 == 0, "kDegree must be a multiple of 4"); @@ -751,37 +985,49 @@ void scalar_encode_signed_20_19(uint8_t out[640], const scalar *s) { b |= c << 8; b |= d << 28; d >>= 4; - OPENSSL_memcpy(&out[10 * i], &a, sizeof(a)); - OPENSSL_memcpy(&out[10 * i + 4], &b, sizeof(b)); - OPENSSL_memcpy(&out[10 * i + 8], &d, 2); + CRYPTO_store_u32_le(&out[10 * i], a); + CRYPTO_store_u32_le(&out[10 * i + 4], b); + CRYPTO_store_u16_le(&out[10 * i + 8], static_cast(d)); } } -// FIPS 204, Algorithm 17 (`BitPack`). -void scalar_encode_signed(uint8_t *out, const scalar *s, int bits, - uint32_t max) { - if (bits == 3) { - assert(max == 2); - scalar_encode_signed_3_2(out, s); - } else if (bits == 4) { - assert(max == 4); - scalar_encode_signed_4_4(out, s); - } else if (bits == 20) { - assert(max == 1u << 19); - scalar_encode_signed_20_19(out, s); - } else { - assert(bits == 13); - assert(max == 1u << 12); - scalar_encode_signed_13_12(out, s); - } -} - -// FIPS 204, Algorithm 18 (`SimpleBitUnpack`). Specialized for bitlen(b) == 10. -void scalar_decode_10(scalar *out, const uint8_t in[320]) { - uint32_t v; +// FIPS 204, Algorithm 17 (`BitPack`). Specialized to bitlen(a+b) = 18 and b = +// 2^17. +template <> +inline void scalar_encode_signed<18, (1u << 17)>(uint8_t out[576], + const scalar *s) { + static const uint32_t kMax = 1u << 17; static_assert(kDegree % 4 == 0, "kDegree must be a multiple of 4"); for (int i = 0; i < kDegree / 4; i++) { - OPENSSL_memcpy(&v, &in[5 * i], sizeof(v)); + uint32_t a = mod_sub(kMax, s->c[4 * i]); + uint32_t b = mod_sub(kMax, s->c[4 * i + 1]); + uint32_t c = mod_sub(kMax, s->c[4 * i + 2]); + uint32_t d = mod_sub(kMax, s->c[4 * i + 3]); + declassify_assert(a < (1u << 18)); + declassify_assert(b < (1u << 18)); + declassify_assert(c < (1u << 18)); + declassify_assert(d < (1u << 18)); + out[9 * i] = (uint8_t)a; + out[9 * i + 1] = (uint8_t)(a >> 8); + out[9 * i + 2] = (uint8_t)(a >> 16) | (uint8_t)(b << 2); + out[9 * i + 3] = (uint8_t)(b >> 6); + out[9 * i + 4] = (uint8_t)(b >> 14) | (uint8_t)(c << 4); + out[9 * i + 5] = (uint8_t)(c >> 4); + out[9 * i + 6] = (uint8_t)(c >> 12) | (uint8_t)(d << 6); + out[9 * i + 7] = (uint8_t)(d >> 2); + out[9 * i + 8] = (uint8_t)(d >> 10); + } +} + +template +inline void scalar_decode(scalar *out, const uint8_t *in); + +// FIPS 204, Algorithm 18 (`SimpleBitUnpack`). Specialized for bitlen(b) == 10. +template <> +inline void scalar_decode<10>(scalar *out, const uint8_t in[320]) { + static_assert(kDegree % 4 == 0, "kDegree must be a multiple of 4"); + for (int i = 0; i < kDegree / 4; i++) { + uint32_t v = CRYPTO_load_u32_le(&in[5 * i]); out->c[4 * i] = v & 0x3ff; out->c[4 * i + 1] = (v >> 10) & 0x3ff; out->c[4 * i + 2] = (v >> 20) & 0x3ff; @@ -789,13 +1035,16 @@ void scalar_decode_10(scalar *out, const uint8_t in[320]) { } } +template +inline int scalar_decode_signed(scalar *out, const uint8_t *in); + // FIPS 204, Algorithm 19 (`BitUnpack`). Specialized to bitlen(a+b) = 4 and b = // 4. -int scalar_decode_signed_4_4(scalar *out, const uint8_t in[128]) { - uint32_t v; +template <> +inline int scalar_decode_signed<4, 4>(scalar *out, const uint8_t in[128]) { static_assert(kDegree % 8 == 0, "kDegree must be a multiple of 8"); for (int i = 0; i < kDegree / 8; i++) { - OPENSSL_memcpy(&v, &in[4 * i], sizeof(v)); + uint32_t v = CRYPTO_load_u32_le(&in[4 * i]); // None of the nibbles may be >= 9. So if the MSB of any nibble is set, none // of the other bits may be set. First, select all the MSBs. const uint32_t msbs = v & 0x88888888u; @@ -821,7 +1070,8 @@ int scalar_decode_signed_4_4(scalar *out, const uint8_t in[128]) { // FIPS 204, Algorithm 19 (`BitUnpack`). Specialized to bitlen(a+b) = 3 and b = // 2. -static int scalar_decode_signed_3_2(scalar *out, const uint8_t in[96]) { +template <> +inline int scalar_decode_signed<3, 2>(scalar *out, const uint8_t in[96]) { uint32_t v; uint8_t v_bytes[sizeof(v)] = {0}; static_assert(kDegree % 8 == 0, "kDegree must be a multiple of 8"); @@ -854,19 +1104,19 @@ static int scalar_decode_signed_3_2(scalar *out, const uint8_t in[96]) { // FIPS 204, Algorithm 19 (`BitUnpack`). Specialized to bitlen(a+b) = 13 and b = // 2^12. -void scalar_decode_signed_13_12(scalar *out, const uint8_t in[416]) { +template <> +inline int scalar_decode_signed<13, (1u << 12)>(scalar *out, + const uint8_t in[416]) { static const uint32_t kMax = 1u << 12; static const uint32_t k13Bits = (1u << 13) - 1; static const uint32_t k7Bits = (1u << 7) - 1; - uint32_t a, b, c; - uint8_t d; static_assert(kDegree % 8 == 0, "kDegree must be a multiple of 8"); for (int i = 0; i < kDegree / 8; i++) { - OPENSSL_memcpy(&a, &in[13 * i], sizeof(a)); - OPENSSL_memcpy(&b, &in[13 * i + 4], sizeof(b)); - OPENSSL_memcpy(&c, &in[13 * i + 8], sizeof(c)); - d = in[13 * i + 12]; + uint32_t a = CRYPTO_load_u32_le(&in[13 * i]); + uint32_t b = CRYPTO_load_u32_le(&in[13 * i + 4]); + uint32_t c = CRYPTO_load_u32_le(&in[13 * i + 8]); + uint8_t d = in[13 * i + 12]; // It's not possible for a 13-bit number to be out of range when the max is // 2^12. @@ -879,21 +1129,51 @@ void scalar_decode_signed_13_12(scalar *out, const uint8_t in[416]) { out->c[i * 8 + 6] = mod_sub(kMax, (c >> 14) & k13Bits); out->c[i * 8 + 7] = mod_sub(kMax, (c >> 27) | ((uint32_t)d) << 5); } + return 1; +} + +// FIPS 204, Algorithm 19 (`BitUnpack`). Specialized to bitlen(a+b) = 18 and b = +// 2^17. +template <> +inline int scalar_decode_signed<18, (1u << 17)>(scalar *out, + const uint8_t in[576]) { + static const uint32_t kMax = 1u << 17; + + static_assert(kDegree % 4 == 0, "kDegree must be a multiple of 4"); + for (int i = 0; i < kDegree / 4; i++) { + uint32_t a = uint32_t{in[9 * i]} | (uint32_t{in[9 * i + 1]} << 8) | + ((uint32_t{in[9 * i + 2]} & 0x3) << 16); + uint32_t b = (uint32_t{in[9 * i + 2]} >> 2) | + (uint32_t{in[9 * i + 3]} << 6) | + ((uint32_t{in[9 * i + 4]} & 0xf) << 14); + uint32_t c = (uint32_t{in[9 * i + 4]} >> 4) | + (uint32_t{in[9 * i + 5]} << 4) | + ((uint32_t{in[9 * i + 6]} & 0x3f) << 12); + uint32_t d = (uint32_t{in[9 * i + 6]} >> 6) | + (uint32_t{in[9 * i + 7]} << 2) | + (uint32_t{in[9 * i + 8]} << 10); + + out->c[i * 4] = mod_sub(kMax, a); + out->c[i * 4 + 1] = mod_sub(kMax, b); + out->c[i * 4 + 2] = mod_sub(kMax, c); + out->c[i * 4 + 3] = mod_sub(kMax, d); + } + return 1; } // FIPS 204, Algorithm 19 (`BitUnpack`). Specialized to bitlen(a+b) = 20 and b = // 2^19. -void scalar_decode_signed_20_19(scalar *out, const uint8_t in[640]) { +template <> +inline int scalar_decode_signed<20, (1u << 19)>(scalar *out, + const uint8_t in[640]) { static const uint32_t kMax = 1u << 19; static const uint32_t k20Bits = (1u << 20) - 1; - uint32_t a, b; - uint16_t c; static_assert(kDegree % 4 == 0, "kDegree must be a multiple of 4"); for (int i = 0; i < kDegree / 4; i++) { - OPENSSL_memcpy(&a, &in[10 * i], sizeof(a)); - OPENSSL_memcpy(&b, &in[10 * i + 4], sizeof(b)); - OPENSSL_memcpy(&c, &in[10 * i + 8], sizeof(c)); + uint32_t a = CRYPTO_load_u32_le(&in[10 * i]); + uint32_t b = CRYPTO_load_u32_le(&in[10 * i + 4]); + uint16_t c = CRYPTO_load_u16_le(&in[10 * i + 8]); // It's not possible for a 20-bit number to be out of range when the max is // 2^19. @@ -902,29 +1182,10 @@ void scalar_decode_signed_20_19(scalar *out, const uint8_t in[640]) { out->c[i * 4 + 2] = mod_sub(kMax, (b >> 8) & k20Bits); out->c[i * 4 + 3] = mod_sub(kMax, (b >> 28) | ((uint32_t)c) << 4); } + return 1; } -// FIPS 204, Algorithm 19 (`BitUnpack`). -int scalar_decode_signed(scalar *out, const uint8_t *in, int bits, - uint32_t max) { - if (bits == 3) { - assert(max == 2); - return scalar_decode_signed_3_2(out, in); - } else if (bits == 4) { - assert(max == 4); - return scalar_decode_signed_4_4(out, in); - } else if (bits == 13) { - assert(max == (1u << 12)); - scalar_decode_signed_13_12(out, in); - return 1; - } else if (bits == 20) { - assert(max == (1u << 19)); - scalar_decode_signed_20_19(out, in); - return 1; - } else { - abort(); - } -} + /* Expansion functions */ @@ -932,97 +1193,219 @@ int scalar_decode_signed(scalar *out, const uint8_t *in, int bits, // // Rejection samples a Keccak stream to get uniformly distributed elements. This // is used for matrix expansion and only operates on public inputs. -void scalar_from_keccak_vartime(scalar *out, - const uint8_t derived_seed[kRhoBytes + 2]) { - struct BORINGSSL_keccak_st keccak_ctx; - BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake128); - BORINGSSL_keccak_absorb(&keccak_ctx, derived_seed, kRhoBytes + 2); - assert(keccak_ctx.squeeze_offset == 0); - assert(keccak_ctx.rate_bytes == 168); +inline void scalar_from_keccak_block_vartime(scalar *out, int *done, + const uint8_t block[168]) { + // kStep is the number of loop iterations to do at once. May need to become + // platform dependent at some point. Must be a compile-time constant - if we + // ever need to runtime dispatch on it, it has to be made a template argument. + const size_t kStep = 2; + + // Branchless sampling as long as there is enough space in the output buffer + // even if all sampled numbers are < `kPrime`. + size_t i = 0; + for (; i <= size_t{168 - 3 * kStep} && *done <= int{kDegree - kStep}; + i += 3 * kStep) { + uint32_t d[kStep]; + for (size_t k = 0; k < kStep; ++k) { + size_t bi = i + 3 * k; + d[k] = (uint32_t)block[bi] | ((uint32_t)block[bi + 1] << 8) | + (((uint32_t)block[bi + 2] & 0x7f) << 16); + } + for (size_t k = 0; k < kStep; ++k) { + out->c[*done] = d[k]; + *done += d[k] < kPrime; + } + } + + // Branchful "tail". + for (; i < 168 && *done < kDegree; i += 3) { + // FIPS 204, Algorithm 14 (`CoeffFromThreeBytes`). + uint32_t value = (uint32_t)block[i] | ((uint32_t)block[i + 1] << 8) | + (((uint32_t)block[i + 2] & 0x7f) << 16); + if (value < kPrime) { + out->c[(*done)++] = value; + } + } +} + +// FIPS 204, Algorithm 30 (`RejNTTPoly`). +// +// Rejection samples a Keccak stream to get uniformly distributed elements. This +// is used for matrix expansion and only operates on public inputs. +inline void scalar_from_keccak_vartime(scalar *out, + BORINGSSL_keccak_st *keccak_ctx) { + assert(keccak_ctx->squeeze_offset == 0); + assert(keccak_ctx->rate_bytes == 168); static_assert(168 % 3 == 0, "block and coefficient boundaries do not align"); int done = 0; while (done < kDegree) { uint8_t block[168]; - BORINGSSL_keccak_squeeze(&keccak_ctx, block, sizeof(block)); - for (size_t i = 0; i < sizeof(block) && done < kDegree; i += 3) { - // FIPS 204, Algorithm 14 (`CoeffFromThreeBytes`). - uint32_t value = (uint32_t)block[i] | ((uint32_t)block[i + 1] << 8) | - (((uint32_t)block[i + 2] & 0x7f) << 16); - if (value < kPrime) { - out->c[done++] = value; - } - } + BORINGSSL_keccak_squeeze(keccak_ctx, block, sizeof(block)); + scalar_from_keccak_block_vartime(out, &done, block); } } +#if defined(HAVE_KECCAK_X2) +inline void scalar_from_keccak_vartime_x2(scalar *out[2], + BORINGSSL_keccak_st keccak_ctx[2]) { + assert(keccak_ctx[0].squeeze_offset == 0); + assert(keccak_ctx[0].rate_bytes == 168); + assert(keccak_ctx[1].squeeze_offset == 0); + assert(keccak_ctx[1].rate_bytes == 168); + static_assert(168 % 3 == 0, "block and coefficient boundaries do not align"); + + int done[2] = {0, 0}; + while (done[0] < kDegree || done[1] < kDegree) { + uint8_t block[2][168]; + uint8_t *blocks[] = {block[0], block[1]}; + BORINGSSL_keccak_squeeze_x2(keccak_ctx, blocks, sizeof(block[0])); + scalar_from_keccak_block_vartime(out[0], &done[0], block[0]); + scalar_from_keccak_block_vartime(out[1], &done[1], block[1]); + } +} +#endif + +#if defined(HAVE_KECCAK_X4) +inline void scalar_from_keccak_vartime_x4(scalar *out[4], + BORINGSSL_keccak_st keccak_ctx[]) { + for (int i = 0; i < 4; i++) { + assert(keccak_ctx[i].squeeze_offset == 0); + assert(keccak_ctx[i].rate_bytes == 168); + } + static_assert(168 % 3 == 0, "block and coefficient boundaries do not align"); + + int done[4] = {0, 0, 0, 0}; + while (done[0] < kDegree || done[1] < kDegree || done[2] < kDegree || + done[3] < kDegree) { + uint8_t block[4][168]; + uint8_t *blocks[] = {block[0], block[1], block[2], block[3]}; + BORINGSSL_keccak_squeeze_x4(keccak_ctx, blocks, sizeof(block[0])); + scalar_from_keccak_block_vartime(out[0], &done[0], block[0]); + scalar_from_keccak_block_vartime(out[1], &done[1], block[1]); + scalar_from_keccak_block_vartime(out[2], &done[2], block[2]); + scalar_from_keccak_block_vartime(out[3], &done[3], block[3]); + } +} +#endif + +template +inline bool coefficient_from_nibble(uint32_t nibble, uint32_t *result); + +template <> +inline bool coefficient_from_nibble<4>(uint32_t nibble, uint32_t *result) { + // Knowing bounds on `nibble` seems to tempt some versions of Clang to emit + // a branch, if we don't have a barrier in `mod_sub`. + *result = mod_sub(4, value_barrier_u32(nibble)); + return constant_time_declassify_int(nibble < 9); +} + +template <> +inline bool coefficient_from_nibble<2>(uint32_t nibble, uint32_t *result) { + // Knowing bounds on `nibble` seems to tempt some versions of Clang to emit + // a branch, if we don't have a barrier in `mod_sub`. + // Constant time "nibble % 5". + uint32_t rem = nibble - 5 * ((205 * nibble) >> 10); + *result = mod_sub(2, value_barrier_u32(rem)); + return constant_time_declassify_int(nibble < 15); +} + template -static bool coefficient_from_nibble(uint32_t nibble, uint32_t *result); - -template <> -bool coefficient_from_nibble<4>(uint32_t nibble, uint32_t *result) { - if (constant_time_declassify_int(nibble < 9)) { - *result = mod_sub(4, nibble); - return true; +inline void scalar_uniform_block(scalar *out, int *done, + const uint8_t block[136]) { + for (size_t i = 0; i < 136 && *done < kDegree; ++i) { + uint32_t t0 = block[i] & 0x0F; + uint32_t t1 = block[i] >> 4; + // FIPS 204, Algorithm 15 (`CoefFromHalfByte`). Although both the input + // and output here are secret, it is OK to leak when we rejected a byte. + // Individual bytes of the SHAKE-256 stream are (indistinguishable from) + // independent of each other and the original seed, so leaking information + // about the rejected bytes does not reveal the input or output. + *done += coefficient_from_nibble(t0, &out->c[*done]); + if (*done < kDegree) { + *done += coefficient_from_nibble(t1, &out->c[*done]); + } } - return false; -} - -template <> -bool coefficient_from_nibble<2>(uint32_t nibble, uint32_t *result) { - if (constant_time_declassify_int(nibble < 15)) { - *result = mod_sub(2, nibble % 5); - return true; - } - return false; } // FIPS 204, Algorithm 31 (`RejBoundedPoly`). template -void scalar_uniform(scalar *out, const uint8_t derived_seed[kSigmaBytes + 2]) { - struct BORINGSSL_keccak_st keccak_ctx; - BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake256); - BORINGSSL_keccak_absorb(&keccak_ctx, derived_seed, kSigmaBytes + 2); - assert(keccak_ctx.squeeze_offset == 0); - assert(keccak_ctx.rate_bytes == 136); +inline void scalar_uniform(scalar *out, BORINGSSL_keccak_st *keccak_ctx) { + assert(keccak_ctx->squeeze_offset == 0); + assert(keccak_ctx->rate_bytes == 136); int done = 0; while (done < kDegree) { uint8_t block[136]; - BORINGSSL_keccak_squeeze(&keccak_ctx, block, sizeof(block)); - for (size_t i = 0; i < sizeof(block) && done < kDegree; ++i) { - uint32_t t0 = block[i] & 0x0F; - uint32_t t1 = block[i] >> 4; - // FIPS 204, Algorithm 15 (`CoefFromHalfByte`). Although both the input - // and output here are secret, it is OK to leak when we rejected a byte. - // Individual bytes of the SHAKE-256 stream are (indistiguishable from) - // independent of each other and the original seed, so leaking information - // about the rejected bytes does not reveal the input or output. - uint32_t v; - if (coefficient_from_nibble(t0, &v)) { - out->c[done++] = v; - } - if (done < kDegree && coefficient_from_nibble(t1, &v)) { - out->c[done++] = v; - } - } + BORINGSSL_keccak_squeeze(keccak_ctx, block, sizeof(block)); + scalar_uniform_block(out, &done, block); } } -// FIPS 204, Algorithm 34 (`ExpandMask`), but just a single step. -void scalar_sample_mask(scalar *out, - const uint8_t derived_seed[kRhoPrimeBytes + 2]) { - uint8_t buf[640]; - BORINGSSL_keccak(buf, sizeof(buf), derived_seed, kRhoPrimeBytes + 2, - boringssl_shake256); +#if defined(HAVE_KECCAK_X2) +template +inline void scalar_uniform_x2(scalar *out[2], + BORINGSSL_keccak_st keccak_ctx[2]) { + assert(keccak_ctx[0].squeeze_offset == 0); + assert(keccak_ctx[0].rate_bytes == 136); + assert(keccak_ctx[1].squeeze_offset == 0); + assert(keccak_ctx[1].rate_bytes == 136); - scalar_decode_signed_20_19(out, buf); + int done[2] = {0, 0}; + while (done[0] < kDegree || done[1] < kDegree) { + uint8_t block[2][136]; + uint8_t *blocks[] = {block[0], block[1]}; + BORINGSSL_keccak_squeeze_x2(keccak_ctx, blocks, sizeof(block[0])); + scalar_uniform_block(out[0], &done[0], block[0]); + scalar_uniform_block(out[1], &done[1], block[1]); + } +} +#endif + +#if defined(HAVE_KECCAK_X4) +template +inline void scalar_uniform_x4(scalar *out[4], + BORINGSSL_keccak_st keccak_ctx[]) { + for (int i = 0; i < 4; i++) { + assert(keccak_ctx[i].squeeze_offset == 0); + assert(keccak_ctx[i].rate_bytes == 136); + } + + int done[4] = {0, 0, 0, 0}; + while (done[0] < kDegree || done[1] < kDegree || done[2] < kDegree || + done[3] < kDegree) { + uint8_t block[4][136]; + uint8_t *blocks[] = {block[0], block[1], block[2], block[3]}; + BORINGSSL_keccak_squeeze_x4(keccak_ctx, blocks, sizeof(block[0])); + scalar_uniform_block(out[0], &done[0], block[0]); + scalar_uniform_block(out[1], &done[1], block[1]); + scalar_uniform_block(out[2], &done[2], block[2]); + scalar_uniform_block(out[3], &done[3], block[3]); + } +} +#endif + +// FIPS 204, Algorithm 34 (`ExpandMask`), but just a single step. +template +inline void scalar_sample_mask(scalar *out, + const uint8_t rho_prime[kRhoPrimeBytes], + 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); + BORINGSSL_keccak_squeeze(&ctx, buf, sizeof(buf)); + scalar_decode_signed() + 1, gamma1()>(out, buf); } // FIPS 204, Algorithm 29 (`SampleInBall`). -void scalar_sample_in_ball_vartime(scalar *out, const uint8_t *seed, int len, - int tau) { - struct BORINGSSL_keccak_st keccak_ctx; +inline void scalar_sample_in_ball_vartime(scalar *out, const uint8_t *seed, + int len, int tau) { + BORINGSSL_keccak_st keccak_ctx; BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake256); BORINGSSL_keccak_absorb(&keccak_ctx, seed, len); assert(keccak_ctx.squeeze_offset == 0); @@ -1062,58 +1445,194 @@ void scalar_sample_in_ball_vartime(scalar *out, const uint8_t *seed, int len, } } -// FIPS 204, Algorithm 32 (`ExpandA`). template -void matrix_expand(matrix *out, const uint8_t rho[kRhoBytes]) { +inline void matrix_expand_step(scalar *out, const uint8_t rho[kRhoBytes], + int index) { + BORINGSSL_keccak_st keccak_ctx; + BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake128); + BORINGSSL_keccak_absorb(&keccak_ctx, rho, kRhoBytes); + uint8_t index_buf[2]; + index_buf[0] = static_cast(index % L); + index_buf[1] = static_cast(index / L); + BORINGSSL_keccak_absorb(&keccak_ctx, index_buf, 2); + scalar_from_keccak_vartime(out, &keccak_ctx); +} + +#if defined(HAVE_KECCAK_X2) +template +inline void matrix_expand_step_x2(matrix *out, + const uint8_t rho[kRhoBytes], int index) { + BORINGSSL_keccak_st keccak_ctx[2]; + BORINGSSL_keccak_init(&keccak_ctx[0], boringssl_shake128); + BORINGSSL_keccak_init(&keccak_ctx[1], boringssl_shake128); + BORINGSSL_keccak_absorb(&keccak_ctx[0], rho, kRhoBytes); + BORINGSSL_keccak_absorb(&keccak_ctx[1], rho, kRhoBytes); + uint8_t index_buf[2]; + index_buf[0] = static_cast(index % L); + index_buf[1] = static_cast(index / L); + BORINGSSL_keccak_absorb(&keccak_ctx[0], index_buf, 2); + index_buf[0] = static_cast((index + 1) % L); + index_buf[1] = static_cast((index + 1) / L); + BORINGSSL_keccak_absorb(&keccak_ctx[1], index_buf, 2); + + scalar *outs[] = {&out->v[index / L][index % L], + &out->v[(index + 1) / L][(index + 1) % L]}; + scalar_from_keccak_vartime_x2(outs, keccak_ctx); +} +#endif + +#if defined(HAVE_KECCAK_X4) +template +inline void matrix_expand_step_x4(matrix *out, + const uint8_t rho[kRhoBytes], int index) { + BORINGSSL_keccak_st keccak_ctx[4]; + for (int k = 0; k < 4; k++) { + BORINGSSL_keccak_init(&keccak_ctx[k], boringssl_shake128); + BORINGSSL_keccak_absorb(&keccak_ctx[k], rho, kRhoBytes); + uint8_t index_buf[2]; + index_buf[0] = static_cast((index + k) % L); + index_buf[1] = static_cast((index + k) / L); + BORINGSSL_keccak_absorb(&keccak_ctx[k], index_buf, 2); + } + + scalar *outs[] = {&out->v[index / L][index % L], + &out->v[(index + 1) / L][(index + 1) % L], + &out->v[(index + 2) / L][(index + 2) % L], + &out->v[(index + 3) / L][(index + 3) % L]}; + scalar_from_keccak_vartime_x4(outs, keccak_ctx); +} +#endif + +template +inline void matrix_expand(matrix *out, const uint8_t rho[kRhoBytes]) { static_assert(K <= 0x100, "K must fit in 8 bits"); static_assert(L <= 0x100, "L must fit in 8 bits"); - uint8_t derived_seed[kRhoBytes + 2]; - OPENSSL_memcpy(derived_seed, rho, kRhoBytes); - for (int i = 0; i < K; i++) { - for (int j = 0; j < L; j++) { - derived_seed[kRhoBytes + 1] = (uint8_t)i; - derived_seed[kRhoBytes] = (uint8_t)j; - scalar_from_keccak_vartime(&out->v[i][j], derived_seed); + int index = 0; +#if defined(HAVE_KECCAK_X4) + if (BORINGSSL_have_keccak_x4()) { + for (; index + 4 <= K * L; index += 4) { + matrix_expand_step_x4(out, rho, index); } } +#endif +#if defined(HAVE_KECCAK_X2) + for (; index + 2 <= K * L; index += 2) { + matrix_expand_step_x2(out, rho, index); + } +#endif + + for (; index < K * L; index++) { + matrix_expand_step(&out->v[index / L][index % L], rho, index); + } } +template +inline void vector_expand_short_step(scalar *out, + const uint8_t sigma[kSigmaBytes], + int index) { + BORINGSSL_keccak_st keccak_ctx; + BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake256); + BORINGSSL_keccak_absorb(&keccak_ctx, sigma, kSigmaBytes); + uint8_t index_buf[2]; + index_buf[0] = static_cast(index); + index_buf[1] = 0; + BORINGSSL_keccak_absorb(&keccak_ctx, index_buf, 2); + scalar_uniform()>(out, &keccak_ctx); +} + +#if defined(HAVE_KECCAK_X2) +template +inline void vector_expand_short_step_x2(scalar *out0, scalar *out1, + const uint8_t sigma[kSigmaBytes], + int index) { + BORINGSSL_keccak_st keccak_ctx[2]; + BORINGSSL_keccak_init(&keccak_ctx[0], boringssl_shake256); + BORINGSSL_keccak_init(&keccak_ctx[1], boringssl_shake256); + BORINGSSL_keccak_absorb(&keccak_ctx[0], sigma, kSigmaBytes); + BORINGSSL_keccak_absorb(&keccak_ctx[1], sigma, kSigmaBytes); + uint8_t index_buf[2]; + index_buf[0] = static_cast(index); + index_buf[1] = 0; + BORINGSSL_keccak_absorb(&keccak_ctx[0], index_buf, 2); + index_buf[0] = static_cast(index + 1); + index_buf[1] = 0; + BORINGSSL_keccak_absorb(&keccak_ctx[1], index_buf, 2); + + scalar *outs[] = {out0, out1}; + scalar_uniform_x2()>(outs, keccak_ctx); +} +#endif + +#if defined(HAVE_KECCAK_X4) +template +inline void vector_expand_short_step_x4(scalar *out0, scalar *out1, + scalar *out2, scalar *out3, + const uint8_t sigma[kSigmaBytes], + int index) { + BORINGSSL_keccak_st keccak_ctx[4]; + for (int k = 0; k < 4; k++) { + BORINGSSL_keccak_init(&keccak_ctx[k], boringssl_shake256); + BORINGSSL_keccak_absorb(&keccak_ctx[k], sigma, kSigmaBytes); + uint8_t index_buf[2]; + index_buf[0] = static_cast(index + k); + index_buf[1] = 0; + BORINGSSL_keccak_absorb(&keccak_ctx[k], index_buf, 2); + } + + scalar *outs[] = {out0, out1, out2, out3}; + scalar_uniform_x4()>(outs, keccak_ctx); +} +#endif + // FIPS 204, Algorithm 33 (`ExpandS`). template -void vector_expand_short(vector *s1, vector *s2, - const uint8_t sigma[kSigmaBytes]) { +inline void vector_expand_short(vector *s1, vector *s2, + const uint8_t sigma[kSigmaBytes]) { static_assert(K <= 0x100, "K must fit in 8 bits"); static_assert(L <= 0x100, "L must fit in 8 bits"); static_assert(K + L <= 0x100, "K+L must fit in 8 bits"); - uint8_t derived_seed[kSigmaBytes + 2]; - OPENSSL_memcpy(derived_seed, sigma, kSigmaBytes); - derived_seed[kSigmaBytes] = 0; - derived_seed[kSigmaBytes + 1] = 0; + scalar *all_scalars[K + L]; for (int i = 0; i < L; i++) { - scalar_uniform()>(&s1->v[i], derived_seed); - ++derived_seed[kSigmaBytes]; + all_scalars[i] = &s1->v[i]; } for (int i = 0; i < K; i++) { - scalar_uniform()>(&s2->v[i], derived_seed); - ++derived_seed[kSigmaBytes]; + all_scalars[L + i] = &s2->v[i]; + } + + int index = 0; +#if defined(HAVE_KECCAK_X4) + if (BORINGSSL_have_keccak_x4()) { + for (; index + 4 <= K + L; index += 4) { + vector_expand_short_step_x4(all_scalars[index], all_scalars[index + 1], + all_scalars[index + 2], + all_scalars[index + 3], sigma, index); + } + } +#endif +#if defined(HAVE_KECCAK_X2) + for (; index + 2 <= K + L; index += 2) { + vector_expand_short_step_x2(all_scalars[index], all_scalars[index + 1], + sigma, index); + } +#endif + + for (; index < K + L; index++) { + vector_expand_short_step(all_scalars[index], sigma, index); } } // FIPS 204, Algorithm 34 (`ExpandMask`). -template -void vector_expand_mask(vector *out, const uint8_t seed[kRhoPrimeBytes], - size_t kappa) { +template +inline void vector_expand_mask(vector *out, + const uint8_t rho_prime[kRhoPrimeBytes], + size_t kappa) { assert(kappa + L <= 0x10000); - uint8_t derived_seed[kRhoPrimeBytes + 2]; - OPENSSL_memcpy(derived_seed, seed, kRhoPrimeBytes); for (int i = 0; i < L; i++) { size_t index = kappa + i; - derived_seed[kRhoPrimeBytes] = index & 0xFF; - derived_seed[kRhoPrimeBytes + 1] = (index >> 8) & 0xFF; - scalar_sample_mask(&out->v[i], derived_seed); + scalar_sample_mask(&out->v[i], rho_prime, index); } } @@ -1121,50 +1640,60 @@ void vector_expand_mask(vector *out, const uint8_t seed[kRhoPrimeBytes], // FIPS 204, Algorithm 16 (`SimpleBitPack`). // -// Encodes an entire vector into 32*K*|bits| bytes. Note that since 256 +// Encodes an entire vector into 32*K*`bits` bytes. Note that since 256 // (kDegree) is divisible by 8, the individual vector entries will always fill a // whole number of bytes, so we do not need to worry about bit packing here. -template -void vector_encode(uint8_t *out, const vector *a, int bits) { - if (bits == 4) { - for (int i = 0; i < K; i++) { - scalar_encode_4(out + i * bits * kDegree / 8, &a->v[i]); - } - } else { - assert(bits == 10); - for (int i = 0; i < K; i++) { - scalar_encode_10(out + i * bits * kDegree / 8, &a->v[i]); - } +template +inline void vector_encode(uint8_t *out, const vector *a) { + for (int i = 0; i < K; i++) { + scalar_encode(out + i * bits * kDegree / 8, &a->v[i]); } } // FIPS 204, Algorithm 18 (`SimpleBitUnpack`). -template -void vector_decode_10(vector *out, const uint8_t *in) { +template +inline void vector_decode(vector *out, const uint8_t *in) { for (int i = 0; i < K; i++) { - scalar_decode_10(&out->v[i], in + i * 10 * kDegree / 8); + scalar_decode(&out->v[i], in + i * bits * kDegree / 8); } } // FIPS 204, Algorithm 17 (`BitPack`). // -// Encodes an entire vector into 32*L*|bits| bytes. Note that since 256 +// Encodes an entire vector into 32*L*`bits` bytes. Note that since 256 // (kDegree) is divisible by 8, the individual vector entries will always fill a // whole number of bytes, so we do not need to worry about bit packing here. -template -void vector_encode_signed(uint8_t *out, const vector *a, int bits, - uint32_t max) { +template +inline void vector_encode_signed(uint8_t *out, const vector *a) { for (int i = 0; i < X; i++) { - scalar_encode_signed(out + i * bits * kDegree / 8, &a->v[i], bits, max); + scalar_encode_signed(out + i * bits * kDegree / 8, &a->v[i]); } } -template -int vector_decode_signed(vector *out, const uint8_t *in, int bits, - uint32_t max) { +// `vector_encode_signed_ntt` behaves like `vector_encode_signed` but takes its +// input in NTT form. This is only used by the testing-only `skEncode` and +// `skDecode` functions and is not performance-sensitive. +template +inline void vector_encode_signed_ntt(uint8_t *out, const vector *a_ntt) { + vector a = *a_ntt; + vector_inverse_ntt_montgomery(&a); + // `vector_inverse_ntt_montgomery` adds an extra factor of R, which we must + // cancel with a Montgomery reduction. for (int i = 0; i < X; i++) { - if (!scalar_decode_signed(&out->v[i], in + i * bits * kDegree / 8, bits, - max)) { + for (int j = 0; j < kDegree; j++) { + a.v[i].c[j] = reduce_montgomery(a.v[i].c[j]); + } + } + + vector_encode_signed(out, &a); +} + +// FIPS 204, Algorithm 19 (`BitUnpack`). +template +inline int vector_decode_signed(vector *out, const uint8_t *in) { + for (int i = 0; i < X; i++) { + if (!scalar_decode_signed(&out->v[i], + in + i * bits * kDegree / 8)) { return 0; } } @@ -1173,13 +1702,13 @@ int vector_decode_signed(vector *out, const uint8_t *in, int bits, // FIPS 204, Algorithm 28 (`w1Encode`). template -void w1_encode(uint8_t out[128 * K], const vector *w1) { - vector_encode(out, w1, 4); +inline void w1_encode(uint8_t out[w1_bytes()], const vector *w1) { + vector_encode()>(out, w1); } // FIPS 204, Algorithm 20 (`HintBitPack`). template -void hint_bit_pack(uint8_t out[omega() + K], const vector *h) { +inline void hint_bit_pack(uint8_t out[omega() + K], const vector *h) { OPENSSL_memset(out, 0, omega() + K); int index = 0; for (int i = 0; i < K; i++) { @@ -1196,7 +1725,7 @@ void hint_bit_pack(uint8_t out[omega() + K], const vector *h) { // FIPS 204, Algorithm 21 (`HintBitUnpack`). template -int hint_bit_unpack(vector *h, const uint8_t in[omega() + K]) { +inline int hint_bit_unpack(vector *h, const uint8_t in[omega() + K]) { vector_zero(h); int index = 0; for (int i = 0; i < K; i++) { @@ -1235,12 +1764,11 @@ struct public_key { template struct private_key { - uint8_t rho[kRhoBytes]; + public_key pub; uint8_t k[kKBytes]; - uint8_t public_key_hash[kTrBytes]; - vector s1; - vector s2; - vector t0; + vector s1_ntt; + vector s2_ntt; + vector t0_ntt; }; template @@ -1252,7 +1780,7 @@ struct signature { // FIPS 204, Algorithm 22 (`pkEncode`). template -int mldsa_marshal_public_key(CBB *out, const struct public_key *pub) { +inline int mldsa_marshal_public_key(CBB *out, const public_key *pub) { if (!CBB_add_bytes(out, pub->rho, sizeof(pub->rho))) { return 0; } @@ -1261,14 +1789,14 @@ int mldsa_marshal_public_key(CBB *out, const struct public_key *pub) { if (!CBB_add_space(out, &vectork_output, 320 * K)) { return 0; } - vector_encode(vectork_output, &pub->t1, 10); + vector_encode<10>(vectork_output, &pub->t1); return 1; } // FIPS 204, Algorithm 23 (`pkDecode`). template -int mldsa_parse_public_key(struct public_key *pub, CBS *in) { +inline int mldsa_parse_public_key(public_key *pub, CBS *in) { const CBS orig_in = *in; if (!CBS_copy_bytes(in, pub->rho, sizeof(pub->rho))) { @@ -1279,7 +1807,7 @@ int mldsa_parse_public_key(struct public_key *pub, CBS *in) { if (!CBS_get_bytes(in, &t1_bytes, 320 * K) || CBS_len(in) != 0) { return 0; } - vector_decode_10(&pub->t1, CBS_data(&t1_bytes)); + vector_decode<10>(&pub->t1, CBS_data(&t1_bytes)); // Compute pre-cached values. BORINGSSL_keccak(pub->public_key_hash, sizeof(pub->public_key_hash), @@ -1290,11 +1818,11 @@ int mldsa_parse_public_key(struct public_key *pub, CBS *in) { // FIPS 204, Algorithm 24 (`skEncode`). template -int mldsa_marshal_private_key(CBB *out, const struct private_key *priv) { - if (!CBB_add_bytes(out, priv->rho, sizeof(priv->rho)) || +inline int mldsa_marshal_private_key(CBB *out, const private_key *priv) { + if (!CBB_add_bytes(out, priv->pub.rho, sizeof(priv->pub.rho)) || !CBB_add_bytes(out, priv->k, sizeof(priv->k)) || - !CBB_add_bytes(out, priv->public_key_hash, - sizeof(priv->public_key_hash))) { + !CBB_add_bytes(out, priv->pub.public_key_hash, + sizeof(priv->pub.public_key_hash))) { return 0; } @@ -1304,46 +1832,59 @@ int mldsa_marshal_private_key(CBB *out, const struct private_key *priv) { if (!CBB_add_space(out, &vectorl_output, scalar_bytes * L)) { return 0; } - vector_encode_signed(vectorl_output, &priv->s1, plus_minus_eta_bitlen(), - eta()); + vector_encode_signed_ntt(), eta()>(vectorl_output, + &priv->s1_ntt); uint8_t *s2_output; if (!CBB_add_space(out, &s2_output, scalar_bytes * K)) { return 0; } - vector_encode_signed(s2_output, &priv->s2, plus_minus_eta_bitlen(), - eta()); + vector_encode_signed_ntt(), eta()>(s2_output, + &priv->s2_ntt); uint8_t *t0_output; if (!CBB_add_space(out, &t0_output, 416 * K)) { return 0; } - vector_encode_signed(t0_output, &priv->t0, 13, 1 << 12); + vector_encode_signed_ntt<13, (1 << 12)>(t0_output, &priv->t0_ntt); return 1; } -// FIPS 204, Algorithm 25 (`skDecode`). +// FIPS 204, Algorithm 25 (`skDecode`). This is only used for testing. The +// supported external way to construct ML-DSA keys is to use the input seed. template -int mldsa_parse_private_key(struct private_key *priv, CBS *in) { - CBS s1_bytes; - CBS s2_bytes; - CBS t0_bytes; +inline int mldsa_parse_private_key(private_key *priv, CBS *in) { + CBS public_key_hash, s1_bytes, s2_bytes, t0_bytes; constexpr size_t scalar_bytes = (kDegree * plus_minus_eta_bitlen() + 7) / 8; - if (!CBS_copy_bytes(in, priv->rho, sizeof(priv->rho)) || + if (!CBS_copy_bytes(in, priv->pub.rho, sizeof(priv->pub.rho)) || !CBS_copy_bytes(in, priv->k, sizeof(priv->k)) || - !CBS_copy_bytes(in, priv->public_key_hash, - sizeof(priv->public_key_hash)) || + !CBS_get_bytes(in, &public_key_hash, kTrBytes) || !CBS_get_bytes(in, &s1_bytes, scalar_bytes * L) || - !vector_decode_signed(&priv->s1, CBS_data(&s1_bytes), - plus_minus_eta_bitlen(), eta()) || + !vector_decode_signed(), eta()>( + &priv->s1_ntt, CBS_data(&s1_bytes)) || !CBS_get_bytes(in, &s2_bytes, scalar_bytes * K) || - !vector_decode_signed(&priv->s2, CBS_data(&s2_bytes), - plus_minus_eta_bitlen(), eta()) || - !CBS_get_bytes(in, &t0_bytes, 416 * K) || - // Note: Decoding 13 bits into (-2^12, 2^12] cannot fail. - !vector_decode_signed(&priv->t0, CBS_data(&t0_bytes), 13, 1 << 12)) { + !vector_decode_signed(), eta()>( + &priv->s2_ntt, CBS_data(&s2_bytes)) || + !CBS_get_bytes(in, &t0_bytes, 416 * K)) { + return 0; + } + + // Compute `t1`, which is not in the `skDecode` input. This also computes + // `t0_ntt` and converts `s1_ntt` and `s2_ntt` to NTT form. + uint8_t unused[public_key_bytes()]; + if (!mldsa_finish_keygen(unused, priv)) { + return 0; + } + + // As a side effect of computing `t1`, we also compute `t0` and + // `public_key_hash`. Check they match the received bytes. + uint8_t t0_computed[416 * K]; + vector_encode_signed_ntt<13, (1 << 12)>(t0_computed, &priv->t0_ntt); + if (!CBS_mem_equal(&public_key_hash, priv->pub.public_key_hash, + sizeof(priv->pub.public_key_hash)) || + !CBS_mem_equal(&t0_bytes, t0_computed, sizeof(t0_computed))) { return 0; } @@ -1352,16 +1893,17 @@ int mldsa_parse_private_key(struct private_key *priv, CBS *in) { // FIPS 204, Algorithm 26 (`sigEncode`). template -int mldsa_marshal_signature(CBB *out, const struct signature *sign) { +inline int mldsa_marshal_signature(CBB *out, const signature *sign) { if (!CBB_add_bytes(out, sign->c_tilde, sizeof(sign->c_tilde))) { return 0; } uint8_t *vectorl_output; - if (!CBB_add_space(out, &vectorl_output, 640 * L)) { + if (!CBB_add_space(out, &vectorl_output, scalar_le_gamma1_bytes() * L)) { return 0; } - vector_encode_signed(vectorl_output, &sign->z, 20, 1 << 19); + vector_encode_signed() + 1, gamma1()>(vectorl_output, + &sign->z); uint8_t *hint_output; if (!CBB_add_space(out, &hint_output, omega() + K)) { @@ -1374,13 +1916,14 @@ int mldsa_marshal_signature(CBB *out, const struct signature *sign) { // FIPS 204, Algorithm 27 (`sigDecode`). template -int mldsa_parse_signature(struct signature *sign, CBS *in) { +inline int mldsa_parse_signature(signature *sign, CBS *in) { CBS z_bytes; CBS hint_bytes; if (!CBS_copy_bytes(in, sign->c_tilde, sizeof(sign->c_tilde)) || - !CBS_get_bytes(in, &z_bytes, 640 * L) || - // Note: Decoding 20 bits into (-2^19, 2^19] cannot fail. - !vector_decode_signed(&sign->z, CBS_data(&z_bytes), 20, 1 << 19) || + !CBS_get_bytes(in, &z_bytes, scalar_le_gamma1_bytes() * L) || + // Note: Decoding b+1 bits into (-2^b, 2^b] cannot fail. + !vector_decode_signed() + 1, gamma1()>( + &sign->z, CBS_data(&z_bytes)) || !CBS_get_bytes(in, &hint_bytes, omega() + K) || !hint_bit_unpack(&sign->h, CBS_data(&hint_bytes))) { return 0; @@ -1389,37 +1932,72 @@ int mldsa_parse_signature(struct signature *sign, CBS *in) { return 1; } -template -struct DeleterFree { - void operator()(T *ptr) { OPENSSL_free(ptr); } -}; +// FIPS 204, Algorithm 6 (`ML-DSA.KeyGen_internal`), steps 3 and 5–11. +// Returns 1 on success and 0 on failure. +// +// On input, `priv->s1_ntt` and `priv->s2_ntt` are not yet in NTT form. They are +// converted to NTT form by this function. +template +inline int mldsa_finish_keygen( + uint8_t out_encoded_public_key[public_key_bytes()], + private_key *priv) { + // Intermediate values, allocated on the heap to allow use when there is a + // limited amount of stack. + struct Values { + enum { kAllowUniquePtr = true }; + matrix a_ntt; + vector t; + }; + auto values = MakeUnique(); + if (values == nullptr) { + return 0; + } + + // Step 3. + matrix_expand(&values->a_ntt, priv->pub.rho); + + // Step 5. Note that, on input, `s1_ntt` and `s2_ntt` are not yet in NTT form, + // but this function is responsible for converting them to NTT. + vector_ntt(&priv->s1_ntt); + matrix_mult_montgomery(&values->t, &values->a_ntt, &priv->s1_ntt); + vector_inverse_ntt_montgomery(&values->t); + vector_add(&values->t, &values->t, &priv->s2_ntt); + vector_ntt(&priv->s2_ntt); + + // Step 6-7. We store t0 in NTT form. + vector_power2_round(&priv->pub.t1, &priv->t0_ntt, &values->t); + vector_ntt(&priv->t0_ntt); + // t1 is public. + CONSTTIME_DECLASSIFY(&priv->pub.t1, sizeof(priv->pub.t1)); + + // Step 8. + CBB cbb; + CBB_init_fixed(&cbb, out_encoded_public_key, public_key_bytes()); + if (!mldsa_marshal_public_key(&cbb, &priv->pub)) { + return 0; + } + assert(CBB_len(&cbb) == public_key_bytes()); + + // Step 9-11. + BORINGSSL_keccak(priv->pub.public_key_hash, sizeof(priv->pub.public_key_hash), + out_encoded_public_key, public_key_bytes(), + boringssl_shake256); + + return 1; +} // FIPS 204, Algorithm 6 (`ML-DSA.KeyGen_internal`). Returns 1 on success and 0 // on failure. template -int mldsa_generate_key_external_entropy( +inline int mldsa_generate_key_external_entropy_no_self_test( uint8_t out_encoded_public_key[public_key_bytes()], - struct private_key *priv, - const uint8_t entropy[BCM_MLDSA_SEED_BYTES]) { - // Intermediate values, allocated on the heap to allow use when there is a - // limited amount of stack. - struct values_st { - struct public_key pub; - matrix a_ntt; - vector s1_ntt; - vector t; - }; - std::unique_ptr> values( - reinterpret_cast(OPENSSL_malloc(sizeof(values_st)))); - if (values == NULL) { - return 0; - } - - uint8_t augmented_entropy[BCM_MLDSA_SEED_BYTES + 2]; - OPENSSL_memcpy(augmented_entropy, entropy, BCM_MLDSA_SEED_BYTES); + private_key *priv, const uint8_t entropy[MLDSA_SEED_BYTES]) { + // Step 1-2. + uint8_t augmented_entropy[MLDSA_SEED_BYTES + 2]; + OPENSSL_memcpy(augmented_entropy, entropy, MLDSA_SEED_BYTES); // The k and l parameters are appended to the seed. - augmented_entropy[BCM_MLDSA_SEED_BYTES] = K; - augmented_entropy[BCM_MLDSA_SEED_BYTES + 1] = L; + augmented_entropy[MLDSA_SEED_BYTES] = K; + augmented_entropy[MLDSA_SEED_BYTES + 1] = L; uint8_t expanded_seed[kRhoBytes + kSigmaBytes + kKBytes]; BORINGSSL_keccak(expanded_seed, sizeof(expanded_seed), augmented_entropy, sizeof(augmented_entropy), boringssl_shake256); @@ -1428,94 +2006,33 @@ int mldsa_generate_key_external_entropy( const uint8_t *const k = expanded_seed + kRhoBytes + kSigmaBytes; // rho is public. CONSTTIME_DECLASSIFY(rho, kRhoBytes); - OPENSSL_memcpy(values->pub.rho, rho, sizeof(values->pub.rho)); - OPENSSL_memcpy(priv->rho, rho, sizeof(priv->rho)); + OPENSSL_memcpy(priv->pub.rho, rho, sizeof(priv->pub.rho)); OPENSSL_memcpy(priv->k, k, sizeof(priv->k)); - - matrix_expand(&values->a_ntt, rho); - vector_expand_short(&priv->s1, &priv->s2, sigma); - - OPENSSL_memcpy(&values->s1_ntt, &priv->s1, sizeof(values->s1_ntt)); - vector_ntt(&values->s1_ntt); - - matrix_mult(&values->t, &values->a_ntt, &values->s1_ntt); - vector_inverse_ntt(&values->t); - vector_add(&values->t, &values->t, &priv->s2); - - vector_power2_round(&values->pub.t1, &priv->t0, &values->t); - // t1 is public. - CONSTTIME_DECLASSIFY(&values->pub.t1, sizeof(values->pub.t1)); - - CBB cbb; - CBB_init_fixed(&cbb, out_encoded_public_key, public_key_bytes()); - if (!mldsa_marshal_public_key(&cbb, &values->pub)) { - return 0; - } - assert(CBB_len(&cbb) == public_key_bytes()); - - BORINGSSL_keccak(priv->public_key_hash, sizeof(priv->public_key_hash), - out_encoded_public_key, public_key_bytes(), - boringssl_shake256); - - return 1; + // Steps 4. This is independent of A (step 3) and can be done first. + // `mldsa_finish_keygen` will convert `s1_ntt` and `s2_ntt` into NTT from. + vector_expand_short(&priv->s1_ntt, &priv->s2_ntt, sigma); + // Steps 3 and 5-11. + return mldsa_finish_keygen(out_encoded_public_key, priv); } template -int mldsa_public_from_private(struct public_key *pub, - const struct private_key *priv) { - // Intermediate values, allocated on the heap to allow use when there is a - // limited amount of stack. - struct values_st { - matrix a_ntt; - vector s1_ntt; - vector t; - vector t0; - }; - std::unique_ptr> values( - reinterpret_cast(OPENSSL_malloc(sizeof(values_st)))); - if (values == NULL) { - return 0; - } - - OPENSSL_memcpy(pub->rho, priv->rho, sizeof(pub->rho)); - OPENSSL_memcpy(pub->public_key_hash, priv->public_key_hash, - sizeof(pub->public_key_hash)); - - matrix_expand(&values->a_ntt, priv->rho); - - OPENSSL_memcpy(&values->s1_ntt, &priv->s1, sizeof(values->s1_ntt)); - vector_ntt(&values->s1_ntt); - - matrix_mult(&values->t, &values->a_ntt, &values->s1_ntt); - vector_inverse_ntt(&values->t); - vector_add(&values->t, &values->t, &priv->s2); - - vector_power2_round(&pub->t1, &values->t0, &values->t); - // t1 is part of the public key and thus is public. - CONSTTIME_DECLASSIFY(&pub->t1, sizeof(pub->t1)); - return 1; +inline int mldsa_generate_key_external_entropy( + uint8_t out_encoded_public_key[public_key_bytes()], + private_key *priv, const uint8_t entropy[MLDSA_SEED_BYTES]) { + fips::ensure_keygen_self_test(); + return mldsa_generate_key_external_entropy_no_self_test( + out_encoded_public_key, priv, entropy); } -// FIPS 204, Algorithm 7 (`ML-DSA.Sign_internal`). Returns 1 on success and 0 -// on failure. +// FIPS 204, Algorithm 7 (`ML-DSA.Sign_internal`), using a pre-computed mu. +// Returns 1 on success and 0 on failure. template -int mldsa_sign_internal( +inline int mldsa_sign_mu_no_self_test( uint8_t out_encoded_signature[signature_bytes()], - const struct private_key *priv, const uint8_t *msg, size_t msg_len, - const uint8_t *context_prefix, size_t context_prefix_len, - const uint8_t *context, size_t context_len, + const private_key *priv, const uint8_t mu[kMuBytes], const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]) { - uint8_t mu[kMuBytes]; - struct BORINGSSL_keccak_st keccak_ctx; - BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake256); - BORINGSSL_keccak_absorb(&keccak_ctx, priv->public_key_hash, - sizeof(priv->public_key_hash)); - BORINGSSL_keccak_absorb(&keccak_ctx, context_prefix, context_prefix_len); - BORINGSSL_keccak_absorb(&keccak_ctx, context, context_len); - BORINGSSL_keccak_absorb(&keccak_ctx, msg, msg_len); - BORINGSSL_keccak_squeeze(&keccak_ctx, mu, kMuBytes); - uint8_t rho_prime[kRhoPrimeBytes]; + BORINGSSL_keccak_st keccak_ctx; BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake256); BORINGSSL_keccak_absorb(&keccak_ctx, priv->k, sizeof(priv->k)); BORINGSSL_keccak_absorb(&keccak_ctx, randomizer, @@ -1525,11 +2042,9 @@ int mldsa_sign_internal( // Intermediate values, allocated on the heap to allow use when there is a // limited amount of stack. - struct values_st { - struct signature sign; - vector s1_ntt; - vector s2_ntt; - vector t0_ntt; + struct Values { + enum { kAllowUniquePtr = true }; + signature sign; matrix a_ntt; vector y; vector w; @@ -1537,41 +2052,31 @@ int mldsa_sign_internal( vector cs1; vector cs2; }; - std::unique_ptr> values( - reinterpret_cast(OPENSSL_malloc(sizeof(values_st)))); - if (values == NULL) { + auto values = MakeUnique(); + if (values == nullptr) { return 0; } - OPENSSL_memcpy(&values->s1_ntt, &priv->s1, sizeof(values->s1_ntt)); - vector_ntt(&values->s1_ntt); - - OPENSSL_memcpy(&values->s2_ntt, &priv->s2, sizeof(values->s2_ntt)); - vector_ntt(&values->s2_ntt); - - OPENSSL_memcpy(&values->t0_ntt, &priv->t0, sizeof(values->t0_ntt)); - vector_ntt(&values->t0_ntt); - - matrix_expand(&values->a_ntt, priv->rho); + matrix_expand(&values->a_ntt, priv->pub.rho); // kappa must not exceed 2**16/L = 13107. But the probability of it // exceeding even 1000 iterations is vanishingly small. for (size_t kappa = 0;; kappa += L) { - vector_expand_mask(&values->y, rho_prime, kappa); + vector_expand_mask(&values->y, rho_prime, kappa); vector *y_ntt = &values->cs1; OPENSSL_memcpy(y_ntt, &values->y, sizeof(*y_ntt)); vector_ntt(y_ntt); - matrix_mult(&values->w, &values->a_ntt, y_ntt); - vector_inverse_ntt(&values->w); + matrix_mult_montgomery(&values->w, &values->a_ntt, y_ntt); + vector_inverse_ntt_montgomery(&values->w); vector_high_bits(&values->w1, &values->w); - uint8_t w1_encoded[128 * K]; + uint8_t w1_encoded[w1_bytes()]; w1_encode(w1_encoded, &values->w1); BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake256); BORINGSSL_keccak_absorb(&keccak_ctx, mu, kMuBytes); - BORINGSSL_keccak_absorb(&keccak_ctx, w1_encoded, 128 * K); + BORINGSSL_keccak_absorb(&keccak_ctx, w1_encoded, w1_bytes()); BORINGSSL_keccak_squeeze(&keccak_ctx, values->sign.c_tilde, 2 * lambda_bytes()); @@ -1580,10 +2085,10 @@ int mldsa_sign_internal( sizeof(values->sign.c_tilde), tau()); scalar_ntt(&c_ntt); - vector_mult_scalar(&values->cs1, &values->s1_ntt, &c_ntt); - vector_inverse_ntt(&values->cs1); - vector_mult_scalar(&values->cs2, &values->s2_ntt, &c_ntt); - vector_inverse_ntt(&values->cs2); + vector_mult_scalar_montgomery(&values->cs1, &priv->s1_ntt, &c_ntt); + vector_inverse_ntt_montgomery(&values->cs1); + vector_mult_scalar_montgomery(&values->cs2, &priv->s2_ntt, &c_ntt); + vector_inverse_ntt_montgomery(&values->cs2); vector_add(&values->sign.z, &values->y, &values->cs1); @@ -1598,26 +2103,36 @@ int mldsa_sign_internal( // https://pq-crystals.org/dilithium/data/dilithium-specification-round3.pdf // describes this leak as OK. Note we leak less than what is described by // the paper; we do not reveal which coefficient violated the bound, and - // we hide which of the |z_max| or |r0_max| bound failed. See also + // we hide which of the `z_max` or `r0_max` bound failed. See also // https://boringssl-review.googlesource.com/c/boringssl/+/67747/comment/2bbab0fa_d241d35a/ uint32_t z_max = vector_max(&values->sign.z); uint32_t r0_max = vector_max_signed(r0); if (constant_time_declassify_w( constant_time_ge_w(z_max, gamma1() - beta()) | - constant_time_ge_w(r0_max, kGamma2 - beta()))) { + constant_time_ge_w(r0_max, gamma2() - beta()))) { +#if defined(BORINGSSL_FIPS_BREAK_TESTS) + // In order to show that our self-tests trigger both restart cases in + // this loop, printf-logging is added when built in break-test mode. + printf("MLDSA signature restart case 1.\n"); +#endif continue; } vector *ct0 = &values->w1; - vector_mult_scalar(ct0, &values->t0_ntt, &c_ntt); - vector_inverse_ntt(ct0); + vector_mult_scalar_montgomery(ct0, &priv->t0_ntt, &c_ntt); + vector_inverse_ntt_montgomery(ct0); vector_make_hint(&values->sign.h, ct0, &values->cs2, &values->w); // See above. uint32_t ct0_max = vector_max(ct0); size_t h_ones = vector_count_ones(&values->sign.h); - if (constant_time_declassify_w(constant_time_ge_w(ct0_max, kGamma2) | + if (constant_time_declassify_w(constant_time_ge_w(ct0_max, gamma2()) | constant_time_lt_w(omega(), h_ones))) { +#if defined(BORINGSSL_FIPS_BREAK_TESTS) + // In order to show that our self-tests trigger both restart cases in + // this loop, printf-logging is added when built in break-test mode. + printf("MLDSA signature restart case 2.\n"); +#endif continue; } @@ -1637,26 +2152,104 @@ int mldsa_sign_internal( } } -// FIPS 204, Algorithm 8 (`ML-DSA.Verify_internal`). +// FIPS 204, Algorithm 7 (`ML-DSA.Sign_internal`), using a pre-computed mu. +// Returns 1 on success and 0 on failure. template -int mldsa_verify_internal(const struct public_key *pub, - const uint8_t encoded_signature[signature_bytes()], - const uint8_t *msg, size_t msg_len, - const uint8_t *context_prefix, - size_t context_prefix_len, const uint8_t *context, - size_t context_len) { +inline int mldsa_sign_mu( + uint8_t out_encoded_signature[signature_bytes()], + const private_key *priv, const uint8_t mu[kMuBytes], + const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]) { + fips::ensure_sign_self_test(); + return mldsa_sign_mu_no_self_test(out_encoded_signature, priv, mu, + randomizer); +} + +// FIPS 204, Algorithm 7 (`ML-DSA.Sign_internal`). Returns 1 on success and 0 +// on failure. +template +inline int mldsa_sign_internal_no_self_test( + uint8_t out_encoded_signature[signature_bytes()], + const private_key *priv, const uint8_t *msg, size_t msg_len, + const uint8_t *context_prefix, size_t context_prefix_len, + const uint8_t *context, size_t context_len, + const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]) { + uint8_t mu[kMuBytes]; + BORINGSSL_keccak_st keccak_ctx; + BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake256); + BORINGSSL_keccak_absorb(&keccak_ctx, priv->pub.public_key_hash, + sizeof(priv->pub.public_key_hash)); + BORINGSSL_keccak_absorb(&keccak_ctx, context_prefix, context_prefix_len); + BORINGSSL_keccak_absorb(&keccak_ctx, context, context_len); + BORINGSSL_keccak_absorb(&keccak_ctx, msg, msg_len); + BORINGSSL_keccak_squeeze(&keccak_ctx, mu, kMuBytes); + + return mldsa_sign_mu_no_self_test(out_encoded_signature, priv, mu, + randomizer); +} + +// FIPS 204, Algorithm 7 (`ML-DSA.Sign_internal`). Returns 1 on success and 0 +// on failure. +template +inline int mldsa_sign_internal( + uint8_t out_encoded_signature[signature_bytes()], + const private_key *priv, const uint8_t *msg, size_t msg_len, + const uint8_t *context_prefix, size_t context_prefix_len, + const uint8_t *context, size_t context_len, + const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]) { + fips::ensure_sign_self_test(); + return mldsa_sign_internal_no_self_test( + out_encoded_signature, priv, msg, msg_len, context_prefix, + context_prefix_len, context, context_len, randomizer); +} + +struct prehash_context { + BORINGSSL_keccak_st keccak_ctx; +}; + +template +inline void mldsa_prehash_init(prehash_context *out_prehash_ctx, + const public_key *pub, + const uint8_t *context_prefix, + size_t context_prefix_len, + const uint8_t *context, size_t context_len) { + BORINGSSL_keccak_init(&out_prehash_ctx->keccak_ctx, boringssl_shake256); + BORINGSSL_keccak_absorb(&out_prehash_ctx->keccak_ctx, pub->public_key_hash, + sizeof(pub->public_key_hash)); + BORINGSSL_keccak_absorb(&out_prehash_ctx->keccak_ctx, context_prefix, + context_prefix_len); + BORINGSSL_keccak_absorb(&out_prehash_ctx->keccak_ctx, context, context_len); +} + +inline void mldsa_prehash_update(prehash_context *inout_prehash_ctx, + const uint8_t *msg, size_t msg_len) { + BORINGSSL_keccak_absorb(&inout_prehash_ctx->keccak_ctx, msg, msg_len); +} + +inline void mldsa_prehash_finalize(uint8_t out_msg_rep[kMuBytes], + prehash_context *inout_prehash_ctx) { + BORINGSSL_keccak_squeeze(&inout_prehash_ctx->keccak_ctx, out_msg_rep, + kMuBytes); +} + +// FIPS 204, Algorithm 8 (`ML-DSA.Verify_internal`), using a pre-computed mu. +// Returns 1 on success and 0 on failure. +template +inline int mldsa_verify_mu_no_self_test( + const public_key *pub, + const uint8_t encoded_signature[signature_bytes()], + const uint8_t mu[kMuBytes]) { // Intermediate values, allocated on the heap to allow use when there is a // limited amount of stack. - struct values_st { - struct signature sign; + struct Values { + enum { kAllowUniquePtr = true }; + signature sign; matrix a_ntt; vector z_ntt; vector az_ntt; vector ct1_ntt; }; - std::unique_ptr> values( - reinterpret_cast(OPENSSL_malloc(sizeof(values_st)))); - if (values == NULL) { + auto values = MakeUnique(); + if (values == nullptr) { return 0; } @@ -1668,16 +2261,6 @@ int mldsa_verify_internal(const struct public_key *pub, matrix_expand(&values->a_ntt, pub->rho); - uint8_t mu[kMuBytes]; - struct BORINGSSL_keccak_st keccak_ctx; - BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake256); - BORINGSSL_keccak_absorb(&keccak_ctx, pub->public_key_hash, - sizeof(pub->public_key_hash)); - BORINGSSL_keccak_absorb(&keccak_ctx, context_prefix, context_prefix_len); - BORINGSSL_keccak_absorb(&keccak_ctx, context, context_len); - BORINGSSL_keccak_absorb(&keccak_ctx, msg, msg_len); - BORINGSSL_keccak_squeeze(&keccak_ctx, mu, kMuBytes); - scalar c_ntt; scalar_sample_in_ball_vartime(&c_ntt, values->sign.c_tilde, sizeof(values->sign.c_tilde), tau()); @@ -1686,25 +2269,26 @@ int mldsa_verify_internal(const struct public_key *pub, OPENSSL_memcpy(&values->z_ntt, &values->sign.z, sizeof(values->z_ntt)); vector_ntt(&values->z_ntt); - matrix_mult(&values->az_ntt, &values->a_ntt, &values->z_ntt); + matrix_mult_montgomery(&values->az_ntt, &values->a_ntt, &values->z_ntt); vector_scale_power2_round(&values->ct1_ntt, &pub->t1); vector_ntt(&values->ct1_ntt); - vector_mult_scalar(&values->ct1_ntt, &values->ct1_ntt, &c_ntt); + vector_mult_scalar_montgomery(&values->ct1_ntt, &values->ct1_ntt, &c_ntt); vector *const w1 = &values->az_ntt; vector_sub(w1, &values->az_ntt, &values->ct1_ntt); - vector_inverse_ntt(w1); + vector_inverse_ntt_montgomery(w1); vector_use_hint_vartime(w1, &values->sign.h, w1); - uint8_t w1_encoded[128 * K]; + uint8_t w1_encoded[w1_bytes()]; w1_encode(w1_encoded, w1); uint8_t c_tilde[2 * lambda_bytes()]; + BORINGSSL_keccak_st keccak_ctx; BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake256); BORINGSSL_keccak_absorb(&keccak_ctx, mu, kMuBytes); - BORINGSSL_keccak_absorb(&keccak_ctx, w1_encoded, 128 * K); + BORINGSSL_keccak_absorb(&keccak_ctx, w1_encoded, w1_bytes()); BORINGSSL_keccak_squeeze(&keccak_ctx, c_tilde, 2 * lambda_bytes()); uint32_t z_max = vector_max(&values->sign.z); @@ -1713,49 +2297,300 @@ int mldsa_verify_internal(const struct public_key *pub, 0; } -struct private_key<6, 5> *private_key_from_external_65( - const struct BCM_mldsa65_private_key *external) { - static_assert(sizeof(struct BCM_mldsa65_private_key) == - sizeof(struct private_key<6, 5>), - "MLDSA65 private key size incorrect"); - static_assert(alignof(struct BCM_mldsa65_private_key) == - alignof(struct private_key<6, 5>), - "MLDSA65 private key align incorrect"); - return (struct private_key<6, 5> *)external; +// FIPS 204, Algorithm 8 (`ML-DSA.Verify_internal`), using a pre-computed mu. +// Returns 1 on success and 0 on failure. +template +inline int mldsa_verify_mu( + const public_key *pub, + const uint8_t encoded_signature[signature_bytes()], + const uint8_t mu[kMuBytes]) { + fips::ensure_verify_self_test(); + return mldsa_verify_mu_no_self_test(pub, encoded_signature, mu); } -struct public_key<6> * -public_key_from_external_65(const struct BCM_mldsa65_public_key *external) { - static_assert(sizeof(struct BCM_mldsa65_public_key) == - sizeof(struct public_key<6>), - "MLDSA65 public key size incorrect"); - static_assert(alignof(struct BCM_mldsa65_public_key) == - alignof(struct public_key<6>), - "MLDSA65 public key align incorrect"); - return (struct public_key<6> *)external; +// FIPS 204, Algorithm 8 (`ML-DSA.Verify_internal`). +template +inline int mldsa_verify_internal_no_self_test( + const public_key *pub, + const uint8_t encoded_signature[signature_bytes()], const uint8_t *msg, + size_t msg_len, const uint8_t *context_prefix, size_t context_prefix_len, + const uint8_t *context, size_t context_len) { + uint8_t mu[kMuBytes]; + BORINGSSL_keccak_st keccak_ctx; + BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake256); + BORINGSSL_keccak_absorb(&keccak_ctx, pub->public_key_hash, + sizeof(pub->public_key_hash)); + BORINGSSL_keccak_absorb(&keccak_ctx, context_prefix, context_prefix_len); + BORINGSSL_keccak_absorb(&keccak_ctx, context, context_len); + BORINGSSL_keccak_absorb(&keccak_ctx, msg, msg_len); + BORINGSSL_keccak_squeeze(&keccak_ctx, mu, kMuBytes); + + return mldsa_verify_mu_no_self_test(pub, encoded_signature, mu); } -struct private_key<8, 7> * -private_key_from_external_87(const struct BCM_mldsa87_private_key *external) { - static_assert(sizeof(struct BCM_mldsa87_private_key) == - sizeof(struct private_key<8, 7>), - "MLDSA87 private key size incorrect"); - static_assert(alignof(struct BCM_mldsa87_private_key) == - alignof(struct private_key<8, 7>), - "MLDSA87 private key align incorrect"); - return (struct private_key<8, 7> *)external; +// FIPS 204, Algorithm 8 (`ML-DSA.Verify_internal`). +template +inline int mldsa_verify_internal( + const public_key *pub, + const uint8_t encoded_signature[signature_bytes()], const uint8_t *msg, + size_t msg_len, const uint8_t *context_prefix, size_t context_prefix_len, + const uint8_t *context, size_t context_len) { + fips::ensure_verify_self_test(); + return mldsa_verify_internal_no_self_test( + pub, encoded_signature, msg, msg_len, context_prefix, context_prefix_len, + context, context_len); } -struct public_key<8> * -public_key_from_external_87(const struct BCM_mldsa87_public_key *external) { - static_assert(sizeof(struct BCM_mldsa87_public_key) == - sizeof(struct public_key<8>), - "MLDSA87 public key size incorrect"); - static_assert(alignof(struct BCM_mldsa87_public_key) == - alignof(struct public_key<8>), - "MLDSA87 public key align incorrect"); - return (struct public_key<8> *)external; +static_assert(sizeof(MLDSA65_private_key) == sizeof(private_key<6, 5>)); +static_assert(alignof(MLDSA65_private_key) == alignof(private_key<6, 5>)); + +inline const private_key<6, 5> *private_key_from_external_65( + const MLDSA65_private_key *external) { + return reinterpret_cast *>(external); } +inline private_key<6, 5> *private_key_from_external_65( + MLDSA65_private_key *external) { + return reinterpret_cast *>(external); +} + +static_assert(sizeof(MLDSA65_public_key) == sizeof(public_key<6>)); +static_assert(alignof(MLDSA65_public_key) == alignof(public_key<6>)); + +inline const public_key<6> *public_key_from_external_65( + const MLDSA65_public_key *external) { + return reinterpret_cast *>(external); +} +inline public_key<6> *public_key_from_external_65( + MLDSA65_public_key *external) { + return reinterpret_cast *>(external); +} + +inline prehash_context *prehash_context_from_external_65( + MLDSA65_prehash *external) { + static_assert(sizeof(MLDSA65_prehash) == sizeof(prehash_context)); + static_assert(alignof(MLDSA65_prehash) == alignof(prehash_context)); + return reinterpret_cast(external); +} + +static_assert(sizeof(MLDSA87_private_key) == sizeof(private_key<8, 7>)); +static_assert(alignof(MLDSA87_private_key) == alignof(private_key<8, 7>)); +inline const private_key<8, 7> *private_key_from_external_87( + const MLDSA87_private_key *external) { + return reinterpret_cast *>(external); +} +inline private_key<8, 7> *private_key_from_external_87( + MLDSA87_private_key *external) { + return reinterpret_cast *>(external); +} + +static_assert(sizeof(MLDSA87_public_key) == sizeof(public_key<8>)); +static_assert(alignof(MLDSA87_public_key) == alignof(public_key<8>)); + +inline const public_key<8> *public_key_from_external_87( + const MLDSA87_public_key *external) { + return reinterpret_cast *>(external); +} +inline public_key<8> *public_key_from_external_87( + MLDSA87_public_key *external) { + return reinterpret_cast *>(external); +} + +inline prehash_context *prehash_context_from_external_87( + MLDSA87_prehash *external) { + static_assert(sizeof(MLDSA87_prehash) == sizeof(prehash_context)); + static_assert(alignof(MLDSA87_prehash) == alignof(prehash_context)); + return reinterpret_cast(external); +} + +static_assert(sizeof(MLDSA44_private_key) == sizeof(private_key<4, 4>)); +static_assert(alignof(MLDSA44_private_key) == alignof(private_key<4, 4>)); + +inline const private_key<4, 4> *private_key_from_external_44( + const MLDSA44_private_key *external) { + return reinterpret_cast *>(external); +} +inline private_key<4, 4> *private_key_from_external_44( + MLDSA44_private_key *external) { + return reinterpret_cast *>(external); +} + +static_assert(sizeof(MLDSA44_public_key) == sizeof(public_key<4>)); +static_assert(alignof(MLDSA44_public_key) == alignof(public_key<4>)); + +inline const public_key<4> *public_key_from_external_44( + const MLDSA44_public_key *external) { + return reinterpret_cast *>(external); +} +inline public_key<4> *public_key_from_external_44( + MLDSA44_public_key *external) { + return reinterpret_cast *>(external); +} + +inline prehash_context *prehash_context_from_external_44( + MLDSA44_prehash *external) { + static_assert(sizeof(MLDSA44_prehash) == sizeof(prehash_context)); + static_assert(alignof(MLDSA44_prehash) == alignof(prehash_context)); + return reinterpret_cast(external); +} + +namespace fips { + +#include "fips_known_values.inc" + +inline int keygen_self_test() { + struct Values { + enum { kAllowUniquePtr = true }; + private_key<6, 5> priv; + uint8_t pub_bytes[MLDSA65_PUBLIC_KEY_BYTES]; + uint8_t priv_bytes[BCM_MLDSA65_PRIVATE_KEY_BYTES]; + }; + auto values = MakeUnique(); + if (values == nullptr || + !mldsa_generate_key_external_entropy_no_self_test( + values->pub_bytes, &values->priv, kGenerateKeyEntropy)) { + return 0; + } + + CBB cbb; + CBB_init_fixed(&cbb, values->priv_bytes, sizeof(values->priv_bytes)); + if (!mldsa_marshal_private_key(&cbb, &values->priv)) { + return 0; + } + + if (!BORINGSSL_check_test(kExpectedPublicKey, values->pub_bytes, + "ML-DSA keygen public key") || + !BORINGSSL_check_test(kExpectedPrivateKey, values->priv_bytes, + "ML-DSA keygen private key")) { + return 0; + } + + return 1; +} + +inline int sign_self_test() { + struct Values { + enum { kAllowUniquePtr = true }; + private_key<6, 5> priv; + uint8_t pub_bytes[MLDSA65_PUBLIC_KEY_BYTES]; + uint8_t sig[MLDSA65_SIGNATURE_BYTES]; + }; + auto values = MakeUnique(); + if (values == nullptr || + !mldsa_generate_key_external_entropy(values->pub_bytes, &values->priv, + kSignEntropy)) { + return 0; + } + + const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES] = {}; + + // This message triggers the first restart case for signing. + uint8_t message[4] = {0}; + if (!mldsa_sign_internal_no_self_test(values->sig, &values->priv, message, + sizeof(message), nullptr, 0, nullptr, 0, + randomizer)) { + return 0; + } + if (!BORINGSSL_check_test(kExpectedCase1Signature, values->sig, + "ML-DSA sign case 1")) { + return 0; + } + + // This message triggers the second restart case for signing. + message[0] = 123; + if (!mldsa_sign_internal_no_self_test(values->sig, &values->priv, message, + sizeof(message), nullptr, 0, nullptr, 0, + randomizer)) { + return 0; + } + if (!BORINGSSL_check_test(kExpectedCase2Signature, values->sig, + "ML-DSA sign case 2")) { + return 0; + } + + return 1; +} + +inline int verify_self_test() { + struct Values { + enum { kAllowUniquePtr = true }; + private_key<6, 5> priv; + uint8_t pub_bytes[MLDSA65_PUBLIC_KEY_BYTES]; + }; + auto values = MakeUnique(); + if (values == nullptr) { + return 0; + } + + if (!mldsa_generate_key_external_entropy(values->pub_bytes, &values->priv, + kSignEntropy)) { + return 0; + } + + const uint8_t message[4] = {1, 0}; + if (!mldsa_verify_internal_no_self_test<6, 5>( + &values->priv.pub, kExpectedVerifySignature, message, sizeof(message), + nullptr, 0, nullptr, 0)) { + return 0; + } + + return 1; +} + +template +inline int check_key(const private_key *priv) { + uint8_t sig[signature_bytes()]; + uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES] = {}; + if (!mldsa_sign_internal_no_self_test(sig, priv, nullptr, 0, nullptr, 0, + nullptr, 0, randomizer)) { + return 0; + } + + if (boringssl_fips_break_test("MLDSA_PWCT")) { + sig[0] ^= 1; + } + + if (!mldsa_verify_internal_no_self_test(&priv->pub, sig, nullptr, 0, + nullptr, 0, nullptr, 0)) { + return 0; + } + return 1; +} + +#if defined(BORINGSSL_FIPS) + +void ensure_keygen_self_test() { + CRYPTO_once(g_mldsa_keygen_self_test_once_bss_get(), []() { + if (!keygen_self_test()) { + BORINGSSL_FIPS_abort(); + } + }); +} + +void ensure_sign_self_test() { + CRYPTO_once(g_mldsa_sign_self_test_once_bss_get(), []() { + if (!sign_self_test()) { + BORINGSSL_FIPS_abort(); + } + }); +} + +void ensure_verify_self_test() { + CRYPTO_once(g_mldsa_verify_self_test_once_bss_get(), []() { + if (!verify_self_test()) { + BORINGSSL_FIPS_abort(); + } + }); +} + +#else + +void ensure_keygen_self_test() {} +void ensure_sign_self_test() {} +void ensure_verify_self_test() {} + +#endif + +} // namespace fips } // namespace } // namespace mldsa @@ -1763,67 +2598,117 @@ public_key_from_external_87(const struct BCM_mldsa87_public_key *external) { // ML-DSA-65 specific wrappers. -bcm_status BCM_mldsa65_parse_public_key( - struct BCM_mldsa65_public_key *public_key, CBS *in) { +bcm_status bssl::BCM_mldsa65_parse_public_key(MLDSA65_public_key *public_key, + CBS *in) { return bcm_as_approved_status(mldsa_parse_public_key( mldsa::public_key_from_external_65(public_key), in)); } -bcm_status BCM_mldsa65_marshal_private_key( - CBB *out, const struct BCM_mldsa65_private_key *private_key) { +bcm_status bssl::BCM_mldsa65_marshal_private_key( + CBB *out, const MLDSA65_private_key *private_key) { return bcm_as_approved_status(mldsa_marshal_private_key( out, mldsa::private_key_from_external_65(private_key))); } -bcm_status BCM_mldsa65_parse_private_key( - struct BCM_mldsa65_private_key *private_key, CBS *in) { +bcm_status bssl::BCM_mldsa65_parse_private_key(MLDSA65_private_key *private_key, + CBS *in) { return bcm_as_approved_status( mldsa_parse_private_key(mldsa::private_key_from_external_65(private_key), in) && CBS_len(in) == 0); } -// Calls |MLDSA_generate_key_external_entropy| with random bytes from -// |BCM_rand_bytes|. -bcm_status BCM_mldsa65_generate_key( - uint8_t out_encoded_public_key[BCM_MLDSA65_PUBLIC_KEY_BYTES], - uint8_t out_seed[BCM_MLDSA_SEED_BYTES], - struct BCM_mldsa65_private_key *out_private_key) { - BCM_rand_bytes(out_seed, BCM_MLDSA_SEED_BYTES); - CONSTTIME_SECRET(out_seed, BCM_MLDSA_SEED_BYTES); +bcm_status bssl::BCM_mldsa65_check_key_fips(MLDSA65_private_key *private_key) { + return bcm_as_approved_status( + mldsa::fips::check_key(mldsa::private_key_from_external_65(private_key))); +} + +// Calls `MLDSA_generate_key_external_entropy` with random bytes from +// `BCM_rand_bytes`. +bcm_status bssl::BCM_mldsa65_generate_key( + uint8_t out_encoded_public_key[MLDSA65_PUBLIC_KEY_BYTES], + uint8_t out_seed[MLDSA_SEED_BYTES], MLDSA65_private_key *out_private_key) { + BCM_rand_bytes(out_seed, MLDSA_SEED_BYTES); + CONSTTIME_SECRET(out_seed, MLDSA_SEED_BYTES); return BCM_mldsa65_generate_key_external_entropy(out_encoded_public_key, out_private_key, out_seed); } -bcm_status BCM_mldsa65_private_key_from_seed( - struct BCM_mldsa65_private_key *out_private_key, - const uint8_t seed[BCM_MLDSA_SEED_BYTES]) { - uint8_t public_key[BCM_MLDSA65_PUBLIC_KEY_BYTES]; +bcm_status bssl::BCM_mldsa65_private_key_from_seed( + MLDSA65_private_key *out_private_key, + const uint8_t seed[MLDSA_SEED_BYTES]) { + uint8_t public_key[MLDSA65_PUBLIC_KEY_BYTES]; return BCM_mldsa65_generate_key_external_entropy(public_key, out_private_key, seed); } -bcm_status BCM_mldsa65_generate_key_external_entropy( - uint8_t out_encoded_public_key[BCM_MLDSA65_PUBLIC_KEY_BYTES], - struct BCM_mldsa65_private_key *out_private_key, - const uint8_t entropy[BCM_MLDSA_SEED_BYTES]) { - return bcm_as_approved_status(mldsa_generate_key_external_entropy( +bcm_status bssl::BCM_mldsa65_generate_key_external_entropy( + uint8_t out_encoded_public_key[MLDSA65_PUBLIC_KEY_BYTES], + MLDSA65_private_key *out_private_key, + const uint8_t entropy[MLDSA_SEED_BYTES]) { + return bcm_as_not_approved_status(mldsa_generate_key_external_entropy( out_encoded_public_key, mldsa::private_key_from_external_65(out_private_key), entropy)); } -bcm_status BCM_mldsa65_public_from_private( - struct BCM_mldsa65_public_key *out_public_key, - const struct BCM_mldsa65_private_key *private_key) { - return bcm_as_approved_status(mldsa_public_from_private( - mldsa::public_key_from_external_65(out_public_key), - mldsa::private_key_from_external_65(private_key))); +bcm_status bssl::BCM_mldsa65_generate_key_fips( + uint8_t out_encoded_public_key[MLDSA65_PUBLIC_KEY_BYTES], + uint8_t out_seed[MLDSA_SEED_BYTES], MLDSA65_private_key *out_private_key) { + if (out_encoded_public_key == nullptr || out_private_key == nullptr) { + return bcm_status::failure; + } + if (BCM_mldsa65_generate_key(out_encoded_public_key, out_seed, + out_private_key) == bcm_status::failure) { + return bcm_status::failure; + } + return BCM_mldsa65_check_key_fips(out_private_key); } -bcm_status BCM_mldsa65_sign_internal( - uint8_t out_encoded_signature[BCM_MLDSA65_SIGNATURE_BYTES], - const struct BCM_mldsa65_private_key *private_key, const uint8_t *msg, - size_t msg_len, const uint8_t *context_prefix, size_t context_prefix_len, +bcm_status bssl::BCM_mldsa65_generate_key_external_entropy_fips( + uint8_t out_encoded_public_key[MLDSA65_PUBLIC_KEY_BYTES], + MLDSA65_private_key *out_private_key, + const uint8_t entropy[MLDSA_SEED_BYTES]) { + if (out_encoded_public_key == nullptr || out_private_key == nullptr) { + return bcm_status::failure; + } + if (BCM_mldsa65_generate_key_external_entropy(out_encoded_public_key, + out_private_key, entropy) == + bcm_status::failure) { + return bcm_status::failure; + } + return BCM_mldsa65_check_key_fips(out_private_key); +} + +bcm_status bssl::BCM_mldsa65_private_key_from_seed_fips( + MLDSA65_private_key *out_private_key, + const uint8_t seed[MLDSA_SEED_BYTES]) { + uint8_t public_key[MLDSA65_PUBLIC_KEY_BYTES]; + if (BCM_mldsa65_generate_key_external_entropy(public_key, out_private_key, + seed) == bcm_status::failure) { + return bcm_status::failure; + } + return BCM_mldsa65_check_key_fips(out_private_key); +} + +bcm_status bssl::BCM_mldsa65_public_from_private( + MLDSA65_public_key *out_public_key, + const MLDSA65_private_key *private_key) { + const auto *priv = mldsa::private_key_from_external_65(private_key); + auto *out_pub = mldsa::public_key_from_external_65(out_public_key); + *out_pub = priv->pub; + return bcm_status::approved; +} + +const MLDSA65_public_key *bssl::BCM_mldsa65_public_of_private( + const MLDSA65_private_key *private_key) { + return reinterpret_cast( + &mldsa::private_key_from_external_65(private_key)->pub); +} + +bcm_status bssl::BCM_mldsa65_sign_internal( + uint8_t out_encoded_signature[MLDSA65_SIGNATURE_BYTES], + const MLDSA65_private_key *private_key, const uint8_t *msg, size_t msg_len, + const uint8_t *context_prefix, size_t context_prefix_len, const uint8_t *context, size_t context_len, const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]) { return bcm_as_approved_status(mldsa_sign_internal( @@ -1832,12 +2717,22 @@ bcm_status BCM_mldsa65_sign_internal( randomizer)); } +bcm_status bssl::BCM_mldsa65_sign_mu_internal( + uint8_t out_encoded_signature[MLDSA65_SIGNATURE_BYTES], + const MLDSA65_private_key *private_key, + const uint8_t msg_rep[MLDSA_MU_BYTES], + const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]) { + return bcm_as_approved_status(mldsa_sign_mu( + out_encoded_signature, mldsa::private_key_from_external_65(private_key), + msg_rep, randomizer)); +} + // ML-DSA signature in randomized mode, filling the random bytes with -// |BCM_rand_bytes|. -bcm_status BCM_mldsa65_sign( - uint8_t out_encoded_signature[BCM_MLDSA65_SIGNATURE_BYTES], - const struct BCM_mldsa65_private_key *private_key, const uint8_t *msg, - size_t msg_len, const uint8_t *context, size_t context_len) { +// `BCM_rand_bytes`. +bcm_status bssl::BCM_mldsa65_sign( + uint8_t out_encoded_signature[MLDSA65_SIGNATURE_BYTES], + const MLDSA65_private_key *private_key, const uint8_t *msg, size_t msg_len, + const uint8_t *context, size_t context_len) { BSSL_CHECK(context_len <= 255); uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]; BCM_rand_bytes(randomizer, sizeof(randomizer)); @@ -1849,10 +2744,61 @@ bcm_status BCM_mldsa65_sign( sizeof(context_prefix), context, context_len, randomizer); } +// ML-DSA pre-hashed API: initializing a pre-hashing context. +void bssl::BCM_mldsa65_prehash_init(MLDSA65_prehash *out_prehash_ctx, + const MLDSA65_public_key *public_key, + const uint8_t *context, + size_t context_len) { + BSSL_CHECK(context_len <= 255); + + const uint8_t context_prefix[2] = {0, static_cast(context_len)}; + mldsa_prehash_init(mldsa::prehash_context_from_external_65(out_prehash_ctx), + mldsa::public_key_from_external_65(public_key), + context_prefix, sizeof(context_prefix), context, + context_len); +} + +// ML-DSA pre-hashed API: updating a pre-hashing context with a message chunk. +void bssl::BCM_mldsa65_prehash_update(MLDSA65_prehash *inout_prehash_ctx, + const uint8_t *msg, size_t msg_len) { + mldsa_prehash_update( + mldsa::prehash_context_from_external_65(inout_prehash_ctx), msg, msg_len); +} + +// ML-DSA pre-hashed API: obtaining a message representative to sign. +void bssl::BCM_mldsa65_prehash_finalize(uint8_t out_msg_rep[MLDSA_MU_BYTES], + MLDSA65_prehash *inout_prehash_ctx) { + mldsa_prehash_finalize( + out_msg_rep, mldsa::prehash_context_from_external_65(inout_prehash_ctx)); +} + +// ML-DSA pre-hashed API: signing a message representative. +bcm_status bssl::BCM_mldsa65_sign_message_representative( + uint8_t out_encoded_signature[MLDSA65_SIGNATURE_BYTES], + const MLDSA65_private_key *private_key, + const uint8_t msg_rep[MLDSA_MU_BYTES]) { + uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]; + BCM_rand_bytes(randomizer, sizeof(randomizer)); + CONSTTIME_SECRET(randomizer, sizeof(randomizer)); + + return bcm_as_approved_status(mldsa_sign_mu( + out_encoded_signature, mldsa::private_key_from_external_65(private_key), + msg_rep, randomizer)); +} + +// ML-DSA pre-hashed API: verifying a message representative. +bcm_status bssl::BCM_mldsa65_verify_message_representative( + const MLDSA65_public_key *public_key, + const uint8_t signature[MLDSA65_SIGNATURE_BYTES], + const uint8_t msg_rep[MLDSA_MU_BYTES]) { + return bcm_as_approved_status(mldsa::mldsa_verify_mu<6, 5>( + mldsa::public_key_from_external_65(public_key), signature, msg_rep)); +} + // FIPS 204, Algorithm 3 (`ML-DSA.Verify`). -bcm_status BCM_mldsa65_verify( - const struct BCM_mldsa65_public_key *public_key, - const uint8_t signature[BCM_MLDSA65_SIGNATURE_BYTES], const uint8_t *msg, +bcm_status bssl::BCM_mldsa65_verify( + const MLDSA65_public_key *public_key, + const uint8_t signature[MLDSA65_SIGNATURE_BYTES], const uint8_t *msg, size_t msg_len, const uint8_t *context, size_t context_len) { BSSL_CHECK(context_len <= 255); const uint8_t context_prefix[2] = {0, static_cast(context_len)}; @@ -1861,9 +2807,9 @@ bcm_status BCM_mldsa65_verify( context, context_len); } -bcm_status BCM_mldsa65_verify_internal( - const struct BCM_mldsa65_public_key *public_key, - const uint8_t encoded_signature[BCM_MLDSA65_SIGNATURE_BYTES], +bcm_status bssl::BCM_mldsa65_verify_internal( + const MLDSA65_public_key *public_key, + const uint8_t encoded_signature[MLDSA65_SIGNATURE_BYTES], const uint8_t *msg, size_t msg_len, const uint8_t *context_prefix, size_t context_prefix_len, const uint8_t *context, size_t context_len) { return bcm_as_approved_status(mldsa::mldsa_verify_internal<6, 5>( @@ -1871,75 +2817,138 @@ bcm_status BCM_mldsa65_verify_internal( msg_len, context_prefix, context_prefix_len, context, context_len)); } -bcm_status BCM_mldsa65_marshal_public_key( - CBB *out, const struct BCM_mldsa65_public_key *public_key) { +bcm_status bssl::BCM_mldsa65_marshal_public_key( + CBB *out, const MLDSA65_public_key *public_key) { return bcm_as_approved_status(mldsa_marshal_public_key( out, mldsa::public_key_from_external_65(public_key))); } +int bssl::BCM_mldsa65_public_keys_equal(const MLDSA65_public_key *a, + const MLDSA65_public_key *b) { + auto *a_pub = mldsa::public_key_from_external_65(a); + auto *b_pub = mldsa::public_key_from_external_65(b); + // It is sufficient to compare `public_key_hash`. When importing a public key, + // the hash must be computed. When importing a private key in expanded form + // (an internal testing-only API), the hash is provided, but we recompute it + // and check for correctness. + return OPENSSL_memcmp(a_pub->public_key_hash, b_pub->public_key_hash, + sizeof(a_pub->public_key_hash)) == 0; +} + // ML-DSA-87 specific wrappers. -bcm_status BCM_mldsa87_parse_public_key( - struct BCM_mldsa87_public_key *public_key, CBS *in) { +bcm_status bssl::BCM_mldsa87_parse_public_key(MLDSA87_public_key *public_key, + CBS *in) { return bcm_as_approved_status(mldsa_parse_public_key( mldsa::public_key_from_external_87(public_key), in)); } -bcm_status BCM_mldsa87_marshal_private_key( - CBB *out, const struct BCM_mldsa87_private_key *private_key) { +bcm_status bssl::BCM_mldsa87_marshal_private_key( + CBB *out, const MLDSA87_private_key *private_key) { return bcm_as_approved_status(mldsa_marshal_private_key( out, mldsa::private_key_from_external_87(private_key))); } -bcm_status BCM_mldsa87_parse_private_key( - struct BCM_mldsa87_private_key *private_key, CBS *in) { +bcm_status bssl::BCM_mldsa87_parse_private_key(MLDSA87_private_key *private_key, + CBS *in) { return bcm_as_approved_status( mldsa_parse_private_key(mldsa::private_key_from_external_87(private_key), in) && CBS_len(in) == 0); } -// Calls |MLDSA_generate_key_external_entropy| with random bytes from -// |BCM_rand_bytes|. -bcm_status BCM_mldsa87_generate_key( - uint8_t out_encoded_public_key[BCM_MLDSA87_PUBLIC_KEY_BYTES], - uint8_t out_seed[BCM_MLDSA_SEED_BYTES], - struct BCM_mldsa87_private_key *out_private_key) { - BCM_rand_bytes(out_seed, BCM_MLDSA_SEED_BYTES); +bcm_status bssl::BCM_mldsa87_check_key_fips(MLDSA87_private_key *private_key) { + return bcm_as_approved_status( + mldsa::fips::check_key(mldsa::private_key_from_external_87(private_key))); +} + +// Calls `MLDSA_generate_key_external_entropy` with random bytes from +// `BCM_rand_bytes`. +bcm_status bssl::BCM_mldsa87_generate_key( + uint8_t out_encoded_public_key[MLDSA87_PUBLIC_KEY_BYTES], + uint8_t out_seed[MLDSA_SEED_BYTES], MLDSA87_private_key *out_private_key) { + BCM_rand_bytes(out_seed, MLDSA_SEED_BYTES); + CONSTTIME_SECRET(out_seed, MLDSA_SEED_BYTES); return BCM_mldsa87_generate_key_external_entropy(out_encoded_public_key, out_private_key, out_seed); } -bcm_status BCM_mldsa87_private_key_from_seed( - struct BCM_mldsa87_private_key *out_private_key, - const uint8_t seed[BCM_MLDSA_SEED_BYTES]) { - uint8_t public_key[BCM_MLDSA87_PUBLIC_KEY_BYTES]; +bcm_status bssl::BCM_mldsa87_private_key_from_seed( + MLDSA87_private_key *out_private_key, + const uint8_t seed[MLDSA_SEED_BYTES]) { + uint8_t public_key[MLDSA87_PUBLIC_KEY_BYTES]; return BCM_mldsa87_generate_key_external_entropy(public_key, out_private_key, seed); } -bcm_status BCM_mldsa87_generate_key_external_entropy( - uint8_t out_encoded_public_key[BCM_MLDSA87_PUBLIC_KEY_BYTES], - struct BCM_mldsa87_private_key *out_private_key, - const uint8_t entropy[BCM_MLDSA_SEED_BYTES]) { - return bcm_as_approved_status(mldsa_generate_key_external_entropy( +bcm_status bssl::BCM_mldsa87_generate_key_external_entropy( + uint8_t out_encoded_public_key[MLDSA87_PUBLIC_KEY_BYTES], + MLDSA87_private_key *out_private_key, + const uint8_t entropy[MLDSA_SEED_BYTES]) { + return bcm_as_not_approved_status(mldsa_generate_key_external_entropy( out_encoded_public_key, mldsa::private_key_from_external_87(out_private_key), entropy)); } -bcm_status BCM_mldsa87_public_from_private( - struct BCM_mldsa87_public_key *out_public_key, - const struct BCM_mldsa87_private_key *private_key) { - return bcm_as_approved_status(mldsa_public_from_private( - mldsa::public_key_from_external_87(out_public_key), - mldsa::private_key_from_external_87(private_key))); +bcm_status bssl::BCM_mldsa87_generate_key_fips( + uint8_t out_encoded_public_key[MLDSA87_PUBLIC_KEY_BYTES], + uint8_t out_seed[MLDSA_SEED_BYTES], MLDSA87_private_key *out_private_key) { + if (out_encoded_public_key == nullptr || out_private_key == nullptr) { + return bcm_status::failure; + } + if (BCM_mldsa87_generate_key(out_encoded_public_key, out_seed, + out_private_key) == bcm_status::failure) { + return bcm_status::failure; + } + return BCM_mldsa87_check_key_fips(out_private_key); } -bcm_status BCM_mldsa87_sign_internal( - uint8_t out_encoded_signature[BCM_MLDSA87_SIGNATURE_BYTES], - const struct BCM_mldsa87_private_key *private_key, const uint8_t *msg, - size_t msg_len, const uint8_t *context_prefix, size_t context_prefix_len, +bcm_status bssl::BCM_mldsa87_generate_key_external_entropy_fips( + uint8_t out_encoded_public_key[MLDSA87_PUBLIC_KEY_BYTES], + MLDSA87_private_key *out_private_key, + const uint8_t entropy[MLDSA_SEED_BYTES]) { + if (out_encoded_public_key == nullptr || out_private_key == nullptr) { + return bcm_status::failure; + } + if (BCM_mldsa87_generate_key_external_entropy(out_encoded_public_key, + out_private_key, entropy) == + bcm_status::failure) { + return bcm_status::failure; + } + return BCM_mldsa87_check_key_fips(out_private_key); +} + +bcm_status bssl::BCM_mldsa87_private_key_from_seed_fips( + MLDSA87_private_key *out_private_key, + const uint8_t seed[MLDSA_SEED_BYTES]) { + uint8_t public_key[MLDSA87_PUBLIC_KEY_BYTES]; + if (BCM_mldsa87_generate_key_external_entropy(public_key, out_private_key, + seed) == bcm_status::failure) { + return bcm_status::failure; + } + return BCM_mldsa87_check_key_fips(out_private_key); +} + +bcm_status bssl::BCM_mldsa87_public_from_private( + MLDSA87_public_key *out_public_key, + const MLDSA87_private_key *private_key) { + const auto *priv = mldsa::private_key_from_external_87(private_key); + auto *out_pub = mldsa::public_key_from_external_87(out_public_key); + *out_pub = priv->pub; + return bcm_status::approved; +} + +const MLDSA87_public_key *bssl::BCM_mldsa87_public_of_private( + const MLDSA87_private_key *private_key) { + return reinterpret_cast( + &mldsa::private_key_from_external_87(private_key)->pub); +} + +bcm_status bssl::BCM_mldsa87_sign_internal( + uint8_t out_encoded_signature[MLDSA87_SIGNATURE_BYTES], + const MLDSA87_private_key *private_key, const uint8_t *msg, size_t msg_len, + const uint8_t *context_prefix, size_t context_prefix_len, const uint8_t *context, size_t context_len, const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]) { return bcm_as_approved_status(mldsa_sign_internal( @@ -1948,15 +2957,26 @@ bcm_status BCM_mldsa87_sign_internal( randomizer)); } +bcm_status bssl::BCM_mldsa87_sign_mu_internal( + uint8_t out_encoded_signature[MLDSA87_SIGNATURE_BYTES], + const MLDSA87_private_key *private_key, + const uint8_t msg_rep[MLDSA_MU_BYTES], + const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]) { + return bcm_as_approved_status(mldsa_sign_mu( + out_encoded_signature, mldsa::private_key_from_external_87(private_key), + msg_rep, randomizer)); +} + // ML-DSA signature in randomized mode, filling the random bytes with -// |BCM_rand_bytes|. -bcm_status BCM_mldsa87_sign( - uint8_t out_encoded_signature[BCM_MLDSA87_SIGNATURE_BYTES], - const struct BCM_mldsa87_private_key *private_key, const uint8_t *msg, - size_t msg_len, const uint8_t *context, size_t context_len) { +// `BCM_rand_bytes`. +bcm_status bssl::BCM_mldsa87_sign( + uint8_t out_encoded_signature[MLDSA87_SIGNATURE_BYTES], + const MLDSA87_private_key *private_key, const uint8_t *msg, size_t msg_len, + const uint8_t *context, size_t context_len) { BSSL_CHECK(context_len <= 255); uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]; BCM_rand_bytes(randomizer, sizeof(randomizer)); + CONSTTIME_SECRET(randomizer, sizeof(randomizer)); const uint8_t context_prefix[2] = {0, static_cast(context_len)}; return BCM_mldsa87_sign_internal( @@ -1964,11 +2984,63 @@ bcm_status BCM_mldsa87_sign( sizeof(context_prefix), context, context_len, randomizer); } +// ML-DSA pre-hashed API: initializing a pre-hashing context. +void bssl::BCM_mldsa87_prehash_init(MLDSA87_prehash *out_prehash_ctx, + const MLDSA87_public_key *public_key, + const uint8_t *context, + size_t context_len) { + BSSL_CHECK(context_len <= 255); + + const uint8_t context_prefix[2] = {0, static_cast(context_len)}; + mldsa_prehash_init(mldsa::prehash_context_from_external_87(out_prehash_ctx), + mldsa::public_key_from_external_87(public_key), + context_prefix, sizeof(context_prefix), context, + context_len); +} + +// ML-DSA pre-hashed API: updating a pre-hashing context with a message chunk. +void bssl::BCM_mldsa87_prehash_update(MLDSA87_prehash *inout_prehash_ctx, + const uint8_t *msg, size_t msg_len) { + mldsa_prehash_update( + mldsa::prehash_context_from_external_87(inout_prehash_ctx), msg, msg_len); +} + +// ML-DSA pre-hashed API: obtaining a message representative to sign. +void bssl::BCM_mldsa87_prehash_finalize(uint8_t out_msg_rep[MLDSA_MU_BYTES], + MLDSA87_prehash *inout_prehash_ctx) { + mldsa_prehash_finalize( + out_msg_rep, mldsa::prehash_context_from_external_87(inout_prehash_ctx)); +} + +// ML-DSA pre-hashed API: signing a message representative. +bcm_status bssl::BCM_mldsa87_sign_message_representative( + uint8_t out_encoded_signature[MLDSA87_SIGNATURE_BYTES], + const MLDSA87_private_key *private_key, + const uint8_t msg_rep[MLDSA_MU_BYTES]) { + uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]; + BCM_rand_bytes(randomizer, sizeof(randomizer)); + CONSTTIME_SECRET(randomizer, sizeof(randomizer)); + + return bcm_as_approved_status(mldsa_sign_mu( + out_encoded_signature, mldsa::private_key_from_external_87(private_key), + msg_rep, randomizer)); +} + +// ML-DSA pre-hashed API: verifying a message representative. +bcm_status bssl::BCM_mldsa87_verify_message_representative( + const MLDSA87_public_key *public_key, + const uint8_t signature[MLDSA87_SIGNATURE_BYTES], + const uint8_t msg_rep[MLDSA_MU_BYTES]) { + return bcm_as_approved_status(mldsa::mldsa_verify_mu<8, 7>( + mldsa::public_key_from_external_87(public_key), signature, msg_rep)); +} + // FIPS 204, Algorithm 3 (`ML-DSA.Verify`). -bcm_status BCM_mldsa87_verify(const struct BCM_mldsa87_public_key *public_key, - const uint8_t *signature, const uint8_t *msg, - size_t msg_len, const uint8_t *context, - size_t context_len) { +bcm_status bssl::BCM_mldsa87_verify(const MLDSA87_public_key *public_key, + const uint8_t *signature, + const uint8_t *msg, size_t msg_len, + const uint8_t *context, + size_t context_len) { BSSL_CHECK(context_len <= 255); const uint8_t context_prefix[2] = {0, static_cast(context_len)}; return BCM_mldsa87_verify_internal(public_key, signature, msg, msg_len, @@ -1976,9 +3048,9 @@ bcm_status BCM_mldsa87_verify(const struct BCM_mldsa87_public_key *public_key, context, context_len); } -bcm_status BCM_mldsa87_verify_internal( - const struct BCM_mldsa87_public_key *public_key, - const uint8_t encoded_signature[BCM_MLDSA87_SIGNATURE_BYTES], +bcm_status bssl::BCM_mldsa87_verify_internal( + const MLDSA87_public_key *public_key, + const uint8_t encoded_signature[MLDSA87_SIGNATURE_BYTES], const uint8_t *msg, size_t msg_len, const uint8_t *context_prefix, size_t context_prefix_len, const uint8_t *context, size_t context_len) { return bcm_as_approved_status(mldsa::mldsa_verify_internal<8, 7>( @@ -1986,8 +3058,266 @@ bcm_status BCM_mldsa87_verify_internal( msg_len, context_prefix, context_prefix_len, context, context_len)); } -bcm_status BCM_mldsa87_marshal_public_key( - CBB *out, const struct BCM_mldsa87_public_key *public_key) { +bcm_status bssl::BCM_mldsa87_marshal_public_key( + CBB *out, const MLDSA87_public_key *public_key) { return bcm_as_approved_status(mldsa_marshal_public_key( out, mldsa::public_key_from_external_87(public_key))); } + +int bssl::BCM_mldsa87_public_keys_equal(const MLDSA87_public_key *a, + const MLDSA87_public_key *b) { + auto *a_pub = mldsa::public_key_from_external_87(a); + auto *b_pub = mldsa::public_key_from_external_87(b); + // It is sufficient to compare `public_key_hash`. When importing a public key, + // the hash must be computed. When importing a private key in expanded form + // (an internal testing-only API), the hash is provided, but we recompute it + // and check for correctness. + return OPENSSL_memcmp(a_pub->public_key_hash, b_pub->public_key_hash, + sizeof(a_pub->public_key_hash)) == 0; +} + + +// ML-DSA-44 specific wrappers. + +bcm_status bssl::BCM_mldsa44_parse_public_key(MLDSA44_public_key *public_key, + CBS *in) { + return bcm_as_approved_status(mldsa_parse_public_key( + mldsa::public_key_from_external_44(public_key), in)); +} + +bcm_status bssl::BCM_mldsa44_marshal_private_key( + CBB *out, const MLDSA44_private_key *private_key) { + return bcm_as_approved_status(mldsa_marshal_private_key( + out, mldsa::private_key_from_external_44(private_key))); +} + +bcm_status bssl::BCM_mldsa44_parse_private_key(MLDSA44_private_key *private_key, + CBS *in) { + return bcm_as_approved_status( + mldsa_parse_private_key(mldsa::private_key_from_external_44(private_key), + in) && + CBS_len(in) == 0); +} + +bcm_status bssl::BCM_mldsa44_check_key_fips(MLDSA44_private_key *private_key) { + return bcm_as_approved_status( + mldsa::fips::check_key(mldsa::private_key_from_external_44(private_key))); +} + +// Calls `MLDSA_generate_key_external_entropy` with random bytes from +// `BCM_rand_bytes`. +bcm_status bssl::BCM_mldsa44_generate_key( + uint8_t out_encoded_public_key[MLDSA44_PUBLIC_KEY_BYTES], + uint8_t out_seed[MLDSA_SEED_BYTES], MLDSA44_private_key *out_private_key) { + BCM_rand_bytes(out_seed, MLDSA_SEED_BYTES); + CONSTTIME_SECRET(out_seed, MLDSA_SEED_BYTES); + return BCM_mldsa44_generate_key_external_entropy(out_encoded_public_key, + out_private_key, out_seed); +} + +bcm_status bssl::BCM_mldsa44_private_key_from_seed( + MLDSA44_private_key *out_private_key, + const uint8_t seed[MLDSA_SEED_BYTES]) { + uint8_t public_key[MLDSA44_PUBLIC_KEY_BYTES]; + return BCM_mldsa44_generate_key_external_entropy(public_key, out_private_key, + seed); +} + +bcm_status bssl::BCM_mldsa44_generate_key_external_entropy( + uint8_t out_encoded_public_key[MLDSA44_PUBLIC_KEY_BYTES], + MLDSA44_private_key *out_private_key, + const uint8_t entropy[MLDSA_SEED_BYTES]) { + return bcm_as_not_approved_status(mldsa_generate_key_external_entropy( + out_encoded_public_key, + mldsa::private_key_from_external_44(out_private_key), entropy)); +} + +bcm_status bssl::BCM_mldsa44_generate_key_fips( + uint8_t out_encoded_public_key[MLDSA44_PUBLIC_KEY_BYTES], + uint8_t out_seed[MLDSA_SEED_BYTES], MLDSA44_private_key *out_private_key) { + if (out_encoded_public_key == nullptr || out_private_key == nullptr) { + return bcm_status::failure; + } + if (BCM_mldsa44_generate_key(out_encoded_public_key, out_seed, + out_private_key) == bcm_status::failure) { + return bcm_status::failure; + } + return BCM_mldsa44_check_key_fips(out_private_key); +} + +bcm_status bssl::BCM_mldsa44_generate_key_external_entropy_fips( + uint8_t out_encoded_public_key[MLDSA44_PUBLIC_KEY_BYTES], + MLDSA44_private_key *out_private_key, + const uint8_t entropy[MLDSA_SEED_BYTES]) { + if (out_encoded_public_key == nullptr || out_private_key == nullptr) { + return bcm_status::failure; + } + if (BCM_mldsa44_generate_key_external_entropy(out_encoded_public_key, + out_private_key, entropy) == + bcm_status::failure) { + return bcm_status::failure; + } + return BCM_mldsa44_check_key_fips(out_private_key); +} + +bcm_status bssl::BCM_mldsa44_private_key_from_seed_fips( + MLDSA44_private_key *out_private_key, + const uint8_t seed[MLDSA_SEED_BYTES]) { + uint8_t public_key[MLDSA44_PUBLIC_KEY_BYTES]; + if (BCM_mldsa44_generate_key_external_entropy(public_key, out_private_key, + seed) == bcm_status::failure) { + return bcm_status::failure; + } + return BCM_mldsa44_check_key_fips(out_private_key); +} + +bcm_status bssl::BCM_mldsa44_public_from_private( + MLDSA44_public_key *out_public_key, + const MLDSA44_private_key *private_key) { + const auto *priv = mldsa::private_key_from_external_44(private_key); + auto *out_pub = mldsa::public_key_from_external_44(out_public_key); + *out_pub = priv->pub; + return bcm_status::approved; +} + +const MLDSA44_public_key *bssl::BCM_mldsa44_public_of_private( + const MLDSA44_private_key *private_key) { + return reinterpret_cast( + &mldsa::private_key_from_external_44(private_key)->pub); +} + +bcm_status bssl::BCM_mldsa44_sign_internal( + uint8_t out_encoded_signature[MLDSA44_SIGNATURE_BYTES], + const MLDSA44_private_key *private_key, const uint8_t *msg, size_t msg_len, + const uint8_t *context_prefix, size_t context_prefix_len, + const uint8_t *context, size_t context_len, + const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]) { + return bcm_as_approved_status(mldsa_sign_internal( + out_encoded_signature, mldsa::private_key_from_external_44(private_key), + msg, msg_len, context_prefix, context_prefix_len, context, context_len, + randomizer)); +} + +bcm_status bssl::BCM_mldsa44_sign_mu_internal( + uint8_t out_encoded_signature[MLDSA44_SIGNATURE_BYTES], + const MLDSA44_private_key *private_key, + const uint8_t msg_rep[MLDSA_MU_BYTES], + const uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]) { + return bcm_as_approved_status(mldsa_sign_mu( + out_encoded_signature, mldsa::private_key_from_external_44(private_key), + msg_rep, randomizer)); +} + +// ML-DSA signature in randomized mode, filling the random bytes with +// `BCM_rand_bytes`. +bcm_status bssl::BCM_mldsa44_sign( + uint8_t out_encoded_signature[MLDSA44_SIGNATURE_BYTES], + const MLDSA44_private_key *private_key, const uint8_t *msg, size_t msg_len, + const uint8_t *context, size_t context_len) { + BSSL_CHECK(context_len <= 255); + uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]; + BCM_rand_bytes(randomizer, sizeof(randomizer)); + CONSTTIME_SECRET(randomizer, sizeof(randomizer)); + + const uint8_t context_prefix[2] = {0, static_cast(context_len)}; + return BCM_mldsa44_sign_internal( + out_encoded_signature, private_key, msg, msg_len, context_prefix, + sizeof(context_prefix), context, context_len, randomizer); +} + +// ML-DSA pre-hashed API: initializing a pre-hashing context. +void bssl::BCM_mldsa44_prehash_init(MLDSA44_prehash *out_prehash_ctx, + const MLDSA44_public_key *public_key, + const uint8_t *context, + size_t context_len) { + BSSL_CHECK(context_len <= 255); + + const uint8_t context_prefix[2] = {0, static_cast(context_len)}; + mldsa_prehash_init(mldsa::prehash_context_from_external_44(out_prehash_ctx), + mldsa::public_key_from_external_44(public_key), + context_prefix, sizeof(context_prefix), context, + context_len); +} + +// ML-DSA pre-hashed API: updating a pre-hashing context with a message chunk. +void bssl::BCM_mldsa44_prehash_update(MLDSA44_prehash *inout_prehash_ctx, + const uint8_t *msg, size_t msg_len) { + mldsa_prehash_update( + mldsa::prehash_context_from_external_44(inout_prehash_ctx), msg, msg_len); +} + +// ML-DSA pre-hashed API: obtaining a message representative to sign. +void bssl::BCM_mldsa44_prehash_finalize(uint8_t out_msg_rep[MLDSA_MU_BYTES], + MLDSA44_prehash *inout_prehash_ctx) { + mldsa_prehash_finalize( + out_msg_rep, mldsa::prehash_context_from_external_44(inout_prehash_ctx)); +} + +// ML-DSA pre-hashed API: signing a message representative. +bcm_status bssl::BCM_mldsa44_sign_message_representative( + uint8_t out_encoded_signature[MLDSA44_SIGNATURE_BYTES], + const MLDSA44_private_key *private_key, + const uint8_t msg_rep[MLDSA_MU_BYTES]) { + uint8_t randomizer[BCM_MLDSA_SIGNATURE_RANDOMIZER_BYTES]; + BCM_rand_bytes(randomizer, sizeof(randomizer)); + CONSTTIME_SECRET(randomizer, sizeof(randomizer)); + + return bcm_as_approved_status(mldsa_sign_mu( + out_encoded_signature, mldsa::private_key_from_external_44(private_key), + msg_rep, randomizer)); +} + +// ML-DSA pre-hashed API: verifying a message representative. +bcm_status bssl::BCM_mldsa44_verify_message_representative( + const MLDSA44_public_key *public_key, + const uint8_t signature[MLDSA44_SIGNATURE_BYTES], + const uint8_t msg_rep[MLDSA_MU_BYTES]) { + return bcm_as_approved_status(mldsa::mldsa_verify_mu<4, 4>( + mldsa::public_key_from_external_44(public_key), signature, msg_rep)); +} + +// FIPS 204, Algorithm 3 (`ML-DSA.Verify`). +bcm_status bssl::BCM_mldsa44_verify(const MLDSA44_public_key *public_key, + const uint8_t *signature, + const uint8_t *msg, size_t msg_len, + const uint8_t *context, + size_t context_len) { + BSSL_CHECK(context_len <= 255); + const uint8_t context_prefix[2] = {0, static_cast(context_len)}; + return BCM_mldsa44_verify_internal(public_key, signature, msg, msg_len, + context_prefix, sizeof(context_prefix), + context, context_len); +} + +bcm_status bssl::BCM_mldsa44_verify_internal( + const MLDSA44_public_key *public_key, + const uint8_t encoded_signature[MLDSA44_SIGNATURE_BYTES], + const uint8_t *msg, size_t msg_len, const uint8_t *context_prefix, + size_t context_prefix_len, const uint8_t *context, size_t context_len) { + return bcm_as_approved_status(mldsa::mldsa_verify_internal<4, 4>( + mldsa::public_key_from_external_44(public_key), encoded_signature, msg, + msg_len, context_prefix, context_prefix_len, context, context_len)); +} + +bcm_status bssl::BCM_mldsa44_marshal_public_key( + CBB *out, const MLDSA44_public_key *public_key) { + return bcm_as_approved_status(mldsa_marshal_public_key( + out, mldsa::public_key_from_external_44(public_key))); +} + +int bssl::BCM_mldsa44_public_keys_equal(const MLDSA44_public_key *a, + const MLDSA44_public_key *b) { + auto *a_pub = mldsa::public_key_from_external_44(a); + auto *b_pub = mldsa::public_key_from_external_44(b); + // It is sufficient to compare `public_key_hash`. When importing a public key, + // the hash must be computed. When importing a private key in expanded form + // (an internal testing-only API), the hash is provided, but we recompute it + // and check for correctness. + return OPENSSL_memcmp(a_pub->public_key_hash, b_pub->public_key_hash, + sizeof(a_pub->public_key_hash)) == 0; +} + +int bssl::boringssl_self_test_mldsa() { + return mldsa::fips::keygen_self_test() && mldsa::fips::sign_self_test() && + mldsa::fips::verify_self_test(); +} diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/mlkem/fips_known_values.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/mlkem/fips_known_values.inc new file mode 100644 index 00000000..ac5aca6b --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/mlkem/fips_known_values.inc @@ -0,0 +1,411 @@ +const uint8_t kTestEntropy[MLKEM_SEED_BYTES] = { + 0xc8, 0x77, 0x34, 0x04, 0xb3, 0xe5, 0x3e, 0x31, 0x7b, 0xab, 0x41, + 0x08, 0xa8, 0x88, 0x9c, 0x90, 0xbe, 0xfb, 0x38, 0x0f, 0x63, 0x89, + 0x70, 0xbc, 0xdc, 0x33, 0xeb, 0x2d, 0xe2, 0x99, 0x6b, 0x1a}; + +const uint8_t kExpectedPublicKeyBytes[MLKEM768_PUBLIC_KEY_BYTES] = { + 0xcb, 0x0b, 0x33, 0xa2, 0xac, 0xc4, 0x94, 0x56, 0x1a, 0x36, 0x1c, 0x0d, + 0xa3, 0x57, 0x5b, 0x63, 0x6c, 0x0d, 0x1f, 0xe1, 0xa8, 0x36, 0xd5, 0x5d, + 0x38, 0x5c, 0xac, 0xf4, 0x67, 0x39, 0x9a, 0x12, 0x5b, 0xef, 0xa1, 0x0a, + 0x57, 0x76, 0x87, 0x83, 0xaa, 0xaf, 0x1d, 0x9c, 0xce, 0x2b, 0x78, 0x9b, + 0x40, 0x82, 0x1e, 0x34, 0xb3, 0x55, 0x2d, 0xd0, 0x20, 0xcd, 0x5b, 0x46, + 0x8d, 0xda, 0xb8, 0x83, 0xa8, 0xab, 0xfb, 0x36, 0x45, 0xcb, 0x40, 0xae, + 0x69, 0x77, 0x03, 0x22, 0xa8, 0xb4, 0xaa, 0x17, 0x53, 0x90, 0x05, 0x6a, + 0x69, 0xb9, 0xc5, 0x2d, 0xbc, 0x9a, 0x81, 0xf6, 0x2a, 0x3c, 0x57, 0x96, + 0x8c, 0xb2, 0x72, 0xa7, 0xd4, 0x84, 0x77, 0xf9, 0x0b, 0x80, 0xe7, 0x1e, + 0x75, 0x61, 0x0e, 0xf9, 0xb0, 0xcf, 0x4c, 0x03, 0xca, 0x30, 0x45, 0x50, + 0x25, 0x82, 0x56, 0x02, 0xbb, 0x58, 0xab, 0x99, 0xc7, 0x8d, 0xd5, 0x37, + 0x12, 0xc8, 0x36, 0x5b, 0x00, 0x5f, 0x91, 0xf6, 0x2d, 0x9b, 0x91, 0xc2, + 0x3e, 0x75, 0x56, 0x83, 0xd2, 0xaa, 0xd4, 0x03, 0xcd, 0xe8, 0xe8, 0x3f, + 0x09, 0xc1, 0x8e, 0x84, 0xb1, 0x75, 0x85, 0x06, 0xa7, 0x4a, 0x40, 0xc2, + 0xc9, 0x90, 0xb0, 0x0f, 0x59, 0x84, 0xe5, 0xf7, 0xa8, 0xd8, 0x35, 0x33, + 0xa5, 0x82, 0x4e, 0xf6, 0xb5, 0xaf, 0xd5, 0xaa, 0xbb, 0x52, 0x30, 0x0b, + 0xb1, 0x67, 0x7b, 0xbb, 0xdc, 0x38, 0x58, 0xf4, 0x2f, 0xe4, 0xeb, 0x47, + 0xf0, 0x49, 0x76, 0x45, 0x10, 0x02, 0x19, 0xa7, 0xc6, 0x1f, 0x8a, 0x71, + 0xda, 0x51, 0x61, 0x79, 0xc4, 0x10, 0xeb, 0x3a, 0x11, 0xd9, 0x93, 0x1d, + 0x83, 0x81, 0x48, 0x3d, 0x68, 0x35, 0xff, 0xe3, 0xa6, 0xa8, 0x40, 0x74, + 0xdb, 0x7c, 0xb4, 0xb2, 0x05, 0x89, 0xc8, 0x09, 0x42, 0x27, 0x28, 0x55, + 0x01, 0x57, 0xc9, 0xf9, 0xfa, 0x36, 0xd3, 0x5c, 0x51, 0x40, 0xca, 0x1e, + 0x34, 0xc8, 0xb9, 0x27, 0xf1, 0x15, 0xc9, 0xa4, 0x18, 0x9c, 0xa8, 0x4c, + 0x55, 0xf8, 0x4d, 0x90, 0xbc, 0x88, 0xd1, 0x46, 0x01, 0x80, 0x96, 0x54, + 0x8d, 0x01, 0x6e, 0xe4, 0x26, 0x0c, 0x7a, 0x08, 0x3d, 0x7c, 0x26, 0x66, + 0xb1, 0xd1, 0x15, 0xc7, 0xc0, 0x0b, 0x06, 0x92, 0x9c, 0x26, 0xa6, 0x6c, + 0x3a, 0x46, 0x47, 0x15, 0x37, 0xb0, 0x0a, 0xc1, 0x5d, 0xe0, 0x51, 0xae, + 0x17, 0x87, 0x2f, 0x75, 0x2c, 0x64, 0xd5, 0x39, 0x09, 0xe6, 0xd0, 0x7c, + 0x3d, 0x79, 0x47, 0x78, 0x0a, 0x82, 0xc9, 0xba, 0x37, 0x07, 0x93, 0x94, + 0xa4, 0x45, 0x7c, 0x07, 0x69, 0x24, 0x1d, 0xc9, 0x75, 0x41, 0x6b, 0xc1, + 0x42, 0x28, 0x06, 0xe3, 0xfc, 0x7b, 0xd2, 0xf8, 0xbf, 0xe7, 0x5a, 0xc2, + 0xc0, 0x81, 0x63, 0xf3, 0x84, 0x32, 0x31, 0x4a, 0x8d, 0x6b, 0xe3, 0x3e, + 0x22, 0x67, 0x9a, 0x3a, 0x96, 0x09, 0xa6, 0xf9, 0x53, 0x40, 0x41, 0x2a, + 0x04, 0xa7, 0xc5, 0x7b, 0x86, 0xcd, 0xed, 0xec, 0xae, 0xfd, 0xc7, 0x11, + 0x48, 0x56, 0x77, 0x0b, 0xb7, 0xbb, 0xaf, 0xfb, 0x6c, 0x9e, 0xd6, 0x5c, + 0xbc, 0xf7, 0x9a, 0x75, 0xb5, 0xb2, 0x20, 0xd9, 0x60, 0x90, 0x65, 0x02, + 0xf9, 0x16, 0x34, 0xdf, 0x0b, 0x16, 0x2a, 0x97, 0x00, 0x5d, 0xc1, 0x65, + 0xc3, 0xb9, 0x1f, 0x2e, 0x85, 0x97, 0xbd, 0xca, 0xaa, 0x1d, 0xf2, 0x4f, + 0x74, 0xe5, 0x56, 0x94, 0xdc, 0x53, 0xbb, 0xc0, 0x75, 0x1c, 0x2b, 0x59, + 0x6b, 0x50, 0x2c, 0x25, 0x4c, 0x78, 0xd7, 0x68, 0x40, 0x0b, 0x91, 0x7a, + 0x93, 0x02, 0x83, 0x5e, 0x6c, 0x03, 0xc7, 0xc4, 0x24, 0x6f, 0x8b, 0xa4, + 0x70, 0x37, 0x1f, 0xe5, 0x33, 0x59, 0xf6, 0xbb, 0x5f, 0xb8, 0x58, 0x50, + 0x62, 0x16, 0x95, 0x2a, 0x88, 0xa3, 0xc6, 0x24, 0x94, 0x4b, 0xb0, 0x03, + 0x8e, 0xe6, 0x50, 0xd1, 0x63, 0xa2, 0xab, 0x00, 0x16, 0xf4, 0x0a, 0x7d, + 0xe6, 0xe0, 0xb9, 0x0c, 0xd8, 0x08, 0xae, 0xf6, 0x80, 0xb7, 0x48, 0xb8, + 0x10, 0xd1, 0x77, 0x57, 0x48, 0x2a, 0xc1, 0xf1, 0x4e, 0x61, 0xb4, 0x06, + 0x5a, 0xa1, 0xba, 0x32, 0x4a, 0x9a, 0xab, 0x8c, 0xa8, 0xe3, 0xa0, 0x68, + 0x39, 0xa3, 0x25, 0x55, 0x48, 0xcd, 0x12, 0x98, 0x14, 0x1b, 0x39, 0x5b, + 0xf4, 0x88, 0xbe, 0x5f, 0xac, 0xba, 0x18, 0x20, 0x74, 0x2c, 0xa1, 0x0b, + 0xfc, 0xf1, 0x00, 0x85, 0x24, 0x27, 0x3d, 0x80, 0xb6, 0x30, 0x42, 0x7b, + 0x74, 0xb0, 0xbf, 0x87, 0x51, 0x9b, 0xa8, 0x1c, 0x79, 0xbd, 0x50, 0x85, + 0x66, 0xe1, 0x93, 0xdd, 0xc5, 0x5d, 0x5d, 0xd0, 0xbe, 0xcb, 0x90, 0x36, + 0xf8, 0xc6, 0xc2, 0xea, 0xea, 0x40, 0xce, 0xa7, 0xb0, 0xae, 0xc5, 0x44, + 0x3a, 0x27, 0xc5, 0x4a, 0xf0, 0x21, 0x4f, 0xf6, 0x63, 0xb1, 0x8c, 0x20, + 0x76, 0x65, 0xb5, 0x79, 0x55, 0x10, 0xa5, 0xa7, 0x4b, 0x57, 0x96, 0xb3, + 0x03, 0xe6, 0xa8, 0x93, 0xf5, 0xc5, 0xca, 0xe0, 0x1a, 0x23, 0x30, 0x6d, + 0x09, 0x07, 0x81, 0x5e, 0x05, 0xc6, 0x1b, 0x7a, 0x0e, 0xde, 0xf3, 0x00, + 0x91, 0xf3, 0xbb, 0x4b, 0xa6, 0x8e, 0x96, 0xc3, 0x3a, 0xc8, 0x72, 0x19, + 0x23, 0x23, 0xc7, 0x94, 0x46, 0x75, 0xa2, 0xc5, 0x9e, 0xa3, 0x15, 0x86, + 0xb4, 0xa7, 0x95, 0xda, 0x16, 0xae, 0x42, 0xe8, 0xcc, 0xf6, 0x41, 0xbc, + 0x9c, 0xe8, 0x07, 0xc9, 0x05, 0x3c, 0x74, 0xb2, 0xad, 0x77, 0xc4, 0x08, + 0x56, 0x78, 0xb8, 0x65, 0x2a, 0x33, 0x39, 0x82, 0x16, 0x3c, 0x2b, 0x73, + 0x41, 0x2a, 0xbc, 0xc8, 0x36, 0x23, 0x2c, 0x23, 0x29, 0xce, 0x94, 0x8a, + 0xba, 0x13, 0x3f, 0xfa, 0xcc, 0x6e, 0x17, 0x40, 0xb0, 0xb4, 0x9c, 0xae, + 0xf9, 0x72, 0x40, 0xf7, 0x2a, 0xaf, 0x00, 0x17, 0x7e, 0x88, 0x44, 0x4e, + 0x32, 0xa4, 0x80, 0x96, 0x53, 0x20, 0xe4, 0xaa, 0x18, 0x9c, 0x69, 0x63, + 0xdb, 0x81, 0x73, 0x0e, 0x64, 0x40, 0x12, 0xc1, 0x26, 0x0e, 0xac, 0x4d, + 0x38, 0xa6, 0x4c, 0x05, 0xeb, 0x42, 0x1f, 0x88, 0x6e, 0x6c, 0xa3, 0x98, + 0x95, 0xc3, 0x5a, 0x31, 0xfc, 0x8a, 0x7c, 0xd6, 0xa5, 0x6c, 0x5a, 0xc9, + 0xf5, 0xf2, 0xb0, 0xf7, 0x05, 0x8d, 0x3a, 0x0b, 0x3f, 0x4d, 0x1b, 0x0e, + 0x38, 0x7b, 0x1c, 0xe5, 0xd0, 0x75, 0x40, 0x77, 0xc2, 0xe0, 0x8b, 0xa9, + 0xfb, 0xa6, 0xa7, 0x13, 0xf0, 0xbc, 0x0c, 0x13, 0xb0, 0x70, 0x3a, 0x2f, + 0x20, 0xe7, 0x38, 0xd8, 0x82, 0xa4, 0xc0, 0x06, 0x96, 0x95, 0x75, 0x5c, + 0xbc, 0x68, 0xce, 0xee, 0xa6, 0x44, 0xbb, 0xf2, 0x62, 0x14, 0x43, 0x10, + 0xe6, 0x0b, 0x5c, 0x66, 0x02, 0xbf, 0x38, 0xe9, 0x8f, 0x19, 0x69, 0x6c, + 0x08, 0xfa, 0x93, 0x23, 0xf1, 0x35, 0x5f, 0x33, 0xcf, 0xe2, 0x32, 0x11, + 0xda, 0x31, 0xbb, 0xd8, 0xf5, 0x7e, 0x55, 0xc3, 0x6a, 0xa3, 0x04, 0x8c, + 0xef, 0x50, 0x67, 0x0f, 0xe9, 0xbb, 0x11, 0x6b, 0xca, 0x5a, 0x23, 0x15, + 0xf7, 0x52, 0x8c, 0x69, 0xbb, 0x2d, 0x26, 0xd3, 0x78, 0x32, 0x33, 0x9b, + 0x1d, 0x02, 0x7c, 0x22, 0x4b, 0x57, 0x19, 0xec, 0xcd, 0x16, 0x63, 0x5d, + 0x1f, 0x0c, 0x67, 0xda, 0x6a, 0xc7, 0x2c, 0xf1, 0x0b, 0xcf, 0x92, 0x10, + 0xcb, 0x78, 0x57, 0x67, 0x61, 0x0e, 0xb3, 0x55, 0xb0, 0x17, 0x32, 0x4e, + 0x95, 0xf1, 0xcb, 0xb5, 0xdb, 0x5d, 0x8e, 0x38, 0x97, 0x28, 0x46, 0x1e, + 0x37, 0x4b, 0x5c, 0x03, 0xf4, 0x84, 0x0c, 0xfc, 0x49, 0x3b, 0xd2, 0xc6, + 0x97, 0xd4, 0x4f, 0xef, 0xe6, 0x5c, 0xb2, 0x96, 0x8e, 0xbc, 0x18, 0x9f, + 0xec, 0x8a, 0x67, 0x53, 0xe8, 0x2a, 0x41, 0x5c, 0x6e, 0xfe, 0xca, 0x1a, + 0xd0, 0x03, 0x4f, 0xe8, 0xd9, 0xb0, 0xe2, 0xa1, 0x6c, 0x32, 0xd5, 0x37, + 0x68, 0x9c, 0x6b, 0x30, 0x87, 0xb4, 0x6e, 0xa8, 0xc5, 0x45, 0xe4, 0x74, + 0x4a, 0x80, 0x02, 0x84, 0x78, 0x0e, 0x2c, 0x9c, 0x37, 0x07, 0x26, 0x31, + 0x88, 0x0a, 0x89, 0xd2, 0xba, 0x8b, 0x09, 0xb2, 0x16, 0x7b, 0x23, 0xa8, + 0x0c, 0x82, 0xc4, 0x22, 0xa2, 0x21, 0x2d, 0xa4, 0xa0, 0xeb, 0xe4, 0xa6, + 0xd4, 0x16, 0xa0, 0xa7, 0x19, 0x8b, 0x8f, 0x87, 0x9b, 0x53, 0x6c, 0xba, + 0x14, 0xa7, 0xc4, 0x64, 0x08, 0xb4, 0x68, 0xda, 0x85, 0xa6, 0x47, 0xbc, + 0x58, 0x34, 0xcd, 0x60, 0x43, 0xad, 0x14, 0xd4, 0xca, 0xd7, 0xb1, 0x6c, + 0xc0, 0x05, 0x68, 0xaf, 0xa7, 0x08, 0x9d, 0x6a, 0xb0, 0x70, 0x96, 0x81, + 0xb8, 0x55, 0xbf, 0xa1, 0xcc, 0xb1, 0x37, 0xe0, 0x94, 0x42, 0x05, 0x0c, + 0x83, 0xef, 0x6d, 0xf0, 0x4e, 0xba, 0xe6, 0x78, 0x49, 0xaf, 0x1f, 0x88, + 0xf0, 0x18, 0x0c, 0x17, 0x66, 0x92, 0xd8, 0x50, 0x57, 0x3b, 0x8e, 0xc9, + 0xd5, 0x8c, 0xfb, 0x9b, 0x78, 0x65, 0x01, 0x76}; + +const uint8_t kExpectedPrivateKeyBytes[2400] = { + 0xd8, 0xc9, 0x39, 0x7c, 0x31, 0x30, 0xd8, 0xec, 0xb4, 0x11, 0xa6, 0x8e, + 0xfc, 0xc8, 0x9a, 0x55, 0x3c, 0xb7, 0xe6, 0x81, 0x7e, 0x02, 0x88, 0xbd, + 0x06, 0x91, 0x60, 0x9b, 0xf5, 0x57, 0x6a, 0xf8, 0x73, 0x9e, 0x52, 0xa8, + 0x03, 0xf0, 0x97, 0xb4, 0x22, 0xb7, 0x02, 0x23, 0xcd, 0x3e, 0xa1, 0x03, + 0x20, 0x66, 0x6e, 0x20, 0x20, 0xcb, 0x42, 0xec, 0xb6, 0xc2, 0x14, 0x2c, + 0xe7, 0xa8, 0x88, 0x3d, 0xd2, 0x26, 0x9c, 0xf7, 0xb3, 0x4f, 0x00, 0x27, + 0x61, 0xc6, 0x10, 0xb2, 0x72, 0x34, 0x39, 0xf1, 0x79, 0x03, 0xcc, 0x06, + 0xd2, 0xe4, 0x29, 0x57, 0x91, 0x2f, 0x0d, 0x45, 0x19, 0x30, 0x27, 0x47, + 0xcc, 0xba, 0xbe, 0x19, 0x01, 0x1a, 0xbb, 0xd8, 0xcb, 0x74, 0xca, 0x4a, + 0xfa, 0x32, 0x2f, 0xb8, 0xbb, 0x5c, 0x19, 0x2a, 0xbf, 0x31, 0x0a, 0x82, + 0xf3, 0x29, 0x74, 0x30, 0xa4, 0x95, 0x4c, 0x42, 0x59, 0x8c, 0xb3, 0xcb, + 0xfe, 0xa9, 0xb4, 0x2e, 0x60, 0x71, 0x64, 0x51, 0x6d, 0xf9, 0x73, 0x5b, + 0xf5, 0x59, 0x9b, 0xf5, 0xd9, 0x9d, 0x3f, 0x86, 0x3a, 0x50, 0x6c, 0x23, + 0x8c, 0x96, 0xc0, 0x5e, 0x7c, 0x48, 0x43, 0xec, 0x08, 0xf5, 0xf7, 0x7e, + 0x6b, 0x54, 0x84, 0xb2, 0x6c, 0x52, 0xd5, 0x2b, 0x38, 0x85, 0xf4, 0x40, + 0x36, 0x09, 0x2f, 0xe6, 0xd0, 0x9e, 0xe6, 0xb6, 0x96, 0x7a, 0xe1, 0xc3, + 0xf7, 0xfa, 0x89, 0xc6, 0x75, 0x6f, 0x65, 0xea, 0x4a, 0x6d, 0x55, 0x33, + 0xe2, 0xc6, 0x30, 0xfb, 0x7b, 0xbd, 0xcb, 0x33, 0x4d, 0xd6, 0x84, 0x1b, + 0x28, 0x77, 0x60, 0xbf, 0x4b, 0x82, 0xd0, 0xb0, 0xc5, 0x88, 0x0c, 0x51, + 0x00, 0x22, 0x5e, 0xd9, 0x41, 0x2e, 0x7e, 0x43, 0xa6, 0x9d, 0x34, 0x5d, + 0x24, 0x80, 0xad, 0x7f, 0xd3, 0xae, 0xc7, 0x5a, 0x51, 0x74, 0x06, 0xc0, + 0x6f, 0x04, 0xae, 0x9b, 0x79, 0x6e, 0x35, 0xfa, 0x0d, 0xf3, 0xda, 0xa4, + 0xfa, 0x38, 0x4a, 0xee, 0xb3, 0xa4, 0x87, 0xa7, 0x27, 0xe2, 0x02, 0x2a, + 0x29, 0x27, 0xcf, 0xca, 0x4a, 0x20, 0x01, 0x15, 0x3d, 0x12, 0xc7, 0xcc, + 0x74, 0x99, 0x17, 0xa6, 0x7b, 0x04, 0xd7, 0xea, 0x64, 0x88, 0xa3, 0x54, + 0xb5, 0xc2, 0xa3, 0xea, 0x69, 0x94, 0xb9, 0xc3, 0x45, 0xf8, 0x2b, 0x3c, + 0xe5, 0xc1, 0x25, 0xf6, 0xc9, 0x82, 0xe3, 0x45, 0x25, 0xca, 0x71, 0x3d, + 0x73, 0x10, 0x99, 0xa5, 0xb5, 0x79, 0xdc, 0x61, 0x8f, 0x04, 0x3c, 0x61, + 0x6b, 0x90, 0x4d, 0x83, 0xa3, 0x0d, 0xb4, 0xba, 0xb7, 0x3b, 0x81, 0xca, + 0xbb, 0x59, 0x16, 0x46, 0xf4, 0x75, 0x7c, 0xaa, 0x0f, 0x90, 0xec, 0x37, + 0xa4, 0x50, 0xa8, 0x41, 0xb4, 0x33, 0xd2, 0xb7, 0x28, 0xe1, 0xda, 0x74, + 0x36, 0x3a, 0xa6, 0x96, 0x76, 0x06, 0x67, 0xd3, 0x8e, 0xda, 0xd5, 0x29, + 0x24, 0x1a, 0xbe, 0x82, 0x83, 0x6b, 0x3a, 0x90, 0xc1, 0x86, 0x34, 0x2d, + 0xd8, 0xa3, 0xa5, 0x7e, 0xe6, 0xca, 0x3f, 0xc5, 0xbf, 0xba, 0x24, 0x14, + 0xd2, 0xfc, 0x3f, 0x97, 0x8c, 0xca, 0x59, 0xa5, 0x52, 0xf1, 0x8c, 0x62, + 0x8d, 0x8a, 0x7d, 0x1b, 0x35, 0x76, 0x79, 0x98, 0x39, 0x57, 0x53, 0x1f, + 0x78, 0x82, 0x7d, 0xcd, 0x9c, 0xab, 0xb3, 0x12, 0x52, 0x86, 0x87, 0xbf, + 0x01, 0x12, 0x58, 0x45, 0x37, 0x75, 0x1a, 0xe0, 0x03, 0xbd, 0x67, 0x4c, + 0x76, 0xfa, 0x06, 0x59, 0xa2, 0x1f, 0x48, 0x73, 0x7f, 0x0c, 0x90, 0xc1, + 0x82, 0xc0, 0x98, 0x2f, 0x6a, 0x1c, 0x6f, 0x6c, 0x98, 0x70, 0x16, 0x8e, + 0x8c, 0x5b, 0x60, 0x92, 0x42, 0x59, 0xd6, 0xb2, 0x13, 0x7a, 0x11, 0xb6, + 0x15, 0x1b, 0x07, 0x50, 0x52, 0x73, 0x86, 0xbc, 0x3a, 0xff, 0x66, 0x71, + 0x57, 0xf8, 0x89, 0x7a, 0x3a, 0x95, 0xc5, 0xa1, 0x31, 0x48, 0x15, 0xc9, + 0xe0, 0x4b, 0x41, 0xb6, 0x07, 0x5a, 0x70, 0x88, 0x11, 0xce, 0xdc, 0xa7, + 0x84, 0x23, 0x85, 0x96, 0xd8, 0x20, 0x9f, 0x89, 0x42, 0xbc, 0x0b, 0xd0, + 0xd9, 0x11, 0x9f, 0x2f, 0x71, 0x37, 0xa2, 0x10, 0x98, 0x95, 0xa7, 0x1f, + 0x99, 0x48, 0x8e, 0x5b, 0x40, 0x65, 0x9f, 0x08, 0x4e, 0x04, 0x16, 0x35, + 0xc8, 0x56, 0xa1, 0x02, 0xa1, 0xaf, 0x0e, 0x5b, 0xaf, 0x02, 0x66, 0x2e, + 0xc8, 0xa5, 0x49, 0xe7, 0xa4, 0x6b, 0x03, 0xe2, 0x42, 0xb3, 0x37, 0x76, + 0x2c, 0x89, 0x00, 0x76, 0x83, 0xb3, 0x93, 0xdc, 0x78, 0x56, 0xc9, 0x02, + 0xf1, 0xd3, 0x92, 0xe5, 0x14, 0x36, 0xba, 0x37, 0x1d, 0x86, 0x87, 0x81, + 0x5f, 0x30, 0x16, 0x7f, 0xdb, 0x76, 0xe2, 0x46, 0x3d, 0x32, 0xe8, 0x47, + 0x35, 0x5b, 0x68, 0x39, 0x70, 0xa3, 0xc2, 0xb8, 0xb3, 0x6e, 0xd0, 0x22, + 0x6b, 0x39, 0x9c, 0xd9, 0xa3, 0x93, 0x69, 0xbc, 0xcb, 0xe0, 0xbc, 0x82, + 0x1b, 0xfb, 0x9f, 0x72, 0x17, 0x40, 0x72, 0xeb, 0xb2, 0x97, 0x31, 0x66, + 0x18, 0x48, 0x9a, 0xe5, 0x3a, 0x2a, 0x41, 0x13, 0x3e, 0xfc, 0xfb, 0xb4, + 0xb0, 0x96, 0x6e, 0x53, 0x37, 0x18, 0xbb, 0x26, 0x1d, 0xbe, 0x33, 0x0f, + 0x06, 0x8b, 0x8c, 0xb1, 0xfc, 0x8c, 0x24, 0x19, 0x8d, 0x7d, 0x76, 0x52, + 0x35, 0x75, 0x71, 0x36, 0x61, 0x7d, 0x75, 0x3a, 0x31, 0x9a, 0x16, 0x05, + 0x2d, 0x51, 0x63, 0x6f, 0x07, 0x64, 0xfd, 0x80, 0x16, 0x2d, 0xa3, 0x3a, + 0x15, 0xca, 0xaa, 0x76, 0xec, 0x2f, 0x91, 0x47, 0xb2, 0x29, 0x61, 0x04, + 0x80, 0x20, 0x8d, 0x3c, 0x31, 0xa6, 0x4f, 0x8b, 0xc8, 0xc0, 0x71, 0xbb, + 0x0a, 0xec, 0xbc, 0xdf, 0xdc, 0x91, 0x8c, 0xb9, 0x80, 0xb7, 0x67, 0xa9, + 0x7f, 0x30, 0x18, 0x4e, 0xd3, 0x68, 0x27, 0x50, 0x15, 0xad, 0x8c, 0x6a, + 0xab, 0xc9, 0xbe, 0xad, 0x41, 0x4b, 0xcd, 0x23, 0x73, 0x9f, 0x77, 0x58, + 0xe3, 0xd8, 0x2e, 0x16, 0xcb, 0xa0, 0x17, 0x89, 0x51, 0x31, 0x53, 0x01, + 0xa8, 0xf1, 0x9b, 0x61, 0xc3, 0x0a, 0x5b, 0x0c, 0x70, 0x36, 0x48, 0x1b, + 0xae, 0x17, 0x51, 0x1f, 0xc7, 0x7b, 0xce, 0xd4, 0x45, 0xff, 0xea, 0xb0, + 0x5f, 0x48, 0x07, 0x4f, 0x79, 0x26, 0x5c, 0xb6, 0xce, 0x4c, 0xc4, 0x02, + 0xd1, 0x31, 0x88, 0xa9, 0xc0, 0x53, 0x6a, 0x42, 0x6f, 0x9c, 0x32, 0xaa, + 0x86, 0xec, 0x25, 0xa7, 0x5b, 0x31, 0x68, 0xc9, 0xa9, 0xd8, 0x2c, 0x70, + 0xa0, 0x02, 0x31, 0x52, 0x8a, 0x2c, 0xc0, 0x0a, 0xbe, 0x8c, 0x59, 0x6c, + 0x72, 0x42, 0x21, 0xcb, 0x44, 0x07, 0x02, 0x27, 0xa0, 0x71, 0xa3, 0x7f, + 0xe3, 0x97, 0x24, 0x70, 0x47, 0x4d, 0x10, 0xfc, 0x54, 0x83, 0xdc, 0x44, + 0x09, 0x36, 0x23, 0x4a, 0x26, 0x95, 0x60, 0x96, 0xa4, 0x11, 0x1b, 0x18, + 0x9d, 0x01, 0x9c, 0x8c, 0xd7, 0x37, 0x60, 0x08, 0x02, 0xef, 0xe3, 0x81, + 0xf3, 0x48, 0x5c, 0x9c, 0xac, 0x4f, 0xb6, 0xc7, 0x66, 0xd6, 0xda, 0x25, + 0x78, 0x4a, 0xca, 0x91, 0xf1, 0x16, 0x75, 0x69, 0x8b, 0x09, 0x63, 0x0d, + 0x74, 0x49, 0x57, 0x33, 0xe1, 0x23, 0x87, 0xc5, 0x0e, 0x85, 0x27, 0x1e, + 0x5a, 0xfa, 0x3f, 0xa8, 0x82, 0xbc, 0x49, 0xc7, 0x99, 0x15, 0xe1, 0x2f, + 0x04, 0x36, 0x88, 0xd4, 0xa1, 0x9a, 0xe5, 0xb3, 0x70, 0x95, 0x85, 0x43, + 0x76, 0xb9, 0x7d, 0x3b, 0x9c, 0x61, 0xf3, 0x30, 0x59, 0x4e, 0x2a, 0xc6, + 0x3f, 0x52, 0x35, 0x81, 0x43, 0x61, 0x72, 0xc0, 0x89, 0x98, 0x67, 0x1e, + 0x6f, 0xec, 0xc6, 0x2a, 0x9a, 0x14, 0x36, 0x34, 0x4c, 0x9f, 0xfb, 0x2e, + 0xd1, 0xd2, 0x4e, 0x6b, 0xb9, 0xc9, 0x56, 0x74, 0xbe, 0xab, 0xa4, 0x7c, + 0x48, 0x84, 0x07, 0xf6, 0x04, 0xb1, 0x89, 0x0b, 0x13, 0x79, 0x13, 0xb5, + 0x31, 0xd6, 0x2c, 0x40, 0x47, 0xbd, 0xba, 0x37, 0xb1, 0x65, 0x7c, 0xb3, + 0xa3, 0x45, 0x1e, 0x0f, 0x41, 0x62, 0x07, 0xf9, 0x1e, 0x25, 0xa5, 0x78, + 0x47, 0xd2, 0xa6, 0x4b, 0x20, 0x7b, 0x9b, 0x39, 0x07, 0x09, 0xf3, 0x9e, + 0x09, 0xfb, 0xac, 0x87, 0xb6, 0xb5, 0x9b, 0xd8, 0x09, 0xa3, 0xd6, 0x69, + 0xb3, 0x3a, 0x87, 0x09, 0xb0, 0x19, 0xb3, 0xc1, 0x47, 0x8e, 0xd7, 0x3a, + 0x6e, 0xb5, 0x48, 0x89, 0x56, 0x87, 0x60, 0xb1, 0xba, 0x52, 0xd5, 0x94, + 0x22, 0x54, 0xbd, 0x7c, 0xf1, 0xa4, 0x54, 0xaa, 0x38, 0x5c, 0x76, 0xa8, + 0x52, 0x19, 0x97, 0x9a, 0x71, 0x47, 0x6c, 0xa0, 0x39, 0xd1, 0x0b, 0xd0, + 0xa6, 0xb3, 0x65, 0xdc, 0xbc, 0xa4, 0x4d, 0x62, 0x44, 0xb2, 0x47, 0x5e, + 0x77, 0x77, 0x32, 0x2f, 0x78, 0xa6, 0x97, 0xdb, 0xb5, 0xba, 0x3b, 0x4a, + 0xcb, 0x0b, 0x33, 0xa2, 0xac, 0xc4, 0x94, 0x56, 0x1a, 0x36, 0x1c, 0x0d, + 0xa3, 0x57, 0x5b, 0x63, 0x6c, 0x0d, 0x1f, 0xe1, 0xa8, 0x36, 0xd5, 0x5d, + 0x38, 0x5c, 0xac, 0xf4, 0x67, 0x39, 0x9a, 0x12, 0x5b, 0xef, 0xa1, 0x0a, + 0x57, 0x76, 0x87, 0x83, 0xaa, 0xaf, 0x1d, 0x9c, 0xce, 0x2b, 0x78, 0x9b, + 0x40, 0x82, 0x1e, 0x34, 0xb3, 0x55, 0x2d, 0xd0, 0x20, 0xcd, 0x5b, 0x46, + 0x8d, 0xda, 0xb8, 0x83, 0xa8, 0xab, 0xfb, 0x36, 0x45, 0xcb, 0x40, 0xae, + 0x69, 0x77, 0x03, 0x22, 0xa8, 0xb4, 0xaa, 0x17, 0x53, 0x90, 0x05, 0x6a, + 0x69, 0xb9, 0xc5, 0x2d, 0xbc, 0x9a, 0x81, 0xf6, 0x2a, 0x3c, 0x57, 0x96, + 0x8c, 0xb2, 0x72, 0xa7, 0xd4, 0x84, 0x77, 0xf9, 0x0b, 0x80, 0xe7, 0x1e, + 0x75, 0x61, 0x0e, 0xf9, 0xb0, 0xcf, 0x4c, 0x03, 0xca, 0x30, 0x45, 0x50, + 0x25, 0x82, 0x56, 0x02, 0xbb, 0x58, 0xab, 0x99, 0xc7, 0x8d, 0xd5, 0x37, + 0x12, 0xc8, 0x36, 0x5b, 0x00, 0x5f, 0x91, 0xf6, 0x2d, 0x9b, 0x91, 0xc2, + 0x3e, 0x75, 0x56, 0x83, 0xd2, 0xaa, 0xd4, 0x03, 0xcd, 0xe8, 0xe8, 0x3f, + 0x09, 0xc1, 0x8e, 0x84, 0xb1, 0x75, 0x85, 0x06, 0xa7, 0x4a, 0x40, 0xc2, + 0xc9, 0x90, 0xb0, 0x0f, 0x59, 0x84, 0xe5, 0xf7, 0xa8, 0xd8, 0x35, 0x33, + 0xa5, 0x82, 0x4e, 0xf6, 0xb5, 0xaf, 0xd5, 0xaa, 0xbb, 0x52, 0x30, 0x0b, + 0xb1, 0x67, 0x7b, 0xbb, 0xdc, 0x38, 0x58, 0xf4, 0x2f, 0xe4, 0xeb, 0x47, + 0xf0, 0x49, 0x76, 0x45, 0x10, 0x02, 0x19, 0xa7, 0xc6, 0x1f, 0x8a, 0x71, + 0xda, 0x51, 0x61, 0x79, 0xc4, 0x10, 0xeb, 0x3a, 0x11, 0xd9, 0x93, 0x1d, + 0x83, 0x81, 0x48, 0x3d, 0x68, 0x35, 0xff, 0xe3, 0xa6, 0xa8, 0x40, 0x74, + 0xdb, 0x7c, 0xb4, 0xb2, 0x05, 0x89, 0xc8, 0x09, 0x42, 0x27, 0x28, 0x55, + 0x01, 0x57, 0xc9, 0xf9, 0xfa, 0x36, 0xd3, 0x5c, 0x51, 0x40, 0xca, 0x1e, + 0x34, 0xc8, 0xb9, 0x27, 0xf1, 0x15, 0xc9, 0xa4, 0x18, 0x9c, 0xa8, 0x4c, + 0x55, 0xf8, 0x4d, 0x90, 0xbc, 0x88, 0xd1, 0x46, 0x01, 0x80, 0x96, 0x54, + 0x8d, 0x01, 0x6e, 0xe4, 0x26, 0x0c, 0x7a, 0x08, 0x3d, 0x7c, 0x26, 0x66, + 0xb1, 0xd1, 0x15, 0xc7, 0xc0, 0x0b, 0x06, 0x92, 0x9c, 0x26, 0xa6, 0x6c, + 0x3a, 0x46, 0x47, 0x15, 0x37, 0xb0, 0x0a, 0xc1, 0x5d, 0xe0, 0x51, 0xae, + 0x17, 0x87, 0x2f, 0x75, 0x2c, 0x64, 0xd5, 0x39, 0x09, 0xe6, 0xd0, 0x7c, + 0x3d, 0x79, 0x47, 0x78, 0x0a, 0x82, 0xc9, 0xba, 0x37, 0x07, 0x93, 0x94, + 0xa4, 0x45, 0x7c, 0x07, 0x69, 0x24, 0x1d, 0xc9, 0x75, 0x41, 0x6b, 0xc1, + 0x42, 0x28, 0x06, 0xe3, 0xfc, 0x7b, 0xd2, 0xf8, 0xbf, 0xe7, 0x5a, 0xc2, + 0xc0, 0x81, 0x63, 0xf3, 0x84, 0x32, 0x31, 0x4a, 0x8d, 0x6b, 0xe3, 0x3e, + 0x22, 0x67, 0x9a, 0x3a, 0x96, 0x09, 0xa6, 0xf9, 0x53, 0x40, 0x41, 0x2a, + 0x04, 0xa7, 0xc5, 0x7b, 0x86, 0xcd, 0xed, 0xec, 0xae, 0xfd, 0xc7, 0x11, + 0x48, 0x56, 0x77, 0x0b, 0xb7, 0xbb, 0xaf, 0xfb, 0x6c, 0x9e, 0xd6, 0x5c, + 0xbc, 0xf7, 0x9a, 0x75, 0xb5, 0xb2, 0x20, 0xd9, 0x60, 0x90, 0x65, 0x02, + 0xf9, 0x16, 0x34, 0xdf, 0x0b, 0x16, 0x2a, 0x97, 0x00, 0x5d, 0xc1, 0x65, + 0xc3, 0xb9, 0x1f, 0x2e, 0x85, 0x97, 0xbd, 0xca, 0xaa, 0x1d, 0xf2, 0x4f, + 0x74, 0xe5, 0x56, 0x94, 0xdc, 0x53, 0xbb, 0xc0, 0x75, 0x1c, 0x2b, 0x59, + 0x6b, 0x50, 0x2c, 0x25, 0x4c, 0x78, 0xd7, 0x68, 0x40, 0x0b, 0x91, 0x7a, + 0x93, 0x02, 0x83, 0x5e, 0x6c, 0x03, 0xc7, 0xc4, 0x24, 0x6f, 0x8b, 0xa4, + 0x70, 0x37, 0x1f, 0xe5, 0x33, 0x59, 0xf6, 0xbb, 0x5f, 0xb8, 0x58, 0x50, + 0x62, 0x16, 0x95, 0x2a, 0x88, 0xa3, 0xc6, 0x24, 0x94, 0x4b, 0xb0, 0x03, + 0x8e, 0xe6, 0x50, 0xd1, 0x63, 0xa2, 0xab, 0x00, 0x16, 0xf4, 0x0a, 0x7d, + 0xe6, 0xe0, 0xb9, 0x0c, 0xd8, 0x08, 0xae, 0xf6, 0x80, 0xb7, 0x48, 0xb8, + 0x10, 0xd1, 0x77, 0x57, 0x48, 0x2a, 0xc1, 0xf1, 0x4e, 0x61, 0xb4, 0x06, + 0x5a, 0xa1, 0xba, 0x32, 0x4a, 0x9a, 0xab, 0x8c, 0xa8, 0xe3, 0xa0, 0x68, + 0x39, 0xa3, 0x25, 0x55, 0x48, 0xcd, 0x12, 0x98, 0x14, 0x1b, 0x39, 0x5b, + 0xf4, 0x88, 0xbe, 0x5f, 0xac, 0xba, 0x18, 0x20, 0x74, 0x2c, 0xa1, 0x0b, + 0xfc, 0xf1, 0x00, 0x85, 0x24, 0x27, 0x3d, 0x80, 0xb6, 0x30, 0x42, 0x7b, + 0x74, 0xb0, 0xbf, 0x87, 0x51, 0x9b, 0xa8, 0x1c, 0x79, 0xbd, 0x50, 0x85, + 0x66, 0xe1, 0x93, 0xdd, 0xc5, 0x5d, 0x5d, 0xd0, 0xbe, 0xcb, 0x90, 0x36, + 0xf8, 0xc6, 0xc2, 0xea, 0xea, 0x40, 0xce, 0xa7, 0xb0, 0xae, 0xc5, 0x44, + 0x3a, 0x27, 0xc5, 0x4a, 0xf0, 0x21, 0x4f, 0xf6, 0x63, 0xb1, 0x8c, 0x20, + 0x76, 0x65, 0xb5, 0x79, 0x55, 0x10, 0xa5, 0xa7, 0x4b, 0x57, 0x96, 0xb3, + 0x03, 0xe6, 0xa8, 0x93, 0xf5, 0xc5, 0xca, 0xe0, 0x1a, 0x23, 0x30, 0x6d, + 0x09, 0x07, 0x81, 0x5e, 0x05, 0xc6, 0x1b, 0x7a, 0x0e, 0xde, 0xf3, 0x00, + 0x91, 0xf3, 0xbb, 0x4b, 0xa6, 0x8e, 0x96, 0xc3, 0x3a, 0xc8, 0x72, 0x19, + 0x23, 0x23, 0xc7, 0x94, 0x46, 0x75, 0xa2, 0xc5, 0x9e, 0xa3, 0x15, 0x86, + 0xb4, 0xa7, 0x95, 0xda, 0x16, 0xae, 0x42, 0xe8, 0xcc, 0xf6, 0x41, 0xbc, + 0x9c, 0xe8, 0x07, 0xc9, 0x05, 0x3c, 0x74, 0xb2, 0xad, 0x77, 0xc4, 0x08, + 0x56, 0x78, 0xb8, 0x65, 0x2a, 0x33, 0x39, 0x82, 0x16, 0x3c, 0x2b, 0x73, + 0x41, 0x2a, 0xbc, 0xc8, 0x36, 0x23, 0x2c, 0x23, 0x29, 0xce, 0x94, 0x8a, + 0xba, 0x13, 0x3f, 0xfa, 0xcc, 0x6e, 0x17, 0x40, 0xb0, 0xb4, 0x9c, 0xae, + 0xf9, 0x72, 0x40, 0xf7, 0x2a, 0xaf, 0x00, 0x17, 0x7e, 0x88, 0x44, 0x4e, + 0x32, 0xa4, 0x80, 0x96, 0x53, 0x20, 0xe4, 0xaa, 0x18, 0x9c, 0x69, 0x63, + 0xdb, 0x81, 0x73, 0x0e, 0x64, 0x40, 0x12, 0xc1, 0x26, 0x0e, 0xac, 0x4d, + 0x38, 0xa6, 0x4c, 0x05, 0xeb, 0x42, 0x1f, 0x88, 0x6e, 0x6c, 0xa3, 0x98, + 0x95, 0xc3, 0x5a, 0x31, 0xfc, 0x8a, 0x7c, 0xd6, 0xa5, 0x6c, 0x5a, 0xc9, + 0xf5, 0xf2, 0xb0, 0xf7, 0x05, 0x8d, 0x3a, 0x0b, 0x3f, 0x4d, 0x1b, 0x0e, + 0x38, 0x7b, 0x1c, 0xe5, 0xd0, 0x75, 0x40, 0x77, 0xc2, 0xe0, 0x8b, 0xa9, + 0xfb, 0xa6, 0xa7, 0x13, 0xf0, 0xbc, 0x0c, 0x13, 0xb0, 0x70, 0x3a, 0x2f, + 0x20, 0xe7, 0x38, 0xd8, 0x82, 0xa4, 0xc0, 0x06, 0x96, 0x95, 0x75, 0x5c, + 0xbc, 0x68, 0xce, 0xee, 0xa6, 0x44, 0xbb, 0xf2, 0x62, 0x14, 0x43, 0x10, + 0xe6, 0x0b, 0x5c, 0x66, 0x02, 0xbf, 0x38, 0xe9, 0x8f, 0x19, 0x69, 0x6c, + 0x08, 0xfa, 0x93, 0x23, 0xf1, 0x35, 0x5f, 0x33, 0xcf, 0xe2, 0x32, 0x11, + 0xda, 0x31, 0xbb, 0xd8, 0xf5, 0x7e, 0x55, 0xc3, 0x6a, 0xa3, 0x04, 0x8c, + 0xef, 0x50, 0x67, 0x0f, 0xe9, 0xbb, 0x11, 0x6b, 0xca, 0x5a, 0x23, 0x15, + 0xf7, 0x52, 0x8c, 0x69, 0xbb, 0x2d, 0x26, 0xd3, 0x78, 0x32, 0x33, 0x9b, + 0x1d, 0x02, 0x7c, 0x22, 0x4b, 0x57, 0x19, 0xec, 0xcd, 0x16, 0x63, 0x5d, + 0x1f, 0x0c, 0x67, 0xda, 0x6a, 0xc7, 0x2c, 0xf1, 0x0b, 0xcf, 0x92, 0x10, + 0xcb, 0x78, 0x57, 0x67, 0x61, 0x0e, 0xb3, 0x55, 0xb0, 0x17, 0x32, 0x4e, + 0x95, 0xf1, 0xcb, 0xb5, 0xdb, 0x5d, 0x8e, 0x38, 0x97, 0x28, 0x46, 0x1e, + 0x37, 0x4b, 0x5c, 0x03, 0xf4, 0x84, 0x0c, 0xfc, 0x49, 0x3b, 0xd2, 0xc6, + 0x97, 0xd4, 0x4f, 0xef, 0xe6, 0x5c, 0xb2, 0x96, 0x8e, 0xbc, 0x18, 0x9f, + 0xec, 0x8a, 0x67, 0x53, 0xe8, 0x2a, 0x41, 0x5c, 0x6e, 0xfe, 0xca, 0x1a, + 0xd0, 0x03, 0x4f, 0xe8, 0xd9, 0xb0, 0xe2, 0xa1, 0x6c, 0x32, 0xd5, 0x37, + 0x68, 0x9c, 0x6b, 0x30, 0x87, 0xb4, 0x6e, 0xa8, 0xc5, 0x45, 0xe4, 0x74, + 0x4a, 0x80, 0x02, 0x84, 0x78, 0x0e, 0x2c, 0x9c, 0x37, 0x07, 0x26, 0x31, + 0x88, 0x0a, 0x89, 0xd2, 0xba, 0x8b, 0x09, 0xb2, 0x16, 0x7b, 0x23, 0xa8, + 0x0c, 0x82, 0xc4, 0x22, 0xa2, 0x21, 0x2d, 0xa4, 0xa0, 0xeb, 0xe4, 0xa6, + 0xd4, 0x16, 0xa0, 0xa7, 0x19, 0x8b, 0x8f, 0x87, 0x9b, 0x53, 0x6c, 0xba, + 0x14, 0xa7, 0xc4, 0x64, 0x08, 0xb4, 0x68, 0xda, 0x85, 0xa6, 0x47, 0xbc, + 0x58, 0x34, 0xcd, 0x60, 0x43, 0xad, 0x14, 0xd4, 0xca, 0xd7, 0xb1, 0x6c, + 0xc0, 0x05, 0x68, 0xaf, 0xa7, 0x08, 0x9d, 0x6a, 0xb0, 0x70, 0x96, 0x81, + 0xb8, 0x55, 0xbf, 0xa1, 0xcc, 0xb1, 0x37, 0xe0, 0x94, 0x42, 0x05, 0x0c, + 0x83, 0xef, 0x6d, 0xf0, 0x4e, 0xba, 0xe6, 0x78, 0x49, 0xaf, 0x1f, 0x88, + 0xf0, 0x18, 0x0c, 0x17, 0x66, 0x92, 0xd8, 0x50, 0x57, 0x3b, 0x8e, 0xc9, + 0xd5, 0x8c, 0xfb, 0x9b, 0x78, 0x65, 0x01, 0x76, 0x7a, 0x0e, 0xf0, 0x7f, + 0x2b, 0xc4, 0x48, 0x81, 0xc2, 0xb7, 0xc1, 0x6e, 0x4b, 0xc7, 0x33, 0xa3, + 0x9b, 0xf1, 0xcf, 0x63, 0x77, 0x52, 0x07, 0xe1, 0x9f, 0xa9, 0x6b, 0xce, + 0x02, 0xbf, 0x06, 0x8d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + +const uint8_t kExpectedCiphertext[MLKEM768_CIPHERTEXT_BYTES] = { + 0x8c, 0xfa, 0xd2, 0x09, 0x06, 0x1b, 0xff, 0x23, 0x9f, 0x84, 0x61, 0xfd, + 0x69, 0x7a, 0xa6, 0x2c, 0x57, 0x43, 0x64, 0x6b, 0x6b, 0x6b, 0xa3, 0xe1, + 0xa9, 0x4f, 0x3e, 0x29, 0xff, 0x3d, 0xb1, 0x84, 0x51, 0x1d, 0x48, 0xe3, + 0xf2, 0xf9, 0x5c, 0x9b, 0xf8, 0x05, 0xa1, 0x4c, 0xf4, 0x78, 0xce, 0xd8, + 0xc8, 0x0a, 0xc9, 0x71, 0xa7, 0x50, 0x89, 0xde, 0x66, 0x11, 0x68, 0x2c, + 0x70, 0x0f, 0xa3, 0x15, 0xa7, 0x8f, 0xa7, 0xd1, 0x49, 0x32, 0x2b, 0xe7, + 0xe3, 0x63, 0xff, 0x6b, 0x8c, 0x77, 0xd8, 0x97, 0x6f, 0x6c, 0x80, 0xc2, + 0x73, 0x7d, 0xe2, 0x39, 0x6f, 0x61, 0x4f, 0xa3, 0x85, 0x14, 0x8e, 0x68, + 0x58, 0x18, 0xba, 0x1c, 0x19, 0x01, 0x4c, 0x06, 0x73, 0x58, 0x4a, 0x9d, + 0xdd, 0x2e, 0x78, 0x82, 0x62, 0xbf, 0x15, 0x0c, 0x8e, 0xa7, 0xcf, 0xee, + 0xd7, 0x9a, 0x42, 0x30, 0xf5, 0x44, 0xdc, 0x3f, 0xdc, 0x67, 0x5c, 0x06, + 0xf0, 0xcf, 0x3b, 0x24, 0x9e, 0xfa, 0xe8, 0x4b, 0x3b, 0x00, 0x01, 0x7c, + 0x4d, 0x50, 0xa8, 0xac, 0x30, 0x74, 0xf4, 0x73, 0x98, 0x5e, 0x09, 0x92, + 0xbd, 0xe1, 0xc4, 0x3a, 0x9f, 0xd0, 0x62, 0xc8, 0x4e, 0x7f, 0xb0, 0xaa, + 0xb3, 0x8c, 0xb5, 0xf9, 0x57, 0xe3, 0x90, 0x9a, 0x94, 0x0d, 0xdb, 0x9e, + 0xf7, 0x78, 0xbf, 0x18, 0xd0, 0x02, 0x8e, 0x02, 0x04, 0xbe, 0xee, 0x87, + 0x49, 0xb1, 0xfe, 0x28, 0xd2, 0xdb, 0xd0, 0x7a, 0x12, 0x50, 0xa3, 0xc6, + 0x32, 0xd6, 0x06, 0xa6, 0xc5, 0xb0, 0xa8, 0xbe, 0x49, 0x8a, 0x8b, 0xfe, + 0xf6, 0xb1, 0xe5, 0xb6, 0xf0, 0x61, 0xc6, 0x1f, 0xe7, 0xcb, 0x4d, 0x66, + 0xdd, 0xe4, 0xd2, 0x2b, 0x73, 0xbd, 0x03, 0x79, 0x76, 0x05, 0x87, 0x58, + 0x6f, 0x6f, 0x8f, 0x20, 0x4f, 0x1f, 0x81, 0xa9, 0x9c, 0x22, 0x8d, 0xbd, + 0xef, 0x41, 0x5e, 0x39, 0x9e, 0x90, 0x4b, 0x63, 0x8b, 0x50, 0xac, 0x4f, + 0x20, 0x08, 0x82, 0x53, 0x52, 0x86, 0xce, 0x55, 0xf5, 0x21, 0xd7, 0x8c, + 0xdf, 0xf3, 0x54, 0x90, 0xed, 0x27, 0xa9, 0x95, 0xbb, 0xec, 0x7a, 0xe2, + 0xeb, 0x80, 0x29, 0xca, 0xc9, 0x4b, 0x1a, 0xfe, 0xe8, 0x40, 0xcf, 0x70, + 0x37, 0xb3, 0xb8, 0xb3, 0x04, 0xf6, 0xc3, 0x44, 0x1e, 0xf8, 0x40, 0x95, + 0xf9, 0x92, 0x97, 0x63, 0xab, 0x35, 0x11, 0x7b, 0x2d, 0x9e, 0x5b, 0xeb, + 0xfe, 0x80, 0xfe, 0xc3, 0xc6, 0xa4, 0x8c, 0xac, 0xd2, 0xa5, 0x0d, 0x11, + 0xcd, 0xbc, 0xdd, 0x57, 0x9d, 0xf4, 0xbc, 0xdf, 0xbe, 0xa2, 0xfc, 0xcd, + 0x2b, 0x83, 0x0e, 0x4e, 0x77, 0x44, 0x10, 0x93, 0xeb, 0xca, 0xec, 0xb6, + 0x26, 0x48, 0x45, 0x08, 0x72, 0xd4, 0xfe, 0xa2, 0xe5, 0xc8, 0x12, 0x8f, + 0x38, 0xcd, 0xd6, 0xaa, 0x97, 0xd4, 0xad, 0xb3, 0x0b, 0x19, 0x5b, 0x70, + 0x50, 0xbf, 0x9d, 0x45, 0xd6, 0x0d, 0xf6, 0x72, 0x08, 0x0f, 0x98, 0xbd, + 0x1f, 0x39, 0xea, 0x4c, 0x76, 0xa8, 0x6e, 0xc2, 0x24, 0xe3, 0x3d, 0xf4, + 0x40, 0xe8, 0x68, 0xfe, 0xaf, 0xeb, 0xae, 0x65, 0x84, 0x86, 0x10, 0xb6, + 0x58, 0x75, 0xb9, 0x22, 0x6d, 0x74, 0x5d, 0xa7, 0xc0, 0x17, 0x10, 0x0f, + 0x36, 0x5f, 0x99, 0xf3, 0x60, 0x39, 0xeb, 0x6e, 0x04, 0x4d, 0x29, 0xc7, + 0xec, 0x2a, 0x1d, 0x8f, 0x5c, 0x23, 0x84, 0xba, 0x65, 0xe9, 0xab, 0x32, + 0xd4, 0x62, 0xd1, 0x53, 0xb8, 0x71, 0x40, 0x9a, 0xf0, 0x05, 0xdb, 0xa0, + 0x5a, 0xca, 0xeb, 0xb0, 0xbf, 0xfe, 0x7e, 0x19, 0x32, 0x42, 0xef, 0xab, + 0xf3, 0x49, 0x13, 0x50, 0x08, 0x98, 0xcd, 0xcf, 0x5a, 0x77, 0x5d, 0xe6, + 0x3f, 0x9d, 0xa0, 0x21, 0x98, 0xcb, 0x78, 0x69, 0xd8, 0x22, 0xdb, 0xae, + 0x87, 0x2c, 0x38, 0x0a, 0x96, 0xa2, 0x30, 0x8f, 0x37, 0xe4, 0xc5, 0x94, + 0x57, 0x40, 0x30, 0xa0, 0x4e, 0x7c, 0xfe, 0x6f, 0x2e, 0x15, 0x88, 0x7b, + 0xf2, 0x22, 0x9c, 0x95, 0x7e, 0xd6, 0x2d, 0x37, 0xd4, 0x13, 0x95, 0x31, + 0xf6, 0xbb, 0xf4, 0xaf, 0x33, 0x42, 0xf0, 0x45, 0xb1, 0xa8, 0xb4, 0x09, + 0x9a, 0x6d, 0x7a, 0xdb, 0xb0, 0xf2, 0x00, 0xdc, 0x77, 0x6a, 0x43, 0xf1, + 0xbb, 0x56, 0xc5, 0x7c, 0xee, 0xa6, 0xd6, 0x10, 0xa0, 0x81, 0xca, 0x28, + 0xab, 0x48, 0xb4, 0x72, 0xbc, 0xe6, 0xe2, 0x24, 0xef, 0x49, 0xdc, 0xb5, + 0x1f, 0x83, 0xe7, 0xda, 0xdd, 0x73, 0x5c, 0x7b, 0x85, 0x4a, 0x15, 0x7b, + 0xcb, 0xf1, 0x14, 0x6b, 0x32, 0xef, 0xce, 0xaf, 0x37, 0x04, 0xa4, 0x1e, + 0xcb, 0x1b, 0x84, 0x1d, 0xdb, 0xbf, 0x2f, 0x88, 0x89, 0xf4, 0x5e, 0xb0, + 0x32, 0x99, 0x81, 0x9c, 0x8a, 0xb0, 0xfd, 0x28, 0x6f, 0xc9, 0xe9, 0xaf, + 0x60, 0x11, 0xa5, 0x8d, 0xa4, 0xfb, 0x93, 0x91, 0x7a, 0xa0, 0xd2, 0xcd, + 0xda, 0x4d, 0xf3, 0xfe, 0xc8, 0x55, 0x4f, 0x26, 0x9d, 0x56, 0x87, 0x12, + 0xfe, 0x93, 0x3e, 0x34, 0xf5, 0x3d, 0x4f, 0x6e, 0x26, 0x56, 0xf7, 0x80, + 0xa2, 0xb9, 0x0f, 0xa1, 0xf8, 0x72, 0xb0, 0xaa, 0xec, 0xe2, 0x97, 0xd0, + 0x3a, 0x6d, 0xe5, 0xe9, 0x12, 0x1b, 0x32, 0x0a, 0xdb, 0x52, 0x8f, 0x9d, + 0xd0, 0xff, 0x67, 0xcc, 0x63, 0x41, 0x32, 0x2f, 0xe7, 0x0c, 0xb0, 0xa5, + 0x73, 0xc5, 0xc3, 0x54, 0x75, 0x06, 0x8e, 0x36, 0x54, 0xea, 0x9c, 0x6b, + 0x60, 0xee, 0x10, 0x06, 0xd2, 0xb3, 0x8c, 0xe3, 0x09, 0xfe, 0x1e, 0x47, + 0xc3, 0xd5, 0x6c, 0x0d, 0x0c, 0x84, 0x5e, 0x4f, 0x01, 0xfa, 0xcf, 0xae, + 0xc1, 0xac, 0xd9, 0xb0, 0x03, 0x74, 0x8e, 0xc5, 0x57, 0x51, 0x96, 0x23, + 0x72, 0xc6, 0x81, 0x7f, 0xf1, 0x6c, 0x29, 0xea, 0x31, 0x2a, 0x23, 0xbb, + 0x88, 0x6f, 0x01, 0xa2, 0x2f, 0x69, 0xd2, 0x1c, 0xe8, 0x1e, 0x63, 0x44, + 0xd9, 0x90, 0x0b, 0x57, 0x78, 0xc6, 0xd1, 0xb3, 0xf6, 0x97, 0x99, 0xd8, + 0x09, 0xe0, 0x9d, 0x69, 0x00, 0xa0, 0xd4, 0xe0, 0x80, 0xfd, 0xdf, 0x23, + 0x3a, 0xf8, 0xc0, 0x97, 0xea, 0xb6, 0xbf, 0x87, 0x75, 0x40, 0x1e, 0x0d, + 0x1e, 0x6c, 0x84, 0xa4, 0x7e, 0xbb, 0xa3, 0x02, 0x76, 0x76, 0xc8, 0x4e, + 0x8b, 0x21, 0x3d, 0x27, 0xbc, 0x38, 0x0f, 0x79, 0xfb, 0xc5, 0xdd, 0x37, + 0x67, 0xcb, 0x61, 0x5a, 0x12, 0x85, 0x31, 0x91, 0x3e, 0x7a, 0x4b, 0x6c, + 0xfd, 0x4e, 0x54, 0x47, 0xfc, 0xc5, 0x2e, 0x34, 0xe4, 0xaa, 0x3d, 0xa2, + 0xd3, 0x1d, 0x15, 0xbc, 0xea, 0xa7, 0xe3, 0xcd, 0xd6, 0x49, 0xee, 0x06, + 0x11, 0x2b, 0xf1, 0x58, 0x81, 0xdd, 0x99, 0xe1, 0xbd, 0x63, 0xa0, 0xd7, + 0xa0, 0x4b, 0x01, 0xab, 0xf3, 0x5c, 0x35, 0xf0, 0xb0, 0xdc, 0xd0, 0x87, + 0x78, 0x02, 0xec, 0x99, 0x0e, 0xb2, 0x23, 0x8b, 0xb1, 0x44, 0x93, 0x65, + 0xd5, 0x1c, 0x00, 0x7e, 0x98, 0xb3, 0x5e, 0xf9, 0xca, 0xbc, 0x26, 0x38, + 0x18, 0x22, 0x14, 0x3c, 0xed, 0x8d, 0x54, 0xa4, 0x05, 0x00, 0x7f, 0xfb, + 0xd5, 0x73, 0x77, 0xf4, 0x98, 0xa0, 0xf7, 0x60, 0xb4, 0x47, 0x10, 0x75, + 0x30, 0x2d, 0xde, 0x9c, 0x3e, 0x08, 0x8f, 0xe5, 0xc9, 0x5a, 0xd9, 0x20, + 0xf3, 0x97, 0xb5, 0xd1, 0xb3, 0x90, 0x23, 0x6f, 0x9f, 0x5e, 0xf1, 0x0f, + 0x76, 0x18, 0xbf, 0x2b, 0x23, 0x8e, 0x45, 0x3f, 0xaf, 0x2b, 0x53, 0x78, + 0x27, 0xa2, 0xf6, 0x07, 0x2b, 0x61, 0x24, 0x5b, 0xc7, 0x2e, 0x25, 0xf1, + 0xb3, 0x4c, 0x50, 0xe8, 0x6d, 0xee, 0x56, 0x52, 0x37, 0xd0, 0x6e, 0xd6, + 0xcb, 0xc8, 0x2a, 0xb1, 0xba, 0x49, 0xc7, 0x5a, 0x55, 0x3c, 0x6f, 0x16, + 0x64, 0x08, 0xa6, 0x46, 0x09, 0x37, 0x86, 0x0b, 0xe7, 0x7e, 0x2d, 0xf4, + 0x96, 0x80, 0x41, 0x77, 0x1a, 0xf9, 0xd2, 0xe0, 0xf3, 0x64, 0x0e, 0x3f, + 0x3d, 0xe1, 0xec, 0x63, 0x40, 0x10, 0x15, 0xcf, 0x4c, 0xc9, 0x1c, 0x9b, + 0x9f, 0xe8, 0x50, 0x27, 0xc2, 0x54, 0x44, 0x14, 0xb6, 0x2e, 0xe4, 0x53, + 0xf2, 0x60, 0x8a, 0xb6, 0x1c, 0x14, 0xb6, 0x25, 0xf2, 0x44, 0x59, 0xb7, + 0x67, 0x3b, 0x94, 0x88, 0x15, 0x70, 0x6f, 0xa8}; + +const uint8_t kExpectedSharedSecret[MLKEM_SHARED_SECRET_BYTES] = { + 0x7d, 0x9f, 0x1c, 0xb4, 0xae, 0x04, 0xd7, 0x5f, 0xa6, 0x57, 0x5a, + 0xe0, 0xe4, 0x29, 0xb5, 0x73, 0xa9, 0x74, 0xb7, 0xa1, 0x25, 0xbd, + 0xfb, 0x8a, 0x6e, 0x0f, 0x19, 0xba, 0xe1, 0x16, 0xae, 0x81}; + +const uint8_t + kExpectedImplicitRejectionSharedSecret[MLKEM_SHARED_SECRET_BYTES] = { + 0xa3, 0x19, 0x2a, 0x8c, 0x88, 0xfc, 0x99, 0x6d, 0x2d, 0xf9, 0x85, + 0x8d, 0x2c, 0x55, 0x36, 0x39, 0x93, 0xf0, 0x49, 0x4d, 0x7e, 0xc0, + 0xbe, 0x5a, 0x56, 0x7b, 0x8a, 0x42, 0x43, 0xa5, 0x74, 0x5d}; diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/mlkem/mlkem.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/mlkem/mlkem.cc.inc index d536805a..be44a5b1 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/mlkem/mlkem.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/mlkem/mlkem.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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 @@ -29,16 +29,46 @@ #include "../keccak/internal.h" +using namespace bssl; + +#if defined(BORINGSSL_FIPS) + +DEFINE_STATIC_ONCE(g_mlkem_keygen_self_test_once) +DEFINE_STATIC_ONCE(g_mlkem_encap_self_test_once) +DEFINE_STATIC_ONCE(g_mlkem_decap_self_test_once) + +#endif + namespace mlkem { namespace { +namespace fips { +void ensure_keygen_self_test(); +void ensure_encap_self_test(); +void ensure_decap_self_test(); +} // namespace fips + // See // https://csrc.nist.gov/pubs/fips/203/final -static void prf(uint8_t *out, size_t out_len, const uint8_t in[33]) { +inline void prf(uint8_t *out, size_t out_len, const uint8_t in[33]) { BORINGSSL_keccak(out, out_len, in, 33, boringssl_shake256); } +#if defined(HAVE_KECCAK_X2) +inline void prf_x2(uint8_t *outs[2], size_t out_len, + const uint8_t *ins[2] /* 33 each */) { + BORINGSSL_keccak_short_x2(outs, out_len, ins, 33, boringssl_shake256); +} +#endif + +#if defined(HAVE_KECCAK_X4) +inline void prf_x4(uint8_t *outs[4], size_t out_len, + const uint8_t *ins[4] /* 33 each */) { + BORINGSSL_keccak_short_x4(outs, out_len, ins, 33, boringssl_shake256); +} +#endif + // Section 4.1 void hash_h(uint8_t out[32], const uint8_t *in, size_t len) { BORINGSSL_keccak(out, 32, in, len, boringssl_sha3_256); @@ -49,21 +79,21 @@ void hash_g(uint8_t out[64], const uint8_t *in, size_t len) { } // This is called `J` in the spec. -void kdf(uint8_t out[BCM_MLKEM_SHARED_SECRET_BYTES], +void kdf(uint8_t out[MLKEM_SHARED_SECRET_BYTES], const uint8_t failure_secret[32], const uint8_t *ciphertext, size_t ciphertext_len) { - struct BORINGSSL_keccak_st st; + BORINGSSL_keccak_st st; BORINGSSL_keccak_init(&st, boringssl_shake256); BORINGSSL_keccak_absorb(&st, failure_secret, 32); BORINGSSL_keccak_absorb(&st, ciphertext, ciphertext_len); - BORINGSSL_keccak_squeeze(&st, out, BCM_MLKEM_SHARED_SECRET_BYTES); + BORINGSSL_keccak_squeeze(&st, out, MLKEM_SHARED_SECRET_BYTES); } // Constants that are common across all sizes. #define DEGREE 256 -const size_t kBarrettMultiplier = 5039; -const unsigned kBarrettShift = 24; -static const uint16_t kPrime = 3329; +const size_t kBarrettMultiplier = 1290167; +const unsigned kBarrettShift = 32; +const uint16_t kPrime = 3329; const int kLog2Prime = 12; const uint16_t kHalfPrime = (/*kPrime=*/3329 - 1) / 2; // kInverseDegree is 128^-1 mod 3329; 128 because kPrime does not have a 512th @@ -72,10 +102,10 @@ const uint16_t kInverseDegree = 3303; // Rank-specific constants. #define RANK768 3 -static const int kDU768 = 10; +const int kDU768 = 10; const int kDV768 = 4; #define RANK1024 4 -static const int kDU1024 = 11; +const int kDU1024 = 11; const int kDV1024 = 5; constexpr size_t encoded_vector_size(int rank) { @@ -86,11 +116,8 @@ constexpr size_t encoded_public_key_size(int rank) { return encoded_vector_size(rank) + /*sizeof(rho)=*/32; } -static_assert(encoded_public_key_size(RANK768) == BCM_MLKEM768_PUBLIC_KEY_BYTES, - ""); -static_assert(encoded_public_key_size(RANK1024) == - BCM_MLKEM1024_PUBLIC_KEY_BYTES, - ""); +static_assert(encoded_public_key_size(RANK768) == MLKEM768_PUBLIC_KEY_BYTES); +static_assert(encoded_public_key_size(RANK1024) == MLKEM1024_PUBLIC_KEY_BYTES); constexpr size_t compressed_vector_size(int rank) { // `if constexpr` isn't available in C++17. @@ -103,13 +130,13 @@ constexpr size_t ciphertext_size(int rank) { (rank == RANK768 ? kDV768 : kDV1024) * DEGREE / 8; } -static_assert(ciphertext_size(RANK768) == BCM_MLKEM768_CIPHERTEXT_BYTES, ""); -static_assert(ciphertext_size(RANK1024) == BCM_MLKEM1024_CIPHERTEXT_BYTES, ""); +static_assert(ciphertext_size(RANK768) == MLKEM768_CIPHERTEXT_BYTES); +static_assert(ciphertext_size(RANK1024) == MLKEM1024_CIPHERTEXT_BYTES); -typedef struct scalar { +struct scalar { // On every function entry and exit, 0 <= c < kPrime. uint16_t c[DEGREE]; -} scalar; +}; template struct vector { @@ -180,7 +207,7 @@ const uint16_t kModRoots[128] = { }; // reduce_once reduces 0 <= x < 2*kPrime, mod kPrime. -uint16_t reduce_once(uint16_t x) { +inline uint16_t reduce_once(uint16_t x) { declassify_assert(x < 2 * kPrime); const uint16_t subtracted = x - kPrime; uint16_t mask = 0u - (subtracted >> 15); @@ -192,55 +219,81 @@ uint16_t reduce_once(uint16_t x) { // We usually add value barriers to selects because Clang turns consecutive // 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|. + // but see `scalar_centered_binomial_distribution_eta_2_with_prf`. return (mask & x) | (~mask & subtracted); } -// constant time reduce x mod kPrime using Barrett reduction. x must be less -// than kPrime + 2×kPrime². -static uint16_t reduce(uint32_t x) { - declassify_assert(x < kPrime + 2u * kPrime * kPrime); +// reduce_partial returns a number equivalent to x mod kPrime. The output is +// less than 2 * kPrime. `x` can be any `uint32_t`. +inline uint32_t reduce_partial(uint32_t x) { uint64_t product = (uint64_t)x * kBarrettMultiplier; uint32_t quotient = (uint32_t)(product >> kBarrettShift); uint32_t remainder = x - quotient * kPrime; - return reduce_once(remainder); + return remainder; } -void scalar_zero(scalar *out) { OPENSSL_memset(out, 0, sizeof(*out)); } +// constant time reduce x mod kPrime using Barrett reduction. `x` can be any +// `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 -void vector_zero(vector *out) { +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 -// relevant roots of unity being stored in |kNTTRoots|. This means the output +// relevant roots of unity being stored in `kNTTRoots`. This means the output // should be seen as 128 elements in GF(3329^2), with the coefficients of the -// elements being consecutive entries in |s->c|. -static void scalar_ntt(scalar *s) { - int offset = DEGREE; - // `int` is used here because using `size_t` throughout caused a ~5% slowdown - // with Clang 14 on Aarch64. - for (int step = 1; step < DEGREE / 2; step <<= 1) { - offset >>= 1; - int k = 0; - for (int i = 0; i < step; i++) { - const uint32_t step_root = kNTTRoots[i + step]; - for (int j = k; j < k + offset; j++) { - uint16_t odd = reduce(step_root * s->c[j + offset]); - uint16_t even = s->c[j]; - s->c[j] = reduce_once(odd + even); - s->c[j + offset] = reduce_once(even - odd + kPrime); - } - k += 2 * offset; - } +// elements being consecutive entries in `s->c`. +inline void scalar_ntt(scalar *s) { + // Manually unrolled loop to maximize vectorization. + // + // Intermediate values of `s` are not fully reduced. `ITER` writes to every + // element of `s` exactly once. Each write adds less than 2*kPrime to some + // value from the previous iteration. After seven iterations, each element + // will be less than 15*kPrime. This fits in `uint16_t`, so we never overflow. +#define ITER(step, offset) \ + { \ + int k = 0; \ + for (int i = 0; i < step; i++) { \ + const uint32_t step_root = kNTTRoots[step + i]; \ + for (int j = k; j < k + offset; j++) { \ + uint32_t even = s->c[j]; \ + /* `reduce_partial` works on values up to 2^32. \ + * `step_root < kPrime` because it's static data. `s->c[...] < 2^16` \ + * because it's 16-bit. */ \ + uint32_t odd = \ + reduce_partial(uint32_t{step_root} * uint32_t{s->c[j + offset]}); \ + s->c[j] = even + odd; \ + s->c[j + offset] = even + 2 * kPrime - odd; \ + } \ + k += 2 * offset; \ + } \ + } + + // for (int step = 1; step < DEGREE / 2; step <<= 1) + ITER(1, 128) + ITER(2, 64) + ITER(4, 32) + ITER(8, 16) + ITER(16, 8) + ITER(32, 4) + ITER(64, 2) + static_assert(DEGREE == 256); +#undef ITER + + // Now `s` is correct but the elements are not fully reduced. Reduce them. + for (int i = 0; i < DEGREE; i++) { + s->c[i] = reduce(s->c[i]); } } template -static void vector_ntt(vector *a) { +inline void vector_ntt(vector *a) { for (int i = 0; i < RANK; i++) { scalar_ntt(&a->v[i]); } @@ -250,27 +303,53 @@ static void vector_ntt(vector *a) { // entries of s->v being interpreted as elements of GF(3329^2). Just as with the // number theoretic transform, this leaves off the first step of the normal iFFT // to account for the fact that 3329 does not have a 512th root of unity, using -// the precomputed 128 roots of unity stored in |kInverseNTTRoots|. +// the precomputed 128 roots of unity stored in `kInverseNTTRoots`. +// +// FIPS 203, Algorithm 10 (`NTT^-1`). void scalar_inverse_ntt(scalar *s) { - int step = DEGREE / 2; - // `int` is used here because using `size_t` throughout caused a ~5% slowdown - // with Clang 14 on Aarch64. - for (int offset = 2; offset < DEGREE; offset <<= 1) { - step >>= 1; - int k = 0; - for (int i = 0; i < step; i++) { - uint32_t step_root = kInverseNTTRoots[i + step]; - for (int j = k; j < k + offset; j++) { - uint16_t odd = s->c[j + offset]; - uint16_t even = s->c[j]; - s->c[j] = reduce_once(odd + even); - s->c[j + offset] = reduce(step_root * (even - odd + kPrime)); - } - k += 2 * offset; - } + // Manually unrolled loop to maximize vectorization. + // + // Intermediate values are not fully reduced. `ITER` writes to every element + // exactly once. Each write either adds two values from the previous + // iteration, or is at most 2 * kPrime. After seven iterations, each element + // will be less than 2^7 * kPrime = 128 * kPrime. This fits in `uint32_t`, so + // we never overflow. + uint32_t c[DEGREE]; +#define ITER(step, offset, src) \ + { \ + int k = 0; \ + for (int i = 0; i < step; i++) { \ + const uint32_t step_root = kInverseNTTRoots[step + i]; \ + for (int j = k; j < k + offset; j++) { \ + uint32_t even = (src)[j]; \ + uint32_t odd = (src)[j + offset]; \ + c[j] = odd + even; \ + /* `reduce_partial` works on values up to 2^32. \ + * `step_root < kPrime` because it's static data. The other term is \ + * less than 2^32, and does not overflow because `odd` is at most \ + * 128 * kPrime per the above. */ \ + c[j + offset] = reduce_partial(uint32_t{step_root} * \ + uint32_t{128 * kPrime + even - odd}); \ + } \ + k += 2 * offset; \ + } \ } + + // for (int offset = 2; offset < DEGREE; offset <<= 1) + ITER(64, 2, s->c) + ITER(32, 4, c) + ITER(16, 8, c) + ITER(8, 16, c) + ITER(4, 32, c) + ITER(2, 64, c) + ITER(1, 128, c) + static_assert(DEGREE == 256); +#undef ITER + + // The final multiplication by `kInverseDegree` also fully reduces the + // partially-reduced values above. for (int i = 0; i < DEGREE; i++) { - s->c[i] = reduce(s->c[i] * kInverseDegree); + s->c[i] = reduce(c[i] * kInverseDegree); } } @@ -281,13 +360,13 @@ void vector_inverse_ntt(vector *a) { } } -void scalar_add(scalar *lhs, const scalar *rhs) { +inline void scalar_add(scalar *lhs, const scalar *rhs) { for (int i = 0; i < DEGREE; i++) { lhs->c[i] = reduce_once(lhs->c[i] + rhs->c[i]); } } -void scalar_sub(scalar *lhs, const scalar *rhs) { +inline void scalar_sub(scalar *lhs, const scalar *rhs) { for (int i = 0; i < DEGREE; i++) { lhs->c[i] = reduce_once(lhs->c[i] - rhs->c[i] + kPrime); } @@ -297,11 +376,11 @@ 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 multipy two reduced numbers together, so we need some +// 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. -void scalar_mult(scalar *out, const scalar *lhs, const scalar *rhs) { +inline void scalar_mult(scalar *out, const scalar *lhs, const scalar *rhs) { 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]; @@ -314,14 +393,14 @@ void scalar_mult(scalar *out, const scalar *lhs, const scalar *rhs) { } template -void vector_add(vector *lhs, const vector *rhs) { +inline void vector_add(vector *lhs, const vector *rhs) { for (int i = 0; i < RANK; i++) { scalar_add(&lhs->v[i], &rhs->v[i]); } } template -static void matrix_mult(vector *out, const matrix *m, +inline void matrix_mult(vector *out, const matrix *m, const vector *a) { vector_zero(out); for (int i = 0; i < RANK; i++) { @@ -334,7 +413,7 @@ static void matrix_mult(vector *out, const matrix *m, } template -void matrix_mult_transpose(vector *out, const matrix *m, +inline void matrix_mult_transpose(vector *out, const matrix *m, const vector *a) { vector_zero(out); for (int i = 0; i < RANK; i++) { @@ -347,7 +426,7 @@ void matrix_mult_transpose(vector *out, const matrix *m, } template -void scalar_inner_product(scalar *out, const vector *lhs, +inline void scalar_inner_product(scalar *out, const vector *lhs, const vector *rhs) { scalar_zero(out); for (int i = 0; i < RANK; i++) { @@ -357,11 +436,49 @@ void scalar_inner_product(scalar *out, const vector *lhs, } } -// Algorithm 6 from the spec. Rejection samples a Keccak stream to get +inline void scalar_from_keccak_block_vartime(scalar *out, int *done, + const uint8_t block[168]) { + // kStep is the number of loop iterations to do at once. May need to become + // platform dependent at some point. Must be a compile-time constant - if we + // ever need to runtime dispatch on it, it has to be made a template argument. + const size_t kStep = 2; + + // Branchless sampling as long as there is enough space in the output buffer + // even if all sampled numbers are < `kPrime`. + size_t i = 0; + for (; i <= size_t{168 - 3 * kStep} && *done <= int{DEGREE - 2 * kStep}; + i += 3 * kStep) { + uint16_t d[2 * kStep]; + for (size_t k = 0; k < kStep; ++k) { + size_t di = 2 * k; + size_t bi = i + 3 * k; + d[di] = block[bi] + 256 * (block[bi + 1] % 16); + d[di + 1] = block[bi + 1] / 16 + 16 * block[bi + 2]; + } + for (size_t k = 0; k < 2 * kStep; ++k) { + out->c[*done] = d[k]; + *done += d[k] < kPrime; + } + } + + // Branchful "tail". + for (; i < 168 && *done < DEGREE; i += 3) { + uint16_t d1 = block[i] + 256 * (block[i + 1] % 16); + uint16_t d2 = block[i + 1] / 16 + 16 * block[i + 2]; + if (d1 < kPrime) { + out->c[(*done)++] = d1; + } + if (d2 < kPrime && *done < DEGREE) { + out->c[(*done)++] = d2; + } + } +} + +// Algorithm 7 from the spec. Rejection samples a Keccak stream to get // uniformly distributed elements. This is used for matrix expansion and only // operates on public inputs. -static void scalar_from_keccak_vartime(scalar *out, - struct BORINGSSL_keccak_st *keccak_ctx) { +inline void scalar_from_keccak_vartime(scalar *out, + BORINGSSL_keccak_st *keccak_ctx) { assert(keccak_ctx->squeeze_offset == 0); assert(keccak_ctx->rate_bytes == 168); static_assert(168 % 3 == 0, "block and coefficient boundaries do not align"); @@ -370,40 +487,64 @@ static void scalar_from_keccak_vartime(scalar *out, while (done < DEGREE) { uint8_t block[168]; BORINGSSL_keccak_squeeze(keccak_ctx, block, sizeof(block)); - for (size_t i = 0; i < sizeof(block) && done < DEGREE; i += 3) { - uint16_t d1 = block[i] + 256 * (block[i + 1] % 16); - uint16_t d2 = block[i + 1] / 16 + 16 * block[i + 2]; - if (d1 < kPrime) { - out->c[done++] = d1; - } - if (d2 < kPrime && done < DEGREE) { - out->c[done++] = d2; - } - } + scalar_from_keccak_block_vartime(out, &done, block); } } -// Algorithm 7 from the spec, with eta fixed to two and the PRF call -// included. Creates binominally distributed elements by sampling 2*|eta| bits, -// and setting the coefficient to the count of the first bits minus the count of -// the second bits, resulting in a centered binomial distribution. Since eta is -// two this gives -2/2 with a probability of 1/16, -1/1 with probability 1/4, -// and 0 with probability 3/8. -void scalar_centered_binomial_distribution_eta_2_with_prf( - scalar *out, const uint8_t input[33]) { - uint8_t entropy[128]; - static_assert(sizeof(entropy) == 2 * /*kEta=*/2 * DEGREE / 8, ""); - prf(entropy, sizeof(entropy), input); +#if defined(HAVE_KECCAK_X2) +inline void scalar_from_keccak_vartime_x2(scalar *out[2], + BORINGSSL_keccak_st keccak_ctx[2]) { + assert(keccak_ctx[0].squeeze_offset == 0); + assert(keccak_ctx[0].rate_bytes == 168); + assert(keccak_ctx[1].squeeze_offset == 0); + assert(keccak_ctx[1].rate_bytes == 168); + static_assert(168 % 3 == 0, "block and coefficient boundaries do not align"); + int done[2] = {0, 0}; + while (done[0] < DEGREE || done[1] < DEGREE) { + uint8_t block[2][168]; + uint8_t *blocks[] = {block[0], block[1]}; + BORINGSSL_keccak_squeeze_x2(keccak_ctx, blocks, sizeof(block[0])); + scalar_from_keccak_block_vartime(out[0], &done[0], block[0]); + scalar_from_keccak_block_vartime(out[1], &done[1], block[1]); + } +} +#endif + +#if defined(HAVE_KECCAK_X4) +inline void scalar_from_keccak_vartime_x4(scalar *out[4], + BORINGSSL_keccak_st keccak_ctx[]) { + for (int i = 0; i < 4; i++) { + assert(keccak_ctx[i].squeeze_offset == 0); + assert(keccak_ctx[i].rate_bytes == 168); + } + static_assert(168 % 3 == 0, "block and coefficient boundaries do not align"); + + int done[4] = {0, 0, 0, 0}; + while (done[0] < DEGREE || done[1] < DEGREE || done[2] < DEGREE || + done[3] < DEGREE) { + uint8_t block[4][168]; + uint8_t *blocks[] = {block[0], block[1], block[2], block[3]}; + BORINGSSL_keccak_squeeze_x4(keccak_ctx, blocks, sizeof(block[0])); + scalar_from_keccak_block_vartime(out[0], &done[0], block[0]); + scalar_from_keccak_block_vartime(out[1], &done[1], block[1]); + scalar_from_keccak_block_vartime(out[2], &done[2], block[2]); + scalar_from_keccak_block_vartime(out[3], &done[3], block[3]); + } +} +#endif + +static void scalar_centered_binomial_distribution_eta_2( + scalar *out, const uint8_t entropy[128]) { for (int i = 0; i < DEGREE; i += 2) { uint8_t byte = entropy[i / 2]; uint16_t value = (byte & 1) + ((byte >> 1) & 1); value -= ((byte >> 2) & 1) + ((byte >> 3) & 1); - // Add |kPrime| if |value| underflowed. See |reduce_once| for a discussion + // Add `kPrime` if `value` underflowed. See `reduce_once` for a discussion // on why the value barrier is omitted. While this could have been written // reduce_once(value + kPrime), this is one extra addition and small range - // of |value| tempts some versions of Clang to emit a branch. + // of `value` tempts some versions of Clang to emit a branch. uint16_t mask = 0u - (value >> 15); out->c[i] = ((value + kPrime) & mask) | (value & ~mask); @@ -416,170 +557,454 @@ void scalar_centered_binomial_distribution_eta_2_with_prf( } } +// Algorithm 8 from the spec, with eta fixed to two and the PRF call +// included. Creates binominally distributed elements by sampling 2*`eta` bits, +// and setting the coefficient to the count of the first bits minus the count of +// the second bits, resulting in a centered binomial distribution. Since eta is +// two this gives -2/2 with a probability of 1/16, -1/1 with probability 1/4, +// and 0 with probability 3/8. +void scalar_centered_binomial_distribution_eta_2_with_prf( + scalar *out, const uint8_t input[33]) { + uint8_t entropy[128]; + static_assert(sizeof(entropy) == 2 * /*kEta=*/2 * DEGREE / 8); + prf(entropy, sizeof(entropy), input); + scalar_centered_binomial_distribution_eta_2(out, entropy); +} + +#if defined(HAVE_KECCAK_X2) +// scalar_centered_binomial_distribution_eta_2_with_prf_x2 computes two blocks +// of scalar_centered_binomial_distribution_eta_2_with_prf. +static void scalar_centered_binomial_distribution_eta_2_with_prf_x2( + scalar out[2], uint8_t input[33]) { + uint8_t entropy[2][128]; + static_assert(sizeof(entropy[0]) == 2 * /*kEta=*/2 * DEGREE / 8); + + uint8_t input1[33]; + OPENSSL_memcpy(input1, input, 33); + ++input1[32]; // Counter. + + uint8_t *entropies[] = {entropy[0], entropy[1]}; + const uint8_t *inputs[2] = {input, input1}; + prf_x2(entropies, sizeof(entropy[0]), inputs); + + for (int k = 0; k < 2; k++) { + scalar_centered_binomial_distribution_eta_2(&out[k], entropy[k]); + } +} +#endif + +#if defined(HAVE_KECCAK_X4) +// scalar_centered_binomial_distribution_eta_2_with_prf_x4 computes four blocks +// of scalar_centered_binomial_distribution_eta_2_with_prf. +static void scalar_centered_binomial_distribution_eta_2_with_prf_x4( + scalar out[4], uint8_t input[33]) { + uint8_t entropy[4][128]; + static_assert(sizeof(entropy[0]) == 2 * /*kEta=*/2 * DEGREE / 8); + + uint8_t inputs[4][33]; + for (int i = 0; i < 4; i++) { + OPENSSL_memcpy(inputs[i], input, 33); + inputs[i][32] += i; + } + uint8_t *entropies[] = {entropy[0], entropy[1], entropy[2], entropy[3]}; + const uint8_t *input_ptrs[4] = {inputs[0], inputs[1], inputs[2], inputs[3]}; + prf_x4(entropies, sizeof(entropy[0]), input_ptrs); + + for (int k = 0; k < 4; k++) { + scalar_centered_binomial_distribution_eta_2(&out[k], entropy[k]); + } +} +#endif + // Generates a secret vector by using -// |scalar_centered_binomial_distribution_eta_2_with_prf|, using the given seed -// appending and incrementing |counter| for entry of the vector. +// `scalar_centered_binomial_distribution_eta_2_with_prf`, using the given seed +// appending and incrementing `counter` for entry of the vector. template void vector_generate_secret_eta_2(vector *out, uint8_t *counter, const uint8_t seed[32]) { uint8_t input[33]; OPENSSL_memcpy(input, seed, 32); - for (int i = 0; i < RANK; i++) { + + int i = 0; +#if defined(HAVE_KECCAK_X4) + if (BORINGSSL_have_keccak_x4()) { + for (; i + 4 <= RANK; i += 4) { + input[32] = *counter; + *counter += 4; + scalar_centered_binomial_distribution_eta_2_with_prf_x4(&out->v[i], + input); + } + } +#endif +#if defined(HAVE_KECCAK_X2) + for (; i + 2 <= RANK; i += 2) { + input[32] = *counter; + *counter += 2; + scalar_centered_binomial_distribution_eta_2_with_prf_x2(&out->v[i], input); + } +#endif + + for (; i < RANK; i++) { input[32] = (*counter)++; scalar_centered_binomial_distribution_eta_2_with_prf(&out->v[i], input); } } +template +void matrix_expand_step(scalar *out, uint8_t input[34], int i) { + input[32] = i / RANK; + input[33] = i % RANK; + BORINGSSL_keccak_st keccak_ctx; + BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake128); + BORINGSSL_keccak_absorb(&keccak_ctx, input, 34); + scalar_from_keccak_vartime(out, &keccak_ctx); +} + +#if defined(HAVE_KECCAK_X2) +template +void matrix_expand_step_x2(matrix *out, uint8_t input[34], int i) { + input[32] = i / RANK; + input[33] = i % RANK; + uint8_t input1[34]; + OPENSSL_memcpy(input1, input, 32); + input1[32] = (i + 1) / RANK; + input1[33] = (i + 1) % RANK; + BORINGSSL_keccak_st keccak_ctx[2]; + BORINGSSL_keccak_init(&keccak_ctx[0], boringssl_shake128); + BORINGSSL_keccak_init(&keccak_ctx[1], boringssl_shake128); + BORINGSSL_keccak_absorb(&keccak_ctx[0], input, 34); + BORINGSSL_keccak_absorb(&keccak_ctx[1], input1, 34); + scalar *outs[] = {&out->v[i / RANK][i % RANK], + &out->v[(i + 1) / RANK][(i + 1) % RANK]}; + scalar_from_keccak_vartime_x2(outs, keccak_ctx); +} +#endif + +#if defined(HAVE_KECCAK_X4) +template +void matrix_expand_step_x4(matrix *out, uint8_t input[34], int i) { + uint8_t inputs[4][34]; + BORINGSSL_keccak_st keccak_ctx[4]; + for (int k = 0; k < 4; k++) { + OPENSSL_memcpy(inputs[k], input, 32); + inputs[k][32] = (i + k) / RANK; + inputs[k][33] = (i + k) % RANK; + BORINGSSL_keccak_init(&keccak_ctx[k], boringssl_shake128); + BORINGSSL_keccak_absorb(&keccak_ctx[k], inputs[k], 34); + } + scalar *outs[] = {&out->v[i / RANK][i % RANK], + &out->v[(i + 1) / RANK][(i + 1) % RANK], + &out->v[(i + 2) / RANK][(i + 2) % RANK], + &out->v[(i + 3) / RANK][(i + 3) % RANK]}; + scalar_from_keccak_vartime_x4(outs, keccak_ctx); +} +#endif + // Expands the matrix of a seed for key generation and for encaps-CPA. template void matrix_expand(matrix *out, const uint8_t rho[32]) { uint8_t input[34]; OPENSSL_memcpy(input, rho, 32); - for (int i = 0; i < RANK; i++) { - for (int j = 0; j < RANK; j++) { - input[32] = i; - input[33] = j; - struct BORINGSSL_keccak_st keccak_ctx; - BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake128); - BORINGSSL_keccak_absorb(&keccak_ctx, input, sizeof(input)); - scalar_from_keccak_vartime(&out->v[i][j], &keccak_ctx); + + int i = 0; +#if defined(HAVE_KECCAK_X4) + if (BORINGSSL_have_keccak_x4()) { + for (; i + 4 <= RANK * RANK; i += 4) { + matrix_expand_step_x4(out, input, i); } } +#endif +#if defined(HAVE_KECCAK_X2) + for (; i + 2 <= RANK * RANK; i += 2) { + matrix_expand_step_x2(out, input, i); + } +#endif + + for (; i < RANK * RANK; i++) { + matrix_expand_step(&out->v[i / RANK][i % RANK], input, i); + } } -const uint8_t kMasks[8] = {0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff}; +// Encodes a scalar of 256 `BITS`-bit words into 32*`BITS` bytes by splitting +// and joining into bytes using LSB-first bit order (i.e. opposite to standard +// reading order). See below for examples. If an input is >= 1 << `BITS`, the +// result is undefined. +template +void scalar_encode(uint8_t *out, const scalar *s); -void scalar_encode(uint8_t *out, const scalar *s, int bits) { - assert(bits <= (int)sizeof(*s->c) * 8 && bits != 1); - - uint8_t out_byte = 0; - int out_byte_bits = 0; - - for (int i = 0; i < DEGREE; i++) { - uint16_t element = s->c[i]; - int element_bits_done = 0; - - while (element_bits_done < bits) { - int chunk_bits = bits - element_bits_done; - int out_bits_remaining = 8 - out_byte_bits; - if (chunk_bits >= out_bits_remaining) { - chunk_bits = out_bits_remaining; - out_byte |= (element & kMasks[chunk_bits - 1]) << out_byte_bits; - *out = out_byte; - out++; - out_byte_bits = 0; - out_byte = 0; - } else { - out_byte |= (element & kMasks[chunk_bits - 1]) << out_byte_bits; - out_byte_bits += chunk_bits; - } - - element_bits_done += chunk_bits; - element >>= chunk_bits; - } - } - - if (out_byte_bits > 0) { - *out = out_byte; +// Encodes a scalar of 256 10-bit words into 320 bytes as follows: +// 000000Aaaaaaaaaa 000000Bbbbbbbbbb 000000Cccccccccc 000000Dddddddddd ... +// -> aaaaaaaa bbbbbbAa ccccBbbb ddCccccc Dddddddd ... +template <> +void scalar_encode<10>(uint8_t out[320], const scalar *s) { + for (int i = 0; i < DEGREE; i += 4) { + uint16_t s0 = s->c[i]; + uint16_t s1 = s->c[i + 1]; + uint16_t s2 = s->c[i + 2]; + uint16_t s3 = s->c[i + 3]; + declassify_assert((s0 | s1 | s2 | s3) < (1 << 10)); + out[0] = (uint8_t)s0; + out[1] = (uint8_t)((s0 >> 8) | (s1 << 2)); + out[2] = (uint8_t)((s1 >> 6) | (s2 << 4)); + out[3] = (uint8_t)((s2 >> 4) | (s3 << 6)); + out[4] = (uint8_t)(s3 >> 2); + out += 5; } } -// scalar_encode_1 is |scalar_encode| specialised for |bits| == 1. -void scalar_encode_1(uint8_t out[32], const scalar *s) { +// Encodes a scalar of 256 12-bit words into 384 bytes as follows: +// 0000Aaaaaaaaaaaa 0000Bbbbbbbbbbbb 0000Cccccccccccc 0000Dddddddddddd ... +// -> aaaaaaaa bbbbAaaa Bbbbbbbb cccccccc ddddCccc Dddddddd .... +template <> +void scalar_encode<12>(uint8_t out[384], const scalar *s) { + for (int i = 0; i < DEGREE; i += 2) { + uint16_t s0 = s->c[i]; + uint16_t s1 = s->c[i + 1]; + declassify_assert((s0 | s1) < (1 << 12)); + out[0] = (uint8_t)s0; + out[1] = (uint8_t)((s0 >> 8) | (s1 << 4)); + out[2] = (uint8_t)(s1 >> 4); + out += 3; + } +} + +// Encodes a scalar of 256 4-bit words into 128 bytes as follows: +// 000000000000Aaaa 00000000000Bbbb 000000000000Cccc 000000000000Dddd ... +// -> BbbbAaaa DdddCccc ... +template <> +void scalar_encode<4>(uint8_t out[128], const scalar *s) { + for (int i = 0; i < DEGREE; i += 2) { + uint16_t s0 = s->c[i]; + uint16_t s1 = s->c[i + 1]; + declassify_assert((s0 | s1) < (1 << 4)); + out[0] = (uint8_t)(s0 | (s1 << 4)); + out += 1; + } +} + +// Encodes a scalar of 256 11-bit words into 352 bytes as follows: +// 00000Aaaaaaaaaaa 00000Bbbbbbbbbbb 00000Ccccccccccc 00000Ddddddddddd ... +// -> aaaaaaaa bbbbbAaa ccBbbbbb cccccccc dddddddC eeeeDddd fEeeeeee ... +template <> +void scalar_encode<11>(uint8_t out[352], const scalar *s) { + for (int i = 0; i < DEGREE; i += 8) { + uint16_t s0 = s->c[i]; + uint16_t s1 = s->c[i + 1]; + uint16_t s2 = s->c[i + 2]; + uint16_t s3 = s->c[i + 3]; + uint16_t s4 = s->c[i + 4]; + uint16_t s5 = s->c[i + 5]; + uint16_t s6 = s->c[i + 6]; + uint16_t s7 = s->c[i + 7]; + declassify_assert((s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7) < (1 << 11)); + out[0] = (uint8_t)s0; + out[1] = (uint8_t)((s0 >> 8) | (s1 << 3)); + out[2] = (uint8_t)((s1 >> 5) | (s2 << 6)); + out[3] = (uint8_t)(s2 >> 2); + out[4] = (uint8_t)((s2 >> 10) | (s3 << 1)); + out[5] = (uint8_t)((s3 >> 7) | (s4 << 4)); + out[6] = (uint8_t)((s4 >> 4) | (s5 << 7)); + out[7] = (uint8_t)(s5 >> 1); + out[8] = (uint8_t)((s5 >> 9) | (s6 << 2)); + out[9] = (uint8_t)((s6 >> 6) | (s7 << 5)); + out[10] = (uint8_t)(s7 >> 3); + out += 11; + } +} + +// Encodes a scalar of 256 5-bit words into 160 bytes as follows: +// 00000000000Aaaaa 00000000000Bbbbb 00000000000Ccccc 00000000000Ddddd ... +// -> bbbAaaaa dCccccBb eeeeDddd ggFffffE HhhhhGgg ... +template <> +void scalar_encode<5>(uint8_t out[160], const scalar *s) { + for (int i = 0; i < DEGREE; i += 8) { + uint16_t s0 = s->c[i]; + uint16_t s1 = s->c[i + 1]; + uint16_t s2 = s->c[i + 2]; + uint16_t s3 = s->c[i + 3]; + uint16_t s4 = s->c[i + 4]; + uint16_t s5 = s->c[i + 5]; + uint16_t s6 = s->c[i + 6]; + uint16_t s7 = s->c[i + 7]; + declassify_assert((s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7) < (1 << 5)); + out[0] = (uint8_t)(s0 | (s1 << 5)); + out[1] = (uint8_t)((s1 >> 3) | (s2 << 2) | (s3 << 7)); + out[2] = (uint8_t)((s3 >> 1) | (s4 << 4)); + out[3] = (uint8_t)((s4 >> 4) | (s5 << 1) | (s6 << 6)); + out[4] = (uint8_t)((s6 >> 2) | (s7 << 3)); + out += 5; + } +} + +// Encodes a scalar of 256 1-bit "words" into 32 bytes as follows: +// 0000000000000A 000000000000000B 000000000000000C 000000000000000D ... +// -> HGFEDCBA PONMLKJI XWVUTSRQ ... +// This order is best understood as the natural way of joining into bytes +// assuming LSB-first bit order. +template <> +void scalar_encode<1>(uint8_t out[32], const scalar *s) { for (int i = 0; i < DEGREE; i += 8) { uint8_t out_byte = 0; for (int j = 0; j < 8; j++) { - out_byte |= (s->c[i + j] & 1) << j; + declassify_assert(s->c[i + j] <= 1); + out_byte |= s->c[i + j] << j; } - *out = out_byte; - out++; + out[i / 8] = out_byte; } } -// Encodes an entire vector into 32*|RANK|*|bits| bytes. Note that since 256 +// Encodes an entire vector into 32*`RANK`*`bits` bytes. Note that since 256 // (DEGREE) is divisible by 8, the individual vector entries will always fill a // whole number of bytes, so we do not need to worry about bit packing here. -template -void vector_encode(uint8_t *out, const vector *a, int bits) { +template +void vector_encode(uint8_t *out, const vector *a) { for (int i = 0; i < RANK; i++) { - scalar_encode(out + i * bits * DEGREE / 8, &a->v[i], bits); + scalar_encode(out + i * bits * DEGREE / 8, &a->v[i]); } } -// scalar_decode parses |DEGREE * bits| bits from |in| into |DEGREE| values in -// |out|. It returns one on success and zero if any parsed value is >= -// |kPrime|. -int scalar_decode(scalar *out, const uint8_t *in, int bits) { - assert(bits <= (int)sizeof(*out->c) * 8 && bits != 1); +// scalar_decode parses `DEGREE * BITS` bits from `in` into `DEGREE` values in +// `out`. This is the inverse of `scalar_encode`. This is only defined for `BITS +// < 12`. Otherwise, the decoding is fallible and must use `scalar_decode_12` +// instead. +template +void scalar_decode(scalar *out, const uint8_t *in); - uint8_t in_byte = 0; - int in_byte_bits_left = 0; - - for (int i = 0; i < DEGREE; i++) { - uint16_t element = 0; - int element_bits_done = 0; - - while (element_bits_done < bits) { - if (in_byte_bits_left == 0) { - in_byte = *in; - in++; - in_byte_bits_left = 8; - } - - int chunk_bits = bits - element_bits_done; - if (chunk_bits > in_byte_bits_left) { - chunk_bits = in_byte_bits_left; - } - - element |= (in_byte & kMasks[chunk_bits - 1]) << element_bits_done; - in_byte_bits_left -= chunk_bits; - in_byte >>= chunk_bits; - - element_bits_done += chunk_bits; - } - - // An element is only out of range in the case of invalid input, in which - // case it is okay to leak the comparison. - if (constant_time_declassify_int(element >= kPrime)) { - return 0; - } - out->c[i] = element; +template <> +void scalar_decode<10>(scalar *out, const uint8_t in[320]) { + for (int i = 0; i < DEGREE; i += 4) { + uint16_t s0 = (uint16_t)(in[0] | ((in[1] & 0x03) << 8)); + uint16_t s1 = (uint16_t)((in[1] >> 2) | ((in[2] & 0x0f) << 6)); + uint16_t s2 = (uint16_t)((in[2] >> 4) | ((in[3] & 0x3f) << 4)); + uint16_t s3 = (uint16_t)((in[3] >> 6) | (in[4] << 2)); + out->c[i] = s0; + out->c[i + 1] = s1; + out->c[i + 2] = s2; + out->c[i + 3] = s3; + in += 5; } - - return 1; } -// scalar_decode_1 is |scalar_decode| specialised for |bits| == 1. -void scalar_decode_1(scalar *out, const uint8_t in[32]) { +template <> +void scalar_decode<4>(scalar *out, const uint8_t in[128]) { + for (int i = 0; i < DEGREE; i += 2) { + uint16_t s0 = (uint16_t)(in[0] & 0x0f); + uint16_t s1 = (uint16_t)(in[0] >> 4); + // kPrime is 3329, so 4-bit values are always < kPrime. + out->c[i] = s0; + out->c[i + 1] = s1; + in += 1; + } +} + +template <> +void scalar_decode<11>(scalar *out, const uint8_t in[352]) { for (int i = 0; i < DEGREE; i += 8) { - uint8_t in_byte = *in; - in++; + uint16_t s0 = (uint16_t)(in[0] | ((in[1] & 0x07) << 8)); + uint16_t s1 = (uint16_t)((in[1] >> 3) | ((in[2] & 0x3f) << 5)); + uint16_t s2 = + (uint16_t)((in[2] >> 6) | (in[3] << 2) | ((in[4] & 0x01) << 10)); + uint16_t s3 = (uint16_t)((in[4] >> 1) | ((in[5] & 0x0f) << 7)); + uint16_t s4 = (uint16_t)((in[5] >> 4) | ((in[6] & 0x7f) << 4)); + uint16_t s5 = + (uint16_t)((in[6] >> 7) | (in[7] << 1) | ((in[8] & 0x03) << 9)); + uint16_t s6 = (uint16_t)((in[8] >> 2) | ((in[9] & 0x1f) << 6)); + uint16_t s7 = (uint16_t)((in[9] >> 5) | (in[10] << 3)); + out->c[i] = s0; + out->c[i + 1] = s1; + out->c[i + 2] = s2; + out->c[i + 3] = s3; + out->c[i + 4] = s4; + out->c[i + 5] = s5; + out->c[i + 6] = s6; + out->c[i + 7] = s7; + in += 11; + } +} + +template <> +void scalar_decode<5>(scalar *out, const uint8_t in[160]) { + for (int i = 0; i < DEGREE; i += 8) { + uint16_t s0 = (uint16_t)(in[0] & 0x1f); + uint16_t s1 = (uint16_t)((in[0] >> 5) | ((in[1] & 0x03) << 3)); + uint16_t s2 = (uint16_t)((in[1] >> 2) & 0x1f); + uint16_t s3 = (uint16_t)((in[1] >> 7) | ((in[2] & 0x0f) << 1)); + uint16_t s4 = (uint16_t)((in[2] >> 4) | ((in[3] & 0x01) << 4)); + uint16_t s5 = (uint16_t)((in[3] >> 1) & 0x1f); + uint16_t s6 = (uint16_t)((in[3] >> 6) | ((in[4] & 0x07) << 2)); + uint16_t s7 = (uint16_t)(in[4] >> 3); + // kPrime is 3329, so 5-bit values are always < kPrime. + out->c[i] = s0; + out->c[i + 1] = s1; + out->c[i + 2] = s2; + out->c[i + 3] = s3; + out->c[i + 4] = s4; + out->c[i + 5] = s5; + out->c[i + 6] = s6; + out->c[i + 7] = s7; + in += 5; + } +} + +template <> +void scalar_decode<1>(scalar *out, const uint8_t in[32]) { + for (int i = 0; i < DEGREE; i += 8) { + uint8_t in_byte = in[i / 8]; for (int j = 0; j < 8; j++) { - out->c[i + j] = in_byte & 1; - in_byte >>= 1; + out->c[i + j] = (in_byte >> j) & 1; } } } -// Decodes 32*|RANK|*|bits| bytes from |in| into |out|. It returns one on -// success or zero if any parsed value is >= |kPrime|. -template -static int vector_decode(vector *out, const uint8_t *in, int bits) { +// The inverse of `scalar_encode<12>`. Returns 1 iff the encoded scalar is +// valid, i.e. all components are < `kPrime`. Otherwise, returns 0 and the value +// of `out` is undefined. +int scalar_decode_12(scalar *out, const uint8_t in[384]) { + for (int i = 0; i < DEGREE; i += 2) { + uint16_t s0 = (uint16_t)(in[0] | ((in[1] & 0x0f) << 8)); + uint16_t s1 = (uint16_t)((in[1] >> 4) | (in[2] << 4)); + // This is only used with secret input when parsing the test-only + // semi-expanded format. Leaking information about invalid inputs is OK. + if (constant_time_declassify_int(s0 >= kPrime) || + constant_time_declassify_int(s1 >= kPrime)) { + return 0; + } + out->c[i] = s0; + out->c[i + 1] = s1; + in += 3; + } + return 1; +} + +// Decodes 32*`RANK`*`bits` bytes from `in` into `out`. This only supports `bits +// < 12`, necessary for decoding to be infallible. +template +inline void vector_decode(vector *out, const uint8_t *in) { + static_assert(bits < 12); for (int i = 0; i < RANK; i++) { - if (!scalar_decode(&out->v[i], in + i * bits * DEGREE / 8, bits)) { + scalar_decode(&out->v[i], in + i * bits * DEGREE / 8); + } +} + +// Decodes 32*`RANK`*12 bytes from `in` into `out` It returns one on success or +// zero if any parsed value is >= `kPrime`. +template +inline int vector_decode_12(vector *out, const uint8_t *in) { + for (int i = 0; i < RANK; i++) { + if (!scalar_decode_12(&out->v[i], in + i * 12 * DEGREE / 8)) { return 0; } } return 1; } -// Compresses (lossily) an input |x| mod 3329 into |bits| many bits by grouping +// Compresses (lossily) an input `x` mod 3329 into `bits` many bits by grouping // numbers close to each other together. The formula used is -// round(2^|bits|/kPrime*x) mod 2^|bits|. +// round(2^`bits`/kPrime*x) mod 2^`bits`. // Uses Barrett reduction to achieve constant time. Since we need both the // remainder (for rounding) and the quotient (as the result), we cannot use -// |reduce| here, but need to do the Barrett reduction directly. -static uint16_t compress(uint16_t x, int bits) { +// `reduce` here, but need to do the Barrett reduction directly. +inline uint16_t compress(uint16_t x, int bits) { uint32_t shifted = (uint32_t)x << bits; uint64_t product = (uint64_t)shifted * kBarrettMultiplier; uint32_t quotient = (uint32_t)(product >> kBarrettShift); @@ -595,30 +1020,30 @@ static uint16_t compress(uint16_t x, int bits) { return quotient & ((1 << bits) - 1); } -// Decompresses |x| by using an equi-distant representative. The formula is -// round(kPrime/2^|bits|*x). Note that 2^|bits| being the divisor allows us to +// Decompresses `x` by using an equi-distant representative. The formula is +// round(kPrime/2^`bits`*x). Note that 2^`bits` being the divisor allows us to // implement this logic using only bit operations. -uint16_t decompress(uint16_t x, int bits) { +inline uint16_t decompress(uint16_t x, int bits) { uint32_t product = (uint32_t)x * kPrime; uint32_t power = 1 << bits; - // This is |product| % power, since |power| is a power of 2. + // This is `product` % power, since `power` is a power of 2. uint32_t remainder = product & (power - 1); - // This is |product| / power, since |power| is a power of 2. + // This is `product` / power, since `power` is a power of 2. uint32_t lower = product >> bits; - // The rounding logic works since the first half of numbers mod |power| have a - // 0 as first bit, and the second half has a 1 as first bit, since |power| is - // a power of 2. As a 12 bit number, |remainder| is always positive, so we + // The rounding logic works since the first half of numbers mod `power` have a + // 0 as first bit, and the second half has a 1 as first bit, since `power` is + // a power of 2. As a 12 bit number, `remainder` is always positive, so we // will shift in 0s for a right shift. return lower + (remainder >> (bits - 1)); } -static void scalar_compress(scalar *s, int bits) { +inline void scalar_compress(scalar *s, int bits) { for (int i = 0; i < DEGREE; i++) { s->c[i] = compress(s->c[i], bits); } } -static void scalar_decompress(scalar *s, int bits) { +inline void scalar_decompress(scalar *s, int bits) { for (int i = 0; i < DEGREE; i++) { s->c[i] = decompress(s->c[i], bits); } @@ -648,41 +1073,40 @@ struct public_key { template struct private_key { - struct public_key pub; + public_key pub; vector s; uint8_t fo_failure_secret[32]; }; template -static void decrypt_cpa( - uint8_t out[32], const struct private_key *priv, - const uint8_t ciphertext[BCM_MLKEM768_CIPHERTEXT_BYTES]) { +inline void decrypt_cpa(uint8_t out[32], const private_key *priv, + const uint8_t ciphertext[MLKEM768_CIPHERTEXT_BYTES]) { constexpr int du = RANK == RANK768 ? kDU768 : kDU1024; constexpr int dv = RANK == RANK768 ? kDV768 : kDV1024; vector u; - vector_decode(&u, ciphertext, du); + vector_decode(&u, ciphertext); vector_decompress(&u, du); vector_ntt(&u); scalar v; - scalar_decode(&v, ciphertext + compressed_vector_size(RANK), dv); + scalar_decode(&v, ciphertext + compressed_vector_size(RANK)); scalar_decompress(&v, dv); scalar mask; scalar_inner_product(&mask, &priv->s, &u); scalar_inverse_ntt(&mask); scalar_sub(&v, &mask); scalar_compress(&v, 1); - scalar_encode_1(out, &v); + scalar_encode<1>(out, &v); } template -static bcm_status mlkem_marshal_public_key(CBB *out, - const struct public_key *pub) { +inline bcm_status mlkem_marshal_public_key(CBB *out, + const public_key *pub) { uint8_t *vector_output; if (!CBB_add_space(out, &vector_output, encoded_vector_size(RANK))) { return bcm_status::failure; } - vector_encode(vector_output, &pub->t, kLog2Prime); + vector_encode(vector_output, &pub->t); if (!CBB_add_bytes(out, pub->rho, sizeof(pub->rho))) { return bcm_status::failure; } @@ -690,9 +1114,15 @@ static bcm_status mlkem_marshal_public_key(CBB *out, } template -void mlkem_generate_key_external_seed( +inline bool mlkem_public_keys_equal(const public_key *a, + const public_key *b) { + return OPENSSL_memcmp(a->public_key_hash, b->public_key_hash, 32) == 0; +} + +template +void mlkem_generate_key_external_seed_no_self_test( uint8_t *out_encoded_public_key, private_key *priv, - const uint8_t seed[BCM_MLKEM_SEED_BYTES]) { + const uint8_t seed[MLKEM_SEED_BYTES]) { uint8_t augmented_seed[33]; OPENSSL_memcpy(augmented_seed, seed, 32); augmented_seed[32] = RANK; @@ -727,12 +1157,21 @@ void mlkem_generate_key_external_seed( OPENSSL_memcpy(priv->fo_failure_secret, seed + 32, 32); } +template +void mlkem_generate_key_external_seed(uint8_t *out_encoded_public_key, + private_key *priv, + const uint8_t seed[MLKEM_SEED_BYTES]) { + fips::ensure_keygen_self_test(); + mlkem_generate_key_external_seed_no_self_test(out_encoded_public_key, priv, + seed); +} + // Encrypts a message with given randomness to -// the ciphertext in |out|. Without applying the Fujisaki-Okamoto transform this +// the ciphertext in `out`. Without applying the Fujisaki-Okamoto transform this // would not result in a CCA secure scheme, since lattice schemes are vulnerable // to decryption failure oracles. template -void encrypt_cpa(uint8_t *out, const struct mlkem::public_key *pub, +void encrypt_cpa(uint8_t *out, const mlkem::public_key *pub, const uint8_t message[32], const uint8_t randomness[32]) { constexpr int du = RANK == RANK768 ? mlkem::kDU768 : mlkem::kDU1024; constexpr int dv = RANK == RANK768 ? mlkem::kDV768 : mlkem::kDV1024; @@ -757,20 +1196,20 @@ void encrypt_cpa(uint8_t *out, const struct mlkem::public_key *pub, scalar_inverse_ntt(&v); scalar_add(&v, &scalar_error); mlkem::scalar expanded_message; - scalar_decode_1(&expanded_message, message); + scalar_decode<1>(&expanded_message, message); scalar_decompress(&expanded_message, 1); scalar_add(&v, &expanded_message); vector_compress(&u, du); - vector_encode(out, &u, du); + vector_encode(out, &u); scalar_compress(&v, dv); - scalar_encode(out + mlkem::compressed_vector_size(RANK), &v, dv); + scalar_encode(out + mlkem::compressed_vector_size(RANK), &v); } // See section 6.3 template -void mlkem_decap(uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], - const uint8_t *ciphertext, - const struct private_key *priv) { +void mlkem_decap_no_self_test( + uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], + const uint8_t *ciphertext, const private_key *priv) { uint8_t decrypted[64]; decrypt_cpa(decrypted, priv, ciphertext); OPENSSL_memcpy(decrypted + 32, priv->pub.public_key_hash, @@ -778,8 +1217,8 @@ void mlkem_decap(uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], uint8_t key_and_randomness[64]; hash_g(key_and_randomness, decrypted, sizeof(decrypted)); constexpr size_t ciphertext_len = ciphertext_size(RANK); - uint8_t expected_ciphertext[BCM_MLKEM1024_CIPHERTEXT_BYTES]; - static_assert(ciphertext_len <= sizeof(expected_ciphertext), ""); + uint8_t expected_ciphertext[MLKEM1024_CIPHERTEXT_BYTES]; + static_assert(ciphertext_len <= sizeof(expected_ciphertext)); encrypt_cpa(expected_ciphertext, &priv->pub, decrypted, key_and_randomness + 32); @@ -788,45 +1227,56 @@ void mlkem_decap(uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], uint8_t mask = constant_time_eq_int_8( CRYPTO_memcmp(ciphertext, expected_ciphertext, ciphertext_len), 0); - for (int i = 0; i < BCM_MLKEM_SHARED_SECRET_BYTES; i++) { + for (int i = 0; i < MLKEM_SHARED_SECRET_BYTES; i++) { out_shared_secret[i] = constant_time_select_8(mask, key_and_randomness[i], failure_key[i]); } } -// mlkem_parse_public_key_no_hash parses |in| into |pub| but doesn't calculate -// the value of |pub->public_key_hash|. template -int mlkem_parse_public_key_no_hash(struct public_key *pub, CBS *in) { +void mlkem_decap(uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], + const uint8_t *ciphertext, const private_key *priv) { + fips::ensure_decap_self_test(); + mlkem_decap_no_self_test(out_shared_secret, ciphertext, priv); +} + +// mlkem_parse_public_key_with_trailing_data parses `in` into `pub` but leaves +// trailing data in `in` for the caller. +template +int mlkem_parse_public_key_with_trailing_data(public_key *pub, CBS *in) { + CBS orig_in = *in; CBS t_bytes; if (!CBS_get_bytes(in, &t_bytes, encoded_vector_size(RANK)) || - !vector_decode(&pub->t, CBS_data(&t_bytes), kLog2Prime) || + !vector_decode_12(&pub->t, CBS_data(&t_bytes)) || !CBS_copy_bytes(in, pub->rho, sizeof(pub->rho))) { return 0; } matrix_expand(&pub->m, pub->rho); + size_t pub_key_len = CBS_len(&orig_in) - CBS_len(in); + assert(pub_key_len == encoded_public_key_size(RANK)); + hash_h(pub->public_key_hash, CBS_data(&orig_in), pub_key_len); return 1; } template -int mlkem_parse_public_key(struct public_key *pub, CBS *in) { - CBS orig_in = *in; - if (!mlkem_parse_public_key_no_hash(pub, in) || // +int mlkem_parse_public_key(public_key *pub, CBS *in) { + if (!mlkem_parse_public_key_with_trailing_data(pub, in) || // CBS_len(in) != 0) { return 0; } - hash_h(pub->public_key_hash, CBS_data(&orig_in), CBS_len(&orig_in)); return 1; } template -int mlkem_parse_private_key(struct private_key *priv, CBS *in) { - CBS s_bytes; +int mlkem_parse_private_key(private_key *priv, CBS *in) { + CBS s_bytes, public_key_hash; if (!CBS_get_bytes(in, &s_bytes, encoded_vector_size(RANK)) || - !vector_decode(&priv->s, CBS_data(&s_bytes), kLog2Prime) || - !mlkem_parse_public_key_no_hash(&priv->pub, in) || - !CBS_copy_bytes(in, priv->pub.public_key_hash, - sizeof(priv->pub.public_key_hash)) || + !vector_decode_12(&priv->s, CBS_data(&s_bytes)) || + !mlkem_parse_public_key_with_trailing_data(&priv->pub, in) || + // We compute the public key hash ourselves, but check it matched. + !CBS_get_bytes(in, &public_key_hash, sizeof(priv->pub.public_key_hash)) || + !CBS_mem_equal(&public_key_hash, priv->pub.public_key_hash, + sizeof(priv->pub.public_key_hash)) || !CBS_copy_bytes(in, priv->fo_failure_secret, sizeof(priv->fo_failure_secret)) || CBS_len(in) != 0) { @@ -836,12 +1286,12 @@ int mlkem_parse_private_key(struct private_key *priv, CBS *in) { } template -int mlkem_marshal_private_key(CBB *out, const struct private_key *priv) { +int mlkem_marshal_private_key(CBB *out, const private_key *priv) { uint8_t *s_output; if (!CBB_add_space(out, &s_output, encoded_vector_size(RANK))) { return 0; } - vector_encode(s_output, &priv->s, kLog2Prime); + vector_encode(s_output, &priv->s); if (!bcm_success(mlkem_marshal_public_key(out, &priv->pub)) || !CBB_add_bytes(out, priv->pub.public_key_hash, sizeof(priv->pub.public_key_hash)) || @@ -852,182 +1302,69 @@ int mlkem_marshal_private_key(CBB *out, const struct private_key *priv) { return 1; } -struct public_key *public_key_768_from_external( - const struct BCM_mlkem768_public_key *external) { - static_assert(sizeof(struct BCM_mlkem768_public_key) >= - sizeof(struct public_key), - "MLKEM public key is too small"); - static_assert(alignof(struct BCM_mlkem768_public_key) >= - alignof(struct public_key), - "MLKEM public key alignment incorrect"); - return (struct public_key *)external; +static_assert(sizeof(MLKEM768_public_key) == sizeof(public_key)); +static_assert(alignof(MLKEM768_public_key) == alignof(public_key)); + +const public_key *public_key_768_from_external( + const MLKEM768_public_key *external) { + return reinterpret_cast *>(external); +} +public_key *public_key_768_from_external( + MLKEM768_public_key *external) { + return reinterpret_cast *>(external); +} +const MLKEM768_public_key *public_key_768_to_external( + const public_key *public_key) { + return reinterpret_cast(public_key); } -static struct public_key * -public_key_1024_from_external(const struct BCM_mlkem1024_public_key *external) { - static_assert(sizeof(struct BCM_mlkem1024_public_key) >= - sizeof(struct public_key), - "MLKEM1024 public key is too small"); - static_assert(alignof(struct BCM_mlkem1024_public_key) >= - alignof(struct public_key), - "MLKEM1024 public key alignment incorrect"); - return (struct public_key *)external; +static_assert(sizeof(MLKEM1024_public_key) == sizeof(public_key)); +static_assert(alignof(MLKEM1024_public_key) == alignof(public_key)); + +const public_key *public_key_1024_from_external( + const MLKEM1024_public_key *external) { + return reinterpret_cast *>(external); +} +public_key *public_key_1024_from_external( + MLKEM1024_public_key *external) { + return reinterpret_cast *>(external); } -struct private_key * -private_key_768_from_external(const struct BCM_mlkem768_private_key *external) { - static_assert(sizeof(struct BCM_mlkem768_private_key) >= - sizeof(struct private_key), - "MLKEM private key too small"); - static_assert(alignof(struct BCM_mlkem768_private_key) >= - alignof(struct private_key), - "MLKEM private key alignment incorrect"); - return (struct private_key *)external; +const MLKEM1024_public_key *public_key_1024_to_external( + const public_key *public_key) { + return reinterpret_cast(public_key); } -struct private_key * -private_key_1024_from_external( - const struct BCM_mlkem1024_private_key *external) { - static_assert(sizeof(struct BCM_mlkem1024_private_key) >= - sizeof(struct private_key), - "MLKEM1024 private key too small"); - static_assert(alignof(struct BCM_mlkem1024_private_key) >= - alignof(struct private_key), - "MLKEM1024 private key alignment incorrect"); - return (struct private_key *)external; +static_assert(sizeof(MLKEM768_private_key) >= sizeof(private_key)); +static_assert(alignof(MLKEM768_private_key) >= alignof(private_key)); + +const private_key *private_key_768_from_external( + const MLKEM768_private_key *external) { + return reinterpret_cast *>(external); +} +private_key *private_key_768_from_external( + MLKEM768_private_key *external) { + return reinterpret_cast *>(external); } -} // namespace -} // namespace mlkem +static_assert(sizeof(MLKEM1024_private_key) >= sizeof(private_key)); +static_assert(alignof(MLKEM1024_private_key) >= alignof(private_key)); -bcm_infallible BCM_mlkem768_generate_key( - uint8_t out_encoded_public_key[BCM_MLKEM768_PUBLIC_KEY_BYTES], - uint8_t optional_out_seed[BCM_MLKEM_SEED_BYTES], - struct BCM_mlkem768_private_key *out_private_key) { - uint8_t seed[BCM_MLKEM_SEED_BYTES]; - BCM_rand_bytes(seed, sizeof(seed)); - CONSTTIME_SECRET(seed, sizeof(seed)); - if (optional_out_seed) { - OPENSSL_memcpy(optional_out_seed, seed, sizeof(seed)); - } - BCM_mlkem768_generate_key_external_seed(out_encoded_public_key, - out_private_key, seed); - return bcm_infallible::approved; +const private_key *private_key_1024_from_external( + const MLKEM1024_private_key *external) { + return reinterpret_cast *>(external); } - -bcm_status BCM_mlkem768_private_key_from_seed( - struct BCM_mlkem768_private_key *out_private_key, const uint8_t *seed, - size_t seed_len) { - if (seed_len != BCM_MLKEM_SEED_BYTES) { - return bcm_status::failure; - } - uint8_t public_key_bytes[BCM_MLKEM768_PUBLIC_KEY_BYTES]; - BCM_mlkem768_generate_key_external_seed(public_key_bytes, out_private_key, - seed); - return bcm_status::approved; -} - -bcm_infallible BCM_mlkem1024_generate_key( - uint8_t out_encoded_public_key[BCM_MLKEM1024_PUBLIC_KEY_BYTES], - uint8_t optional_out_seed[BCM_MLKEM_SEED_BYTES], - struct BCM_mlkem1024_private_key *out_private_key) { - uint8_t seed[BCM_MLKEM_SEED_BYTES]; - BCM_rand_bytes(seed, sizeof(seed)); - CONSTTIME_SECRET(seed, sizeof(seed)); - if (optional_out_seed) { - OPENSSL_memcpy(optional_out_seed, seed, sizeof(seed)); - } - BCM_mlkem1024_generate_key_external_seed(out_encoded_public_key, - out_private_key, seed); - return bcm_infallible::approved; -} - -bcm_status BCM_mlkem1024_private_key_from_seed( - struct BCM_mlkem1024_private_key *out_private_key, const uint8_t *seed, - size_t seed_len) { - if (seed_len != BCM_MLKEM_SEED_BYTES) { - return bcm_status::failure; - } - uint8_t public_key_bytes[BCM_MLKEM1024_PUBLIC_KEY_BYTES]; - BCM_mlkem1024_generate_key_external_seed(public_key_bytes, out_private_key, - seed); - return bcm_status::approved; -} - -bcm_infallible BCM_mlkem768_generate_key_external_seed( - uint8_t out_encoded_public_key[BCM_MLKEM768_PUBLIC_KEY_BYTES], - struct BCM_mlkem768_private_key *out_private_key, - const uint8_t seed[BCM_MLKEM_SEED_BYTES]) { - mlkem::private_key *priv = - mlkem::private_key_768_from_external(out_private_key); - mlkem_generate_key_external_seed(out_encoded_public_key, priv, seed); - return bcm_infallible::approved; -} - -bcm_infallible BCM_mlkem1024_generate_key_external_seed( - uint8_t out_encoded_public_key[BCM_MLKEM1024_PUBLIC_KEY_BYTES], - struct BCM_mlkem1024_private_key *out_private_key, - const uint8_t seed[BCM_MLKEM_SEED_BYTES]) { - mlkem::private_key *priv = - mlkem::private_key_1024_from_external(out_private_key); - mlkem_generate_key_external_seed(out_encoded_public_key, priv, seed); - return bcm_infallible::approved; -} - -bcm_infallible BCM_mlkem768_public_from_private( - struct BCM_mlkem768_public_key *out_public_key, - const struct BCM_mlkem768_private_key *private_key) { - struct mlkem::public_key *const pub = - mlkem::public_key_768_from_external(out_public_key); - const struct mlkem::private_key *const priv = - mlkem::private_key_768_from_external(private_key); - *pub = priv->pub; - return bcm_infallible::approved; -} - -bcm_infallible BCM_mlkem1024_public_from_private( - struct BCM_mlkem1024_public_key *out_public_key, - const struct BCM_mlkem1024_private_key *private_key) { - struct mlkem::public_key *const pub = - mlkem::public_key_1024_from_external(out_public_key); - const struct mlkem::private_key *const priv = - mlkem::private_key_1024_from_external(private_key); - *pub = priv->pub; - return bcm_infallible::approved; -} - -// Calls |MLKEM768_encap_external_entropy| with random bytes from -// |BCM_rand_bytes| -bcm_infallible BCM_mlkem768_encap( - uint8_t out_ciphertext[BCM_MLKEM768_CIPHERTEXT_BYTES], - uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], - const struct BCM_mlkem768_public_key *public_key) { - uint8_t entropy[BCM_MLKEM_ENCAP_ENTROPY]; - BCM_rand_bytes(entropy, BCM_MLKEM_ENCAP_ENTROPY); - CONSTTIME_SECRET(entropy, BCM_MLKEM_ENCAP_ENTROPY); - BCM_mlkem768_encap_external_entropy(out_ciphertext, out_shared_secret, - public_key, entropy); - return bcm_infallible::approved; -} - -bcm_infallible BCM_mlkem1024_encap( - uint8_t out_ciphertext[BCM_MLKEM1024_CIPHERTEXT_BYTES], - uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], - const struct BCM_mlkem1024_public_key *public_key) { - uint8_t entropy[BCM_MLKEM_ENCAP_ENTROPY]; - BCM_rand_bytes(entropy, BCM_MLKEM_ENCAP_ENTROPY); - CONSTTIME_SECRET(entropy, BCM_MLKEM_ENCAP_ENTROPY); - BCM_mlkem1024_encap_external_entropy(out_ciphertext, out_shared_secret, - public_key, entropy); - return bcm_infallible::approved; +private_key *private_key_1024_from_external( + MLKEM1024_private_key *external) { + return reinterpret_cast *>(external); } // See section 6.2. template -void mlkem_encap_external_entropy( +void mlkem_encap_external_entropy_no_self_test( uint8_t *out_ciphertext, - uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], - const struct mlkem::public_key *pub, + uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], + const mlkem::public_key *pub, const uint8_t entropy[BCM_MLKEM_ENCAP_ENTROPY]) { uint8_t input[64]; OPENSSL_memcpy(input, entropy, BCM_MLKEM_ENCAP_ENTROPY); @@ -1038,75 +1375,424 @@ void mlkem_encap_external_entropy( encrypt_cpa(out_ciphertext, pub, entropy, key_and_randomness + 32); // The ciphertext is public. CONSTTIME_DECLASSIFY(out_ciphertext, mlkem::ciphertext_size(RANK)); - static_assert(BCM_MLKEM_SHARED_SECRET_BYTES == 32, ""); + static_assert(MLKEM_SHARED_SECRET_BYTES == 32); memcpy(out_shared_secret, key_and_randomness, 32); } -bcm_infallible BCM_mlkem768_encap_external_entropy( - uint8_t out_ciphertext[BCM_MLKEM768_CIPHERTEXT_BYTES], - uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], - const struct BCM_mlkem768_public_key *public_key, +template +void mlkem_encap_external_entropy( + uint8_t *out_ciphertext, + uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], + const mlkem::public_key *pub, const uint8_t entropy[BCM_MLKEM_ENCAP_ENTROPY]) { - const struct mlkem::public_key *pub = + fips::ensure_encap_self_test(); + mlkem_encap_external_entropy_no_self_test(out_ciphertext, out_shared_secret, + pub, entropy); +} + +namespace fips { + +#include "fips_known_values.inc" + +inline int keygen_self_test() { + uint8_t pub_key[MLKEM768_PUBLIC_KEY_BYTES]; + private_key priv; + static_assert(sizeof(kTestEntropy) >= MLKEM_SEED_BYTES); + mlkem_generate_key_external_seed_no_self_test(pub_key, &priv, kTestEntropy); + CBB cbb; + constexpr size_t kMarshaledPrivateKeySize = 2400; + uint8_t priv_bytes[kMarshaledPrivateKeySize]; + CBB_init_fixed(&cbb, priv_bytes, sizeof(priv_bytes)); + if (!mlkem_marshal_private_key(&cbb, &priv) || + !BORINGSSL_check_test(kExpectedPrivateKeyBytes, priv_bytes, + "ML-KEM keygen private key") || + !BORINGSSL_check_test(kExpectedPublicKeyBytes, pub_key, + "ML-KEM keygen public key")) { + return 0; + } + return 1; +} + +inline int encap_self_test() { + CBS cbs; + CBS_init(&cbs, kExpectedPublicKeyBytes, sizeof(kExpectedPublicKeyBytes)); + public_key pub; + if (!mlkem_parse_public_key(&pub, &cbs)) { + return 0; + } + uint8_t ciphertext[MLKEM768_CIPHERTEXT_BYTES]; + uint8_t shared_secret[MLKEM_SHARED_SECRET_BYTES]; + static_assert(sizeof(kTestEntropy) >= BCM_MLKEM_ENCAP_ENTROPY); + mlkem_encap_external_entropy_no_self_test(ciphertext, shared_secret, &pub, + kTestEntropy); + if (!BORINGSSL_check_test(ciphertext, kExpectedCiphertext, + "ML-KEM encap ciphertext") || + !BORINGSSL_check_test(kExpectedSharedSecret, shared_secret, + "ML-KEM encap shared secret")) { + return 0; + } + return 1; +} + +inline int decap_self_test() { + CBS cbs; + CBS_init(&cbs, kExpectedPrivateKeyBytes, sizeof(kExpectedPrivateKeyBytes)); + private_key priv; + if (!mlkem_parse_private_key(&priv, &cbs)) { + return 0; + } + uint8_t shared_secret[MLKEM_SHARED_SECRET_BYTES]; + mlkem_decap_no_self_test(shared_secret, kExpectedCiphertext, &priv); + if (!BORINGSSL_check_test(kExpectedSharedSecret, shared_secret, + "ML-KEM decap shared secret")) { + return 0; + } + + uint8_t implicit_rejection_shared_secret[MLKEM_SHARED_SECRET_BYTES]; + static_assert(sizeof(kExpectedPrivateKeyBytes) >= + sizeof(kExpectedCiphertext)); + mlkem_decap_no_self_test(implicit_rejection_shared_secret, + kExpectedPrivateKeyBytes, &priv); + if (!BORINGSSL_check_test(kExpectedImplicitRejectionSharedSecret, + implicit_rejection_shared_secret, + "ML-KEM decap implicit rejection shared secret")) { + return 0; + } + return 1; +} + +#if defined(BORINGSSL_FIPS) + +void ensure_keygen_self_test() { + CRYPTO_once(g_mlkem_keygen_self_test_once_bss_get(), []() { + if (!keygen_self_test()) { + BORINGSSL_FIPS_abort(); + } + }); +} + +void ensure_encap_self_test() { + CRYPTO_once(g_mlkem_encap_self_test_once_bss_get(), []() { + if (!encap_self_test()) { + BORINGSSL_FIPS_abort(); + } + }); +} + +void ensure_decap_self_test() { + CRYPTO_once(g_mlkem_decap_self_test_once_bss_get(), []() { + if (!decap_self_test()) { + BORINGSSL_FIPS_abort(); + } + }); +} + +#else + +void ensure_keygen_self_test() {} +void ensure_encap_self_test() {} +void ensure_decap_self_test() {} + +#endif +} // namespace fips + +} // namespace +} // namespace mlkem + +bcm_status bssl::BCM_mlkem768_check_fips( + const MLKEM768_private_key *private_key) { + const mlkem::private_key *priv = + mlkem::private_key_768_from_external(private_key); + + const uint8_t entropy[BCM_MLKEM_ENCAP_ENTROPY] = {1, 2, 3, 4}; + uint8_t ciphertext[MLKEM768_CIPHERTEXT_BYTES]; + uint8_t shared_secret[MLKEM_SHARED_SECRET_BYTES]; + mlkem_encap_external_entropy_no_self_test(ciphertext, shared_secret, + &priv->pub, entropy); + + if (boringssl_fips_break_test("MLKEM_PWCT")) { + shared_secret[0] ^= 1; + } + + 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) { + return bcm_status::failure; + } + return bcm_status::approved; +} + +bcm_status bssl::BCM_mlkem768_generate_key_fips( + uint8_t out_encoded_public_key[MLKEM768_PUBLIC_KEY_BYTES], + uint8_t optional_out_seed[MLKEM_SEED_BYTES], + MLKEM768_private_key *out_private_key) { + if (out_encoded_public_key == nullptr || out_private_key == nullptr) { + return bcm_status::failure; + } + BCM_mlkem768_generate_key(out_encoded_public_key, optional_out_seed, + out_private_key); + return BCM_mlkem768_check_fips(out_private_key); +} + +bcm_infallible bssl::BCM_mlkem768_generate_key( + uint8_t out_encoded_public_key[MLKEM768_PUBLIC_KEY_BYTES], + uint8_t optional_out_seed[MLKEM_SEED_BYTES], + MLKEM768_private_key *out_private_key) { + uint8_t seed[MLKEM_SEED_BYTES]; + BCM_rand_bytes(seed, sizeof(seed)); + CONSTTIME_SECRET(seed, sizeof(seed)); + if (optional_out_seed) { + OPENSSL_memcpy(optional_out_seed, seed, sizeof(seed)); + } + BCM_mlkem768_generate_key_external_seed(out_encoded_public_key, + out_private_key, seed); + return bcm_infallible::not_approved; +} + +bcm_status bssl::BCM_mlkem768_private_key_from_seed( + MLKEM768_private_key *out_private_key, const uint8_t *seed, + size_t seed_len) { + if (seed_len != MLKEM_SEED_BYTES) { + return bcm_status::failure; + } + + uint8_t public_key_bytes[MLKEM768_PUBLIC_KEY_BYTES]; + BCM_mlkem768_generate_key_external_seed(public_key_bytes, out_private_key, + seed); + return bcm_status::not_approved; +} + +bcm_status bssl::BCM_mlkem1024_check_fips( + const MLKEM1024_private_key *private_key) { + const mlkem::private_key *priv = + mlkem::private_key_1024_from_external(private_key); + + const uint8_t entropy[BCM_MLKEM_ENCAP_ENTROPY] = {1, 2, 3, 4}; + uint8_t ciphertext[MLKEM1024_CIPHERTEXT_BYTES]; + uint8_t shared_secret[MLKEM_SHARED_SECRET_BYTES]; + mlkem_encap_external_entropy_no_self_test(ciphertext, shared_secret, + &priv->pub, entropy); + + if (boringssl_fips_break_test("MLKEM_PWCT")) { + shared_secret[0] ^= 1; + } + + 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) { + return bcm_status::failure; + } + return bcm_status::approved; +} + +bcm_status bssl::BCM_mlkem1024_generate_key_fips( + uint8_t out_encoded_public_key[MLKEM1024_PUBLIC_KEY_BYTES], + uint8_t optional_out_seed[MLKEM_SEED_BYTES], + MLKEM1024_private_key *out_private_key) { + if (out_encoded_public_key == nullptr || out_private_key == nullptr) { + return bcm_status::failure; + } + BCM_mlkem1024_generate_key(out_encoded_public_key, optional_out_seed, + out_private_key); + return BCM_mlkem1024_check_fips(out_private_key); +} + +bcm_infallible bssl::BCM_mlkem1024_generate_key( + uint8_t out_encoded_public_key[MLKEM1024_PUBLIC_KEY_BYTES], + uint8_t optional_out_seed[MLKEM_SEED_BYTES], + MLKEM1024_private_key *out_private_key) { + uint8_t seed[MLKEM_SEED_BYTES]; + BCM_rand_bytes(seed, sizeof(seed)); + CONSTTIME_SECRET(seed, sizeof(seed)); + if (optional_out_seed) { + OPENSSL_memcpy(optional_out_seed, seed, sizeof(seed)); + } + BCM_mlkem1024_generate_key_external_seed(out_encoded_public_key, + out_private_key, seed); + return bcm_infallible::not_approved; +} + +bcm_status bssl::BCM_mlkem1024_private_key_from_seed( + MLKEM1024_private_key *out_private_key, const uint8_t *seed, + size_t seed_len) { + if (seed_len != MLKEM_SEED_BYTES) { + return bcm_status::failure; + } + uint8_t public_key_bytes[MLKEM1024_PUBLIC_KEY_BYTES]; + BCM_mlkem1024_generate_key_external_seed(public_key_bytes, out_private_key, + seed); + return bcm_status::not_approved; +} + +bcm_infallible bssl::BCM_mlkem768_generate_key_external_seed( + uint8_t out_encoded_public_key[MLKEM768_PUBLIC_KEY_BYTES], + MLKEM768_private_key *out_private_key, + const uint8_t seed[MLKEM_SEED_BYTES]) { + mlkem::private_key *priv = + mlkem::private_key_768_from_external(out_private_key); + mlkem_generate_key_external_seed(out_encoded_public_key, priv, seed); + return bcm_infallible::approved; +} + +bcm_infallible bssl::BCM_mlkem1024_generate_key_external_seed( + uint8_t out_encoded_public_key[MLKEM1024_PUBLIC_KEY_BYTES], + MLKEM1024_private_key *out_private_key, + const uint8_t seed[MLKEM_SEED_BYTES]) { + mlkem::private_key *priv = + mlkem::private_key_1024_from_external(out_private_key); + mlkem_generate_key_external_seed(out_encoded_public_key, priv, seed); + return bcm_infallible::approved; +} + +bcm_infallible bssl::BCM_mlkem768_public_from_private( + MLKEM768_public_key *out_public_key, + const MLKEM768_private_key *private_key) { + mlkem::public_key *const pub = + mlkem::public_key_768_from_external(out_public_key); + const mlkem::private_key *const priv = + mlkem::private_key_768_from_external(private_key); + *pub = priv->pub; + return bcm_infallible::approved; +} + +bcm_infallible bssl::BCM_mlkem1024_public_from_private( + MLKEM1024_public_key *out_public_key, + const MLKEM1024_private_key *private_key) { + mlkem::public_key *const pub = + mlkem::public_key_1024_from_external(out_public_key); + const mlkem::private_key *const priv = + mlkem::private_key_1024_from_external(private_key); + *pub = priv->pub; + return bcm_infallible::approved; +} + +const MLKEM768_public_key *bssl::BCM_mlkem768_public_of_private( + const MLKEM768_private_key *private_key) { + const mlkem::private_key *const priv = + mlkem::private_key_768_from_external(private_key); + return mlkem::public_key_768_to_external(&priv->pub); +} + +const MLKEM1024_public_key *bssl::BCM_mlkem1024_public_of_private( + const MLKEM1024_private_key *private_key) { + const mlkem::private_key *const priv = + mlkem::private_key_1024_from_external(private_key); + return mlkem::public_key_1024_to_external(&priv->pub); +} + +// Calls `MLKEM768_encap_external_entropy` with random bytes from +// `BCM_rand_bytes` +bcm_infallible bssl::BCM_mlkem768_encap( + uint8_t out_ciphertext[MLKEM768_CIPHERTEXT_BYTES], + uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], + const MLKEM768_public_key *public_key) { + uint8_t entropy[BCM_MLKEM_ENCAP_ENTROPY]; + BCM_rand_bytes(entropy, BCM_MLKEM_ENCAP_ENTROPY); + CONSTTIME_SECRET(entropy, BCM_MLKEM_ENCAP_ENTROPY); + BCM_mlkem768_encap_external_entropy(out_ciphertext, out_shared_secret, + public_key, entropy); + return bcm_infallible::approved; +} + +bcm_infallible bssl::BCM_mlkem1024_encap( + uint8_t out_ciphertext[MLKEM1024_CIPHERTEXT_BYTES], + uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], + const MLKEM1024_public_key *public_key) { + uint8_t entropy[BCM_MLKEM_ENCAP_ENTROPY]; + BCM_rand_bytes(entropy, BCM_MLKEM_ENCAP_ENTROPY); + CONSTTIME_SECRET(entropy, BCM_MLKEM_ENCAP_ENTROPY); + BCM_mlkem1024_encap_external_entropy(out_ciphertext, out_shared_secret, + public_key, entropy); + return bcm_infallible::approved; +} + +bcm_infallible bssl::BCM_mlkem768_encap_external_entropy( + uint8_t out_ciphertext[MLKEM768_CIPHERTEXT_BYTES], + uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], + const MLKEM768_public_key *public_key, + const uint8_t entropy[BCM_MLKEM_ENCAP_ENTROPY]) { + const mlkem::public_key *pub = mlkem::public_key_768_from_external(public_key); mlkem_encap_external_entropy(out_ciphertext, out_shared_secret, pub, entropy); return bcm_infallible::approved; } -bcm_infallible BCM_mlkem1024_encap_external_entropy( - uint8_t out_ciphertext[BCM_MLKEM1024_CIPHERTEXT_BYTES], - uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], - const struct BCM_mlkem1024_public_key *public_key, +bcm_infallible bssl::BCM_mlkem1024_encap_external_entropy( + uint8_t out_ciphertext[MLKEM1024_CIPHERTEXT_BYTES], + uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], + const MLKEM1024_public_key *public_key, const uint8_t entropy[BCM_MLKEM_ENCAP_ENTROPY]) { - const struct mlkem::public_key *pub = + const mlkem::public_key *pub = mlkem::public_key_1024_from_external(public_key); mlkem_encap_external_entropy(out_ciphertext, out_shared_secret, pub, entropy); return bcm_infallible::approved; } -bcm_status BCM_mlkem768_decap( - uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], +bcm_status bssl::BCM_mlkem768_decap( + uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], const uint8_t *ciphertext, size_t ciphertext_len, - const struct BCM_mlkem768_private_key *private_key) { - if (ciphertext_len != BCM_MLKEM768_CIPHERTEXT_BYTES) { - BCM_rand_bytes(out_shared_secret, BCM_MLKEM_SHARED_SECRET_BYTES); + const MLKEM768_private_key *private_key) { + if (ciphertext_len != MLKEM768_CIPHERTEXT_BYTES) { + BCM_rand_bytes(out_shared_secret, MLKEM_SHARED_SECRET_BYTES); return bcm_status::failure; } - const struct mlkem::private_key *priv = + const mlkem::private_key *priv = mlkem::private_key_768_from_external(private_key); mlkem_decap(out_shared_secret, ciphertext, priv); return bcm_status::approved; } -bcm_status BCM_mlkem1024_decap( - uint8_t out_shared_secret[BCM_MLKEM_SHARED_SECRET_BYTES], +bcm_status bssl::BCM_mlkem1024_decap( + uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], const uint8_t *ciphertext, size_t ciphertext_len, - const struct BCM_mlkem1024_private_key *private_key) { - if (ciphertext_len != BCM_MLKEM1024_CIPHERTEXT_BYTES) { - BCM_rand_bytes(out_shared_secret, BCM_MLKEM_SHARED_SECRET_BYTES); + const MLKEM1024_private_key *private_key) { + if (ciphertext_len != MLKEM1024_CIPHERTEXT_BYTES) { + BCM_rand_bytes(out_shared_secret, MLKEM_SHARED_SECRET_BYTES); return bcm_status::failure; } - const struct mlkem::private_key *priv = + const mlkem::private_key *priv = mlkem::private_key_1024_from_external(private_key); mlkem_decap(out_shared_secret, ciphertext, priv); return bcm_status::approved; } -bcm_status BCM_mlkem768_marshal_public_key( - CBB *out, const struct BCM_mlkem768_public_key *public_key) { +bcm_status bssl::BCM_mlkem768_marshal_public_key( + CBB *out, const MLKEM768_public_key *public_key) { return mlkem_marshal_public_key( out, mlkem::public_key_768_from_external(public_key)); } -bcm_status BCM_mlkem1024_marshal_public_key( - CBB *out, const struct BCM_mlkem1024_public_key *public_key) { +bcm_status bssl::BCM_mlkem1024_marshal_public_key( + CBB *out, const MLKEM1024_public_key *public_key) { return mlkem_marshal_public_key( out, mlkem::public_key_1024_from_external(public_key)); } -bcm_status BCM_mlkem768_parse_public_key( - struct BCM_mlkem768_public_key *public_key, CBS *in) { - struct mlkem::public_key *pub = +int bssl::BCM_mlkem768_public_keys_equal(const MLKEM768_public_key *a, + const MLKEM768_public_key *b) { + const auto *pub_a = mlkem::public_key_768_from_external(a); + const auto *pub_b = mlkem::public_key_768_from_external(b); + if (mlkem_public_keys_equal(pub_a, pub_b)) { + return 1; + } + return 0; +} + +int bssl::BCM_mlkem1024_public_keys_equal(const MLKEM1024_public_key *a, + const MLKEM1024_public_key *b) { + const auto *pub_a = mlkem::public_key_1024_from_external(a); + const auto *pub_b = mlkem::public_key_1024_from_external(b); + if (mlkem_public_keys_equal(pub_a, pub_b)) { + return 1; + } + return 0; +} + +bcm_status bssl::BCM_mlkem768_parse_public_key(MLKEM768_public_key *public_key, + CBS *in) { + mlkem::public_key *pub = mlkem::public_key_768_from_external(public_key); if (!mlkem_parse_public_key(pub, in)) { return bcm_status::failure; @@ -1114,9 +1800,9 @@ bcm_status BCM_mlkem768_parse_public_key( return bcm_status::approved; } -bcm_status BCM_mlkem1024_parse_public_key( - struct BCM_mlkem1024_public_key *public_key, CBS *in) { - struct mlkem::public_key *pub = +bcm_status bssl::BCM_mlkem1024_parse_public_key( + MLKEM1024_public_key *public_key, CBS *in) { + mlkem::public_key *pub = mlkem::public_key_1024_from_external(public_key); if (!mlkem_parse_public_key(pub, in)) { return bcm_status::failure; @@ -1124,9 +1810,9 @@ bcm_status BCM_mlkem1024_parse_public_key( return bcm_status::approved; } -bcm_status BCM_mlkem768_marshal_private_key( - CBB *out, const struct BCM_mlkem768_private_key *private_key) { - const struct mlkem::private_key *const priv = +bcm_status bssl::BCM_mlkem768_marshal_private_key( + CBB *out, const MLKEM768_private_key *private_key) { + const mlkem::private_key *const priv = mlkem::private_key_768_from_external(private_key); if (!mlkem_marshal_private_key(out, priv)) { return bcm_status::failure; @@ -1134,9 +1820,9 @@ bcm_status BCM_mlkem768_marshal_private_key( return bcm_status::approved; } -bcm_status BCM_mlkem1024_marshal_private_key( - CBB *out, const struct BCM_mlkem1024_private_key *private_key) { - const struct mlkem::private_key *const priv = +bcm_status bssl::BCM_mlkem1024_marshal_private_key( + CBB *out, const MLKEM1024_private_key *private_key) { + const mlkem::private_key *const priv = mlkem::private_key_1024_from_external(private_key); if (!mlkem_marshal_private_key(out, priv)) { return bcm_status::failure; @@ -1144,9 +1830,9 @@ bcm_status BCM_mlkem1024_marshal_private_key( return bcm_status::approved; } -bcm_status BCM_mlkem768_parse_private_key( - struct BCM_mlkem768_private_key *out_private_key, CBS *in) { - struct mlkem::private_key *const priv = +bcm_status bssl::BCM_mlkem768_parse_private_key( + MLKEM768_private_key *out_private_key, CBS *in) { + mlkem::private_key *const priv = mlkem::private_key_768_from_external(out_private_key); if (!mlkem_parse_private_key(priv, in)) { return bcm_status::failure; @@ -1154,12 +1840,17 @@ bcm_status BCM_mlkem768_parse_private_key( return bcm_status::approved; } -bcm_status BCM_mlkem1024_parse_private_key( - struct BCM_mlkem1024_private_key *out_private_key, CBS *in) { - struct mlkem::private_key *const priv = +bcm_status bssl::BCM_mlkem1024_parse_private_key( + MLKEM1024_private_key *out_private_key, CBS *in) { + mlkem::private_key *const priv = mlkem::private_key_1024_from_external(out_private_key); if (!mlkem_parse_private_key(priv, in)) { return bcm_status::failure; } return bcm_status::approved; } + +int bssl::boringssl_self_test_mlkem() { + return mlkem::fips::keygen_self_test() && mlkem::fips::encap_self_test() && + mlkem::fips::decap_self_test(); +} diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/rand/android_entropy_client.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/rand/android_entropy_client.cc.inc new file mode 100644 index 00000000..475fd2dd --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/rand/android_entropy_client.cc.inc @@ -0,0 +1,82 @@ +// Copyright 2020 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 + +#if defined(BORINGSSL_FIPS) && defined(OPENSSL_ANDROID) + +#include +#include +#include +#include +#include + +#include "internal.h" + +BSSL_NAMESPACE_BEGIN + +int bssl_get_seed_from_daemon(uint8_t *out_entropy, size_t *inout_entropy_len) { + const int sock = socket(AF_UNIX, SOCK_STREAM, 0); + if (sock < 0) { + return 0; + } + + struct sockaddr_un sun; + memset(&sun, 0, sizeof(sun)); + sun.sun_family = AF_UNIX; + static const char kSocketPath[] = "/dev/socket/prng_seeder"; + static_assert(sizeof(kSocketPath) <= UNIX_PATH_MAX, "kSocketPath too long"); + OPENSSL_memcpy(sun.sun_path, kSocketPath, sizeof(kSocketPath)); + + int ret = 0; + size_t done = 0; + if (connect(sock, (struct sockaddr *)&sun, sizeof(sun))) { + goto out; + } + + uint8_t buffer[BSSL_ENTROPY_DAEMON_RESPONSE_LEN]; + while (done < sizeof(buffer)) { + ssize_t n; + do { + n = read(sock, buffer + done, sizeof(buffer) - done); + } while (n == -1 && errno == EINTR); + + if (n < 1) { + goto out; + } + done += n; + } + + if (done != BSSL_ENTROPY_DAEMON_RESPONSE_LEN) { + // The daemon should always write `BSSL_ENTROPY_DAEMON_RESPONSE_LEN` bytes + // on every connection. + goto out; + } + + if (*inout_entropy_len > sizeof(buffer)) { + *inout_entropy_len = sizeof(buffer); + } + OPENSSL_memcpy(out_entropy, buffer, *inout_entropy_len); + ret = 1; + +out: + if (sock >= 0) { + close(sock); + } + return ret; +} + +BSSL_NAMESPACE_END + +#endif // FIPS && ANDROID diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/rand/ctrdrbg.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/rand/ctrdrbg.cc.inc index b67f963d..510b9f2e 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/rand/ctrdrbg.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/rand/ctrdrbg.cc.inc @@ -1,70 +1,224 @@ -/* Copyright 2017 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2017 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 "../../mem_internal.h" #include "../aes/internal.h" #include "../service_indicator/internal.h" #include "internal.h" +using namespace bssl; + // Section references in this file refer to SP 800-90Ar1: // http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf -// See table 3. -static const uint64_t kMaxReseedCount = UINT64_C(1) << 48; +// Also see table 3. +constexpr uint64_t kMaxReseedCount = UINT64_C(1) << 48; + +// Implements the BCC function as described in Section 10.3.3. +static void bcc(uint8_t out[AES_BLOCK_SIZE], const AES_KEY *aes_key, + const uint8_t *data, size_t data_len) { + // 1. chaining_value = 0^outlen. + uint8_t *chaining_value = out; + OPENSSL_memset(chaining_value, 0, AES_BLOCK_SIZE); + + // 2. n = len (data)/outlen. + BSSL_CHECK(data_len % AES_BLOCK_SIZE == 0); + const size_t n = data_len / AES_BLOCK_SIZE; + + for (size_t i = 0; i < n; i++) { + const uint8_t *block = data + (i * AES_BLOCK_SIZE); + uint8_t input_block[AES_BLOCK_SIZE]; + + // 4.1: input_block = chaining_value ⊕ block_i. + CRYPTO_xor16(input_block, chaining_value, block); + + // 4.2: chaining_value = Block_Encrypt (Key, input_block). + BCM_aes_encrypt(input_block, chaining_value, aes_key); + } + + // 5. output_block = chaining_value. +} + +// Implements the derivation function as described in Section 10.3.2. +static int block_cipher_df(uint8_t *out, size_t out_len, const uint8_t *input, + size_t input_len) { + // Constants for AES-256 + constexpr size_t kAESKeyLen = 32; + constexpr size_t kAESOutLen = AES_BLOCK_SIZE; + constexpr size_t kMaxNumBits = 512; + + if (out_len > kMaxNumBits / 8 || input_len > (1u << 30)) { + return 0; + } + + // 4. S = L || N || input_string || 0x80. + const size_t s_rawlen = sizeof(uint32_t) + sizeof(uint32_t) + input_len + 1; + // S is padded up to a block size. + const size_t s_len = (s_rawlen + kAESOutLen - 1) & ~(kAESOutLen - 1); + uint8_t iv_plus_s[/* space used below */ kAESOutLen + 4 + 4 + + CTR_DRBG_MAX_ENTROPY_LEN + CTR_DRBG_NONCE_LEN + + CTR_DRBG_SEED_LEN + 1 + + /* padding */ 7]; + if (kAESOutLen + s_len > sizeof(iv_plus_s)) { + return 0; + } + OPENSSL_memset(iv_plus_s, 0, sizeof(iv_plus_s)); + uint8_t *s_ptr = iv_plus_s + kAESOutLen; + // 2. L = len (input_string)/8. + CRYPTO_store_u32_be(s_ptr, (uint32_t)input_len); + s_ptr += sizeof(uint32_t); + // 3. N = number_of_bits_to_return/8. + CRYPTO_store_u32_be(s_ptr, (uint32_t)out_len); + s_ptr += sizeof(uint32_t); + OPENSSL_memcpy(s_ptr, input, input_len); + s_ptr += input_len; + *s_ptr = 0x80; + + uint8_t temp[kAESKeyLen + kAESOutLen]; + size_t temp_len = 0; + + // 8. K = leftmost (0x00010203...1D1E1F, keylen). + static const uint8_t kInitialKey[kAESKeyLen] = { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, + 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f}; + AES_KEY aes_key; + bcm_status status = + BCM_aes_set_encrypt_key(kInitialKey, 8 * sizeof(kInitialKey), &aes_key); + BSSL_CHECK(status != bcm_status::failure); + + // 7. i = 0. + uint32_t i = 0; + while (temp_len < sizeof(temp)) { + // 9.1 IV = i || 0^(outlen - len(i)). + CRYPTO_store_u32_be(iv_plus_s, i); + + // 9.2 temp = temp || BCC (K, (IV || S)). + bcc(temp + temp_len, &aes_key, iv_plus_s, kAESOutLen + s_len); + temp_len += kAESOutLen; + + // 9.3 i = i + 1. + i++; + } + + // 10. K = leftmost (temp, keylen). + uint8_t *const k = temp; + + // 11. X = select (temp, keylen+1, keylen+outlen). + uint8_t *const x = temp + kAESKeyLen; + + // 12. temp = the Null string. + temp_len = 0; + + // Create an AES key schedule for the final encryption steps. + status = BCM_aes_set_encrypt_key(k, kAESKeyLen * 8, &aes_key); + BSSL_CHECK(status != bcm_status::failure); + + // 13. While len (temp) < number_of_bits_to_return, do: + while (temp_len < out_len) { + // 13.1 X = Block_Encrypt (K, X). + BCM_aes_encrypt(x, x, &aes_key); + + // 13.2 temp = temp || X. + size_t to_copy = std::min(kAESOutLen, out_len - temp_len); + OPENSSL_memcpy(out + temp_len, x, to_copy); + temp_len += to_copy; + } + + return 1; +} CTR_DRBG_STATE *CTR_DRBG_new(const uint8_t entropy[CTR_DRBG_ENTROPY_LEN], const uint8_t *personalization, size_t personalization_len) { - CTR_DRBG_STATE *drbg = reinterpret_cast( - OPENSSL_malloc(sizeof(CTR_DRBG_STATE))); - if (drbg == NULL || - !CTR_DRBG_init(drbg, entropy, personalization, personalization_len)) { + CTR_DRBG_STATE *drbg = New(); + if (drbg == nullptr || + !CTR_DRBG_init(drbg, /*df=*/false, entropy, CTR_DRBG_ENTROPY_LEN, + /*nonce=*/nullptr, personalization, personalization_len)) { CTR_DRBG_free(drbg); - return NULL; + return nullptr; } return drbg; } -void CTR_DRBG_free(CTR_DRBG_STATE *state) { OPENSSL_free(state); } +CTR_DRBG_STATE *CTR_DRBG_new_df(const uint8_t *entropy, size_t entropy_len, + const uint8_t nonce[CTR_DRBG_NONCE_LEN], + const uint8_t *personalization, + size_t personalization_len) { + CTR_DRBG_STATE *drbg = New(); + if (drbg == nullptr || + !CTR_DRBG_init(drbg, /*df=*/true, entropy, entropy_len, nonce, + personalization, personalization_len)) { + CTR_DRBG_free(drbg); + return nullptr; + } -int CTR_DRBG_init(CTR_DRBG_STATE *drbg, - const uint8_t entropy[CTR_DRBG_ENTROPY_LEN], - const uint8_t *personalization, size_t personalization_len) { - // Section 10.2.1.3.1 - if (personalization_len > CTR_DRBG_ENTROPY_LEN) { + return drbg; +} + +void CTR_DRBG_free(CTR_DRBG_STATE *state) { Delete(state); } + +int bssl::CTR_DRBG_init(CTR_DRBG_STATE *drbg, int df, const uint8_t *entropy, + size_t entropy_len, + const uint8_t nonce[CTR_DRBG_NONCE_LEN], + const uint8_t *personalization, + size_t personalization_len) { + // Section 10.2.1.3.1 and 10.2.1.3.2 + if (personalization_len > CTR_DRBG_SEED_LEN || + (!df && entropy_len != CTR_DRBG_ENTROPY_LEN) || + (df && (entropy_len < CTR_DRBG_MIN_ENTROPY_LEN || + entropy_len > CTR_DRBG_MAX_ENTROPY_LEN)) || // + (df != (nonce != nullptr))) { return 0; } - uint8_t seed_material[CTR_DRBG_ENTROPY_LEN]; - OPENSSL_memcpy(seed_material, entropy, CTR_DRBG_ENTROPY_LEN); + uint8_t seed_material[CTR_DRBG_SEED_LEN]; + if (df) { + uint8_t pre_seed_material[CTR_DRBG_MAX_ENTROPY_LEN + CTR_DRBG_NONCE_LEN + + CTR_DRBG_SEED_LEN]; + OPENSSL_memcpy(pre_seed_material, entropy, entropy_len); + OPENSSL_memcpy(pre_seed_material + entropy_len, nonce, CTR_DRBG_NONCE_LEN); + OPENSSL_memcpy(pre_seed_material + entropy_len + CTR_DRBG_NONCE_LEN, + personalization, personalization_len); + const size_t pre_seed_material_length = + entropy_len + CTR_DRBG_NONCE_LEN + personalization_len; - for (size_t i = 0; i < personalization_len; i++) { - seed_material[i] ^= personalization[i]; + if (!block_cipher_df(seed_material, sizeof(seed_material), + pre_seed_material, pre_seed_material_length)) { + return 0; + } + } else { + OPENSSL_memcpy(seed_material, entropy, CTR_DRBG_ENTROPY_LEN); + for (size_t i = 0; i < personalization_len; i++) { + seed_material[i] ^= personalization[i]; + } } // Section 10.2.1.2 // kInitMask is the result of encrypting blocks with big-endian value 1, 2 // and 3 with the all-zero AES-256 key. - static const uint8_t kInitMask[CTR_DRBG_ENTROPY_LEN] = { + static const uint8_t kInitMask[CTR_DRBG_SEED_LEN] = { 0x53, 0x0f, 0x8a, 0xfb, 0xc7, 0x45, 0x36, 0xb9, 0xa9, 0x63, 0xb4, 0xf1, 0xc4, 0xcb, 0x73, 0x8b, 0xce, 0xa7, 0x40, 0x3d, 0x4d, 0x60, 0x6b, 0x6e, 0x07, 0x4e, 0xc5, 0xd3, 0xba, 0xf3, 0x9d, 0x18, 0x72, 0x60, 0x03, 0xca, @@ -75,43 +229,38 @@ int CTR_DRBG_init(CTR_DRBG_STATE *drbg, seed_material[i] ^= kInitMask[i]; } - drbg->ctr = aes_ctr_set_key(&drbg->ks, NULL, &drbg->block, seed_material, 32); + drbg->df = df; + drbg->ctr = + aes_ctr_set_key(&drbg->ks, nullptr, &drbg->block, seed_material, 32); OPENSSL_memcpy(drbg->counter, seed_material + 32, 16); drbg->reseed_counter = 1; return 1; } -static_assert(CTR_DRBG_ENTROPY_LEN % AES_BLOCK_SIZE == 0, +static_assert(CTR_DRBG_SEED_LEN % AES_BLOCK_SIZE == 0, "not a multiple of AES block size"); -// ctr_inc adds |n| to the last four bytes of |drbg->counter|, treated as a +// ctr_inc adds `n` to the last four bytes of `drbg->counter`, treated as a // big-endian number. static void ctr32_add(CTR_DRBG_STATE *drbg, uint32_t n) { uint32_t ctr = CRYPTO_load_u32_be(drbg->counter + 12); CRYPTO_store_u32_be(drbg->counter + 12, ctr + n); } -static int ctr_drbg_update(CTR_DRBG_STATE *drbg, const uint8_t *data, - size_t data_len) { - // Per section 10.2.1.2, |data_len| must be |CTR_DRBG_ENTROPY_LEN|. Here, we - // allow shorter inputs and right-pad them with zeros. This is equivalent to - // the specified algorithm but saves a copy in |CTR_DRBG_generate|. - if (data_len > CTR_DRBG_ENTROPY_LEN) { - return 0; - } - - uint8_t temp[CTR_DRBG_ENTROPY_LEN]; - for (size_t i = 0; i < CTR_DRBG_ENTROPY_LEN; i += AES_BLOCK_SIZE) { +static int ctr_drbg_update(CTR_DRBG_STATE *drbg, + const uint8_t data[CTR_DRBG_SEED_LEN]) { + uint8_t temp[CTR_DRBG_SEED_LEN]; + for (size_t i = 0; i < CTR_DRBG_SEED_LEN; i += AES_BLOCK_SIZE) { ctr32_add(drbg, 1); drbg->block(drbg->counter, temp + i, &drbg->ks); } - for (size_t i = 0; i < data_len; i++) { + for (size_t i = 0; i < CTR_DRBG_SEED_LEN; i++) { temp[i] ^= data[i]; } - drbg->ctr = aes_ctr_set_key(&drbg->ks, NULL, &drbg->block, temp, 32); + drbg->ctr = aes_ctr_set_key(&drbg->ks, nullptr, &drbg->block, temp, 32); OPENSSL_memcpy(drbg->counter, temp + 32, 16); return 1; @@ -121,23 +270,46 @@ int CTR_DRBG_reseed(CTR_DRBG_STATE *drbg, const uint8_t entropy[CTR_DRBG_ENTROPY_LEN], const uint8_t *additional_data, size_t additional_data_len) { - // Section 10.2.1.4 - uint8_t entropy_copy[CTR_DRBG_ENTROPY_LEN]; + return CTR_DRBG_reseed_ex(drbg, entropy, CTR_DRBG_ENTROPY_LEN, + additional_data, additional_data_len); +} - if (additional_data_len > 0) { - if (additional_data_len > CTR_DRBG_ENTROPY_LEN) { - return 0; - } - - OPENSSL_memcpy(entropy_copy, entropy, CTR_DRBG_ENTROPY_LEN); - for (size_t i = 0; i < additional_data_len; i++) { - entropy_copy[i] ^= additional_data[i]; - } - - entropy = entropy_copy; +int CTR_DRBG_reseed_ex(CTR_DRBG_STATE *drbg, const uint8_t *entropy, + size_t entropy_len, const uint8_t *additional_data, + size_t additional_data_len) { + if (additional_data_len > CTR_DRBG_SEED_LEN || + (drbg->df && (entropy_len > CTR_DRBG_MAX_ENTROPY_LEN || + entropy_len < CTR_DRBG_MIN_ENTROPY_LEN)) || + (!drbg->df && entropy_len != CTR_DRBG_ENTROPY_LEN)) { + return 0; } - if (!ctr_drbg_update(drbg, entropy, CTR_DRBG_ENTROPY_LEN)) { + uint8_t seed_material[CTR_DRBG_SEED_LEN]; + if (drbg->df) { + // Section 10.2.1.4.2 + uint8_t pre_seed_material[CTR_DRBG_MAX_ENTROPY_LEN + CTR_DRBG_SEED_LEN]; + static_assert(CTR_DRBG_MAX_ENTROPY_LEN <= sizeof(pre_seed_material)); + OPENSSL_memcpy(pre_seed_material, entropy, entropy_len); + OPENSSL_memcpy(pre_seed_material + entropy_len, additional_data, + additional_data_len); + const size_t pre_seed_material_len = entropy_len + additional_data_len; + + if (!block_cipher_df(seed_material, sizeof(seed_material), + pre_seed_material, pre_seed_material_len)) { + return 0; + } + } else { + // Section 10.2.1.4 + static_assert(CTR_DRBG_ENTROPY_LEN == sizeof(seed_material)); + OPENSSL_memcpy(seed_material, entropy, CTR_DRBG_ENTROPY_LEN); + if (additional_data_len > 0) { + for (size_t i = 0; i < additional_data_len; i++) { + seed_material[i] ^= additional_data[i]; + } + } + } + + if (!ctr_drbg_update(drbg, seed_material)) { return 0; } @@ -159,9 +331,26 @@ int CTR_DRBG_generate(CTR_DRBG_STATE *drbg, uint8_t *out, size_t out_len, return 0; } - if (additional_data_len != 0 && - !ctr_drbg_update(drbg, additional_data, additional_data_len)) { - return 0; + uint8_t processed_additional_data[CTR_DRBG_SEED_LEN]; + OPENSSL_memset(processed_additional_data, 0, + sizeof(processed_additional_data)); + if (additional_data_len != 0) { + if (drbg->df) { + if (!block_cipher_df(processed_additional_data, + sizeof(processed_additional_data), additional_data, + additional_data_len)) { + return 0; + } + } else { + if (additional_data_len > sizeof(processed_additional_data)) { + return 0; + } + OPENSSL_memcpy(processed_additional_data, additional_data, + additional_data_len); + } + if (!ctr_drbg_update(drbg, processed_additional_data)) { + return 0; + } } // kChunkSize is used to interact better with the cache. Since the AES-CTR @@ -170,7 +359,7 @@ int CTR_DRBG_generate(CTR_DRBG_STATE *drbg, uint8_t *out, size_t out_len, // the whole buffer, flushing the L1 cache, and then do another pass (missing // the cache every time) to “encrypt” it. The code can avoid this by // chunking. - static const size_t kChunkSize = 8 * 1024; + constexpr size_t kChunkSize = 8 * 1024; while (out_len >= AES_BLOCK_SIZE) { size_t todo = kChunkSize; @@ -198,9 +387,7 @@ int CTR_DRBG_generate(CTR_DRBG_STATE *drbg, uint8_t *out, size_t out_len, OPENSSL_memcpy(out, block, out_len); } - // Right-padding |additional_data| in step 2.2 is handled implicitly by - // |ctr_drbg_update|, to save a copy. - if (!ctr_drbg_update(drbg, additional_data, additional_data_len)) { + if (!ctr_drbg_update(drbg, processed_additional_data)) { return 0; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/rand/internal.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/rand/internal.h index 21c2755b..5be81e54 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/rand/internal.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/rand/internal.h @@ -1,19 +1,19 @@ -/* Copyright 2015 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2015 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. -#ifndef OPENSSL_HEADER_CRYPTO_RAND_INTERNAL_H -#define OPENSSL_HEADER_CRYPTO_RAND_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_RAND_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_RAND_INTERNAL_H #include #include @@ -21,64 +21,79 @@ #include "../../bcm_support.h" #include "../aes/internal.h" -#if defined(__cplusplus) -extern "C" { -#endif + +BSSL_NAMESPACE_BEGIN // rand_fork_unsafe_buffering_enabled returns whether fork-unsafe buffering has -// been enabled via |RAND_enable_fork_unsafe_buffering|. -int rand_fork_unsafe_buffering_enabled(void); +// been enabled via `RAND_enable_fork_unsafe_buffering`. +int rand_fork_unsafe_buffering_enabled(); + +BSSL_NAMESPACE_END // CTR_DRBG_STATE contains the state of a CTR_DRBG based on AES-256. See SP // 800-90Ar1. struct ctr_drbg_state_st { AES_KEY ks; - block128_f block; - ctr128_f ctr; + bssl::block128_f block; + bssl::ctr128_f ctr; uint8_t counter[16]; uint64_t reseed_counter; + int df; }; -// CTR_DRBG_init initialises |*drbg| given |CTR_DRBG_ENTROPY_LEN| bytes of -// entropy in |entropy| and, optionally, a personalization string up to -// |CTR_DRBG_ENTROPY_LEN| bytes in length. It returns one on success and zero -// on error. -OPENSSL_EXPORT int CTR_DRBG_init(CTR_DRBG_STATE *drbg, - const uint8_t entropy[CTR_DRBG_ENTROPY_LEN], +BSSL_NAMESPACE_BEGIN + +// CTR_DRBG_init initialises `*drbg` given `entropy_len` bytes of entropy in +// `entropy` and, optionally, a personalization string up to +// `CTR_DRBG_SEED_LEN` bytes in length. It returns one on success and zero on +// error. +// +// If `df` is false then `entropy_len` must be `CTR_DRBG_ENTROPY_LEN` and +// `nonce` must be nullptr. +OPENSSL_EXPORT int CTR_DRBG_init(CTR_DRBG_STATE *drbg, int df, + const uint8_t *entropy, size_t entropy_len, + const uint8_t nonce[CTR_DRBG_NONCE_LEN], const uint8_t *personalization, size_t personalization_len); +// BSSL_ENTROPY_DAEMON_RESPONSE_LEN is the number of bytes that the Android +// entropy daemon replies with. +#define BSSL_ENTROPY_DAEMON_RESPONSE_LEN (48 * 10 + 16) + +// bssl_get_seed_from_daemon fetches up to `*inout_entropy_len` bytes of +// entropy from the Android entropy daemon, writing them to `*out_entropy`. +// On successful exit, `*inout_entropy_len` contains the number of bytes +// written. Returns one on success and zero on error. +int bssl_get_seed_from_daemon(uint8_t *out_entropy, size_t *inout_entropy_len); + #if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM) -inline int have_rdrand(void) { return CRYPTO_is_RDRAND_capable(); } +inline int have_rdrand() { return CRYPTO_is_RDRAND_capable(); } // have_fast_rdrand returns true if RDRAND is supported and it's reasonably // fast. Concretely the latter is defined by whether the chip is Intel (fast) or // not (assumed slow). -inline int have_fast_rdrand(void) { +inline int have_fast_rdrand() { return CRYPTO_is_RDRAND_capable() && CRYPTO_is_intel_cpu(); } // CRYPTO_rdrand writes eight bytes of random data from the hardware RNG to -// |out|. It returns one on success or zero on hardware failure. -int CRYPTO_rdrand(uint8_t out[8]); +// `out`. It returns one on success or zero on hardware failure. +extern "C" int CRYPTO_rdrand(uint8_t out[8]); -// CRYPTO_rdrand_multiple8_buf fills |len| bytes at |buf| with random data from -// the hardware RNG. The |len| argument must be a multiple of eight. It returns +// CRYPTO_rdrand_multiple8_buf fills `len` bytes at `buf` with random data from +// the hardware RNG. The `len` argument must be a multiple of eight. It returns // one on success and zero on hardware failure. -int CRYPTO_rdrand_multiple8_buf(uint8_t *buf, size_t len); +extern "C" int CRYPTO_rdrand_multiple8_buf(uint8_t *buf, size_t len); #else // OPENSSL_X86_64 && !OPENSSL_NO_ASM -inline int have_rdrand(void) { return 0; } +inline int have_rdrand() { return 0; } -inline int have_fast_rdrand(void) { return 0; } +inline int have_fast_rdrand() { return 0; } #endif // OPENSSL_X86_64 && !OPENSSL_NO_ASM +BSSL_NAMESPACE_END -#if defined(__cplusplus) -} // extern C -#endif - -#endif // OPENSSL_HEADER_CRYPTO_RAND_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_RAND_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/rand/rand.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/rand/rand.cc.inc index 40185364..aa323154 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/rand/rand.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/rand/rand.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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 @@ -23,125 +23,257 @@ #include #include #include +#include +#include #include "../../bcm_support.h" +#include "../../mem_internal.h" #include "../bcm_interface.h" #include "../delocate.h" #include "internal.h" +#if defined(BORINGSSL_FIPS) +#include "../entropy/internal.h" +#endif -// It's assumed that the operating system always has an unfailing source of -// entropy which is accessed via |CRYPTO_sysrand[_for_seed]|. (If the operating -// system entropy source fails, it's up to |CRYPTO_sysrand| to abort the -// process—we don't try to handle it.) + +using namespace bssl; + +// # Entropy design // -// In addition, the hardware may provide a low-latency RNG. Intel's rdrand -// instruction is the canonical example of this. When a hardware RNG is -// available we don't need to worry about an RNG failure arising from fork()ing -// the process or moving a VM, so we can keep thread-local RNG state and use it -// as an additional-data input to CTR-DRBG. +// Each thread gets its own, thread-local DRBG. These are `rand_thread_state` +// objects. In non-FIPS mode these are seeded from the operating system. It's +// assumed that the operating system always has an unfailing source of entropy +// which is accessed via `CRYPTO_sysrand`. (If the operating system entropy +// source fails, it's up to `CRYPTO_sysrand` to abort the process—we don't try +// to handle it.) +// +// If running in FIPS mode, a compliant entropy source must be used to seed the +// thread-local DRBGs instead. That is either the BoringCrypto jitter source or, +// on Android, a source provided by the OS which is accessed via a UNIX domain +// socket. When seeding from these sources, OS entropy is still used via the +// "additional data" input to the DRBG. But, from a compliance perspective, +// this input is irrelevent. +// +// Since the jitter source takes some time to run, there is a single jitter +// source per address space. It's used to seed a DRBG (`core_drbg`) which, in +// turn, seeds the thread-local DRBGs. Android also uses this core DRBG design +// in order to keep things more uniform across platforms. +// +// The core DRBG will be reseeded in accordance with NIST's reseeding +// requirements. However, since our DRBG configuration allows for 2**48 +// generate calls before reseeding, it's unlikely that any process would +// observe a reseed of that DRBG. +// +// The thread-local DRBGs mean that we have to worry about the process fork()ing +// or the underlying VM getting cloned. Thus we try to mix entropy into each +// generation from the thread-local DRBGs. The hardware may provide a +// low-latency RNG. (Intel's rdrand instruction is the canonical example of +// this.) If available, that'll be used for this additional data. Otherwise +// we'll draw from the OS if it doesn't provide other fork-detection APIs. // // (We assume that the OS entropy is safe from fork()ing and VM duplication. // This might be a bit of a leap of faith, esp on Windows, but there's nothing // that we can do about it.) -// kReseedInterval is the number of generate calls made to CTR-DRBG before -// reseeding. -static const unsigned kReseedInterval = 4096; +#if defined(BORINGSSL_FIPS) +// This #if-block needs to be outside of the anonymous namespace: -// CRNGT_BLOCK_SIZE is the number of bytes in a “block” for the purposes of the -// continuous random number generator test in FIPS 140-2, section 4.9.2. -#define CRNGT_BLOCK_SIZE 16 +struct core_drbg { + CTR_DRBG_STATE drbg; + // calls is the number of generate calls made on `drbg` since it was last + // (re)seeded. This is bound by `kCoreReseedInterval`. + uint64_t calls = 0; +}; + +DEFINE_BSS_GET(struct core_drbg *, g_core_drbg, = nullptr) +DEFINE_STATIC_MUTEX(g_core_drbg_lock) +#endif // FIPS namespace { + +#if defined(BORINGSSL_FIPS) + +// The number of times we'll generate from the core DRBG before reseeding. +// This is within the permitted bounds but so high that this effectively means +// that we'll never reseed it. See SP 800-90Ar1 table 3. +constexpr uint64_t kCoreReseedInterval = (UINT64_C(1) << 48) - 1; +constexpr size_t kCoreDRBGEntropySize = 48; + +#if defined(OPENSSL_ANDROID) +// Android seeds from a system daemon which is responsible for getting +// entropy from a validated source. +void core_drbg_get_entropy(uint8_t entropy[kCoreDRBGEntropySize]) { + uint8_t daemon_buffer[BSSL_ENTROPY_DAEMON_RESPONSE_LEN]; + size_t daemon_buffer_len = sizeof(daemon_buffer); + if (!bssl_get_seed_from_daemon(daemon_buffer, &daemon_buffer_len)) { + // If the daemon isn't running then fallback to system entropy. + CRYPTO_sysrand(entropy, kCoreDRBGEntropySize); + return; + } + SHA384(daemon_buffer, daemon_buffer_len, entropy); +} +#else +// Non-Android platforms use the jitter source. +void core_drbg_get_entropy(uint8_t entropy[kCoreDRBGEntropySize]) { + // This runs the jitter source and takes some milliseconds. + for (unsigned i = 0; i < 100; i++) { + // The internal health checks of the jitter source may cause spurious + // failures, therefore we retry a number of times because failure + // to get entropy is fatal. + if (entropy::GetSeed(entropy)) { + return; + } + } + fprintf(stderr, "Persistent jitter source failure.\n"); + BORINGSSL_FIPS_abort(); +} +#endif + +struct core_drbg *core_drbg_get_locked() { + struct core_drbg **core = g_core_drbg_bss_get(); + if (*core != nullptr) { + return *core; + } + + uint8_t entropy[kCoreDRBGEntropySize]; + core_drbg_get_entropy(entropy); + + *core = New(); + if (!*core) { + BORINGSSL_FIPS_abort(); + } + + uint8_t nonce[CTR_DRBG_NONCE_LEN] = {0}; + static constexpr char kPersonalization[] = "BoringSSL"; + if (!CTR_DRBG_init(&(*core)->drbg, /*df=*/1, entropy, sizeof(entropy), nonce, + reinterpret_cast(kPersonalization), + sizeof(kPersonalization))) { + BORINGSSL_FIPS_abort(); + } + + return *core; +} + +// Draw a seed for a thread-local DRBG from the core DRBG. +void core_drbg_draw_seed(uint8_t *out_seed, size_t len) { + MutexWriteLock lock(g_core_drbg_lock_bss_get()); + + struct core_drbg *const core = core_drbg_get_locked(); + if (core->calls > kCoreReseedInterval) { + uint8_t reseed_entropy[kCoreDRBGEntropySize]; + core_drbg_get_entropy(reseed_entropy); + if (!CTR_DRBG_reseed(&core->drbg, reseed_entropy, + /*additional_data=*/nullptr, 0)) { + BORINGSSL_FIPS_abort(); + } + core->calls = 0; + } + + if (!CTR_DRBG_generate(&core->drbg, out_seed, len, + /*additional_data=*/nullptr, 0)) { + BORINGSSL_FIPS_abort(); + } + core->calls++; +} + +#endif // BORINGSSL_FIPS + +// kReseedInterval is the number of generate calls made to a thread-local +// CTR-DRBG before reseeding. +static const unsigned kReseedInterval = 4096; + // rand_thread_state contains the per-thread state for the RNG. struct rand_thread_state { CTR_DRBG_STATE drbg; uint64_t fork_generation; - // calls is the number of generate calls made on |drbg| since it was last - // (re)seeded. This is bound by |kReseedInterval|. + // calls is the number of generate calls made on `drbg` since it was last + // (re)seeded. This is bound by `kReseedInterval`. unsigned calls; - // last_block_valid is non-zero iff |last_block| contains data from - // |get_seed_entropy|. - int last_block_valid; - // fork_unsafe_buffering is non-zero iff, when |drbg| was last (re)seeded, + // fork_unsafe_buffering is non-zero iff, when `drbg` was last (re)seeded, // fork-unsafe buffering was enabled. int fork_unsafe_buffering; #if defined(BORINGSSL_FIPS) - // last_block contains the previous block from |get_seed_entropy|. - uint8_t last_block[CRNGT_BLOCK_SIZE]; - // next and prev form a NULL-terminated, double-linked list of all states in - // a process. + // next and prev form a nullptr-terminated, double-linked list of all states + // in a process. struct rand_thread_state *next, *prev; - // clear_drbg_lock synchronizes between uses of |drbg| and - // |rand_thread_state_clear_all| clearing it. This lock should be uncontended + // clear_drbg_lock synchronizes between uses of `drbg` and + // `rand_thread_state_clear_all` clearing it. This lock should be uncontended // in the common case, except on shutdown. - CRYPTO_MUTEX clear_drbg_lock; + Mutex clear_drbg_lock; #endif }; + } // namespace #if defined(BORINGSSL_FIPS) -// thread_states_list is the head of a linked-list of all |rand_thread_state| +// thread_states_list is the head of a linked-list of all `rand_thread_state` // objects in the process, one per thread. This is needed because FIPS requires -// that they be zeroed on process exit, but thread-local destructors aren't -// called when the whole process is exiting. -DEFINE_BSS_GET(struct rand_thread_state *, thread_states_list, nullptr) +// the ability to zero them on demand (AS09.28). BoringSSL triggers this with a +// destructor function. +DEFINE_BSS_GET(struct rand_thread_state *, thread_states_list, = nullptr) DEFINE_STATIC_MUTEX(thread_states_list_lock) -static void rand_thread_state_clear_all(void) __attribute__((destructor)); -static void rand_thread_state_clear_all(void) { - CRYPTO_MUTEX_lock_write(thread_states_list_lock_bss_get()); +static void rand_thread_state_clear_all() __attribute__((destructor)); +static void rand_thread_state_clear_all() { + thread_states_list_lock_bss_get()->LockWrite(); for (struct rand_thread_state *cur = *thread_states_list_bss_get(); - cur != NULL; cur = cur->next) { - CRYPTO_MUTEX_lock_write(&cur->clear_drbg_lock); + cur != nullptr; cur = cur->next) { + cur->clear_drbg_lock.LockWrite(); CTR_DRBG_clear(&cur->drbg); } + + g_core_drbg_lock_bss_get()->LockWrite(); + struct core_drbg **core = g_core_drbg_bss_get(); + if (*core) { + CTR_DRBG_clear(&(*core)->drbg); + } + // The locks are deliberately left locked so that any threads that are still - // running will hang if they try to call |BCM_rand_bytes|. It also ensures - // |rand_thread_state_free| cannot free any thread state while we've taken the + // running will hang if they try to call `BCM_rand_bytes`. It also ensures + // `rand_thread_state_free` cannot free any thread state while we've taken the // lock. } #endif -// rand_thread_state_free frees a |rand_thread_state|. This is called when a +// rand_thread_state_free frees a `rand_thread_state`. This is called when a // thread exits. static void rand_thread_state_free(void *state_in) { struct rand_thread_state *state = reinterpret_cast(state_in); - if (state_in == NULL) { + if (state_in == nullptr) { return; } #if defined(BORINGSSL_FIPS) - CRYPTO_MUTEX_lock_write(thread_states_list_lock_bss_get()); + thread_states_list_lock_bss_get()->LockWrite(); - if (state->prev != NULL) { + if (state->prev != nullptr) { state->prev->next = state->next; } else if (*thread_states_list_bss_get() == state) { - // |state->prev| may be NULL either if it is the head of the list, - // or if |state| is freed before it was added to the list at all. + // `state->prev` may be nullptr either if it is the head of the list, + // or if `state` is freed before it was added to the list at all. // Compare against the head of the list to distinguish these cases. *thread_states_list_bss_get() = state->next; } - if (state->next != NULL) { + if (state->next != nullptr) { state->next->prev = state->prev; } - CRYPTO_MUTEX_unlock_write(thread_states_list_lock_bss_get()); + thread_states_list_lock_bss_get()->UnlockWrite(); CTR_DRBG_clear(&state->drbg); #endif - OPENSSL_free(state); + Delete(state); } #if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM) && \ - !defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE) -// rdrand should only be called if either |have_rdrand| or |have_fast_rdrand| + !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) +// rdrand should only be called if either `have_rdrand` or `have_fast_rdrand` // returned true. static int rdrand(uint8_t *buf, const size_t len) { const size_t len_multiple8 = len & ~7; @@ -169,7 +301,7 @@ static int rdrand(uint8_t *buf, size_t len) { return 0; } #endif -bcm_status BCM_rand_bytes_hwrng(uint8_t *buf, const size_t len) { +bcm_status bssl::BCM_rand_bytes_hwrng(uint8_t *buf, const size_t len) { if (!have_rdrand()) { return bcm_status::failure; } @@ -181,155 +313,32 @@ bcm_status BCM_rand_bytes_hwrng(uint8_t *buf, const size_t len) { #if defined(BORINGSSL_FIPS) -// In passive entropy mode, entropy is supplied from outside of the module via -// |BCM_rand_load_entropy| and is stored in global instance of the following -// structure. - -struct entropy_buffer { - // bytes contains entropy suitable for seeding a DRBG. - uint8_t - bytes[CRNGT_BLOCK_SIZE + CTR_DRBG_ENTROPY_LEN * BORINGSSL_FIPS_OVERREAD]; - // bytes_valid indicates the number of bytes of |bytes| that contain valid - // data. - size_t bytes_valid; - // want_additional_input is true if any of the contents of |bytes| were - // obtained via a method other than from the kernel. In these cases entropy - // from the kernel is also provided via an additional input to the DRBG. - int want_additional_input; -}; - -DEFINE_BSS_GET(struct entropy_buffer, entropy_buffer, {}) -DEFINE_STATIC_MUTEX(entropy_buffer_lock) - -bcm_infallible BCM_rand_load_entropy(const uint8_t *entropy, size_t entropy_len, - int want_additional_input) { - struct entropy_buffer *const buffer = entropy_buffer_bss_get(); - - CRYPTO_MUTEX_lock_write(entropy_buffer_lock_bss_get()); - const size_t space = sizeof(buffer->bytes) - buffer->bytes_valid; - if (entropy_len > space) { - entropy_len = space; - } - - OPENSSL_memcpy(&buffer->bytes[buffer->bytes_valid], entropy, entropy_len); - buffer->bytes_valid += entropy_len; - buffer->want_additional_input |= want_additional_input && (entropy_len != 0); - CRYPTO_MUTEX_unlock_write(entropy_buffer_lock_bss_get()); - return bcm_infallible::not_approved; -} - -// get_seed_entropy fills |out_entropy_len| bytes of |out_entropy| from the -// global |entropy_buffer|. -static void get_seed_entropy(uint8_t *out_entropy, size_t out_entropy_len, - int *out_want_additional_input) { - struct entropy_buffer *const buffer = entropy_buffer_bss_get(); - if (out_entropy_len > sizeof(buffer->bytes)) { - abort(); - } - - CRYPTO_MUTEX_lock_write(entropy_buffer_lock_bss_get()); - while (buffer->bytes_valid < out_entropy_len) { - CRYPTO_MUTEX_unlock_write(entropy_buffer_lock_bss_get()); - RAND_need_entropy(out_entropy_len - buffer->bytes_valid); - CRYPTO_MUTEX_lock_write(entropy_buffer_lock_bss_get()); - } - - *out_want_additional_input = buffer->want_additional_input; - OPENSSL_memcpy(out_entropy, buffer->bytes, out_entropy_len); - OPENSSL_memmove(buffer->bytes, &buffer->bytes[out_entropy_len], - buffer->bytes_valid - out_entropy_len); - buffer->bytes_valid -= out_entropy_len; - if (buffer->bytes_valid == 0) { - buffer->want_additional_input = 0; - } - - CRYPTO_MUTEX_unlock_write(entropy_buffer_lock_bss_get()); -} - -// rand_get_seed fills |seed| with entropy. In some cases, it will additionally -// fill |additional_input| with entropy to supplement |seed|. It sets -// |*out_additional_input_len| to the number of extra bytes. +// rand_get_seed fills `seed` with entropy. Since, in FIPS mode, this entropy +// comes from the jitter source / system daemon, `additional_input` will also be +// filled with system entropy. static void rand_get_seed(struct rand_thread_state *state, uint8_t seed[CTR_DRBG_ENTROPY_LEN], - uint8_t additional_input[CTR_DRBG_ENTROPY_LEN], + uint8_t additional_input[CTR_DRBG_SEED_LEN], size_t *out_additional_input_len) { - uint8_t entropy_bytes[sizeof(state->last_block) + - CTR_DRBG_ENTROPY_LEN * BORINGSSL_FIPS_OVERREAD]; - uint8_t *entropy = entropy_bytes; - size_t entropy_len = sizeof(entropy_bytes); - - if (state->last_block_valid) { - // No need to fill |state->last_block| with entropy from the read. - entropy += sizeof(state->last_block); - entropy_len -= sizeof(state->last_block); - } - - int want_additional_input; - get_seed_entropy(entropy, entropy_len, &want_additional_input); - - if (!state->last_block_valid) { - OPENSSL_memcpy(state->last_block, entropy, sizeof(state->last_block)); - entropy += sizeof(state->last_block); - entropy_len -= sizeof(state->last_block); - } - - // See FIPS 140-2, section 4.9.2. This is the “continuous random number - // generator test” which causes the program to randomly abort. Hopefully the - // rate of failure is small enough not to be a problem in practice. - if (CRYPTO_memcmp(state->last_block, entropy, sizeof(state->last_block)) == - 0) { - fprintf(CRYPTO_get_stderr(), "CRNGT failed.\n"); - BORINGSSL_FIPS_abort(); - } - - assert(entropy_len % CRNGT_BLOCK_SIZE == 0); - for (size_t i = CRNGT_BLOCK_SIZE; i < entropy_len; i += CRNGT_BLOCK_SIZE) { - if (CRYPTO_memcmp(entropy + i - CRNGT_BLOCK_SIZE, entropy + i, - CRNGT_BLOCK_SIZE) == 0) { - fprintf(CRYPTO_get_stderr(), "CRNGT failed.\n"); - BORINGSSL_FIPS_abort(); - } - } - OPENSSL_memcpy(state->last_block, entropy + entropy_len - CRNGT_BLOCK_SIZE, - CRNGT_BLOCK_SIZE); - - assert(entropy_len == BORINGSSL_FIPS_OVERREAD * CTR_DRBG_ENTROPY_LEN); - OPENSSL_memcpy(seed, entropy, CTR_DRBG_ENTROPY_LEN); - - for (size_t i = 1; i < BORINGSSL_FIPS_OVERREAD; i++) { - for (size_t j = 0; j < CTR_DRBG_ENTROPY_LEN; j++) { - seed[j] ^= entropy[CTR_DRBG_ENTROPY_LEN * i + j]; - } - } - - // If we used something other than system entropy then also - // opportunistically read from the system. This avoids solely relying on the - // hardware once the entropy pool has been initialized. - *out_additional_input_len = 0; - if (want_additional_input && - CRYPTO_sysrand_if_available(additional_input, CTR_DRBG_ENTROPY_LEN)) { - *out_additional_input_len = CTR_DRBG_ENTROPY_LEN; - } + core_drbg_draw_seed(seed, CTR_DRBG_ENTROPY_LEN); + CRYPTO_sysrand(additional_input, CTR_DRBG_SEED_LEN); + *out_additional_input_len = CTR_DRBG_SEED_LEN; } #else -// rand_get_seed fills |seed| with entropy. In some cases, it will additionally -// fill |additional_input| with entropy to supplement |seed|. It sets -// |*out_additional_input_len| to the number of extra bytes. +// rand_get_seed fills `seed` with system entropy in a non-FIPS build. static void rand_get_seed(struct rand_thread_state *state, uint8_t seed[CTR_DRBG_ENTROPY_LEN], - uint8_t additional_input[CTR_DRBG_ENTROPY_LEN], + uint8_t additional_input[CTR_DRBG_SEED_LEN], size_t *out_additional_input_len) { - // If not in FIPS mode, we don't overread from the system entropy source and - // we don't depend only on the hardware RDRAND. - CRYPTO_sysrand_for_seed(seed, CTR_DRBG_ENTROPY_LEN); + CRYPTO_sysrand(seed, CTR_DRBG_ENTROPY_LEN); *out_additional_input_len = 0; } #endif -bcm_infallible BCM_rand_bytes_with_additional_data( +bcm_infallible bssl::BCM_rand_bytes_with_additional_data( uint8_t *out, size_t out_len, const uint8_t user_additional_data[32]) { if (out_len == 0) { return bcm_infallible::approved; @@ -348,18 +357,12 @@ bcm_infallible BCM_rand_bytes_with_additional_data( if (!have_fast_rdrand() || !rdrand(additional_data, sizeof(additional_data))) { // Without a hardware RNG to save us from address-space duplication, the OS - // entropy is used. This can be expensive (one read per |RAND_bytes| call) + // entropy is used. This can be expensive (one read per `RAND_bytes` call) // and so is disabled when we have fork detection, or if the application has // promised not to fork. if (fork_generation != 0 || fork_unsafe_buffering) { OPENSSL_memset(additional_data, 0, sizeof(additional_data)); - } else if (!have_rdrand()) { - // No alternative so block for OS entropy. - CRYPTO_sysrand(additional_data, sizeof(additional_data)); - } else if (!CRYPTO_sysrand_if_available(additional_data, - sizeof(additional_data)) && - !rdrand(additional_data, sizeof(additional_data))) { - // RDRAND failed: block for OS entropy. + } else { CRYPTO_sysrand(additional_data, sizeof(additional_data)); } } @@ -372,25 +375,26 @@ bcm_infallible BCM_rand_bytes_with_additional_data( struct rand_thread_state *state = reinterpret_cast( CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_RAND)); - if (state == NULL) { - state = reinterpret_cast( - OPENSSL_zalloc(sizeof(struct rand_thread_state))); - if (state == NULL || + if (state == nullptr) { + state = New(); + if (state == nullptr || !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); state = &stack_state; } - state->last_block_valid = 0; uint8_t seed[CTR_DRBG_ENTROPY_LEN]; - uint8_t personalization[CTR_DRBG_ENTROPY_LEN] = {0}; + uint8_t personalization[CTR_DRBG_SEED_LEN] = {0}; size_t personalization_len = 0; rand_get_seed(state, seed, personalization, &personalization_len); - if (!CTR_DRBG_init(&state->drbg, seed, personalization, - personalization_len)) { + if (!CTR_DRBG_init(&state->drbg, /*df=*/true, seed, + sizeof(seed) - CTR_DRBG_NONCE_LEN, + seed + sizeof(seed) - CTR_DRBG_NONCE_LEN, + personalization, personalization_len)) { abort(); } state->calls = 0; @@ -398,43 +402,42 @@ bcm_infallible BCM_rand_bytes_with_additional_data( state->fork_unsafe_buffering = fork_unsafe_buffering; #if defined(BORINGSSL_FIPS) - CRYPTO_MUTEX_init(&state->clear_drbg_lock); if (state != &stack_state) { - CRYPTO_MUTEX_lock_write(thread_states_list_lock_bss_get()); + MutexWriteLock lock(thread_states_list_lock_bss_get()); struct rand_thread_state **states_list = thread_states_list_bss_get(); state->next = *states_list; - if (state->next != NULL) { + if (state->next != nullptr) { state->next->prev = state; } - state->prev = NULL; + state->prev = nullptr; *states_list = state; - CRYPTO_MUTEX_unlock_write(thread_states_list_lock_bss_get()); } #endif } if (state->calls >= kReseedInterval || - // If we've forked since |state| was last seeded, reseed. + // If we've forked since `state` was last seeded, reseed. state->fork_generation != fork_generation || - // If |state| was seeded from a state with different fork-safety - // preferences, reseed. Suppose |state| was fork-safe, then forked into + // If `state` was seeded from a state with different fork-safety + // preferences, reseed. Suppose `state` was fork-safe, then forked into // two children, but each of the children never fork and disable fork // safety. The children must reseed to avoid working from the same PRNG // state. state->fork_unsafe_buffering != fork_unsafe_buffering) { uint8_t seed[CTR_DRBG_ENTROPY_LEN]; - uint8_t reseed_additional_data[CTR_DRBG_ENTROPY_LEN] = {0}; + uint8_t reseed_additional_data[CTR_DRBG_SEED_LEN] = {0}; size_t reseed_additional_data_len = 0; rand_get_seed(state, seed, reseed_additional_data, &reseed_additional_data_len); #if defined(BORINGSSL_FIPS) - // Take a read lock around accesses to |state->drbg|. This is needed to + // Take a read lock around accesses to `state->drbg`. This is needed to // avoid returning bad entropy if we race with - // |rand_thread_state_clear_all|. - CRYPTO_MUTEX_lock_read(&state->clear_drbg_lock); + // `rand_thread_state_clear_all`. + state->clear_drbg_lock.LockRead(); #endif - if (!CTR_DRBG_reseed(&state->drbg, seed, reseed_additional_data, - reseed_additional_data_len)) { + if (!CTR_DRBG_reseed_ex(&state->drbg, seed, sizeof(seed), + reseed_additional_data, + reseed_additional_data_len)) { abort(); } state->calls = 0; @@ -442,7 +445,7 @@ bcm_infallible BCM_rand_bytes_with_additional_data( state->fork_unsafe_buffering = fork_unsafe_buffering; } else { #if defined(BORINGSSL_FIPS) - CRYPTO_MUTEX_lock_read(&state->clear_drbg_lock); + state->clear_drbg_lock.LockRead(); #endif } @@ -461,7 +464,7 @@ bcm_infallible BCM_rand_bytes_with_additional_data( out += todo; out_len -= todo; // Though we only check before entering the loop, this cannot add enough to - // overflow a |size_t|. + // overflow a `size_t`. state->calls++; first_call = 0; } @@ -471,12 +474,12 @@ bcm_infallible BCM_rand_bytes_with_additional_data( } #if defined(BORINGSSL_FIPS) - CRYPTO_MUTEX_unlock_read(&state->clear_drbg_lock); + state->clear_drbg_lock.UnlockRead(); #endif return bcm_infallible::approved; } -bcm_infallible BCM_rand_bytes(uint8_t *out, size_t out_len) { +bcm_infallible bssl::BCM_rand_bytes(uint8_t *out, size_t out_len) { static const uint8_t kZeroAdditionalData[32] = {0}; BCM_rand_bytes_with_additional_data(out, out_len, kZeroAdditionalData); return bcm_infallible::approved; diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/blinding.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/blinding.cc.inc deleted file mode 100644 index bc1cb688..00000000 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/blinding.cc.inc +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ - -#include - -#include - -#include -#include -#include - -#include "../../internal.h" -#include "internal.h" - - -#define BN_BLINDING_COUNTER 32 - -struct bn_blinding_st { - BIGNUM *A; // The base blinding factor, Montgomery-encoded. - BIGNUM *Ai; // The inverse of the blinding factor, Montgomery-encoded. - unsigned counter; -}; - -static int bn_blinding_create_param(BN_BLINDING *b, const BIGNUM *e, - const BN_MONT_CTX *mont, BN_CTX *ctx); - -BN_BLINDING *BN_BLINDING_new(void) { - BN_BLINDING *ret = - reinterpret_cast(OPENSSL_zalloc(sizeof(BN_BLINDING))); - if (ret == NULL) { - return NULL; - } - - ret->A = BN_new(); - if (ret->A == NULL) { - goto err; - } - - ret->Ai = BN_new(); - if (ret->Ai == NULL) { - goto err; - } - - // The blinding values need to be created before this blinding can be used. - ret->counter = BN_BLINDING_COUNTER - 1; - - return ret; - -err: - BN_BLINDING_free(ret); - return NULL; -} - -void BN_BLINDING_free(BN_BLINDING *r) { - if (r == nullptr) { - return; - } - BN_free(r->A); - BN_free(r->Ai); - OPENSSL_free(r); -} - -void BN_BLINDING_invalidate(BN_BLINDING *b) { - b->counter = BN_BLINDING_COUNTER - 1; -} - -static int bn_blinding_update(BN_BLINDING *b, const BIGNUM *e, - const BN_MONT_CTX *mont, BN_CTX *ctx) { - if (++b->counter == BN_BLINDING_COUNTER) { - // re-create blinding parameters - if (!bn_blinding_create_param(b, e, mont, ctx)) { - goto err; - } - b->counter = 0; - } else { - if (!BN_mod_mul_montgomery(b->A, b->A, b->A, mont, ctx) || - !BN_mod_mul_montgomery(b->Ai, b->Ai, b->Ai, mont, ctx)) { - goto err; - } - } - - return 1; - -err: - // |A| and |Ai| may be in an inconsistent state so they both need to be - // replaced the next time this blinding is used. Note that this is only - // sufficient because support for |BN_BLINDING_NO_UPDATE| and - // |BN_BLINDING_NO_RECREATE| was previously dropped. - b->counter = BN_BLINDING_COUNTER - 1; - - return 0; -} - -int BN_BLINDING_convert(BIGNUM *n, BN_BLINDING *b, const BIGNUM *e, - const BN_MONT_CTX *mont, BN_CTX *ctx) { - // |n| is not Montgomery-encoded and |b->A| is. |BN_mod_mul_montgomery| - // cancels one Montgomery factor, so the resulting value of |n| is unencoded. - if (!bn_blinding_update(b, e, mont, ctx) || - !BN_mod_mul_montgomery(n, n, b->A, mont, ctx)) { - return 0; - } - - return 1; -} - -int BN_BLINDING_invert(BIGNUM *n, const BN_BLINDING *b, BN_MONT_CTX *mont, - BN_CTX *ctx) { - // |n| is not Montgomery-encoded and |b->A| is. |BN_mod_mul_montgomery| - // cancels one Montgomery factor, so the resulting value of |n| is unencoded. - return BN_mod_mul_montgomery(n, n, b->Ai, mont, ctx); -} - -static int bn_blinding_create_param(BN_BLINDING *b, const BIGNUM *e, - const BN_MONT_CTX *mont, BN_CTX *ctx) { - int no_inverse; - if (!BN_rand_range_ex(b->A, 1, &mont->N) || - // Compute |b->A|^-1 in Montgomery form. Note |BN_from_montgomery| + - // |BN_mod_inverse_blinded| is equivalent to, but more efficient than, - // |BN_mod_inverse_blinded| + |BN_to_montgomery|. - // - // We do not retry if |b->A| has no inverse. Finding a non-invertible - // value of |b->A| is equivalent to factoring |mont->N|. There is - // negligible probability of stumbling on one at random. - !BN_from_montgomery(b->Ai, b->A, mont, ctx) || - !BN_mod_inverse_blinded(b->Ai, &no_inverse, b->Ai, mont, ctx) || - // TODO(davidben): |BN_mod_exp_mont| internally computes the result in - // Montgomery form. Save a pair of Montgomery reductions and a - // multiplication by returning that value directly. - !BN_mod_exp_mont(b->A, b->A, e, &mont->N, ctx, mont) || - !BN_to_montgomery(b->A, b->A, mont, ctx)) { - OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); - return 0; - } - - return 1; -} diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/internal.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/internal.h index 55b10475..a5b88423 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/internal.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/internal.h @@ -1,14 +1,19 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. -#ifndef OPENSSL_HEADER_RSA_INTERNAL_H -#define OPENSSL_HEADER_RSA_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_RSA_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_RSA_INTERNAL_H #include @@ -16,71 +21,85 @@ #include #include "../../internal.h" - -#if defined(__cplusplus) -extern "C" { -#endif +#include "../../mem_internal.h" -typedef struct bn_blinding_st BN_BLINDING; +DECLARE_OPAQUE_STRUCT(rsa_st, RSAImpl) -struct rsa_st { - RSA_METHOD *meth; +BSSL_NAMESPACE_BEGIN - BIGNUM *n; - BIGNUM *e; - BIGNUM *d; - BIGNUM *p; - BIGNUM *q; - BIGNUM *dmp1; - BIGNUM *dmq1; - BIGNUM *iqmp; +// TODO(crbug.com/42290480): Raise this limit. 512-bit RSA was factored in 1999. +#define OPENSSL_RSA_MIN_MODULUS_BITS 512 + +// TODO(davidben): This is inside BCM because `RSA` is inside BCM, but BCM never +// uses this. Split the RSA type in two. +enum rsa_pss_params_t { + // No parameters. + // TODO(davidben): Remove this and use std::optional where appropriate. + rsa_pss_none = 0, + // RSA-PSS using SHA-256, MGF1 with SHA-256, salt length 32. + rsa_pss_sha256, + // RSA-PSS using SHA-384, MGF1 with SHA-384, salt length 48. + rsa_pss_sha384, + // RSA-PSS using SHA-512, MGF1 with SHA-512, salt length 64. + rsa_pss_sha512, +}; + +class RSAImpl : public rsa_st, public RefCounted { + public: + explicit RSAImpl(const ENGINE *engine); + + RSA_METHOD *meth = nullptr; + + UniquePtr n; + UniquePtr e; + UniquePtr d; + UniquePtr p; + UniquePtr q; + UniquePtr dmp1; + UniquePtr dmq1; + UniquePtr iqmp; // be careful using this if the RSA structure is shared - CRYPTO_EX_DATA ex_data; - CRYPTO_refcount_t references; - int flags; + CRYPTO_EX_DATA ex_data = {}; + int flags = 0; - CRYPTO_MUTEX lock; + Mutex lock; // Used to cache montgomery values. The creation of these values is protected - // by |lock|. - BN_MONT_CTX *mont_n; - BN_MONT_CTX *mont_p; - BN_MONT_CTX *mont_q; + // by `lock`. + UniquePtr mont_n; + UniquePtr mont_p; + UniquePtr mont_q; - // The following fields are copies of |d|, |dmp1|, and |dmq1|, respectively, + // The following fields are copies of `d`, `dmp1`, and `dmq1`, respectively, // but with the correct widths to prevent side channels. These must use // separate copies due to threading concerns caused by OpenSSL's API // mistakes. See https://github.com/openssl/openssl/issues/5158 and - // the |freeze_private_key| implementation. - BIGNUM *d_fixed, *dmp1_fixed, *dmq1_fixed; + // the `freeze_private_key` implementation. + UniquePtr d_fixed, dmp1_fixed, dmq1_fixed; - // iqmp_mont is q^-1 mod p in Montgomery form, using |mont_p|. - BIGNUM *iqmp_mont; + // iqmp_mont is q^-1 mod p in Montgomery form, using `mont_p`. + UniquePtr iqmp_mont; - // num_blindings contains the size of the |blindings| and |blindings_inuse| - // arrays. This member and the |blindings_inuse| array are protected by - // |lock|. - size_t num_blindings; - // blindings is an array of BN_BLINDING structures that can be reserved by a - // thread by locking |lock| and changing the corresponding element in - // |blindings_inuse| from 0 to 1. - BN_BLINDING **blindings; - unsigned char *blindings_inuse; - uint64_t blinding_fork_generation; + // pss_params is the RSA-PSS parameters associated with the key. This is not + // used by the low-level RSA implementation, just the EVP layer. + bssl::rsa_pss_params_t pss_params = bssl::rsa_pss_none; // private_key_frozen is one if the key has been used for a private key // operation and may no longer be mutated. - unsigned private_key_frozen:1; -}; + unsigned private_key_frozen = 0; + private: + friend RefCounted; + ~RSAImpl(); +}; #define RSA_PKCS1_PADDING_SIZE 11 // Default implementations of RSA operations. -const RSA_METHOD *RSA_default_method(void); +const RSA_METHOD *RSA_default_method(); int rsa_default_sign_raw(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, const uint8_t *in, size_t in_len, @@ -89,15 +108,6 @@ int rsa_default_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in, size_t len); -BN_BLINDING *BN_BLINDING_new(void); -void BN_BLINDING_free(BN_BLINDING *b); -void BN_BLINDING_invalidate(BN_BLINDING *b); -int BN_BLINDING_convert(BIGNUM *n, BN_BLINDING *b, const BIGNUM *e, - const BN_MONT_CTX *mont_ctx, BN_CTX *ctx); -int BN_BLINDING_invert(BIGNUM *n, const BN_BLINDING *b, BN_MONT_CTX *mont_ctx, - BN_CTX *ctx); - - int PKCS1_MGF1(uint8_t *out, size_t len, const uint8_t *seed, size_t seed_len, const EVP_MD *md); int RSA_padding_add_PKCS1_type_1(uint8_t *to, size_t to_len, @@ -108,34 +118,29 @@ int RSA_padding_check_PKCS1_type_1(uint8_t *out, size_t *out_len, int RSA_padding_add_none(uint8_t *to, size_t to_len, const uint8_t *from, size_t from_len); -// rsa_check_public_key checks that |rsa|'s public modulus and exponent are +// rsa_check_public_key checks that `rsa`'s public modulus and exponent are // within DoS bounds. int rsa_check_public_key(const RSA *rsa); // rsa_private_transform_no_self_test calls either the method-specific -// |private_transform| function (if given) or the generic one. See the comment -// for |private_transform| in |rsa_meth_st|. +// `private_transform` function (if given) or the generic one. See the comment +// for `private_transform` in `rsa_meth_st`. int rsa_private_transform_no_self_test(RSA *rsa, uint8_t *out, const uint8_t *in, size_t len); -// rsa_private_transform acts the same as |rsa_private_transform_no_self_test| +// rsa_private_transform acts the same as `rsa_private_transform_no_self_test` // but, in FIPS mode, performs an RSA self test before calling the default RSA // implementation. int rsa_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in, size_t len); -// rsa_invalidate_key is called after |rsa| has been mutated, to invalidate +// rsa_invalidate_key is called after `rsa` has been mutated, to invalidate // fields derived from the original structure. This function assumes exclusive -// access to |rsa|. In particular, no other thread may be concurrently signing, -// etc., with |rsa|. +// access to `rsa`. In particular, no other thread may be concurrently signing, +// etc., with `rsa`. void rsa_invalidate_key(RSA *rsa); -// This constant is exported for test purposes. -extern const BN_ULONG kBoringSSLRSASqrtTwo[]; -extern const size_t kBoringSSLRSASqrtTwoLen; - - // Functions that avoid self-tests. // // Self-tests need to call functions that don't try and ensure that the @@ -157,9 +162,6 @@ int rsa_sign_no_self_test(int hash_nid, const uint8_t *digest, size_t digest_len, uint8_t *out, unsigned *out_len, RSA *rsa); +BSSL_NAMESPACE_END -#if defined(__cplusplus) -} // extern C -#endif - -#endif // OPENSSL_HEADER_RSA_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_RSA_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/padding.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/padding.cc.inc index 2dee31c6..cb205c0d 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/padding.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/padding.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -24,8 +29,10 @@ #include "internal.h" -int RSA_padding_add_PKCS1_type_1(uint8_t *to, size_t to_len, - const uint8_t *from, size_t from_len) { +using namespace bssl; + +int bssl::RSA_padding_add_PKCS1_type_1(uint8_t *to, size_t to_len, + const uint8_t *from, size_t from_len) { // See RFC 8017, section 9.2. if (to_len < RSA_PKCS1_PADDING_SIZE) { OPENSSL_PUT_ERROR(RSA, RSA_R_KEY_SIZE_TOO_SMALL); @@ -45,9 +52,9 @@ int RSA_padding_add_PKCS1_type_1(uint8_t *to, size_t to_len, return 1; } -int RSA_padding_check_PKCS1_type_1(uint8_t *out, size_t *out_len, - size_t max_out, const uint8_t *from, - size_t from_len) { +int bssl::RSA_padding_check_PKCS1_type_1(uint8_t *out, size_t *out_len, + size_t max_out, const uint8_t *from, + size_t from_len) { // See RFC 8017, section 9.2. This is part of signature verification and thus // does not need to run in constant-time. if (from_len < 2) { @@ -97,8 +104,8 @@ int RSA_padding_check_PKCS1_type_1(uint8_t *out, size_t *out_len, return 1; } -int RSA_padding_add_none(uint8_t *to, size_t to_len, const uint8_t *from, - size_t from_len) { +int bssl::RSA_padding_add_none(uint8_t *to, size_t to_len, const uint8_t *from, + size_t from_len) { if (from_len > to_len) { OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); return 0; @@ -113,11 +120,10 @@ int RSA_padding_add_none(uint8_t *to, size_t to_len, const uint8_t *from, return 1; } -int PKCS1_MGF1(uint8_t *out, size_t len, const uint8_t *seed, size_t seed_len, - const EVP_MD *md) { +int bssl::PKCS1_MGF1(uint8_t *out, size_t len, const uint8_t *seed, + size_t seed_len, const EVP_MD *md) { int ret = 0; - EVP_MD_CTX ctx; - EVP_MD_CTX_init(&ctx); + ScopedEVP_MD_CTX ctx; FIPS_service_indicator_lock_state(); size_t md_len = EVP_MD_size(md); @@ -128,21 +134,21 @@ int PKCS1_MGF1(uint8_t *out, size_t len, const uint8_t *seed, size_t seed_len, counter[1] = (uint8_t)(i >> 16); counter[2] = (uint8_t)(i >> 8); counter[3] = (uint8_t)i; - if (!EVP_DigestInit_ex(&ctx, md, NULL) || - !EVP_DigestUpdate(&ctx, seed, seed_len) || - !EVP_DigestUpdate(&ctx, counter, sizeof(counter))) { + if (!EVP_DigestInit_ex(ctx.get(), md, nullptr) || + !EVP_DigestUpdate(ctx.get(), seed, seed_len) || + !EVP_DigestUpdate(ctx.get(), counter, sizeof(counter))) { goto err; } if (md_len <= len) { - if (!EVP_DigestFinal_ex(&ctx, out, NULL)) { + if (!EVP_DigestFinal_ex(ctx.get(), out, nullptr)) { goto err; } out += md_len; len -= md_len; } else { uint8_t digest[EVP_MAX_MD_SIZE]; - if (!EVP_DigestFinal_ex(&ctx, digest, NULL)) { + if (!EVP_DigestFinal_ex(ctx.get(), digest, nullptr)) { goto err; } OPENSSL_memcpy(out, digest, len); @@ -153,7 +159,6 @@ int PKCS1_MGF1(uint8_t *out, size_t len, const uint8_t *seed, size_t seed_len, ret = 1; err: - EVP_MD_CTX_cleanup(&ctx); FIPS_service_indicator_unlock_state(); return ret; } @@ -163,34 +168,31 @@ static const uint8_t kPSSZeroes[] = {0, 0, 0, 0, 0, 0, 0, 0}; int RSA_verify_PKCS1_PSS_mgf1(const RSA *rsa, const uint8_t *mHash, const EVP_MD *Hash, const EVP_MD *mgf1Hash, const uint8_t *EM, int sLen) { - if (mgf1Hash == NULL) { + if (mgf1Hash == nullptr) { mgf1Hash = Hash; } int ret = 0; - uint8_t *DB = NULL; + uint8_t *DB = nullptr; const uint8_t *H; - EVP_MD_CTX ctx; - EVP_MD_CTX_init(&ctx); + ScopedEVP_MD_CTX ctx; unsigned MSBits; size_t emLen, maskedDBLen, salt_start; FIPS_service_indicator_lock_state(); - // Negative sLen has special meanings: - // -1 sLen == hLen - // -2 salt length is autorecovered from signature - // -N reserved size_t hLen = EVP_MD_size(Hash); - if (sLen == -1) { + if (sLen == RSA_PSS_SALTLEN_DIGEST) { sLen = (int)hLen; - } else if (sLen == -2) { - sLen = -2; - } else if (sLen < -2) { + } else if (sLen == RSA_PSS_SALTLEN_AUTO) { + // Leave `sLen` negative, which will trigger the logic below to recover and + // allow any salt length. + } else if (sLen < 0) { + // Other negative values are reserved. OPENSSL_PUT_ERROR(RSA, RSA_R_SLEN_CHECK_FAILED); goto err; } - MSBits = (BN_num_bits(rsa->n) - 1) & 0x7; + MSBits = (RSA_bits(rsa) - 1) & 0x7; emLen = RSA_size(rsa); if (EM[0] & (0xFF << MSBits)) { OPENSSL_PUT_ERROR(RSA, RSA_R_FIRST_OCTET_INVALID); @@ -200,7 +202,7 @@ int RSA_verify_PKCS1_PSS_mgf1(const RSA *rsa, const uint8_t *mHash, EM++; emLen--; } - // |sLen| may be -2 for the non-standard salt length recovery mode. + // `sLen` may be negative for the non-standard salt length recovery mode. if (emLen < hLen + 2 || (sLen >= 0 && emLen < hLen + (size_t)sLen + 2)) { OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE); goto err; @@ -242,11 +244,11 @@ int RSA_verify_PKCS1_PSS_mgf1(const RSA *rsa, const uint8_t *mHash, goto err; } uint8_t H_[EVP_MAX_MD_SIZE]; - if (!EVP_DigestInit_ex(&ctx, Hash, NULL) || - !EVP_DigestUpdate(&ctx, kPSSZeroes, sizeof(kPSSZeroes)) || - !EVP_DigestUpdate(&ctx, mHash, hLen) || - !EVP_DigestUpdate(&ctx, DB + salt_start, maskedDBLen - salt_start) || - !EVP_DigestFinal_ex(&ctx, H_, NULL)) { + if (!EVP_DigestInit_ex(ctx.get(), Hash, nullptr) || + !EVP_DigestUpdate(ctx.get(), kPSSZeroes, sizeof(kPSSZeroes)) || + !EVP_DigestUpdate(ctx.get(), mHash, hLen) || + !EVP_DigestUpdate(ctx.get(), DB + salt_start, maskedDBLen - salt_start) || + !EVP_DigestFinal_ex(ctx.get(), H_, nullptr)) { goto err; } if (OPENSSL_memcmp(H_, H, hLen) != 0) { @@ -258,7 +260,6 @@ int RSA_verify_PKCS1_PSS_mgf1(const RSA *rsa, const uint8_t *mHash, err: OPENSSL_free(DB); - EVP_MD_CTX_cleanup(&ctx); FIPS_service_indicator_unlock_state(); return ret; } @@ -267,24 +268,26 @@ int RSA_padding_add_PKCS1_PSS_mgf1(const RSA *rsa, unsigned char *EM, const unsigned char *mHash, const EVP_MD *Hash, const EVP_MD *mgf1Hash, int sLenRequested) { - int ret = 0, digest_ok; + int ret = 0; + ScopedEVP_MD_CTX ctx; size_t maskedDBLen, MSBits, emLen; size_t hLen; - unsigned char *H, *salt = NULL, *p; + unsigned char *H, *salt = nullptr, *p; - if (mgf1Hash == NULL) { + if (mgf1Hash == nullptr) { mgf1Hash = Hash; } FIPS_service_indicator_lock_state(); hLen = EVP_MD_size(Hash); - if (BN_is_zero(rsa->n)) { + unsigned rsa_bits = RSA_bits(rsa); + if (rsa_bits == 0) { OPENSSL_PUT_ERROR(RSA, RSA_R_EMPTY_PUBLIC_KEY); goto err; } - MSBits = (BN_num_bits(rsa->n) - 1) & 0x7; + MSBits = (rsa_bits - 1) & 0x7; emLen = RSA_size(rsa); if (MSBits == 0) { assert(emLen >= 1); @@ -297,16 +300,14 @@ int RSA_padding_add_PKCS1_PSS_mgf1(const RSA *rsa, unsigned char *EM, goto err; } - // Negative sLenRequested has special meanings: - // -1 sLen == hLen - // -2 salt length is maximized - // -N reserved size_t sLen; - if (sLenRequested == -1) { + if (sLenRequested == RSA_PSS_SALTLEN_DIGEST) { sLen = hLen; - } else if (sLenRequested == -2) { + } else if (sLenRequested == RSA_PSS_SALTLEN_AUTO) { + // Use the maximum possible salt length. sLen = emLen - hLen - 2; } else if (sLenRequested < 0) { + // Other negative values are reserved. OPENSSL_PUT_ERROR(RSA, RSA_R_SLEN_CHECK_FAILED); goto err; } else { @@ -328,15 +329,11 @@ int RSA_padding_add_PKCS1_PSS_mgf1(const RSA *rsa, unsigned char *EM, maskedDBLen = emLen - hLen - 1; H = EM + maskedDBLen; - EVP_MD_CTX ctx; - EVP_MD_CTX_init(&ctx); - digest_ok = EVP_DigestInit_ex(&ctx, Hash, NULL) && - EVP_DigestUpdate(&ctx, kPSSZeroes, sizeof(kPSSZeroes)) && - EVP_DigestUpdate(&ctx, mHash, hLen) && - EVP_DigestUpdate(&ctx, salt, sLen) && - EVP_DigestFinal_ex(&ctx, H, NULL); - EVP_MD_CTX_cleanup(&ctx); - if (!digest_ok) { + if (!EVP_DigestInit_ex(ctx.get(), Hash, nullptr) || + !EVP_DigestUpdate(ctx.get(), kPSSZeroes, sizeof(kPSSZeroes)) || + !EVP_DigestUpdate(ctx.get(), mHash, hLen) || + !EVP_DigestUpdate(ctx.get(), salt, sLen) || + !EVP_DigestFinal_ex(ctx.get(), H, nullptr)) { goto err; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/rsa.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/rsa.cc.inc index c6e1b235..9a41223f 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/rsa.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/rsa.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -13,6 +18,8 @@ #include #include +#include + #include #include #include @@ -21,40 +28,41 @@ #include #include #include -#include #include "../../internal.h" +#include "../../mem_internal.h" #include "../bcm_interface.h" #include "../bn/internal.h" #include "../delocate.h" #include "internal.h" +using namespace bssl; + // RSA_R_BLOCK_TYPE_IS_NOT_02 is part of the legacy SSLv23 padding scheme. // Cryptography.io depends on this error code. OPENSSL_DECLARE_ERROR_REASON(RSA, BLOCK_TYPE_IS_NOT_02) DEFINE_STATIC_EX_DATA_CLASS(g_rsa_ex_data_class) -static int bn_dup_into(BIGNUM **dst, const BIGNUM *src) { - if (src == NULL) { +static int bn_dup_into(UniquePtr *dst, const BIGNUM *src) { + if (src == nullptr) { OPENSSL_PUT_ERROR(RSA, ERR_R_PASSED_NULL_PARAMETER); return 0; } - BN_free(*dst); - *dst = BN_dup(src); - return *dst != NULL; + dst->reset(BN_dup(src)); + return *dst != nullptr; } RSA *RSA_new_public_key(const BIGNUM *n, const BIGNUM *e) { - RSA *rsa = RSA_new(); - if (rsa == NULL || // + RSAImpl *rsa = FromOpaque(RSA_new()); + if (rsa == nullptr || // !bn_dup_into(&rsa->n, n) || // !bn_dup_into(&rsa->e, e) || // !RSA_check_key(rsa)) { RSA_free(rsa); - return NULL; + return nullptr; } return rsa; @@ -63,8 +71,8 @@ RSA *RSA_new_public_key(const BIGNUM *n, const BIGNUM *e) { RSA *RSA_new_private_key(const BIGNUM *n, const BIGNUM *e, const BIGNUM *d, const BIGNUM *p, const BIGNUM *q, const BIGNUM *dmp1, const BIGNUM *dmq1, const BIGNUM *iqmp) { - RSA *rsa = RSA_new(); - if (rsa == NULL || // + RSAImpl *rsa = FromOpaque(RSA_new()); + if (rsa == nullptr || // !bn_dup_into(&rsa->n, n) || // !bn_dup_into(&rsa->e, e) || // !bn_dup_into(&rsa->d, d) || // @@ -75,7 +83,7 @@ RSA *RSA_new_private_key(const BIGNUM *n, const BIGNUM *e, const BIGNUM *d, !bn_dup_into(&rsa->iqmp, iqmp) || // !RSA_check_key(rsa)) { RSA_free(rsa); - return NULL; + return nullptr; } return rsa; @@ -83,23 +91,23 @@ RSA *RSA_new_private_key(const BIGNUM *n, const BIGNUM *e, const BIGNUM *d, RSA *RSA_new_private_key_no_crt(const BIGNUM *n, const BIGNUM *e, const BIGNUM *d) { - RSA *rsa = RSA_new(); - if (rsa == NULL || // + RSAImpl *rsa = FromOpaque(RSA_new()); + if (rsa == nullptr || // !bn_dup_into(&rsa->n, n) || // !bn_dup_into(&rsa->e, e) || // !bn_dup_into(&rsa->d, d) || // !RSA_check_key(rsa)) { RSA_free(rsa); - return NULL; + return nullptr; } return rsa; } RSA *RSA_new_private_key_no_e(const BIGNUM *n, const BIGNUM *d) { - RSA *rsa = RSA_new(); - if (rsa == NULL) { - return NULL; + RSAImpl *rsa = FromOpaque(RSA_new()); + if (rsa == nullptr) { + return nullptr; } rsa->flags |= RSA_FLAG_NO_PUBLIC_EXPONENT; @@ -107,16 +115,16 @@ RSA *RSA_new_private_key_no_e(const BIGNUM *n, const BIGNUM *d) { !bn_dup_into(&rsa->d, d) || // !RSA_check_key(rsa)) { RSA_free(rsa); - return NULL; + return nullptr; } return rsa; } RSA *RSA_new_public_key_large_e(const BIGNUM *n, const BIGNUM *e) { - RSA *rsa = RSA_new(); - if (rsa == NULL) { - return NULL; + RSAImpl *rsa = FromOpaque(RSA_new()); + if (rsa == nullptr) { + return nullptr; } rsa->flags |= RSA_FLAG_LARGE_PUBLIC_EXPONENT; @@ -124,7 +132,7 @@ RSA *RSA_new_public_key_large_e(const BIGNUM *n, const BIGNUM *e) { !bn_dup_into(&rsa->e, e) || // !RSA_check_key(rsa)) { RSA_free(rsa); - return NULL; + return nullptr; } return rsa; @@ -134,9 +142,9 @@ RSA *RSA_new_private_key_large_e(const BIGNUM *n, const BIGNUM *e, const BIGNUM *d, const BIGNUM *p, const BIGNUM *q, const BIGNUM *dmp1, const BIGNUM *dmq1, const BIGNUM *iqmp) { - RSA *rsa = RSA_new(); - if (rsa == NULL) { - return NULL; + RSAImpl *rsa = FromOpaque(RSA_new()); + if (rsa == nullptr) { + return nullptr; } rsa->flags |= RSA_FLAG_LARGE_PUBLIC_EXPONENT; @@ -150,165 +158,151 @@ RSA *RSA_new_private_key_large_e(const BIGNUM *n, const BIGNUM *e, !bn_dup_into(&rsa->iqmp, iqmp) || // !RSA_check_key(rsa)) { RSA_free(rsa); - return NULL; + return nullptr; } return rsa; } -RSA *RSA_new(void) { return RSA_new_method(NULL); } +RSAImpl::RSAImpl(const ENGINE *engine) + : RefCounted(CheckSubClass()), + meth(engine ? ENGINE_get_RSA_method(engine) : nullptr) { + if (meth == nullptr) { + meth = const_cast(RSA_default_method()); + } + METHOD_ref(meth); + flags = meth->flags; + CRYPTO_new_ex_data(&ex_data); +} + +RSA *RSA_new() { return RSA_new_method(nullptr); } RSA *RSA_new_method(const ENGINE *engine) { - RSA *rsa = reinterpret_cast(OPENSSL_zalloc(sizeof(RSA))); - if (rsa == NULL) { - return NULL; + UniquePtr rsa(New(engine)); + if (rsa == nullptr) { + return nullptr; } - if (engine) { - rsa->meth = ENGINE_get_RSA_method(engine); - } - - if (rsa->meth == NULL) { - rsa->meth = (RSA_METHOD *)RSA_default_method(); - } - METHOD_ref(rsa->meth); - - rsa->references = 1; - rsa->flags = rsa->meth->flags; - CRYPTO_MUTEX_init(&rsa->lock); - CRYPTO_new_ex_data(&rsa->ex_data); - - if (rsa->meth->init && !rsa->meth->init(rsa)) { - CRYPTO_free_ex_data(g_rsa_ex_data_class_bss_get(), rsa, &rsa->ex_data); - CRYPTO_MUTEX_cleanup(&rsa->lock); + if (rsa->meth->init && !rsa->meth->init(rsa.get())) { METHOD_unref(rsa->meth); - OPENSSL_free(rsa); - return NULL; + rsa->meth = nullptr; + return nullptr; } - return rsa; + return rsa.release(); } RSA *RSA_new_method_no_e(const ENGINE *engine, const BIGNUM *n) { - RSA *rsa = RSA_new_method(engine); - if (rsa == NULL || !bn_dup_into(&rsa->n, n)) { + RSAImpl *rsa = FromOpaque(RSA_new_method(engine)); + if (rsa == nullptr || !bn_dup_into(&rsa->n, n)) { RSA_free(rsa); - return NULL; + return nullptr; } rsa->flags |= RSA_FLAG_NO_PUBLIC_EXPONENT; return rsa; } +RSAImpl::~RSAImpl() { + if (meth != nullptr && meth->finish != nullptr) { + meth->finish(this); + } + METHOD_unref(meth); + + CRYPTO_free_ex_data(g_rsa_ex_data_class_bss_get(), &ex_data); +} + void RSA_free(RSA *rsa) { - if (rsa == NULL) { - return; + if (rsa != nullptr) { + FromOpaque(rsa)->DecRefInternal(); } - - if (!CRYPTO_refcount_dec_and_test_zero(&rsa->references)) { - return; - } - - if (rsa->meth->finish) { - rsa->meth->finish(rsa); - } - METHOD_unref(rsa->meth); - - CRYPTO_free_ex_data(g_rsa_ex_data_class_bss_get(), rsa, &rsa->ex_data); - - BN_free(rsa->n); - BN_free(rsa->e); - BN_free(rsa->d); - BN_free(rsa->p); - BN_free(rsa->q); - BN_free(rsa->dmp1); - BN_free(rsa->dmq1); - BN_free(rsa->iqmp); - rsa_invalidate_key(rsa); - CRYPTO_MUTEX_cleanup(&rsa->lock); - OPENSSL_free(rsa); } int RSA_up_ref(RSA *rsa) { - CRYPTO_refcount_inc(&rsa->references); + FromOpaque(rsa)->UpRefInternal(); return 1; } -unsigned RSA_bits(const RSA *rsa) { return BN_num_bits(rsa->n); } +unsigned RSA_bits(const RSA *rsa) { + return BN_num_bits(FromOpaque(rsa)->n.get()); +} -const BIGNUM *RSA_get0_n(const RSA *rsa) { return rsa->n; } +const BIGNUM *RSA_get0_n(const RSA *rsa) { return FromOpaque(rsa)->n.get(); } -const BIGNUM *RSA_get0_e(const RSA *rsa) { return rsa->e; } +const BIGNUM *RSA_get0_e(const RSA *rsa) { return FromOpaque(rsa)->e.get(); } -const BIGNUM *RSA_get0_d(const RSA *rsa) { return rsa->d; } +const BIGNUM *RSA_get0_d(const RSA *rsa) { return FromOpaque(rsa)->d.get(); } -const BIGNUM *RSA_get0_p(const RSA *rsa) { return rsa->p; } +const BIGNUM *RSA_get0_p(const RSA *rsa) { return FromOpaque(rsa)->p.get(); } -const BIGNUM *RSA_get0_q(const RSA *rsa) { return rsa->q; } +const BIGNUM *RSA_get0_q(const RSA *rsa) { return FromOpaque(rsa)->q.get(); } -const BIGNUM *RSA_get0_dmp1(const RSA *rsa) { return rsa->dmp1; } +const BIGNUM *RSA_get0_dmp1(const RSA *rsa) { + return FromOpaque(rsa)->dmp1.get(); +} -const BIGNUM *RSA_get0_dmq1(const RSA *rsa) { return rsa->dmq1; } +const BIGNUM *RSA_get0_dmq1(const RSA *rsa) { + return FromOpaque(rsa)->dmq1.get(); +} -const BIGNUM *RSA_get0_iqmp(const RSA *rsa) { return rsa->iqmp; } +const BIGNUM *RSA_get0_iqmp(const RSA *rsa) { + return FromOpaque(rsa)->iqmp.get(); +} void RSA_get0_key(const RSA *rsa, const BIGNUM **out_n, const BIGNUM **out_e, const BIGNUM **out_d) { - if (out_n != NULL) { - *out_n = rsa->n; + auto *impl = FromOpaque(rsa); + if (out_n != nullptr) { + *out_n = impl->n.get(); } - if (out_e != NULL) { - *out_e = rsa->e; + if (out_e != nullptr) { + *out_e = impl->e.get(); } - if (out_d != NULL) { - *out_d = rsa->d; + if (out_d != nullptr) { + *out_d = impl->d.get(); } } void RSA_get0_factors(const RSA *rsa, const BIGNUM **out_p, const BIGNUM **out_q) { - if (out_p != NULL) { - *out_p = rsa->p; + auto *impl = FromOpaque(rsa); + if (out_p != nullptr) { + *out_p = impl->p.get(); } - if (out_q != NULL) { - *out_q = rsa->q; + if (out_q != nullptr) { + *out_q = impl->q.get(); } } -const RSA_PSS_PARAMS *RSA_get0_pss_params(const RSA *rsa) { - // We do not support the id-RSASSA-PSS key encoding. If we add support later, - // the |maskHash| field should be filled in for OpenSSL compatibility. - return NULL; -} - void RSA_get0_crt_params(const RSA *rsa, const BIGNUM **out_dmp1, const BIGNUM **out_dmq1, const BIGNUM **out_iqmp) { - if (out_dmp1 != NULL) { - *out_dmp1 = rsa->dmp1; + auto *impl = FromOpaque(rsa); + if (out_dmp1 != nullptr) { + *out_dmp1 = impl->dmp1.get(); } - if (out_dmq1 != NULL) { - *out_dmq1 = rsa->dmq1; + if (out_dmq1 != nullptr) { + *out_dmq1 = impl->dmq1.get(); } - if (out_iqmp != NULL) { - *out_iqmp = rsa->iqmp; + if (out_iqmp != nullptr) { + *out_iqmp = impl->iqmp.get(); } } int RSA_set0_key(RSA *rsa, BIGNUM *n, BIGNUM *e, BIGNUM *d) { - if ((rsa->n == NULL && n == NULL) || (rsa->e == NULL && e == NULL)) { + auto *impl = FromOpaque(rsa); + + if ((impl->n == nullptr && n == nullptr) || + (impl->e == nullptr && e == nullptr)) { return 0; } - if (n != NULL) { - BN_free(rsa->n); - rsa->n = n; + if (n != nullptr) { + impl->n.reset(n); } - if (e != NULL) { - BN_free(rsa->e); - rsa->e = e; + if (e != nullptr) { + impl->e.reset(e); } - if (d != NULL) { - BN_free(rsa->d); - rsa->d = d; + if (d != nullptr) { + impl->d.reset(d); } rsa_invalidate_key(rsa); @@ -316,17 +310,18 @@ int RSA_set0_key(RSA *rsa, BIGNUM *n, BIGNUM *e, BIGNUM *d) { } int RSA_set0_factors(RSA *rsa, BIGNUM *p, BIGNUM *q) { - if ((rsa->p == NULL && p == NULL) || (rsa->q == NULL && q == NULL)) { + auto *impl = FromOpaque(rsa); + + if ((impl->p == nullptr && p == nullptr) || + (impl->q == nullptr && q == nullptr)) { return 0; } - if (p != NULL) { - BN_free(rsa->p); - rsa->p = p; + if (p != nullptr) { + impl->p.reset(p); } - if (q != NULL) { - BN_free(rsa->q); - rsa->q = q; + if (q != nullptr) { + impl->q.reset(q); } rsa_invalidate_key(rsa); @@ -334,23 +329,22 @@ int RSA_set0_factors(RSA *rsa, BIGNUM *p, BIGNUM *q) { } int RSA_set0_crt_params(RSA *rsa, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp) { - if ((rsa->dmp1 == NULL && dmp1 == NULL) || - (rsa->dmq1 == NULL && dmq1 == NULL) || - (rsa->iqmp == NULL && iqmp == NULL)) { + auto *impl = FromOpaque(rsa); + + if ((impl->dmp1 == nullptr && dmp1 == nullptr) || + (impl->dmq1 == nullptr && dmq1 == nullptr) || + (impl->iqmp == nullptr && iqmp == nullptr)) { return 0; } - if (dmp1 != NULL) { - BN_free(rsa->dmp1); - rsa->dmp1 = dmp1; + if (dmp1 != nullptr) { + impl->dmp1.reset(dmp1); } - if (dmq1 != NULL) { - BN_free(rsa->dmq1); - rsa->dmq1 = dmq1; + if (dmq1 != nullptr) { + impl->dmq1.reset(dmq1); } - if (iqmp != NULL) { - BN_free(rsa->iqmp); - rsa->iqmp = iqmp; + if (iqmp != nullptr) { + impl->iqmp.reset(iqmp); } rsa_invalidate_key(rsa); @@ -360,8 +354,11 @@ int RSA_set0_crt_params(RSA *rsa, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp) { static int rsa_sign_raw_no_self_test(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, const uint8_t *in, size_t in_len, int padding) { - if (rsa->meth->sign_raw) { - return rsa->meth->sign_raw(rsa, out_len, out, max_out, in, in_len, padding); + auto *impl = FromOpaque(rsa); + + if (impl->meth->sign_raw) { + return impl->meth->sign_raw(rsa, out_len, out, max_out, in, in_len, + padding); } return rsa_default_sign_raw(rsa, out_len, out, max_out, in, in_len, padding); @@ -369,15 +366,18 @@ static int rsa_sign_raw_no_self_test(RSA *rsa, size_t *out_len, uint8_t *out, int RSA_sign_raw(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, const uint8_t *in, size_t in_len, int padding) { - boringssl_ensure_rsa_self_test(); + boringssl_ensure_rsa_sign_self_test(); return rsa_sign_raw_no_self_test(rsa, out_len, out, max_out, in, in_len, padding); } -unsigned RSA_size(const RSA *rsa) { return BN_num_bytes(rsa->n); } +unsigned RSA_size(const RSA *rsa) { + return BN_num_bytes(FromOpaque(rsa)->n.get()); +} int RSA_is_opaque(const RSA *rsa) { - return rsa->meth && (rsa->meth->flags & RSA_FLAG_OPAQUE); + auto *impl = FromOpaque(rsa); + return impl->meth && (impl->meth->flags & RSA_FLAG_OPAQUE); } int RSA_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused, @@ -387,11 +387,13 @@ int RSA_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused, } int RSA_set_ex_data(RSA *rsa, int idx, void *arg) { - return CRYPTO_set_ex_data(&rsa->ex_data, idx, arg); + auto *impl = FromOpaque(rsa); + return CRYPTO_set_ex_data(&impl->ex_data, idx, arg); } void *RSA_get_ex_data(const RSA *rsa, int idx) { - return CRYPTO_get_ex_data(&rsa->ex_data, idx); + auto *impl = FromOpaque(rsa); + return CRYPTO_get_ex_data(&impl->ex_data, idx); } // SSL_SIG_LENGTH is the size of an SSL/TLS (prior to TLS 1.2) signature: it's @@ -405,7 +407,7 @@ struct pkcs1_sig_prefix { int nid; // hash_len is the expected length of the hash function. uint8_t hash_len; - // len is the number of bytes of |bytes| which are valid. + // len is the number of bytes of `bytes` which are valid. uint8_t len; // bytes contains the DER bytes. uint8_t bytes[19]; @@ -423,35 +425,35 @@ static const struct pkcs1_sig_prefix kPKCS1SigPrefixes[] = { }, { NID_sha1, - BCM_SHA_DIGEST_LENGTH, + SHA_DIGEST_LENGTH, 15, {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14}, }, { NID_sha224, - BCM_SHA224_DIGEST_LENGTH, + SHA224_DIGEST_LENGTH, 19, {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c}, }, { NID_sha256, - BCM_SHA256_DIGEST_LENGTH, + SHA256_DIGEST_LENGTH, 19, {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20}, }, { NID_sha384, - BCM_SHA384_DIGEST_LENGTH, + SHA384_DIGEST_LENGTH, 19, {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30}, }, { NID_sha512, - BCM_SHA512_DIGEST_LENGTH, + SHA512_DIGEST_LENGTH, 19, {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40}, @@ -540,23 +542,25 @@ int RSA_add_pkcs1_prefix(uint8_t **out_msg, size_t *out_msg_len, return 0; } -int rsa_sign_no_self_test(int hash_nid, const uint8_t *digest, - size_t digest_len, uint8_t *out, unsigned *out_len, - RSA *rsa) { - if (rsa->meth->sign) { +int bssl::rsa_sign_no_self_test(int hash_nid, const uint8_t *digest, + size_t digest_len, uint8_t *out, + unsigned *out_len, RSA *rsa) { + auto *impl = FromOpaque(rsa); + + if (impl->meth->sign) { if (!rsa_check_digest_size(hash_nid, digest_len)) { return 0; } - // All supported digest lengths fit in |unsigned|. + // All supported digest lengths fit in `unsigned`. assert(digest_len <= EVP_MAX_MD_SIZE); static_assert(EVP_MAX_MD_SIZE <= UINT_MAX, "digest too long"); - return rsa->meth->sign(hash_nid, digest, (unsigned)digest_len, out, out_len, - rsa); + return impl->meth->sign(hash_nid, digest, (unsigned)digest_len, out, + out_len, rsa); } const unsigned rsa_size = RSA_size(rsa); int ret = 0; - uint8_t *signed_msg = NULL; + uint8_t *signed_msg = nullptr; size_t signed_msg_len = 0; int signed_msg_is_alloced = 0; size_t size_t_out_len; @@ -586,7 +590,7 @@ err: int RSA_sign(int hash_nid, const uint8_t *digest, size_t digest_len, uint8_t *out, unsigned *out_len, RSA *rsa) { - boringssl_ensure_rsa_self_test(); + boringssl_ensure_rsa_sign_self_test(); return rsa_sign_no_self_test(hash_nid, digest, digest_len, out, out_len, rsa); } @@ -601,7 +605,7 @@ int RSA_sign_pss_mgf1(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, size_t padded_len = RSA_size(rsa); uint8_t *padded = reinterpret_cast(OPENSSL_malloc(padded_len)); - if (padded == NULL) { + if (padded == nullptr) { return 0; } @@ -613,18 +617,19 @@ int RSA_sign_pss_mgf1(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, return ret; } -int rsa_verify_no_self_test(int hash_nid, const uint8_t *digest, - size_t digest_len, const uint8_t *sig, - size_t sig_len, RSA *rsa) { - if (rsa->n == NULL || rsa->e == NULL) { +int bssl::rsa_verify_no_self_test(int hash_nid, const uint8_t *digest, + size_t digest_len, const uint8_t *sig, + size_t sig_len, RSA *rsa) { + auto *impl = FromOpaque(rsa); + if (impl->n == nullptr || impl->e == nullptr) { OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING); return 0; } const size_t rsa_size = RSA_size(rsa); - uint8_t *buf = NULL; + uint8_t *buf = nullptr; int ret = 0; - uint8_t *signed_msg = NULL; + uint8_t *signed_msg = nullptr; size_t signed_msg_len = 0, len; int signed_msg_is_alloced = 0; @@ -646,8 +651,8 @@ int rsa_verify_no_self_test(int hash_nid, const uint8_t *digest, goto out; } - // Check that no other information follows the hash value (FIPS 186-4 Section - // 5.5) and it matches the expected hash. + // Check that no other information follows the hash value (FIPS 186-5 Section + // 5.4) and it matches the expected hash. if (len != signed_msg_len || OPENSSL_memcmp(buf, signed_msg, len) != 0) { OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_SIGNATURE); goto out; @@ -665,7 +670,7 @@ out: int RSA_verify(int hash_nid, const uint8_t *digest, size_t digest_len, const uint8_t *sig, size_t sig_len, RSA *rsa) { - boringssl_ensure_rsa_self_test(); + boringssl_ensure_rsa_verify_self_test(); return rsa_verify_no_self_test(hash_nid, digest, digest_len, sig, sig_len, rsa); } @@ -680,7 +685,7 @@ int RSA_verify_pss_mgf1(RSA *rsa, const uint8_t *digest, size_t digest_len, size_t em_len = RSA_size(rsa); uint8_t *em = reinterpret_cast(OPENSSL_malloc(em_len)); - if (em == NULL) { + if (em == nullptr) { return 0; } @@ -710,24 +715,24 @@ static int check_mod_inverse(int *out_ok, const BIGNUM *a, const BIGNUM *ainv, return 1; } - // Note |bn_mul_consttime| and |bn_div_consttime| do not scale linearly, but - // checking |ainv| is in range bounds the running time, assuming |m|'s bounds + // Note `bn_mul_consttime` and `bn_div_consttime` do not scale linearly, but + // checking `ainv` is in range bounds the running time, assuming `m`'s bounds // were checked by the caller. - BN_CTX_start(ctx); + BN_CTXScope scope(ctx); BIGNUM *tmp = BN_CTX_get(ctx); - int ret = tmp != NULL && bn_mul_consttime(tmp, a, ainv, ctx) && - bn_div_consttime(NULL, tmp, tmp, m, m_min_bits, ctx); - if (ret) { - *out_ok = constant_time_declassify_int(BN_is_one(tmp)); + if (tmp == nullptr || // + !bn_mul_consttime(tmp, a, ainv, ctx) || + !bn_div_consttime(nullptr, tmp, tmp, m, m_min_bits, ctx)) { + return 0; } - BN_CTX_end(ctx); - return ret; + *out_ok = constant_time_declassify_int(BN_is_one(tmp)); + return 1; } int RSA_check_key(const RSA *key) { // TODO(davidben): RSA key initialization is spread across - // |rsa_check_public_key|, |RSA_check_key|, |freeze_private_key|, and - // |BN_MONT_CTX_set_locked| as a result of API issues. See + // `rsa_check_public_key`, `RSA_check_key`, `freeze_private_key`, and + // `BN_MONT_CTX_set_locked` as a result of API issues. See // https://crbug.com/boringssl/316. As a result, we inconsistently check RSA // invariants. We should fix this and integrate that logic. @@ -735,32 +740,34 @@ int RSA_check_key(const RSA *key) { return 0; } - if ((key->p != NULL) != (key->q != NULL)) { + auto *impl = FromOpaque(key); + if ((impl->p != nullptr) != (impl->q != nullptr)) { OPENSSL_PUT_ERROR(RSA, RSA_R_ONLY_ONE_OF_P_Q_GIVEN); return 0; } - // |key->d| must be bounded by |key->n|. This ensures bounds on |RSA_bits| + // `impl->d` must be bounded by `impl->n`. This ensures bounds on `RSA_bits` // translate to bounds on the running time of private key operations. - if (key->d != NULL && - (BN_is_negative(key->d) || BN_cmp(key->d, key->n) >= 0)) { + if (impl->d != nullptr && (BN_is_negative(impl->d.get()) || + BN_cmp(impl->d.get(), impl->n.get()) >= 0)) { OPENSSL_PUT_ERROR(RSA, RSA_R_D_OUT_OF_RANGE); return 0; } - if (key->d == NULL || key->p == NULL) { + if (impl->d == nullptr || impl->p == nullptr) { // For a public key, or without p and q, there's nothing that can be // checked. return 1; } BN_CTX *ctx = BN_CTX_new(); - if (ctx == NULL) { + if (ctx == nullptr) { return 0; } BIGNUM tmp, de, pm1, qm1, dmp1, dmq1; - int ok = 0, has_crt_values; + int ok = 0; + bool has_crt_values; unsigned pm1_bits, qm1_bits; BN_init(&tmp); BN_init(&de); @@ -770,21 +777,21 @@ int RSA_check_key(const RSA *key) { BN_init(&dmq1); // Check that p * q == n. Before we multiply, we check that p and q are in - // bounds, to avoid a DoS vector in |bn_mul_consttime| below. Note that - // n was bound by |rsa_check_public_key|. This also implicitly checks p and q + // bounds, to avoid a DoS vector in `bn_mul_consttime` below. Note that + // n was bound by `rsa_check_public_key`. This also implicitly checks p and q // are odd, which is a necessary condition for Montgomery reduction. - if (BN_is_negative(key->p) || - constant_time_declassify_int(BN_cmp(key->p, key->n) >= 0) || - BN_is_negative(key->q) || - constant_time_declassify_int(BN_cmp(key->q, key->n) >= 0)) { + if (BN_is_negative(impl->p.get()) || + constant_time_declassify_int(BN_cmp(impl->p.get(), impl->n.get()) >= 0) || + BN_is_negative(impl->q.get()) || + constant_time_declassify_int(BN_cmp(impl->q.get(), impl->n.get()) >= 0)) { OPENSSL_PUT_ERROR(RSA, RSA_R_N_NOT_EQUAL_P_Q); goto out; } - if (!bn_mul_consttime(&tmp, key->p, key->q, ctx)) { + if (!bn_mul_consttime(&tmp, impl->p.get(), impl->q.get(), ctx)) { OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); goto out; } - if (BN_cmp(&tmp, key->n) != 0) { + if (BN_cmp(&tmp, impl->n.get()) != 0) { OPENSSL_PUT_ERROR(RSA, RSA_R_N_NOT_EQUAL_P_Q); goto out; } @@ -793,16 +800,16 @@ int RSA_check_key(const RSA *key) { // may be unreduced because other implementations use the Euler totient. We // simply check that d * e is one mod p-1 and mod q-1. Note d and e were bound // by earlier checks in this function. - if (!bn_usub_consttime(&pm1, key->p, BN_value_one()) || - !bn_usub_consttime(&qm1, key->q, BN_value_one())) { + if (!bn_usub_consttime(&pm1, impl->p.get(), BN_value_one()) || + !bn_usub_consttime(&qm1, impl->q.get(), BN_value_one())) { OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); goto out; } pm1_bits = BN_num_bits(&pm1); qm1_bits = BN_num_bits(&qm1); - if (!bn_mul_consttime(&de, key->d, key->e, ctx) || - !bn_div_consttime(NULL, &tmp, &de, &pm1, pm1_bits, ctx) || - !bn_div_consttime(NULL, &de, &de, &qm1, qm1_bits, ctx)) { + if (!bn_mul_consttime(&de, impl->d.get(), impl->e.get(), ctx) || + !bn_div_consttime(nullptr, &tmp, &de, &pm1, pm1_bits, ctx) || + !bn_div_consttime(nullptr, &de, &de, &qm1, qm1_bits, ctx)) { OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); goto out; } @@ -813,21 +820,23 @@ int RSA_check_key(const RSA *key) { goto out; } - has_crt_values = key->dmp1 != NULL; - if (has_crt_values != (key->dmq1 != NULL) || - has_crt_values != (key->iqmp != NULL)) { + has_crt_values = impl->dmp1 != nullptr; + if (has_crt_values != (impl->dmq1 != nullptr) || + has_crt_values != (impl->iqmp != nullptr)) { OPENSSL_PUT_ERROR(RSA, RSA_R_INCONSISTENT_SET_OF_CRT_VALUES); goto out; } if (has_crt_values) { int dmp1_ok, dmq1_ok, iqmp_ok; - if (!check_mod_inverse(&dmp1_ok, key->e, key->dmp1, &pm1, pm1_bits, ctx) || - !check_mod_inverse(&dmq1_ok, key->e, key->dmq1, &qm1, qm1_bits, ctx) || - // |p| is odd, so |pm1| and |p| have the same bit width. If they didn't, + if (!check_mod_inverse(&dmp1_ok, impl->e.get(), impl->dmp1.get(), &pm1, + pm1_bits, ctx) || + !check_mod_inverse(&dmq1_ok, impl->e.get(), impl->dmq1.get(), &qm1, + qm1_bits, ctx) || + // `p` is odd, so `pm1` and `p` have the same bit width. If they didn't, // we only need a lower bound anyway. - !check_mod_inverse(&iqmp_ok, key->q, key->iqmp, key->p, pm1_bits, - ctx)) { + !check_mod_inverse(&iqmp_ok, impl->q.get(), impl->iqmp.get(), + impl->p.get(), pm1_bits, ctx)) { OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); goto out; } @@ -873,8 +882,8 @@ static const BN_ULONG kSmallFactorsLimbs[] = {TOBN(0xc4309333, 0x3ef4e3e1), 0x000017b1}; DEFINE_LOCAL_DATA(BIGNUM, g_small_factors) { - out->d = (BN_ULONG *)kSmallFactorsLimbs; - out->width = OPENSSL_ARRAY_SIZE(kSmallFactorsLimbs); + out->d = const_cast(kSmallFactorsLimbs); + out->width = std::size(kSmallFactorsLimbs); out->dmax = out->width; out->neg = 0; out->flags = BN_FLG_STATIC_DATA; @@ -886,7 +895,7 @@ int RSA_check_fips(RSA *key) { } BN_CTX *ctx = BN_CTX_new(); - if (ctx == NULL) { + if (ctx == nullptr) { return 0; } @@ -897,23 +906,24 @@ int RSA_check_fips(RSA *key) { // Perform partial public key validation of RSA keys (SP 800-89 5.3.3). // Although this is not for primality testing, SP 800-89 cites an RSA - // primality testing algorithm, so we use |BN_prime_checks_for_generation| to + // primality testing algorithm, so we use `BN_prime_checks_for_generation` to // match. This is only a plausibility test and we expect the value to be // composite, so too few iterations will cause us to reject the key, not use // an implausible one. // - // |key->e| may be nullptr if created with |RSA_new_private_key_no_e|. + // `key->e` may be nullptr if created with `RSA_new_private_key_no_e`. enum bn_primality_result_t primality_result; - if (key->e == nullptr || // - BN_num_bits(key->e) <= 16 || // - BN_num_bits(key->e) > 256 || // - !BN_is_odd(key->n) || // - !BN_is_odd(key->e) || - !BN_gcd(&small_gcd, key->n, g_small_factors(), ctx) || + auto *impl = FromOpaque(key); + if (impl->e.get() == nullptr || // + BN_num_bits(impl->e.get()) <= 16 || // + BN_num_bits(impl->e.get()) > 256 || // + !BN_is_odd(impl->n.get()) || // + !BN_is_odd(impl->e.get()) || + !BN_gcd(&small_gcd, impl->n.get(), g_small_factors(), ctx) || !BN_is_one(&small_gcd) || - !BN_enhanced_miller_rabin_primality_test(&primality_result, key->n, + !BN_enhanced_miller_rabin_primality_test(&primality_result, impl->n.get(), BN_prime_checks_for_generation, - ctx, NULL) || + ctx, nullptr) || primality_result != bn_non_prime_power_composite) { OPENSSL_PUT_ERROR(RSA, RSA_R_PUBLIC_KEY_VALIDATION_FAILED); ret = 0; @@ -922,20 +932,20 @@ int RSA_check_fips(RSA *key) { BN_free(&small_gcd); BN_CTX_free(ctx); - if (!ret || key->d == NULL || key->p == NULL) { + if (!ret || impl->d == nullptr || impl->p == nullptr) { // On a failure or on only a public key, there's nothing else can be // checked. return ret; } // FIPS pairwise consistency test (FIPS 140-2 4.9.2). Per FIPS 140-2 IG, - // section 9.9, it is not known whether |rsa| will be used for signing or + // section 9.9, it is not known whether `rsa` will be used for signing or // encryption, so either pair-wise consistency self-test is acceptable. We // perform a signing test. uint8_t data[32] = {0}; unsigned sig_len = RSA_size(key); uint8_t *sig = reinterpret_cast(OPENSSL_malloc(sig_len)); - if (sig == NULL) { + if (sig == nullptr) { return 0; } @@ -958,21 +968,29 @@ cleanup: return ret; } -int rsa_private_transform_no_self_test(RSA *rsa, uint8_t *out, - const uint8_t *in, size_t len) { - if (rsa->meth->private_transform) { - return rsa->meth->private_transform(rsa, out, in, len); +int bssl::rsa_private_transform_no_self_test(RSA *rsa, uint8_t *out, + const uint8_t *in, size_t len) { + auto *impl = FromOpaque(rsa); + + if (impl->meth->private_transform) { + return impl->meth->private_transform(rsa, out, in, len); } return rsa_default_private_transform(rsa, out, in, len); } -int rsa_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in, - size_t len) { - boringssl_ensure_rsa_self_test(); +int bssl::rsa_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in, + size_t len) { + boringssl_ensure_rsa_sign_self_test(); return rsa_private_transform_no_self_test(rsa, out, in, len); } -int RSA_flags(const RSA *rsa) { return rsa->flags; } +int RSA_flags(const RSA *rsa) { + auto *impl = FromOpaque(rsa); + return impl->flags; +} -int RSA_test_flags(const RSA *rsa, int flags) { return rsa->flags & flags; } +int RSA_test_flags(const RSA *rsa, int flags) { + auto *impl = FromOpaque(rsa); + return impl->flags & flags; +} diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/rsa_impl.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/rsa_impl.cc.inc index bb78677b..9d4ede97 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/rsa_impl.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/rsa/rsa_impl.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -13,58 +18,67 @@ #include #include +#include + #include #include #include -#include #include "../../bcm_support.h" #include "../../internal.h" +#include "../../mem_internal.h" #include "../bn/internal.h" #include "../delocate.h" #include "../service_indicator/internal.h" #include "internal.h" -int rsa_check_public_key(const RSA *rsa) { - if (rsa->n == NULL) { +using namespace bssl; + +static_assert(OPENSSL_RSA_MAX_MODULUS_BITS <= + BN_MONTGOMERY_MAX_WORDS * BN_BITS2, + "Max RSA size too big for Montgomery arithmetic"); + +int bssl::rsa_check_public_key(const RSA *rsa) { + auto *impl = FromOpaque(rsa); + + if (impl->n == nullptr) { OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING); return 0; } - unsigned n_bits = BN_num_bits(rsa->n); + unsigned n_bits = BN_num_bits(impl->n.get()); if (n_bits > OPENSSL_RSA_MAX_MODULUS_BITS) { OPENSSL_PUT_ERROR(RSA, RSA_R_MODULUS_TOO_LARGE); return 0; } - // TODO(crbug.com/boringssl/607): Raise this limit. 512-bit RSA was factored - // in 1999. - if (n_bits < 512) { + if (n_bits < OPENSSL_RSA_MIN_MODULUS_BITS) { OPENSSL_PUT_ERROR(RSA, RSA_R_KEY_SIZE_TOO_SMALL); return 0; } // RSA moduli must be positive and odd. In addition to being necessary for RSA // in general, we cannot setup Montgomery reduction with even moduli. - if (!BN_is_odd(rsa->n) || BN_is_negative(rsa->n)) { + if (!BN_is_odd(impl->n.get()) || BN_is_negative(impl->n.get())) { OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_RSA_PARAMETERS); return 0; } static const unsigned kMaxExponentBits = 33; - if (rsa->e != NULL) { + if (impl->e != nullptr) { // Reject e = 1, negative e, and even e. e must be odd to be relatively // prime with phi(n). - unsigned e_bits = BN_num_bits(rsa->e); - if (e_bits < 2 || BN_is_negative(rsa->e) || !BN_is_odd(rsa->e)) { + unsigned e_bits = BN_num_bits(impl->e.get()); + if (e_bits < 2 || BN_is_negative(impl->e.get()) || + !BN_is_odd(impl->e.get())) { OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_E_VALUE); return 0; } - if (rsa->flags & RSA_FLAG_LARGE_PUBLIC_EXPONENT) { + if (impl->flags & RSA_FLAG_LARGE_PUBLIC_EXPONENT) { // The caller has requested disabling DoS protections. Still, e must be // less than n. - if (BN_ucmp(rsa->n, rsa->e) <= 0) { + if (BN_ucmp(impl->n.get(), impl->e.get()) <= 0) { OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_E_VALUE); return 0; } @@ -83,11 +97,11 @@ int rsa_check_public_key(const RSA *rsa) { return 0; } - // The upper bound on |e_bits| and lower bound on |n_bits| imply e is + // The upper bound on `e_bits` and lower bound on `n_bits` imply e is // bounded by n. - assert(BN_ucmp(rsa->n, rsa->e) > 0); + assert(BN_ucmp(impl->n.get(), impl->e.get()) > 0); } - } else if (!(rsa->flags & RSA_FLAG_NO_PUBLIC_EXPONENT)) { + } else if (!(impl->flags & RSA_FLAG_NO_PUBLIC_EXPONENT)) { OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING); return 0; } @@ -95,290 +109,134 @@ int rsa_check_public_key(const RSA *rsa) { return 1; } -static int ensure_fixed_copy(BIGNUM **out, const BIGNUM *in, int width) { - if (*out != NULL) { +static int ensure_fixed_copy(UniquePtr *out, const BIGNUM *in, + int width) { + if (*out != nullptr) { return 1; } - BIGNUM *copy = BN_dup(in); - if (copy == NULL || !bn_resize_words(copy, width)) { - BN_free(copy); + UniquePtr copy(BN_dup(in)); + if (copy == nullptr || !bn_resize_words(copy.get(), width)) { return 0; } - *out = copy; - bn_secret(copy); - + bn_secret(copy.get()); + *out = std::move(copy); return 1; } -// freeze_private_key finishes initializing |rsa|'s private key components. -// After this function has returned, |rsa| may not be changed. This is needed -// because |RSA| is a public struct and, additionally, OpenSSL 1.1.0 opaquified +// freeze_private_key finishes initializing `rsa`'s private key components. +// After this function has returned, `rsa` may not be changed. This is needed +// because `RSA` is a public struct and, additionally, OpenSSL 1.1.0 opaquified // it wrong (see https://github.com/openssl/openssl/issues/5158). -static int freeze_private_key(RSA *rsa, BN_CTX *ctx) { - CRYPTO_MUTEX_lock_read(&rsa->lock); +static int freeze_private_key(RSAImpl *rsa, BN_CTX *ctx) { + rsa->lock.LockRead(); int frozen = rsa->private_key_frozen; - CRYPTO_MUTEX_unlock_read(&rsa->lock); + rsa->lock.UnlockRead(); if (frozen) { return 1; } - int ret = 0; const BIGNUM *n_fixed; - CRYPTO_MUTEX_lock_write(&rsa->lock); + MutexWriteLock lock(&rsa->lock); if (rsa->private_key_frozen) { - ret = 1; - goto err; + return 1; } // Check the public components are within DoS bounds. if (!rsa_check_public_key(rsa)) { - goto err; + return 0; } // Pre-compute various intermediate values, as well as copies of private // exponents with correct widths. Note that other threads may concurrently - // read from |rsa->n|, |rsa->e|, etc., so any fixes must be in separate - // copies. We use |mont_n->N|, |mont_p->N|, and |mont_q->N| as copies of |n|, - // |p|, and |q| with the correct minimal widths. + // read from `rsa->n`, `rsa->e`, etc., so any fixes must be in separate + // copies. We use `mont_n->N`, `mont_p->N`, and `mont_q->N` as copies of `n`, + // `p`, and `q` with the correct minimal widths. - if (rsa->mont_n == NULL) { - rsa->mont_n = BN_MONT_CTX_new_for_modulus(rsa->n, ctx); - if (rsa->mont_n == NULL) { - goto err; + if (rsa->mont_n == nullptr) { + rsa->mont_n.reset(BN_MONT_CTX_new_for_modulus(rsa->n.get(), ctx)); + if (rsa->mont_n == nullptr) { + return 0; } } n_fixed = &rsa->mont_n->N; - // The only public upper-bound of |rsa->d| is the bit length of |rsa->n|. The + // The only public upper-bound of `rsa->d` is the bit length of `rsa->n`. The // ASN.1 serialization of RSA private keys unfortunately leaks the byte length - // of |rsa->d|, but normalize it so we only leak it once, rather than per + // of `rsa->d`, but normalize it so we only leak it once, rather than per // operation. - if (rsa->d != NULL && - !ensure_fixed_copy(&rsa->d_fixed, rsa->d, n_fixed->width)) { - goto err; + if (rsa->d != nullptr && + !ensure_fixed_copy(&rsa->d_fixed, rsa->d.get(), n_fixed->width)) { + return 0; } - if (rsa->e != NULL && rsa->p != NULL && rsa->q != NULL) { + if (rsa->e != nullptr && rsa->p != nullptr && rsa->q != nullptr) { // TODO: p and q are also CONSTTIME_SECRET but not yet marked as such // because the Montgomery code does things like test whether or not values // are zero. So the secret marking probably needs to happen inside that // code. - if (rsa->mont_p == NULL) { - rsa->mont_p = BN_MONT_CTX_new_consttime(rsa->p, ctx); - if (rsa->mont_p == NULL) { - goto err; + if (rsa->mont_p == nullptr) { + rsa->mont_p.reset(BN_MONT_CTX_new_consttime(rsa->p.get(), ctx)); + if (rsa->mont_p == nullptr) { + return 0; } } - if (rsa->mont_q == NULL) { - rsa->mont_q = BN_MONT_CTX_new_consttime(rsa->q, ctx); - if (rsa->mont_q == NULL) { - goto err; + if (rsa->mont_q == nullptr) { + rsa->mont_q.reset(BN_MONT_CTX_new_consttime(rsa->q.get(), ctx)); + if (rsa->mont_q == nullptr) { + return 0; } } - if (rsa->dmp1 != NULL && rsa->dmq1 != NULL && rsa->iqmp != NULL) { + if (rsa->dmp1 != nullptr && rsa->dmq1 != nullptr && rsa->iqmp != nullptr) { // CRT components are only publicly bounded by their corresponding // moduli's bit lengths. const BIGNUM *p_fixed = &rsa->mont_p->N; const BIGNUM *q_fixed = &rsa->mont_q->N; - if (!ensure_fixed_copy(&rsa->dmp1_fixed, rsa->dmp1, p_fixed->width) || - !ensure_fixed_copy(&rsa->dmq1_fixed, rsa->dmq1, q_fixed->width)) { - goto err; + if (!ensure_fixed_copy(&rsa->dmp1_fixed, rsa->dmp1.get(), + p_fixed->width) || + !ensure_fixed_copy(&rsa->dmq1_fixed, rsa->dmq1.get(), + q_fixed->width)) { + return 0; } - // Compute |iqmp_mont|, which is |iqmp| in Montgomery form and with the + // Compute `iqmp_mont`, which is `iqmp` in Montgomery form and with the // correct bit width. - if (rsa->iqmp_mont == NULL) { - BIGNUM *iqmp_mont = BN_new(); - if (iqmp_mont == NULL || - !BN_to_montgomery(iqmp_mont, rsa->iqmp, rsa->mont_p, ctx)) { - BN_free(iqmp_mont); - goto err; + if (rsa->iqmp_mont == nullptr) { + UniquePtr iqmp_mont(BN_new()); + if (iqmp_mont == nullptr || + !BN_to_montgomery(iqmp_mont.get(), rsa->iqmp.get(), + rsa->mont_p.get(), ctx)) { + return 0; } - rsa->iqmp_mont = iqmp_mont; - bn_secret(rsa->iqmp_mont); + rsa->iqmp_mont = std::move(iqmp_mont); + bn_secret(rsa->iqmp_mont.get()); } } } rsa->private_key_frozen = 1; - ret = 1; - -err: - CRYPTO_MUTEX_unlock_write(&rsa->lock); - return ret; + return 1; } -void rsa_invalidate_key(RSA *rsa) { - rsa->private_key_frozen = 0; - - BN_MONT_CTX_free(rsa->mont_n); - rsa->mont_n = NULL; - BN_MONT_CTX_free(rsa->mont_p); - rsa->mont_p = NULL; - BN_MONT_CTX_free(rsa->mont_q); - rsa->mont_q = NULL; - - BN_free(rsa->d_fixed); - rsa->d_fixed = NULL; - BN_free(rsa->dmp1_fixed); - rsa->dmp1_fixed = NULL; - BN_free(rsa->dmq1_fixed); - rsa->dmq1_fixed = NULL; - BN_free(rsa->iqmp_mont); - rsa->iqmp_mont = NULL; - - for (size_t i = 0; i < rsa->num_blindings; i++) { - BN_BLINDING_free(rsa->blindings[i]); - } - OPENSSL_free(rsa->blindings); - rsa->blindings = NULL; - rsa->num_blindings = 0; - OPENSSL_free(rsa->blindings_inuse); - rsa->blindings_inuse = NULL; - rsa->blinding_fork_generation = 0; +void bssl::rsa_invalidate_key(RSA *rsa) { + auto *impl = FromOpaque(rsa); + impl->private_key_frozen = 0; + impl->mont_n = nullptr; + impl->mont_p = nullptr; + impl->mont_q = nullptr; + impl->d_fixed = nullptr; + impl->dmp1_fixed = nullptr; + impl->dmq1_fixed = nullptr; + impl->iqmp_mont = nullptr; } -// MAX_BLINDINGS_PER_RSA defines the maximum number of cached BN_BLINDINGs per -// RSA*. Then this limit is exceeded, BN_BLINDING objects will be created and -// destroyed as needed. -#if defined(OPENSSL_TSAN) -// Smaller under TSAN so that the edge case can be hit with fewer threads. -#define MAX_BLINDINGS_PER_RSA 2 -#else -#define MAX_BLINDINGS_PER_RSA 1024 -#endif - -// rsa_blinding_get returns a BN_BLINDING to use with |rsa|. It does this by -// allocating one of the cached BN_BLINDING objects in |rsa->blindings|. If -// none are free, the cache will be extended by a extra element and the new -// BN_BLINDING is returned. -// -// On success, the index of the assigned BN_BLINDING is written to -// |*index_used| and must be passed to |rsa_blinding_release| when finished. -static BN_BLINDING *rsa_blinding_get(RSA *rsa, size_t *index_used, - BN_CTX *ctx) { - assert(ctx != NULL); - assert(rsa->mont_n != NULL); - - BN_BLINDING *ret = NULL; - const uint64_t fork_generation = CRYPTO_get_fork_generation(); - CRYPTO_MUTEX_lock_write(&rsa->lock); - - // Wipe the blinding cache on |fork|. - if (rsa->blinding_fork_generation != fork_generation) { - for (size_t i = 0; i < rsa->num_blindings; i++) { - // The inuse flag must be zero unless we were forked from a - // multi-threaded process, in which case calling back into BoringSSL is - // forbidden. - assert(rsa->blindings_inuse[i] == 0); - BN_BLINDING_invalidate(rsa->blindings[i]); - } - rsa->blinding_fork_generation = fork_generation; - } - - uint8_t *const free_inuse_flag = reinterpret_cast( - OPENSSL_memchr(rsa->blindings_inuse, 0, rsa->num_blindings)); - size_t new_num_blindings; - BN_BLINDING **new_blindings; - uint8_t *new_blindings_inuse; - if (free_inuse_flag != NULL) { - *free_inuse_flag = 1; - *index_used = free_inuse_flag - rsa->blindings_inuse; - ret = rsa->blindings[*index_used]; - goto out; - } - - if (rsa->num_blindings >= MAX_BLINDINGS_PER_RSA) { - // No |BN_BLINDING| is free and nor can the cache be extended. This index - // value is magic and indicates to |rsa_blinding_release| that a - // |BN_BLINDING| was not inserted into the array. - *index_used = MAX_BLINDINGS_PER_RSA; - ret = BN_BLINDING_new(); - goto out; - } - - // Double the length of the cache. - static_assert(MAX_BLINDINGS_PER_RSA < UINT_MAX / 2, - "MAX_BLINDINGS_PER_RSA too large"); - new_num_blindings = rsa->num_blindings * 2; - if (new_num_blindings == 0) { - new_num_blindings = 1; - } - if (new_num_blindings > MAX_BLINDINGS_PER_RSA) { - new_num_blindings = MAX_BLINDINGS_PER_RSA; - } - assert(new_num_blindings > rsa->num_blindings); - - new_blindings = reinterpret_cast( - OPENSSL_calloc(new_num_blindings, sizeof(BN_BLINDING *))); - new_blindings_inuse = - reinterpret_cast(OPENSSL_malloc(new_num_blindings)); - if (new_blindings == NULL || new_blindings_inuse == NULL) { - goto err; - } - - OPENSSL_memcpy(new_blindings, rsa->blindings, - sizeof(BN_BLINDING *) * rsa->num_blindings); - OPENSSL_memcpy(new_blindings_inuse, rsa->blindings_inuse, rsa->num_blindings); - - for (size_t i = rsa->num_blindings; i < new_num_blindings; i++) { - new_blindings[i] = BN_BLINDING_new(); - if (new_blindings[i] == NULL) { - for (size_t j = rsa->num_blindings; j < i; j++) { - BN_BLINDING_free(new_blindings[j]); - } - goto err; - } - } - memset(&new_blindings_inuse[rsa->num_blindings], 0, - new_num_blindings - rsa->num_blindings); - - new_blindings_inuse[rsa->num_blindings] = 1; - *index_used = rsa->num_blindings; - assert(*index_used != MAX_BLINDINGS_PER_RSA); - ret = new_blindings[rsa->num_blindings]; - - OPENSSL_free(rsa->blindings); - rsa->blindings = new_blindings; - OPENSSL_free(rsa->blindings_inuse); - rsa->blindings_inuse = new_blindings_inuse; - rsa->num_blindings = new_num_blindings; - - goto out; - -err: - OPENSSL_free(new_blindings_inuse); - OPENSSL_free(new_blindings); - -out: - CRYPTO_MUTEX_unlock_write(&rsa->lock); - return ret; -} - -// rsa_blinding_release marks the cached BN_BLINDING at the given index as free -// for other threads to use. -static void rsa_blinding_release(RSA *rsa, BN_BLINDING *blinding, - size_t blinding_index) { - if (blinding_index == MAX_BLINDINGS_PER_RSA) { - // This blinding wasn't cached. - BN_BLINDING_free(blinding); - return; - } - - CRYPTO_MUTEX_lock_write(&rsa->lock); - rsa->blindings_inuse[blinding_index] = 0; - CRYPTO_MUTEX_unlock_write(&rsa->lock); -} - -// signing -int rsa_default_sign_raw(RSA *rsa, size_t *out_len, uint8_t *out, - size_t max_out, const uint8_t *in, size_t in_len, - int padding) { +int bssl::rsa_default_sign_raw(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 = NULL; + uint8_t *buf = nullptr; int i, ret = 0; if (max_out < rsa_size) { @@ -387,7 +245,7 @@ int rsa_default_sign_raw(RSA *rsa, size_t *out_len, uint8_t *out, } buf = reinterpret_cast(OPENSSL_malloc(rsa_size)); - if (buf == NULL) { + if (buf == nullptr) { goto err; } @@ -422,12 +280,15 @@ err: } -static int rsa_mod_exp_crt(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx); +static int rsa_mod_exp_crt(BIGNUM *r0, const BIGNUM *I, RSAImpl *rsa, + BN_CTX *ctx); -int rsa_verify_raw_no_self_test(RSA *rsa, size_t *out_len, uint8_t *out, - size_t max_out, const uint8_t *in, - size_t in_len, int padding) { - if (rsa->n == NULL || rsa->e == NULL) { +int bssl::rsa_verify_raw_no_self_test(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); + + if (impl->n == nullptr || impl->e == nullptr) { OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING); return 0; } @@ -437,8 +298,6 @@ int rsa_verify_raw_no_self_test(RSA *rsa, size_t *out_len, uint8_t *out, } const unsigned rsa_size = RSA_size(rsa); - BIGNUM *f, *result; - if (max_out < rsa_size) { OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL); return 0; @@ -449,18 +308,17 @@ int rsa_verify_raw_no_self_test(RSA *rsa, size_t *out_len, uint8_t *out, return 0; } - BN_CTX *ctx = BN_CTX_new(); - if (ctx == NULL) { + UniquePtr ctx(BN_CTX_new()); + if (ctx == nullptr) { return 0; } int ret = 0; - uint8_t *buf = NULL; - - BN_CTX_start(ctx); - f = BN_CTX_get(ctx); - result = BN_CTX_get(ctx); - if (f == NULL || result == NULL) { + uint8_t *buf = nullptr; + BN_CTXScope scope(ctx.get()); + BIGNUM *f = BN_CTX_get(ctx.get()); + BIGNUM *result = BN_CTX_get(ctx.get()); + if (f == nullptr || result == nullptr) { goto err; } @@ -469,22 +327,24 @@ int rsa_verify_raw_no_self_test(RSA *rsa, size_t *out_len, uint8_t *out, } else { // Allocate a temporary buffer to hold the padded plaintext. buf = reinterpret_cast(OPENSSL_malloc(rsa_size)); - if (buf == NULL) { + if (buf == nullptr) { goto err; } } - if (BN_bin2bn(in, in_len, f) == NULL) { + if (BN_bin2bn(in, in_len, f) == nullptr) { goto err; } - if (BN_ucmp(f, rsa->n) >= 0) { + if (BN_ucmp(f, impl->n.get()) >= 0) { OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE_FOR_MODULUS); goto err; } - if (!BN_MONT_CTX_set_locked(&rsa->mont_n, &rsa->lock, rsa->n, ctx) || - !BN_mod_exp_mont(result, f, rsa->e, &rsa->mont_n->N, ctx, rsa->mont_n)) { + if (!BN_MONT_CTX_set_locked(&impl->mont_n, &impl->lock, impl->n.get(), + ctx.get()) || + !BN_mod_exp_mont(result, f, impl->e.get(), &impl->mont_n->N, ctx.get(), + impl->mont_n.get())) { goto err; } @@ -513,8 +373,6 @@ int rsa_verify_raw_no_self_test(RSA *rsa, size_t *out_len, uint8_t *out, } err: - BN_CTX_end(ctx); - BN_CTX_free(ctx); if (buf != out) { OPENSSL_free(buf); } @@ -523,96 +381,74 @@ err: int RSA_verify_raw(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, const uint8_t *in, size_t in_len, int padding) { - boringssl_ensure_rsa_self_test(); + boringssl_ensure_rsa_verify_self_test(); return rsa_verify_raw_no_self_test(rsa, out_len, out, max_out, in, in_len, padding); } -int rsa_default_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in, - size_t len) { - if (rsa->n == NULL || rsa->d == NULL) { +int bssl::rsa_default_private_transform(RSA *rsa, uint8_t *out, + const uint8_t *in, size_t len) { + auto *impl = FromOpaque(rsa); + + if (impl->n == nullptr || impl->d == nullptr) { OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING); return 0; } - BIGNUM *f, *result; - BN_CTX *ctx = NULL; - size_t blinding_index = 0; - BN_BLINDING *blinding = NULL; - int ret = 0, do_blinding; - - ctx = BN_CTX_new(); - if (ctx == NULL) { - goto err; + UniquePtr ctx(BN_CTX_new()); + if (ctx == nullptr) { + return 0; } - BN_CTX_start(ctx); - f = BN_CTX_get(ctx); - result = BN_CTX_get(ctx); - - if (f == NULL || result == NULL) { - goto err; + BN_CTXScope scope(ctx.get()); + BIGNUM *f = BN_CTX_get(ctx.get()); + BIGNUM *result = BN_CTX_get(ctx.get()); + if (f == nullptr || result == nullptr) { + return 0; } // The caller should have ensured this. - assert(len == BN_num_bytes(rsa->n)); - if (BN_bin2bn(in, len, f) == NULL) { - goto err; + assert(len == BN_num_bytes(impl->n.get())); + if (BN_bin2bn(in, len, f) == nullptr) { + return 0; } // The input to the RSA private transform may be secret, but padding is // expected to construct a value within range, so we can leak this comparison. - if (constant_time_declassify_int(BN_ucmp(f, rsa->n) >= 0)) { + if (constant_time_declassify_int(BN_ucmp(f, impl->n.get()) >= 0)) { // Usually the padding functions would catch this. OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE_FOR_MODULUS); - goto err; + return 0; } - if (!freeze_private_key(rsa, ctx)) { + if (!freeze_private_key(impl, ctx.get())) { OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); - goto err; + return 0; } - do_blinding = - (rsa->flags & (RSA_FLAG_NO_BLINDING | RSA_FLAG_NO_PUBLIC_EXPONENT)) == 0; - - if (rsa->e == NULL && do_blinding) { - // We cannot do blinding or verification without |e|, and continuing without - // those countermeasures is dangerous. However, the Java/Android RSA API - // requires support for keys where only |d| and |n| (and not |e|) are known. - // The callers that require that bad behavior must set - // |RSA_FLAG_NO_BLINDING| or use |RSA_new_private_key_no_e|. - // - // TODO(davidben): Update this comment when Conscrypt is updated to use - // |RSA_new_private_key_no_e|. + if (impl->e == nullptr && (impl->flags & RSA_FLAG_NO_PUBLIC_EXPONENT) == 0) { + // Unless the private key was specifically created with an API like + // `RSA_new_private_key_no_e`, don't allow RSA keys to be missing the public + // exponent, which disables some fault attack mitigations. (It should not be + // possible to construct such an `RSA` object in the public API.) OPENSSL_PUT_ERROR(RSA, RSA_R_NO_PUBLIC_EXPONENT); - goto err; + return 0; } - if (do_blinding) { - blinding = rsa_blinding_get(rsa, &blinding_index, ctx); - if (blinding == NULL) { - OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); - goto err; - } - if (!BN_BLINDING_convert(f, blinding, rsa->e, rsa->mont_n, ctx)) { - goto err; - } - } - - if (rsa->p != NULL && rsa->q != NULL && rsa->e != NULL && rsa->dmp1 != NULL && - rsa->dmq1 != NULL && rsa->iqmp != NULL && - // Require that we can reduce |f| by |rsa->p| and |rsa->q| in constant + if (impl->p != nullptr && impl->q != nullptr && impl->e != nullptr && + impl->dmp1 != nullptr && impl->dmq1 != nullptr && impl->iqmp != nullptr && + // Require that we can reduce `f` by `impl->p` and `impl->q` in constant // time, which requires primes be the same size, rounded to the Montgomery - // coefficient. (See |mod_montgomery|.) This is not required by RFC 8017, + // coefficient. (See `mod_montgomery`.) This is not required by RFC 8017, // but it is true for keys generated by us and all common implementations. - bn_less_than_montgomery_R(rsa->q, rsa->mont_p) && - bn_less_than_montgomery_R(rsa->p, rsa->mont_q)) { - if (!rsa_mod_exp_crt(result, f, rsa, ctx)) { - goto err; + bn_less_than_montgomery_R(impl->q.get(), impl->mont_p.get()) && + bn_less_than_montgomery_R(impl->p.get(), impl->mont_q.get())) { + if (!rsa_mod_exp_crt(result, f, impl, ctx.get())) { + return 0; } - } else if (!BN_mod_exp_mont_consttime(result, f, rsa->d_fixed, rsa->n, ctx, - rsa->mont_n)) { - goto err; + } else if (!BN_mod_exp_mont_consttime(result, f, impl->d_fixed.get(), + impl->n.get(), ctx.get(), + impl->mont_n.get())) { + return 0; } // Verify the result to protect against fault attacks as described in the @@ -623,50 +459,36 @@ int rsa_default_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in, // works when the CRT isn't used. That attack is much less likely to succeed // than the CRT attack, but there have likely been improvements since 1997. // - // This check is cheap assuming |e| is small, which we require in - // |rsa_check_public_key|. - if (rsa->e != NULL) { - BIGNUM *vrfy = BN_CTX_get(ctx); - if (vrfy == NULL || - !BN_mod_exp_mont(vrfy, result, rsa->e, rsa->n, ctx, rsa->mont_n) || + // This check is cheap assuming `e` is small, which we require in + // `rsa_check_public_key`. + if (impl->e != nullptr) { + BIGNUM *vrfy = BN_CTX_get(ctx.get()); + if (vrfy == nullptr || + !BN_mod_exp_mont(vrfy, result, impl->e.get(), impl->n.get(), ctx.get(), + impl->mont_n.get()) || !constant_time_declassify_int(BN_equal_consttime(vrfy, f))) { OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); - goto err; + return 0; } } - if (do_blinding && !BN_BLINDING_invert(result, blinding, rsa->mont_n, ctx)) { - goto err; - } - - // The computation should have left |result| as a maximally-wide number, so + // The computation should have left `result` as a maximally-wide number, so // that it and serializing does not leak information about the magnitude of // the result. // // See Falko Strenzke, "Manger's Attack revisited", ICICS 2010. - assert(result->width == rsa->mont_n->N.width); + assert(result->width == impl->mont_n->N.width); bn_assert_fits_in_bytes(result, len); if (!BN_bn2bin_padded(out, len, result)) { OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); - goto err; + return 0; } - ret = 1; - -err: - if (ctx != NULL) { - BN_CTX_end(ctx); - BN_CTX_free(ctx); - } - if (blinding != NULL) { - rsa_blinding_release(rsa, blinding, blinding_index); - } - - return ret; + return 1; } -// mod_montgomery sets |r| to |I| mod |p|. |I| must already be fully reduced -// modulo |p| times |q|. It returns one on success and zero on error. +// mod_montgomery sets `r` to `I` mod `p`. `I` must already be fully reduced +// modulo `p` times `q`. It returns one on success and zero on error. static int mod_montgomery(BIGNUM *r, const BIGNUM *I, const BIGNUM *p, const BN_MONT_CTX *mont_p, const BIGNUM *q, BN_CTX *ctx) { @@ -680,188 +502,112 @@ static int mod_montgomery(BIGNUM *r, const BIGNUM *I, const BIGNUM *p, if ( // Reduce mod p with Montgomery reduction. This computes I * R^-1 mod p. !BN_from_montgomery(r, I, mont_p, ctx) || - // Multiply by R^2 and do another Montgomery reduction to compute - // I * R^-1 * R^2 * R^-1 = I mod p. + // Multiply by R² and do another Montgomery reduction to compute + // I * R^-1 * R² * R^-1 = I mod p. !BN_to_montgomery(r, r, mont_p, ctx)) { return 0; } - // By precomputing R^3 mod p (normally |BN_MONT_CTX| only uses R^2 mod p) and - // adjusting the API for |BN_mod_exp_mont_consttime|, we could instead compute + // By precomputing R³ mod p (normally `BN_MONT_CTX` only uses R² mod p) and + // adjusting the API for `BN_mod_exp_mont_consttime`, we could instead compute // I * R mod p here and save a reduction per prime. But this would require // changing the RSAZ code and may not be worth it. Note that the RSAZ code // uses a different radix, so it uses R' = 2^1044. There we'd actually want - // R^2 * R', and would futher benefit from a precomputed R'^2. It currently - // converts |mont_p->RR| to R'^2. + // R² * R', and would further benefit from a precomputed R'². It currently + // converts `mont_p->RR` to R'². return 1; } -static int rsa_mod_exp_crt(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) { - assert(ctx != NULL); +static int rsa_mod_exp_crt(BIGNUM *r0, const BIGNUM *I, RSAImpl *rsa, + BN_CTX *ctx) { + assert(ctx != nullptr); - assert(rsa->n != NULL); - assert(rsa->e != NULL); - assert(rsa->d != NULL); - assert(rsa->p != NULL); - assert(rsa->q != NULL); - assert(rsa->dmp1 != NULL); - assert(rsa->dmq1 != NULL); - assert(rsa->iqmp != NULL); + assert(rsa->n != nullptr); + assert(rsa->e != nullptr); + assert(rsa->d != nullptr); + assert(rsa->p != nullptr); + assert(rsa->q != nullptr); + assert(rsa->dmp1 != nullptr); + assert(rsa->dmq1 != nullptr); + assert(rsa->iqmp != nullptr); - BIGNUM *r1, *m1; - int ret = 0; - - BN_CTX_start(ctx); - r1 = BN_CTX_get(ctx); - m1 = BN_CTX_get(ctx); - BIGNUM *n, *p, *q; - if (r1 == NULL || m1 == NULL) { - goto err; + BN_CTXScope scope(ctx); + BIGNUM *r1 = BN_CTX_get(ctx); + BIGNUM *m1 = BN_CTX_get(ctx); + if (r1 == nullptr || m1 == nullptr) { + return 0; } - // Use the minimal-width versions of |n|, |p|, and |q|. Either works, but if + // Use the minimal-width versions of `n`, `p`, and `q`. Either works, but if // someone gives us non-minimal values, these will be slightly more efficient // on the non-Montgomery operations. - n = &rsa->mont_n->N; - p = &rsa->mont_p->N; - q = &rsa->mont_q->N; + BIGNUM *n = &rsa->mont_n->N; + BIGNUM *p = &rsa->mont_p->N; + BIGNUM *q = &rsa->mont_q->N; - // This is a pre-condition for |mod_montgomery|. It was already checked by the + // This is a pre-condition for `mod_montgomery`. It was already checked by the // caller. declassify_assert(BN_ucmp(I, n) < 0); - if ( // |m1| is the result modulo |q|. - !mod_montgomery(r1, I, q, rsa->mont_q, p, ctx) || - !BN_mod_exp_mont_consttime(m1, r1, rsa->dmq1_fixed, q, ctx, - rsa->mont_q) || - // |r0| is the result modulo |p|. - !mod_montgomery(r1, I, p, rsa->mont_p, q, ctx) || - !BN_mod_exp_mont_consttime(r0, r1, rsa->dmp1_fixed, p, ctx, - rsa->mont_p) || - // Compute r0 = r0 - m1 mod p. |m1| is reduced mod |q|, not |p|, so we - // just run |mod_montgomery| again for simplicity. This could be more - // efficient with more cases: if |p > q|, |m1| is already reduced. If - // |p < q| but they have the same bit width, |bn_reduce_once| suffices. + if ( // `m1` is the result modulo `q`. + !mod_montgomery(r1, I, q, rsa->mont_q.get(), p, ctx) || + !BN_mod_exp_mont_consttime(m1, r1, rsa->dmq1_fixed.get(), q, ctx, + rsa->mont_q.get()) || + // `r0` is the result modulo `p`. + !mod_montgomery(r1, I, p, rsa->mont_p.get(), q, ctx) || + !BN_mod_exp_mont_consttime(r0, r1, rsa->dmp1_fixed.get(), p, ctx, + rsa->mont_p.get()) || + // Compute r0 = r0 - m1 mod p. `m1` is reduced mod `q`, not `p`, so we + // just run `mod_montgomery` again for srsaicity. This could be more + // efficient with more cases: if `p > q`, `m1` is already reduced. If + // `p < q` but they have the same bit width, `bn_reduce_once` suffices. // However, compared to over 2048 Montgomery multiplications above, this // difference is not measurable. - !mod_montgomery(r1, m1, p, rsa->mont_p, q, ctx) || + !mod_montgomery(r1, m1, p, rsa->mont_p.get(), q, ctx) || !bn_mod_sub_consttime(r0, r0, r1, p, ctx) || // r0 = r0 * iqmp mod p. We use Montgomery multiplication to compute this - // in constant time. |iqmp_mont| is in Montgomery form and r0 is not, so + // in constant time. `iqmp_mont` is in Montgomery form and r0 is not, so // the result is taken out of Montgomery form. - !BN_mod_mul_montgomery(r0, r0, rsa->iqmp_mont, rsa->mont_p, ctx) || + !BN_mod_mul_montgomery(r0, r0, rsa->iqmp_mont.get(), rsa->mont_p.get(), + ctx) || // r0 = r0 * q + m1 gives the final result. Reducing modulo q gives m1, so // it is correct mod p. Reducing modulo p gives (r0-m1)*iqmp*q + m1 = r0, // so it is correct mod q. Finally, the result is bounded by [m1, n + m1), - // and the result is at least |m1|, so this must be the unique answer in + // and the result is at least `m1`, so this must be the unique answer in // [0, n). !bn_mul_consttime(r0, r0, q, ctx) || // !bn_uadd_consttime(r0, r0, m1)) { - goto err; + return 0; } - // The result should be bounded by |n|, but fixed-width operations may + // The result should be bounded by `n`, but fixed-width operations may // bound the width slightly higher, so fix it. This trips constant-time checks // because a naive data flow analysis does not realize the excess words are // publicly zero. declassify_assert(BN_cmp(r0, n) < 0); bn_assert_fits_in_bytes(r0, BN_num_bytes(n)); if (!bn_resize_words(r0, n->width)) { - goto err; + return 0; } - ret = 1; - -err: - BN_CTX_end(ctx); - return ret; + return 1; } -static int ensure_bignum(BIGNUM **out) { - if (*out == NULL) { - *out = BN_new(); +static int ensure_bignum(UniquePtr *out) { + if (*out == nullptr) { + out->reset(BN_new()); } - return *out != NULL; + return *out != nullptr; } -// kBoringSSLRSASqrtTwo is the BIGNUM representation of ⌊2²⁰⁴⁷×√2⌋. This is -// chosen to give enough precision for 4096-bit RSA, the largest key size FIPS -// specifies. Key sizes beyond this will round up. -// -// To calculate, use the following Haskell code: -// -// import Text.Printf (printf) -// import Data.List (intercalate) -// -// pow2 = 4095 -// target = 2^pow2 -// -// f x = x*x - (toRational target) -// -// fprime x = 2*x -// -// newtonIteration x = x - (f x) / (fprime x) -// -// converge x = -// let n = floor x in -// if n*n - target < 0 && (n+1)*(n+1) - target > 0 -// then n -// else converge (newtonIteration x) -// -// divrem bits x = (x `div` (2^bits), x `rem` (2^bits)) -// -// bnWords :: Integer -> [Integer] -// bnWords x = -// if x == 0 -// then [] -// else let (high, low) = divrem 64 x in low : bnWords high -// -// showWord x = let (high, low) = divrem 32 x in printf "TOBN(0x%08x, 0x%08x)" -// high low -// -// output :: String -// output = intercalate ", " $ map showWord $ bnWords $ converge (2 ^ (pow2 -// `div` 2)) -// -// To verify this number, check that n² < 2⁴⁰⁹⁵ < (n+1)², where n is value -// represented here. Note the components are listed in little-endian order. Here -// is some sample Python code to check: -// -// >>> TOBN = lambda a, b: a << 32 | b -// >>> l = [ ] -// >>> n = sum(a * 2**(64*i) for i, a in enumerate(l)) -// >>> n**2 < 2**4095 < (n+1)**2 -// True -const BN_ULONG kBoringSSLRSASqrtTwo[] = { - TOBN(0x4d7c60a5, 0xe633e3e1), TOBN(0x5fcf8f7b, 0xca3ea33b), - TOBN(0xc246785e, 0x92957023), TOBN(0xf9acce41, 0x797f2805), - TOBN(0xfdfe170f, 0xd3b1f780), TOBN(0xd24f4a76, 0x3facb882), - TOBN(0x18838a2e, 0xaff5f3b2), TOBN(0xc1fcbdde, 0xa2f7dc33), - TOBN(0xdea06241, 0xf7aa81c2), TOBN(0xf6a1be3f, 0xca221307), - TOBN(0x332a5e9f, 0x7bda1ebf), TOBN(0x0104dc01, 0xfe32352f), - TOBN(0xb8cf341b, 0x6f8236c7), TOBN(0x4264dabc, 0xd528b651), - TOBN(0xf4d3a02c, 0xebc93e0c), TOBN(0x81394ab6, 0xd8fd0efd), - TOBN(0xeaa4a089, 0x9040ca4a), TOBN(0xf52f120f, 0x836e582e), - TOBN(0xcb2a6343, 0x31f3c84d), TOBN(0xc6d5a8a3, 0x8bb7e9dc), - TOBN(0x460abc72, 0x2f7c4e33), TOBN(0xcab1bc91, 0x1688458a), - TOBN(0x53059c60, 0x11bc337b), TOBN(0xd2202e87, 0x42af1f4e), - TOBN(0x78048736, 0x3dfa2768), TOBN(0x0f74a85e, 0x439c7b4a), - TOBN(0xa8b1fe6f, 0xdc83db39), TOBN(0x4afc8304, 0x3ab8a2c3), - TOBN(0xed17ac85, 0x83339915), TOBN(0x1d6f60ba, 0x893ba84c), - TOBN(0x597d89b3, 0x754abe9f), TOBN(0xb504f333, 0xf9de6484), -}; -const size_t kBoringSSLRSASqrtTwoLen = OPENSSL_ARRAY_SIZE(kBoringSSLRSASqrtTwo); - -// generate_prime sets |out| to a prime with length |bits| such that |out|-1 is -// relatively prime to |e|. If |p| is non-NULL, |out| will also not be close to -// |p|. |sqrt2| must be ⌊2^(bits-1)×√2⌋ (or a slightly overestimate for large -// sizes), and |pow2_bits_100| must be 2^(bits-100). +// generate_prime sets `out` to a prime with length `bits` such that `out`-1 is +// relatively prime to `e`. If `p` is non-NULL, `out` will also not be close to +// `p`. `pow2_bits_100` must be 2^(bits-100). // // This function fails with probability around 2^-21. static int generate_prime(BIGNUM *out, int bits, const BIGNUM *e, - const BIGNUM *p, const BIGNUM *sqrt2, - const BIGNUM *pow2_bits_100, BN_CTX *ctx, - BN_GENCB *cb) { + const BIGNUM *p, const BIGNUM *pow2_bits_100, + BN_CTX *ctx, BN_GENCB *cb) { if (bits < 128 || (bits % BN_BITS2) != 0) { OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); return 0; @@ -869,14 +615,14 @@ static int generate_prime(BIGNUM *out, int bits, const BIGNUM *e, assert(BN_is_pow2(pow2_bits_100)); assert(BN_is_bit_set(pow2_bits_100, bits - 100)); - // See FIPS 186-4 appendix B.3.3, steps 4 and 5. Note |bits| here is nlen/2. + // See FIPS 186-5 appendix A.1.3, steps 4 and 5. Note `bits` here is nlen/2. - // Use the limit from steps 4.7 and 5.8 for most values of |e|. When |e| is 3, - // the 186-4 limit is too low, so we use a higher one. Note this case is not - // reachable from |RSA_generate_key_fips|. + // Use the limit from steps 4.7 and 5.8 for most values of `e`. When `e` is 3, + // the 186-5 limit is too low, so we use a higher one. Note this case is not + // reachable from `RSA_generate_key_fips`. // - // |limit| determines the failure probability. We must find a prime that is - // not 1 mod |e|. By the prime number theorem, we'll find one with probability + // `limit` determines the failure probability. We must find a prime that is + // not 1 mod `e`. By the prime number theorem, we'll find one with probability // p = (e-1)/e * 2/(ln(2)*bits). Note the second term is doubled because we // discard even numbers. // @@ -905,46 +651,37 @@ static int generate_prime(BIGNUM *out, int bits, const BIGNUM *e, } int limit = BN_is_word(e, 3) ? bits * 8 : bits * 5; - int ret = 0, tries = 0, rand_tries = 0; - BN_CTX_start(ctx); + int tries = 0, rand_tries = 0; + BN_CTXScope scope(ctx); BIGNUM *tmp = BN_CTX_get(ctx); - if (tmp == NULL) { - goto err; + if (tmp == nullptr) { + return 0; } for (;;) { - // Generate a random number of length |bits| where the bottom bit is set - // (steps 4.2, 4.3, 5.2 and 5.3) and the top bit is set (implied by the - // bound checked below in steps 4.4 and 5.5). - if (!BN_rand(out, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD) || + // Generate a random number of length `bits` where the bottom bit is set and + // top two bits are set (steps 4.2–4.4 and 5.2–5.4): + // + // - Setting the top two bits is permitted by steps 4.2.1 and 5.2.1. Doing + // so implements steps 4.4 and 5.4 by making this case impossible because + // √2 < 1.5. + // + // - Setting the bottom bit implements steps 4.3 and 5.3. + if (!BN_rand(out, bits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ODD) || !BN_GENCB_call(cb, BN_GENCB_GENERATED, rand_tries++)) { - goto err; + return 0; } - if (p != NULL) { - // If |p| and |out| are too close, try again (step 5.4). + if (p != nullptr) { + // If `p` and `out` are too close, try again (step 5.5). if (!bn_abs_sub_consttime(tmp, out, p, ctx)) { - goto err; + return 0; } if (BN_cmp(tmp, pow2_bits_100) <= 0) { continue; } } - // If out < 2^(bits-1)×√2, try again (steps 4.4 and 5.5). This is equivalent - // to out <= ⌊2^(bits-1)×√2⌋, or out <= sqrt2 for FIPS key sizes. - // - // For larger keys, the comparison is approximate, leaning towards - // retrying. That is, we reject a negligible fraction of primes that are - // within the FIPS bound, but we will never accept a prime outside the - // bound, ensuring the resulting RSA key is the right size. - // - // Values over the threshold are discarded, so it is safe to leak this - // comparison. - if (constant_time_declassify_int(BN_cmp(out, sqrt2) <= 0)) { - continue; - } - // RSA key generation's bottleneck is discarding composites. If it fails // trial division, do not bother computing a GCD or performing Miller-Rabin. if (!bn_odd_number_is_obviously_composite(out)) { @@ -954,64 +691,59 @@ static int generate_prime(BIGNUM *out, int bits, const BIGNUM *e, int relatively_prime; if (!bn_usub_consttime(tmp, out, BN_value_one()) || !bn_is_relatively_prime(&relatively_prime, tmp, e, ctx)) { - goto err; + return 0; } if (constant_time_declassify_int(relatively_prime)) { - // Test |out| for primality (steps 4.5.1 and 5.6.1). + // Test `out` for primality (steps 4.5.1 and 5.6.1). int is_probable_prime; if (!BN_primality_test(&is_probable_prime, out, BN_prime_checks_for_generation, ctx, 0, cb)) { - goto err; + return 0; } if (is_probable_prime) { - ret = 1; - goto err; + return 1; } } } - // If we've tried too many times to find a prime, abort (steps 4.7 and - // 5.8). + // If we've tried too many times to find a prime, abort (steps 4.7 and 5.8). tries++; if (tries >= limit) { OPENSSL_PUT_ERROR(RSA, RSA_R_TOO_MANY_ITERATIONS); - goto err; + return 0; } if (!BN_GENCB_call(cb, 2, tries)) { - goto err; + return 0; } } - -err: - BN_CTX_end(ctx); - return ret; } // rsa_generate_key_impl generates an RSA key using a generalized version of -// FIPS 186-4 appendix B.3. |RSA_generate_key_fips| performs additional checks +// FIPS 186-5 appendix A.1.3. `RSA_generate_key_fips` performs additional checks // for FIPS-compliant key generation. // // This function returns one on success and zero on failure. It has a failure // probability of about 2^-20. -static int rsa_generate_key_impl(RSA *rsa, int bits, const BIGNUM *e_value, +static int rsa_generate_key_impl(RSAImpl *rsa, int bits, const BIGNUM *e_value, BN_GENCB *cb) { - // See FIPS 186-4 appendix B.3. This function implements a generalized version - // of the FIPS algorithm. |RSA_generate_key_fips| performs additional checks - // for FIPS-compliant key generation. + if (bits > OPENSSL_RSA_MAX_MODULUS_BITS) { + OPENSSL_PUT_ERROR(RSA, RSA_R_MODULUS_TOO_LARGE); + return 0; + } - // Always generate RSA keys which are a multiple of 128 bits. Round |bits| + // Always generate RSA keys which are a multiple of 128 bits. Round `bits` // down as needed. bits &= ~127; // Reject excessively small keys. - if (bits < 256) { + if (bits < OPENSSL_RSA_MIN_MODULUS_BITS) { OPENSSL_PUT_ERROR(RSA, RSA_R_KEY_SIZE_TOO_SMALL); return 0; } // Reject excessively large public exponents. Windows CryptoAPI and Go don't // support values larger than 32 bits, so match their limits for generating - // keys. (|rsa_check_public_key| uses a slightly more conservative value, but + // keys. (`rsa_check_public_key` uses a slightly more conservative value, but // we don't need to support generating such keys.) // https://github.com/golang/go/issues/3161 // https://msdn.microsoft.com/en-us/library/aa387685(VS.85).aspx @@ -1020,29 +752,45 @@ static int rsa_generate_key_impl(RSA *rsa, int bits, const BIGNUM *e_value, return 0; } - int ret = 0; - int prime_bits = bits / 2; - BN_CTX *ctx = BN_CTX_new(); - BIGNUM *totient, *pm1, *qm1, *sqrt2, *pow2_prime_bits_100, *pow2_prime_bits; - int sqrt2_bits; - if (ctx == NULL) { - goto bn_err; - } - BN_CTX_start(ctx); - totient = BN_CTX_get(ctx); - pm1 = BN_CTX_get(ctx); - qm1 = BN_CTX_get(ctx); - sqrt2 = BN_CTX_get(ctx); - pow2_prime_bits_100 = BN_CTX_get(ctx); - pow2_prime_bits = BN_CTX_get(ctx); - if (totient == NULL || pm1 == NULL || qm1 == NULL || sqrt2 == NULL || - pow2_prime_bits_100 == NULL || pow2_prime_bits == NULL || - !BN_set_bit(pow2_prime_bits_100, prime_bits - 100) || - !BN_set_bit(pow2_prime_bits, prime_bits)) { - goto bn_err; + // The smallest reasonable RSA exponent is 3, and it definitely must be odd. + // Catching these here prevents endless loops or slow computation when trying + // to generate keys later, and results in a better error code. + if ( + // Would fail in `bn_lcm_consttime` as it only allows positive integers. + BN_is_negative(e_value) || + // Would fail in `generate_prime` as only one `rsa->p`-1 is coprime with + // an even `e_value` and that one is a little bit short. (The R in RSA + // doesn't stand for Rabin.) + !BN_is_odd(e_value) || + // Would loop endlessly because it'll always compute an `rsa->d` exponent + // of 1, which is too small. + BN_is_one(e_value)) { + OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_E_VALUE); + return 0; } - // We need the RSA components non-NULL. + UniquePtr ctx(BN_CTX_new()); + if (ctx == nullptr) { + OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); + return 0; + } + + int prime_bits = bits / 2; + BN_CTXScope scope(ctx.get()); + BIGNUM *totient = BN_CTX_get(ctx.get()); + BIGNUM *pm1 = BN_CTX_get(ctx.get()); + BIGNUM *qm1 = BN_CTX_get(ctx.get()); + BIGNUM *pow2_prime_bits_100 = BN_CTX_get(ctx.get()); + BIGNUM *pow2_prime_bits = BN_CTX_get(ctx.get()); + if (totient == nullptr || pm1 == nullptr || qm1 == nullptr || + pow2_prime_bits_100 == nullptr || pow2_prime_bits == nullptr || + !BN_set_bit(pow2_prime_bits_100, prime_bits - 100) || + !BN_set_bit(pow2_prime_bits, prime_bits)) { + OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); + return 0; + } + + // We need the RSA components non-null. if (!ensure_bignum(&rsa->n) || // !ensure_bignum(&rsa->d) || // !ensure_bignum(&rsa->e) || // @@ -1051,229 +799,186 @@ static int rsa_generate_key_impl(RSA *rsa, int bits, const BIGNUM *e_value, !ensure_bignum(&rsa->dmp1) || // !ensure_bignum(&rsa->dmq1) || // !ensure_bignum(&rsa->iqmp)) { - goto bn_err; + OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); + return 0; } - if (!BN_copy(rsa->e, e_value)) { - goto bn_err; + if (!BN_copy(rsa->e.get(), e_value)) { + OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); + return 0; } - // Compute sqrt2 >= ⌊2^(prime_bits-1)×√2⌋. - if (!bn_set_words(sqrt2, kBoringSSLRSASqrtTwo, kBoringSSLRSASqrtTwoLen)) { - goto bn_err; - } - sqrt2_bits = kBoringSSLRSASqrtTwoLen * BN_BITS2; - assert(sqrt2_bits == (int)BN_num_bits(sqrt2)); - if (sqrt2_bits > prime_bits) { - // For key sizes up to 4096 (prime_bits = 2048), this is exactly - // ⌊2^(prime_bits-1)×√2⌋. - if (!BN_rshift(sqrt2, sqrt2, sqrt2_bits - prime_bits)) { - goto bn_err; - } - } else if (prime_bits > sqrt2_bits) { - // For key sizes beyond 4096, this is approximate. We err towards retrying - // to ensure our key is the right size and round up. - if (!BN_add_word(sqrt2, 1) || - !BN_lshift(sqrt2, sqrt2, prime_bits - sqrt2_bits)) { - goto bn_err; - } - } - assert(prime_bits == (int)BN_num_bits(sqrt2)); - do { - // Generate p and q, each of size |prime_bits|, using the steps outlined in - // appendix FIPS 186-4 appendix B.3.3. + // Generate p and q, each of size `prime_bits`, using the steps outlined in + // appendix FIPS 186-5 appendix C.3.3. // - // Each call to |generate_prime| fails with probability p = 2^-21. The - // probability that either call fails is 1 - (1-p)^2, which is around 2^-20. - if (!generate_prime(rsa->p, prime_bits, rsa->e, NULL, sqrt2, - pow2_prime_bits_100, ctx, cb) || + // Each call to `generate_prime` fails with probability p = 2^-21. The + // probability that either call fails is 1 - (1-p)², which is around 2^-20. + if (!generate_prime(rsa->p.get(), prime_bits, rsa->e.get(), nullptr, + pow2_prime_bits_100, ctx.get(), cb) || !BN_GENCB_call(cb, 3, 0) || - !generate_prime(rsa->q, prime_bits, rsa->e, rsa->p, sqrt2, - pow2_prime_bits_100, ctx, cb) || + !generate_prime(rsa->q.get(), prime_bits, rsa->e.get(), rsa->p.get(), + pow2_prime_bits_100, ctx.get(), cb) || !BN_GENCB_call(cb, 3, 1)) { - goto bn_err; + OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); + return 0; } - if (BN_cmp(rsa->p, rsa->q) < 0) { - BIGNUM *tmp = rsa->p; - rsa->p = rsa->q; - rsa->q = tmp; + if (BN_cmp(rsa->p.get(), rsa->q.get()) < 0) { + std::swap(rsa->p, rsa->q); } - // Calculate d = e^(-1) (mod lcm(p-1, q-1)), per FIPS 186-4. This differs - // from typical RSA implementations which use (p-1)*(q-1). + // Calculate d = e^(-1) (mod lcm(p-1, q-1)), per FIPS 186-5. This differs + // from typical RSA rsaementations which use (p-1)*(q-1). // // Note this means the size of d might reveal information about p-1 and // q-1. However, we do operations with Chinese Remainder Theorem, so we only // use d (mod p-1) and d (mod q-1) as exponents. Using a minimal totient // does not affect those two values. int no_inverse; - if (!bn_usub_consttime(pm1, rsa->p, BN_value_one()) || - !bn_usub_consttime(qm1, rsa->q, BN_value_one()) || - !bn_lcm_consttime(totient, pm1, qm1, ctx) || - !bn_mod_inverse_consttime(rsa->d, &no_inverse, rsa->e, totient, ctx)) { - goto bn_err; + if (!bn_usub_consttime(pm1, rsa->p.get(), BN_value_one()) || + !bn_usub_consttime(qm1, rsa->q.get(), BN_value_one()) || + !bn_lcm_consttime(totient, pm1, qm1, ctx.get()) || + !bn_mod_inverse_consttime(rsa->d.get(), &no_inverse, rsa->e.get(), + totient, ctx.get())) { + OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); + return 0; } - // Retry if |rsa->d| <= 2^|prime_bits|. See appendix B.3.1's guidance on + // Retry if `rsa->d` <= 2^`prime_bits`. See appendix A.3.1's guidance on // values for d. When we retry, p and q are discarded, so it is safe to leak // this comparison. - } while (constant_time_declassify_int(BN_cmp(rsa->d, pow2_prime_bits) <= 0)); + } while ( + constant_time_declassify_int(BN_cmp(rsa->d.get(), pow2_prime_bits) <= 0)); assert(BN_num_bits(pm1) == (unsigned)prime_bits); assert(BN_num_bits(qm1) == (unsigned)prime_bits); if ( // Calculate n. - !bn_mul_consttime(rsa->n, rsa->p, rsa->q, ctx) || + !bn_mul_consttime(rsa->n.get(), rsa->p.get(), rsa->q.get(), ctx.get()) || // Calculate d mod (p-1). - !bn_div_consttime(NULL, rsa->dmp1, rsa->d, pm1, prime_bits, ctx) || + !bn_div_consttime(nullptr, rsa->dmp1.get(), rsa->d.get(), pm1, prime_bits, + ctx.get()) || // Calculate d mod (q-1) - !bn_div_consttime(NULL, rsa->dmq1, rsa->d, qm1, prime_bits, ctx)) { - goto bn_err; + !bn_div_consttime(nullptr, rsa->dmq1.get(), rsa->d.get(), qm1, prime_bits, + ctx.get())) { + OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); + return 0; } - bn_set_minimal_width(rsa->n); + bn_set_minimal_width(rsa->n.get()); - // |rsa->n| is computed from the private key, but is public. - bn_declassify(rsa->n); + // `rsa->n` is computed from the private key, but is public. + bn_declassify(rsa->n.get()); // Calculate q^-1 mod p. - rsa->mont_p = BN_MONT_CTX_new_consttime(rsa->p, ctx); - if (rsa->mont_p == NULL || // - !bn_mod_inverse_secret_prime(rsa->iqmp, rsa->q, rsa->p, ctx, - rsa->mont_p)) { - goto bn_err; + rsa->mont_p.reset(BN_MONT_CTX_new_consttime(rsa->p.get(), ctx.get())); + if (rsa->mont_p == nullptr || // + !bn_mod_inverse_secret_prime(rsa->iqmp.get(), rsa->q.get(), rsa->p.get(), + ctx.get(), rsa->mont_p.get())) { + OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); + return 0; } - // Sanity-check that |rsa->n| has the specified size. This is implied by - // |generate_prime|'s bounds. - if (BN_num_bits(rsa->n) != (unsigned)bits) { + // Sanity-check that `rsa->n` has the specified size. This is rsaied by + // `generate_prime`'s bounds. + if (BN_num_bits(rsa->n.get()) != (unsigned)bits) { OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); - goto err; + return 0; } // The key generation process is complex and thus error-prone. It could be // disastrous to generate and then use a bad key so double-check that the key - // makes sense. Also, while |rsa| is mutable, fill in the cached components. - if (!RSA_check_key(rsa) || - !freeze_private_key(rsa, ctx)) { + // makes sense. Also, while `rsa` is mutable, fill in the cached components. + if (!RSA_check_key(rsa) || !freeze_private_key(rsa, ctx.get())) { OPENSSL_PUT_ERROR(RSA, RSA_R_INTERNAL_ERROR); - goto err; + return 0; } - ret = 1; - -bn_err: - if (!ret) { - OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); - } -err: - if (ctx != NULL) { - BN_CTX_end(ctx); - BN_CTX_free(ctx); - } - return ret; + return 1; } -static void replace_bignum(BIGNUM **out, BIGNUM **in) { - BN_free(*out); - *out = *in; - *in = NULL; -} - -static void replace_bn_mont_ctx(BN_MONT_CTX **out, BN_MONT_CTX **in) { - BN_MONT_CTX_free(*out); - *out = *in; - *in = NULL; -} - -static int RSA_generate_key_ex_maybe_fips(RSA *rsa, int bits, +static int RSA_generate_key_ex_maybe_fips(RSAImpl *rsa, int bits, const BIGNUM *e_value, BN_GENCB *cb, int check_fips) { - boringssl_ensure_rsa_self_test(); + boringssl_ensure_rsa_sign_self_test(); + boringssl_ensure_rsa_verify_self_test(); - if (rsa == NULL) { + if (rsa == nullptr) { OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } - RSA *tmp = NULL; - uint32_t err; - int ret = 0; + UniquePtr tmp; - // |rsa_generate_key_impl|'s 2^-20 failure probability is too high at scale, + // `rsa_generate_key_impl`'s 2^-20 failure probability is too high at scale, // so we run the FIPS algorithm four times, bringing it down to 2^-80. We - // should just adjust the retry limit, but FIPS 186-4 prescribes that value + // should just adjust the retry limit, but FIPS 186-5 prescribes that value // and thus results in unnecessary complexity. int failures = 0; do { ERR_clear_error(); // Generate into scratch space, to avoid leaving partial work on failure. - tmp = RSA_new(); - if (tmp == NULL) { - goto out; + tmp.reset(FromOpaque(RSA_new())); + if (tmp == nullptr) { + return 0; } - if (rsa_generate_key_impl(tmp, bits, e_value, cb)) { + if (rsa_generate_key_impl(tmp.get(), bits, e_value, cb)) { break; } - err = ERR_peek_error(); - RSA_free(tmp); - tmp = NULL; + tmp = nullptr; failures++; - // Only retry on |RSA_R_TOO_MANY_ITERATIONS|. This is so a caller-induced - // failure in |BN_GENCB_call| is still fatal. - } while (failures < 4 && ERR_GET_LIB(err) == ERR_LIB_RSA && - ERR_GET_REASON(err) == RSA_R_TOO_MANY_ITERATIONS); + // Only retry on `RSA_R_TOO_MANY_ITERATIONS`. This is so a caller-induced + // failure in `BN_GENCB_call` is still fatal. + } while (failures < 4 && ERR_equals(ERR_peek_error(), ERR_LIB_RSA, + RSA_R_TOO_MANY_ITERATIONS)); - if (tmp == NULL || (check_fips && !RSA_check_fips(tmp))) { - goto out; + if (tmp == nullptr || (check_fips && !RSA_check_fips(tmp.get()))) { + return 0; } rsa_invalidate_key(rsa); - replace_bignum(&rsa->n, &tmp->n); - replace_bignum(&rsa->e, &tmp->e); - replace_bignum(&rsa->d, &tmp->d); - replace_bignum(&rsa->p, &tmp->p); - replace_bignum(&rsa->q, &tmp->q); - replace_bignum(&rsa->dmp1, &tmp->dmp1); - replace_bignum(&rsa->dmq1, &tmp->dmq1); - replace_bignum(&rsa->iqmp, &tmp->iqmp); - replace_bn_mont_ctx(&rsa->mont_n, &tmp->mont_n); - replace_bn_mont_ctx(&rsa->mont_p, &tmp->mont_p); - replace_bn_mont_ctx(&rsa->mont_q, &tmp->mont_q); - replace_bignum(&rsa->d_fixed, &tmp->d_fixed); - replace_bignum(&rsa->dmp1_fixed, &tmp->dmp1_fixed); - replace_bignum(&rsa->dmq1_fixed, &tmp->dmq1_fixed); - replace_bignum(&rsa->iqmp_mont, &tmp->iqmp_mont); + rsa->n = std::move(tmp->n); + rsa->e = std::move(tmp->e); + rsa->d = std::move(tmp->d); + rsa->p = std::move(tmp->p); + rsa->q = std::move(tmp->q); + rsa->dmp1 = std::move(tmp->dmp1); + rsa->dmq1 = std::move(tmp->dmq1); + rsa->iqmp = std::move(tmp->iqmp); + rsa->mont_n = std::move(tmp->mont_n); + rsa->mont_p = std::move(tmp->mont_p); + rsa->mont_q = std::move(tmp->mont_q); + rsa->d_fixed = std::move(tmp->d_fixed); + rsa->dmp1_fixed = std::move(tmp->dmp1_fixed); + rsa->dmq1_fixed = std::move(tmp->dmq1_fixed); + rsa->iqmp_mont = std::move(tmp->iqmp_mont); rsa->private_key_frozen = tmp->private_key_frozen; - ret = 1; - -out: - RSA_free(tmp); - return ret; + return 1; } int RSA_generate_key_ex(RSA *rsa, int bits, const BIGNUM *e_value, BN_GENCB *cb) { - return RSA_generate_key_ex_maybe_fips(rsa, bits, e_value, cb, + return RSA_generate_key_ex_maybe_fips(FromOpaque(rsa), bits, e_value, cb, /*check_fips=*/0); } int RSA_generate_key_fips(RSA *rsa, int bits, BN_GENCB *cb) { - // FIPS 186-4 allows 2048-bit and 3072-bit RSA keys (1024-bit and 1536-bit + // FIPS 186-4 allowed 2048-bit and 3072-bit RSA keys (1024-bit and 1536-bit // primes, respectively) with the prime generation method we use. // Subsequently, IG A.14 stated that larger modulus sizes can be used and ACVP - // testing supports 4096 bits. + // testing supports 4096 bits, and FIPS 186-5 allowed all key sizes at least + // 2048. if (bits != 2048 && bits != 3072 && bits != 4096) { OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_RSA_PARAMETERS); return 0; } BIGNUM *e = BN_new(); - int ret = e != NULL && BN_set_word(e, RSA_F4) && - RSA_generate_key_ex_maybe_fips(rsa, bits, e, cb, /*check_fips=*/1); + int ret = e != nullptr && BN_set_word(e, RSA_F4) && + RSA_generate_key_ex_maybe_fips(FromOpaque(rsa), bits, e, cb, + /*check_fips=*/1); BN_free(e); if (ret) { @@ -1282,10 +987,14 @@ int RSA_generate_key_fips(RSA *rsa, int bits, BN_GENCB *cb) { return ret; } +BSSL_NAMESPACE_BEGIN + DEFINE_METHOD_FUNCTION(RSA_METHOD, RSA_default_method) { // All of the methods are NULL to make it easier for the compiler/linker to // drop unused functions. The wrapper functions will select the appropriate - // |rsa_default_*| implementation. + // `rsa_default_*` implementation. OPENSSL_memset(out, 0, sizeof(RSA_METHOD)); out->common.is_static = 1; } + +BSSL_NAMESPACE_END diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/self_check/fips.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/self_check/fips.cc.inc index fe52f032..052c1278 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/self_check/fips.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/self_check/fips.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2017 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2017 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 @@ -18,7 +18,9 @@ #include "../delocate.h" -int FIPS_mode(void) { +using namespace bssl; + +int FIPS_mode() { #if defined(BORINGSSL_FIPS) && !defined(OPENSSL_ASAN) return 1; #else @@ -28,9 +30,9 @@ int FIPS_mode(void) { int FIPS_mode_set(int on) { return on == FIPS_mode(); } -const char *FIPS_module_name(void) { return "BoringCrypto"; } +const char *FIPS_module_name() { return "BoringCrypto"; } -int CRYPTO_has_asm(void) { +int CRYPTO_has_asm() { #if defined(OPENSSL_NO_ASM) return 0; #else @@ -38,9 +40,7 @@ int CRYPTO_has_asm(void) { #endif } -uint32_t FIPS_version(void) { - return 0; -} +uint32_t FIPS_version() { return 0; } int FIPS_query_algorithm_status(const char *algorithm) { #if defined(BORINGSSL_FIPS) @@ -67,8 +67,8 @@ int FIPS_query_algorithm_status(const char *algorithm) { "SHA2-512", "SHA2-512/256", }; - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kApprovedAlgorithms); i++) { - if (strcmp(algorithm, kApprovedAlgorithms[i]) == 0) { + for (const char *approved : kApprovedAlgorithms) { + if (strcmp(algorithm, approved) == 0) { return 1; } } @@ -94,7 +94,7 @@ size_t FIPS_read_counter(enum fips_counter_t counter) { return array[index]; } -void boringssl_fips_inc_counter(enum fips_counter_t counter) { +void bssl::boringssl_fips_inc_counter(enum fips_counter_t counter) { size_t index = (size_t)counter; if (index > fips_counter_max) { abort(); @@ -111,7 +111,7 @@ void boringssl_fips_inc_counter(enum fips_counter_t counter) { if (!CRYPTO_set_thread_local(OPENSSL_THREAD_LOCAL_FIPS_COUNTERS, array, OPENSSL_free)) { - // |OPENSSL_free| has already been called by |CRYPTO_set_thread_local|. + // `OPENSSL_free` has already been called by `CRYPTO_set_thread_local`. return; } } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/self_check/self_check.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/self_check/self_check.cc.inc index 45217375..ccb8c3d0 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/self_check/self_check.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/self_check/self_check.cc.inc @@ -1,22 +1,24 @@ -/* Copyright 2017 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2017 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 @@ -31,6 +33,8 @@ #include #include #include +#include +#include #include "../../bcm_support.h" #include "../../internal.h" @@ -44,29 +48,22 @@ #include "../tls/internal.h" -// MSVC wants to put a NUL byte at the end of non-char arrays and so cannot -// compile the real logic. -#if defined(_MSC_VER) +using namespace bssl; -int BORINGSSL_self_test(void) { return 0; } - -#else - -static void hexdump(FILE *out, const void *in, size_t len) { - const uint8_t *in8 = reinterpret_cast(in); - for (size_t i = 0; i < len; i++) { - fprintf(out, "%02x", in8[i]); +static void hexdump(FILE *out, Span in) { + for (uint8_t b : in) { + fprintf(out, "%02x", b); } } -static int check_test(const void *expected, const void *actual, - size_t expected_len, const char *name) { - if (OPENSSL_memcmp(actual, expected, expected_len) != 0) { +int bssl::BORINGSSL_check_test(Span expected, + Span actual, const char *name) { + if (expected != actual) { FILE *err = CRYPTO_get_stderr(); fprintf(err, "%s failed.\nExpected: ", name); - hexdump(err, expected, expected_len); + hexdump(err, expected); fprintf(err, "\nCalculated: "); - hexdump(err, actual, expected_len); + hexdump(err, actual); fprintf(err, "\n"); fflush(err); return 0; @@ -74,37 +71,50 @@ static int check_test(const void *expected, const void *actual, return 1; } -static int set_bignum(BIGNUM **out, const uint8_t *in, size_t len) { - *out = BN_bin2bn(in, len, NULL); - return *out != NULL; +static int set_bignum(UniquePtr *out, Span in) { + out->reset(BN_bin2bn(in.data(), in.size(), nullptr)); + return *out != nullptr; } -static RSA *self_test_rsa_key(void) { - static const uint8_t kN[] = { - 0xd3, 0x3a, 0x62, 0x9f, 0x07, 0x77, 0xb0, 0x18, 0xf3, 0xff, 0xfe, 0xcc, - 0xc9, 0xa2, 0xc2, 0x3a, 0xa6, 0x1d, 0xd8, 0xf0, 0x26, 0x5b, 0x38, 0x90, - 0x17, 0x48, 0x15, 0xce, 0x21, 0xcd, 0xd6, 0x62, 0x99, 0xe2, 0xd7, 0xda, - 0x40, 0x80, 0x3c, 0xad, 0x18, 0xb7, 0x26, 0xe9, 0x30, 0x8a, 0x23, 0x3f, - 0x68, 0x9a, 0x9c, 0x31, 0x34, 0x91, 0x99, 0x06, 0x11, 0x36, 0xb2, 0x9e, - 0x3a, 0xd0, 0xbc, 0xb9, 0x93, 0x4e, 0xb8, 0x72, 0xa1, 0x9f, 0xb6, 0x8c, - 0xd5, 0x17, 0x1f, 0x7e, 0xaa, 0x75, 0xbb, 0xdf, 0xa1, 0x70, 0x48, 0xc4, - 0xec, 0x9a, 0x51, 0xed, 0x41, 0xc9, 0x74, 0xc0, 0x3e, 0x1e, 0x85, 0x2f, - 0xbe, 0x34, 0xc7, 0x65, 0x34, 0x8b, 0x4d, 0x55, 0x4b, 0xe1, 0x45, 0x54, - 0x0d, 0x75, 0x7e, 0x89, 0x4d, 0x0c, 0xf6, 0x33, 0xe5, 0xfc, 0xfb, 0x56, - 0x1b, 0xf2, 0x39, 0x9d, 0xe0, 0xff, 0x55, 0xcf, 0x02, 0x05, 0xb9, 0x74, - 0xd2, 0x91, 0xfc, 0x87, 0xe1, 0xbb, 0x97, 0x2a, 0xe4, 0xdd, 0x20, 0xc0, - 0x38, 0x47, 0xc0, 0x76, 0x3f, 0xa1, 0x9b, 0x5c, 0x20, 0xff, 0xff, 0xc7, - 0x49, 0x3b, 0x4c, 0xaf, 0x99, 0xa6, 0x3e, 0x82, 0x5c, 0x58, 0x27, 0xce, - 0x01, 0x03, 0xc3, 0x16, 0x35, 0x20, 0xe9, 0xf0, 0x15, 0x7a, 0x41, 0xd5, - 0x1f, 0x52, 0xea, 0xdf, 0xad, 0x4c, 0xbb, 0x0d, 0xcb, 0x04, 0x91, 0xb0, - 0x95, 0xa8, 0xce, 0x25, 0xfd, 0xd2, 0x62, 0x47, 0x77, 0xee, 0x13, 0xf1, - 0x48, 0x72, 0x9e, 0xd9, 0x2d, 0xe6, 0x5f, 0xa4, 0xc6, 0x9e, 0x5a, 0xb2, - 0xc6, 0xa2, 0xf7, 0x0a, 0x16, 0x17, 0xae, 0x6b, 0x1c, 0x30, 0x7c, 0x63, - 0x08, 0x83, 0xe7, 0x43, 0xec, 0x54, 0x5e, 0x2c, 0x08, 0x0b, 0x5e, 0x46, - 0xa7, 0x10, 0x93, 0x43, 0x53, 0x4e, 0xe3, 0x16, 0x73, 0x55, 0xce, 0xf2, - 0x94, 0xc0, 0xbe, 0xb3, - }; - static const uint8_t kE[] = {0x01, 0x00, 0x01}; // 65537 +static const uint8_t kRSASelfTestN[] = { + 0xd3, 0x3a, 0x62, 0x9f, 0x07, 0x77, 0xb0, 0x18, 0xf3, 0xff, 0xfe, 0xcc, + 0xc9, 0xa2, 0xc2, 0x3a, 0xa6, 0x1d, 0xd8, 0xf0, 0x26, 0x5b, 0x38, 0x90, + 0x17, 0x48, 0x15, 0xce, 0x21, 0xcd, 0xd6, 0x62, 0x99, 0xe2, 0xd7, 0xda, + 0x40, 0x80, 0x3c, 0xad, 0x18, 0xb7, 0x26, 0xe9, 0x30, 0x8a, 0x23, 0x3f, + 0x68, 0x9a, 0x9c, 0x31, 0x34, 0x91, 0x99, 0x06, 0x11, 0x36, 0xb2, 0x9e, + 0x3a, 0xd0, 0xbc, 0xb9, 0x93, 0x4e, 0xb8, 0x72, 0xa1, 0x9f, 0xb6, 0x8c, + 0xd5, 0x17, 0x1f, 0x7e, 0xaa, 0x75, 0xbb, 0xdf, 0xa1, 0x70, 0x48, 0xc4, + 0xec, 0x9a, 0x51, 0xed, 0x41, 0xc9, 0x74, 0xc0, 0x3e, 0x1e, 0x85, 0x2f, + 0xbe, 0x34, 0xc7, 0x65, 0x34, 0x8b, 0x4d, 0x55, 0x4b, 0xe1, 0x45, 0x54, + 0x0d, 0x75, 0x7e, 0x89, 0x4d, 0x0c, 0xf6, 0x33, 0xe5, 0xfc, 0xfb, 0x56, + 0x1b, 0xf2, 0x39, 0x9d, 0xe0, 0xff, 0x55, 0xcf, 0x02, 0x05, 0xb9, 0x74, + 0xd2, 0x91, 0xfc, 0x87, 0xe1, 0xbb, 0x97, 0x2a, 0xe4, 0xdd, 0x20, 0xc0, + 0x38, 0x47, 0xc0, 0x76, 0x3f, 0xa1, 0x9b, 0x5c, 0x20, 0xff, 0xff, 0xc7, + 0x49, 0x3b, 0x4c, 0xaf, 0x99, 0xa6, 0x3e, 0x82, 0x5c, 0x58, 0x27, 0xce, + 0x01, 0x03, 0xc3, 0x16, 0x35, 0x20, 0xe9, 0xf0, 0x15, 0x7a, 0x41, 0xd5, + 0x1f, 0x52, 0xea, 0xdf, 0xad, 0x4c, 0xbb, 0x0d, 0xcb, 0x04, 0x91, 0xb0, + 0x95, 0xa8, 0xce, 0x25, 0xfd, 0xd2, 0x62, 0x47, 0x77, 0xee, 0x13, 0xf1, + 0x48, 0x72, 0x9e, 0xd9, 0x2d, 0xe6, 0x5f, 0xa4, 0xc6, 0x9e, 0x5a, 0xb2, + 0xc6, 0xa2, 0xf7, 0x0a, 0x16, 0x17, 0xae, 0x6b, 0x1c, 0x30, 0x7c, 0x63, + 0x08, 0x83, 0xe7, 0x43, 0xec, 0x54, 0x5e, 0x2c, 0x08, 0x0b, 0x5e, 0x46, + 0xa7, 0x10, 0x93, 0x43, 0x53, 0x4e, 0xe3, 0x16, 0x73, 0x55, 0xce, 0xf2, + 0x94, 0xc0, 0xbe, 0xb3, +}; +static const uint8_t kRSASelfTestE[] = {0x01, 0x00, 0x01}; // 65537 + +static RSA *self_test_rsa_public_key() { + RSAImpl *rsa = FromOpaque(RSA_new()); + if (rsa == nullptr || // + !set_bignum(&rsa->n, kRSASelfTestN) || + !set_bignum(&rsa->e, kRSASelfTestE)) { + RSA_free(rsa); + return nullptr; + } + + return rsa; +} + +static RSA *self_test_rsa_private_key() { static const uint8_t kD[] = { 0x2f, 0x2c, 0x1e, 0xd2, 0x3d, 0x2c, 0xb1, 0x9b, 0x21, 0x02, 0xce, 0xb8, 0x95, 0x5f, 0x4f, 0xd9, 0x21, 0x38, 0x11, 0x36, 0xb0, 0x9a, 0x36, 0xab, @@ -195,24 +205,24 @@ static RSA *self_test_rsa_key(void) { 0x89, 0x29, 0xc7, 0x05, 0x27, 0x68, 0x90, 0x15, }; - RSA *rsa = RSA_new(); - if (rsa == NULL || // - !set_bignum(&rsa->n, kN, sizeof(kN)) || - !set_bignum(&rsa->e, kE, sizeof(kE)) || - !set_bignum(&rsa->d, kD, sizeof(kD)) || - !set_bignum(&rsa->p, kP, sizeof(kP)) || - !set_bignum(&rsa->q, kQ, sizeof(kQ)) || - !set_bignum(&rsa->dmp1, kDModPMinusOne, sizeof(kDModPMinusOne)) || - !set_bignum(&rsa->dmq1, kDModQMinusOne, sizeof(kDModQMinusOne)) || - !set_bignum(&rsa->iqmp, kQInverseModP, sizeof(kQInverseModP))) { + RSAImpl *rsa = FromOpaque(RSA_new()); + if (rsa == nullptr || // + !set_bignum(&rsa->n, kRSASelfTestN) || + !set_bignum(&rsa->e, kRSASelfTestE) || // + !set_bignum(&rsa->d, kD) || // + !set_bignum(&rsa->p, kP) || // + !set_bignum(&rsa->q, kQ) || // + !set_bignum(&rsa->dmp1, kDModPMinusOne) || + !set_bignum(&rsa->dmq1, kDModQMinusOne) || + !set_bignum(&rsa->iqmp, kQInverseModP)) { RSA_free(rsa); - return NULL; + return nullptr; } return rsa; } -static EC_KEY *self_test_ecdsa_key(void) { +static EC_KEY *self_test_ecdsa_key() { static const uint8_t kQx[] = { 0xc8, 0x15, 0x61, 0xec, 0xf2, 0xe5, 0x4e, 0xde, 0xfe, 0x66, 0x17, 0xdb, 0x1c, 0x7a, 0x34, 0xa7, 0x07, 0x44, 0xdd, 0xb2, 0x61, 0xf2, @@ -230,15 +240,15 @@ static EC_KEY *self_test_ecdsa_key(void) { }; EC_KEY *ec_key = EC_KEY_new(); - BIGNUM *qx = BN_bin2bn(kQx, sizeof(kQx), NULL); - BIGNUM *qy = BN_bin2bn(kQy, sizeof(kQy), NULL); - BIGNUM *d = BN_bin2bn(kD, sizeof(kD), NULL); - if (ec_key == NULL || qx == NULL || qy == NULL || d == NULL || + BIGNUM *qx = BN_bin2bn(kQx, sizeof(kQx), nullptr); + BIGNUM *qy = BN_bin2bn(kQy, sizeof(kQy), nullptr); + BIGNUM *d = BN_bin2bn(kD, sizeof(kD), nullptr); + if (ec_key == nullptr || qx == nullptr || qy == nullptr || d == nullptr || !EC_KEY_set_group(ec_key, EC_group_p256()) || !EC_KEY_set_public_key_affine_coordinates(ec_key, qx, qy) || !EC_KEY_set_private_key(ec_key, d)) { EC_KEY_free(ec_key); - ec_key = NULL; + ec_key = nullptr; } BN_free(qx); @@ -247,10 +257,10 @@ static EC_KEY *self_test_ecdsa_key(void) { return ec_key; } -static DH *self_test_dh(void) { +static DH *self_test_dh() { DH *dh = DH_get_rfc7919_2048(); if (!dh) { - return NULL; + return nullptr; } BIGNUM *priv = BN_new(); @@ -269,9 +279,9 @@ static DH *self_test_dh(void) { }; bn_set_static_words(priv, kFFDHE2048PrivateKeyData, - OPENSSL_ARRAY_SIZE(kFFDHE2048PrivateKeyData)); + std::size(kFFDHE2048PrivateKeyData)); - if (!DH_set0_key(dh, NULL, priv)) { + if (!DH_set0_key(dh, nullptr, priv)) { goto err; } return dh; @@ -279,7 +289,7 @@ static DH *self_test_dh(void) { err: BN_free(priv); DH_free(dh); - return NULL; + return nullptr; } @@ -287,20 +297,14 @@ err: // // Self tests that are slow are deferred until the corresponding algorithm is // actually exercised, in FIPS mode. (In non-FIPS mode these tests are only run -// when requested by |BORINGSSL_self_test|.) +// when requested by `BORINGSSL_self_test`.) -static int boringssl_self_test_rsa(void) { - int ret = 0; - uint8_t output[256]; - - RSA *const rsa_key = self_test_rsa_key(); - if (rsa_key == NULL) { +static int boringssl_self_test_rsa_sign() { + UniquePtr rsa_key(self_test_rsa_private_key()); + if (rsa_key == nullptr) { fprintf(CRYPTO_get_stderr(), "RSA key construction failed\n"); - goto err; + return 0; } - // Disable blinding for the power-on tests because it's not needed and - // triggers an entropy draw. - rsa_key->flags |= RSA_FLAG_NO_BLINDING; // RSA Sign KAT @@ -334,13 +338,24 @@ static int boringssl_self_test_rsa(void) { 0x10, 0xaf, 0x72, 0x67, }; + uint8_t output[256]; unsigned sig_len; if (!rsa_sign_no_self_test(NID_sha256, kRSASignDigest, sizeof(kRSASignDigest), - output, &sig_len, rsa_key) || - !check_test(kRSASignSignature, output, sizeof(kRSASignSignature), - "RSA-sign KAT")) { + output, &sig_len, rsa_key.get()) || + !BORINGSSL_check_test(kRSASignSignature, Span(output, sig_len), + "RSA-sign KAT")) { fprintf(CRYPTO_get_stderr(), "RSA signing test failed.\n"); - goto err; + return 0; + } + + return 1; +} + +static int boringssl_self_test_rsa_verify() { + UniquePtr rsa_key(self_test_rsa_public_key()); + if (rsa_key == nullptr) { + fprintf(CRYPTO_get_stderr(), "RSA key construction failed\n"); + return 0; } // RSA Verify KAT @@ -376,33 +391,28 @@ static int boringssl_self_test_rsa(void) { }; if (!rsa_verify_no_self_test(NID_sha256, kRSAVerifyDigest, sizeof(kRSAVerifyDigest), kRSAVerifySignature, - sizeof(kRSAVerifySignature), rsa_key)) { + sizeof(kRSAVerifySignature), rsa_key.get())) { fprintf(CRYPTO_get_stderr(), "RSA-verify KAT failed.\n"); - goto err; + return 0; } - ret = 1; - -err: - RSA_free(rsa_key); - - return ret; + return 1; } -static int boringssl_self_test_ecc(void) { +static int boringssl_self_test_ecc() { int ret = 0; - EC_KEY *ec_key = NULL; - EC_POINT *ec_point_in = NULL; - EC_POINT *ec_point_out = NULL; - BIGNUM *ec_scalar = NULL; - const EC_GROUP *ec_group = NULL; + EC_KEY *ec_key = nullptr; + EC_POINT *ec_point_in = nullptr; + EC_POINT *ec_point_out = nullptr; + BIGNUM *ec_scalar = nullptr; + const EC_GROUP *ec_group = nullptr; // The 'k' value for ECDSA is fixed to avoid an entropy draw. uint8_t ecdsa_k[32] = {0}; ecdsa_k[31] = 42; ec_key = self_test_ecdsa_key(); - if (ec_key == NULL) { + if (ec_key == nullptr) { fprintf(CRYPTO_get_stderr(), "ECDSA KeyGen failed\n"); goto err; } @@ -429,8 +439,9 @@ static int boringssl_self_test_ecc(void) { kECDSASignDigest, sizeof(kECDSASignDigest), ecdsa_sign_output, &ecdsa_sign_output_len, sizeof(ecdsa_sign_output), ec_key, ecdsa_k, sizeof(ecdsa_k)) || - !check_test(kECDSASignSig, ecdsa_sign_output, sizeof(ecdsa_sign_output), - "ECDSA-sign signature")) { + !BORINGSSL_check_test(kECDSASignSig, + Span(ecdsa_sign_output, ecdsa_sign_output_len), + "ECDSA-sign signature")) { fprintf(CRYPTO_get_stderr(), "ECDSA-sign KAT failed.\n"); goto err; } @@ -473,7 +484,7 @@ static int boringssl_self_test_ecc(void) { 0xa5, 0x2c, 0xb5, 0x9f, 0xeb, 0x70, 0xae, 0xde, 0x6c, 0xe3, 0xbf, 0xb3, 0xe0, 0x10, 0x54, 0x85, 0xab, 0xd8, 0x61, 0xd7, 0x7b, }; - // kP256PointResult is |kP256Scalar|×|kP256Point|. + // kP256PointResult is `kP256Scalar`×`kP256Point`. static const uint8_t kP256PointResult[65] = { 0x04, 0xf1, 0x63, 0x00, 0x88, 0xc5, 0xd5, 0xe9, 0x05, 0x52, 0xac, 0xb6, 0xec, 0x68, 0x76, 0xb8, 0x73, 0x7f, 0x0f, 0x72, 0x34, 0xe6, @@ -488,16 +499,18 @@ static int boringssl_self_test_ecc(void) { ec_point_out = EC_POINT_new(ec_group); ec_scalar = BN_new(); uint8_t z_comp_result[65]; - if (ec_point_in == NULL || ec_point_out == NULL || ec_scalar == NULL || + if (ec_point_in == nullptr || ec_point_out == nullptr || + ec_scalar == nullptr || !EC_POINT_oct2point(ec_group, ec_point_in, kP256Point, sizeof(kP256Point), - NULL) || + nullptr) || !BN_bin2bn(kP256Scalar, sizeof(kP256Scalar), ec_scalar) || - !ec_point_mul_no_self_test(ec_group, ec_point_out, NULL, ec_point_in, - ec_scalar, NULL) || - !EC_POINT_point2oct(ec_group, ec_point_out, POINT_CONVERSION_UNCOMPRESSED, - z_comp_result, sizeof(z_comp_result), NULL) || - !check_test(kP256PointResult, z_comp_result, sizeof(z_comp_result), - "Z Computation Result")) { + !ec_point_mul_no_self_test(ec_group, ec_point_out, nullptr, ec_point_in, + ec_scalar, nullptr) || + EC_POINT_point2oct(ec_group, ec_point_out, POINT_CONVERSION_UNCOMPRESSED, + z_comp_result, sizeof(z_comp_result), + nullptr) != sizeof(z_comp_result) || + !BORINGSSL_check_test(kP256PointResult, z_comp_result, + "Z Computation Result")) { fprintf(CRYPTO_get_stderr(), "Z-computation KAT failed.\n"); goto err; } @@ -513,10 +526,10 @@ err: return ret; } -static int boringssl_self_test_ffdh(void) { +static int boringssl_self_test_ffdh() { int ret = 0; - DH *dh = NULL; - BIGNUM *ffdhe2048_value = NULL; + DH *dh = nullptr; + BIGNUM *ffdhe2048_value = nullptr; // FFC Diffie-Hellman KAT @@ -568,15 +581,16 @@ static int boringssl_self_test_ffdh(void) { ffdhe2048_value = BN_new(); if (ffdhe2048_value) { bn_set_static_words(ffdhe2048_value, kFFDHE2048PublicValueData, - OPENSSL_ARRAY_SIZE(kFFDHE2048PublicValueData)); + std::size(kFFDHE2048PublicValueData)); } dh = self_test_dh(); uint8_t dh_out[sizeof(kDHOutput)]; - if (dh == NULL || ffdhe2048_value == NULL || sizeof(dh_out) != DH_size(dh) || + if (dh == nullptr || ffdhe2048_value == nullptr || + sizeof(dh_out) != DH_size(dh) || dh_compute_key_padded_no_self_test(dh_out, ffdhe2048_value, dh) != sizeof(dh_out) || - !check_test(kDHOutput, dh_out, sizeof(dh_out), "FFC DH")) { + !BORINGSSL_check_test(kDHOutput, dh_out, "FFC DH")) { fprintf(CRYPTO_get_stderr(), "FFDH failed.\n"); goto err; } @@ -592,21 +606,35 @@ err: #if defined(BORINGSSL_FIPS) -static void run_self_test_rsa(void) { +static void run_self_test_rsa_sign() { FIPS_service_indicator_lock_state(); - if (!boringssl_self_test_rsa()) { + if (!boringssl_self_test_rsa_sign()) { BORINGSSL_FIPS_abort(); } FIPS_service_indicator_unlock_state(); } -DEFINE_STATIC_ONCE(g_self_test_once_rsa) +DEFINE_STATIC_ONCE(g_self_test_once_rsa_sign) -void boringssl_ensure_rsa_self_test(void) { - CRYPTO_once(g_self_test_once_rsa_bss_get(), run_self_test_rsa); +void bssl::boringssl_ensure_rsa_sign_self_test() { + CRYPTO_once(g_self_test_once_rsa_sign_bss_get(), run_self_test_rsa_sign); } -static void run_self_test_ecc(void) { +static void run_self_test_rsa_verify() { + FIPS_service_indicator_lock_state(); + if (!boringssl_self_test_rsa_verify()) { + BORINGSSL_FIPS_abort(); + } + FIPS_service_indicator_unlock_state(); +} + +DEFINE_STATIC_ONCE(g_self_test_once_rsa_verify) + +void bssl::boringssl_ensure_rsa_verify_self_test() { + CRYPTO_once(g_self_test_once_rsa_verify_bss_get(), run_self_test_rsa_verify); +} + +static void run_self_test_ecc() { FIPS_service_indicator_lock_state(); if (!boringssl_self_test_ecc()) { BORINGSSL_FIPS_abort(); @@ -616,11 +644,11 @@ static void run_self_test_ecc(void) { DEFINE_STATIC_ONCE(g_self_test_once_ecc) -void boringssl_ensure_ecc_self_test(void) { +void bssl::boringssl_ensure_ecc_self_test() { CRYPTO_once(g_self_test_once_ecc_bss_get(), run_self_test_ecc); } -static void run_self_test_ffdh(void) { +static void run_self_test_ffdh() { FIPS_service_indicator_lock_state(); if (!boringssl_self_test_ffdh()) { BORINGSSL_FIPS_abort(); @@ -630,7 +658,7 @@ static void run_self_test_ffdh(void) { DEFINE_STATIC_ONCE(g_self_test_once_ffdh) -void boringssl_ensure_ffdh_self_test(void) { +void bssl::boringssl_ensure_ffdh_self_test() { CRYPTO_once(g_self_test_once_ffdh_bss_get(), run_self_test_ffdh); } @@ -641,7 +669,7 @@ void boringssl_ensure_ffdh_self_test(void) { // // These tests are run at process start when in FIPS mode. -int boringssl_self_test_sha256(void) { +int bssl::boringssl_self_test_sha256() { static const uint8_t kInput[16] = { 0xff, 0x3b, 0x85, 0x7d, 0xa7, 0x23, 0x6a, 0x2b, 0xaa, 0x0f, 0x39, 0x6b, 0x51, 0x52, 0x22, 0x17, @@ -655,11 +683,10 @@ int boringssl_self_test_sha256(void) { // SHA-256 KAT SHA256(kInput, sizeof(kInput), output); - return check_test(kPlaintextSHA256, output, sizeof(kPlaintextSHA256), - "SHA-256 KAT"); + return BORINGSSL_check_test(kPlaintextSHA256, output, "SHA-256 KAT"); } -int boringssl_self_test_sha512(void) { +int bssl::boringssl_self_test_sha512() { static const uint8_t kInput[16] = { 0x21, 0x25, 0x12, 0xf8, 0xd2, 0xad, 0x83, 0x22, 0x78, 0x1c, 0x6c, 0x4d, 0x69, 0xa9, 0xda, 0xa1, @@ -676,11 +703,10 @@ int boringssl_self_test_sha512(void) { // SHA-512 KAT SHA512(kInput, sizeof(kInput), output); - return check_test(kPlaintextSHA512, output, sizeof(kPlaintextSHA512), - "SHA-512 KAT"); + return BORINGSSL_check_test(kPlaintextSHA512, output, "SHA-512 KAT"); } -int boringssl_self_test_hmac_sha256(void) { +int bssl::boringssl_self_test_hmac_sha256() { static const uint8_t kInput[16] = { 0xda, 0xd9, 0x12, 0x93, 0xdf, 0xcf, 0x2a, 0x7c, 0x8e, 0xcd, 0x13, 0xfe, 0x35, 0x3f, 0xa7, 0x5b, @@ -693,342 +719,369 @@ int boringssl_self_test_hmac_sha256(void) { uint8_t output[EVP_MAX_MD_SIZE]; unsigned output_len; - HMAC(EVP_sha256(), kInput, sizeof(kInput), kInput, sizeof(kInput), output, - &output_len); - return output_len == sizeof(kPlaintextHMACSHA256) && - check_test(kPlaintextHMACSHA256, output, sizeof(kPlaintextHMACSHA256), - "HMAC-SHA-256 KAT"); + return nullptr != HMAC(EVP_sha256(), kInput, sizeof(kInput), kInput, + sizeof(kInput), output, &output_len) && + BORINGSSL_check_test(kPlaintextHMACSHA256, Span(output, output_len), + "HMAC-SHA-256 KAT"); } -static int boringssl_self_test_fast(void) { +static int boringssl_self_test_fast() { static const uint8_t kAESKey[16] = { 'B', 'o', 'r', 'i', 'n', 'g', 'C', 'r', 'y', 'p', 't', 'o', ' ', 'K', 'e', 'y', }; - static const uint8_t kAESIV[16] = {0}; - EVP_AEAD_CTX aead_ctx; - EVP_AEAD_CTX_zero(&aead_ctx); - int ret = 0; - - AES_KEY aes_key; - uint8_t aes_iv[16]; - uint8_t output[256]; - - // AES-CBC Encryption KAT - static const uint8_t kAESCBCEncPlaintext[32] = { - 0x07, 0x86, 0x09, 0xa6, 0xc5, 0xac, 0x25, 0x44, 0x69, 0x9a, 0xdf, - 0x68, 0x2f, 0xa3, 0x77, 0xf9, 0xbe, 0x8a, 0xb6, 0xae, 0xf5, 0x63, - 0xe8, 0xc5, 0x6a, 0x36, 0xb8, 0x4f, 0x55, 0x7f, 0xad, 0xd3, - }; - static const uint8_t kAESCBCEncCiphertext[sizeof(kAESCBCEncPlaintext)] = { - 0x56, 0x46, 0xc1, 0x41, 0xf4, 0x13, 0xd6, 0xff, 0x62, 0x92, 0x41, - 0x7a, 0x26, 0xc6, 0x86, 0xbd, 0x30, 0x5f, 0xb6, 0x57, 0xa7, 0xd2, - 0x50, 0x3a, 0xc5, 0x5e, 0x8e, 0x93, 0x40, 0xf2, 0x10, 0xd8, - }; - memcpy(aes_iv, kAESIV, sizeof(kAESIV)); - if (AES_set_encrypt_key(kAESKey, 8 * sizeof(kAESKey), &aes_key) != 0) { - fprintf(CRYPTO_get_stderr(), "AES_set_encrypt_key failed.\n"); - goto err; - } - AES_cbc_encrypt(kAESCBCEncPlaintext, output, sizeof(kAESCBCEncPlaintext), - &aes_key, aes_iv, AES_ENCRYPT); - if (!check_test(kAESCBCEncCiphertext, output, sizeof(kAESCBCEncCiphertext), - "AES-CBC-encrypt KAT")) { - goto err; + { + // AES-CBC Encryption KAT + static const uint8_t kAESCBCEncPlaintext[32] = { + 0x07, 0x86, 0x09, 0xa6, 0xc5, 0xac, 0x25, 0x44, 0x69, 0x9a, 0xdf, + 0x68, 0x2f, 0xa3, 0x77, 0xf9, 0xbe, 0x8a, 0xb6, 0xae, 0xf5, 0x63, + 0xe8, 0xc5, 0x6a, 0x36, 0xb8, 0x4f, 0x55, 0x7f, 0xad, 0xd3, + }; + static const uint8_t kAESCBCEncCiphertext[sizeof(kAESCBCEncPlaintext)] = { + 0x56, 0x46, 0xc1, 0x41, 0xf4, 0x13, 0xd6, 0xff, 0x62, 0x92, 0x41, + 0x7a, 0x26, 0xc6, 0x86, 0xbd, 0x30, 0x5f, 0xb6, 0x57, 0xa7, 0xd2, + 0x50, 0x3a, 0xc5, 0x5e, 0x8e, 0x93, 0x40, 0xf2, 0x10, 0xd8, + }; + AES_KEY aes_key; + if (!bcm_success( + BCM_aes_set_encrypt_key(kAESKey, 8 * sizeof(kAESKey), &aes_key))) { + fprintf(CRYPTO_get_stderr(), "BCM_aes_set_encrypt_key failed.\n"); + return 0; + } + uint8_t aes_iv[16] = {}; + uint8_t output[sizeof(kAESCBCEncPlaintext)]; + AES_cbc_encrypt(kAESCBCEncPlaintext, output, sizeof(kAESCBCEncPlaintext), + &aes_key, aes_iv, AES_ENCRYPT); + if (!BORINGSSL_check_test(kAESCBCEncCiphertext, output, + "AES-CBC-encrypt KAT")) { + return 0; + } } - // AES-CBC Decryption KAT - static const uint8_t kAESCBCDecCiphertext[32] = { - 0x34, 0x7a, 0xa5, 0xa0, 0x24, 0xb2, 0x82, 0x57, 0xb3, 0x65, 0x10, - 0xbe, 0x58, 0x3d, 0x4f, 0x47, 0xad, 0xb7, 0xbb, 0xee, 0xdc, 0x60, - 0x05, 0xbb, 0xbd, 0x0d, 0x0a, 0x9f, 0x06, 0xbb, 0x7b, 0x10, - }; - static const uint8_t kAESCBCDecPlaintext[sizeof(kAESCBCDecCiphertext)] = { - 0x51, 0xa7, 0xa0, 0x1f, 0x6b, 0x79, 0x6c, 0xcd, 0x48, 0x03, 0xa1, - 0x41, 0xdc, 0x56, 0xa6, 0xc2, 0x16, 0xb5, 0xd1, 0xd3, 0xb7, 0x06, - 0xb2, 0x25, 0x6f, 0xa6, 0xd0, 0xd2, 0x0e, 0x6f, 0x19, 0xb5, - }; - memcpy(aes_iv, kAESIV, sizeof(kAESIV)); - if (AES_set_decrypt_key(kAESKey, 8 * sizeof(kAESKey), &aes_key) != 0) { - fprintf(CRYPTO_get_stderr(), "AES_set_decrypt_key failed.\n"); - goto err; - } - AES_cbc_encrypt(kAESCBCDecCiphertext, output, sizeof(kAESCBCDecCiphertext), - &aes_key, aes_iv, AES_DECRYPT); - if (!check_test(kAESCBCDecPlaintext, output, sizeof(kAESCBCDecPlaintext), - "AES-CBC-decrypt KAT")) { - goto err; + { + // AES-CBC Decryption KAT + static const uint8_t kAESCBCDecCiphertext[32] = { + 0x34, 0x7a, 0xa5, 0xa0, 0x24, 0xb2, 0x82, 0x57, 0xb3, 0x65, 0x10, + 0xbe, 0x58, 0x3d, 0x4f, 0x47, 0xad, 0xb7, 0xbb, 0xee, 0xdc, 0x60, + 0x05, 0xbb, 0xbd, 0x0d, 0x0a, 0x9f, 0x06, 0xbb, 0x7b, 0x10, + }; + static const uint8_t kAESCBCDecPlaintext[sizeof(kAESCBCDecCiphertext)] = { + 0x51, 0xa7, 0xa0, 0x1f, 0x6b, 0x79, 0x6c, 0xcd, 0x48, 0x03, 0xa1, + 0x41, 0xdc, 0x56, 0xa6, 0xc2, 0x16, 0xb5, 0xd1, 0xd3, 0xb7, 0x06, + 0xb2, 0x25, 0x6f, 0xa6, 0xd0, 0xd2, 0x0e, 0x6f, 0x19, 0xb5, + }; + AES_KEY aes_key; + if (!bcm_success( + BCM_aes_set_decrypt_key(kAESKey, 8 * sizeof(kAESKey), &aes_key))) { + fprintf(CRYPTO_get_stderr(), "BCM_aes_set_decrypt_key failed.\n"); + return 0; + } + uint8_t aes_iv[16] = {}; + uint8_t output[sizeof(kAESCBCDecCiphertext)]; + AES_cbc_encrypt(kAESCBCDecCiphertext, output, sizeof(kAESCBCDecCiphertext), + &aes_key, aes_iv, AES_DECRYPT); + if (!BORINGSSL_check_test(kAESCBCDecPlaintext, output, + "AES-CBC-decrypt KAT")) { + return 0; + } } - size_t out_len; - uint8_t nonce[EVP_AEAD_MAX_NONCE_LENGTH]; - OPENSSL_memset(nonce, 0, sizeof(nonce)); - if (!EVP_AEAD_CTX_init(&aead_ctx, EVP_aead_aes_128_gcm(), kAESKey, - sizeof(kAESKey), 0, NULL)) { - fprintf(CRYPTO_get_stderr(), "EVP_AEAD_CTX_init for AES-128-GCM failed.\n"); - goto err; + { + size_t out_len; + ScopedEVP_AEAD_CTX aead_ctx; + if (!EVP_AEAD_CTX_init(aead_ctx.get(), EVP_aead_aes_128_gcm(), kAESKey, + sizeof(kAESKey), 0, nullptr)) { + fprintf(CRYPTO_get_stderr(), + "EVP_AEAD_CTX_init for AES-128-GCM failed.\n"); + return 0; + } + + // AES-GCM Encryption KAT + static const uint8_t kAESGCMEncPlaintext[32] = { + 0x8f, 0xcc, 0x40, 0x99, 0x80, 0x8e, 0x75, 0xca, 0xaf, 0xf5, 0x82, + 0x89, 0x88, 0x48, 0xa8, 0x8d, 0x80, 0x8b, 0x55, 0xab, 0x4e, 0x93, + 0x70, 0x79, 0x7d, 0x94, 0x0b, 0xe8, 0xcc, 0x1d, 0x78, 0x84, + }; + static const uint8_t kAESGCMCiphertext[sizeof(kAESGCMEncPlaintext) + 16] = { + 0x87, 0x7b, 0xd5, 0x8d, 0x96, 0x3e, 0x4b, 0xe6, 0x64, 0x94, 0x40, 0x2f, + 0x61, 0x9b, 0x7e, 0x56, 0x52, 0x7d, 0xa4, 0x5a, 0xf9, 0xa6, 0xe2, 0xdb, + 0x1c, 0x63, 0x2e, 0x97, 0x93, 0x0f, 0xfb, 0xed, 0xb5, 0x9e, 0x1c, 0x20, + 0xb2, 0xb0, 0x58, 0xda, 0x48, 0x07, 0x2d, 0xbd, 0x96, 0x0d, 0x34, 0xc6, + }; + uint8_t nonce[12] = {}; + uint8_t output[sizeof(kAESGCMCiphertext)]; + if (!EVP_AEAD_CTX_seal(aead_ctx.get(), output, &out_len, sizeof(output), + nonce, sizeof(nonce), kAESGCMEncPlaintext, + sizeof(kAESGCMEncPlaintext), nullptr, 0) || + !BORINGSSL_check_test(kAESGCMCiphertext, Span(output, out_len), + "AES-GCM-encrypt KAT")) { + fprintf(CRYPTO_get_stderr(), + "EVP_AEAD_CTX_seal for AES-128-GCM failed.\n"); + return 0; + } + + // AES-GCM Decryption KAT + static const uint8_t kAESGCMDecCiphertext[48] = { + 0x35, 0xf3, 0x05, 0x8f, 0x87, 0x57, 0x60, 0xff, 0x09, 0xd3, 0x12, 0x0f, + 0x70, 0xc4, 0xbc, 0x9e, 0xd7, 0xa8, 0x68, 0x72, 0xe1, 0x34, 0x52, 0x20, + 0x21, 0x76, 0xf7, 0x37, 0x1a, 0xe0, 0x4f, 0xaa, 0xe1, 0xdd, 0x39, 0x19, + 0x20, 0xf5, 0xd1, 0x39, 0x53, 0xd8, 0x96, 0x78, 0x59, 0x94, 0x82, 0x3c, + }; + static const uint8_t + kAESGCMDecPlaintext[sizeof(kAESGCMDecCiphertext) - 16] = { + 0x3d, 0x44, 0x90, 0x9b, 0x91, 0xe7, 0x5e, 0xd3, 0xc2, 0xb2, 0xd0, + 0xa9, 0x99, 0x17, 0x6a, 0x45, 0x05, 0x5e, 0x99, 0x83, 0x56, 0x01, + 0xc0, 0x82, 0x40, 0x81, 0xd2, 0x48, 0x45, 0xf2, 0xcc, 0xc3, + }; + if (!EVP_AEAD_CTX_open(aead_ctx.get(), output, &out_len, sizeof(output), + nonce, sizeof(nonce), + kAESGCMDecCiphertext, sizeof(kAESGCMDecCiphertext), + nullptr, 0) || + !BORINGSSL_check_test(kAESGCMDecPlaintext, Span(output, out_len), + "AES-GCM-decrypt KAT")) { + fprintf(CRYPTO_get_stderr(), + "AES-GCM-decrypt KAT failed because EVP_AEAD_CTX_open failed.\n"); + return 0; + } } - // AES-GCM Encryption KAT - static const uint8_t kAESGCMEncPlaintext[32] = { - 0x8f, 0xcc, 0x40, 0x99, 0x80, 0x8e, 0x75, 0xca, 0xaf, 0xf5, 0x82, - 0x89, 0x88, 0x48, 0xa8, 0x8d, 0x80, 0x8b, 0x55, 0xab, 0x4e, 0x93, - 0x70, 0x79, 0x7d, 0x94, 0x0b, 0xe8, 0xcc, 0x1d, 0x78, 0x84, - }; - static const uint8_t kAESGCMCiphertext[sizeof(kAESGCMEncPlaintext) + 16] = { - 0x87, 0x7b, 0xd5, 0x8d, 0x96, 0x3e, 0x4b, 0xe6, 0x64, 0x94, 0x40, 0x2f, - 0x61, 0x9b, 0x7e, 0x56, 0x52, 0x7d, 0xa4, 0x5a, 0xf9, 0xa6, 0xe2, 0xdb, - 0x1c, 0x63, 0x2e, 0x97, 0x93, 0x0f, 0xfb, 0xed, 0xb5, 0x9e, 0x1c, 0x20, - 0xb2, 0xb0, 0x58, 0xda, 0x48, 0x07, 0x2d, 0xbd, 0x96, 0x0d, 0x34, 0xc6, - }; - if (!EVP_AEAD_CTX_seal(&aead_ctx, output, &out_len, sizeof(output), nonce, - EVP_AEAD_nonce_length(EVP_aead_aes_128_gcm()), - kAESGCMEncPlaintext, sizeof(kAESGCMEncPlaintext), NULL, - 0) || - !check_test(kAESGCMCiphertext, output, sizeof(kAESGCMCiphertext), - "AES-GCM-encrypt KAT")) { - fprintf(CRYPTO_get_stderr(), "EVP_AEAD_CTX_seal for AES-128-GCM failed.\n"); - goto err; + { + // SHA-1 KAT + static const uint8_t kSHA1Input[16] = { + 0x13, 0x2f, 0xd9, 0xba, 0xd5, 0xc1, 0x82, 0x62, + 0x63, 0xba, 0xfb, 0xb6, 0x99, 0xf7, 0x07, 0xa5, + }; + static const uint8_t kSHA1Digest[20] = { + 0x94, 0x19, 0x55, 0x93, 0x0a, 0x58, 0x29, 0x38, 0xeb, 0xf5, + 0x09, 0x11, 0x6d, 0x1a, 0xfd, 0x0f, 0x1e, 0x11, 0xe3, 0xcb, + }; + uint8_t output[SHA_DIGEST_LENGTH]; + SHA1(kSHA1Input, sizeof(kSHA1Input), output); + if (!BORINGSSL_check_test(kSHA1Digest, output, "SHA-1 KAT")) { + return 0; + } } - // AES-GCM Decryption KAT - static const uint8_t kAESGCMDecCiphertext[48] = { - 0x35, 0xf3, 0x05, 0x8f, 0x87, 0x57, 0x60, 0xff, 0x09, 0xd3, 0x12, 0x0f, - 0x70, 0xc4, 0xbc, 0x9e, 0xd7, 0xa8, 0x68, 0x72, 0xe1, 0x34, 0x52, 0x20, - 0x21, 0x76, 0xf7, 0x37, 0x1a, 0xe0, 0x4f, 0xaa, 0xe1, 0xdd, 0x39, 0x19, - 0x20, 0xf5, 0xd1, 0x39, 0x53, 0xd8, 0x96, 0x78, 0x59, 0x94, 0x82, 0x3c, - }; - static const uint8_t kAESGCMDecPlaintext[sizeof(kAESGCMDecCiphertext) - 16] = - { - 0x3d, 0x44, 0x90, 0x9b, 0x91, 0xe7, 0x5e, 0xd3, 0xc2, 0xb2, 0xd0, - 0xa9, 0x99, 0x17, 0x6a, 0x45, 0x05, 0x5e, 0x99, 0x83, 0x56, 0x01, - 0xc0, 0x82, 0x40, 0x81, 0xd2, 0x48, 0x45, 0xf2, 0xcc, 0xc3, - }; - if (!EVP_AEAD_CTX_open(&aead_ctx, output, &out_len, sizeof(output), nonce, - EVP_AEAD_nonce_length(EVP_aead_aes_128_gcm()), - kAESGCMDecCiphertext, sizeof(kAESGCMDecCiphertext), - NULL, 0) || - !check_test(kAESGCMDecPlaintext, output, sizeof(kAESGCMDecPlaintext), - "AES-GCM-decrypt KAT")) { - fprintf(CRYPTO_get_stderr(), - "AES-GCM-decrypt KAT failed because EVP_AEAD_CTX_open failed.\n"); - goto err; - } - - // SHA-1 KAT - static const uint8_t kSHA1Input[16] = { - 0x13, 0x2f, 0xd9, 0xba, 0xd5, 0xc1, 0x82, 0x62, - 0x63, 0xba, 0xfb, 0xb6, 0x99, 0xf7, 0x07, 0xa5, - }; - static const uint8_t kSHA1Digest[20] = { - 0x94, 0x19, 0x55, 0x93, 0x0a, 0x58, 0x29, 0x38, 0xeb, 0xf5, - 0x09, 0x11, 0x6d, 0x1a, 0xfd, 0x0f, 0x1e, 0x11, 0xe3, 0xcb, - }; - SHA1(kSHA1Input, sizeof(kSHA1Input), output); - if (!check_test(kSHA1Digest, output, sizeof(kSHA1Digest), "SHA-1 KAT")) { - goto err; - } - - if (!boringssl_self_test_sha256() || !boringssl_self_test_sha512() || + if (!boringssl_self_test_sha256() || // + !boringssl_self_test_sha512() || // !boringssl_self_test_hmac_sha256()) { - goto err; + return 0; } - // DBRG KAT - static const uint8_t kDRBGEntropy[48] = { - 0xc4, 0xda, 0x07, 0x40, 0xd5, 0x05, 0xf1, 0xee, 0x28, 0x0b, 0x95, 0xe5, - 0x8c, 0x49, 0x31, 0xac, 0x6d, 0xe8, 0x46, 0xa0, 0x15, 0x2f, 0xbb, 0x4a, - 0x3f, 0x17, 0x4c, 0xf4, 0x78, 0x7a, 0x4f, 0x1a, 0x40, 0xc2, 0xb5, 0x0b, - 0xab, 0xe1, 0x4a, 0xae, 0x53, 0x0b, 0xe5, 0x88, 0x6d, 0x91, 0x0a, 0x27, - }; - static const uint8_t kDRBGPersonalization[18] = { - 'B', 'C', 'M', 'P', 'e', 'r', 's', 'o', 'n', - 'a', 'l', 'i', 'z', 'a', 't', 'i', 'o', 'n'}; - static const uint8_t kDRBGAD[16] = {'B', 'C', 'M', ' ', 'D', 'R', 'B', 'G', - ' ', 'K', 'A', 'T', ' ', 'A', 'D', ' '}; - static const uint8_t kDRBGOutput[64] = { - 0x19, 0x1f, 0x2b, 0x49, 0x76, 0x85, 0xfd, 0x51, 0xb6, 0x56, 0xbc, - 0x1c, 0x7d, 0xd5, 0xdd, 0x44, 0x76, 0xa3, 0x5e, 0x17, 0x9b, 0x8e, - 0xb8, 0x98, 0x65, 0x12, 0xca, 0x35, 0x6c, 0xa0, 0x6f, 0xa0, 0x22, - 0xe4, 0xf6, 0xd8, 0x43, 0xed, 0x4e, 0x2d, 0x97, 0x39, 0x43, 0x3b, - 0x57, 0xfc, 0x23, 0x3f, 0x71, 0x0a, 0xe0, 0xed, 0xfe, 0xd5, 0xb8, - 0x67, 0x7a, 0x00, 0x39, 0xb2, 0x6e, 0xa9, 0x25, 0x97, - }; - static const uint8_t kDRBGEntropy2[48] = { - 0xc7, 0x16, 0x1c, 0xa3, 0x6c, 0x23, 0x09, 0xb7, 0x16, 0xe9, 0x85, 0x9b, - 0xb9, 0x6c, 0x6d, 0x49, 0xbd, 0xc8, 0x35, 0x21, 0x03, 0xa1, 0x8c, 0xd2, - 0x4e, 0xf4, 0x2e, 0xc9, 0x7e, 0xf4, 0x6b, 0xf4, 0x46, 0xeb, 0x1a, 0x45, - 0x76, 0xc1, 0x86, 0xe9, 0x35, 0x18, 0x03, 0x76, 0x3a, 0x79, 0x12, 0xfe, - }; - static const uint8_t kDRBGReseedOutput[64] = { - 0x00, 0xf2, 0x05, 0xaa, 0xfd, 0x11, 0x6c, 0x77, 0xbc, 0x81, 0x86, - 0x99, 0xca, 0x51, 0xcf, 0x80, 0x15, 0x9f, 0x02, 0x9e, 0x0b, 0xcd, - 0x26, 0xc8, 0x4b, 0x87, 0x8a, 0x15, 0x1a, 0xdd, 0xf2, 0xf3, 0xeb, - 0x94, 0x0b, 0x08, 0xc8, 0xc9, 0x57, 0xa4, 0x0b, 0x4b, 0x0f, 0x13, - 0xde, 0x7c, 0x0c, 0x6a, 0xac, 0x34, 0x4a, 0x9a, 0xf2, 0xd0, 0x83, - 0x02, 0x05, 0x17, 0xc9, 0x81, 0x8f, 0x2a, 0x81, 0x92, - }; - CTR_DRBG_STATE drbg; - if (!CTR_DRBG_init(&drbg, kDRBGEntropy, kDRBGPersonalization, - sizeof(kDRBGPersonalization)) || - !CTR_DRBG_generate(&drbg, output, sizeof(kDRBGOutput), kDRBGAD, - sizeof(kDRBGAD)) || - !check_test(kDRBGOutput, output, sizeof(kDRBGOutput), - "DRBG Generate KAT") || - !CTR_DRBG_reseed(&drbg, kDRBGEntropy2, kDRBGAD, sizeof(kDRBGAD)) || - !CTR_DRBG_generate(&drbg, output, sizeof(kDRBGReseedOutput), kDRBGAD, - sizeof(kDRBGAD)) || - !check_test(kDRBGReseedOutput, output, sizeof(kDRBGReseedOutput), - "DRBG-reseed KAT")) { - fprintf(CRYPTO_get_stderr(), "CTR-DRBG failed.\n"); - goto err; - } - CTR_DRBG_clear(&drbg); + { + // DBRG KAT + static const uint8_t kDRBGEntropy[32] = { + 0xc4, 0xda, 0x07, 0x40, 0xd5, 0x05, 0xf1, 0xee, 0x28, 0x0b, 0x95, + 0xe5, 0x8c, 0x49, 0x31, 0xac, 0x6d, 0xe8, 0x46, 0xa0, 0x15, 0x2f, + 0xbb, 0x4a, 0x3f, 0x17, 0x4c, 0xf4, 0x78, 0x7a, 0x4f, 0x1a, + }; + static const uint8_t kDRBGNonce[CTR_DRBG_NONCE_LEN] = { + 0x40, 0xc2, 0xb5, 0x0b, 0xab, 0xe1, 0x4a, 0xae, + 0x53, 0x0b, 0xe5, 0x88, 0x6d, 0x91, 0x0a, 0x27, + }; + static const uint8_t kDRBGPersonalization[18] = { + 'B', 'C', 'M', 'P', 'e', 'r', 's', 'o', 'n', + 'a', 'l', 'i', 'z', 'a', 't', 'i', 'o', 'n'}; + static const uint8_t kDRBGAD[16] = {'B', 'C', 'M', ' ', 'D', 'R', 'B', 'G', + ' ', 'K', 'A', 'T', ' ', 'A', 'D', ' '}; + static const uint8_t kDRBGOutput[64] = { + 0x55, 0x88, 0x81, 0x88, 0x16, 0x49, 0x68, 0xd8, 0x23, 0xc8, 0x18, + 0x57, 0x5d, 0x06, 0xc3, 0x5f, 0x60, 0x3a, 0xe8, 0xfe, 0x7c, 0x7e, + 0x1c, 0x4a, 0x6a, 0xa8, 0x91, 0x07, 0xc0, 0x0d, 0x1f, 0x70, 0x4a, + 0xbb, 0x20, 0x42, 0xd3, 0x3f, 0x19, 0xf1, 0xb1, 0xfc, 0xef, 0xa1, + 0x71, 0xfd, 0xf7, 0xaf, 0xc5, 0x12, 0x7a, 0x98, 0xad, 0x42, 0xbc, + 0x01, 0xe6, 0xa2, 0x83, 0xbc, 0x73, 0xb5, 0xba, 0x84, + }; + static const uint8_t kDRBGEntropy2[48] = { + 0xc7, 0x16, 0x1c, 0xa3, 0x6c, 0x23, 0x09, 0xb7, 0x16, 0xe9, 0x85, 0x9b, + 0xb9, 0x6c, 0x6d, 0x49, 0xbd, 0xc8, 0x35, 0x21, 0x03, 0xa1, 0x8c, 0xd2, + 0x4e, 0xf4, 0x2e, 0xc9, 0x7e, 0xf4, 0x6b, 0xf4, 0x46, 0xeb, 0x1a, 0x45, + 0x76, 0xc1, 0x86, 0xe9, 0x35, 0x18, 0x03, 0x76, 0x3a, 0x79, 0x12, 0xfe, + }; + static const uint8_t kDRBGReseedOutput[64] = { + 0xda, 0x49, 0xa1, 0x01, 0x31, 0x71, 0x77, 0xde, 0xf6, 0x8d, 0xb5, + 0x4f, 0x86, 0x0d, 0xc8, 0xd6, 0x3c, 0xaa, 0xbc, 0x72, 0x0a, 0x9c, + 0x8b, 0x68, 0xa9, 0x70, 0xf1, 0x21, 0x13, 0xce, 0xc6, 0xbc, 0xff, + 0xaf, 0xa8, 0xd5, 0x26, 0x76, 0x26, 0xcc, 0x0d, 0x89, 0x66, 0xab, + 0xc2, 0x11, 0xa8, 0x2f, 0xf1, 0x36, 0xa3, 0x2b, 0x52, 0xcd, 0x1a, + 0x2d, 0xe4, 0x82, 0xac, 0x3c, 0xbb, 0xa9, 0x17, 0x90, + }; + CTR_DRBG_STATE drbg; + uint8_t output[64]; + if (!CTR_DRBG_init(&drbg, /*df=*/true, kDRBGEntropy, sizeof(kDRBGEntropy), + kDRBGNonce, kDRBGPersonalization, + sizeof(kDRBGPersonalization)) || + !CTR_DRBG_generate(&drbg, output, sizeof(output), kDRBGAD, + sizeof(kDRBGAD)) || + !BORINGSSL_check_test(kDRBGOutput, output, "DRBG Generate KAT") || + !CTR_DRBG_reseed_ex(&drbg, kDRBGEntropy2, sizeof(kDRBGEntropy2), + kDRBGAD, sizeof(kDRBGAD)) || + !CTR_DRBG_generate(&drbg, output, sizeof(output), kDRBGAD, + sizeof(kDRBGAD)) || + !BORINGSSL_check_test(kDRBGReseedOutput, output, "DRBG-reseed KAT")) { + fprintf(CRYPTO_get_stderr(), "CTR-DRBG failed.\n"); + return 0; + } + CTR_DRBG_clear(&drbg); - CTR_DRBG_STATE kZeroDRBG; - memset(&kZeroDRBG, 0, sizeof(kZeroDRBG)); - if (!check_test(&kZeroDRBG, &drbg, sizeof(drbg), "DRBG Clear KAT")) { - goto err; + uint8_t kZeroDRBG[sizeof(drbg)] = {}; + if (!BORINGSSL_check_test( + kZeroDRBG, + Span(reinterpret_cast(&drbg), sizeof(drbg)), + "DRBG Clear KAT")) { + return 0; + } } - // TLS KDF KAT - static const char kTLSLabel[] = "FIPS self test"; - static const uint8_t kTLSSeed1[16] = { - 0x8f, 0x0d, 0xe8, 0xb6, 0x90, 0x8f, 0xb1, 0xd2, - 0x6d, 0x51, 0xf4, 0x79, 0x18, 0x63, 0x51, 0x65, - }; - static const uint8_t kTLSSeed2[16] = { - 0x7d, 0x24, 0x1a, 0x9d, 0x3c, 0x59, 0xbf, 0x3c, - 0x31, 0x1e, 0x2b, 0x21, 0x41, 0x8d, 0x32, 0x81, - }; + { + // TLS KDF KAT + static const uint8_t kTLSLabel[] = "FIPS self test"; + static const uint8_t kTLSSeed1[16] = { + 0x8f, 0x0d, 0xe8, 0xb6, 0x90, 0x8f, 0xb1, 0xd2, + 0x6d, 0x51, 0xf4, 0x79, 0x18, 0x63, 0x51, 0x65, + }; + static const uint8_t kTLSSeed2[16] = { + 0x7d, 0x24, 0x1a, 0x9d, 0x3c, 0x59, 0xbf, 0x3c, + 0x31, 0x1e, 0x2b, 0x21, 0x41, 0x8d, 0x32, 0x81, + }; - static const uint8_t kTLS10Secret[32] = { - 0xab, 0xc3, 0x65, 0x7b, 0x09, 0x4c, 0x76, 0x28, 0xa0, 0xb2, 0x82, - 0x99, 0x6f, 0xe7, 0x5a, 0x75, 0xf4, 0x98, 0x4f, 0xd9, 0x4d, 0x4e, - 0xcc, 0x2f, 0xcf, 0x53, 0xa2, 0xc4, 0x69, 0xa3, 0xf7, 0x31, - }; - static const uint8_t kTLS10Output[32] = { - 0x69, 0x7c, 0x4e, 0x2c, 0xee, 0x82, 0xb1, 0xd2, 0x8b, 0xac, 0x90, - 0x7a, 0xa1, 0x8a, 0x81, 0xfe, 0xc5, 0x58, 0x45, 0x57, 0x61, 0x2f, - 0x7a, 0x8d, 0x80, 0xfb, 0x44, 0xd8, 0x81, 0x60, 0xe5, 0xf8, - }; - uint8_t tls10_output[sizeof(kTLS10Output)]; - if (!CRYPTO_tls1_prf(EVP_md5_sha1(), tls10_output, sizeof(tls10_output), - kTLS10Secret, sizeof(kTLS10Secret), kTLSLabel, - sizeof(kTLSLabel), kTLSSeed1, sizeof(kTLSSeed1), - kTLSSeed2, sizeof(kTLSSeed2)) || - !check_test(kTLS10Output, tls10_output, sizeof(kTLS10Output), - "TLS10-KDF KAT")) { - fprintf(CRYPTO_get_stderr(), "TLS KDF failed.\n"); - goto err; + static const uint8_t kTLS10Secret[32] = { + 0xab, 0xc3, 0x65, 0x7b, 0x09, 0x4c, 0x76, 0x28, 0xa0, 0xb2, 0x82, + 0x99, 0x6f, 0xe7, 0x5a, 0x75, 0xf4, 0x98, 0x4f, 0xd9, 0x4d, 0x4e, + 0xcc, 0x2f, 0xcf, 0x53, 0xa2, 0xc4, 0x69, 0xa3, 0xf7, 0x31, + }; + static const uint8_t kTLS10Output[32] = { + 0x69, 0x7c, 0x4e, 0x2c, 0xee, 0x82, 0xb1, 0xd2, 0x8b, 0xac, 0x90, + 0x7a, 0xa1, 0x8a, 0x81, 0xfe, 0xc5, 0x58, 0x45, 0x57, 0x61, 0x2f, + 0x7a, 0x8d, 0x80, 0xfb, 0x44, 0xd8, 0x81, 0x60, 0xe5, 0xf8, + }; + uint8_t tls10_output[sizeof(kTLS10Output)]; + // For this test, labels null-terminated + if (!CRYPTO_tls1_prf(EVP_md5_sha1(), tls10_output, sizeof(tls10_output), + kTLS10Secret, sizeof(kTLS10Secret), kTLSLabel, + sizeof(kTLSLabel), kTLSSeed1, sizeof(kTLSSeed1), + kTLSSeed2, sizeof(kTLSSeed2)) || + !BORINGSSL_check_test(kTLS10Output, tls10_output, "TLS10-KDF KAT")) { + fprintf(CRYPTO_get_stderr(), "TLS KDF failed.\n"); + return 0; + } + + static const uint8_t kTLS12Secret[32] = { + 0xc5, 0x43, 0x8e, 0xe2, 0x6f, 0xd4, 0xac, 0xbd, 0x25, 0x9f, 0xc9, + 0x18, 0x55, 0xdc, 0x69, 0xbf, 0x88, 0x4e, 0xe2, 0x93, 0x22, 0xfc, + 0xbf, 0xd2, 0x96, 0x6a, 0x46, 0x23, 0xd4, 0x2e, 0xc7, 0x81, + }; + static const uint8_t kTLS12Output[32] = { + 0xee, 0x4a, 0xcd, 0x3f, 0xa3, 0xd3, 0x55, 0x89, 0x9e, 0x6f, 0xf1, + 0x38, 0x46, 0x9d, 0x2b, 0x33, 0xaa, 0x7f, 0xc4, 0x7f, 0x51, 0x85, + 0x8a, 0xf3, 0x13, 0x84, 0xbf, 0x53, 0x6a, 0x65, 0x37, 0x51, + }; + uint8_t tls12_output[sizeof(kTLS12Output)]; + if (!CRYPTO_tls1_prf(EVP_sha256(), tls12_output, sizeof(tls12_output), + kTLS12Secret, sizeof(kTLS12Secret), kTLSLabel, + sizeof(kTLSLabel), kTLSSeed1, sizeof(kTLSSeed1), + kTLSSeed2, sizeof(kTLSSeed2)) || + !BORINGSSL_check_test(kTLS12Output, tls12_output, "TLS12-KDF KAT")) { + fprintf(CRYPTO_get_stderr(), "TLS KDF failed.\n"); + return 0; + } + + // TLS v1.3: derives a dummy client-early-traffic secret. + static const uint8_t kTLS13Secret[32] = { + 0x02, 0x4a, 0x0d, 0x80, 0xf3, 0x57, 0xf2, 0x49, 0x9a, 0x12, 0x44, + 0xda, 0xc2, 0x6d, 0xab, 0x66, 0xfc, 0x13, 0xed, 0x85, 0xfc, 0xa7, + 0x1d, 0xac, 0xe1, 0x46, 0x21, 0x11, 0x19, 0x52, 0x58, 0x74, + }; + static const uint8_t kTLS13Salt[16] = { + 0x54, 0x61, 0x11, 0x36, 0x75, 0x91, 0xf0, 0xf8, + 0x92, 0xec, 0x70, 0xbd, 0x78, 0x2a, 0xef, 0x61, + }; + static const uint8_t kTLS13Label[] = "c e traffic"; + static const uint8_t kTLS13ClientHelloHash[32] = { + 0x1d, 0xe8, 0x67, 0xed, 0x93, 0x6a, 0x73, 0x65, 0x9b, 0x05, 0xcf, + 0x8a, 0x22, 0x77, 0xb7, 0x37, 0x29, 0xf2, 0x44, 0x94, 0x81, 0x6a, + 0x83, 0x33, 0x7f, 0x09, 0xbb, 0x6c, 0xc2, 0x6f, 0x48, 0x9c, + }; + static const uint8_t kTLS13ExpandLabelOutput[32] = { + 0x62, 0x91, 0x52, 0x90, 0x2e, 0xc9, 0xcf, 0x9c, 0x5f, 0x1e, 0x0a, + 0xb7, 0x00, 0x33, 0x42, 0x24, 0xc4, 0xe3, 0xba, 0x01, 0x40, 0x32, + 0x06, 0xab, 0x09, 0x23, 0x8a, 0xdd, 0x01, 0xa4, 0x05, 0xcd, + }; + uint8_t tls13_extract_output[32]; + size_t tls13_extract_output_len; + uint8_t tls13_expand_label_output[32]; + if (!HKDF_extract(tls13_extract_output, &tls13_extract_output_len, + EVP_sha256(), kTLS13Secret, sizeof(kTLS13Secret), + kTLS13Salt, sizeof(kTLS13Salt)) || + tls13_extract_output_len != sizeof(tls13_extract_output) || + !CRYPTO_tls13_hkdf_expand_label( + tls13_expand_label_output, sizeof(tls13_expand_label_output), + EVP_sha256(), tls13_extract_output, sizeof(tls13_extract_output), + kTLS13Label, sizeof(kTLS13Label) - 1, kTLS13ClientHelloHash, + sizeof(kTLS13ClientHelloHash)) || + !BORINGSSL_check_test(kTLS13ExpandLabelOutput, + tls13_expand_label_output, + "CRYPTO_tls13_hkdf_expand_label")) { + fprintf(CRYPTO_get_stderr(), "TLS13-KDF failed.\n"); + return 0; + } } - static const uint8_t kTLS12Secret[32] = { - 0xc5, 0x43, 0x8e, 0xe2, 0x6f, 0xd4, 0xac, 0xbd, 0x25, 0x9f, 0xc9, - 0x18, 0x55, 0xdc, 0x69, 0xbf, 0x88, 0x4e, 0xe2, 0x93, 0x22, 0xfc, - 0xbf, 0xd2, 0x96, 0x6a, 0x46, 0x23, 0xd4, 0x2e, 0xc7, 0x81, - }; - static const uint8_t kTLS12Output[32] = { - 0xee, 0x4a, 0xcd, 0x3f, 0xa3, 0xd3, 0x55, 0x89, 0x9e, 0x6f, 0xf1, - 0x38, 0x46, 0x9d, 0x2b, 0x33, 0xaa, 0x7f, 0xc4, 0x7f, 0x51, 0x85, - 0x8a, 0xf3, 0x13, 0x84, 0xbf, 0x53, 0x6a, 0x65, 0x37, 0x51, - }; - uint8_t tls12_output[sizeof(kTLS12Output)]; - if (!CRYPTO_tls1_prf(EVP_sha256(), tls12_output, sizeof(tls12_output), - kTLS12Secret, sizeof(kTLS12Secret), kTLSLabel, - sizeof(kTLSLabel), kTLSSeed1, sizeof(kTLSSeed1), - kTLSSeed2, sizeof(kTLSSeed2)) || - !check_test(kTLS12Output, tls12_output, sizeof(kTLS12Output), - "TLS12-KDF KAT")) { - fprintf(CRYPTO_get_stderr(), "TLS KDF failed.\n"); - goto err; + { + // HKDF + static const uint8_t kHKDFSecret[32] = { + 0x68, 0x67, 0x85, 0x04, 0xb9, 0xb3, 0xad, 0xd1, 0x7d, 0x59, 0x67, + 0xa1, 0xa7, 0xbd, 0x37, 0x99, 0x3f, 0xd8, 0xa3, 0x3c, 0xe7, 0x30, + 0x30, 0x71, 0xf3, 0x9c, 0x09, 0x6d, 0x16, 0x35, 0xb3, 0xc9, + }; + static const uint8_t kHKDFSalt[32] = { + 0x8a, 0xab, 0x18, 0xb4, 0x9b, 0x0a, 0x17, 0xf9, 0xe8, 0xe6, 0x97, + 0x1a, 0x3d, 0xff, 0xda, 0x9b, 0x26, 0x8b, 0x3d, 0x17, 0x78, 0x0a, + 0xb3, 0xea, 0x65, 0xdb, 0x2a, 0xc0, 0x29, 0x9c, 0xfa, 0x72, + }; + static const uint8_t kHKDFInfo[32] = { + 0xe5, 0x6f, 0xf9, 0xe1, 0x18, 0x5e, 0x64, 0x8c, 0x6c, 0x8f, 0xee, + 0xc6, 0x93, 0x5a, 0xc5, 0x14, 0x8c, 0xf3, 0xd9, 0x78, 0xd2, 0x3a, + 0x86, 0xdd, 0x01, 0xdf, 0xb9, 0xe9, 0x5e, 0xe5, 0x1a, 0x56, + }; + static const uint8_t kHKDFOutput[32] = { + 0xa6, 0x29, 0xb4, 0xd7, 0xf4, 0xc1, 0x16, 0x64, 0x71, 0x5e, 0xa4, + 0xa8, 0xe6, 0x60, 0x8c, 0xf3, 0xc1, 0xa5, 0x03, 0xe2, 0x22, 0xf9, + 0x89, 0xe2, 0x12, 0x18, 0xbe, 0xef, 0x16, 0x86, 0xe0, 0xec, + }; + uint8_t hkdf_output[sizeof(kHKDFOutput)]; + if (!HKDF(hkdf_output, sizeof(hkdf_output), EVP_sha256(), kHKDFSecret, + sizeof(kHKDFSecret), kHKDFSalt, sizeof(kHKDFSalt), kHKDFInfo, + sizeof(kHKDFInfo)) || + !BORINGSSL_check_test(kHKDFOutput, hkdf_output, "HKDF")) { + fprintf(CRYPTO_get_stderr(), "HKDF failed.\n"); + return 0; + } } - // TLS v1.3: derives a dummy client-early-traffic secret. - static const uint8_t kTLS13Secret[32] = { - 0x02, 0x4a, 0x0d, 0x80, 0xf3, 0x57, 0xf2, 0x49, 0x9a, 0x12, 0x44, - 0xda, 0xc2, 0x6d, 0xab, 0x66, 0xfc, 0x13, 0xed, 0x85, 0xfc, 0xa7, - 0x1d, 0xac, 0xe1, 0x46, 0x21, 0x11, 0x19, 0x52, 0x58, 0x74, - }; - static const uint8_t kTLS13Salt[16] = { - 0x54, 0x61, 0x11, 0x36, 0x75, 0x91, 0xf0, 0xf8, - 0x92, 0xec, 0x70, 0xbd, 0x78, 0x2a, 0xef, 0x61, - }; - static const uint8_t kTLS13Label[] = "c e traffic"; - static const uint8_t kTLS13ClientHelloHash[32] = { - 0x1d, 0xe8, 0x67, 0xed, 0x93, 0x6a, 0x73, 0x65, 0x9b, 0x05, 0xcf, - 0x8a, 0x22, 0x77, 0xb7, 0x37, 0x29, 0xf2, 0x44, 0x94, 0x81, 0x6a, - 0x83, 0x33, 0x7f, 0x09, 0xbb, 0x6c, 0xc2, 0x6f, 0x48, 0x9c, - }; - static const uint8_t kTLS13ExpandLabelOutput[32] = { - 0x62, 0x91, 0x52, 0x90, 0x2e, 0xc9, 0xcf, 0x9c, 0x5f, 0x1e, 0x0a, - 0xb7, 0x00, 0x33, 0x42, 0x24, 0xc4, 0xe3, 0xba, 0x01, 0x40, 0x32, - 0x06, 0xab, 0x09, 0x23, 0x8a, 0xdd, 0x01, 0xa4, 0x05, 0xcd, - }; - uint8_t tls13_extract_output[32]; - size_t tls13_extract_output_len; - uint8_t tls13_expand_label_output[32]; - if (!HKDF_extract(tls13_extract_output, &tls13_extract_output_len, - EVP_sha256(), kTLS13Secret, sizeof(kTLS13Secret), - kTLS13Salt, sizeof(kTLS13Salt)) || - tls13_extract_output_len != sizeof(tls13_extract_output) || - !CRYPTO_tls13_hkdf_expand_label( - tls13_expand_label_output, sizeof(tls13_expand_label_output), - EVP_sha256(), tls13_extract_output, sizeof(tls13_extract_output), - kTLS13Label, sizeof(kTLS13Label) - 1, kTLS13ClientHelloHash, - sizeof(kTLS13ClientHelloHash)) || - !check_test(kTLS13ExpandLabelOutput, tls13_expand_label_output, - sizeof(kTLS13ExpandLabelOutput), - "CRYPTO_tls13_hkdf_expand_label")) { - fprintf(CRYPTO_get_stderr(), "TLS13-KDF failed.\n"); - goto err; - } - - // HKDF - static const uint8_t kHKDFSecret[32] = { - 0x68, 0x67, 0x85, 0x04, 0xb9, 0xb3, 0xad, 0xd1, 0x7d, 0x59, 0x67, - 0xa1, 0xa7, 0xbd, 0x37, 0x99, 0x3f, 0xd8, 0xa3, 0x3c, 0xe7, 0x30, - 0x30, 0x71, 0xf3, 0x9c, 0x09, 0x6d, 0x16, 0x35, 0xb3, 0xc9, - }; - static const uint8_t kHKDFSalt[32] = { - 0x8a, 0xab, 0x18, 0xb4, 0x9b, 0x0a, 0x17, 0xf9, 0xe8, 0xe6, 0x97, - 0x1a, 0x3d, 0xff, 0xda, 0x9b, 0x26, 0x8b, 0x3d, 0x17, 0x78, 0x0a, - 0xb3, 0xea, 0x65, 0xdb, 0x2a, 0xc0, 0x29, 0x9c, 0xfa, 0x72, - }; - static const uint8_t kHKDFInfo[32] = { - 0xe5, 0x6f, 0xf9, 0xe1, 0x18, 0x5e, 0x64, 0x8c, 0x6c, 0x8f, 0xee, - 0xc6, 0x93, 0x5a, 0xc5, 0x14, 0x8c, 0xf3, 0xd9, 0x78, 0xd2, 0x3a, - 0x86, 0xdd, 0x01, 0xdf, 0xb9, 0xe9, 0x5e, 0xe5, 0x1a, 0x56, - }; - static const uint8_t kHKDFOutput[32] = { - 0xa6, 0x29, 0xb4, 0xd7, 0xf4, 0xc1, 0x16, 0x64, 0x71, 0x5e, 0xa4, - 0xa8, 0xe6, 0x60, 0x8c, 0xf3, 0xc1, 0xa5, 0x03, 0xe2, 0x22, 0xf9, - 0x89, 0xe2, 0x12, 0x18, 0xbe, 0xef, 0x16, 0x86, 0xe0, 0xec, - }; - uint8_t hkdf_output[sizeof(kHKDFOutput)]; - if (!HKDF(hkdf_output, sizeof(hkdf_output), EVP_sha256(), kHKDFSecret, - sizeof(kHKDFSecret), kHKDFSalt, sizeof(kHKDFSalt), kHKDFInfo, - sizeof(kHKDFInfo)) || - !check_test(kHKDFOutput, hkdf_output, sizeof(kHKDFOutput), "HKDF")) { - fprintf(CRYPTO_get_stderr(), "HKDF failed.\n"); - goto err; - } - - ret = 1; - -err: - EVP_AEAD_CTX_cleanup(&aead_ctx); - - return ret; + return 1; } -int BORINGSSL_self_test(void) { +int BORINGSSL_self_test() { if (!boringssl_self_test_fast() || - // When requested to run self tests, also run the lazy tests. - !boringssl_self_test_rsa() || // - !boringssl_self_test_ecc() || // - !boringssl_self_test_ffdh()) { + // When requested to run self tests, also run some of the lazy tests. + !boringssl_self_test_rsa_sign() || // + !boringssl_self_test_rsa_verify() || // + !boringssl_self_test_ecc() || // + !boringssl_self_test_ffdh() || // + !boringssl_self_test_mlkem() || // + !boringssl_self_test_mldsa()) { + return 0; + } + + return 1; +} + +int BORINGSSL_self_test_all() { + if (!BORINGSSL_self_test() || + // When requested to run all self tests, add in the really slow tests. + !boringssl_self_test_slhdsa()) { return 0; } @@ -1036,7 +1089,5 @@ int BORINGSSL_self_test(void) { } #if defined(BORINGSSL_FIPS) -int boringssl_self_test_startup(void) { return boringssl_self_test_fast(); } +int bssl::boringssl_self_test_startup() { return boringssl_self_test_fast(); } #endif - -#endif // !_MSC_VER diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/service_indicator/internal.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/service_indicator/internal.h index 8ee87463..0bf7e4c4 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/service_indicator/internal.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/service_indicator/internal.h @@ -1,42 +1,63 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// 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. -#ifndef OPENSSL_HEADER_SERVICE_INDICATOR_INTERNAL_H -#define OPENSSL_HEADER_SERVICE_INDICATOR_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_SERVICE_INDICATOR_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_SERVICE_INDICATOR_INTERNAL_H #include -#include + + +BSSL_NAMESPACE_BEGIN + +// FIPS_service_indicator_before_call and `FIPS_service_indicator_after_call` +// both currently return the same local thread counter which is slowly +// incremented whenever approved services are called. The +// `CALL_SERVICE_AND_CHECK_APPROVED` macro is strongly recommended over calling +// these functions directly. +// +// `FIPS_service_indicator_before_call` is intended to be called immediately +// before an approved service, while `FIPS_service_indicator_after_call` should +// be called immediately after. If the values returned from these two functions +// are not equal, this means that the service called in between is deemed to be +// approved. If the values are still the same, this means the counter has not +// been incremented, and the service called is not approved for FIPS. +// +// In non-FIPS builds, `FIPS_service_indicator_before_call` always returns zero +// and `FIPS_service_indicator_after_call` always returns one. Thus calls always +// appear to be approved. This is intended to simplify testing. +OPENSSL_EXPORT uint64_t FIPS_service_indicator_before_call(); +OPENSSL_EXPORT uint64_t FIPS_service_indicator_after_call(); #if defined(BORINGSSL_FIPS) // FIPS_service_indicator_update_state records that an approved service has been // invoked. -void FIPS_service_indicator_update_state(void); +void FIPS_service_indicator_update_state(); -// FIPS_service_indicator_lock_state and |FIPS_service_indicator_unlock_state| -// stop |FIPS_service_indicator_update_state| from actually updating the service +// FIPS_service_indicator_lock_state and `FIPS_service_indicator_unlock_state` +// stop `FIPS_service_indicator_update_state` from actually updating the service // indicator. This is used when a primitive calls a potentially approved // primitive to avoid false positives. For example, just because a key -// generation calls |BCM_rand_bytes| (and thus the approved DRBG) doesn't mean +// generation calls `BCM_rand_bytes` (and thus the approved DRBG) doesn't mean // that the key generation operation itself is approved. // // This lock nests: i.e. locking twice is fine so long as each lock is paired // with an unlock. If the (64-bit) counter overflows, the process aborts. -void FIPS_service_indicator_lock_state(void); -void FIPS_service_indicator_unlock_state(void); +void FIPS_service_indicator_lock_state(); +void FIPS_service_indicator_unlock_state(); -// The following functions may call |FIPS_service_indicator_update_state| if +// The following functions may call `FIPS_service_indicator_update_state` if // their parameter specifies an approved operation. void AEAD_GCM_verify_service_indicator(const EVP_AEAD_CTX *ctx); @@ -53,9 +74,9 @@ void TLSKDF_verify_service_indicator(const EVP_MD *dgst); // Service indicator functions are no-ops in non-FIPS builds. -inline void FIPS_service_indicator_update_state(void) {} -inline void FIPS_service_indicator_lock_state(void) {} -inline void FIPS_service_indicator_unlock_state(void) {} +inline void FIPS_service_indicator_update_state() {} +inline void FIPS_service_indicator_lock_state() {} +inline void FIPS_service_indicator_unlock_state() {} inline void AEAD_GCM_verify_service_indicator( [[maybe_unused]] const EVP_AEAD_CTX *ctx) {} @@ -86,4 +107,6 @@ inline void TLSKDF_verify_service_indicator( #endif // BORINGSSL_FIPS -#endif // OPENSSL_HEADER_SERVICE_INDICATOR_INTERNAL_H +BSSL_NAMESPACE_END + +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_SERVICE_INDICATOR_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/service_indicator/service_indicator.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/service_indicator/service_indicator.cc.inc index f2ef1c6d..146c6535 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/service_indicator/service_indicator.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/service_indicator/service_indicator.cc.inc @@ -1,28 +1,31 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// 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 "../../evp/internal.h" #include "../../internal.h" +#include "../../mem_internal.h" #include "internal.h" + +using namespace bssl; + #if defined(BORINGSSL_FIPS) #define STATE_UNLOCKED 0 @@ -31,29 +34,28 @@ // state of the FIPS service indicator. struct fips_service_indicator_state { // lock_state records the number of times the indicator has been locked. - // When it is zero (i.e. |STATE_UNLOCKED|) then the indicator can be updated. + // When it is zero (i.e. `STATE_UNLOCKED`) then the indicator can be updated. uint64_t lock_state; // counter is the indicator state. It is incremented when an approved service // completes. uint64_t counter; }; -// service_indicator_get returns a pointer to the |fips_service_indicator_state| -// for the current thread. It returns NULL on error. +// service_indicator_get returns a pointer to the `fips_service_indicator_state` +// for the current thread. It returns nullptr on error. // // FIPS 140-3 requires that the module should provide the service indicator // for approved services irrespective of whether the user queries it or not. // Hence, it is lazily initialized in any call to an approved service. -static struct fips_service_indicator_state *service_indicator_get(void) { +static struct fips_service_indicator_state *service_indicator_get() { struct fips_service_indicator_state *indicator = reinterpret_cast(CRYPTO_get_thread_local( OPENSSL_THREAD_LOCAL_FIPS_SERVICE_INDICATOR_STATE)); - if (indicator == NULL) { - indicator = reinterpret_cast( - OPENSSL_malloc(sizeof(struct fips_service_indicator_state))); - if (indicator == NULL) { - return NULL; + if (indicator == nullptr) { + indicator = New(); + if (indicator == nullptr) { + return nullptr; } indicator->lock_state = STATE_UNLOCKED; @@ -63,60 +65,60 @@ static struct fips_service_indicator_state *service_indicator_get(void) { OPENSSL_THREAD_LOCAL_FIPS_SERVICE_INDICATOR_STATE, indicator, OPENSSL_free)) { OPENSSL_PUT_ERROR(CRYPTO, ERR_R_INTERNAL_ERROR); - return NULL; + return nullptr; } } return indicator; } -static uint64_t service_indicator_get_counter(void) { +static uint64_t service_indicator_get_counter() { struct fips_service_indicator_state *indicator = service_indicator_get(); - if (indicator == NULL) { + if (indicator == nullptr) { return 0; } return indicator->counter; } -uint64_t FIPS_service_indicator_before_call(void) { +uint64_t bssl::FIPS_service_indicator_before_call() { return service_indicator_get_counter(); } -uint64_t FIPS_service_indicator_after_call(void) { +uint64_t bssl::FIPS_service_indicator_after_call() { return service_indicator_get_counter(); } -void FIPS_service_indicator_update_state(void) { +void bssl::FIPS_service_indicator_update_state() { struct fips_service_indicator_state *indicator = service_indicator_get(); if (indicator && indicator->lock_state == STATE_UNLOCKED) { indicator->counter++; } } -void FIPS_service_indicator_lock_state(void) { +void bssl::FIPS_service_indicator_lock_state() { struct fips_service_indicator_state *indicator = service_indicator_get(); - if (indicator == NULL) { + if (indicator == nullptr) { return; } - // |FIPS_service_indicator_lock_state| and - // |FIPS_service_indicator_unlock_state| should not under/overflow in normal + // `FIPS_service_indicator_lock_state` and + // `FIPS_service_indicator_unlock_state` should not under/overflow in normal // operation. They are still checked and errors added to facilitate testing in // service_indicator_test.cc. This should only happen if lock/unlock are // called in an incorrect order or multiple times in the same function. const uint64_t new_state = indicator->lock_state + 1; if (new_state < indicator->lock_state) { // Overflow. This would imply that our call stack length has exceeded a - // |uint64_t| which impossible on a 64-bit system. + // `uint64_t` which impossible on a 64-bit system. abort(); } indicator->lock_state = new_state; } -void FIPS_service_indicator_unlock_state(void) { +void bssl::FIPS_service_indicator_unlock_state() { struct fips_service_indicator_state *indicator = service_indicator_get(); - if (indicator == NULL) { + if (indicator == nullptr) { return; } @@ -127,14 +129,14 @@ void FIPS_service_indicator_unlock_state(void) { indicator->lock_state--; } -void AEAD_GCM_verify_service_indicator(const EVP_AEAD_CTX *ctx) { +void bssl::AEAD_GCM_verify_service_indicator(const EVP_AEAD_CTX *ctx) { const size_t key_len = EVP_AEAD_key_length(ctx->aead); if (key_len == 16 || key_len == 32) { FIPS_service_indicator_update_state(); } } -void AEAD_CCM_verify_service_indicator(const EVP_AEAD_CTX *ctx) { +void bssl::AEAD_CCM_verify_service_indicator(const EVP_AEAD_CTX *ctx) { if (EVP_AEAD_key_length(ctx->aead) == 16 && ctx->tag_len == 4) { FIPS_service_indicator_update_state(); } @@ -186,7 +188,7 @@ static int is_md_fips_approved_for_verifying(int md_type) { static void evp_md_ctx_verify_service_indicator(const EVP_MD_CTX *ctx, int (*md_ok)(int md_type)) { - if (EVP_MD_CTX_get0_md(ctx) == NULL) { + if (EVP_MD_CTX_get0_md(ctx) == nullptr) { // Signature schemes without a prehash are currently never FIPS approved. return; } @@ -199,8 +201,8 @@ static void evp_md_ctx_verify_service_indicator(const EVP_MD_CTX *ctx, // EVP_PKEY_RSA_PSS SPKIs aren't supported. if (pkey_type == EVP_PKEY_RSA) { // Message digest used in the private key should be of the same type - // as the given one, so we extract the MD type from the |EVP_PKEY| - // and compare it with the type in |ctx|. + // as the given one, so we extract the MD type from the `EVP_PKEY` + // and compare it with the type in `ctx`. const EVP_MD *pctx_md; if (!EVP_PKEY_CTX_get_signature_md(pctx, &pctx_md)) { goto err; @@ -218,7 +220,8 @@ static void evp_md_ctx_verify_service_indicator(const EVP_MD_CTX *ctx, const EVP_MD *mgf1_md; if (!EVP_PKEY_CTX_get_rsa_pss_saltlen(pctx, &salt_len) || !EVP_PKEY_CTX_get_rsa_mgf1_md(pctx, &mgf1_md) || - (salt_len != -1 && salt_len != (int)EVP_MD_size(pctx_md)) || + (salt_len != RSA_PSS_SALTLEN_DIGEST && + salt_len != (int)EVP_MD_size(pctx_md)) || EVP_MD_type(mgf1_md) != md_type) { // Only PSS where saltLen == hashLen is tested with ACVP. Cases with // non-standard padding functions are also excluded. @@ -227,8 +230,8 @@ 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(ctx->pctx->pkey); + // Note: `EVP_PKEY_size` returns the size in bytes. + size_t pkey_size = EVP_PKEY_size(FromOpaque(ctx->pctx)->pkey.get()); // Check if the MD type and the RSA key size are approved. if (md_ok(md_type) && @@ -238,8 +241,8 @@ static void evp_md_ctx_verify_service_indicator(const EVP_MD_CTX *ctx, } else if (pkey_type == EVP_PKEY_EC) { // Check if the MD type and the elliptic curve are approved. if (md_ok(md_type) && - is_ec_fips_approved(EC_GROUP_get_curve_name( - EC_KEY_get0_group(EVP_PKEY_get0_EC_KEY(ctx->pctx->pkey))))) { + is_ec_fips_approved(EC_GROUP_get_curve_name(EC_KEY_get0_group( + EVP_PKEY_get0_EC_KEY(FromOpaque(ctx->pctx)->pkey.get()))))) { FIPS_service_indicator_update_state(); } } @@ -249,19 +252,19 @@ err: ERR_clear_error(); } -void EC_KEY_keygen_verify_service_indicator(const EC_KEY *eckey) { +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(); } } -void ECDH_verify_service_indicator(const EC_KEY *ec_key) { +void bssl::ECDH_verify_service_indicator(const EC_KEY *ec_key) { if (is_ec_fips_approved(EC_GROUP_get_curve_name(EC_KEY_get0_group(ec_key)))) { FIPS_service_indicator_update_state(); } } -void EVP_Cipher_verify_service_indicator(const EVP_CIPHER_CTX *ctx) { +void bssl::EVP_Cipher_verify_service_indicator(const EVP_CIPHER_CTX *ctx) { switch (EVP_CIPHER_CTX_nid(ctx)) { case NID_aes_128_ecb: case NID_aes_192_ecb: @@ -278,17 +281,17 @@ void EVP_Cipher_verify_service_indicator(const EVP_CIPHER_CTX *ctx) { } } -void EVP_DigestVerify_verify_service_indicator(const EVP_MD_CTX *ctx) { +void bssl::EVP_DigestVerify_verify_service_indicator(const EVP_MD_CTX *ctx) { return evp_md_ctx_verify_service_indicator(ctx, is_md_fips_approved_for_verifying); } -void EVP_DigestSign_verify_service_indicator(const EVP_MD_CTX *ctx) { +void bssl::EVP_DigestSign_verify_service_indicator(const EVP_MD_CTX *ctx) { return evp_md_ctx_verify_service_indicator(ctx, is_md_fips_approved_for_signing); } -void HMAC_verify_service_indicator(const EVP_MD *evp_md) { +void bssl::HMAC_verify_service_indicator(const EVP_MD *evp_md) { switch (EVP_MD_type(evp_md)) { case NID_sha1: case NID_sha224: @@ -301,7 +304,7 @@ void HMAC_verify_service_indicator(const EVP_MD *evp_md) { } } -void TLSKDF_verify_service_indicator(const EVP_MD *md) { +void bssl::TLSKDF_verify_service_indicator(const EVP_MD *md) { // HMAC-SHA{256, 384, 512} are approved for use in the KDF in TLS 1.2. These // Key Derivation functions are to be used in the context of the TLS protocol. switch (EVP_MD_type(md)) { @@ -315,11 +318,11 @@ void TLSKDF_verify_service_indicator(const EVP_MD *md) { #else -uint64_t FIPS_service_indicator_before_call(void) { return 0; } +uint64_t bssl::FIPS_service_indicator_before_call() { return 0; } -uint64_t FIPS_service_indicator_after_call(void) { +uint64_t bssl::FIPS_service_indicator_after_call() { // One is returned so that the return value is always greater than zero, the - // return value of |FIPS_service_indicator_before_call|. This makes everything + // return value of `FIPS_service_indicator_before_call`. This makes everything // report as "approved" in non-FIPS builds. return 1; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/internal.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/internal.h index 6e9c8e52..9bec8340 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/internal.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/internal.h @@ -1,27 +1,26 @@ -/* Copyright 2018 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2018 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. -#ifndef OPENSSL_HEADER_SHA_INTERNAL_H -#define OPENSSL_HEADER_SHA_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_SHA_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_SHA_INTERNAL_H #include #include "../../internal.h" -#if defined(__cplusplus) -extern "C" { -#endif + +BSSL_NAMESPACE_BEGIN // Define SHA{n}[_{variant}]_ASM if sha{n}_block_data_order[_{variant}] is // defined in assembly. @@ -33,23 +32,23 @@ extern "C" { #define SHA512_ASM_NOHW #define SHA1_ASM_HW -inline int sha1_hw_capable(void) { return CRYPTO_is_ARMv8_SHA1_capable(); } +inline int sha1_hw_capable() { return CRYPTO_is_ARMv8_SHA1_capable(); } #define SHA1_ASM_NEON -void sha1_block_data_order_neon(uint32_t state[5], const uint8_t *data, - size_t num); +extern "C" void sha1_block_data_order_neon(uint32_t state[5], + const uint8_t *data, size_t num); #define SHA256_ASM_HW -inline int sha256_hw_capable(void) { return CRYPTO_is_ARMv8_SHA256_capable(); } +inline int sha256_hw_capable() { return CRYPTO_is_ARMv8_SHA256_capable(); } #define SHA256_ASM_NEON -void sha256_block_data_order_neon(uint32_t state[8], const uint8_t *data, - size_t num); +extern "C" void sha256_block_data_order_neon(uint32_t state[8], + const uint8_t *data, size_t num); // Armv8.2 SHA-512 instructions are not available in 32-bit. #define SHA512_ASM_NEON -void sha512_block_data_order_neon(uint64_t state[8], const uint8_t *data, - size_t num); +extern "C" void sha512_block_data_order_neon(uint64_t state[8], + const uint8_t *data, size_t num); #elif !defined(OPENSSL_NO_ASM) && defined(OPENSSL_AARCH64) @@ -58,13 +57,13 @@ void sha512_block_data_order_neon(uint64_t state[8], const uint8_t *data, #define SHA512_ASM_NOHW #define SHA1_ASM_HW -inline int sha1_hw_capable(void) { return CRYPTO_is_ARMv8_SHA1_capable(); } +inline int sha1_hw_capable() { return CRYPTO_is_ARMv8_SHA1_capable(); } #define SHA256_ASM_HW -inline int sha256_hw_capable(void) { return CRYPTO_is_ARMv8_SHA256_capable(); } +inline int sha256_hw_capable() { return CRYPTO_is_ARMv8_SHA256_capable(); } #define SHA512_ASM_HW -inline int sha512_hw_capable(void) { return CRYPTO_is_ARMv8_SHA512_capable(); } +inline int sha512_hw_capable() { return CRYPTO_is_ARMv8_SHA512_capable(); } #elif !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86) @@ -73,59 +72,39 @@ inline int sha512_hw_capable(void) { return CRYPTO_is_ARMv8_SHA512_capable(); } #define SHA512_ASM_NOHW #define SHA1_ASM_SSSE3 -inline int sha1_ssse3_capable(void) { - // TODO(davidben): Do we need to check the FXSR bit? The Intel manual does not - // say to. - return CRYPTO_is_SSSE3_capable() && CRYPTO_is_FXSR_capable(); -} -void sha1_block_data_order_ssse3(uint32_t state[5], const uint8_t *data, - size_t num); +inline int sha1_ssse3_capable() { return CRYPTO_is_SSSE3_capable(); } +extern "C" void sha1_block_data_order_ssse3(uint32_t state[5], + const uint8_t *data, size_t num); #define SHA1_ASM_AVX -inline int sha1_avx_capable(void) { - // Pre-Zen AMD CPUs had slow SHLD/SHRD; Zen added the SHA extension; see the - // discussion in sha1-586.pl. +inline int sha1_avx_capable() { + // AMD CPUs have slow SHLD/SHRD. See also the discussion in sha1-586.pl. // - // TODO(davidben): Should we enable SHAEXT on 32-bit x86? - // TODO(davidben): Do we need to check the FXSR bit? The Intel manual does not - // say to. - return CRYPTO_is_AVX_capable() && CRYPTO_is_intel_cpu() && - CRYPTO_is_FXSR_capable(); + // TODO(crbug.com/42290564): Should we enable SHAEXT on 32-bit x86? + return CRYPTO_is_AVX_capable() && CRYPTO_is_intel_cpu(); } -void sha1_block_data_order_avx(uint32_t state[5], const uint8_t *data, - size_t num); +extern "C" void sha1_block_data_order_avx(uint32_t state[5], + const uint8_t *data, size_t num); #define SHA256_ASM_SSSE3 -inline int sha256_ssse3_capable(void) { - // TODO(davidben): Do we need to check the FXSR bit? The Intel manual does not - // say to. - return CRYPTO_is_SSSE3_capable() && CRYPTO_is_FXSR_capable(); -} -void sha256_block_data_order_ssse3(uint32_t state[8], const uint8_t *data, - size_t num); +inline int sha256_ssse3_capable() { return CRYPTO_is_SSSE3_capable(); } +extern "C" void sha256_block_data_order_ssse3(uint32_t state[8], + const uint8_t *data, size_t num); #define SHA256_ASM_AVX -inline int sha256_avx_capable(void) { - // Pre-Zen AMD CPUs had slow SHLD/SHRD; Zen added the SHA extension; see the - // discussion in sha1-586.pl. +inline int sha256_avx_capable() { + // AMD CPUs have slow SHLD/SHRD. See also the discussion in sha1-586.pl. // - // TODO(davidben): Should we enable SHAEXT on 32-bit x86? - // TODO(davidben): Do we need to check the FXSR bit? The Intel manual does not - // say to. - return CRYPTO_is_AVX_capable() && CRYPTO_is_intel_cpu() && - CRYPTO_is_FXSR_capable(); + // TODO(crbug.com/42290564): Should we enable SHAEXT on 32-bit x86? + return CRYPTO_is_AVX_capable() && CRYPTO_is_intel_cpu(); } -void sha256_block_data_order_avx(uint32_t state[8], const uint8_t *data, - size_t num); +extern "C" void sha256_block_data_order_avx(uint32_t state[8], + const uint8_t *data, size_t num); #define SHA512_ASM_SSSE3 -inline int sha512_ssse3_capable(void) { - // TODO(davidben): Do we need to check the FXSR bit? The Intel manual does not - // say to. - return CRYPTO_is_SSSE3_capable() && CRYPTO_is_FXSR_capable(); -} -void sha512_block_data_order_ssse3(uint64_t state[8], const uint8_t *data, - size_t num); +inline int sha512_ssse3_capable() { return CRYPTO_is_SSSE3_capable(); } +extern "C" void sha512_block_data_order_ssse3(uint64_t state[8], + const uint8_t *data, size_t num); #elif !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) @@ -134,89 +113,93 @@ void sha512_block_data_order_ssse3(uint64_t state[8], const uint8_t *data, #define SHA512_ASM_NOHW #define SHA1_ASM_HW -inline int sha1_hw_capable(void) { +inline int sha1_hw_capable() { return CRYPTO_is_x86_SHA_capable() && CRYPTO_is_SSSE3_capable(); } #define SHA1_ASM_AVX2 -inline int sha1_avx2_capable(void) { +inline int sha1_avx2_capable() { return CRYPTO_is_AVX2_capable() && CRYPTO_is_BMI2_capable() && CRYPTO_is_BMI1_capable(); } -void sha1_block_data_order_avx2(uint32_t state[5], const uint8_t *data, - size_t num); +extern "C" void sha1_block_data_order_avx2(uint32_t state[5], + const uint8_t *data, size_t num); #define SHA1_ASM_AVX -inline int sha1_avx_capable(void) { - // Pre-Zen AMD CPUs had slow SHLD/SHRD; Zen added the SHA extension; see the - // discussion in sha1-586.pl. +inline int sha1_avx_capable() { + // AMD CPUs have slow SHLD/SHRD. See also the discussion in sha1-586.pl. Zen + // added the SHA extension, so this is moot on newer AMD CPUs. return CRYPTO_is_AVX_capable() && CRYPTO_is_intel_cpu(); } -void sha1_block_data_order_avx(uint32_t state[5], const uint8_t *data, - size_t num); +extern "C" void sha1_block_data_order_avx(uint32_t state[5], + const uint8_t *data, size_t num); #define SHA1_ASM_SSSE3 -inline int sha1_ssse3_capable(void) { return CRYPTO_is_SSSE3_capable(); } -void sha1_block_data_order_ssse3(uint32_t state[5], const uint8_t *data, - size_t num); +inline int sha1_ssse3_capable() { return CRYPTO_is_SSSE3_capable(); } +extern "C" void sha1_block_data_order_ssse3(uint32_t state[5], + const uint8_t *data, size_t num); #define SHA256_ASM_HW -inline int sha256_hw_capable(void) { +inline int sha256_hw_capable() { // Note that the original assembly did not check SSSE3. return CRYPTO_is_x86_SHA_capable() && CRYPTO_is_SSSE3_capable(); } #define SHA256_ASM_AVX -inline int sha256_avx_capable(void) { - // Pre-Zen AMD CPUs had slow SHLD/SHRD; Zen added the SHA extension; see the - // discussion in sha1-586.pl. +inline int sha256_avx_capable() { + // AMD CPUs have slow SHLD/SHRD. See also the discussion in sha1-586.pl. Zen + // added the SHA extension, so this is moot on newer AMD CPUs. return CRYPTO_is_AVX_capable() && CRYPTO_is_intel_cpu(); } -void sha256_block_data_order_avx(uint32_t state[8], const uint8_t *data, - size_t num); +extern "C" void sha256_block_data_order_avx(uint32_t state[8], + const uint8_t *data, size_t num); #define SHA256_ASM_SSSE3 -inline int sha256_ssse3_capable(void) { return CRYPTO_is_SSSE3_capable(); } -void sha256_block_data_order_ssse3(uint32_t state[8], const uint8_t *data, - size_t num); +inline int sha256_ssse3_capable() { return CRYPTO_is_SSSE3_capable(); } +extern "C" void sha256_block_data_order_ssse3(uint32_t state[8], + const uint8_t *data, size_t num); #define SHA512_ASM_AVX -inline int sha512_avx_capable(void) { return CRYPTO_is_AVX_capable(); } -void sha512_block_data_order_avx(uint64_t state[8], const uint8_t *data, - size_t num); +inline int sha512_avx_capable() { + // AMD CPUs have slow SHLD/SHRD. See also the discussion in sha1-586.pl. + // + // TODO(crbug.com/42290564): Fixing and enabling the AVX2 implementation would + // mitigate this on newer AMD CPUs. + return CRYPTO_is_AVX_capable() && CRYPTO_is_intel_cpu(); +} +extern "C" void sha512_block_data_order_avx(uint64_t state[8], + const uint8_t *data, size_t num); #endif #if defined(SHA1_ASM_HW) -void sha1_block_data_order_hw(uint32_t state[5], const uint8_t *data, - size_t num); +extern "C" void sha1_block_data_order_hw(uint32_t state[5], const uint8_t *data, + size_t num); #endif #if defined(SHA1_ASM_NOHW) -void sha1_block_data_order_nohw(uint32_t state[5], const uint8_t *data, - size_t num); +extern "C" void sha1_block_data_order_nohw(uint32_t state[5], + const uint8_t *data, size_t num); #endif #if defined(SHA256_ASM_HW) -void sha256_block_data_order_hw(uint32_t state[8], const uint8_t *data, - size_t num); +extern "C" void sha256_block_data_order_hw(uint32_t state[8], + const uint8_t *data, size_t num); #endif #if defined(SHA256_ASM_NOHW) -void sha256_block_data_order_nohw(uint32_t state[8], const uint8_t *data, - size_t num); +extern "C" void sha256_block_data_order_nohw(uint32_t state[8], + const uint8_t *data, size_t num); #endif #if defined(SHA512_ASM_HW) -void sha512_block_data_order_hw(uint64_t state[8], const uint8_t *data, - size_t num); +extern "C" void sha512_block_data_order_hw(uint64_t state[8], + const uint8_t *data, size_t num); #endif #if defined(SHA512_ASM_NOHW) -void sha512_block_data_order_nohw(uint64_t state[8], const uint8_t *data, - size_t num); +extern "C" void sha512_block_data_order_nohw(uint64_t state[8], + const uint8_t *data, size_t num); #endif -#if defined(__cplusplus) -} // extern "C" -#endif +BSSL_NAMESPACE_END -#endif // OPENSSL_HEADER_SHA_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_SHA_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/sha1.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/sha1.cc.inc index f3e045d2..0dc59381 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/sha1.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/sha1.cc.inc @@ -1,15 +1,21 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../../internal.h" #include "../bcm_interface.h" @@ -18,7 +24,9 @@ #include "internal.h" -bcm_infallible BCM_sha1_init(SHA_CTX *sha) { +using namespace bssl; + +bcm_infallible bssl::BCM_sha1_init(SHA_CTX *sha) { OPENSSL_memset(sha, 0, sizeof(SHA_CTX)); sha->h[0] = 0x67452301UL; sha->h[1] = 0xefcdab89UL; @@ -33,15 +41,27 @@ static void sha1_block_data_order(uint32_t state[5], const uint8_t *data, size_t num); #endif -bcm_infallible BCM_sha1_transform(SHA_CTX *c, const uint8_t data[SHA_CBLOCK]) { +bcm_infallible bssl::BCM_sha1_transform(SHA_CTX *c, + const uint8_t data[SHA_CBLOCK]) { sha1_block_data_order(c->h, data, 1); return bcm_infallible::approved; } -bcm_infallible BCM_sha1_update(SHA_CTX *c, const void *data, size_t len) { - crypto_md32_update(&sha1_block_data_order, c->h, c->data, SHA_CBLOCK, &c->num, - &c->Nh, &c->Nl, reinterpret_cast(data), - len); +namespace { +struct SHA1Traits { + using HashContext = SHA_CTX; + static constexpr size_t kBlockSize = SHA_CBLOCK; + static constexpr bool kLengthIsBigEndian = true; + static void HashBlocks(uint32_t *state, const uint8_t *data, + size_t num_blocks) { + sha1_block_data_order(state, data, num_blocks); + } +}; +} // namespace + +bcm_infallible bssl::BCM_sha1_update(SHA_CTX *c, const void *data, size_t len) { + crypto_md32_update(c, + Span(static_cast(data), len)); return bcm_infallible::approved; } @@ -54,17 +74,16 @@ static void sha1_output_state(uint8_t out[SHA_DIGEST_LENGTH], CRYPTO_store_u32_be(out + 16, ctx->h[4]); } -bcm_infallible BCM_sha1_final(uint8_t out[SHA_DIGEST_LENGTH], SHA_CTX *c) { - crypto_md32_final(&sha1_block_data_order, c->h, c->data, SHA_CBLOCK, &c->num, - c->Nh, c->Nl, /*is_big_endian=*/1); - +bcm_infallible bssl::BCM_sha1_final(uint8_t out[SHA_DIGEST_LENGTH], + SHA_CTX *c) { + crypto_md32_final(c); sha1_output_state(out, c); FIPS_service_indicator_update_state(); return bcm_infallible::approved; } -bcm_infallible BCM_fips_186_2_prf(uint8_t *out, size_t out_len, - const uint8_t xkey[SHA_DIGEST_LENGTH]) { +bcm_infallible bssl::BCM_fips_186_2_prf(uint8_t *out, size_t out_len, + const uint8_t xkey[SHA_DIGEST_LENGTH]) { // XKEY and XVAL are 160-bit values, but are internally right-padded up to // block size. See FIPS 186-2, Appendix 3.3. This buffer maintains both the // current value of XKEY and the padding. @@ -78,7 +97,7 @@ bcm_infallible BCM_fips_186_2_prf(uint8_t *out, size_t out_len, BCM_sha1_init(&ctx); BCM_sha1_transform(&ctx, block); - // XKEY = (1 + XKEY + w_i) mod 2^b + // XKEY = (1 + XKEY + wᵢ) mod 2ᵇ uint32_t carry = 1; for (int i = 4; i >= 0; i--) { uint32_t tmp = CRYPTO_load_u32_be(block + i * 4); @@ -86,7 +105,7 @@ bcm_infallible BCM_fips_186_2_prf(uint8_t *out, size_t out_len, CRYPTO_store_u32_be(block + i * 4, tmp); } - // Output w_i. + // Output wᵢ. if (out_len < SHA_DIGEST_LENGTH) { uint8_t buf[SHA_DIGEST_LENGTH]; sha1_output_state(buf, &ctx); @@ -169,7 +188,7 @@ bcm_infallible BCM_fips_186_2_prf(uint8_t *out, size_t out_len, #endif /* Originally X was an array. As it's automatic it's natural - * to expect RISC compiler to accomodate at least part of it in + * to expect RISC compiler to accommodate at least part of it in * the register bank, isn't it? Unfortunately not all compilers * "find" this expectation reasonable:-( On order to make such * compilers generate better code I replace X[] with a bunch of diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/sha256.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/sha256.cc.inc index 99512490..ed1d2a2e 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/sha256.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/sha256.cc.inc @@ -1,15 +1,21 @@ -/* - * Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../../internal.h" #include "../bcm_interface.h" @@ -18,7 +24,9 @@ #include "internal.h" -bcm_infallible BCM_sha224_init(SHA256_CTX *sha) { +using namespace bssl; + +bcm_infallible bssl::BCM_sha224_init(SHA256_CTX *sha) { OPENSSL_memset(sha, 0, sizeof(SHA256_CTX)); sha->h[0] = 0xc1059ed8UL; sha->h[1] = 0x367cd507UL; @@ -28,11 +36,11 @@ bcm_infallible BCM_sha224_init(SHA256_CTX *sha) { sha->h[5] = 0x68581511UL; sha->h[6] = 0x64f98fa7UL; sha->h[7] = 0xbefa4fa4UL; - sha->md_len = BCM_SHA224_DIGEST_LENGTH; + sha->md_len = SHA224_DIGEST_LENGTH; return bcm_infallible::approved; } -bcm_infallible BCM_sha256_init(SHA256_CTX *sha) { +bcm_infallible bssl::BCM_sha256_init(SHA256_CTX *sha) { OPENSSL_memset(sha, 0, sizeof(SHA256_CTX)); sha->h[0] = 0x6a09e667UL; sha->h[1] = 0xbb67ae85UL; @@ -42,7 +50,7 @@ bcm_infallible BCM_sha256_init(SHA256_CTX *sha) { sha->h[5] = 0x9b05688cUL; sha->h[6] = 0x1f83d9abUL; sha->h[7] = 0x5be0cd19UL; - sha->md_len = BCM_SHA256_DIGEST_LENGTH; + sha->md_len = SHA256_DIGEST_LENGTH; return bcm_infallible::approved; } @@ -51,29 +59,40 @@ static void sha256_block_data_order(uint32_t state[8], const uint8_t *in, size_t num); #endif -bcm_infallible BCM_sha256_transform(SHA256_CTX *c, - const uint8_t data[BCM_SHA256_CBLOCK]) { +bcm_infallible bssl::BCM_sha256_transform(SHA256_CTX *c, + const uint8_t data[SHA256_CBLOCK]) { sha256_block_data_order(c->h, data, 1); return bcm_infallible::approved; } -bcm_infallible BCM_sha256_update(SHA256_CTX *c, const void *data, size_t len) { - crypto_md32_update(&sha256_block_data_order, c->h, c->data, BCM_SHA256_CBLOCK, - &c->num, &c->Nh, &c->Nl, - reinterpret_cast(data), len); +namespace { +struct SHA256Traits { + using HashContext = SHA256_CTX; + static constexpr size_t kBlockSize = SHA256_CBLOCK; + static constexpr bool kLengthIsBigEndian = true; + static void HashBlocks(uint32_t *state, const uint8_t *data, + size_t num_blocks) { + sha256_block_data_order(state, data, num_blocks); + } +}; +} // namespace + +bcm_infallible bssl::BCM_sha256_update(SHA256_CTX *c, const void *data, + size_t len) { + crypto_md32_update( + c, Span(static_cast(data), len)); return bcm_infallible::approved; } -bcm_infallible BCM_sha224_update(SHA256_CTX *ctx, const void *data, - size_t len) { +bcm_infallible bssl::BCM_sha224_update(SHA256_CTX *ctx, const void *data, + size_t len) { return BCM_sha256_update(ctx, data, len); } static void sha256_final_impl(uint8_t *out, size_t md_len, SHA256_CTX *c) { - crypto_md32_final(&sha256_block_data_order, c->h, c->data, BCM_SHA256_CBLOCK, - &c->num, c->Nh, c->Nl, /*is_big_endian=*/1); + crypto_md32_final(c); - BSSL_CHECK(md_len <= BCM_SHA256_DIGEST_LENGTH); + BSSL_CHECK(md_len <= SHA256_DIGEST_LENGTH); assert(md_len % 4 == 0); const size_t out_words = md_len / 4; @@ -85,23 +104,23 @@ static void sha256_final_impl(uint8_t *out, size_t md_len, SHA256_CTX *c) { FIPS_service_indicator_update_state(); } -bcm_infallible BCM_sha256_final(uint8_t out[BCM_SHA256_DIGEST_LENGTH], - SHA256_CTX *c) { - // Ideally we would assert |sha->md_len| is |BCM_SHA256_DIGEST_LENGTH| to - // match the size hint, but calling code often pairs |SHA224_Init| with - // |SHA256_Final| and expects |sha->md_len| to carry the size over. +bcm_infallible bssl::BCM_sha256_final(uint8_t out[SHA256_DIGEST_LENGTH], + SHA256_CTX *c) { + // Ideally we would assert `sha->md_len` is `SHA256_DIGEST_LENGTH` tomatch the + // size hint, but calling code often pairs `SHA224_Init` with `SHA256_Final` + // and expects `sha->md_len` to carry the size over. // // TODO(davidben): Add an assert and fix code to match them up. sha256_final_impl(out, c->md_len, c); return bcm_infallible::approved; } -bcm_infallible BCM_sha224_final(uint8_t out[BCM_SHA224_DIGEST_LENGTH], - SHA256_CTX *ctx) { - // This function must be paired with |SHA224_Init|, which sets |ctx->md_len| - // to |BCM_SHA224_DIGEST_LENGTH|. - assert(ctx->md_len == BCM_SHA224_DIGEST_LENGTH); - sha256_final_impl(out, BCM_SHA224_DIGEST_LENGTH, ctx); +bcm_infallible bssl::BCM_sha224_final(uint8_t out[SHA224_DIGEST_LENGTH], + SHA256_CTX *ctx) { + // This function must be paired with `SHA224_Init`, which sets `ctx->md_len` + // to `SHA224_DIGEST_LENGTH`. + assert(ctx->md_len == SHA224_DIGEST_LENGTH); + sha256_final_impl(out, SHA224_DIGEST_LENGTH, ctx); return bcm_infallible::approved; } @@ -277,10 +296,12 @@ static void sha256_block_data_order(uint32_t state[8], const uint8_t *data, #endif // !defined(SHA256_ASM) -bcm_infallible BCM_sha256_transform_blocks(uint32_t state[8], - const uint8_t *data, - size_t num_blocks) { - sha256_block_data_order(state, data, num_blocks); +bcm_infallible bssl::BCM_sha256_transform_blocks(uint32_t state[8], + const uint8_t *data, + size_t num_blocks) { + if (num_blocks > 0) { + sha256_block_data_order(state, data, num_blocks); + } return bcm_infallible::approved; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/sha512.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/sha512.cc.inc index f452187f..c30ccf04 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/sha512.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/sha/sha512.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,6 +22,8 @@ #include "internal.h" +using namespace bssl; + // The 32-bit hash algorithms share a common byte-order neutral collector and // padding function implementations that operate on unaligned data, // ../digest/md32_common.h. SHA-512 is the only 64-bit hash algorithm, as of @@ -25,7 +32,7 @@ static void sha512_final_impl(uint8_t *out, size_t md_len, SHA512_CTX *sha); -bcm_infallible BCM_sha384_init(SHA512_CTX *sha) { +bcm_infallible bssl::BCM_sha384_init(SHA512_CTX *sha) { sha->h[0] = UINT64_C(0xcbbb9d5dc1059ed8); sha->h[1] = UINT64_C(0x629a292a367cd507); sha->h[2] = UINT64_C(0x9159015a3070dd17); @@ -35,15 +42,15 @@ bcm_infallible BCM_sha384_init(SHA512_CTX *sha) { sha->h[6] = UINT64_C(0xdb0c2e0d64f98fa7); sha->h[7] = UINT64_C(0x47b5481dbefa4fa4); - sha->Nl = 0; - sha->Nh = 0; + sha->bytes_so_far_low = 0; + sha->bytes_so_far_high = 0; sha->num = 0; - sha->md_len = BCM_SHA384_DIGEST_LENGTH; + sha->md_len = SHA384_DIGEST_LENGTH; return bcm_infallible::approved; } -bcm_infallible BCM_sha512_init(SHA512_CTX *sha) { +bcm_infallible bssl::BCM_sha512_init(SHA512_CTX *sha) { sha->h[0] = UINT64_C(0x6a09e667f3bcc908); sha->h[1] = UINT64_C(0xbb67ae8584caa73b); sha->h[2] = UINT64_C(0x3c6ef372fe94f82b); @@ -53,14 +60,14 @@ bcm_infallible BCM_sha512_init(SHA512_CTX *sha) { sha->h[6] = UINT64_C(0x1f83d9abfb41bd6b); sha->h[7] = UINT64_C(0x5be0cd19137e2179); - sha->Nl = 0; - sha->Nh = 0; + sha->bytes_so_far_low = 0; + sha->bytes_so_far_high = 0; sha->num = 0; - sha->md_len = BCM_SHA512_DIGEST_LENGTH; + sha->md_len = SHA512_DIGEST_LENGTH; return bcm_infallible::approved; } -bcm_infallible BCM_sha512_256_init(SHA512_CTX *sha) { +bcm_infallible bssl::BCM_sha512_256_init(SHA512_CTX *sha) { sha->h[0] = UINT64_C(0x22312194fc2bf72c); sha->h[1] = UINT64_C(0x9f555fa3c84c64c2); sha->h[2] = UINT64_C(0x2393b86b6f53b151); @@ -70,10 +77,10 @@ bcm_infallible BCM_sha512_256_init(SHA512_CTX *sha) { sha->h[6] = UINT64_C(0x2b0199fc2c85b8aa); sha->h[7] = UINT64_C(0x0eb72ddc81c52ca2); - sha->Nl = 0; - sha->Nh = 0; + sha->bytes_so_far_low = 0; + sha->bytes_so_far_high = 0; sha->num = 0; - sha->md_len = BCM_SHA512_256_DIGEST_LENGTH; + sha->md_len = SHA512_256_DIGEST_LENGTH; return bcm_infallible::approved; } @@ -83,43 +90,42 @@ static void sha512_block_data_order(uint64_t state[8], const uint8_t *in, #endif -bcm_infallible BCM_sha384_final(uint8_t out[BCM_SHA384_DIGEST_LENGTH], - SHA512_CTX *sha) { - // This function must be paired with |BCM_sha384_init|, which sets - // |sha->md_len| to |BCM_SHA384_DIGEST_LENGTH|. - assert(sha->md_len == BCM_SHA384_DIGEST_LENGTH); - sha512_final_impl(out, BCM_SHA384_DIGEST_LENGTH, sha); +bcm_infallible bssl::BCM_sha384_final(uint8_t out[SHA384_DIGEST_LENGTH], + SHA512_CTX *sha) { + // This function must be paired with `BCM_sha384_init`, which sets + // `sha->md_len` to `SHA384_DIGEST_LENGTH`. + assert(sha->md_len == SHA384_DIGEST_LENGTH); + sha512_final_impl(out, SHA384_DIGEST_LENGTH, sha); return bcm_infallible::approved; } -bcm_infallible BCM_sha384_update(SHA512_CTX *sha, const void *data, - size_t len) { +bcm_infallible bssl::BCM_sha384_update(SHA512_CTX *sha, const void *data, + size_t len) { return BCM_sha512_update(sha, data, len); } -bcm_infallible BCM_sha512_256_update(SHA512_CTX *sha, const void *data, - size_t len) { +bcm_infallible bssl::BCM_sha512_256_update(SHA512_CTX *sha, const void *data, + size_t len) { return BCM_sha512_update(sha, data, len); } -bcm_infallible BCM_sha512_256_final(uint8_t out[BCM_SHA512_256_DIGEST_LENGTH], - SHA512_CTX *sha) { - // This function must be paired with |BCM_sha512_256_init|, which sets - // |sha->md_len| to |BCM_SHA512_256_DIGEST_LENGTH|. - assert(sha->md_len == BCM_SHA512_256_DIGEST_LENGTH); - sha512_final_impl(out, BCM_SHA512_256_DIGEST_LENGTH, sha); +bcm_infallible bssl::BCM_sha512_256_final(uint8_t out[SHA512_256_DIGEST_LENGTH], + SHA512_CTX *sha) { + // This function must be paired with `BCM_sha512_256_init`, which sets + // `sha->md_len` to `SHA512_256_DIGEST_LENGTH`. + assert(sha->md_len == SHA512_256_DIGEST_LENGTH); + sha512_final_impl(out, SHA512_256_DIGEST_LENGTH, sha); return bcm_infallible::approved; } -bcm_infallible BCM_sha512_transform(SHA512_CTX *c, - const uint8_t block[SHA512_CBLOCK]) { +bcm_infallible bssl::BCM_sha512_transform(SHA512_CTX *c, + const uint8_t block[SHA512_CBLOCK]) { sha512_block_data_order(c->h, block, 1); return bcm_infallible::approved; } -bcm_infallible BCM_sha512_update(SHA512_CTX *c, const void *in_data, - size_t len) { - uint64_t l; +bcm_infallible bssl::BCM_sha512_update(SHA512_CTX *c, const void *in_data, + size_t len) { uint8_t *p = c->p; const uint8_t *data = reinterpret_cast(in_data); @@ -127,14 +133,10 @@ bcm_infallible BCM_sha512_update(SHA512_CTX *c, const void *in_data, return bcm_infallible::approved; } - l = (c->Nl + (((uint64_t)len) << 3)) & UINT64_C(0xffffffffffffffff); - if (l < c->Nl) { - c->Nh++; + c->bytes_so_far_low += len; + if (c->bytes_so_far_low < len) { + c->bytes_so_far_high++; } - if (sizeof(len) >= 8) { - c->Nh += (((uint64_t)len) >> 61); - } - c->Nl = l; if (c->num != 0) { size_t n = sizeof(c->p) - c->num; @@ -166,11 +168,11 @@ bcm_infallible BCM_sha512_update(SHA512_CTX *c, const void *in_data, return bcm_infallible::approved; } -bcm_infallible BCM_sha512_final(uint8_t out[BCM_SHA512_DIGEST_LENGTH], - SHA512_CTX *sha) { - // Ideally we would assert |sha->md_len| is |BCM_SHA512_DIGEST_LENGTH| to - // match the size hint, but calling code often pairs |BCM_sha384_init| with - // |BCM_sha512_final| and expects |sha->md_len| to carry the size over. +bcm_infallible bssl::BCM_sha512_final(uint8_t out[SHA512_DIGEST_LENGTH], + SHA512_CTX *sha) { + // Ideally we would assert `sha->md_len` is `SHA512_DIGEST_LENGTH` to match + // the size hint, but calling code often pairs `BCM_sha384_init` with + // `BCM_sha512_final` and expects `sha->md_len` to carry the size over. // // TODO(davidben): Add an assert and fix code to match them up. sha512_final_impl(out, sha->md_len, sha); @@ -190,8 +192,11 @@ static void sha512_final_impl(uint8_t *out, size_t md_len, SHA512_CTX *sha) { } OPENSSL_memset(p + n, 0, sizeof(sha->p) - 16 - n); - CRYPTO_store_u64_be(p + sizeof(sha->p) - 16, sha->Nh); - CRYPTO_store_u64_be(p + sizeof(sha->p) - 8, sha->Nl); + const uint64_t Nh = (uint64_t{sha->bytes_so_far_high} << 3) | + (sha->bytes_so_far_low >> (64 - 3)); + const uint64_t Nl = sha->bytes_so_far_low << 3; + CRYPTO_store_u64_be(p + sizeof(sha->p) - 16, Nh); + CRYPTO_store_u64_be(p + sizeof(sha->p) - 8, Nl); sha512_block_data_order(sha->h, p, 1); diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/address.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/address.h index 0166b6b4..901f65e5 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/address.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/address.h @@ -1,16 +1,16 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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. #ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_ADDRESS_H #define OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_ADDRESS_H @@ -18,102 +18,127 @@ #include #include "../../internal.h" - -#if defined(__cplusplus) -extern "C" { -#endif +#include "./params.h" -// Offsets of various fields in the address structure for SLH-DSA-SHA2-128s. +BSSL_NAMESPACE_BEGIN -// The byte used to specify the Merkle tree layer. -#define SLHDSA_SHA2_128S_OFFSET_LAYER 0 +#define SLHDSA_ADDR_TYPE_WOTS 0 +#define SLHDSA_ADDR_TYPE_WOTSPK 1 +#define SLHDSA_ADDR_TYPE_HASHTREE 2 +#define SLHDSA_ADDR_TYPE_FORSTREE 3 +#define SLHDSA_ADDR_TYPE_FORSPK 4 +#define SLHDSA_ADDR_TYPE_WOTSPRF 5 +#define SLHDSA_ADDR_TYPE_FORSPRF 6 -// The start of the 8 byte field used to specify the tree. -#define SLHDSA_SHA2_128S_OFFSET_TREE 1 - -// The byte used to specify the hash type (reason). -#define SLHDSA_SHA2_128S_OFFSET_TYPE 9 - -// The high byte used to specify the key pair (which one-time signature). -#define SLHDSA_SHA2_128S_OFFSET_KP_ADDR2 12 - -// The low byte used to specific the key pair. -#define SLHDSA_SHA2_128S_OFFSET_KP_ADDR1 13 - -// The byte used to specify the chain address (which Winternitz chain). -#define SLHDSA_SHA2_128S_OFFSET_CHAIN_ADDR 17 - -// The byte used to specify the hash address (where in the Winternitz chain). -#define SLHDSA_SHA2_128S_OFFSET_HASH_ADDR 21 - -// The byte used to specify the height of this node in the FORS or Merkle tree. -#define SLHDSA_SHA2_128S_OFFSET_TREE_HGT 17 - -// The start of the 4 byte field used to specify the node in the FORS or Merkle -// tree. -#define SLHDSA_SHA2_128S_OFFSET_TREE_INDEX 18 - - -inline void slhdsa_set_chain_addr(uint8_t addr[32], uint32_t chain) { - addr[SLHDSA_SHA2_128S_OFFSET_CHAIN_ADDR] = (uint8_t)chain; +inline void slhdsa_set_chain_addr(const slh_dsa_config *config, + uint8_t addr[32], uint32_t chain) { + if (config->compressed_addresses) { + bssl::CRYPTO_store_u32_be(addr + SLHDSA_ADDR_COMP_OFFSET_CHAIN, chain); + } else { + bssl::CRYPTO_store_u32_be(addr + SLHDSA_ADDR_FULL_OFFSET_CHAIN, chain); + } } -inline void slhdsa_set_hash_addr(uint8_t addr[32], uint32_t hash) { - addr[SLHDSA_SHA2_128S_OFFSET_HASH_ADDR] = (uint8_t)hash; +inline void slhdsa_set_hash_addr(const slh_dsa_config *config, uint8_t addr[32], + uint32_t hash) { + if (config->compressed_addresses) { + bssl::CRYPTO_store_u32_be(addr + SLHDSA_ADDR_COMP_OFFSET_HASH, hash); + } else { + bssl::CRYPTO_store_u32_be(addr + SLHDSA_ADDR_FULL_OFFSET_HASH, hash); + } } -inline void slhdsa_set_keypair_addr(uint8_t addr[32], uint32_t keypair) { - addr[SLHDSA_SHA2_128S_OFFSET_KP_ADDR2] = (uint8_t)(keypair >> 8); - addr[SLHDSA_SHA2_128S_OFFSET_KP_ADDR1] = (uint8_t)keypair; +inline void slhdsa_set_keypair_addr(const slh_dsa_config *config, + uint8_t addr[32], uint32_t keypair) { + if (config->compressed_addresses) { + bssl::CRYPTO_store_u32_be(addr + SLHDSA_ADDR_COMP_OFFSET_KEYPAIR, keypair); + } else { + bssl::CRYPTO_store_u32_be(addr + SLHDSA_ADDR_FULL_OFFSET_KEYPAIR, keypair); + } } -inline void slhdsa_copy_keypair_addr(uint8_t out[32], const uint8_t in[32]) { - OPENSSL_memcpy(out, in, SLHDSA_SHA2_128S_OFFSET_TREE + 8); - out[SLHDSA_SHA2_128S_OFFSET_KP_ADDR2] = in[SLHDSA_SHA2_128S_OFFSET_KP_ADDR2]; - out[SLHDSA_SHA2_128S_OFFSET_KP_ADDR1] = in[SLHDSA_SHA2_128S_OFFSET_KP_ADDR1]; +inline void slhdsa_copy_keypair_addr(const slh_dsa_config *config, + uint8_t out[32], const uint8_t in[32]) { + if (config->compressed_addresses) { + bssl::OPENSSL_memcpy(out, in, SLHDSA_ADDR_COMP_OFFSET_TYPE); + bssl::OPENSSL_memcpy(out + SLHDSA_ADDR_COMP_OFFSET_KEYPAIR, + in + SLHDSA_ADDR_COMP_OFFSET_KEYPAIR, 4); + } else { + bssl::OPENSSL_memcpy(out, in, SLHDSA_ADDR_FULL_OFFSET_TYPE); + bssl::OPENSSL_memcpy(out + SLHDSA_ADDR_FULL_OFFSET_KEYPAIR, + in + SLHDSA_ADDR_FULL_OFFSET_KEYPAIR, 4); + } } -inline void slhdsa_set_layer_addr(uint8_t addr[32], uint32_t layer) { - addr[SLHDSA_SHA2_128S_OFFSET_LAYER] = (uint8_t)layer; +inline void slhdsa_set_layer_addr(const slh_dsa_config *config, + uint8_t addr[32], uint32_t layer) { + if (config->compressed_addresses) { + addr[SLHDSA_ADDR_COMP_OFFSET_LAYER] = (uint8_t)layer; + } else { + bssl::CRYPTO_store_u32_be(addr + SLHDSA_ADDR_FULL_OFFSET_LAYER, layer); + } } -inline void slhdsa_set_tree_addr(uint8_t addr[32], uint64_t tree) { - CRYPTO_store_u64_be(&addr[SLHDSA_SHA2_128S_OFFSET_TREE], tree); +inline void slhdsa_set_tree_addr(const slh_dsa_config *config, uint8_t addr[32], + uint64_t tree) { + if (config->compressed_addresses) { + bssl::CRYPTO_store_u64_be(addr + SLHDSA_ADDR_COMP_OFFSET_TREE, tree); + } else { + // The tree address is 12 bytes in this configuration. Just zero the top + // four bytes. + bssl::OPENSSL_memset(addr + SLHDSA_ADDR_FULL_OFFSET_TREE, 0, 4); + bssl::CRYPTO_store_u64_be(addr + SLHDSA_ADDR_FULL_OFFSET_TREE + 4, tree); + } } -#define SLHDSA_SHA2_128S_ADDR_TYPE_WOTS 0 -#define SLHDSA_SHA2_128S_ADDR_TYPE_WOTSPK 1 -#define SLHDSA_SHA2_128S_ADDR_TYPE_HASHTREE 2 -#define SLHDSA_SHA2_128S_ADDR_TYPE_FORSTREE 3 -#define SLHDSA_SHA2_128S_ADDR_TYPE_FORSPK 4 -#define SLHDSA_SHA2_128S_ADDR_TYPE_WOTSPRF 5 -#define SLHDSA_SHA2_128S_ADDR_TYPE_FORSPRF 6 - -inline void slhdsa_set_type(uint8_t addr[32], uint32_t type) { +inline void slhdsa_set_type(const slh_dsa_config *config, uint8_t addr[32], + uint32_t type) { // FIPS 205 relies on this setting parts of the address to 0, so we do it // here to avoid confusion. // // The behavior here is only correct for the SHA-2 instantiations. - OPENSSL_memset(addr + 10, 0, 12); - addr[SLHDSA_SHA2_128S_OFFSET_TYPE] = (uint8_t)type; + if (config->compressed_addresses) { + bssl::OPENSSL_memset(addr + SLHDSA_ADDR_COMP_ZERO_START, 0, + SLHDSA_ADDR_COMP_ZERO_LEN); + addr[SLHDSA_ADDR_COMP_OFFSET_TYPE] = (uint8_t)type; + } else { + bssl::OPENSSL_memset(addr + SLHDSA_ADDR_FULL_ZERO_START, 0, + SLHDSA_ADDR_FULL_ZERO_LEN); + bssl::CRYPTO_store_u32_be(addr + SLHDSA_ADDR_FULL_OFFSET_TYPE, type); + } } -inline void slhdsa_set_tree_height(uint8_t addr[32], uint32_t tree_height) { - addr[SLHDSA_SHA2_128S_OFFSET_TREE_HGT] = (uint8_t)tree_height; +inline void slhdsa_set_tree_height(const slh_dsa_config *config, + uint8_t addr[32], uint32_t tree_height) { + if (config->compressed_addresses) { + bssl::CRYPTO_store_u32_be(addr + SLHDSA_ADDR_COMP_OFFSET_TREE_HEIGHT, + tree_height); + } else { + bssl::CRYPTO_store_u32_be(addr + SLHDSA_ADDR_FULL_OFFSET_TREE_HEIGHT, + tree_height); + } } -inline void slhdsa_set_tree_index(uint8_t addr[32], uint32_t tree_index) { - CRYPTO_store_u32_be(&addr[SLHDSA_SHA2_128S_OFFSET_TREE_INDEX], tree_index); +inline void slhdsa_set_tree_index(const slh_dsa_config *config, + uint8_t addr[32], uint32_t tree_index) { + if (config->compressed_addresses) { + bssl::CRYPTO_store_u32_be(addr + SLHDSA_ADDR_COMP_OFFSET_TREE_INDEX, + tree_index); + } else { + bssl::CRYPTO_store_u32_be(addr + SLHDSA_ADDR_FULL_OFFSET_TREE_INDEX, + tree_index); + } } -inline uint32_t slhdsa_get_tree_index(uint8_t addr[32]) { - return CRYPTO_load_u32_be(addr + SLHDSA_SHA2_128S_OFFSET_TREE_INDEX); +inline uint32_t slhdsa_get_tree_index(const slh_dsa_config *config, + uint8_t addr[32]) { + if (config->compressed_addresses) { + return bssl::CRYPTO_load_u32_be(addr + SLHDSA_ADDR_COMP_OFFSET_TREE_INDEX); + } + return bssl::CRYPTO_load_u32_be(addr + SLHDSA_ADDR_FULL_OFFSET_TREE_INDEX); } - -#if defined(__cplusplus) -} // extern C -#endif +BSSL_NAMESPACE_END #endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_ADDRESS_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/fips_known_values.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/fips_known_values.inc new file mode 100644 index 00000000..5bff695a --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/fips_known_values.inc @@ -0,0 +1,674 @@ +const uint8_t kExpectedPublicKey[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xbe, 0x6b, 0xd7, 0xe8, 0xe1, 0x98, + 0xea, 0xf6, 0x2d, 0x57, 0x2f, 0x13, 0xfc, 0x79, 0xf2, 0x6f}; + +const uint8_t kExpectedPrivateKey[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xbe, 0x6b, 0xd7, 0xe8, 0xe1, 0x98, 0xea, + 0xf6, 0x2d, 0x57, 0x2f, 0x13, 0xfc, 0x79, 0xf2, 0x6f}; + +const uint8_t kExpectedSignatureSHA256[32] = { + 0x82, 0xd4, 0x09, 0x74, 0x4d, 0x97, 0xae, 0x30, 0x53, 0x18, 0x46, + 0x9f, 0x7b, 0x85, 0x7b, 0x91, 0xd4, 0xe3, 0x33, 0x10, 0xb7, 0x09, + 0xb5, 0x50, 0xa7, 0xc4, 0x8a, 0x46, 0x09, 0x4e, 0xc9, 0xd4}; + +const uint8_t kExpectedSignature[BCM_SLHDSA_SHA2_128S_SIGNATURE_BYTES] = { + 0x3f, 0xd6, 0x91, 0x93, 0xee, 0x97, 0x08, 0xbd, 0xea, 0x11, 0x0b, 0xa2, + 0x9f, 0x23, 0x5f, 0xf2, 0xec, 0x98, 0x88, 0xd1, 0x27, 0x61, 0xf8, 0x4d, + 0xc6, 0xe3, 0xf0, 0xd7, 0xeb, 0x48, 0xd0, 0x5c, 0xac, 0xf6, 0xe8, 0x7f, + 0xb7, 0xe9, 0x58, 0xf2, 0x21, 0x47, 0x21, 0x64, 0x03, 0xf1, 0xcd, 0x17, + 0xab, 0x8d, 0xfb, 0x3d, 0xf1, 0x60, 0xd8, 0xc5, 0xaa, 0x43, 0xcf, 0x56, + 0x2d, 0x82, 0x61, 0x99, 0xcc, 0x72, 0x56, 0x12, 0x3f, 0x06, 0xdb, 0x84, + 0x2d, 0xd8, 0x31, 0x7e, 0x60, 0x1e, 0x4d, 0x8c, 0xf2, 0x15, 0x57, 0xa3, + 0x78, 0x90, 0x59, 0xbe, 0x6a, 0x7e, 0xc7, 0xc7, 0xe2, 0x6d, 0x6c, 0x81, + 0xf1, 0xc7, 0xc0, 0x2a, 0x98, 0xdd, 0x64, 0x05, 0x86, 0x99, 0x1f, 0x09, + 0x16, 0xef, 0xad, 0xd6, 0x13, 0x7a, 0xf7, 0x8c, 0x38, 0xd3, 0x2e, 0xde, + 0x10, 0xd6, 0x6e, 0x38, 0x24, 0xa2, 0x24, 0x40, 0xf5, 0x7c, 0x63, 0x42, + 0xf1, 0xab, 0x72, 0x01, 0xc4, 0x54, 0xf6, 0x66, 0x34, 0x32, 0x39, 0xbb, + 0x35, 0x13, 0x45, 0xd1, 0xea, 0x6d, 0x87, 0xff, 0x8b, 0x4a, 0x65, 0x7f, + 0x84, 0xbd, 0xb1, 0x03, 0xe1, 0xd7, 0x43, 0xea, 0xbe, 0xe3, 0x78, 0xa5, + 0xc5, 0xf5, 0xf9, 0xb2, 0x00, 0xe3, 0x13, 0x06, 0x36, 0xf3, 0xe8, 0xee, + 0x07, 0xf2, 0x03, 0x48, 0xfd, 0x51, 0x1b, 0xb5, 0x10, 0xaa, 0x1d, 0xa9, + 0x99, 0xad, 0x10, 0xc4, 0x59, 0xbf, 0x66, 0xdd, 0x27, 0x8d, 0xd8, 0x6a, + 0x53, 0xe5, 0x9d, 0x1a, 0xc1, 0x17, 0x36, 0x2e, 0x2e, 0xaf, 0xc0, 0xc8, + 0x96, 0x89, 0xbc, 0x4e, 0x7c, 0xa5, 0xcc, 0xa9, 0x2a, 0x76, 0xc3, 0x1d, + 0xa0, 0xa1, 0xa0, 0x27, 0xbf, 0x93, 0x21, 0xf0, 0x67, 0x7c, 0x10, 0x5f, + 0x7f, 0x3c, 0x68, 0xbd, 0x7b, 0x2d, 0x0a, 0x4a, 0xde, 0x1b, 0xd4, 0xaa, + 0x85, 0x5c, 0xa1, 0x56, 0x9e, 0x61, 0x6c, 0x97, 0x65, 0xae, 0xc4, 0x13, + 0xa8, 0x1a, 0x82, 0x87, 0x66, 0x1b, 0x72, 0x27, 0x43, 0xca, 0xb8, 0xc6, + 0x4e, 0xe9, 0xbe, 0x4a, 0x77, 0x66, 0xea, 0xf4, 0xa0, 0x71, 0x94, 0x52, + 0xee, 0xc6, 0xef, 0x38, 0x7b, 0x24, 0x94, 0xc3, 0x7a, 0xc9, 0x35, 0x93, + 0x5b, 0x19, 0xc5, 0x4d, 0xf1, 0x7d, 0xb0, 0xb9, 0x60, 0xaf, 0x1e, 0xa9, + 0x24, 0x85, 0x92, 0x50, 0x78, 0x13, 0x1d, 0xb6, 0x6d, 0x4a, 0x4c, 0x1b, + 0xa0, 0x51, 0x86, 0xc9, 0xb4, 0x79, 0xe5, 0x09, 0x4e, 0x61, 0xf4, 0x80, + 0x07, 0x04, 0xd6, 0x44, 0x7b, 0xf6, 0xc0, 0x90, 0xc0, 0x46, 0xce, 0xa3, + 0x92, 0x1a, 0xfd, 0x85, 0xd7, 0xbc, 0xd5, 0x60, 0x0d, 0xcb, 0xc3, 0x02, + 0xbc, 0x82, 0x75, 0xe4, 0x1f, 0xc4, 0xce, 0x5f, 0x35, 0x6b, 0xdf, 0x31, + 0x1e, 0x39, 0x18, 0xcd, 0x4c, 0xc7, 0xcc, 0x1e, 0x20, 0x19, 0x4a, 0x87, + 0xf4, 0x07, 0xb3, 0x15, 0x02, 0xe4, 0x1a, 0x63, 0x1c, 0xa1, 0x3c, 0x0b, + 0xae, 0x33, 0x2c, 0x9a, 0xc4, 0x23, 0x02, 0x44, 0x96, 0x14, 0x09, 0x64, + 0xea, 0x84, 0x08, 0x52, 0xed, 0x26, 0x2c, 0x29, 0xc0, 0x56, 0x34, 0xaa, + 0x20, 0xba, 0x44, 0x39, 0x8d, 0x3e, 0xce, 0xed, 0x6a, 0x3f, 0xca, 0xcd, + 0xd3, 0xbe, 0xa0, 0xee, 0x49, 0xb4, 0xdc, 0x24, 0xa7, 0xe1, 0x7a, 0x89, + 0x8f, 0x75, 0xb7, 0x19, 0x71, 0xc6, 0x5e, 0x14, 0x9c, 0xbc, 0xde, 0xd7, + 0x52, 0xd9, 0x32, 0x6a, 0xd3, 0xd4, 0xc5, 0x5f, 0x39, 0xf0, 0xd4, 0xda, + 0xe2, 0x50, 0xfc, 0x14, 0x73, 0xd2, 0xc2, 0x28, 0xd0, 0x84, 0x46, 0xed, + 0xe9, 0x7c, 0x40, 0x16, 0xec, 0x72, 0xbf, 0x77, 0xef, 0xac, 0xe8, 0xce, + 0xbf, 0x58, 0x65, 0x29, 0x9d, 0x0d, 0xe2, 0xc9, 0xbf, 0x19, 0xdd, 0x9b, + 0x8c, 0xb9, 0x1c, 0x32, 0x24, 0x3b, 0xa5, 0x7a, 0x1f, 0x78, 0x85, 0x77, + 0xb0, 0x6c, 0x42, 0xb8, 0xc0, 0x75, 0xf5, 0xc0, 0x45, 0xe3, 0x44, 0x7c, + 0xbd, 0x75, 0x6c, 0x5b, 0xe4, 0x91, 0x72, 0x9a, 0x5f, 0xe7, 0x1e, 0xe9, + 0xa0, 0x6f, 0x26, 0xbb, 0x31, 0x9d, 0xe4, 0xec, 0x32, 0xae, 0x8d, 0xae, + 0x7d, 0x14, 0x33, 0x04, 0x19, 0x26, 0x42, 0x09, 0x91, 0x0c, 0x5f, 0xaa, + 0x1a, 0x74, 0xfa, 0x31, 0x67, 0xad, 0x71, 0x49, 0xd8, 0xf3, 0xe7, 0x8c, + 0x91, 0x38, 0x0e, 0x10, 0x5b, 0xe5, 0x1e, 0xd2, 0x9a, 0x0c, 0x4d, 0x7b, + 0x60, 0xac, 0x6a, 0x94, 0x9d, 0x4f, 0x8c, 0xd0, 0x1d, 0x2f, 0xf7, 0x3d, + 0x06, 0x46, 0xc8, 0xd6, 0x25, 0x86, 0xfe, 0x67, 0xf2, 0x01, 0xe1, 0x73, + 0x02, 0xa1, 0xdd, 0xf2, 0x6d, 0xe6, 0x9d, 0xb9, 0x83, 0x21, 0x38, 0x74, + 0x04, 0xec, 0xe3, 0x9e, 0x21, 0xc0, 0xed, 0x91, 0x47, 0x46, 0x44, 0x6e, + 0xf7, 0x76, 0xe7, 0xad, 0xbe, 0xef, 0xfe, 0xcd, 0xda, 0x1d, 0x60, 0xc8, + 0x5f, 0x92, 0xd7, 0x21, 0xb4, 0x3c, 0x11, 0x5d, 0x24, 0x50, 0x44, 0xb2, + 0xf8, 0x59, 0x7e, 0xc4, 0x7a, 0x25, 0xea, 0x19, 0x4f, 0x1c, 0x8e, 0xb5, + 0x0d, 0xd6, 0x7a, 0xe6, 0x0a, 0x11, 0x1f, 0x6b, 0x28, 0x9f, 0xc0, 0x02, + 0xc6, 0x1b, 0xca, 0x06, 0xdd, 0x59, 0xa3, 0xe0, 0xd0, 0x25, 0x3e, 0x10, + 0x0a, 0x49, 0x54, 0xdc, 0xe5, 0x07, 0x8b, 0xcc, 0xa6, 0x3d, 0x41, 0xe5, + 0x00, 0x70, 0xf7, 0x13, 0xed, 0x63, 0x7a, 0x4b, 0x69, 0x21, 0xaa, 0xf2, + 0xd5, 0xf7, 0xa4, 0x9c, 0x52, 0x51, 0xef, 0xb9, 0xef, 0xee, 0x3b, 0xa4, + 0xdf, 0x16, 0x29, 0x08, 0x0f, 0x6f, 0xbd, 0x4e, 0x53, 0xa2, 0x5c, 0x75, + 0x5f, 0x04, 0x5a, 0xdf, 0x48, 0xd6, 0xeb, 0xf9, 0x80, 0x85, 0xd3, 0x1d, + 0x7f, 0x23, 0x01, 0x04, 0x8b, 0x78, 0xba, 0xba, 0xc3, 0x74, 0xbe, 0x7d, + 0x5b, 0x3e, 0x65, 0x3d, 0xcd, 0x5d, 0x96, 0xe3, 0x40, 0x40, 0x7f, 0x50, + 0xfe, 0xa0, 0x53, 0xa6, 0xd9, 0x71, 0x15, 0x33, 0x39, 0x24, 0x83, 0xee, + 0x69, 0x6f, 0x3c, 0x0a, 0x5e, 0xdc, 0x83, 0xb9, 0x8a, 0x1f, 0x7f, 0x67, + 0x39, 0xb2, 0x58, 0xe4, 0x48, 0xd0, 0xac, 0x75, 0xba, 0x57, 0x13, 0x37, + 0xaa, 0x0b, 0xd5, 0x02, 0x89, 0x01, 0x5f, 0xe8, 0x75, 0xcc, 0x2d, 0x76, + 0x05, 0xde, 0x57, 0xa2, 0xac, 0x48, 0x95, 0xce, 0xa7, 0x1d, 0xf6, 0xdb, + 0x64, 0xff, 0xde, 0x85, 0x7e, 0x13, 0xb9, 0x58, 0x4f, 0xdd, 0xf0, 0xcb, + 0x9a, 0x31, 0x7e, 0xc5, 0x61, 0x41, 0x97, 0x56, 0xe4, 0xfa, 0xb1, 0xcb, + 0x1e, 0xb3, 0xfd, 0x9c, 0xfd, 0xfd, 0x81, 0x84, 0x78, 0xca, 0xbd, 0xf1, + 0x17, 0xec, 0xcb, 0x49, 0xa7, 0x8e, 0xe8, 0xc6, 0xc5, 0x9c, 0x30, 0xf4, + 0xc5, 0xac, 0x2a, 0x0e, 0x36, 0x72, 0x03, 0x7d, 0xf2, 0xac, 0xf9, 0x88, + 0x84, 0xb6, 0xae, 0x16, 0x77, 0x96, 0x81, 0x7b, 0xfc, 0x17, 0x07, 0x8f, + 0xc2, 0x74, 0xd9, 0xce, 0x57, 0xfc, 0x33, 0x53, 0xec, 0x85, 0x0e, 0x55, + 0x2e, 0xe3, 0xad, 0x5b, 0xeb, 0x47, 0x8d, 0xf6, 0xb4, 0xb9, 0xc9, 0xb7, + 0x9a, 0x63, 0x0e, 0xd9, 0x56, 0xa1, 0x2b, 0x05, 0x39, 0x02, 0xf8, 0x28, + 0xdf, 0x67, 0xa7, 0xce, 0x57, 0xfd, 0xd1, 0xb4, 0x55, 0x26, 0x85, 0xe7, + 0xd2, 0x5b, 0x90, 0x26, 0xe1, 0x25, 0x5e, 0x73, 0x12, 0xcc, 0x65, 0x8e, + 0xdc, 0x1c, 0x64, 0xe9, 0x2e, 0x58, 0xde, 0x70, 0xc3, 0xc6, 0xc9, 0x75, + 0x35, 0x0a, 0x0f, 0x60, 0x35, 0xb4, 0x9f, 0xcb, 0x52, 0x20, 0xc9, 0x36, + 0xb2, 0x52, 0xbb, 0x35, 0x61, 0xf9, 0xf2, 0xc0, 0xd3, 0x50, 0x08, 0xf6, + 0x73, 0x7d, 0xcb, 0x12, 0xd2, 0xd7, 0x4c, 0x56, 0x59, 0xb9, 0x74, 0xec, + 0xee, 0x4c, 0x93, 0x1d, 0x9d, 0x73, 0x79, 0xe6, 0xa9, 0x2a, 0x98, 0x22, + 0x77, 0x80, 0x84, 0x73, 0x78, 0xe2, 0x8a, 0xec, 0x1e, 0x08, 0x6f, 0x49, + 0x64, 0xea, 0x79, 0x99, 0xb1, 0xec, 0x19, 0x6e, 0x65, 0xbd, 0xaa, 0x28, + 0x81, 0x4a, 0xe7, 0x70, 0x44, 0xc6, 0xa1, 0xbc, 0xe3, 0x72, 0x8c, 0xa1, + 0x13, 0x8a, 0x17, 0x16, 0xcc, 0xfb, 0x03, 0x20, 0x36, 0xb6, 0x6f, 0x4c, + 0x52, 0xc4, 0xc6, 0x7e, 0x61, 0x08, 0x56, 0x27, 0xb0, 0xf9, 0x96, 0x44, + 0xd9, 0x62, 0x4a, 0x29, 0xea, 0xf2, 0x33, 0x2b, 0x68, 0x45, 0xe0, 0x50, + 0x97, 0x6a, 0x1c, 0x59, 0x89, 0x43, 0x60, 0xc2, 0x5f, 0x31, 0xfe, 0xc7, + 0x00, 0xcb, 0x6a, 0xe0, 0xcb, 0x1b, 0x50, 0x43, 0x18, 0xd1, 0x67, 0xbc, + 0x62, 0xcf, 0xb8, 0xe9, 0x77, 0x81, 0x1d, 0x12, 0x97, 0xa4, 0x87, 0xbe, + 0xa2, 0x16, 0x08, 0xf6, 0x1f, 0x42, 0x40, 0x51, 0x65, 0xe3, 0x72, 0x21, + 0xef, 0x72, 0xba, 0xff, 0xa7, 0xfa, 0x3b, 0xac, 0xd7, 0xc9, 0x60, 0xa1, + 0x5e, 0xae, 0xa5, 0x19, 0x80, 0xfa, 0x5c, 0xd8, 0xf0, 0x1a, 0xf4, 0x0f, + 0xb2, 0x5f, 0x57, 0x9a, 0xd2, 0x1b, 0x7c, 0xef, 0xb9, 0x24, 0xd0, 0x30, + 0x0e, 0x92, 0xc9, 0x44, 0x05, 0xcf, 0x16, 0x31, 0xc4, 0x3e, 0xa2, 0x94, + 0x1f, 0x69, 0xad, 0x0e, 0xcf, 0x7f, 0xce, 0x41, 0x9a, 0xaf, 0x89, 0xc6, + 0xbd, 0x65, 0x8c, 0x65, 0xca, 0x36, 0xea, 0xd4, 0x78, 0x04, 0x1b, 0x62, + 0x14, 0x2f, 0x37, 0xbe, 0x9b, 0xbe, 0xfd, 0xf4, 0x9d, 0x3c, 0x48, 0xe4, + 0x46, 0x71, 0x0d, 0x07, 0x93, 0xfa, 0x86, 0x6c, 0xa7, 0xce, 0xe9, 0x6a, + 0xf3, 0xa1, 0x72, 0x19, 0x0a, 0xc9, 0xb9, 0xc4, 0x3b, 0x76, 0x2f, 0x16, + 0x82, 0x85, 0xbc, 0x4c, 0x46, 0x32, 0x37, 0xc7, 0x19, 0xc5, 0x24, 0xe1, + 0x0f, 0xe2, 0x8f, 0x6d, 0x62, 0x6b, 0x6c, 0x9e, 0xc8, 0x15, 0x01, 0x93, + 0x5b, 0x03, 0x44, 0x6e, 0xd0, 0xdc, 0xbd, 0x29, 0x2f, 0x2e, 0x89, 0x11, + 0x24, 0x37, 0xfa, 0xff, 0x83, 0x51, 0x1b, 0x31, 0x5e, 0xc6, 0x71, 0x0b, + 0xbf, 0x64, 0xb0, 0xca, 0x01, 0xfd, 0x49, 0x64, 0x05, 0xe2, 0xe7, 0x9e, + 0x6e, 0xfe, 0xce, 0x98, 0x86, 0xef, 0x16, 0xec, 0x19, 0x66, 0xbe, 0x0d, + 0x8a, 0x99, 0xbb, 0xbf, 0x39, 0xa8, 0x85, 0xeb, 0x14, 0x51, 0x2d, 0x18, + 0xd5, 0x93, 0x6f, 0x78, 0x7a, 0x5e, 0xa1, 0xee, 0xc0, 0xc3, 0x93, 0x68, + 0x04, 0x0c, 0xd4, 0xfe, 0x6a, 0xf7, 0x05, 0x78, 0xac, 0xcf, 0xee, 0x9f, + 0x92, 0x53, 0x8d, 0xd4, 0x99, 0x75, 0x27, 0x7f, 0x79, 0x6c, 0x97, 0x52, + 0x34, 0x08, 0x31, 0xad, 0x4a, 0x54, 0x34, 0xab, 0x33, 0x2e, 0x16, 0x54, + 0xcd, 0x7a, 0x75, 0x96, 0x29, 0x72, 0x3f, 0x40, 0x2e, 0xa4, 0xc8, 0x1c, + 0x67, 0xb6, 0x37, 0x15, 0x51, 0x64, 0x83, 0x69, 0xd7, 0x62, 0xcf, 0x8f, + 0x34, 0x18, 0x46, 0x98, 0x5c, 0x8b, 0x61, 0x5f, 0x73, 0xe2, 0xc6, 0xe2, + 0x86, 0x82, 0xf5, 0xee, 0x1e, 0x2d, 0xb2, 0x73, 0xb0, 0x1b, 0x69, 0xf1, + 0x23, 0x47, 0x0d, 0xe6, 0x30, 0xe6, 0xed, 0x91, 0x69, 0x23, 0x23, 0xdd, + 0x28, 0x64, 0x56, 0xce, 0x98, 0xa1, 0xfd, 0x93, 0x8b, 0xd3, 0xc0, 0xb7, + 0xdd, 0xc8, 0x4a, 0x16, 0xe4, 0x75, 0xa3, 0xef, 0xba, 0x20, 0x92, 0x42, + 0xa8, 0x1b, 0xbc, 0x54, 0x88, 0x3e, 0x1b, 0xf0, 0xa1, 0x1f, 0xeb, 0x5d, + 0xcb, 0x49, 0x61, 0x19, 0xf3, 0x7f, 0x06, 0xe3, 0xd5, 0x29, 0xbc, 0x1a, + 0x54, 0x53, 0xb6, 0xf3, 0x33, 0x50, 0x01, 0xf5, 0xb2, 0xcf, 0x1a, 0x2a, + 0x17, 0x8f, 0xfa, 0x1f, 0x41, 0x47, 0x6d, 0x61, 0x60, 0x02, 0x19, 0x36, + 0x06, 0xfb, 0x66, 0xfc, 0x42, 0xe3, 0x87, 0xc6, 0x14, 0x82, 0x2e, 0x15, + 0xe6, 0x29, 0xbf, 0x44, 0x4d, 0xb4, 0x85, 0xa9, 0x6e, 0x81, 0x75, 0xb9, + 0x09, 0x8d, 0xcc, 0x57, 0x13, 0x4c, 0x43, 0xca, 0x94, 0x00, 0x5b, 0xb5, + 0x23, 0xbe, 0xf6, 0x3a, 0x1d, 0x42, 0x15, 0xa0, 0xea, 0x2e, 0x89, 0x78, + 0x7f, 0xba, 0x6c, 0xe4, 0x27, 0x4c, 0xb6, 0x86, 0x73, 0x0e, 0x9c, 0x8c, + 0xef, 0x14, 0xe4, 0x35, 0x43, 0x6d, 0x56, 0xcd, 0x4d, 0xab, 0x48, 0x96, + 0x18, 0xb0, 0x4f, 0x03, 0xad, 0xec, 0x62, 0xd3, 0x34, 0x5a, 0xd0, 0xff, + 0x14, 0xb1, 0xaf, 0x92, 0xc4, 0x20, 0xaf, 0x2d, 0x17, 0x5e, 0x22, 0x51, + 0x5c, 0x66, 0x09, 0x20, 0x1f, 0x50, 0x0c, 0xbc, 0xe0, 0xf5, 0x6e, 0x85, + 0x31, 0x48, 0x80, 0xef, 0xf6, 0xef, 0x7c, 0xf5, 0xf3, 0x0e, 0x6b, 0x8d, + 0x0b, 0x94, 0x5d, 0xaa, 0x27, 0x81, 0xd3, 0x9b, 0x07, 0xe0, 0x22, 0x0a, + 0xce, 0x9d, 0xa1, 0x79, 0x38, 0xe2, 0x6d, 0x58, 0xa7, 0xde, 0x9b, 0xb0, + 0x25, 0x0e, 0x6b, 0x25, 0x1e, 0xac, 0x48, 0xb0, 0x34, 0x27, 0x42, 0x30, + 0xf5, 0xdb, 0x35, 0x4d, 0xf3, 0x1f, 0xbc, 0x58, 0x2a, 0xeb, 0x86, 0x82, + 0x6e, 0x9a, 0x0b, 0xf6, 0xdb, 0xa6, 0x18, 0x12, 0x42, 0x17, 0x5c, 0xb3, + 0xe9, 0x49, 0x5f, 0x2a, 0xf9, 0x81, 0x35, 0x2f, 0x2b, 0x92, 0xaa, 0x0d, + 0x6b, 0xa7, 0xe1, 0xed, 0x55, 0xa4, 0xf1, 0xef, 0xa4, 0x6b, 0x50, 0x85, + 0xe3, 0xcd, 0x9a, 0xb2, 0xc7, 0xd9, 0xdd, 0x46, 0x6a, 0xfc, 0x2c, 0xed, + 0xd8, 0xf9, 0x4d, 0x8a, 0xb4, 0x30, 0xa0, 0xd0, 0x08, 0xf8, 0xf0, 0x61, + 0xc5, 0x39, 0xa2, 0xfd, 0x78, 0x65, 0x41, 0x5a, 0x52, 0x06, 0xfe, 0x50, + 0x74, 0xe2, 0x80, 0xb2, 0x22, 0x2d, 0x96, 0xbf, 0xd2, 0x4f, 0xc9, 0x00, + 0x36, 0x58, 0xa7, 0x67, 0x7d, 0xfc, 0xc0, 0xae, 0x34, 0x69, 0xe3, 0x16, + 0xbe, 0x59, 0x9e, 0x01, 0x9e, 0x39, 0x0b, 0x3d, 0x16, 0x80, 0x8b, 0xfb, + 0xe0, 0x58, 0x81, 0xcd, 0xd1, 0x2c, 0x66, 0x9a, 0xe5, 0x0b, 0x4a, 0xec, + 0xb7, 0x45, 0x7f, 0x98, 0xf2, 0xfb, 0xbe, 0x2b, 0xc8, 0xdd, 0x48, 0x95, + 0x22, 0xde, 0x8e, 0xb8, 0xb8, 0x4c, 0x09, 0xe8, 0x9e, 0x34, 0x4b, 0xab, + 0xe3, 0xa1, 0x19, 0x56, 0xb6, 0x08, 0x67, 0x29, 0x47, 0xba, 0x84, 0xe5, + 0x5c, 0x7d, 0x81, 0x7c, 0x8e, 0x48, 0x0a, 0xce, 0x9f, 0x61, 0xfd, 0x26, + 0x94, 0xe1, 0x35, 0x43, 0x60, 0xe4, 0x5c, 0x11, 0x26, 0x47, 0xab, 0x1b, + 0x0e, 0x24, 0x8b, 0x25, 0x51, 0x6e, 0x21, 0x39, 0x36, 0xa6, 0x46, 0x4c, + 0x93, 0x8d, 0xf8, 0xb1, 0xd6, 0x28, 0xdd, 0x21, 0x43, 0xf0, 0xa2, 0x5d, + 0x2f, 0xbe, 0x67, 0xe3, 0x89, 0x7a, 0xe5, 0xa2, 0x22, 0x3f, 0xf7, 0x0a, + 0xcd, 0xc4, 0xcc, 0xde, 0x81, 0xf1, 0x03, 0xa6, 0xac, 0x29, 0xa3, 0xbe, + 0xdc, 0x3a, 0x84, 0x81, 0x98, 0x33, 0x97, 0xa5, 0xe2, 0x93, 0x98, 0xbd, + 0x28, 0x7c, 0x78, 0xed, 0xdb, 0x30, 0x26, 0x11, 0x87, 0x32, 0x6f, 0xeb, + 0xb0, 0x36, 0x05, 0xcf, 0xe3, 0x28, 0xfc, 0x3e, 0x71, 0xd3, 0x7c, 0x8e, + 0xcd, 0xa9, 0xb4, 0x8b, 0x6e, 0x45, 0xdb, 0xc2, 0x48, 0xdf, 0x7f, 0xb8, + 0x8a, 0x5b, 0x43, 0xc0, 0x41, 0x25, 0xe7, 0x0a, 0xe5, 0x02, 0x56, 0x21, + 0xa1, 0x71, 0xa5, 0xee, 0x13, 0x9f, 0xd7, 0x6b, 0xdb, 0xfa, 0x28, 0x43, + 0x58, 0x76, 0x2a, 0x32, 0x89, 0x9b, 0x11, 0x7c, 0xc8, 0xe5, 0x71, 0xe6, + 0x2e, 0x08, 0xe1, 0x7a, 0xe5, 0x96, 0x30, 0x61, 0xb1, 0xd9, 0x0a, 0xe5, + 0x39, 0x60, 0xaa, 0xf9, 0x3f, 0x7f, 0x88, 0xc7, 0x23, 0xa9, 0x02, 0xe1, + 0xbd, 0xa9, 0xcd, 0xb7, 0xee, 0x6c, 0x67, 0xc7, 0x1b, 0xe0, 0xe1, 0x22, + 0x08, 0xbe, 0xdb, 0xf6, 0x2b, 0x0d, 0x61, 0xc7, 0x62, 0x5c, 0x5a, 0x9c, + 0xb0, 0xd0, 0x6a, 0x7f, 0xd4, 0x4b, 0x43, 0x4e, 0x93, 0x69, 0xf6, 0x43, + 0xc7, 0xbd, 0x78, 0xfe, 0xf3, 0x2f, 0xc8, 0x1f, 0x6c, 0xf0, 0x13, 0x9d, + 0xff, 0x46, 0xfc, 0xe9, 0x09, 0xe3, 0xaf, 0x47, 0x83, 0x71, 0x99, 0x74, + 0xa1, 0xce, 0xa8, 0x35, 0x18, 0x29, 0xa4, 0xbd, 0x4a, 0x84, 0x55, 0x05, + 0x29, 0x53, 0x2f, 0xa5, 0xad, 0xa7, 0xf2, 0x1c, 0x45, 0x13, 0xa3, 0xb0, + 0xa9, 0x11, 0x80, 0xd6, 0x22, 0xff, 0x64, 0x3e, 0x39, 0xa0, 0x15, 0x58, + 0x7f, 0x08, 0x99, 0x08, 0xff, 0x8e, 0x5f, 0x73, 0x98, 0x17, 0x3d, 0x5e, + 0xe6, 0xcd, 0x2d, 0xdf, 0xd1, 0x32, 0x2b, 0x8c, 0x08, 0xa6, 0xdb, 0x51, + 0x2a, 0x5f, 0xac, 0xad, 0x7a, 0x9b, 0x4c, 0x82, 0x25, 0xad, 0x33, 0x7f, + 0x30, 0xc7, 0x48, 0xbd, 0xb4, 0xf5, 0x0d, 0x22, 0xd3, 0xf8, 0x47, 0x58, + 0xd3, 0x17, 0x65, 0x81, 0xe4, 0x07, 0xa0, 0x32, 0x7e, 0xee, 0x30, 0xe9, + 0x17, 0xaa, 0xa0, 0x0b, 0xd7, 0x97, 0x25, 0xa7, 0xdb, 0xfe, 0xab, 0xd2, + 0x3c, 0x9b, 0x6b, 0xdf, 0xa6, 0x87, 0xa3, 0xc0, 0x59, 0xb4, 0x08, 0x11, + 0xd4, 0x94, 0x49, 0x83, 0x70, 0x5f, 0x5b, 0x2d, 0x09, 0xd8, 0x53, 0x25, + 0xb6, 0xd9, 0x91, 0x32, 0xd3, 0x94, 0x79, 0xbb, 0x4d, 0xf7, 0xb6, 0x92, + 0xd3, 0xf4, 0x08, 0x50, 0xda, 0x7d, 0x91, 0x69, 0xad, 0xc3, 0x59, 0x4d, + 0xc0, 0x1c, 0x14, 0xf2, 0x95, 0xd3, 0xea, 0xa8, 0x85, 0xa3, 0x93, 0x62, + 0x73, 0x68, 0x4c, 0x36, 0x49, 0x35, 0x88, 0xf0, 0xe1, 0xc8, 0x29, 0xab, + 0x59, 0x4f, 0xef, 0x2c, 0x4c, 0x07, 0xbd, 0xf3, 0x05, 0x24, 0x41, 0x46, + 0x92, 0x66, 0x66, 0x79, 0x92, 0x32, 0x87, 0xcb, 0x90, 0x11, 0x2d, 0x54, + 0xda, 0x6d, 0x64, 0x72, 0xae, 0x7d, 0x19, 0x50, 0x61, 0x46, 0xd9, 0x58, + 0x2d, 0x28, 0x0d, 0x33, 0x7b, 0x17, 0x01, 0x61, 0x44, 0x77, 0x7e, 0x06, + 0x2b, 0x41, 0x88, 0xe6, 0x92, 0x9c, 0x69, 0xa8, 0x89, 0x9f, 0x4a, 0xa4, + 0x6f, 0x31, 0xa5, 0x68, 0xff, 0xdb, 0xb6, 0xe3, 0x0c, 0x3f, 0xc6, 0x24, + 0x5e, 0xfc, 0x0e, 0x31, 0x32, 0x64, 0xec, 0x3f, 0xe7, 0x7a, 0x29, 0x16, + 0x8f, 0xed, 0x6a, 0xb7, 0x96, 0x77, 0x29, 0xa3, 0xfe, 0x1e, 0x6b, 0x54, + 0x91, 0xe9, 0xbb, 0x38, 0x65, 0x70, 0x8c, 0x4e, 0x50, 0x39, 0x5e, 0x63, + 0xe4, 0x49, 0x33, 0x61, 0xb9, 0x92, 0x92, 0x51, 0xe9, 0x31, 0xf6, 0x5c, + 0x21, 0x1a, 0x53, 0xbf, 0x4a, 0xe1, 0xbc, 0x1f, 0x61, 0x66, 0x3d, 0x83, + 0x8c, 0x27, 0x17, 0x53, 0xbd, 0xf4, 0x3d, 0x13, 0xe3, 0xfe, 0x58, 0x60, + 0x12, 0x78, 0x3b, 0xb1, 0xd7, 0x94, 0x87, 0xe2, 0x3e, 0xc2, 0x16, 0x43, + 0x4e, 0xc8, 0xce, 0x43, 0xbc, 0x4a, 0xe4, 0xba, 0xd6, 0xfa, 0xfa, 0x7e, + 0x13, 0xd3, 0x28, 0x8f, 0xd2, 0x2b, 0x0b, 0x93, 0x8d, 0x42, 0xe8, 0xd2, + 0x50, 0x34, 0x31, 0xd8, 0xb3, 0xa7, 0x1c, 0x93, 0x3d, 0x80, 0x8f, 0x3f, + 0xee, 0x7d, 0x3c, 0xd1, 0xcc, 0x2a, 0x99, 0x39, 0xfd, 0x8f, 0xed, 0x8e, + 0x85, 0x51, 0x20, 0x04, 0xa7, 0xd7, 0x34, 0x83, 0x20, 0x7c, 0x91, 0x20, + 0x96, 0xe6, 0x88, 0xd6, 0x29, 0x99, 0xff, 0x18, 0xa9, 0x3b, 0x3e, 0x41, + 0x42, 0x80, 0x14, 0x3b, 0xf2, 0xc4, 0x24, 0x4e, 0x18, 0x04, 0xa0, 0xfb, + 0x17, 0x00, 0x2b, 0xf7, 0x44, 0x22, 0x4b, 0x7c, 0x38, 0xb6, 0x66, 0x4c, + 0x56, 0x85, 0xb2, 0x82, 0x92, 0xe8, 0x7b, 0x76, 0x33, 0x59, 0xe8, 0x09, + 0xd1, 0xef, 0xa0, 0x1b, 0x5b, 0xc2, 0xb1, 0x01, 0x6d, 0x7f, 0xbb, 0x37, + 0x72, 0x3f, 0xcd, 0x20, 0x6f, 0x2d, 0x9c, 0xfc, 0xfc, 0x1c, 0x2c, 0x24, + 0x3f, 0x30, 0xcd, 0xf5, 0x91, 0x0a, 0x09, 0xa5, 0xeb, 0x97, 0xb0, 0xc4, + 0x2c, 0xa3, 0x95, 0x57, 0xea, 0x59, 0x15, 0xc7, 0x81, 0xdf, 0x64, 0x99, + 0x1b, 0x20, 0x8d, 0xe0, 0x29, 0x7c, 0x23, 0x16, 0x3c, 0x8e, 0x2e, 0x0b, + 0xff, 0x02, 0xdc, 0x6f, 0x24, 0x1e, 0xfc, 0xac, 0x0f, 0x16, 0x38, 0xde, + 0x5c, 0x9c, 0x5f, 0x48, 0x13, 0xfb, 0xac, 0xbd, 0x99, 0x5e, 0x7e, 0xe0, + 0xcc, 0x3c, 0x21, 0x17, 0xfa, 0x67, 0x53, 0x31, 0xb3, 0x99, 0x98, 0x05, + 0x2d, 0xa1, 0xb2, 0x72, 0xf6, 0xe0, 0x73, 0xb5, 0x6e, 0xc7, 0xa0, 0x7f, + 0xfa, 0x75, 0x89, 0x20, 0x4c, 0x84, 0xa1, 0x2b, 0x39, 0x4a, 0xd1, 0xf5, + 0x36, 0xfa, 0x5f, 0xb2, 0x7e, 0x75, 0x1b, 0x21, 0xae, 0x30, 0x83, 0x14, + 0x3d, 0xf6, 0x4c, 0x3a, 0xd8, 0x1e, 0x05, 0xed, 0x93, 0xbf, 0xd3, 0xb2, + 0x46, 0x23, 0x43, 0x3d, 0x78, 0xf9, 0x94, 0x78, 0xae, 0x20, 0x8b, 0x49, + 0x8c, 0xac, 0x8f, 0x41, 0xe4, 0x5d, 0x96, 0x25, 0xd6, 0xd9, 0xde, 0x8b, + 0x6a, 0xcd, 0x37, 0x22, 0x1b, 0xd7, 0xca, 0x8a, 0xa3, 0x79, 0x7b, 0x3d, + 0x3e, 0x2d, 0xe3, 0x09, 0xa4, 0xbf, 0x9a, 0x48, 0x63, 0xa5, 0x88, 0xbf, + 0xb6, 0xfb, 0x7b, 0xcc, 0x29, 0xd2, 0x2f, 0xdc, 0x36, 0xab, 0xd6, 0x46, + 0xae, 0xf7, 0xca, 0xa9, 0xb4, 0x14, 0xae, 0xfe, 0x12, 0x62, 0xb9, 0xce, + 0x4b, 0x99, 0xf8, 0xa5, 0x59, 0x81, 0x83, 0x68, 0x48, 0x44, 0x75, 0xab, + 0xb2, 0x12, 0x89, 0x1c, 0xe7, 0x3d, 0x9b, 0x19, 0xa2, 0x6c, 0xa5, 0x62, + 0x48, 0xed, 0x1c, 0xba, 0x89, 0x61, 0xe4, 0x24, 0x8a, 0xd8, 0x87, 0xb7, + 0x64, 0xc8, 0x09, 0x20, 0x83, 0x50, 0x2b, 0xe7, 0xb9, 0x8c, 0x99, 0x05, + 0x18, 0xd3, 0xf5, 0x19, 0xec, 0x75, 0x83, 0x4c, 0x80, 0x20, 0x2b, 0x6a, + 0xa0, 0x75, 0x6b, 0x62, 0xd1, 0x02, 0x06, 0x16, 0x66, 0x9e, 0x5a, 0x13, + 0xfe, 0x1d, 0xf4, 0x95, 0xff, 0xc2, 0xd7, 0x94, 0xda, 0x70, 0x57, 0xc2, + 0x1d, 0xe8, 0x70, 0x13, 0x13, 0x95, 0x58, 0xdb, 0x0f, 0x1e, 0xab, 0x40, + 0xbc, 0x14, 0xe5, 0xdd, 0x8b, 0xf5, 0x42, 0x21, 0xb4, 0x86, 0xf9, 0x18, + 0x2b, 0xd4, 0x92, 0x39, 0xff, 0x11, 0x87, 0xa5, 0xe6, 0x64, 0xbc, 0x44, + 0xa0, 0x41, 0x38, 0xed, 0xce, 0x3b, 0xce, 0x8c, 0x56, 0xad, 0xa2, 0xd5, + 0xf2, 0x1c, 0x3b, 0xcb, 0x49, 0x27, 0x99, 0xab, 0xb1, 0x4a, 0x1b, 0x24, + 0x8f, 0xb0, 0x17, 0xc0, 0x9d, 0xb3, 0x25, 0xac, 0xa8, 0x71, 0x78, 0x2b, + 0xd3, 0xa0, 0xc9, 0x76, 0xc5, 0x5b, 0x2d, 0xfc, 0x20, 0x5c, 0x48, 0x0f, + 0xfe, 0x19, 0x0b, 0x21, 0xed, 0xf3, 0xed, 0x19, 0xa1, 0xba, 0x27, 0xc3, + 0x91, 0xa1, 0xf4, 0x98, 0x62, 0x14, 0xcf, 0x4a, 0x13, 0x1a, 0x35, 0xda, + 0x09, 0xfe, 0x34, 0x6a, 0x47, 0x2a, 0x47, 0x7e, 0x99, 0x52, 0x03, 0x8b, + 0x47, 0xc6, 0x37, 0x2f, 0xb6, 0xc8, 0x80, 0x7a, 0x14, 0x41, 0x7d, 0x10, + 0x93, 0x48, 0xad, 0x95, 0xb5, 0xbb, 0x72, 0xd0, 0x36, 0xfb, 0x07, 0xfa, + 0x42, 0x2c, 0x5b, 0x0a, 0xea, 0xe4, 0xea, 0x67, 0x05, 0x1c, 0x73, 0x20, + 0xc5, 0xe6, 0x86, 0x87, 0xac, 0xe1, 0xcb, 0x67, 0xae, 0x01, 0x71, 0x05, + 0x1e, 0xe5, 0x13, 0x1a, 0x9e, 0xa8, 0xbc, 0xd0, 0x66, 0x83, 0x30, 0x33, + 0xcb, 0xf8, 0x01, 0x61, 0x60, 0xe3, 0xfc, 0x55, 0x7f, 0x3b, 0xd0, 0x51, + 0x2e, 0x82, 0xb6, 0x11, 0x25, 0xe1, 0x50, 0x77, 0x02, 0x7d, 0x6c, 0x16, + 0x37, 0x02, 0xa6, 0x9f, 0x8c, 0xdd, 0x50, 0xdc, 0x95, 0xb6, 0x4a, 0xc9, + 0x97, 0xee, 0x0a, 0x11, 0x3c, 0x81, 0xbd, 0x08, 0x23, 0xda, 0xbe, 0xa7, + 0x39, 0x8c, 0x24, 0x68, 0x2b, 0x68, 0x7b, 0x9e, 0x1a, 0xf1, 0xb7, 0x58, + 0x2f, 0x2a, 0x3f, 0x90, 0xd8, 0x9a, 0xad, 0x92, 0xae, 0x2b, 0xb2, 0x41, + 0x46, 0x2d, 0x80, 0xac, 0x84, 0x61, 0xe4, 0x7f, 0xb0, 0x59, 0xa6, 0x3e, + 0x4d, 0x61, 0x8a, 0xb7, 0x6b, 0xaa, 0xb4, 0x86, 0x63, 0xd2, 0xf3, 0x12, + 0xac, 0xe5, 0x97, 0x88, 0xaf, 0x29, 0xdd, 0x7c, 0xa3, 0xcd, 0x8d, 0x9f, + 0x53, 0x22, 0xaf, 0x62, 0xad, 0xf9, 0x96, 0x10, 0x8d, 0x98, 0x99, 0x9a, + 0x39, 0x10, 0x1a, 0x09, 0xad, 0x50, 0x52, 0x73, 0xb5, 0xfd, 0xde, 0xe4, + 0xf6, 0xe9, 0x96, 0x65, 0xc8, 0x42, 0xf0, 0xf8, 0x31, 0x5a, 0xe5, 0x6d, + 0x3b, 0x66, 0x02, 0xc4, 0x76, 0x45, 0xd8, 0xce, 0x97, 0xb9, 0xdd, 0x3b, + 0x00, 0x8a, 0xda, 0x7b, 0x23, 0x7d, 0xc2, 0x4e, 0x18, 0xa9, 0xa0, 0x89, + 0x3a, 0x19, 0xfd, 0xff, 0xcb, 0x3e, 0xd6, 0x8d, 0xcb, 0x40, 0xa7, 0x9f, + 0x3b, 0xe9, 0x9c, 0xe9, 0x4f, 0x91, 0x5a, 0xa0, 0x24, 0x44, 0x4a, 0x37, + 0x2b, 0xd5, 0x2c, 0x39, 0x8c, 0xe6, 0x1a, 0xcc, 0x23, 0x28, 0x88, 0xca, + 0xfc, 0x77, 0xbd, 0xbf, 0x71, 0x2b, 0x0b, 0x2a, 0xb9, 0x36, 0x6a, 0x71, + 0x88, 0x1e, 0x50, 0x76, 0x4c, 0xba, 0xe4, 0x43, 0xd0, 0xf1, 0x08, 0x5f, + 0xe3, 0xb4, 0x18, 0x3e, 0x6c, 0x9d, 0xcd, 0xb7, 0xf4, 0xb7, 0x54, 0xdd, + 0x71, 0xe0, 0xd3, 0xcb, 0x30, 0x3d, 0x74, 0x7c, 0x8a, 0x22, 0xd4, 0x38, + 0x9c, 0x63, 0x24, 0x37, 0x26, 0x0c, 0x32, 0xaa, 0x7b, 0xaa, 0x54, 0x49, + 0x98, 0xc4, 0x5a, 0x4e, 0xb3, 0x9b, 0xa8, 0x8e, 0xb6, 0x61, 0x0c, 0xf6, + 0xe8, 0x1c, 0x1e, 0xb2, 0x4c, 0xd6, 0x2c, 0x03, 0x2d, 0x87, 0xc8, 0x23, + 0x85, 0xfa, 0x06, 0x4e, 0x60, 0x23, 0x88, 0x9b, 0x8c, 0xad, 0x74, 0x99, + 0x95, 0x5d, 0x9b, 0x79, 0x40, 0xad, 0x1e, 0x9c, 0xa3, 0xcf, 0xa4, 0x5e, + 0xf4, 0xc0, 0x2e, 0xe1, 0x1b, 0x22, 0xc3, 0x9d, 0xb0, 0xc7, 0x80, 0xc5, + 0x00, 0x8b, 0xd8, 0x45, 0x01, 0x27, 0xf2, 0x1c, 0x25, 0x9d, 0x73, 0xa3, + 0xf4, 0x1c, 0x19, 0x1d, 0xc4, 0x46, 0xb3, 0x12, 0x9b, 0xdb, 0xa0, 0x31, + 0x46, 0xb6, 0xf2, 0xaa, 0x27, 0xae, 0x80, 0x51, 0xac, 0x2c, 0xca, 0x1a, + 0x60, 0xaa, 0x1a, 0x57, 0xb9, 0x88, 0x2f, 0xbd, 0x60, 0x48, 0xa0, 0xe6, + 0xf3, 0xce, 0x3b, 0x48, 0x80, 0xe4, 0x3a, 0x82, 0x49, 0xcf, 0x68, 0x54, + 0x48, 0xd3, 0xab, 0x70, 0xd8, 0x0a, 0x8c, 0x75, 0x66, 0x9b, 0x8b, 0x71, + 0x65, 0xbf, 0x1b, 0x7c, 0xcf, 0x51, 0x67, 0xce, 0x3c, 0x16, 0x3b, 0x1c, + 0xe8, 0x77, 0x33, 0x49, 0x4d, 0x15, 0x04, 0x2b, 0xfc, 0x3a, 0xcf, 0x97, + 0x38, 0x97, 0x65, 0x77, 0x23, 0x95, 0xc4, 0x24, 0x7e, 0x44, 0x60, 0x04, + 0x46, 0xa1, 0x41, 0x9a, 0x1a, 0x22, 0xbc, 0x4f, 0x10, 0xad, 0x52, 0xc1, + 0xf2, 0xbf, 0xe8, 0xd6, 0x44, 0x65, 0xed, 0x66, 0x93, 0x77, 0x64, 0xa1, + 0xcf, 0x25, 0xb6, 0x53, 0x32, 0x5a, 0x89, 0xf4, 0xe3, 0x47, 0x7f, 0xeb, + 0x60, 0x68, 0x12, 0x50, 0x47, 0x32, 0x72, 0x31, 0x61, 0x26, 0xf9, 0x20, + 0x52, 0x9c, 0xa6, 0x95, 0x66, 0xb7, 0x28, 0x7b, 0xc7, 0x9b, 0xe0, 0xc6, + 0x19, 0x06, 0x3d, 0xe0, 0x29, 0x59, 0xe6, 0xc1, 0x21, 0x26, 0x5c, 0x72, + 0x98, 0x05, 0xde, 0x5b, 0xae, 0x5a, 0x5c, 0x40, 0xf8, 0x31, 0x9b, 0x5e, + 0xa8, 0x18, 0x75, 0x1e, 0xb4, 0x22, 0x4a, 0xda, 0x41, 0xa8, 0x1e, 0xec, + 0x6a, 0x39, 0x8c, 0xfa, 0x6f, 0xa9, 0xdc, 0xa5, 0x8f, 0xc5, 0x67, 0x8a, + 0x68, 0xde, 0xee, 0xc4, 0x0a, 0xcd, 0x34, 0x6b, 0xf7, 0x57, 0x5f, 0x19, + 0x8c, 0x98, 0xdd, 0xec, 0x4f, 0xd2, 0x28, 0x48, 0x4d, 0x34, 0x86, 0x6a, + 0x2f, 0x5a, 0x36, 0x80, 0x5d, 0x22, 0x68, 0xd2, 0x3e, 0x39, 0x2a, 0x0d, + 0xeb, 0xbf, 0x91, 0x83, 0x80, 0x60, 0xa8, 0x44, 0x67, 0x21, 0x89, 0xca, + 0x8a, 0x52, 0xcd, 0x7e, 0xcf, 0xa5, 0x99, 0xd0, 0x72, 0xa9, 0x62, 0x7b, + 0xfa, 0x38, 0x36, 0x20, 0xe1, 0x19, 0xb5, 0x6d, 0x68, 0x9a, 0x44, 0x7e, + 0x7b, 0x1d, 0x46, 0x11, 0x49, 0x26, 0x9e, 0xbd, 0x06, 0xb2, 0x01, 0x53, + 0x02, 0xf2, 0x47, 0xe6, 0x57, 0x74, 0x09, 0x13, 0x39, 0x38, 0x02, 0x34, + 0x2a, 0x3b, 0x8d, 0xc0, 0x68, 0x2d, 0x2c, 0x7c, 0x1e, 0x38, 0x80, 0xdb, + 0x0a, 0xbf, 0xf7, 0x31, 0x35, 0xec, 0xbb, 0xaa, 0xc9, 0xaa, 0x0e, 0x9c, + 0x33, 0x8e, 0x7f, 0x85, 0x1f, 0x69, 0x9f, 0xf2, 0x48, 0x5d, 0x51, 0x51, + 0xde, 0x33, 0x87, 0x8f, 0x09, 0x02, 0x9e, 0xb7, 0x42, 0xa5, 0x32, 0x1a, + 0xe8, 0xf7, 0xa3, 0x8e, 0xfc, 0x5c, 0xcc, 0x8b, 0x8c, 0xc4, 0x44, 0x66, + 0xca, 0x28, 0xe4, 0x54, 0xc2, 0xfa, 0x9f, 0x69, 0xd8, 0xfe, 0x1e, 0x37, + 0x6b, 0x34, 0x04, 0x94, 0xfe, 0x47, 0xa4, 0x6d, 0x45, 0x28, 0x19, 0xa2, + 0xd8, 0x42, 0x89, 0xc7, 0xa0, 0x05, 0x34, 0x3c, 0x9f, 0xb3, 0x0d, 0xa2, + 0x56, 0xb3, 0x45, 0xc4, 0x8c, 0x0b, 0x60, 0xcf, 0x58, 0x40, 0xa0, 0x21, + 0x49, 0x3a, 0xac, 0xee, 0x6b, 0xc8, 0x98, 0x1c, 0x7c, 0xf9, 0x9d, 0xac, + 0x7c, 0x9c, 0xc8, 0xd5, 0xcf, 0xf9, 0x2a, 0x83, 0xec, 0x50, 0x0e, 0xf2, + 0x4d, 0x73, 0x05, 0xf2, 0x0f, 0xea, 0xca, 0x45, 0x2b, 0x97, 0x75, 0xbd, + 0x53, 0x63, 0x36, 0x68, 0x9b, 0x14, 0x5c, 0xe0, 0x75, 0xd3, 0xb9, 0xe3, + 0x25, 0x04, 0x75, 0x7a, 0xe7, 0xb7, 0xa5, 0x44, 0x14, 0x0d, 0xc4, 0x4f, + 0xab, 0x86, 0x94, 0xdf, 0x50, 0x76, 0x73, 0xd7, 0x8d, 0x21, 0x2c, 0x77, + 0x51, 0x16, 0xb2, 0x4a, 0x5f, 0xcb, 0x45, 0x6c, 0x19, 0x7a, 0x3b, 0x61, + 0xbb, 0x98, 0xe4, 0xd3, 0x4a, 0x33, 0x1d, 0x88, 0x4c, 0x65, 0x1d, 0xdb, + 0x86, 0xd0, 0x14, 0x2f, 0x3e, 0x27, 0x37, 0x1e, 0xbc, 0x88, 0x84, 0x23, + 0x07, 0xe1, 0xc4, 0xaa, 0x5b, 0xde, 0x03, 0x86, 0x77, 0xfd, 0x53, 0x73, + 0xd0, 0x70, 0xa2, 0xf9, 0xc6, 0x6c, 0xcb, 0x60, 0xd7, 0xe3, 0xa5, 0xd8, + 0x34, 0xf8, 0x35, 0x7d, 0xe1, 0xaf, 0x8b, 0x0c, 0x04, 0x42, 0x70, 0x06, + 0x32, 0xb5, 0x7e, 0x9e, 0xec, 0xda, 0xef, 0xd3, 0xd6, 0x3d, 0xd0, 0x6a, + 0xcb, 0x7b, 0xed, 0xde, 0xb9, 0x0c, 0xf3, 0xb1, 0x88, 0x35, 0x4a, 0x79, + 0x2c, 0x88, 0x63, 0xbc, 0xb7, 0x1a, 0x3e, 0xee, 0x61, 0xc5, 0x1f, 0x1b, + 0x94, 0xbb, 0xc1, 0x6b, 0x61, 0xfa, 0x43, 0x27, 0x9b, 0x39, 0x5d, 0x0f, + 0xb8, 0x0d, 0x25, 0xa7, 0xcc, 0x1c, 0x99, 0x36, 0xa0, 0x07, 0x71, 0xa9, + 0x39, 0x73, 0x3a, 0x5a, 0x12, 0x99, 0xa6, 0x32, 0x30, 0xa5, 0x85, 0x84, + 0xa4, 0xe8, 0x98, 0xb4, 0xd1, 0xd1, 0x5d, 0x39, 0xeb, 0x24, 0xde, 0xf2, + 0xb4, 0xc2, 0x09, 0x90, 0x1a, 0x1b, 0x61, 0x58, 0x51, 0x11, 0x75, 0x7a, + 0x37, 0x0f, 0x69, 0x07, 0x6d, 0xfa, 0x14, 0x08, 0x84, 0xce, 0x4e, 0xa4, + 0x91, 0x96, 0x64, 0xfe, 0x1b, 0x4d, 0xa4, 0x52, 0x4e, 0xa8, 0x25, 0xa8, + 0x70, 0x25, 0xb0, 0x60, 0xed, 0xbe, 0x65, 0x3f, 0x8a, 0xf5, 0x95, 0x5a, + 0xf7, 0xda, 0xe2, 0xd7, 0xc2, 0xcf, 0x3b, 0xdc, 0x44, 0xf6, 0xe7, 0x68, + 0x10, 0x50, 0x29, 0xbe, 0x48, 0x55, 0xcc, 0xac, 0xaf, 0x12, 0xa9, 0x61, + 0x89, 0x89, 0xc9, 0xca, 0xef, 0x37, 0x35, 0x49, 0x0c, 0xc2, 0xb6, 0x36, + 0xbf, 0x6e, 0x24, 0x80, 0x5c, 0x0c, 0x78, 0x33, 0x64, 0xfe, 0x5b, 0xf3, + 0x75, 0x36, 0x65, 0x28, 0xeb, 0x20, 0xb4, 0xb0, 0x61, 0xcd, 0x7a, 0x0b, + 0x24, 0x1e, 0x46, 0x1d, 0x10, 0xb1, 0x25, 0x6e, 0x3a, 0x25, 0x86, 0xf6, + 0xad, 0x1c, 0x43, 0x0c, 0xf9, 0xcf, 0x42, 0xe0, 0x67, 0x2b, 0x36, 0x51, + 0x66, 0xbb, 0xf7, 0xea, 0x41, 0x69, 0x6e, 0xb8, 0xb7, 0x0e, 0xfc, 0xfd, + 0xaa, 0x1a, 0x95, 0x43, 0x08, 0x4b, 0xb8, 0xfc, 0x3b, 0x99, 0xeb, 0xa0, + 0x7c, 0x8d, 0xbd, 0x69, 0x49, 0xd3, 0xdd, 0x0f, 0x8e, 0xbe, 0x34, 0xd2, + 0x27, 0x87, 0x64, 0x79, 0x0d, 0xa6, 0xf2, 0xe5, 0x2f, 0xe3, 0xad, 0x2f, + 0x21, 0xd6, 0x36, 0x58, 0x2c, 0x6e, 0x6a, 0x43, 0x6b, 0xc7, 0x3d, 0x8b, + 0x8d, 0x24, 0xf0, 0xcb, 0x33, 0xdf, 0xf1, 0xd2, 0xeb, 0xcb, 0x5d, 0x00, + 0xb1, 0x63, 0x08, 0x77, 0x9d, 0xfc, 0xa1, 0x58, 0x7d, 0xe4, 0xb7, 0x95, + 0xc5, 0x99, 0x08, 0x6f, 0xf9, 0xc9, 0x50, 0x4f, 0x8c, 0xa8, 0xc0, 0xe6, + 0xc4, 0xff, 0x00, 0xcd, 0x6f, 0xbe, 0xa3, 0xb6, 0x66, 0x63, 0x5d, 0x4b, + 0x60, 0x4b, 0x1b, 0x3e, 0xc6, 0x70, 0x65, 0xe4, 0x8e, 0x48, 0xb2, 0x68, + 0xdc, 0xd1, 0xac, 0x78, 0x46, 0x3d, 0x32, 0x58, 0x00, 0xfb, 0x28, 0x95, + 0x7a, 0xf7, 0x11, 0x33, 0x5a, 0x5b, 0xb8, 0xfa, 0xe0, 0xa1, 0x84, 0x33, + 0x64, 0x36, 0x37, 0xd4, 0x64, 0x9e, 0xc1, 0x05, 0xca, 0x87, 0x1d, 0xee, + 0xc0, 0x4f, 0xf4, 0xd4, 0x81, 0x78, 0x54, 0x09, 0x93, 0x56, 0xc0, 0xb6, + 0x7e, 0x26, 0xc3, 0xed, 0xec, 0xdb, 0x24, 0x2c, 0x80, 0xee, 0x0a, 0x57, + 0x6c, 0xa9, 0x85, 0x1d, 0x44, 0xdd, 0x61, 0xb6, 0xfc, 0xdb, 0xd1, 0x00, + 0xd0, 0x5f, 0xbb, 0x43, 0xcf, 0x32, 0x41, 0x2a, 0xef, 0xe8, 0x57, 0x89, + 0x6d, 0xf0, 0x55, 0x8c, 0x54, 0x61, 0xee, 0x8a, 0xf7, 0x1d, 0x90, 0x51, + 0x0f, 0x4e, 0x56, 0xd6, 0x9d, 0x71, 0x77, 0x3c, 0xe5, 0x28, 0xee, 0xc1, + 0xd6, 0x8f, 0xef, 0xbd, 0x2c, 0x83, 0xb8, 0xce, 0x24, 0xa4, 0x41, 0x90, + 0x14, 0x59, 0xd2, 0xfc, 0xc3, 0x0e, 0x5d, 0xa9, 0x22, 0x3b, 0xd3, 0xa4, + 0x30, 0x19, 0x05, 0x64, 0x61, 0x1e, 0x86, 0xec, 0x89, 0x19, 0x75, 0xaf, + 0x80, 0xe3, 0xd7, 0xfb, 0x0a, 0x91, 0xe2, 0xb7, 0xd1, 0x6f, 0xe4, 0xcc, + 0x88, 0x92, 0x48, 0xed, 0x1e, 0x3b, 0xec, 0xa3, 0x9d, 0xeb, 0x9e, 0x78, + 0xb1, 0xa9, 0x34, 0xc1, 0xb6, 0x9b, 0xfc, 0x1e, 0x2d, 0xef, 0xb1, 0x16, + 0x49, 0xd9, 0x60, 0xde, 0xd0, 0xf5, 0x69, 0x12, 0x4d, 0xa1, 0xf7, 0xb4, + 0x58, 0x3d, 0x9e, 0xb7, 0x93, 0xce, 0x37, 0x33, 0xc1, 0x82, 0x00, 0x74, + 0x20, 0xfb, 0x3f, 0x48, 0xb1, 0x52, 0x43, 0x0c, 0x5c, 0x96, 0x82, 0x84, + 0x4b, 0xe3, 0x8e, 0x1a, 0xe4, 0x64, 0x39, 0x6d, 0x98, 0x1c, 0x65, 0x11, + 0xb2, 0x06, 0xc1, 0xae, 0x01, 0x68, 0xd6, 0xfe, 0x57, 0xe7, 0x53, 0xd7, + 0xb1, 0x9f, 0xf9, 0xc8, 0x14, 0x17, 0x85, 0x5c, 0x41, 0x2b, 0x30, 0x60, + 0xbe, 0xfb, 0x61, 0x6b, 0xd9, 0x04, 0x24, 0xa3, 0xec, 0x84, 0x29, 0x20, + 0x6a, 0x70, 0x85, 0x1c, 0xf7, 0xe1, 0xce, 0x37, 0x14, 0x13, 0x6c, 0xfe, + 0xe5, 0x48, 0x6a, 0x33, 0xb9, 0xb9, 0xa2, 0x31, 0x5f, 0xec, 0x3f, 0x8b, + 0x16, 0x63, 0xb1, 0x2a, 0xb3, 0x6b, 0x07, 0x9a, 0x72, 0x62, 0xd2, 0x02, + 0xef, 0x4c, 0x77, 0x82, 0x1b, 0xaa, 0xbf, 0xc4, 0xe2, 0x21, 0x2f, 0xc9, + 0x31, 0x3d, 0x92, 0xf4, 0x73, 0x02, 0xa2, 0x47, 0x90, 0xed, 0xcb, 0xb2, + 0xb9, 0xcd, 0xbf, 0xab, 0x7f, 0x6a, 0xe8, 0xc5, 0x19, 0x9a, 0x6a, 0x02, + 0x98, 0x36, 0xfb, 0xe1, 0xae, 0xac, 0x6b, 0xca, 0x93, 0x59, 0xf1, 0x04, + 0x9e, 0xd8, 0x78, 0x1e, 0x6d, 0x85, 0x3e, 0x2a, 0xe8, 0x79, 0x12, 0x67, + 0x27, 0xb4, 0x9b, 0x66, 0xf7, 0xe2, 0x01, 0xf4, 0x98, 0xbe, 0xb0, 0x74, + 0x6d, 0x91, 0xf8, 0x3c, 0x18, 0x7e, 0xc6, 0x84, 0x10, 0x51, 0xda, 0x14, + 0x69, 0xc0, 0xac, 0xa4, 0xe3, 0xd8, 0x97, 0x73, 0xfe, 0xeb, 0xe0, 0xae, + 0x51, 0xc4, 0x22, 0xa5, 0x91, 0x6f, 0x87, 0x38, 0x39, 0x9e, 0x97, 0x3a, + 0xeb, 0x91, 0xa9, 0xbb, 0xf9, 0xa4, 0xca, 0x3e, 0xef, 0x17, 0x58, 0x79, + 0x45, 0x77, 0x2b, 0xe7, 0x50, 0x92, 0x85, 0x90, 0x12, 0xc5, 0xc3, 0xe3, + 0xcd, 0xc4, 0xbe, 0xbf, 0x6f, 0x47, 0x25, 0x88, 0xcd, 0x6c, 0xcc, 0xee, + 0x9e, 0x61, 0x1b, 0x78, 0x0d, 0xd7, 0xaa, 0x77, 0x1b, 0x05, 0x91, 0xe7, + 0x28, 0x09, 0xfc, 0x66, 0xe5, 0x7e, 0x28, 0xb3, 0x1d, 0x29, 0x33, 0x09, + 0xdd, 0x15, 0x28, 0x17, 0x40, 0xa2, 0xef, 0xf4, 0xb9, 0x98, 0x2d, 0xc4, + 0x22, 0x9b, 0x1e, 0xc1, 0xef, 0x49, 0x5f, 0xe7, 0xb9, 0xf2, 0x5b, 0x74, + 0x6c, 0xd0, 0x11, 0xca, 0x5a, 0x3c, 0xa5, 0x78, 0xe7, 0xd2, 0xd7, 0x05, + 0x86, 0x06, 0x7d, 0xe9, 0x13, 0x6f, 0xcd, 0x12, 0x26, 0x51, 0x9c, 0xf8, + 0xcb, 0x5f, 0x38, 0x89, 0x32, 0xbb, 0xaa, 0x8c, 0xb9, 0xac, 0x67, 0x19, + 0xee, 0xf8, 0x9f, 0x8b, 0x89, 0xca, 0xbc, 0x89, 0x13, 0xd3, 0x7e, 0x2b, + 0xa7, 0xb0, 0x8c, 0x5f, 0x4e, 0x89, 0xad, 0x75, 0xc7, 0xc1, 0xf1, 0xd3, + 0xa1, 0x0d, 0xc1, 0xbc, 0x7f, 0x60, 0xcf, 0x83, 0x5f, 0x27, 0x43, 0xe1, + 0x2f, 0x45, 0x0c, 0x01, 0x65, 0x73, 0x31, 0x34, 0x63, 0x52, 0x44, 0x0e, + 0x2a, 0x6c, 0x10, 0x29, 0xf4, 0xad, 0x51, 0x07, 0x58, 0x41, 0xc6, 0x74, + 0xac, 0x8c, 0xfc, 0x01, 0xba, 0x80, 0xb9, 0x2d, 0x02, 0xc6, 0x96, 0x1d, + 0xcf, 0x6d, 0xad, 0xb2, 0xc1, 0x8f, 0xec, 0x6d, 0xdd, 0xb6, 0x70, 0x4c, + 0x99, 0x33, 0x16, 0xb2, 0x60, 0x34, 0xc3, 0xaa, 0x15, 0x09, 0xf2, 0x62, + 0xf2, 0x95, 0x80, 0xf2, 0xc1, 0xca, 0x6d, 0x20, 0x67, 0x79, 0x7a, 0x29, + 0xfa, 0xbb, 0x19, 0xd8, 0xd8, 0x20, 0xa7, 0x56, 0x84, 0xce, 0x96, 0x2c, + 0x92, 0x0d, 0xf7, 0x00, 0x66, 0xc5, 0x8e, 0x05, 0x59, 0x3e, 0xf7, 0xa9, + 0x14, 0x6b, 0x50, 0xaf, 0x83, 0xfd, 0x7b, 0x58, 0x5c, 0x2c, 0x6b, 0x7f, + 0x84, 0x60, 0x53, 0xbb, 0x02, 0x3e, 0xad, 0x6c, 0x58, 0xe4, 0x0f, 0x7b, + 0x77, 0x54, 0xd8, 0x11, 0x35, 0x5d, 0x98, 0x63, 0x51, 0x0c, 0x3f, 0x16, + 0x3f, 0x8a, 0x1e, 0xf3, 0x58, 0x59, 0xb1, 0x32, 0x98, 0x10, 0xda, 0x94, + 0x61, 0x81, 0x78, 0xf4, 0xec, 0x3b, 0x88, 0xc6, 0x47, 0xb1, 0xad, 0x01, + 0xe6, 0xdb, 0x70, 0xa8, 0x13, 0x59, 0xbb, 0x67, 0x10, 0xeb, 0x7c, 0x5c, + 0xba, 0x5d, 0xba, 0xdf, 0x81, 0xf0, 0xe9, 0x80, 0x75, 0xe4, 0x61, 0xb0, + 0x72, 0xcf, 0x3b, 0x7a, 0xeb, 0xf0, 0xc1, 0xdf, 0xb9, 0xcc, 0x6f, 0x07, + 0x75, 0xce, 0x22, 0xc8, 0x90, 0x3f, 0x90, 0xc9, 0xf3, 0x68, 0x91, 0xc8, + 0xf2, 0x51, 0x2e, 0x72, 0x54, 0x40, 0x76, 0xdb, 0x9c, 0x75, 0x70, 0x5b, + 0x5f, 0xd4, 0x5a, 0x45, 0x81, 0x89, 0x4a, 0xd8, 0x76, 0x22, 0x3e, 0xba, + 0xaf, 0x80, 0xee, 0xe6, 0x8e, 0xd1, 0x14, 0xad, 0x24, 0x6f, 0x54, 0x71, + 0x7d, 0x9f, 0x94, 0x25, 0x19, 0x39, 0xcc, 0x11, 0x11, 0x1a, 0x15, 0xcb, + 0xc7, 0x02, 0xcd, 0x82, 0xf5, 0x7c, 0xbf, 0x11, 0x32, 0xd2, 0x33, 0xc6, + 0xee, 0x05, 0x02, 0x46, 0x9d, 0xe6, 0xaf, 0xdd, 0xde, 0x94, 0xac, 0x35, + 0xf1, 0x4f, 0x21, 0xbe, 0xab, 0x05, 0x78, 0xae, 0xd4, 0x6c, 0x64, 0x10, + 0x71, 0xc4, 0x64, 0x11, 0x5d, 0x06, 0xc7, 0xdf, 0xfd, 0x1b, 0x90, 0x81, + 0x75, 0xd2, 0xee, 0x2f, 0x8e, 0x5a, 0xe2, 0xc6, 0x12, 0x95, 0xda, 0xfb, + 0xf1, 0xea, 0xf2, 0xfc, 0xcc, 0x09, 0x8b, 0xd3, 0x0d, 0x76, 0x20, 0xb1, + 0xe6, 0x62, 0xe4, 0xee, 0xfe, 0x1e, 0x45, 0x70, 0x25, 0x91, 0x61, 0x3a, + 0xb5, 0xd5, 0x86, 0xa3, 0xb6, 0x96, 0x9c, 0xc0, 0xa3, 0x61, 0x77, 0x30, + 0xc4, 0x83, 0x1b, 0xeb, 0xa6, 0x46, 0x5c, 0xe7, 0xb6, 0x2b, 0xb2, 0xf6, + 0xce, 0xd8, 0xb0, 0xad, 0xff, 0x8d, 0x70, 0x19, 0x3d, 0x37, 0x6a, 0x77, + 0xc6, 0xac, 0x91, 0x20, 0xdd, 0x8c, 0x4a, 0x9f, 0x99, 0x3e, 0x9f, 0x57, + 0x7e, 0x81, 0x84, 0xd3, 0x4c, 0x56, 0x2e, 0xa4, 0xff, 0xa7, 0xa5, 0x25, + 0x86, 0xbf, 0x80, 0x04, 0x6e, 0x8f, 0xe8, 0xf9, 0x1f, 0x38, 0x60, 0xf6, + 0x2c, 0xae, 0x7f, 0xe0, 0xe5, 0x9f, 0x5e, 0x21, 0x08, 0xbb, 0xe1, 0x41, + 0x42, 0xc2, 0xa5, 0xd9, 0xfd, 0x73, 0x82, 0x86, 0xfa, 0x86, 0xe6, 0x91, + 0x53, 0x6f, 0x99, 0x21, 0x29, 0x09, 0xb9, 0xfe, 0x91, 0x20, 0x99, 0xd8, + 0xf1, 0xe9, 0xfc, 0x63, 0x2f, 0x51, 0x52, 0x7d, 0x3f, 0xe6, 0x88, 0xbd, + 0x31, 0xdf, 0x74, 0xa0, 0xb8, 0x5d, 0xf0, 0x9d, 0x07, 0x20, 0xd3, 0x26, + 0x7b, 0x80, 0xbd, 0x07, 0x6d, 0x32, 0xbb, 0x62, 0xd2, 0xec, 0x35, 0x3f, + 0x7e, 0x5c, 0x10, 0xd0, 0x94, 0xd9, 0x14, 0x09, 0xee, 0xdc, 0x6f, 0xcd, + 0xbb, 0x57, 0x1b, 0xed, 0x9a, 0x29, 0xfe, 0x34, 0x83, 0x3e, 0x08, 0x82, + 0xc1, 0xa1, 0xae, 0x8d, 0xc6, 0x7c, 0xa2, 0x5f, 0x49, 0x1e, 0x9a, 0x55, + 0xfc, 0x88, 0x21, 0x45, 0xde, 0xd1, 0x7e, 0x4c, 0xe0, 0x38, 0x9c, 0xea, + 0xd7, 0x18, 0x0a, 0xba, 0x80, 0x23, 0xd6, 0x3e, 0x2e, 0xe1, 0x3e, 0x34, + 0x83, 0x7b, 0x69, 0x42, 0xfc, 0xf6, 0xf0, 0x17, 0xc1, 0xac, 0x7f, 0x86, + 0xc1, 0x86, 0x81, 0x8c, 0x01, 0xe7, 0x70, 0x02, 0x55, 0x7a, 0x72, 0xf2, + 0xee, 0x4c, 0x96, 0xb9, 0xa1, 0xb9, 0x50, 0x67, 0x95, 0x74, 0x42, 0xd1, + 0x16, 0x79, 0x90, 0xb2, 0x85, 0x78, 0x5b, 0x91, 0xf8, 0x59, 0x19, 0xe7, + 0x6e, 0xb6, 0xc6, 0xff, 0xe0, 0x27, 0x2a, 0x39, 0x82, 0x91, 0xf2, 0x5b, + 0xb4, 0x4c, 0x56, 0x22, 0x46, 0x06, 0x09, 0xf3, 0x6e, 0x2e, 0x69, 0x3b, + 0x58, 0x7f, 0xb9, 0x8e, 0x40, 0x59, 0x51, 0xb0, 0x2f, 0x4c, 0x0d, 0x7b, + 0x01, 0x9f, 0x0a, 0xf3, 0xdd, 0x38, 0xb3, 0xc9, 0x49, 0x15, 0xea, 0xaf, + 0x6a, 0xf0, 0x2a, 0xe7, 0x3d, 0x23, 0xb2, 0xe7, 0xf7, 0x5d, 0xb9, 0xa0, + 0x40, 0xd0, 0x4b, 0xcd, 0x95, 0xca, 0x54, 0xba, 0x25, 0x82, 0x11, 0xb8, + 0x45, 0x76, 0x4c, 0xa9, 0x6f, 0x46, 0x1e, 0xf0, 0xcb, 0xcb, 0x89, 0x92, + 0x2c, 0x5f, 0xdf, 0xbb, 0x80, 0xcb, 0x30, 0x5b, 0xbe, 0x29, 0x21, 0x23, + 0x2f, 0x87, 0xa0, 0x1e, 0xe8, 0xe4, 0x29, 0x8c, 0x77, 0x78, 0x10, 0xb1, + 0x2c, 0x35, 0x10, 0xa0, 0x17, 0x8c, 0x12, 0x57, 0x2e, 0xca, 0xae, 0xa7, + 0x56, 0x21, 0xde, 0x74, 0x17, 0xf9, 0xa4, 0xdd, 0x38, 0x9c, 0xb9, 0x0f, + 0x2a, 0xa7, 0x33, 0xb7, 0x22, 0xb3, 0x2b, 0xd9, 0xcd, 0x88, 0x3e, 0x86, + 0x85, 0x38, 0xae, 0xb5, 0x88, 0x8d, 0xa4, 0x8f, 0x99, 0x1e, 0x2f, 0x4a, + 0x8c, 0xfe, 0x58, 0x7f, 0xb4, 0x6e, 0xf2, 0x4f, 0x9e, 0x9f, 0x36, 0xec, + 0xf2, 0x5b, 0xd3, 0xa2, 0x76, 0xf5, 0xa2, 0x2f, 0xbb, 0x42, 0x1d, 0x9c, + 0xa5, 0xb9, 0x20, 0xb7, 0xcc, 0xdb, 0xd9, 0x5c, 0xe0, 0x69, 0x10, 0xbb, + 0xae, 0xa3, 0xb4, 0x69, 0x86, 0xa0, 0x7e, 0xfa, 0xb5, 0x6d, 0xf2, 0xac, + 0x3c, 0x96, 0xe5, 0xb6, 0x07, 0xe5, 0x8a, 0x97, 0xb8, 0x90, 0xcb, 0x5a, + 0x23, 0x75, 0x56, 0xba, 0xf1, 0xbb, 0xf6, 0x10, 0x69, 0xc1, 0xf2, 0x57, + 0xec, 0xab, 0x8b, 0xbe, 0x19, 0x0f, 0x72, 0x79, 0x46, 0xcc, 0xcb, 0xac, + 0xab, 0xbe, 0x94, 0xae, 0xa4, 0x52, 0x43, 0xf4, 0x74, 0x05, 0x95, 0x33, + 0x97, 0xd5, 0x7c, 0x41, 0x92, 0xef, 0x33, 0x02, 0x64, 0x57, 0x8e, 0x14, + 0x05, 0x2c, 0xf4, 0x14, 0xc6, 0x62, 0x16, 0xa5, 0xc6, 0xe1, 0x38, 0x19, + 0x01, 0x9f, 0xd2, 0x68, 0x18, 0x20, 0xaf, 0x81, 0xd1, 0x62, 0xd8, 0x32, + 0x7a, 0x0e, 0x75, 0x85, 0x47, 0x43, 0xc2, 0xee, 0x8d, 0x96, 0xc7, 0xae, + 0x00, 0xc3, 0x29, 0xc5, 0xf5, 0xf4, 0xca, 0xdd, 0x05, 0x1b, 0xfd, 0x82, + 0x26, 0xa0, 0x67, 0xa0, 0x9f, 0xcb, 0x37, 0xe9, 0xe3, 0x3f, 0x79, 0x71, + 0x80, 0x7f, 0x12, 0xc2, 0xe8, 0x54, 0x60, 0x8b, 0x8b, 0xb9, 0x19, 0xe7, + 0x81, 0x70, 0x28, 0xd5, 0xf2, 0xb6, 0x3e, 0xb1, 0xc7, 0x66, 0x44, 0x4f, + 0xe3, 0xa8, 0xe1, 0xa1, 0x97, 0x9a, 0xea, 0x60, 0x6c, 0x1b, 0xdd, 0x93, + 0xd5, 0x76, 0x0e, 0xe8, 0xce, 0x8f, 0x75, 0x3f, 0x08, 0x55, 0x03, 0x55, + 0x2e, 0xd6, 0x93, 0xb8, 0x4a, 0xe4, 0xef, 0x18, 0xbc, 0x7d, 0x7e, 0x4a, + 0xae, 0x90, 0x5d, 0xd6, 0x53, 0x72, 0xff, 0x5b, 0xaa, 0x8b, 0x3b, 0x22, + 0xb4, 0x8d, 0x1c, 0xdc, 0x8d, 0x4d, 0x2b, 0xd6, 0x4a, 0x33, 0xaf, 0xa6, + 0x5c, 0xb3, 0x02, 0xfe, 0x57, 0x6e, 0x1f, 0xe8, 0x39, 0x0e, 0x62, 0x68, + 0x93, 0xa9, 0x7b, 0x64, 0x40, 0x2c, 0xc6, 0xea, 0xd6, 0x26, 0xf0, 0x0e, + 0x40, 0xdd, 0xf2, 0x6e, 0x6a, 0x2b, 0x9e, 0x0e, 0xd7, 0x03, 0xdf, 0x4c, + 0x00, 0x8a, 0x6a, 0xf4, 0x14, 0x4c, 0x5a, 0x61, 0x23, 0x93, 0x12, 0xeb, + 0x97, 0xe9, 0xfb, 0x6b, 0x63, 0xc4, 0x08, 0x54, 0xac, 0x01, 0xd0, 0xe8, + 0xb4, 0x6e, 0xee, 0x58, 0x3c, 0x4b, 0x89, 0xfa, 0xd8, 0x6e, 0x4f, 0x5c, + 0xb3, 0xdb, 0x51, 0x20, 0x63, 0x96, 0xa8, 0xef, 0x68, 0xbe, 0xbf, 0x0a, + 0x69, 0x71, 0x33, 0x2a, 0x57, 0x0c, 0x20, 0x21, 0x5f, 0xe5, 0x45, 0x4d, + 0xa0, 0x95, 0xd2, 0xb9, 0xe8, 0xc3, 0xbf, 0x6c, 0x77, 0xb8, 0xd8, 0x28, + 0x2b, 0xce, 0x68, 0x2c, 0xb5, 0x7b, 0xdd, 0x31, 0xae, 0xd8, 0xa4, 0xee, + 0x66, 0x7b, 0x3c, 0xc6, 0x6d, 0x58, 0xf3, 0xc2, 0xee, 0xff, 0x95, 0x98, + 0x2b, 0xff, 0x1a, 0x52, 0xc1, 0xca, 0xb2, 0xbe, 0x87, 0x79, 0x9b, 0xe1, + 0x19, 0x5c, 0xa5, 0x6c, 0x20, 0x8b, 0x2d, 0xa5, 0x46, 0x9d, 0xa7, 0x8a, + 0xa5, 0x2e, 0xb0, 0xe1, 0x54, 0x1d, 0x74, 0xb8, 0x2e, 0x55, 0x99, 0x74, + 0x7a, 0xe1, 0xe0, 0x81, 0xce, 0x64, 0x85, 0xb2, 0x5a, 0x1e, 0x57, 0xdc, + 0x60, 0xf0, 0xfe, 0x0f, 0xe2, 0x72, 0x96, 0xab, 0x68, 0x6d, 0xcb, 0x5a, + 0x1a, 0x32, 0xf0, 0x77, 0xda, 0x54, 0x36, 0x3d, 0x26, 0x12, 0x23, 0x23, + 0xcf, 0x01, 0xf3, 0x49, 0xe4, 0x68, 0x1f, 0x5b, 0x95, 0x50, 0x04, 0xb5, + 0x67, 0x49, 0xf5, 0x31, 0x0b, 0xb1, 0x2c, 0xf2, 0xb6, 0x26, 0xb4, 0x5d, + 0x27, 0x9f, 0x3d, 0x7d, 0x2f, 0xf0, 0x06, 0xd4, 0x95, 0xdc, 0x38, 0x0f, + 0xdb, 0xa8, 0xc8, 0x23, 0x9f, 0xe6, 0x6c, 0x4d, 0xe7, 0xdc, 0xeb, 0x30, + 0xdf, 0xc1, 0xfa, 0xeb, 0xa0, 0xa0, 0x08, 0x0f, 0xdc, 0xad, 0xf6, 0xe3, + 0xb3, 0x62, 0x62, 0x5b, 0xe4, 0xf7, 0x14, 0xda, 0x07, 0x2f, 0x75, 0x35, + 0xe4, 0xaf, 0x7c, 0xda, 0x8e, 0x2a, 0xf1, 0x62, 0x60, 0x8d, 0x63, 0xe3, + 0x9a, 0x98, 0x6a, 0xbe, 0x9b, 0xfb, 0x51, 0xd9, 0x40, 0x8f, 0xf5, 0x5c, + 0xb5, 0x32, 0xc0, 0xfd, 0x9e, 0xce, 0xa3, 0x64, 0xe5, 0x38, 0xf9, 0xd6, + 0xef, 0x85, 0x25, 0x70, 0xb8, 0x38, 0xc5, 0x12, 0xb9, 0x5d, 0xd5, 0x57, + 0xf0, 0x29, 0x76, 0xa0, 0x1d, 0xc7, 0x9b, 0xf2, 0xf8, 0xe8, 0xb3, 0xea, + 0x10, 0x28, 0x3d, 0xf2, 0x71, 0xa8, 0x2d, 0x12, 0xfa, 0x6a, 0x74, 0x61, + 0x05, 0x16, 0x98, 0x63, 0xcc, 0x70, 0x78, 0xdb, 0xe6, 0x39, 0x45, 0x83, + 0xd2, 0x16, 0x6d, 0x8e, 0xf5, 0x0e, 0xbc, 0x13, 0xf5, 0x37, 0x0c, 0xb4, + 0x86, 0x10, 0x0b, 0x07, 0xb6, 0xc6, 0x59, 0xbe, 0xfa, 0x70, 0xc9, 0x6a, + 0x29, 0xa7, 0xbe, 0x94, 0x0d, 0xde, 0xb8, 0x01, 0x87, 0xb2, 0xa0, 0xcf, + 0xa0, 0xb7, 0x2d, 0x4d, 0x26, 0x69, 0x15, 0x34, 0x23, 0x52, 0x4a, 0x82, + 0xce, 0xd7, 0xe2, 0x7a, 0xd3, 0x4c, 0x4c, 0x57, 0x37, 0xb3, 0xc9, 0xc4, + 0x4f, 0xec, 0xad, 0xd2, 0x1b, 0x95, 0xef, 0xa8, 0x1f, 0x43, 0xb6, 0x4f, + 0x66, 0x5a, 0xad, 0xf2, 0x64, 0x13, 0x4b, 0x0f, 0x0a, 0x02, 0x00, 0x2a, + 0x11, 0xb8, 0x53, 0x09, 0xaa, 0x08, 0x2f, 0x8c, 0x30, 0x68, 0x8e, 0x9c, + 0xd1, 0xb8, 0x0c, 0xf5, 0xd0, 0xb6, 0x8e, 0x1c, 0xdb, 0x2e, 0x0e, 0xaa, + 0x86, 0xcc, 0x86, 0x16, 0x3b, 0x8f, 0xe0, 0xa3, 0xb0, 0x36, 0x50, 0x25, + 0x11, 0x16, 0xd2, 0xc4, 0xc7, 0x2b, 0xbf, 0xa5, 0x25, 0xc5, 0xcb, 0x6e, + 0xd3, 0x8b, 0xca, 0x24, 0xec, 0x69, 0x1a, 0x75, 0x38, 0x3f, 0x60, 0x9b, + 0x17, 0xf6, 0x9c, 0x9a, 0xc1, 0xb2, 0xeb, 0xac, 0x20, 0x43, 0x73, 0x5f, + 0x6d, 0x6a, 0x53, 0xcf, 0x4a, 0xfd, 0x42, 0xa7, 0x2d, 0x98, 0xb0, 0x53, + 0x44, 0xad, 0xe2, 0x28, 0xf9, 0x61, 0xc3, 0x94, 0xef, 0x7e, 0x70, 0x3c, + 0x09, 0xf5, 0xd0, 0x30, 0x10, 0xc9, 0x15, 0xb2, 0x99, 0xbc, 0xb9, 0xbb, + 0x58, 0x72, 0x4d, 0x12, 0x80, 0x87, 0x8b, 0xd2, 0x3f, 0xf2, 0xa3, 0xc8, + 0x92, 0xde, 0xb1, 0xf8, 0xf4, 0x2c, 0x3b, 0x1a, 0x37, 0x10, 0xb9, 0xea, + 0x32, 0xc9, 0x34, 0xac, 0x3e, 0x6d, 0xb6, 0xd2, 0x7f, 0x02, 0x27, 0xfa, + 0x36, 0xca, 0x29, 0x18, 0x35, 0x7a, 0x3d, 0x75, 0x36, 0x38, 0x98, 0x8f, + 0x96, 0xa4, 0xaf, 0x17, 0x22, 0x2e, 0xdb, 0xaf, 0xbe, 0xd4, 0x1b, 0x42, + 0x92, 0x37, 0x1b, 0x85, 0x97, 0xd6, 0x98, 0xf6, 0x20, 0xfb, 0x9f, 0xbd, + 0xee, 0x7b, 0xd5, 0xb2, 0xed, 0x26, 0xfd, 0xc3, 0xd7, 0x36, 0x93, 0xb5, + 0xeb, 0xe9, 0xe2, 0xd9, 0xcc, 0x5c, 0x15, 0xf1, 0x63, 0xa2, 0xc8, 0x21, + 0xff, 0x3e, 0x06, 0x2e, 0x09, 0xe5, 0x2c, 0x57, 0xfe, 0x66, 0x36, 0x26, + 0x00, 0xd2, 0x2f, 0xe1, 0x4b, 0xfb, 0x55, 0x38, 0xfa, 0x29, 0xff, 0x3d, + 0x12, 0x28, 0xf8, 0xd8, 0xc0, 0x19, 0x55, 0xd3, 0xc6, 0xde, 0xb6, 0xa4, + 0xf7, 0x1a, 0x8c, 0xd3, 0x2b, 0x32, 0xc3, 0x45, 0x69, 0xd0, 0xc2, 0xf3, + 0x44, 0x07, 0x9a, 0x30, 0x3a, 0x68, 0xab, 0xdb, 0xa3, 0x05, 0x90, 0x57, + 0xef, 0x93, 0x8a, 0x09, 0x3a, 0xdc, 0xc1, 0x14, 0x00, 0x00, 0x3f, 0xd3, + 0x11, 0x16, 0x07, 0x89, 0xe8, 0x62, 0x63, 0x5a, 0x12, 0xba, 0x69, 0x56, + 0x66, 0x7e, 0xa8, 0xac, 0x65, 0xe4, 0xd3, 0xa3, 0xfa, 0x14, 0x63, 0xac, + 0x4b, 0x6e, 0xa5, 0x3d, 0x2e, 0xd7, 0xfa, 0xe0, 0xcf, 0x2f, 0x02, 0x80, + 0x6a, 0xfa, 0x35, 0xfe, 0xac, 0x29, 0x99, 0xa6, 0x07, 0xec, 0x54, 0xcb, + 0x0f, 0x16, 0x84, 0x6e, 0x65, 0x99, 0x52, 0x7c, 0xd7, 0x02, 0xa1, 0xdc, + 0xa8, 0x0d, 0x79, 0x4e, 0x1d, 0x87, 0x6f, 0xad, 0xe2, 0xb3, 0xed, 0x92, + 0xea, 0xe1, 0xcb, 0xa2, 0x50, 0xf0, 0x52, 0x53, 0x00, 0xaf, 0x02, 0xab, + 0xb3, 0xda, 0xed, 0xa8, 0x68, 0xc7, 0xf4, 0xb6, 0xa6, 0x7e, 0x43, 0x9c, + 0x4b, 0x18, 0x23, 0x3d, 0x02, 0x5a, 0xc9, 0x1b, 0x55, 0xda, 0x93, 0xc7, + 0x8d, 0x4d, 0xdd, 0xd3, 0xb2, 0x48, 0xf9, 0x6b, 0x98, 0x98, 0x12, 0x2a, + 0x59, 0x19, 0x7f, 0xfb, 0xc8, 0x2e, 0x08, 0x21, 0xc3, 0x49, 0x9c, 0x86, + 0xf4, 0xf8, 0x32, 0x82, 0x97, 0x49, 0x58, 0x1c, 0x3a, 0x22, 0xd3, 0x24, + 0x13, 0xf2, 0xc7, 0xa5, 0x71, 0x76, 0x40, 0x4c, 0x4a, 0x21, 0x04, 0x18, + 0x8c, 0xcc, 0x15, 0x37, 0xa9, 0xf6, 0x3b, 0x79, 0xe5, 0xc3, 0x7a, 0xba, + 0x2a, 0x5c, 0xc1, 0x35, 0x14, 0x5b, 0xd1, 0x13, 0x66, 0xaf, 0xe3, 0xc8, + 0xb9, 0x50, 0x82, 0x26, 0x5d, 0x6b, 0xc7, 0x72, 0x19, 0x4b, 0x7c, 0xa9, + 0xd6, 0xa3, 0xf8, 0x5a, 0xd6, 0x0e, 0xc6, 0x4e, 0xa0, 0x5a, 0xe5, 0x59, + 0x84, 0x6b, 0x42, 0x2d, 0x2d, 0x4d, 0x52, 0x62, 0x36, 0x11, 0x05, 0x3f, + 0xc8, 0x0b, 0xcf, 0x53, 0xd7, 0x5e, 0xb7, 0x18, 0x9e, 0xa4, 0xe0, 0xba, + 0xe2, 0x48, 0xb8, 0x9d, 0x97, 0x88, 0xa0, 0xd8, 0x47, 0x97, 0x82, 0x3b, + 0x08, 0x0b, 0x8b, 0x89, 0x6c, 0xaf, 0x95, 0xf2, 0xd7, 0x08, 0x1c, 0x9d, + 0x98, 0x0c, 0x20, 0x37, 0x3e, 0xc8, 0x18, 0xd3, 0x53, 0x9c, 0x4f, 0x4d, + 0x14, 0xd1, 0xac, 0xf9, 0x54, 0xf1, 0x54, 0x66, 0x39, 0x24, 0x22, 0x1a, + 0xfb, 0xf7, 0x2a, 0x1d, 0x13, 0x09, 0x58, 0x31, 0x4a, 0x0f, 0xac, 0x67, + 0xa6, 0xbe, 0xe8, 0x36, 0x1b, 0xd6, 0x05, 0xb3, 0x9a, 0xbb, 0x37, 0xb9, + 0xf5, 0x48, 0xe5, 0x89, 0x0c, 0x89, 0xbb, 0x02, 0x26, 0x86, 0x1d, 0x82, + 0xb9, 0xe7, 0xd7, 0x8e, 0x50, 0x19, 0xfc, 0xac, 0x6f, 0x65, 0xb5, 0xb2, + 0x21, 0xf7, 0xd4, 0x76, 0x92, 0x6e, 0x6f, 0x56, 0x01, 0x94, 0x01, 0xab, + 0x9e, 0x89, 0x05, 0x77, 0xa9, 0x65, 0x12, 0x2c, 0x62, 0xb2, 0xb1, 0xcc, + 0xac, 0x46, 0x02, 0x9f, 0x09, 0x7d, 0xa2, 0xac, 0x9e, 0x40, 0x83, 0x2a, + 0xd7, 0x9e, 0xc3, 0x7c, 0xa4, 0x8c, 0xa6, 0x01, 0xe3, 0x61, 0xc0, 0x09, + 0xb9, 0xdb, 0x8a, 0xfc, 0x11, 0x03, 0xa2, 0xbb, 0x1b, 0x13, 0x59, 0x9e, + 0xb6, 0x9b, 0x4b, 0xe8, 0x30, 0x4e, 0x6b, 0x8d, 0xd7, 0x04, 0x20, 0x3d, + 0x82, 0x53, 0xfb, 0x75, 0x6f, 0x43, 0xdf, 0x05, 0x44, 0xb1, 0x7a, 0x94, + 0x83, 0x9d, 0x55, 0x3d, 0x65, 0xa4, 0xdf, 0x78, 0x4a, 0xf1, 0x15, 0xb3, + 0x6b, 0x4a, 0x23, 0xfa, 0xcf, 0x52, 0xc6, 0xa4, 0x3c, 0x98, 0x54, 0xc6, + 0x3b, 0x5f, 0x90, 0x83, 0x67, 0x70, 0xbe, 0x5d, 0x93, 0x24, 0x32, 0xb2, + 0xbc, 0x56, 0x81, 0x89, 0x91, 0x8d, 0xf9, 0x17, 0x56, 0x2d, 0xd4, 0xec, + 0x0d, 0x17, 0xd9, 0x35, 0x05, 0x46, 0x29, 0x60, 0xf0, 0x6f, 0x3a, 0x9d, + 0x20, 0x5d, 0xee, 0x3c, 0x30, 0x72, 0xee, 0x39, 0xbc, 0x2b, 0xf8, 0xcb, + 0x94, 0xff, 0x65, 0x8e, 0x1c, 0x51, 0xfa, 0x1e, 0xd9, 0xb9, 0xc2, 0xcb, + 0x29, 0x4b, 0x45, 0x67, 0x70, 0x7c, 0x38, 0xf1, 0xd8, 0xd1, 0xba, 0xa9, + 0xae, 0x1f, 0xff, 0x80, 0x76, 0x8b, 0x5b, 0xe0, 0x2c, 0xcd, 0xe5, 0x9f, + 0x39, 0x38, 0x62, 0x91, 0x62, 0x40, 0x37, 0xf9, 0x87, 0x65, 0xc9, 0x62, + 0x53, 0xe9, 0xbf, 0xb0, 0x22, 0x72, 0x9e, 0x85, 0xf8, 0xa3, 0x9e, 0xa8, + 0x71, 0x46, 0xef, 0xd5, 0xec, 0x5d, 0xa0, 0x47, 0x58, 0x96, 0xc7, 0x53, + 0xdf, 0x69, 0x9e, 0xc5, 0xb0, 0x6c, 0x34, 0x6a, 0x85, 0xb3, 0xa2, 0xa2, + 0x6d, 0x04, 0x0c, 0xd0, 0x31, 0xdd, 0x0c, 0x78, 0x69, 0x9e, 0x4b, 0x79, + 0xde, 0xb6, 0x1d, 0x86, 0x83, 0x04, 0x98, 0x54, 0x97, 0x04, 0xae, 0xa2, + 0xc1, 0xd9, 0xe5, 0x3d, 0xda, 0x98, 0x02, 0xb5, 0xad, 0x67, 0x0b, 0x7c, + 0xb3, 0x6d, 0x0a, 0x40, 0xbe, 0xf2, 0x3a, 0x63, 0x1a, 0x34, 0x64, 0xbe, + 0x76, 0x83, 0x82, 0x39, 0xfa, 0xb6, 0x6f, 0xc1, 0x9a, 0x9f, 0xb1, 0x5c, + 0x8c, 0x86, 0x39, 0xf5, 0xcf, 0x78, 0x5e, 0x9e, 0x07, 0x17, 0xcb, 0x69, + 0x74, 0x19, 0x4a, 0x48, 0x48, 0x50, 0xda, 0xae, 0xfa, 0xa2, 0xd4, 0xb8, + 0x11, 0x00, 0x1a, 0x22, 0x69, 0x9c, 0x83, 0xf8, 0x00, 0x17, 0x65, 0xf9, + 0x18, 0xc9, 0xef, 0x99, 0x0f, 0x91, 0x4b, 0x90, 0x4d, 0xb5, 0x8c, 0x20, + 0x76, 0x7a, 0x2b, 0x7c, 0x21, 0xf6, 0x2e, 0x45, 0x32, 0xd3, 0x53, 0x80, + 0xd0, 0xfc, 0xb1, 0xd2, 0x1c, 0x27, 0x33, 0x75, 0x4c, 0x6a, 0xaa, 0xfb, + 0x68, 0x7b, 0x10, 0x6c, 0x93, 0xca, 0x2f, 0xa6, 0x50, 0x9c, 0x55, 0x63, + 0x65, 0x4f, 0xd9, 0xcf, 0xee, 0x88, 0x8c, 0xf5, 0x96, 0x9a, 0x72, 0x52, + 0x2e, 0xe5, 0xc0, 0xdf, 0xbc, 0x95, 0x68, 0x82, 0x97, 0xe8, 0x4f, 0xe2, + 0x4c, 0x3a, 0x8c, 0xe5, 0xe4, 0x36, 0xd9, 0x7d, 0xd0, 0xd1, 0xce, 0xd6, + 0xd4, 0x50, 0xd3, 0xee, 0x77, 0x14, 0x3e, 0x14, 0x1a, 0x47, 0x1d, 0xa7, + 0x3b, 0x30, 0x1f, 0x99, 0x6b, 0x1e, 0x93, 0x27, 0xbd, 0x62, 0x09, 0x27, + 0xbc, 0x9f, 0xcd, 0x94, 0x3b, 0x97, 0x89, 0x23, 0xc3, 0x56, 0xde, 0x87, + 0x92, 0xa8, 0xc9, 0x3e, 0x37, 0x6a, 0x14, 0xf2, 0x84, 0x79, 0x23, 0x1d, + 0xc0, 0x8f, 0x25, 0xc0, 0xc1, 0x0a, 0x22, 0x45, 0x5f, 0xf4, 0x4e, 0xbf, + 0x3f, 0x71, 0x88, 0x9b, 0x36, 0x20, 0x5b, 0x96, 0xc0, 0x20, 0xba, 0x15, + 0x8d, 0x7d, 0xef, 0x96, 0x1f, 0x79, 0xb5, 0x8c, 0x4c, 0x51, 0xd9, 0x38, + 0x35, 0x57, 0x24, 0x73, 0xbe, 0x21, 0xb1, 0xf7, 0x23, 0x89, 0x3c, 0x13, + 0x13, 0xd9, 0x70, 0x12, 0x8c, 0x41, 0x18, 0xab, 0xb9, 0xb0, 0x9e, 0x11, + 0x4e, 0x1d, 0xb6, 0x99, 0xd2, 0xb2, 0x9f, 0x14, 0x5b, 0x15, 0xfd, 0xc8, + 0x2f, 0xfb, 0xac, 0x10, 0xcc, 0x37, 0x92, 0xd9, 0x54, 0xab, 0x83, 0x0c, + 0xc8, 0xad, 0x4d, 0xe0, 0x33, 0x41, 0x1e, 0xd8, 0xce, 0xff, 0x44, 0x87, + 0x64, 0x04, 0x30, 0x33, 0x55, 0x3f, 0x1b, 0xe2, 0x3b, 0x42, 0x2b, 0x3c, + 0x52, 0x28, 0xbd, 0x35, 0x44, 0xa1, 0xc9, 0xa4, 0x27, 0x23, 0x52, 0xe9, + 0x74, 0xbc, 0x70, 0x1a, 0x54, 0x65, 0x1c, 0x02, 0xeb, 0xa0, 0x41, 0x8e, + 0x3f, 0x14, 0x92, 0x04, 0x44, 0x1d, 0x30, 0x1e, 0x33, 0x31, 0x17, 0x4f, + 0xed, 0xbc, 0xc5, 0xa1, 0x8f, 0xc7, 0x54, 0x72, 0xee, 0x93, 0x7e, 0x0a, + 0x57, 0x00, 0xdd, 0x93, 0xc5, 0xe5, 0xc7, 0xa1, 0x37, 0x7f, 0x66, 0x07, + 0xa8, 0x94, 0x90, 0x61, 0xd5, 0x08, 0x9d, 0xd7, 0xce, 0x1f, 0x76, 0xff, + 0x6e, 0xaa, 0x50, 0x93, 0x36, 0xda, 0x34, 0xf9, 0x85, 0x7f, 0x0f, 0x87, + 0x90, 0x93, 0x9e, 0x54, 0x5d, 0x48, 0xe7, 0xa3, 0x66, 0xb6, 0xb8, 0xd1, + 0x09, 0x69, 0x55, 0x93, 0xcb, 0x70, 0x2d, 0xea, 0xe6, 0x6c, 0xe5, 0x54, + 0x08, 0x7d, 0x26, 0x38, 0x1c, 0x8c, 0x1d, 0xc1, 0xfd, 0x54, 0xa3, 0x3e, + 0x5a, 0x1f, 0x7a, 0xb9, 0x17, 0xec, 0x14, 0x1a, 0xba, 0x73, 0x97, 0x34, + 0x04, 0x03, 0xc9, 0x90, 0xfc, 0x21, 0xcc, 0xb5, 0xec, 0x9b, 0x25, 0x81, + 0x96, 0x5c, 0xc5, 0x00, 0xa8, 0xdd, 0x32, 0x5b, 0xdc, 0xd1, 0x23, 0xdb, + 0xc2, 0x0c, 0xed, 0x22, 0xb2, 0xd5, 0x49, 0xae, 0xb1, 0x10, 0x10, 0xb8, + 0xdf, 0xb0, 0xf8, 0x51, 0xee, 0x6f, 0x23, 0x85, 0xb8, 0xe7, 0x45, 0x17, + 0x21, 0x32, 0x17, 0x66, 0x73, 0x31, 0x09, 0x02, 0xa6, 0x82, 0x30, 0x7f, + 0x9d, 0xc4, 0x54, 0x41, 0x83, 0x5e, 0xc2, 0x42, 0xff, 0x0f, 0x85, 0x40, + 0xe6, 0x86, 0x6c, 0x31, 0x9c, 0xbb, 0x86, 0xa9, 0xde, 0xf6, 0xda, 0x34, + 0x1b, 0x22, 0x4b, 0xba, 0x65, 0x31, 0x4f, 0xbb, 0x28, 0x58, 0x9d, 0x96, + 0x73, 0x5f, 0x5c, 0x16, 0x42, 0x15, 0x47, 0x3e, 0xa0, 0xf5, 0xf1, 0x0d, + 0xbe, 0x51, 0x21, 0x64, 0x8d, 0xf1, 0x93, 0x21, 0x62, 0x2c, 0x34, 0x25, + 0x99, 0x64, 0xe2, 0x70, 0xb4, 0x34, 0x17, 0x6f, 0x92, 0x38, 0x31, 0x20, + 0x45, 0x6d, 0x84, 0x5e, 0xe4, 0xd0, 0x3f, 0x78, 0xab, 0xa9, 0x8f, 0x33, + 0xa3, 0xc7, 0x74, 0x6f, 0x33, 0x38, 0x17, 0xe8, 0xa9, 0x55, 0xa7, 0x5a, + 0x51, 0xf1, 0x94, 0xe2, 0xa7, 0x25, 0x06, 0x6d, 0x1c, 0x2b, 0xf8, 0x1c, + 0xcf, 0xff, 0xab, 0xc0, 0xdc, 0x64, 0xc5, 0x77, 0xcb, 0x3c, 0x8a, 0xac, + 0x4d, 0x07, 0xc5, 0x4f, 0x7d, 0x64, 0xee, 0x20, 0x30, 0xa9, 0x08, 0x88, + 0xf1, 0x6c, 0x53, 0x4f, 0x60, 0xe0, 0x46, 0x1e, 0x2d, 0xf9, 0x59, 0xfd, + 0xd6, 0x52, 0x09, 0x56, 0x19, 0x5c, 0x14, 0x47, 0xd2, 0x9c, 0x8f, 0x59, + 0x64, 0xde, 0x15, 0xeb, 0xec, 0x60, 0xc4, 0x9f, 0xbc, 0xd3, 0xde, 0x37, + 0x0a, 0xc0, 0x68, 0xcb, 0xc5, 0x2f, 0x91, 0xf1, 0xb4, 0x33, 0x82, 0x9d, + 0x1e, 0x33, 0x2e, 0x9d, 0xfe, 0x9a, 0x5f, 0x8a, 0xa9, 0x19, 0x9e, 0x5b, + 0xdb, 0x2c, 0x9a, 0xcf, 0x99, 0x58, 0x7f, 0x00, 0xdd, 0x85, 0x96, 0xff, + 0x3e, 0xd0, 0x0a, 0xd2, 0xa3, 0xc5, 0x93, 0xba, 0xa3, 0x8a, 0x6e, 0x9a, + 0x36, 0xa9, 0x85, 0x89, 0x8a, 0x96, 0x5b, 0x94, 0x0e, 0xc3, 0x02, 0xe2, + 0x5d, 0x62, 0x8b, 0x2c, 0x55, 0x47, 0xfb, 0x50, 0xde, 0x18, 0x01, 0x03, + 0xe4, 0xfb, 0xf7, 0x42, 0x22, 0xfb, 0xd4, 0xfd}; diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/fors.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/fors.cc.inc index b310e1ba..e771064d 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/fors.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/fors.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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 @@ -23,147 +23,157 @@ #include "./params.h" #include "./thash.h" -// Compute the base 2^12 representation of `message` (algorithm 4, page 16). -static void fors_base_b( - uint16_t indices[SLHDSA_SHA2_128S_FORS_TREES], - const uint8_t message[SLHDSA_SHA2_128S_FORS_MSG_BYTES]) { - static_assert(SLHDSA_SHA2_128S_FORS_HEIGHT == 12, ""); - static_assert((SLHDSA_SHA2_128S_FORS_TREES & 1) == 0, ""); - const uint8_t *msg = message; - for (size_t i = 0; i < SLHDSA_SHA2_128S_FORS_TREES; i += 2) { - uint32_t val = ((uint32_t)msg[0] << 16) | ((uint32_t)msg[1] << 8) | msg[2]; - indices[i] = (val >> 12) & 0xFFF; - indices[i + 1] = val & 0xFFF; - msg += 3; +using namespace bssl; + +// Compute the base 2ᵃ representation of `message` (algorithm 4, page 16). +static void fors_base_b(const slh_dsa_config *config, uint32_t *indices, + const uint8_t *message) { + const size_t bits_per_index = config->fors_height; + BSSL_CHECK(bits_per_index <= SLHDSA_MAX_FORS_HEIGHT); + const size_t total_bits = bits_per_index * config->fors_trees; + const size_t msg_bytes = slhdsa_fors_msg_bytes(config); + BSSL_CHECK(total_bits <= msg_bytes * 8); + + size_t bit_offset = 0; + for (size_t i = 0; i < config->fors_trees; ++i) { + uint32_t value = 0; + for (size_t j = 0; j < bits_per_index; ++j) { + const size_t bit_index = bit_offset + j; + const size_t byte_index = bit_index >> 3; + const size_t bit_in_byte = 7 - (bit_index & 7); + const uint8_t bit = (message[byte_index] >> bit_in_byte) & 0x01; + value = (value << 1) | bit; + } + indices[i] = value; + bit_offset += bits_per_index; } } // Implements Algorithm 14: fors_skGen function (page 29) -void slhdsa_fors_sk_gen(uint8_t fors_sk[BCM_SLHDSA_SHA2_128S_N], uint32_t idx, - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]) { +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]) { uint8_t sk_addr[32]; OPENSSL_memcpy(sk_addr, addr, sizeof(sk_addr)); - slhdsa_set_type(sk_addr, SLHDSA_SHA2_128S_ADDR_TYPE_FORSPRF); - slhdsa_copy_keypair_addr(sk_addr, addr); - slhdsa_set_tree_index(sk_addr, idx); - slhdsa_thash_prf(fors_sk, pk_seed, sk_seed, 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); } // Implements Algorithm 15: fors_node function (page 30) -void slhdsa_fors_treehash(uint8_t root_node[BCM_SLHDSA_SHA2_128S_N], - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - uint32_t i /*target node index*/, - uint32_t z /*target node height*/, - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]) { - BSSL_CHECK(z <= SLHDSA_SHA2_128S_FORS_HEIGHT); - BSSL_CHECK(i < (uint32_t)(SLHDSA_SHA2_128S_FORS_TREES * - (1 << (SLHDSA_SHA2_128S_FORS_HEIGHT - z)))); +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]) { + 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)); if (z == 0) { - uint8_t sk[BCM_SLHDSA_SHA2_128S_N]; - slhdsa_set_tree_height(addr, 0); - slhdsa_set_tree_index(addr, i); - slhdsa_fors_sk_gen(sk, i, sk_seed, pk_seed, addr); - slhdsa_thash_f(root_node, sk, pk_seed, addr); + 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); } else { // Stores left node and right node. - uint8_t nodes[2 * BCM_SLHDSA_SHA2_128S_N]; - slhdsa_fors_treehash(nodes, sk_seed, 2 * i, z - 1, pk_seed, addr); - slhdsa_fors_treehash(nodes + BCM_SLHDSA_SHA2_128S_N, sk_seed, 2 * i + 1, z - 1, + 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 + config->n, sk_seed, 2 * i + 1, z - 1, pk_seed, addr); - slhdsa_set_tree_height(addr, z); - slhdsa_set_tree_index(addr, i); - slhdsa_thash_h(root_node, nodes, pk_seed, 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); } } // Implements Algorithm 16: fors_sign function (page 31) -void slhdsa_fors_sign(uint8_t fors_sig[SLHDSA_SHA2_128S_FORS_BYTES], - const uint8_t message[SLHDSA_SHA2_128S_FORS_MSG_BYTES], - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]) { - uint16_t indices[SLHDSA_SHA2_128S_FORS_TREES]; +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]) { + 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); // Derive FORS indices compatible with the NIST changes. - fors_base_b(indices, message); + fors_base_b(config, indices, message); - for (size_t i = 0; i < SLHDSA_SHA2_128S_FORS_TREES; ++i) { - slhdsa_set_tree_height(addr, 0); + const size_t n = config->n; + const size_t node_stride = n * (config->fors_height + 1); + + for (uint32_t i = 0; i < config->fors_trees; ++i) { + slhdsa_set_tree_height(config, addr, 0); // Write the FORS secret key element to the correct position. - slhdsa_fors_sk_gen( - fors_sig + i * BCM_SLHDSA_SHA2_128S_N * (SLHDSA_SHA2_128S_FORS_HEIGHT + 1), - i * (1 << SLHDSA_SHA2_128S_FORS_HEIGHT) + indices[i], sk_seed, pk_seed, - addr); - for (size_t j = 0; j < SLHDSA_SHA2_128S_FORS_HEIGHT; ++j) { - size_t s = (indices[i] / (1 << j)) ^ 1; + 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); + 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( - fors_sig + BCM_SLHDSA_SHA2_128S_N * - (i * (SLHDSA_SHA2_128S_FORS_HEIGHT + 1) + j + 1), - sk_seed, i * (1ULL << (SLHDSA_SHA2_128S_FORS_HEIGHT - j)) + s, j, - pk_seed, addr); + slhdsa_fors_treehash(config, tree_sig + (j + 1) * n, sk_seed, + i * (1u << (config->fors_height - j)) + sibling, j, + pk_seed, addr); } } } // Implements Algorithm 17: fors_pkFromSig function (page 32) -void slhdsa_fors_pk_from_sig( - uint8_t fors_pk[BCM_SLHDSA_SHA2_128S_N], - const uint8_t fors_sig[SLHDSA_SHA2_128S_FORS_BYTES], - const uint8_t message[SLHDSA_SHA2_128S_FORS_MSG_BYTES], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], uint8_t addr[32]) { - uint16_t indices[SLHDSA_SHA2_128S_FORS_TREES]; - uint8_t tmp[2 * BCM_SLHDSA_SHA2_128S_N]; - uint8_t roots[SLHDSA_SHA2_128S_FORS_TREES * BCM_SLHDSA_SHA2_128S_N]; +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]) { + uint32_t indices[SLHDSA_MAX_FORS_TREES]; + uint8_t tmp[2 * SLHDSA_MAX_N]; + uint8_t roots[SLHDSA_MAX_FORS_TREES * SLHDSA_MAX_N]; + BSSL_CHECK(config->fors_trees <= SLHDSA_MAX_FORS_TREES); + BSSL_CHECK(config->fors_height <= SLHDSA_MAX_FORS_HEIGHT); // Derive FORS indices compatible with the NIST changes. - fors_base_b(indices, message); + fors_base_b(config, indices, message); - for (size_t i = 0; i < SLHDSA_SHA2_128S_FORS_TREES; ++i) { + const size_t n = config->n; + const size_t node_stride = n * (config->fors_height + 1); + + for (size_t i = 0; i < config->fors_trees; ++i) { // Pointer to current sk and authentication path - const uint8_t *sk = - fors_sig + i * BCM_SLHDSA_SHA2_128S_N * (SLHDSA_SHA2_128S_FORS_HEIGHT + 1); - const uint8_t *auth = - fors_sig + i * BCM_SLHDSA_SHA2_128S_N * (SLHDSA_SHA2_128S_FORS_HEIGHT + 1) + - BCM_SLHDSA_SHA2_128S_N; - uint8_t nodes[2 * BCM_SLHDSA_SHA2_128S_N]; + const uint8_t *tree_sig = fors_sig + i * node_stride; + const uint8_t *auth = tree_sig + n; + uint8_t nodes[2 * SLHDSA_MAX_N]; - slhdsa_set_tree_height(addr, 0); - slhdsa_set_tree_index( - addr, (i * (1 << SLHDSA_SHA2_128S_FORS_HEIGHT)) + indices[i]); + slhdsa_set_tree_height(config, addr, 0); + uint32_t index = i * (1ULL << config->fors_height) + indices[i]; + slhdsa_set_tree_index(config, addr, index); - slhdsa_thash_f(nodes, sk, pk_seed, addr); + slhdsa_thash_f(config, nodes, tree_sig, pk_seed, addr); - for (size_t j = 0; j < SLHDSA_SHA2_128S_FORS_HEIGHT; ++j) { - slhdsa_set_tree_height(addr, j + 1); + for (uint32_t j = 0; j < config->fors_height; ++j) { + slhdsa_set_tree_height(config, addr, j + 1); + index >>= 1; + slhdsa_set_tree_index(config, addr, index); // Even node - if (((indices[i] / (1 << j)) % 2) == 0) { - slhdsa_set_tree_index(addr, slhdsa_get_tree_index(addr) / 2); - OPENSSL_memcpy(tmp, nodes, BCM_SLHDSA_SHA2_128S_N); - OPENSSL_memcpy(tmp + BCM_SLHDSA_SHA2_128S_N, auth + j * BCM_SLHDSA_SHA2_128S_N, - BCM_SLHDSA_SHA2_128S_N); - slhdsa_thash_h(nodes + BCM_SLHDSA_SHA2_128S_N, tmp, pk_seed, addr); + 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); } else { - slhdsa_set_tree_index(addr, (slhdsa_get_tree_index(addr) - 1) / 2); - OPENSSL_memcpy(tmp, auth + j * BCM_SLHDSA_SHA2_128S_N, BCM_SLHDSA_SHA2_128S_N); - OPENSSL_memcpy(tmp + BCM_SLHDSA_SHA2_128S_N, nodes, BCM_SLHDSA_SHA2_128S_N); - slhdsa_thash_h(nodes + BCM_SLHDSA_SHA2_128S_N, tmp, pk_seed, addr); + OPENSSL_memcpy(tmp, auth + j * n, n); + OPENSSL_memcpy(tmp + n, nodes, n); + slhdsa_thash_h(config, nodes + n, tmp, pk_seed, addr); } - OPENSSL_memcpy(nodes, nodes + BCM_SLHDSA_SHA2_128S_N, BCM_SLHDSA_SHA2_128S_N); + OPENSSL_memcpy(nodes, nodes + n, n); } - OPENSSL_memcpy(roots + i * BCM_SLHDSA_SHA2_128S_N, nodes, BCM_SLHDSA_SHA2_128S_N); + OPENSSL_memcpy(roots + i * n, nodes, n); } uint8_t forspk_addr[32]; OPENSSL_memcpy(forspk_addr, addr, sizeof(forspk_addr)); - slhdsa_set_type(forspk_addr, SLHDSA_SHA2_128S_ADDR_TYPE_FORSPK); - slhdsa_copy_keypair_addr(forspk_addr, addr); - slhdsa_thash_tk(fors_pk, roots, pk_seed, 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); } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/fors.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/fors.h index 03882c27..f123a22f 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/fors.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/fors.h @@ -1,58 +1,48 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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. #ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_FORS_H #define OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_FORS_H #include "./params.h" -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN // Implements Algorithm 14: fors_skGen function (page 29) -void slhdsa_fors_sk_gen(uint8_t fors_sk[BCM_SLHDSA_SHA2_128S_N], uint32_t idx, - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]); +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]); // Implements Algorithm 15: fors_node function (page 30) -void slhdsa_fors_treehash(uint8_t root_node[BCM_SLHDSA_SHA2_128S_N], - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], +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[BCM_SLHDSA_SHA2_128S_N], + const uint8_t *pk_seed, uint8_t addr[32]); // Implements Algorithm 16: fors_sign function (page 31) -void slhdsa_fors_sign(uint8_t fors_sig[SLHDSA_SHA2_128S_FORS_BYTES], - const uint8_t message[SLHDSA_SHA2_128S_FORS_MSG_BYTES], - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]); +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]); // Implements Algorithm 17: fors_pkFromSig function (page 32) -void slhdsa_fors_pk_from_sig( - uint8_t fors_pk[BCM_SLHDSA_SHA2_128S_N], - const uint8_t fors_sig[SLHDSA_SHA2_128S_FORS_BYTES], - const uint8_t message[SLHDSA_SHA2_128S_FORS_MSG_BYTES], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], uint8_t addr[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]); - -#if defined(__cplusplus) -} // extern C -#endif +BSSL_NAMESPACE_END #endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_FORS_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/merkle.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/merkle.cc.inc index fa857d9f..866732ac 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/merkle.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/merkle.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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 @@ -24,138 +24,141 @@ #include "./wots.h" +using namespace bssl; + // Implements Algorithm 9: xmss_node function (page 23) -void slhdsa_treehash(uint8_t out_pk[BCM_SLHDSA_SHA2_128S_N], - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - uint32_t i /*target node index*/, - uint32_t z /*target node height*/, - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]) { - BSSL_CHECK(z <= SLHDSA_SHA2_128S_TREE_HEIGHT); - BSSL_CHECK(i < (uint32_t)(1 << (SLHDSA_SHA2_128S_TREE_HEIGHT - z))); +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]) { + BSSL_CHECK(z <= config->tree_height); + BSSL_CHECK(i < (uint32_t)(1u << (config->tree_height - z))); if (z == 0) { - slhdsa_set_type(addr, SLHDSA_SHA2_128S_ADDR_TYPE_WOTS); - slhdsa_set_keypair_addr(addr, i); - slhdsa_wots_pk_gen(out_pk, sk_seed, pk_seed, addr); + 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); } else { // Stores left node and right node. - uint8_t nodes[2 * BCM_SLHDSA_SHA2_128S_N]; - slhdsa_treehash(nodes, sk_seed, 2 * i, z - 1, pk_seed, addr); - slhdsa_treehash(nodes + BCM_SLHDSA_SHA2_128S_N, sk_seed, 2 * i + 1, z - 1, + uint8_t nodes[2 * SLHDSA_MAX_N]; + slhdsa_treehash(config, nodes, sk_seed, 2 * i, z - 1, pk_seed, addr); + slhdsa_treehash(config, nodes + config->n, sk_seed, 2 * i + 1, z - 1, pk_seed, addr); - slhdsa_set_type(addr, SLHDSA_SHA2_128S_ADDR_TYPE_HASHTREE); - slhdsa_set_tree_height(addr, z); - slhdsa_set_tree_index(addr, i); - slhdsa_thash_h(out_pk, nodes, pk_seed, 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); } } // Implements Algorithm 10: xmss_sign function (page 24) -void slhdsa_xmss_sign(uint8_t sig[SLHDSA_SHA2_128S_XMSS_BYTES], - const uint8_t msg[BCM_SLHDSA_SHA2_128S_N], unsigned int idx, - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]) { +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, + uint8_t addr[32]) { // Build authentication path - for (size_t j = 0; j < SLHDSA_SHA2_128S_TREE_HEIGHT; ++j) { + 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(sig + SLHDSA_SHA2_128S_WOTS_BYTES + j * BCM_SLHDSA_SHA2_128S_N, - sk_seed, k, j, pk_seed, addr); + slhdsa_treehash(config, sig + wots_bytes + j * n, sk_seed, k, j, pk_seed, + addr); } // Compute WOTS+ signature - slhdsa_set_type(addr, SLHDSA_SHA2_128S_ADDR_TYPE_WOTS); - slhdsa_set_keypair_addr(addr, idx); - slhdsa_wots_sign(sig, msg, sk_seed, pk_seed, addr); + 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); } // Implements Algorithm 11: xmss_pkFromSig function (page 25) -void slhdsa_xmss_pk_from_sig( - uint8_t root[BCM_SLHDSA_SHA2_128S_N], - const uint8_t xmss_sig[SLHDSA_SHA2_128S_XMSS_BYTES], unsigned int idx, - const uint8_t msg[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], uint8_t addr[32]) { +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, + uint8_t addr[32]) { // Stores node[0] and node[1] from Algorithm 11 - slhdsa_set_type(addr, SLHDSA_SHA2_128S_ADDR_TYPE_WOTS); - slhdsa_set_keypair_addr(addr, idx); - uint8_t node[2 * BCM_SLHDSA_SHA2_128S_N]; - slhdsa_wots_pk_from_sig(node, xmss_sig, msg, pk_seed, addr); + 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_set_type(addr, SLHDSA_SHA2_128S_ADDR_TYPE_HASHTREE); - slhdsa_set_tree_index(addr, idx); + slhdsa_set_type(config, addr, SLHDSA_ADDR_TYPE_HASHTREE); + slhdsa_set_tree_index(config, addr, idx); - uint8_t tmp[2 * BCM_SLHDSA_SHA2_128S_N]; - const uint8_t *const auth = xmss_sig + SLHDSA_SHA2_128S_WOTS_BYTES; - for (size_t k = 0; k < SLHDSA_SHA2_128S_TREE_HEIGHT; ++k) { - slhdsa_set_tree_height(addr, k + 1); + uint8_t tmp[2 * SLHDSA_MAX_N]; + const uint8_t *const auth = xmss_sig + slhdsa_wots_bytes(config); + for (uint32_t k = 0; k < config->tree_height; ++k) { + slhdsa_set_tree_height(config, addr, k + 1); if (((idx >> k) & 1) == 0) { - slhdsa_set_tree_index(addr, slhdsa_get_tree_index(addr) >> 1); - OPENSSL_memcpy(tmp, node, BCM_SLHDSA_SHA2_128S_N); - OPENSSL_memcpy(tmp + BCM_SLHDSA_SHA2_128S_N, auth + k * BCM_SLHDSA_SHA2_128S_N, - BCM_SLHDSA_SHA2_128S_N); - slhdsa_thash_h(node + BCM_SLHDSA_SHA2_128S_N, tmp, pk_seed, addr); + slhdsa_set_tree_index(config, addr, + 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); } else { - slhdsa_set_tree_index(addr, (slhdsa_get_tree_index(addr) - 1) >> 1); - OPENSSL_memcpy(tmp, auth + k * BCM_SLHDSA_SHA2_128S_N, BCM_SLHDSA_SHA2_128S_N); - OPENSSL_memcpy(tmp + BCM_SLHDSA_SHA2_128S_N, node, BCM_SLHDSA_SHA2_128S_N); - slhdsa_thash_h(node + BCM_SLHDSA_SHA2_128S_N, tmp, pk_seed, addr); + 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); } - OPENSSL_memcpy(node, node + BCM_SLHDSA_SHA2_128S_N, BCM_SLHDSA_SHA2_128S_N); + OPENSSL_memcpy(node, node + n, n); } - OPENSSL_memcpy(root, node, BCM_SLHDSA_SHA2_128S_N); + OPENSSL_memcpy(root, node, n); } // Implements Algorithm 12: ht_sign function (page 27) -void slhdsa_ht_sign( - uint8_t sig[SLHDSA_SHA2_128S_XMSS_BYTES * SLHDSA_SHA2_128S_D], - const uint8_t message[BCM_SLHDSA_SHA2_128S_N], uint64_t idx_tree, - uint32_t idx_leaf, const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N]) { +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) { uint8_t addr[32] = {0}; - slhdsa_set_tree_addr(addr, idx_tree); + slhdsa_set_tree_addr(config, addr, idx_tree); // Layer 0 - slhdsa_xmss_sign(sig, message, idx_leaf, sk_seed, pk_seed, addr); - uint8_t root[BCM_SLHDSA_SHA2_128S_N]; - slhdsa_xmss_pk_from_sig(root, sig, idx_leaf, message, pk_seed, addr); - sig += SLHDSA_SHA2_128S_XMSS_BYTES; + slhdsa_xmss_sign(config, sig, message, idx_leaf, sk_seed, pk_seed, addr); + uint8_t root[SLHDSA_MAX_N]; + slhdsa_xmss_pk_from_sig(config, root, sig, idx_leaf, message, pk_seed, addr); + sig += slhdsa_xmss_bytes(config); // All other layers - for (size_t j = 1; j < SLHDSA_SHA2_128S_D; ++j) { - idx_leaf = idx_tree % (1 << SLHDSA_SHA2_128S_TREE_HEIGHT); - idx_tree = idx_tree >> SLHDSA_SHA2_128S_TREE_HEIGHT; - slhdsa_set_layer_addr(addr, j); - slhdsa_set_tree_addr(addr, idx_tree); - slhdsa_xmss_sign(sig, root, idx_leaf, sk_seed, pk_seed, addr); - if (j < (SLHDSA_SHA2_128S_D - 1)) { - slhdsa_xmss_pk_from_sig(root, sig, idx_leaf, root, pk_seed, addr); + BSSL_CHECK(config->tree_height <= SLHDSA_MAX_TREE_HEIGHT); + const uint32_t leaf_mask = (1u << config->tree_height) - 1; + for (uint32_t j = 1; j < config->d; ++j) { + idx_leaf = idx_tree & leaf_mask; + 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); + if (j < (config->d - 1)) { + slhdsa_xmss_pk_from_sig(config, root, sig, idx_leaf, root, pk_seed, addr); } - sig += SLHDSA_SHA2_128S_XMSS_BYTES; + sig += slhdsa_xmss_bytes(config); } } // Implements Algorithm 13: ht_verify function (page 28) -int slhdsa_ht_verify( - const uint8_t sig[SLHDSA_SHA2_128S_D * SLHDSA_SHA2_128S_XMSS_BYTES], - const uint8_t message[BCM_SLHDSA_SHA2_128S_N], uint64_t idx_tree, - uint32_t idx_leaf, const uint8_t pk_root[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N]) { +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) { uint8_t addr[32] = {0}; - slhdsa_set_tree_addr(addr, idx_tree); + slhdsa_set_tree_addr(config, addr, idx_tree); - uint8_t node[BCM_SLHDSA_SHA2_128S_N]; - slhdsa_xmss_pk_from_sig(node, sig, idx_leaf, message, pk_seed, addr); + uint8_t node[SLHDSA_MAX_N]; + slhdsa_xmss_pk_from_sig(config, node, sig, idx_leaf, message, pk_seed, addr); - for (size_t j = 1; j < SLHDSA_SHA2_128S_D; ++j) { - idx_leaf = idx_tree % (1 << SLHDSA_SHA2_128S_TREE_HEIGHT); - idx_tree = idx_tree >> SLHDSA_SHA2_128S_TREE_HEIGHT; - slhdsa_set_layer_addr(addr, j); - slhdsa_set_tree_addr(addr, idx_tree); + BSSL_CHECK(config->tree_height <= SLHDSA_MAX_TREE_HEIGHT); + const uint32_t leaf_mask = (1u << config->tree_height) - 1; + for (uint32_t j = 1; j < config->d; ++j) { + idx_leaf = idx_tree & leaf_mask; + idx_tree = idx_tree >> config->tree_height; + slhdsa_set_layer_addr(config, addr, j); + slhdsa_set_tree_addr(config, addr, idx_tree); - slhdsa_xmss_pk_from_sig(node, sig + j * SLHDSA_SHA2_128S_XMSS_BYTES, + slhdsa_xmss_pk_from_sig(config, node, sig + j * slhdsa_xmss_bytes(config), idx_leaf, node, pk_seed, addr); } - return memcmp(node, pk_root, BCM_SLHDSA_SHA2_128S_N) == 0; + return memcmp(node, pk_root, config->n) == 0; } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/merkle.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/merkle.h index b21203df..79d33dfe 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/merkle.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/merkle.h @@ -1,16 +1,16 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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. #ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_MERKLE_H #define OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_MERKLE_H @@ -21,50 +21,38 @@ #include "./params.h" -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN // Implements Algorithm 9: xmss_node function (page 23) -void slhdsa_treehash(uint8_t out_pk[BCM_SLHDSA_SHA2_128S_N], - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - uint32_t i /*target node index*/, - uint32_t z /*target node height*/, - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], +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]); // Implements Algorithm 10: xmss_sign function (page 24) -void slhdsa_xmss_sign(uint8_t sig[SLHDSA_SHA2_128S_XMSS_BYTES], - const uint8_t msg[BCM_SLHDSA_SHA2_128S_N], unsigned int idx, - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], +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, uint8_t addr[32]); // Implements Algorithm 11: xmss_pkFromSig function (page 25) -void slhdsa_xmss_pk_from_sig( - uint8_t root[BCM_SLHDSA_SHA2_128S_N], - const uint8_t xmss_sig[SLHDSA_SHA2_128S_XMSS_BYTES], unsigned int idx, - const uint8_t msg[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], uint8_t addr[32]); +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, + uint8_t addr[32]); // Implements Algorithm 12: ht_sign function (page 27) -void slhdsa_ht_sign( - uint8_t sig[SLHDSA_SHA2_128S_D * SLHDSA_SHA2_128S_XMSS_BYTES], - const uint8_t message[BCM_SLHDSA_SHA2_128S_N], uint64_t idx_tree, - uint32_t idx_leaf, const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N]); +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); // Implements Algorithm 13: ht_verify function (page 28) -int slhdsa_ht_verify( - const uint8_t sig[SLHDSA_SHA2_128S_D * SLHDSA_SHA2_128S_XMSS_BYTES], - const uint8_t message[BCM_SLHDSA_SHA2_128S_N], uint64_t idx_tree, - uint32_t idx_leaf, const uint8_t pk_root[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N]); +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); - -#if defined(__cplusplus) -} // extern C -#endif +BSSL_NAMESPACE_END #endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_MERKLE_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/params.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/params.h index 9e8d2658..f9855e93 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/params.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/params.h @@ -1,78 +1,178 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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. #ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_PARAMS_H #define OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_PARAMS_H #include + +#include + #include "../bcm_interface.h" -#if defined(__cplusplus) -extern "C" { -#endif -// Total height of the tree structure. -#define SLHDSA_SHA2_128S_FULL_HEIGHT 63 -// Number of subtree layers. -#define SLHDSA_SHA2_128S_D 7 -// Height of the trees on each layer -#define SLHDSA_SHA2_128S_TREE_HEIGHT 9 -// Height of each individual FORS tree. -#define SLHDSA_SHA2_128S_FORS_HEIGHT 12 -// Total number of FORS tree used. -#define SLHDSA_SHA2_128S_FORS_TREES 14 -// Size of a FORS signature -#define SLHDSA_SHA2_128S_FORS_BYTES \ - ((SLHDSA_SHA2_128S_FORS_HEIGHT + 1) * SLHDSA_SHA2_128S_FORS_TREES * \ - BCM_SLHDSA_SHA2_128S_N) +BSSL_NAMESPACE_BEGIN -// Winternitz parameter and derived values -#define SLHDSA_SHA2_128S_WOTS_W 16 -#define SLHDSA_SHA2_128S_WOTS_LOG_W 4 -#define SLHDSA_SHA2_128S_WOTS_LEN1 32 -#define SLHDSA_SHA2_128S_WOTS_LEN2 3 -#define SLHDSA_SHA2_128S_WOTS_LEN 35 -#define SLHDSA_SHA2_128S_WOTS_BYTES \ - (BCM_SLHDSA_SHA2_128S_N * SLHDSA_SHA2_128S_WOTS_LEN) +enum slh_dsa_hash_type { + SLH_DSA_HASH_SHA2_256, + SLH_DSA_HASH_SHAKE_256, +}; -// XMSS sizes -#define SLHDSA_SHA2_128S_XMSS_BYTES \ - (SLHDSA_SHA2_128S_WOTS_BYTES + \ - (BCM_SLHDSA_SHA2_128S_N * SLHDSA_SHA2_128S_TREE_HEIGHT)) +// Upper bounds for stack allocations across all SLH-DSA parameter sets in +// FIPS 205. These keep the code simple and avoid dynamic allocation while +// still covering larger future parameter sets such as SLH-DSA-SHAKE-256f. +#define SLHDSA_MAX_N 32 +#define SLHDSA_MAX_WOTS_LEN 67 +#define SLHDSA_MAX_WOTS_BYTES (SLHDSA_MAX_N * SLHDSA_MAX_WOTS_LEN) +#define SLHDSA_MAX_FORS_HEIGHT 17 +#define SLHDSA_MAX_FORS_TREES 35 +#define SLHDSA_MAX_FORS_BYTES \ + ((SLHDSA_MAX_FORS_HEIGHT + 1) * SLHDSA_MAX_FORS_TREES * SLHDSA_MAX_N) +#define SLHDSA_MAX_FORS_MSG_BYTES \ + ((SLHDSA_MAX_FORS_HEIGHT * SLHDSA_MAX_FORS_TREES + 7) / 8) +#define SLHDSA_MAX_TREE_HEIGHT 18 +#define SLHDSA_MAX_D 18 +#define SLHDSA_MAX_DIGEST_SIZE 64 +#define SLHDSA_MAX_HASH_BLOCK_BYTES 168 -// Size of the message digest (NOTE: This is only correct for the SHA-256 params -// here) -#define SLHDSA_SHA2_128S_DIGEST_SIZE \ - (((SLHDSA_SHA2_128S_FORS_TREES * SLHDSA_SHA2_128S_FORS_HEIGHT) / 8) + \ - (((SLHDSA_SHA2_128S_FULL_HEIGHT - SLHDSA_SHA2_128S_TREE_HEIGHT) / 8) + 1) + \ - (SLHDSA_SHA2_128S_TREE_HEIGHT / 8) + 1) +// Values bound by these limits are assumed to be valid shifts within a +// uint32_t. +static_assert(SLHDSA_MAX_TREE_HEIGHT < 32); +static_assert(SLHDSA_MAX_FORS_HEIGHT < 32); -// Compressed address size when using SHA-256 -#define SLHDSA_SHA2_128S_SHA256_ADDR_BYTES 22 +#define SLHDSA_ADDR_BYTES 32 +#define SLHDSA_ADDR_COMPRESSED_BYTES 22 +#define SLHDSA_ADDR_COMP_OFFSET_LAYER 0 +#define SLHDSA_ADDR_COMP_OFFSET_TREE 1 +#define SLHDSA_ADDR_COMP_OFFSET_TYPE 9 +#define SLHDSA_ADDR_COMP_OFFSET_KEYPAIR 10 +#define SLHDSA_ADDR_COMP_OFFSET_CHAIN 14 +#define SLHDSA_ADDR_COMP_OFFSET_TREE_HEIGHT 14 +#define SLHDSA_ADDR_COMP_OFFSET_HASH 18 +#define SLHDSA_ADDR_COMP_OFFSET_TREE_INDEX 18 +#define SLHDSA_ADDR_COMP_ZERO_START 10 +#define SLHDSA_ADDR_COMP_ZERO_LEN 12 +#define SLHDSA_ADDR_FULL_OFFSET_LAYER 0 +#define SLHDSA_ADDR_FULL_OFFSET_TREE 4 +#define SLHDSA_ADDR_FULL_OFFSET_TYPE 16 +#define SLHDSA_ADDR_FULL_OFFSET_KEYPAIR 20 +#define SLHDSA_ADDR_FULL_OFFSET_CHAIN 24 +#define SLHDSA_ADDR_FULL_OFFSET_TREE_HEIGHT 24 +#define SLHDSA_ADDR_FULL_OFFSET_HASH 28 +#define SLHDSA_ADDR_FULL_OFFSET_TREE_INDEX 28 +#define SLHDSA_ADDR_FULL_ZERO_START 20 +#define SLHDSA_ADDR_FULL_ZERO_LEN 12 -// Size of the FORS message hash -#define SLHDSA_SHA2_128S_FORS_MSG_BYTES \ - ((SLHDSA_SHA2_128S_FORS_HEIGHT * SLHDSA_SHA2_128S_FORS_TREES + 7) / 8) -#define SLHDSA_SHA2_128S_TREE_BITS \ - (SLHDSA_SHA2_128S_TREE_HEIGHT * (SLHDSA_SHA2_128S_D - 1)) -#define SLHDSA_SHA2_128S_TREE_BYTES ((SLHDSA_SHA2_128S_TREE_BITS + 7) / 8) -#define SLHDSA_SHA2_128S_LEAF_BITS SLHDSA_SHA2_128S_TREE_HEIGHT -#define SLHDSA_SHA2_128S_LEAF_BYTES ((SLHDSA_SHA2_128S_LEAF_BITS + 7) / 8) +typedef struct slh_dsa_config { + uint32_t n; + uint32_t full_height; + uint32_t d; + uint32_t tree_height; + uint32_t fors_height; + uint32_t fors_trees; + uint32_t wots_w; + uint32_t wots_log_w; + uint32_t wots_len1; + uint32_t wots_len2; + uint32_t digest_size; + uint32_t hash_block_bytes; + uint32_t hash_output_bytes; + uint32_t public_key_bytes; + uint32_t private_key_bytes; + uint32_t signature_bytes; + enum slh_dsa_hash_type hash_type; + bool compressed_addresses; +} slh_dsa_config; +inline uint32_t slhdsa_wots_len(const slh_dsa_config *config) { + return config->wots_len1 + config->wots_len2; +} -#if defined(__cplusplus) -} // extern C -#endif +inline uint32_t slhdsa_wots_bytes(const slh_dsa_config *config) { + return config->n * slhdsa_wots_len(config); +} + +inline uint32_t slhdsa_xmss_bytes(const slh_dsa_config *config) { + return slhdsa_wots_bytes(config) + config->n * config->tree_height; +} + +inline uint32_t slhdsa_fors_msg_bytes(const slh_dsa_config *config) { + return (config->fors_height * config->fors_trees + 7) / 8; +} + +inline uint32_t slhdsa_fors_bytes(const slh_dsa_config *config) { + return (config->fors_height + 1) * config->fors_trees * config->n; +} + +inline uint32_t slhdsa_tree_bits(const slh_dsa_config *config) { + return config->tree_height * (config->d - 1); +} + +inline uint32_t slhdsa_tree_bytes(const slh_dsa_config *config) { + return (slhdsa_tree_bits(config) + 7) / 8; +} + +inline uint32_t slhdsa_leaf_bits(const slh_dsa_config *config) { + return config->tree_height; +} + +inline uint32_t slhdsa_leaf_bytes(const slh_dsa_config *config) { + return (slhdsa_leaf_bits(config) + 7) / 8; +} + +static const slh_dsa_config kSLHDSAConfigSHA2_128s = { + /*n=*/BCM_SLHDSA_SHA2_128S_N, + /*full_height=*/63, + /*d=*/7, + /*tree_height=*/9, + /*fors_height=*/12, + /*fors_trees=*/14, + /*wots_w=*/16, + /*wots_log_w=*/4, + /*wots_len1=*/32, + /*wots_len2=*/3, + /*digest_size=*/30, + /*hash_block_bytes=*/64, + /*hash_output_bytes=*/32, + /*public_key_bytes=*/BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES, + /*private_key_bytes=*/BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES, + /*signature_bytes=*/BCM_SLHDSA_SHA2_128S_SIGNATURE_BYTES, + /*hash_type=*/SLH_DSA_HASH_SHA2_256, + /*compressed_addresses=*/true, +}; + +static const slh_dsa_config kSLHDSAConfigSHAKE_256f = { + /*n=*/BCM_SLHDSA_SHAKE_256F_N, + /*full_height=*/68, + /*d=*/17, + /*tree_height=*/4, + /*fors_height=*/9, + /*fors_trees=*/35, + /*wots_w=*/16, + /*wots_log_w=*/4, + /*wots_len1=*/64, + /*wots_len2=*/3, + /*digest_size=*/49, + /*hash_block_bytes=*/136, + /*hash_output_bytes=*/32, + /*public_key_bytes=*/BCM_SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES, + /*private_key_bytes=*/BCM_SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES, + /*signature_bytes=*/BCM_SLHDSA_SHAKE_256F_SIGNATURE_BYTES, + /*hash_type=*/SLH_DSA_HASH_SHAKE_256, + /*compressed_addresses=*/false, +}; + +BSSL_NAMESPACE_END #endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_PARAMS_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/slhdsa.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/slhdsa.cc.inc index b03146ae..1195f2d1 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/slhdsa.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/slhdsa.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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 @@ -29,48 +29,362 @@ #include "thash.h" +using namespace bssl; + +#if defined(BORINGSSL_FIPS) + +DEFINE_STATIC_ONCE(g_slhdsa_keygen_self_test_once) +DEFINE_STATIC_ONCE(g_slhdsa_sign_self_test_once) +DEFINE_STATIC_ONCE(g_slhdsa_verify_self_test_once) + +#endif + +namespace { + +namespace fips { +void ensure_keygen_self_test(); +void ensure_sign_self_test(); +void ensure_verify_self_test(); +} // namespace fips + // The OBJECT IDENTIFIER header is also included in these values, per the spec. -static const uint8_t kSHA256OID[] = {0x06, 0x09, 0x60, 0x86, 0x48, 0x01, - 0x65, 0x03, 0x04, 0x02, 0x01}; -static const uint8_t kSHA384OID[] = {0x06, 0x09, 0x60, 0x86, 0x48, 0x01, - 0x65, 0x03, 0x04, 0x02, 0x02}; +const uint8_t kSHA256OID[] = {0x06, 0x09, 0x60, 0x86, 0x48, 0x01, + 0x65, 0x03, 0x04, 0x02, 0x01}; +const uint8_t kSHA384OID[] = {0x06, 0x09, 0x60, 0x86, 0x48, 0x01, + 0x65, 0x03, 0x04, 0x02, 0x02}; #define MAX_OID_LENGTH 11 #define MAX_CONTEXT_LENGTH 255 -bcm_infallible BCM_slhdsa_sha2_128s_generate_key_from_seed( - uint8_t out_public_key[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], - uint8_t out_secret_key[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES], - const uint8_t seed[3 * BCM_SLHDSA_SHA2_128S_N]) { +bcm_infallible generate_key_from_seed_no_self_test(const slh_dsa_config *config, + uint8_t *out_public_key, + uint8_t *out_secret_key, + const uint8_t *seed) { // Initialize SK.seed || SK.prf || PK.seed from seed. - OPENSSL_memcpy(out_secret_key, seed, 3 * BCM_SLHDSA_SHA2_128S_N); + OPENSSL_memcpy(out_secret_key, seed, 3 * config->n); // Initialize PK.seed from seed. - OPENSSL_memcpy(out_public_key, seed + 2 * BCM_SLHDSA_SHA2_128S_N, - BCM_SLHDSA_SHA2_128S_N); + OPENSSL_memcpy(out_public_key, seed + 2 * config->n, config->n); uint8_t addr[32] = {0}; - slhdsa_set_layer_addr(addr, SLHDSA_SHA2_128S_D - 1); + slhdsa_set_layer_addr(config, addr, config->d - 1); // Set PK.root - slhdsa_treehash(out_public_key + BCM_SLHDSA_SHA2_128S_N, out_secret_key, 0, - SLHDSA_SHA2_128S_TREE_HEIGHT, out_public_key, addr); - OPENSSL_memcpy(out_secret_key + 3 * BCM_SLHDSA_SHA2_128S_N, - out_public_key + BCM_SLHDSA_SHA2_128S_N, - BCM_SLHDSA_SHA2_128S_N); + slhdsa_treehash(config, out_public_key + config->n, out_secret_key, 0, + config->tree_height, out_public_key, addr); + OPENSSL_memcpy(out_secret_key + 3 * config->n, out_public_key + config->n, + config->n); + + // FIPS 140-3 IG 10.3.A comment 1 says of the pair-wise consistency test for + // SLH-DSA: + // + // "For key pairs generated for use with approved algorithms in SP 800-208 and + // FIPS 205, the PCT (described by the tester in TE10.35.02) may be limited to + // confirming the same key identifier (I in the case of LMS, SEED in the case + // of XMSS and PK.SEED for SLH-DSA) is shared by the resulting public and + // private key following generation." + // + // Since this is cheap, we always do this. + + if (boringssl_fips_break_test("SLHDSA_PWCT")) { + out_public_key[0] ^= 1; + } + if (OPENSSL_memcmp(out_public_key, out_secret_key + 2 * config->n, + config->n) != 0) { + abort(); + } + + return bcm_infallible::not_approved; +} + +uint64_t load_tree_index(const slh_dsa_config *config, const uint8_t *in) { + const size_t tree_bits = slhdsa_tree_bits(config); + const size_t tree_bytes = slhdsa_tree_bytes(config); + BSSL_CHECK(tree_bits <= 64); + BSSL_CHECK(tree_bytes <= 8); + + uint8_t buf[8] = {0}; + OPENSSL_memcpy(buf + (sizeof(buf) - tree_bytes), in, tree_bytes); + uint64_t index = CRYPTO_load_u64_be(buf); + if (tree_bits < 64) { + index &= (~(uint64_t)0) >> (64 - tree_bits); + } + return index; +} + +// Implements Algorithm 22: slh_sign function (Section 10.2.1, page 39) +bcm_infallible sign_internal_no_self_test( + const slh_dsa_config *config, uint8_t *out_signature, + const uint8_t *secret_key, + 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) { + const size_t n = config->n; + const uint8_t *sk_seed = secret_key; + const uint8_t *sk_prf = secret_key + n; + const uint8_t *pk_seed = secret_key + 2 * n; + const uint8_t *pk_root = secret_key + 3 * n; + + // Derive randomizer R and copy it to signature + uint8_t R[SLHDSA_MAX_N]; + slhdsa_thash_prfmsg(config, R, sk_prf, entropy, header, context, context_len, + msg, msg_len); + OPENSSL_memcpy(out_signature, R, n); + + // Compute message digest + uint8_t digest[SLHDSA_MAX_DIGEST_SIZE]; + slhdsa_thash_hmsg(config, digest, R, pk_seed, pk_root, header, context, + context_len, msg, msg_len); + + uint8_t fors_digest[SLHDSA_MAX_FORS_MSG_BYTES]; + const size_t fors_msg_bytes = slhdsa_fors_msg_bytes(config); + OPENSSL_memcpy(fors_digest, digest, fors_msg_bytes); + + size_t digest_offset = fors_msg_bytes; + const uint64_t idx_tree = load_tree_index(config, digest + digest_offset); + digest_offset += slhdsa_tree_bytes(config); + uint32_t idx_leaf = 0; + const size_t leaf_bytes = slhdsa_leaf_bytes(config); + for (size_t i = 0; i < leaf_bytes; ++i) { + idx_leaf = (idx_leaf << 8) | digest[digest_offset + i]; + } + const size_t leaf_bits = slhdsa_leaf_bits(config); + if (leaf_bits < 32) { + idx_leaf &= (~(uint32_t)0) >> (32 - leaf_bits); + } + + uint8_t addr[32] = {0}; + slhdsa_set_tree_addr(config, addr, idx_tree); + 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, + addr); + + uint8_t pk_fors[SLHDSA_MAX_N]; + slhdsa_fors_pk_from_sig(config, pk_fors, out_signature + n, fors_digest, + pk_seed, addr); + + slhdsa_ht_sign(config, out_signature + n + slhdsa_fors_bytes(config), pk_fors, + idx_tree, idx_leaf, sk_seed, pk_seed); return bcm_infallible::approved; } -bcm_infallible BCM_slhdsa_sha2_128s_generate_key( +bcm_status verify_internal(const slh_dsa_config *config, + const uint8_t *signature, size_t signature_len, + const uint8_t *public_key, + 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 size_t n = config->n; + if (signature_len != config->signature_bytes) { + return bcm_status::failure; + } + const uint8_t *pk_seed = public_key; + const uint8_t *pk_root = public_key + n; + + const uint8_t *r = signature; + const uint8_t *sig_fors = signature + n; + const uint8_t *sig_ht = sig_fors + slhdsa_fors_bytes(config); + + uint8_t digest[SLHDSA_MAX_DIGEST_SIZE]; + slhdsa_thash_hmsg(config, digest, r, pk_seed, pk_root, header, context, + context_len, msg, msg_len); + + uint8_t fors_digest[SLHDSA_MAX_FORS_MSG_BYTES]; + const size_t fors_msg_bytes = slhdsa_fors_msg_bytes(config); + OPENSSL_memcpy(fors_digest, digest, fors_msg_bytes); + + size_t digest_offset = fors_msg_bytes; + const uint64_t idx_tree = load_tree_index(config, digest + digest_offset); + digest_offset += slhdsa_tree_bytes(config); + uint32_t idx_leaf = 0; + const size_t leaf_bytes = slhdsa_leaf_bytes(config); + for (size_t i = 0; i < leaf_bytes; ++i) { + idx_leaf = (idx_leaf << 8) | digest[digest_offset + i]; + } + const size_t leaf_bits = slhdsa_leaf_bits(config); + if (leaf_bits < 32) { + idx_leaf &= (~(uint32_t)0) >> (32 - leaf_bits); + } + + uint8_t addr[32] = {0}; + slhdsa_set_tree_addr(config, addr, idx_tree); + slhdsa_set_type(config, addr, SLHDSA_ADDR_TYPE_FORSTREE); + 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, + addr); + + if (!slhdsa_ht_verify(config, sig_ht, pk_fors, idx_tree, idx_leaf, pk_root, + pk_seed)) { + return bcm_status::failure; + } + + return bcm_status::approved; +} + +namespace fips { + +#include "fips_known_values.inc" + +static int keygen_self_test() { + uint8_t seed[3 * BCM_SLHDSA_SHA2_128S_N] = {0}; + uint8_t pub[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES]; + uint8_t priv[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES]; + generate_key_from_seed_no_self_test(&kSLHDSAConfigSHA2_128s, pub, priv, seed); + + if (!BORINGSSL_check_test(kExpectedPublicKey, pub, "SLH-DSA public key") || + !BORINGSSL_check_test(kExpectedPrivateKey, priv, "SLH-DSA private key")) { + return 0; + } + + return 1; +} + +static int sign_self_test() { + uint8_t header[BCM_SLHDSA_M_PRIME_HEADER_LEN] = {0}; + uint8_t entropy[BCM_SLHDSA_SHA2_128S_N] = {0}; + uint8_t sig[BCM_SLHDSA_SHA2_128S_SIGNATURE_BYTES]; + sign_internal_no_self_test(&kSLHDSAConfigSHA2_128s, sig, kExpectedPrivateKey, + header, nullptr, 0, nullptr, 0, entropy); + uint8_t digest[32]; + SHA256(sig, sizeof(sig), digest); + + if (!BORINGSSL_check_test(kExpectedSignatureSHA256, digest, + "SLH-DSA signature")) { + return 0; + } + + return 1; +} + +static int verify_self_test() { + uint8_t header[BCM_SLHDSA_M_PRIME_HEADER_LEN] = {0}; + return verify_internal(&kSLHDSAConfigSHA2_128s, kExpectedSignature, + sizeof(kExpectedSignature), kExpectedPublicKey, header, + nullptr, 0, nullptr, 0) == bcm_status::approved; +} + +#if defined(BORINGSSL_FIPS) + +void ensure_keygen_self_test() { + CRYPTO_once(g_slhdsa_keygen_self_test_once_bss_get(), []() { + if (!keygen_self_test()) { + BORINGSSL_FIPS_abort(); + } + }); +} + +void ensure_sign_self_test() { + CRYPTO_once(g_slhdsa_sign_self_test_once_bss_get(), []() { + if (!sign_self_test()) { + BORINGSSL_FIPS_abort(); + } + }); +} + +void ensure_verify_self_test() { + CRYPTO_once(g_slhdsa_verify_self_test_once_bss_get(), []() { + if (!verify_self_test()) { + BORINGSSL_FIPS_abort(); + } + }); +} + +#else + +void ensure_keygen_self_test() {} +void ensure_sign_self_test() {} +void ensure_verify_self_test() {} + +#endif + +} // namespace fips + +} // namespace + +bcm_infallible bssl::BCM_slhdsa_sha2_128s_generate_key_from_seed( + uint8_t out_public_key[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], + uint8_t out_secret_key[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES], + const uint8_t seed[3 * BCM_SLHDSA_SHA2_128S_N]) { + fips::ensure_keygen_self_test(); + return generate_key_from_seed_no_self_test( + &kSLHDSAConfigSHA2_128s, out_public_key, out_secret_key, seed); +} + +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); +} + +bcm_status bssl::BCM_slhdsa_sha2_128s_generate_key_from_seed_fips( + uint8_t out_public_key[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], + uint8_t out_secret_key[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES], + const uint8_t seed[3 * BCM_SLHDSA_SHA2_128S_N]) { + if (out_public_key == nullptr || out_secret_key == nullptr) { + return bcm_status::failure; + } + BCM_slhdsa_sha2_128s_generate_key_from_seed(out_public_key, out_secret_key, + seed); + return bcm_status::approved; +} + +bcm_status bssl::BCM_slhdsa_shake_256f_generate_key_from_seed_fips( + 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]) { + if (out_public_key == nullptr || out_secret_key == nullptr) { + return bcm_status::failure; + } + BCM_slhdsa_shake_256f_generate_key_from_seed(out_public_key, out_secret_key, + seed); + return bcm_status::approved; +} + +bcm_infallible bssl::BCM_slhdsa_sha2_128s_generate_key( uint8_t out_public_key[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], uint8_t out_private_key[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES]) { uint8_t seed[3 * BCM_SLHDSA_SHA2_128S_N]; RAND_bytes(seed, 3 * BCM_SLHDSA_SHA2_128S_N); - BCM_slhdsa_sha2_128s_generate_key_from_seed(out_public_key, out_private_key, - seed); - return bcm_infallible::approved; + return BCM_slhdsa_sha2_128s_generate_key_from_seed(out_public_key, + out_private_key, seed); } -bcm_infallible BCM_slhdsa_sha2_128s_public_from_private( +bcm_infallible bssl::BCM_slhdsa_shake_256f_generate_key( + uint8_t out_public_key[BCM_SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], + uint8_t out_private_key[BCM_SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES]) { + uint8_t seed[3 * BCM_SLHDSA_SHAKE_256F_N]; + RAND_bytes(seed, 3 * BCM_SLHDSA_SHAKE_256F_N); + return BCM_slhdsa_shake_256f_generate_key_from_seed(out_public_key, + out_private_key, seed); +} + +bcm_status bssl::BCM_slhdsa_sha2_128s_generate_key_fips( + uint8_t out_public_key[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], + uint8_t out_private_key[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES]) { + if (out_public_key == nullptr || out_private_key == nullptr) { + return bcm_status::failure; + } + BCM_slhdsa_sha2_128s_generate_key(out_public_key, out_private_key); + return bcm_status::approved; +} + +bcm_status bssl::BCM_slhdsa_shake_256f_generate_key_fips( + uint8_t out_public_key[BCM_SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], + uint8_t out_private_key[BCM_SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES]) { + if (out_public_key == nullptr || out_private_key == nullptr) { + return bcm_status::failure; + } + BCM_slhdsa_shake_256f_generate_key(out_public_key, out_private_key); + return bcm_status::approved; +} + +bcm_infallible bssl::BCM_slhdsa_sha2_128s_public_from_private( uint8_t out_public_key[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], const uint8_t private_key[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES]) { OPENSSL_memcpy(out_public_key, private_key + 2 * BCM_SLHDSA_SHA2_128S_N, @@ -78,68 +392,15 @@ bcm_infallible BCM_slhdsa_sha2_128s_public_from_private( return bcm_infallible::approved; } -// Note that this overreads by a byte. This is fine in the context that it's -// used. -static uint64_t load_tree_index(const uint8_t in[8]) { - static_assert(SLHDSA_SHA2_128S_TREE_BYTES == 7, - "This code needs to be updated"); - uint64_t index = CRYPTO_load_u64_be(in); - index >>= 8; - index &= (~(uint64_t)0) >> (64 - SLHDSA_SHA2_128S_TREE_BITS); - return index; -} - -// Implements Algorithm 22: slh_sign function (Section 10.2.1, page 39) -bcm_infallible BCM_slhdsa_sha2_128s_sign_internal( - uint8_t out_signature[BCM_SLHDSA_SHA2_128S_SIGNATURE_BYTES], - const uint8_t secret_key[BCM_SLHDSA_SHA2_128S_PRIVATE_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, - const uint8_t entropy[BCM_SLHDSA_SHA2_128S_N]) { - const uint8_t *sk_seed = secret_key; - const uint8_t *sk_prf = secret_key + BCM_SLHDSA_SHA2_128S_N; - const uint8_t *pk_seed = secret_key + 2 * BCM_SLHDSA_SHA2_128S_N; - const uint8_t *pk_root = secret_key + 3 * BCM_SLHDSA_SHA2_128S_N; - - // Derive randomizer R and copy it to signature - uint8_t R[BCM_SLHDSA_SHA2_128S_N]; - slhdsa_thash_prfmsg(R, sk_prf, entropy, header, context, context_len, msg, - msg_len); - OPENSSL_memcpy(out_signature, R, BCM_SLHDSA_SHA2_128S_N); - - // Compute message digest - uint8_t digest[SLHDSA_SHA2_128S_DIGEST_SIZE]; - slhdsa_thash_hmsg(digest, R, pk_seed, pk_root, header, context, context_len, - msg, msg_len); - - uint8_t fors_digest[SLHDSA_SHA2_128S_FORS_MSG_BYTES]; - OPENSSL_memcpy(fors_digest, digest, SLHDSA_SHA2_128S_FORS_MSG_BYTES); - - const uint64_t idx_tree = - load_tree_index(digest + SLHDSA_SHA2_128S_FORS_MSG_BYTES); - uint32_t idx_leaf = CRYPTO_load_u16_be( - digest + SLHDSA_SHA2_128S_FORS_MSG_BYTES + SLHDSA_SHA2_128S_TREE_BYTES); - idx_leaf &= (~(uint32_t)0) >> (32 - SLHDSA_SHA2_128S_LEAF_BITS); - - uint8_t addr[32] = {0}; - slhdsa_set_tree_addr(addr, idx_tree); - slhdsa_set_type(addr, SLHDSA_SHA2_128S_ADDR_TYPE_FORSTREE); - slhdsa_set_keypair_addr(addr, idx_leaf); - - slhdsa_fors_sign(out_signature + BCM_SLHDSA_SHA2_128S_N, fors_digest, sk_seed, - pk_seed, addr); - - uint8_t pk_fors[BCM_SLHDSA_SHA2_128S_N]; - slhdsa_fors_pk_from_sig(pk_fors, out_signature + BCM_SLHDSA_SHA2_128S_N, - fors_digest, pk_seed, addr); - - slhdsa_ht_sign( - out_signature + BCM_SLHDSA_SHA2_128S_N + SLHDSA_SHA2_128S_FORS_BYTES, - pk_fors, idx_tree, idx_leaf, sk_seed, pk_seed); +bcm_infallible bssl::BCM_slhdsa_shake_256f_public_from_private( + uint8_t out_public_key[BCM_SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], + 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; } -bcm_status BCM_slhdsa_sha2_128s_sign( +bcm_status bssl::BCM_slhdsa_sha2_128s_sign( uint8_t out_signature[BCM_SLHDSA_SHA2_128S_SIGNATURE_BYTES], const uint8_t private_key[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES], const uint8_t *msg, size_t msg_len, const uint8_t *context, @@ -161,6 +422,27 @@ bcm_status BCM_slhdsa_sha2_128s_sign( return bcm_status::approved; } +bcm_status bssl::BCM_slhdsa_shake_256f_sign( + uint8_t out_signature[BCM_SLHDSA_SHAKE_256F_SIGNATURE_BYTES], + const uint8_t private_key[BCM_SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES], + const uint8_t *msg, size_t msg_len, const uint8_t *context, + size_t context_len) { + if (context_len > MAX_CONTEXT_LENGTH) { + return bcm_status::failure; + } + + uint8_t M_prime_header[2]; + M_prime_header[0] = 0; + M_prime_header[1] = (uint8_t)context_len; + + uint8_t entropy[BCM_SLHDSA_SHAKE_256F_N]; + RAND_bytes(entropy, sizeof(entropy)); + BCM_slhdsa_shake_256f_sign_internal(out_signature, private_key, + M_prime_header, context, context_len, msg, + msg_len, entropy); + return bcm_status::approved; +} + static int slhdsa_get_context_and_oid(uint8_t *out_context_and_oid, size_t *out_context_and_oid_len, size_t max_out_context_and_oid, @@ -174,7 +456,7 @@ static int slhdsa_get_context_and_oid(uint8_t *out_context_and_oid, case NID_sha256: oid = kSHA256OID; oid_len = sizeof(kSHA256OID); - static_assert(sizeof(kSHA256OID) <= MAX_OID_LENGTH, ""); + static_assert(sizeof(kSHA256OID) <= MAX_OID_LENGTH); expected_hash_len = 32; break; @@ -183,7 +465,7 @@ static int slhdsa_get_context_and_oid(uint8_t *out_context_and_oid, case NID_sha384: oid = kSHA384OID; oid_len = sizeof(kSHA384OID); - static_assert(sizeof(kSHA384OID) <= MAX_OID_LENGTH, ""); + static_assert(sizeof(kSHA384OID) <= MAX_OID_LENGTH); expected_hash_len = 48; break; @@ -208,8 +490,31 @@ static int slhdsa_get_context_and_oid(uint8_t *out_context_and_oid, return 1; } +bcm_infallible bssl::BCM_slhdsa_sha2_128s_sign_internal( + uint8_t out_signature[BCM_SLHDSA_SHA2_128S_SIGNATURE_BYTES], + const uint8_t secret_key[BCM_SLHDSA_SHA2_128S_PRIVATE_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, + const uint8_t entropy[BCM_SLHDSA_SHA2_128S_N]) { + fips::ensure_sign_self_test(); + return sign_internal_no_self_test(&kSLHDSAConfigSHA2_128s, out_signature, + secret_key, header, context, context_len, + msg, msg_len, entropy); +} -bcm_status BCM_slhdsa_sha2_128s_prehash_sign( +bcm_infallible bssl::BCM_slhdsa_shake_256f_sign_internal( + uint8_t out_signature[BCM_SLHDSA_SHAKE_256F_SIGNATURE_BYTES], + const uint8_t secret_key[BCM_SLHDSA_SHAKE_256F_PRIVATE_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, + 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); +} + +bcm_status bssl::BCM_slhdsa_sha2_128s_prehash_sign( uint8_t out_signature[BCM_SLHDSA_SHA2_128S_SIGNATURE_BYTES], const uint8_t private_key[BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES], const uint8_t *hashed_msg, size_t hashed_msg_len, int hash_nid, @@ -238,8 +543,37 @@ bcm_status BCM_slhdsa_sha2_128s_prehash_sign( return bcm_status::approved; } +bcm_status bssl::BCM_slhdsa_shake_256f_prehash_sign( + uint8_t out_signature[BCM_SLHDSA_SHAKE_256F_SIGNATURE_BYTES], + const uint8_t private_key[BCM_SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES], + const uint8_t *hashed_msg, size_t hashed_msg_len, int hash_nid, + const uint8_t *context, size_t context_len) { + if (context_len > MAX_CONTEXT_LENGTH) { + return bcm_status::failure; + } + + uint8_t M_prime_header[2]; + M_prime_header[0] = 1; + M_prime_header[1] = (uint8_t)context_len; + + uint8_t context_and_oid[MAX_CONTEXT_LENGTH + MAX_OID_LENGTH]; + size_t context_and_oid_len; + if (!slhdsa_get_context_and_oid(context_and_oid, &context_and_oid_len, + sizeof(context_and_oid), context, context_len, + hash_nid, hashed_msg_len)) { + return bcm_status::failure; + } + + uint8_t entropy[BCM_SLHDSA_SHAKE_256F_N]; + RAND_bytes(entropy, sizeof(entropy)); + 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; +} + // Implements Algorithm 24: slh_verify function (Section 10.3, page 41) -bcm_status BCM_slhdsa_sha2_128s_verify( +bcm_status bssl::BCM_slhdsa_sha2_128s_verify( const uint8_t *signature, size_t signature_len, const uint8_t public_key[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], const uint8_t *msg, size_t msg_len, const uint8_t *context, @@ -258,7 +592,25 @@ bcm_status BCM_slhdsa_sha2_128s_verify( context_len, msg, msg_len); } -bcm_status BCM_slhdsa_sha2_128s_prehash_verify( +bcm_status bssl::BCM_slhdsa_shake_256f_verify( + const uint8_t *signature, size_t signature_len, + const uint8_t public_key[BCM_SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], + const uint8_t *msg, size_t msg_len, const uint8_t *context, + size_t context_len) { + if (context_len > MAX_CONTEXT_LENGTH) { + return bcm_status::failure; + } + + uint8_t M_prime_header[2]; + M_prime_header[0] = 0; + M_prime_header[1] = (uint8_t)context_len; + + return BCM_slhdsa_shake_256f_verify_internal( + signature, signature_len, public_key, M_prime_header, context, + context_len, msg, msg_len); +} + +bcm_status bssl::BCM_slhdsa_sha2_128s_prehash_verify( const uint8_t *signature, size_t signature_len, const uint8_t public_key[BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], const uint8_t *hashed_msg, size_t hashed_msg_len, int hash_nid, @@ -284,46 +636,55 @@ bcm_status BCM_slhdsa_sha2_128s_prehash_verify( context_and_oid_len, hashed_msg, hashed_msg_len); } -bcm_status BCM_slhdsa_sha2_128s_verify_internal( +bcm_status bssl::BCM_slhdsa_shake_256f_prehash_verify( + const uint8_t *signature, size_t signature_len, + const uint8_t public_key[BCM_SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], + const uint8_t *hashed_msg, size_t hashed_msg_len, int hash_nid, + const uint8_t *context, size_t context_len) { + if (context_len > MAX_CONTEXT_LENGTH) { + return bcm_status::failure; + } + + uint8_t M_prime_header[2]; + M_prime_header[0] = 1; + M_prime_header[1] = (uint8_t)context_len; + + uint8_t context_and_oid[MAX_CONTEXT_LENGTH + MAX_OID_LENGTH]; + size_t context_and_oid_len; + if (!slhdsa_get_context_and_oid(context_and_oid, &context_and_oid_len, + sizeof(context_and_oid), context, context_len, + hash_nid, hashed_msg_len)) { + return bcm_status::failure; + } + + return BCM_slhdsa_shake_256f_verify_internal( + signature, signature_len, public_key, M_prime_header, context_and_oid, + context_and_oid_len, hashed_msg, hashed_msg_len); +} + +bcm_status bssl::BCM_slhdsa_sha2_128s_verify_internal( const uint8_t *signature, size_t signature_len, const uint8_t public_key[BCM_SLHDSA_SHA2_128S_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) { - if (signature_len != BCM_SLHDSA_SHA2_128S_SIGNATURE_BYTES) { - return bcm_status::failure; - } - const uint8_t *pk_seed = public_key; - const uint8_t *pk_root = public_key + BCM_SLHDSA_SHA2_128S_N; - - const uint8_t *r = signature; - const uint8_t *sig_fors = signature + BCM_SLHDSA_SHA2_128S_N; - const uint8_t *sig_ht = sig_fors + SLHDSA_SHA2_128S_FORS_BYTES; - - uint8_t digest[SLHDSA_SHA2_128S_DIGEST_SIZE]; - slhdsa_thash_hmsg(digest, r, pk_seed, pk_root, header, context, context_len, - msg, msg_len); - - uint8_t fors_digest[SLHDSA_SHA2_128S_FORS_MSG_BYTES]; - OPENSSL_memcpy(fors_digest, digest, SLHDSA_SHA2_128S_FORS_MSG_BYTES); - - const uint64_t idx_tree = - load_tree_index(digest + SLHDSA_SHA2_128S_FORS_MSG_BYTES); - uint32_t idx_leaf = CRYPTO_load_u16_be( - digest + SLHDSA_SHA2_128S_FORS_MSG_BYTES + SLHDSA_SHA2_128S_TREE_BYTES); - idx_leaf &= (~(uint32_t)0) >> (32 - SLHDSA_SHA2_128S_LEAF_BITS); - - uint8_t addr[32] = {0}; - slhdsa_set_tree_addr(addr, idx_tree); - slhdsa_set_type(addr, SLHDSA_SHA2_128S_ADDR_TYPE_FORSTREE); - slhdsa_set_keypair_addr(addr, idx_leaf); - - uint8_t pk_fors[BCM_SLHDSA_SHA2_128S_N]; - slhdsa_fors_pk_from_sig(pk_fors, sig_fors, fors_digest, pk_seed, addr); - - if (!slhdsa_ht_verify(sig_ht, pk_fors, idx_tree, idx_leaf, pk_root, - pk_seed)) { - return bcm_status::failure; - } - - return bcm_status::approved; + fips::ensure_verify_self_test(); + return verify_internal(&kSLHDSAConfigSHA2_128s, signature, signature_len, + public_key, header, context, context_len, msg, + msg_len); +} + +bcm_status bssl::BCM_slhdsa_shake_256f_verify_internal( + const uint8_t *signature, size_t signature_len, + 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); +} + +int bssl::boringssl_self_test_slhdsa() { + return fips::keygen_self_test() && fips::sign_self_test() && + fips::verify_self_test(); } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/thash.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/thash.cc.inc index e403945e..490cb3fe 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/thash.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/thash.cc.inc @@ -1,173 +1,326 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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 "../../internal.h" -#include "./params.h" +#include "../keccak/internal.h" #include "./thash.h" -// Internal thash function used by F, H, and T_l (Section 11.2, pages 44-46) -static void slhdsa_thash(uint8_t output[BCM_SLHDSA_SHA2_128S_N], - const uint8_t *input, size_t input_blocks, - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]) { +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) +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]) { + BSSL_CHECK(config->hash_type == SLH_DSA_HASH_SHA2_256); SHA256_CTX sha256; SHA256_Init(&sha256); - // Process pubseed with padding to full block. - static const uint8_t kZeros[64 - BCM_SLHDSA_SHA2_128S_N] = {0}; - SHA256_Update(&sha256, pk_seed, BCM_SLHDSA_SHA2_128S_N); - SHA256_Update(&sha256, kZeros, sizeof(kZeros)); - SHA256_Update(&sha256, addr, SLHDSA_SHA2_128S_SHA256_ADDR_BYTES); - SHA256_Update(&sha256, input, input_blocks * BCM_SLHDSA_SHA2_128S_N); + 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); + SHA256_Update(&sha256, addr, SLHDSA_ADDR_COMPRESSED_BYTES); + SHA256_Update(&sha256, input, input_blocks * config->n); - uint8_t hash[32]; + uint8_t hash[SLHDSA_MAX_DIGEST_SIZE]; SHA256_Final(hash, &sha256); - OPENSSL_memcpy(output, hash, BCM_SLHDSA_SHA2_128S_N); + OPENSSL_memcpy(output, hash, config->n); +} + +// Internal thash function used by F, H, and T_l for SHAKE-256 based parameter +// sets (Section 11.1, pages 43-45) +static void slhdsa_thash_shake(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]) { + BSSL_CHECK(config->hash_type == SLH_DSA_HASH_SHAKE_256); + BSSL_CHECK(!config->compressed_addresses); + + struct BORINGSSL_keccak_st ctx; + BORINGSSL_keccak_init(&ctx, boringssl_shake256); + BORINGSSL_keccak_absorb(&ctx, pk_seed, config->n); + BORINGSSL_keccak_absorb(&ctx, addr, SLHDSA_ADDR_BYTES); + BORINGSSL_keccak_absorb(&ctx, input, input_blocks * config->n); + BORINGSSL_keccak_squeeze(&ctx, output, config->n); +} + +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]) { + switch (config->hash_type) { + case SLH_DSA_HASH_SHA2_256: + slhdsa_thash_sha256(config, output, input, input_blocks, pk_seed, addr); + return; + case SLH_DSA_HASH_SHAKE_256: + slhdsa_thash_shake(config, output, input, input_blocks, pk_seed, addr); + return; + } + BSSL_CHECK(false); } // Implements PRF_msg function (Section 4.1, page 11 and Section 11.2, pages // 44-46) -void slhdsa_thash_prfmsg(uint8_t output[BCM_SLHDSA_SHA2_128S_N], - const uint8_t sk_prf[BCM_SLHDSA_SHA2_128S_N], - const uint8_t entropy[BCM_SLHDSA_SHA2_128S_N], - const uint8_t header[BCM_SLHDSA_M_PRIME_HEADER_LEN], - const uint8_t *ctx, size_t ctx_len, const uint8_t *msg, - size_t msg_len) { +static void slhdsa_thash_prfmsg_sha256(const slh_dsa_config *config, + uint8_t *output, const uint8_t *sk_prf, + const uint8_t *entropy, + const uint8_t *header, + const uint8_t *ctx, size_t ctx_len, + const uint8_t *msg, size_t msg_len) { + BSSL_CHECK(config->hash_type == SLH_DSA_HASH_SHA2_256); // Compute HMAC-SHA256(sk_prf, entropy || header || ctx || msg). We inline // HMAC to avoid an allocation. uint8_t hmac_key[SHA256_CBLOCK]; - static_assert(BCM_SLHDSA_SHA2_128S_N <= SHA256_CBLOCK, - "HMAC key is larger than block size"); - OPENSSL_memcpy(hmac_key, sk_prf, BCM_SLHDSA_SHA2_128S_N); - for (size_t i = 0; i < BCM_SLHDSA_SHA2_128S_N; i++) { + BSSL_CHECK(config->n <= sizeof(hmac_key)); + OPENSSL_memcpy(hmac_key, sk_prf, config->n); + for (size_t i = 0; i < config->n; i++) { hmac_key[i] ^= 0x36; } - OPENSSL_memset(hmac_key + BCM_SLHDSA_SHA2_128S_N, 0x36, - sizeof(hmac_key) - BCM_SLHDSA_SHA2_128S_N); + OPENSSL_memset(hmac_key + config->n, 0x36, sizeof(hmac_key) - config->n); SHA256_CTX sha_ctx; SHA256_Init(&sha_ctx); SHA256_Update(&sha_ctx, hmac_key, sizeof(hmac_key)); - SHA256_Update(&sha_ctx, entropy, BCM_SLHDSA_SHA2_128S_N); + SHA256_Update(&sha_ctx, entropy, config->n); if (header) { SHA256_Update(&sha_ctx, header, BCM_SLHDSA_M_PRIME_HEADER_LEN); } - SHA256_Update(&sha_ctx, ctx, ctx_len); - SHA256_Update(&sha_ctx, msg, msg_len); + if (ctx_len != 0) { + SHA256_Update(&sha_ctx, ctx, ctx_len); + } + if (msg_len != 0) { + SHA256_Update(&sha_ctx, msg, msg_len); + } uint8_t hash[SHA256_DIGEST_LENGTH]; SHA256_Final(hash, &sha_ctx); - for (size_t i = 0; i < BCM_SLHDSA_SHA2_128S_N; i++) { + for (size_t i = 0; i < config->n; i++) { hmac_key[i] ^= 0x36 ^ 0x5c; } - OPENSSL_memset(hmac_key + BCM_SLHDSA_SHA2_128S_N, 0x5c, - sizeof(hmac_key) - BCM_SLHDSA_SHA2_128S_N); + OPENSSL_memset(hmac_key + config->n, 0x5c, sizeof(hmac_key) - config->n); SHA256_Init(&sha_ctx); SHA256_Update(&sha_ctx, hmac_key, sizeof(hmac_key)); SHA256_Update(&sha_ctx, hash, sizeof(hash)); SHA256_Final(hash, &sha_ctx); - // Truncate to BCM_SLHDSA_SHA2_128S_N bytes - OPENSSL_memcpy(output, hash, BCM_SLHDSA_SHA2_128S_N); + // Truncate to n bytes + OPENSSL_memcpy(output, hash, config->n); +} + +static void slhdsa_thash_prfmsg_shake(const slh_dsa_config *config, + uint8_t *output, const uint8_t *sk_prf, + const uint8_t *entropy, + const uint8_t *header, + const uint8_t *ctx, size_t ctx_len, + const uint8_t *msg, size_t msg_len) { + BSSL_CHECK(config->hash_type == SLH_DSA_HASH_SHAKE_256); + + struct BORINGSSL_keccak_st keccak; + BORINGSSL_keccak_init(&keccak, boringssl_shake256); + BORINGSSL_keccak_absorb(&keccak, sk_prf, config->n); + BORINGSSL_keccak_absorb(&keccak, entropy, config->n); + if (header) { + BORINGSSL_keccak_absorb(&keccak, header, BCM_SLHDSA_M_PRIME_HEADER_LEN); + } + if (ctx_len != 0) { + BORINGSSL_keccak_absorb(&keccak, ctx, ctx_len); + } + if (msg_len != 0) { + BORINGSSL_keccak_absorb(&keccak, msg, msg_len); + } + BORINGSSL_keccak_squeeze(&keccak, output, config->n); +} + +void bssl::slhdsa_thash_prfmsg(const slh_dsa_config *config, uint8_t *output, + const uint8_t *sk_prf, const uint8_t *entropy, + const uint8_t *header, const uint8_t *ctx, + size_t ctx_len, const uint8_t *msg, + size_t msg_len) { + switch (config->hash_type) { + case SLH_DSA_HASH_SHA2_256: + slhdsa_thash_prfmsg_sha256(config, output, sk_prf, entropy, header, ctx, + ctx_len, msg, msg_len); + return; + case SLH_DSA_HASH_SHAKE_256: + slhdsa_thash_prfmsg_shake(config, output, sk_prf, entropy, header, ctx, + ctx_len, msg, msg_len); + return; + } + BSSL_CHECK(false); } // Implements H_msg function (Section 4.1, page 11 and Section 11.2, pages // 44-46) -void slhdsa_thash_hmsg(uint8_t output[SLHDSA_SHA2_128S_DIGEST_SIZE], - const uint8_t r[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_root[BCM_SLHDSA_SHA2_128S_N], - const uint8_t header[BCM_SLHDSA_M_PRIME_HEADER_LEN], - const uint8_t *ctx, size_t ctx_len, const uint8_t *msg, - size_t msg_len) { +static void slhdsa_thash_hmsg_sha256(const slh_dsa_config *config, + uint8_t *output, const uint8_t *r, + const uint8_t *pk_seed, + const uint8_t *pk_root, + const uint8_t *header, + const uint8_t *ctx, size_t ctx_len, + const uint8_t *msg, size_t msg_len) { + BSSL_CHECK(config->hash_type == SLH_DSA_HASH_SHA2_256); // MGF1-SHA-256(R || PK.seed || SHA-256(R || PK.seed || PK.root || header || // ctx || M), m) input_buffer stores R || PK_SEED || SHA256(..) || 4-byte // index - uint8_t input_buffer[2 * BCM_SLHDSA_SHA2_128S_N + 32 + 4] = {0}; - OPENSSL_memcpy(input_buffer, r, BCM_SLHDSA_SHA2_128S_N); - OPENSSL_memcpy(input_buffer + BCM_SLHDSA_SHA2_128S_N, pk_seed, - BCM_SLHDSA_SHA2_128S_N); + uint8_t input_buffer[2 * SLHDSA_MAX_N + SLHDSA_MAX_DIGEST_SIZE + 4] = {0}; + OPENSSL_memcpy(input_buffer, r, config->n); + OPENSSL_memcpy(input_buffer + config->n, pk_seed, config->n); // Inner hash SHA256_CTX sha_ctx; SHA256_Init(&sha_ctx); - SHA256_Update(&sha_ctx, r, BCM_SLHDSA_SHA2_128S_N); - SHA256_Update(&sha_ctx, pk_seed, BCM_SLHDSA_SHA2_128S_N); - SHA256_Update(&sha_ctx, pk_root, BCM_SLHDSA_SHA2_128S_N); + SHA256_Update(&sha_ctx, r, config->n); + SHA256_Update(&sha_ctx, pk_seed, config->n); + SHA256_Update(&sha_ctx, pk_root, config->n); if (header) { SHA256_Update(&sha_ctx, header, BCM_SLHDSA_M_PRIME_HEADER_LEN); } - SHA256_Update(&sha_ctx, ctx, ctx_len); - SHA256_Update(&sha_ctx, msg, msg_len); + if (ctx_len != 0) { + SHA256_Update(&sha_ctx, ctx, ctx_len); + } + if (msg_len != 0) { + SHA256_Update(&sha_ctx, msg, msg_len); + } // Write directly into the input buffer - SHA256_Final(input_buffer + 2 * BCM_SLHDSA_SHA2_128S_N, &sha_ctx); + SHA256_Final(input_buffer + 2 * config->n, &sha_ctx); // MGF1-SHA-256 uint8_t hash[32]; - static_assert(SLHDSA_SHA2_128S_DIGEST_SIZE < sizeof(hash), - "More MGF1 iterations required"); - SHA256(input_buffer, sizeof(input_buffer), hash); - OPENSSL_memcpy(output, hash, SLHDSA_SHA2_128S_DIGEST_SIZE); + BSSL_CHECK(config->digest_size <= sizeof(hash)); + BSSL_CHECK(config->hash_output_bytes == sizeof(hash)); + const size_t mgf_input_len = + 2 * config->n + config->hash_output_bytes + 4; + SHA256(input_buffer, mgf_input_len, hash); + OPENSSL_memcpy(output, hash, config->digest_size); +} + +static void slhdsa_thash_hmsg_shake(const slh_dsa_config *config, + uint8_t *output, const uint8_t *r, + const uint8_t *pk_seed, + const uint8_t *pk_root, + const uint8_t *header, + const uint8_t *ctx, size_t ctx_len, + const uint8_t *msg, size_t msg_len) { + BSSL_CHECK(config->hash_type == SLH_DSA_HASH_SHAKE_256); + + struct BORINGSSL_keccak_st keccak; + BORINGSSL_keccak_init(&keccak, boringssl_shake256); + BORINGSSL_keccak_absorb(&keccak, r, config->n); + BORINGSSL_keccak_absorb(&keccak, pk_seed, config->n); + BORINGSSL_keccak_absorb(&keccak, pk_root, config->n); + if (header) { + BORINGSSL_keccak_absorb(&keccak, header, BCM_SLHDSA_M_PRIME_HEADER_LEN); + } + if (ctx_len != 0) { + BORINGSSL_keccak_absorb(&keccak, ctx, ctx_len); + } + if (msg_len != 0) { + BORINGSSL_keccak_absorb(&keccak, msg, msg_len); + } + BORINGSSL_keccak_squeeze(&keccak, output, config->digest_size); +} + +void bssl::slhdsa_thash_hmsg(const slh_dsa_config *config, uint8_t *output, + const uint8_t *r, const uint8_t *pk_seed, + const uint8_t *pk_root, const uint8_t *header, + const uint8_t *ctx, size_t ctx_len, + const uint8_t *msg, size_t msg_len) { + switch (config->hash_type) { + case SLH_DSA_HASH_SHA2_256: + slhdsa_thash_hmsg_sha256(config, output, r, pk_seed, pk_root, header, ctx, + ctx_len, msg, msg_len); + return; + case SLH_DSA_HASH_SHAKE_256: + slhdsa_thash_hmsg_shake(config, output, r, pk_seed, pk_root, header, ctx, + ctx_len, msg, msg_len); + return; + } + BSSL_CHECK(false); } // Implements PRF function (Section 4.1, page 11 and Section 11.2, pages 44-46) -void slhdsa_thash_prf(uint8_t output[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]) { - slhdsa_thash(output, sk_seed, 1, pk_seed, addr); +static void slhdsa_thash_prf_sha256(const slh_dsa_config *config, + uint8_t *output, const uint8_t *pk_seed, + const uint8_t *sk_seed, uint8_t addr[32]) { + slhdsa_thash_sha256(config, output, sk_seed, 1, pk_seed, addr); +} + +static void slhdsa_thash_prf_shake(const slh_dsa_config *config, + uint8_t *output, const uint8_t *pk_seed, + const uint8_t *sk_seed, uint8_t addr[32]) { + BSSL_CHECK(config->hash_type == SLH_DSA_HASH_SHAKE_256); + BSSL_CHECK(!config->compressed_addresses); + + struct BORINGSSL_keccak_st keccak; + BORINGSSL_keccak_init(&keccak, boringssl_shake256); + BORINGSSL_keccak_absorb(&keccak, pk_seed, config->n); + BORINGSSL_keccak_absorb(&keccak, addr, SLHDSA_ADDR_BYTES); + BORINGSSL_keccak_absorb(&keccak, sk_seed, config->n); + BORINGSSL_keccak_squeeze(&keccak, output, config->n); +} + +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]) { + switch (config->hash_type) { + case SLH_DSA_HASH_SHA2_256: + slhdsa_thash_prf_sha256(config, output, pk_seed, sk_seed, addr); + return; + case SLH_DSA_HASH_SHAKE_256: + slhdsa_thash_prf_shake(config, output, pk_seed, sk_seed, addr); + return; + } + BSSL_CHECK(false); } // Implements T_l function for WOTS+ public key compression (Section 4.1, page // 11 and Section 11.2, pages 44-46) -void slhdsa_thash_tl(uint8_t output[BCM_SLHDSA_SHA2_128S_N], - const uint8_t input[SLHDSA_SHA2_128S_WOTS_BYTES], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]) { - slhdsa_thash(output, input, SLHDSA_SHA2_128S_WOTS_LEN, pk_seed, addr); +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); } // Implements H function (Section 4.1, page 11 and Section 11.2, pages 44-46) -void slhdsa_thash_h(uint8_t output[BCM_SLHDSA_SHA2_128S_N], - const uint8_t input[2 * BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]) { - slhdsa_thash(output, input, 2, pk_seed, addr); +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); } // Implements F function (Section 4.1, page 11 and Section 11.2, pages 44-46) -void slhdsa_thash_f(uint8_t output[BCM_SLHDSA_SHA2_128S_N], - const uint8_t input[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]) { - slhdsa_thash(output, input, 1, pk_seed, addr); +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); } // Implements T_k function for FORS public key compression (Section 4.1, page 11 // and Section 11.2, pages 44-46) -void slhdsa_thash_tk( - uint8_t output[BCM_SLHDSA_SHA2_128S_N], - const uint8_t input[SLHDSA_SHA2_128S_FORS_TREES * BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], uint8_t addr[32]) { - slhdsa_thash(output, input, SLHDSA_SHA2_128S_FORS_TREES, pk_seed, addr); +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, + addr); } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/thash.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/thash.h index b861de56..23a42c6b 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/thash.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/thash.h @@ -1,85 +1,71 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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. #ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_THASH_H #define OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_THASH_H #include "./params.h" -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN // 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) -void slhdsa_thash_prfmsg(uint8_t output[BCM_SLHDSA_SHA2_128S_N], - const uint8_t sk_prf[BCM_SLHDSA_SHA2_128S_N], - const uint8_t opt_rand[BCM_SLHDSA_SHA2_128S_N], - const uint8_t header[BCM_SLHDSA_M_PRIME_HEADER_LEN], - const uint8_t *ctx, size_t ctx_len, const uint8_t *msg, - size_t msg_len); +void slhdsa_thash_prfmsg(const slh_dsa_config *config, uint8_t *output, + const uint8_t *sk_prf, const uint8_t *opt_rand, + const uint8_t *header, const uint8_t *ctx, + size_t ctx_len, const uint8_t *msg, size_t msg_len); // Implements H_msg: a hash function used to generate the digest of the message // to be signed. (Section 4.1, page 11) -void slhdsa_thash_hmsg(uint8_t output[SLHDSA_SHA2_128S_DIGEST_SIZE], - const uint8_t r[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_root[BCM_SLHDSA_SHA2_128S_N], - const uint8_t header[BCM_SLHDSA_M_PRIME_HEADER_LEN], +void slhdsa_thash_hmsg(const slh_dsa_config *config, uint8_t *output, + const uint8_t *r, const uint8_t *pk_seed, + const uint8_t *pk_root, const uint8_t *header, const uint8_t *ctx, size_t ctx_len, const uint8_t *msg, size_t msg_len); // 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(uint8_t output[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], +void 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]); // 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(uint8_t output[BCM_SLHDSA_SHA2_128S_N], - const uint8_t input[SLHDSA_SHA2_128S_WOTS_BYTES], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], +void slhdsa_thash_tl(const slh_dsa_config *config, uint8_t *output, + const uint8_t *input, const uint8_t *pk_seed, 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(uint8_t output[BCM_SLHDSA_SHA2_128S_N], - const uint8_t input[2 * BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], +void slhdsa_thash_h(const slh_dsa_config *config, uint8_t *output, + const uint8_t *input, const uint8_t *pk_seed, 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(uint8_t output[BCM_SLHDSA_SHA2_128S_N], - const uint8_t input[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], +void slhdsa_thash_f(const slh_dsa_config *config, uint8_t *output, + const uint8_t *input, const uint8_t *pk_seed, 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( - uint8_t output[BCM_SLHDSA_SHA2_128S_N], - const uint8_t input[SLHDSA_SHA2_128S_FORS_TREES * BCM_SLHDSA_SHA2_128S_N], - const uint8_t pk_seed[BCM_SLHDSA_SHA2_128S_N], uint8_t addr[32]); +void slhdsa_thash_tk(const slh_dsa_config *config, uint8_t *output, + const uint8_t *input, const uint8_t *pk_seed, + uint8_t addr[32]); - -#if defined(__cplusplus) -} // extern C -#endif +BSSL_NAMESPACE_END #endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_THASH_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/wots.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/wots.cc.inc index 6ac97d3f..251c76d9 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/wots.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/wots.cc.inc @@ -1,16 +1,16 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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 @@ -25,147 +25,148 @@ #include "./wots.h" +using namespace bssl; + // Implements Algorithm 5: chain function, page 18 -static void chain(uint8_t output[BCM_SLHDSA_SHA2_128S_N], - const uint8_t input[BCM_SLHDSA_SHA2_128S_N], uint32_t start, - uint32_t steps, const uint8_t pub_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]) { - assert(start < SLHDSA_SHA2_128S_WOTS_W); - assert(steps < SLHDSA_SHA2_128S_WOTS_W); +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]) { + assert(start < config->wots_w); + assert(steps < config->wots_w); - OPENSSL_memcpy(output, input, BCM_SLHDSA_SHA2_128S_N); + OPENSSL_memcpy(output, input, config->n); - for (size_t i = start; i < (start + steps) && i < SLHDSA_SHA2_128S_WOTS_W; - ++i) { - slhdsa_set_hash_addr(addr, i); - slhdsa_thash_f(output, output, pub_seed, addr); + 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); } } -static void slhdsa_wots_do_chain(uint8_t out[BCM_SLHDSA_SHA2_128S_N], +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[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pub_seed[BCM_SLHDSA_SHA2_128S_N], + uint8_t value, const uint8_t *sk_seed, + const uint8_t *pub_seed, uint32_t chain_index) { - uint8_t tmp_sk[BCM_SLHDSA_SHA2_128S_N]; - slhdsa_set_chain_addr(sk_addr, chain_index); - slhdsa_thash_prf(tmp_sk, pub_seed, sk_seed, sk_addr); - slhdsa_set_chain_addr(addr, chain_index); - chain(out, tmp_sk, 0, value, pub_seed, addr); + 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_set_chain_addr(config, addr, chain_index); + chain(config, out, tmp_sk, 0, value, pub_seed, addr); } // Implements Algorithm 6: wots_pkGen function, page 18 -void slhdsa_wots_pk_gen(uint8_t pk[BCM_SLHDSA_SHA2_128S_N], - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pub_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]) { +void bssl::slhdsa_wots_pk_gen(const slh_dsa_config *config, uint8_t *pk, + const uint8_t *sk_seed, const uint8_t *pub_seed, + uint8_t addr[32]) { uint8_t wots_pk_addr[32], sk_addr[32]; OPENSSL_memcpy(wots_pk_addr, addr, sizeof(wots_pk_addr)); OPENSSL_memcpy(sk_addr, addr, sizeof(sk_addr)); - slhdsa_set_type(sk_addr, SLHDSA_SHA2_128S_ADDR_TYPE_WOTSPRF); - slhdsa_copy_keypair_addr(sk_addr, addr); + slhdsa_set_type(config, sk_addr, SLHDSA_ADDR_TYPE_WOTSPRF); + slhdsa_copy_keypair_addr(config, sk_addr, addr); - uint8_t tmp[SLHDSA_SHA2_128S_WOTS_BYTES]; - for (size_t i = 0; i < SLHDSA_SHA2_128S_WOTS_LEN; ++i) { - slhdsa_wots_do_chain(tmp + i * BCM_SLHDSA_SHA2_128S_N, sk_addr, addr, - SLHDSA_SHA2_128S_WOTS_W - 1, sk_seed, pub_seed, i); + uint8_t tmp[SLHDSA_MAX_WOTS_BYTES]; + const uint32_t n = config->n; + const uint32_t wots_len = slhdsa_wots_len(config); + 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); } // Compress pk - slhdsa_set_type(wots_pk_addr, SLHDSA_SHA2_128S_ADDR_TYPE_WOTSPK); - slhdsa_copy_keypair_addr(wots_pk_addr, addr); - slhdsa_thash_tl(pk, tmp, pub_seed, wots_pk_addr); + 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); } // Implements Algorithm 7: wots_sign function, page 20 -void slhdsa_wots_sign(uint8_t sig[SLHDSA_SHA2_128S_WOTS_BYTES], - const uint8_t msg[BCM_SLHDSA_SHA2_128S_N], - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pub_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]) { - // Compute checksum - static_assert(SLHDSA_SHA2_128S_WOTS_LEN1 == BCM_SLHDSA_SHA2_128S_N * 2, ""); +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]) { + BSSL_CHECK(config->wots_w == 16); + const size_t n = config->n; + const uint32_t max_chain = config->wots_w - 1; + uint16_t csum = 0; - for (size_t i = 0; i < BCM_SLHDSA_SHA2_128S_N; ++i) { - csum += SLHDSA_SHA2_128S_WOTS_W - 1 - (msg[i] >> 4); - csum += SLHDSA_SHA2_128S_WOTS_W - 1 - (msg[i] & 15); + for (size_t i = 0; i < n; ++i) { + csum += max_chain - (msg[i] >> 4); + csum += max_chain - (msg[i] & 15); } // Compute chains uint8_t sk_addr[32]; OPENSSL_memcpy(sk_addr, addr, sizeof(sk_addr)); - slhdsa_set_type(sk_addr, SLHDSA_SHA2_128S_ADDR_TYPE_WOTSPRF); - slhdsa_copy_keypair_addr(sk_addr, addr); + slhdsa_set_type(config, sk_addr, SLHDSA_ADDR_TYPE_WOTSPRF); + slhdsa_copy_keypair_addr(config, sk_addr, addr); uint32_t chain_index = 0; - for (size_t i = 0; i < BCM_SLHDSA_SHA2_128S_N; ++i) { - slhdsa_wots_do_chain(sig, sk_addr, addr, msg[i] >> 4, sk_seed, pub_seed, - chain_index++); - sig += BCM_SLHDSA_SHA2_128S_N; + 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++); + sig += n; - slhdsa_wots_do_chain(sig, sk_addr, addr, msg[i] & 15, sk_seed, pub_seed, - chain_index++); - sig += BCM_SLHDSA_SHA2_128S_N; + slhdsa_wots_do_chain(config, sig, sk_addr, addr, msg[i] & 15, sk_seed, + pub_seed, chain_index++); + sig += n; } - // Include the SLHDSA_SHA2_128S_WOTS_LEN2 checksum values. - slhdsa_wots_do_chain(sig, sk_addr, addr, (csum >> 8) & 15, sk_seed, pub_seed, - chain_index++); - sig += BCM_SLHDSA_SHA2_128S_N; - slhdsa_wots_do_chain(sig, sk_addr, addr, (csum >> 4) & 15, sk_seed, pub_seed, - chain_index++); - sig += BCM_SLHDSA_SHA2_128S_N; - slhdsa_wots_do_chain(sig, sk_addr, addr, csum & 15, sk_seed, pub_seed, + // 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++); + sig += n; + slhdsa_wots_do_chain(config, sig, sk_addr, addr, (csum >> 4) & 15, sk_seed, + pub_seed, chain_index++); + sig += n; + slhdsa_wots_do_chain(config, sig, sk_addr, addr, csum & 15, sk_seed, pub_seed, chain_index++); } -static void slhdsa_wots_pk_from_sig_do_chain( - uint8_t out[SLHDSA_SHA2_128S_WOTS_BYTES], uint8_t addr[32], - const uint8_t in[SLHDSA_SHA2_128S_WOTS_BYTES], uint8_t value, - const uint8_t pub_seed[BCM_SLHDSA_SHA2_128S_N], uint32_t chain_index) { - slhdsa_set_chain_addr(addr, chain_index); - chain(out + chain_index * BCM_SLHDSA_SHA2_128S_N, - in + chain_index * BCM_SLHDSA_SHA2_128S_N, value, - SLHDSA_SHA2_128S_WOTS_W - 1 - value, pub_seed, addr); +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, + 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); } // Implements Algorithm 8: wots_pkFromSig function, page 21 -void slhdsa_wots_pk_from_sig(uint8_t pk[BCM_SLHDSA_SHA2_128S_N], - const uint8_t sig[SLHDSA_SHA2_128S_WOTS_BYTES], - const uint8_t msg[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pub_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]) { - // Compute checksum - static_assert(SLHDSA_SHA2_128S_WOTS_LEN1 == BCM_SLHDSA_SHA2_128S_N * 2, ""); +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]) { + BSSL_CHECK(config->wots_w == 16); + const size_t n = config->n; + const uint32_t max_chain = config->wots_w - 1; + uint16_t csum = 0; - for (size_t i = 0; i < BCM_SLHDSA_SHA2_128S_N; ++i) { - csum += SLHDSA_SHA2_128S_WOTS_W - 1 - (msg[i] >> 4); - csum += SLHDSA_SHA2_128S_WOTS_W - 1 - (msg[i] & 15); + for (size_t i = 0; i < n; ++i) { + csum += max_chain - (msg[i] >> 4); + csum += max_chain - (msg[i] & 15); } - uint8_t tmp[SLHDSA_SHA2_128S_WOTS_BYTES]; + uint8_t tmp[SLHDSA_MAX_WOTS_BYTES]; uint8_t wots_pk_addr[32]; OPENSSL_memcpy(wots_pk_addr, addr, sizeof(wots_pk_addr)); uint32_t chain_index = 0; - static_assert(SLHDSA_SHA2_128S_WOTS_LEN1 == BCM_SLHDSA_SHA2_128S_N * 2, ""); - for (size_t i = 0; i < BCM_SLHDSA_SHA2_128S_N; ++i) { - slhdsa_wots_pk_from_sig_do_chain(tmp, addr, sig, msg[i] >> 4, pub_seed, - chain_index++); - slhdsa_wots_pk_from_sig_do_chain(tmp, addr, sig, msg[i] & 15, pub_seed, - chain_index++); + 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++); + slhdsa_wots_pk_from_sig_do_chain(config, tmp, addr, sig, msg[i] & 15, + pub_seed, chain_index++); } - slhdsa_wots_pk_from_sig_do_chain(tmp, addr, sig, csum >> 8, pub_seed, + slhdsa_wots_pk_from_sig_do_chain(config, tmp, addr, sig, csum >> 8, pub_seed, chain_index++); - slhdsa_wots_pk_from_sig_do_chain(tmp, addr, sig, (csum >> 4) & 15, pub_seed, - chain_index++); - slhdsa_wots_pk_from_sig_do_chain(tmp, addr, sig, csum & 15, pub_seed, + 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, chain_index++); // Compress pk - slhdsa_set_type(wots_pk_addr, SLHDSA_SHA2_128S_ADDR_TYPE_WOTSPK); - slhdsa_copy_keypair_addr(wots_pk_addr, addr); - slhdsa_thash_tl(pk, tmp, pub_seed, wots_pk_addr); + 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); } diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/wots.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/wots.h index 29a72ec6..28afeb05 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/wots.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/slhdsa/wots.h @@ -1,50 +1,40 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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. #ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_WOTS_H #define OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_WOTS_H #include "./params.h" -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN // Implements Algorithm 6: wots_pkGen function, page 18 -void slhdsa_wots_pk_gen(uint8_t pk[BCM_SLHDSA_SHA2_128S_N], - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pub_seed[BCM_SLHDSA_SHA2_128S_N], +void slhdsa_wots_pk_gen(const slh_dsa_config *config, uint8_t *pk, + const uint8_t *sk_seed, const uint8_t *pub_seed, uint8_t addr[32]); // Implements Algorithm 7: wots_sign function, page 20 -void slhdsa_wots_sign(uint8_t sig[SLHDSA_SHA2_128S_WOTS_BYTES], - const uint8_t msg[BCM_SLHDSA_SHA2_128S_N], - const uint8_t sk_seed[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pub_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]); +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]); // Implements Algorithm 8: wots_pkFromSig function, page 21 -void slhdsa_wots_pk_from_sig(uint8_t pk[BCM_SLHDSA_SHA2_128S_N], - const uint8_t sig[SLHDSA_SHA2_128S_WOTS_BYTES], - const uint8_t msg[BCM_SLHDSA_SHA2_128S_N], - const uint8_t pub_seed[BCM_SLHDSA_SHA2_128S_N], - uint8_t addr[32]); +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]); - -#if defined(__cplusplus) -} // extern C -#endif +BSSL_NAMESPACE_END #endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_SLHDSA_WOTS_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/tls/internal.h b/Sources/CNIOBoringSSL/crypto/fipsmodule/tls/internal.h index 6b827f00..103643fe 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/tls/internal.h +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/tls/internal.h @@ -1,35 +1,24 @@ -/* Copyright 2018 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2018 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. #ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_TLS_INTERNAL_H #define OPENSSL_HEADER_CRYPTO_FIPSMODULE_TLS_INTERNAL_H #include -#if defined(__cplusplus) -extern "C" { -#endif - -// tls1_prf calculates |out_len| bytes of the TLS PDF, using |digest|, and -// writes them to |out|. It returns one on success and zero on error. -OPENSSL_EXPORT int CRYPTO_tls1_prf(const EVP_MD *digest, - uint8_t *out, size_t out_len, - const uint8_t *secret, size_t secret_len, - const char *label, size_t label_len, - const uint8_t *seed1, size_t seed1_len, - const uint8_t *seed2, size_t seed2_len); +BSSL_NAMESPACE_BEGIN // CRYPTO_tls13_hkdf_expand_label computes the TLS 1.3 KDF function of the same // name. See https://www.rfc-editor.org/rfc/rfc8446#section-7.1. @@ -39,9 +28,6 @@ OPENSSL_EXPORT int CRYPTO_tls13_hkdf_expand_label( const uint8_t *label, size_t label_len, // const uint8_t *hash, size_t hash_len); - -#if defined(__cplusplus) -} -#endif +BSSL_NAMESPACE_END #endif // OPENSSL_HEADER_CRYPTO_FIPSMODULE_TLS_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/fipsmodule/tls/kdf.cc.inc b/Sources/CNIOBoringSSL/crypto/fipsmodule/tls/kdf.cc.inc index 3fc88196..766a80e2 100644 --- a/Sources/CNIOBoringSSL/crypto/fipsmodule/tls/kdf.cc.inc +++ b/Sources/CNIOBoringSSL/crypto/fipsmodule/tls/kdf.cc.inc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,20 +19,22 @@ #include #include #include +#include -#include "internal.h" #include "../../internal.h" #include "../service_indicator/internal.h" +#include "internal.h" +using namespace bssl; + // tls1_P_hash computes the TLS P_ function as described in RFC 5246, -// section 5. It XORs |out_len| bytes to |out|, using |md| as the hash and -// |secret| as the secret. |label|, |seed1|, and |seed2| are concatenated to +// section 5. It XORs `out_len` bytes to `out`, using `md` as the hash and +// `secret` as the secret. `label`, `seed1`, and `seed2` are concatenated to // form the seed parameter. It returns true on success and false on failure. -static int tls1_P_hash(uint8_t *out, size_t out_len, - const EVP_MD *md, +static int tls1_P_hash(uint8_t *out, size_t out_len, const EVP_MD *md, const uint8_t *secret, size_t secret_len, - const char *label, size_t label_len, + const uint8_t *label, size_t label_len, const uint8_t *seed1, size_t seed1_len, const uint8_t *seed2, size_t seed2_len) { HMAC_CTX ctx, ctx_tmp, ctx_init; @@ -40,11 +47,11 @@ static int tls1_P_hash(uint8_t *out, size_t out_len, HMAC_CTX_init(&ctx_tmp); HMAC_CTX_init(&ctx_init); - if (!HMAC_Init_ex(&ctx_init, secret, secret_len, md, NULL) || + if (!HMAC_Init_ex(&ctx_init, secret, secret_len, md, nullptr) || !HMAC_CTX_copy_ex(&ctx, &ctx_init) || - !HMAC_Update(&ctx, (const uint8_t *) label, label_len) || + !HMAC_Update(&ctx, label, label_len) || !HMAC_Update(&ctx, seed1, seed1_len) || - !HMAC_Update(&ctx, seed2, seed2_len) || + !HMAC_Update(&ctx, seed2, seed2_len) || // !HMAC_Final(&ctx, A1, &A1_len)) { goto err; } @@ -52,11 +59,10 @@ static int tls1_P_hash(uint8_t *out, size_t out_len, for (;;) { unsigned len_u; uint8_t hmac[EVP_MAX_MD_SIZE]; - if (!HMAC_CTX_copy_ex(&ctx, &ctx_init) || - !HMAC_Update(&ctx, A1, A1_len) || - // Save a copy of |ctx| to compute the next A1 value below. + if (!HMAC_CTX_copy_ex(&ctx, &ctx_init) || !HMAC_Update(&ctx, A1, A1_len) || + // Save a copy of `ctx` to compute the next A1 value below. (out_len > chunk && !HMAC_CTX_copy_ex(&ctx_tmp, &ctx)) || - !HMAC_Update(&ctx, (const uint8_t *) label, label_len) || + !HMAC_Update(&ctx, (const uint8_t *)label, label_len) || !HMAC_Update(&ctx, seed1, seed1_len) || !HMAC_Update(&ctx, seed2, seed2_len) || !HMAC_Final(&ctx, hmac, &len_u)) { @@ -65,7 +71,7 @@ static int tls1_P_hash(uint8_t *out, size_t out_len, size_t len = len_u; assert(len == chunk); - // XOR the result into |out|. + // XOR the result into `out`. if (len > out_len) { len = out_len; } @@ -95,10 +101,9 @@ err: return ret; } -int CRYPTO_tls1_prf(const EVP_MD *digest, - uint8_t *out, size_t out_len, +int CRYPTO_tls1_prf(const EVP_MD *digest, uint8_t *out, size_t out_len, const uint8_t *secret, size_t secret_len, - const char *label, size_t label_len, + const uint8_t *label, size_t label_len, const uint8_t *seed1, size_t seed1_len, const uint8_t *seed2, size_t seed2_len) { if (out_len == 0) { @@ -112,14 +117,14 @@ int CRYPTO_tls1_prf(const EVP_MD *digest, int ret = 0; if (digest == EVP_md5_sha1()) { - // If using the MD5/SHA1 PRF, |secret| is partitioned between MD5 and SHA-1. + // If using the MD5/SHA1 PRF, `secret` is partitioned between MD5 and SHA-1. size_t secret_half = secret_len - (secret_len / 2); if (!tls1_P_hash(out, out_len, EVP_md5(), secret, secret_half, label, label_len, seed1, seed1_len, seed2, seed2_len)) { goto end; } - // Note that, if |secret_len| is odd, the two halves share a byte. + // Note that, if `secret_len` is odd, the two halves share a byte. secret += secret_len - secret_half; secret_len = secret_half; digest = EVP_sha1(); @@ -136,14 +141,15 @@ end: return ret; } -int CRYPTO_tls13_hkdf_expand_label(uint8_t *out, size_t out_len, - const EVP_MD *digest, // - const uint8_t *secret, size_t secret_len, - const uint8_t *label, size_t label_len, - const uint8_t *hash, size_t hash_len) { +int bssl::CRYPTO_tls13_hkdf_expand_label(uint8_t *out, size_t out_len, + const EVP_MD *digest, // + const uint8_t *secret, + size_t secret_len, + const uint8_t *label, size_t label_len, + const uint8_t *hash, size_t hash_len) { static const uint8_t kProtocolLabel[] = "tls13 "; CBB cbb, child; - uint8_t *hkdf_label = NULL; + uint8_t *hkdf_label = nullptr; size_t hkdf_label_len; FIPS_service_indicator_lock_state(); @@ -172,4 +178,3 @@ int CRYPTO_tls13_hkdf_expand_label(uint8_t *out, size_t out_len, } return ret; } - diff --git a/Sources/CNIOBoringSSL/crypto/fuzzer_mode.cc b/Sources/CNIOBoringSSL/crypto/fuzzer_mode.cc new file mode 100644 index 00000000..3b863dfd --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/fuzzer_mode.cc @@ -0,0 +1,30 @@ +// Copyright 2025 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 "internal.h" + + +using namespace bssl; + +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) +static bssl::Atomic fuzzer_mode_enabled = 0; + +int bssl::CRYPTO_fuzzer_mode_enabled() { return fuzzer_mode_enabled.load(); } + +void CRYPTO_set_fuzzer_mode(int enabled) { + fuzzer_mode_enabled.store(!!enabled); +} +#endif // FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION diff --git a/Sources/CNIOBoringSSL/crypto/hpke/hpke.cc b/Sources/CNIOBoringSSL/crypto/hpke/hpke.cc index aaf9a523..47af5932 100644 --- a/Sources/CNIOBoringSSL/crypto/hpke/hpke.cc +++ b/Sources/CNIOBoringSSL/crypto/hpke/hpke.cc @@ -1,45 +1,67 @@ -/* Copyright 2020 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2020 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 #include #include +#include #include -#include +#include +#include +#include #include "../fipsmodule/ec/internal.h" +#include "../fipsmodule/keccak/internal.h" #include "../internal.h" +#include "../mem_internal.h" +using namespace bssl; + // This file implements RFC 9180. -#define MAX_SEED_LEN X25519_PRIVATE_KEY_LEN +#define MAX_SEED_LEN XWING_SEED_LEN #define MAX_SHARED_SECRET_LEN SHA256_DIGEST_LENGTH struct evp_hpke_kem_st { uint16_t id; + + // 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)(); + size_t public_key_len; size_t private_key_len; size_t seed_len; @@ -47,6 +69,7 @@ struct evp_hpke_kem_st { 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, @@ -67,17 +90,32 @@ struct evp_hpke_kem_st { 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); }; struct evp_hpke_kdf_st { uint16_t id; // We only support HKDF-based KDFs. - const EVP_MD *(*hkdf_md_func)(void); + const EVP_MD *(*hkdf_md_func)(); }; struct evp_hpke_aead_st { uint16_t id; - const EVP_AEAD *(*aead_func)(void); + const EVP_AEAD *(*aead_func)(); }; @@ -126,9 +164,44 @@ 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) { + 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) { + // 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; + BORINGSSL_keccak_init(&ctx, boringssl_shake256); + BORINGSSL_keccak_absorb(&ctx, ikm.data(), ikm.size()); + auto hpke_version_id = StringAsBytes(kHpkeVersionId); + BORINGSSL_keccak_absorb(&ctx, hpke_version_id.data(), hpke_version_id.size()); + BORINGSSL_keccak_absorb(&ctx, suite_id.data(), suite_id.size()); + auto label_bytes = StringAsBytes(label); + assert(label_bytes.size() < 0xffff); + absorb_u16(&ctx, static_cast(label_bytes.size())); + BORINGSSL_keccak_absorb(&ctx, label_bytes.data(), label_bytes.size()); + assert(out.size() <= 0xffff); + absorb_u16(&ctx, static_cast(out.size())); + BORINGSSL_keccak_absorb(&ctx, context.data(), context.size()); + BORINGSSL_keccak_squeeze(&ctx, out.data(), out.size()); +} + // KEM implementations. +static 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)}; +} + // 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, @@ -136,16 +209,15 @@ static int dhkem_extract_and_expand(uint16_t kem_id, const EVP_MD *hkdf_md, const uint8_t *dh, size_t dh_len, const uint8_t *kem_context, size_t kem_context_len) { - // concat("KEM", I2OSP(kem_id, 2)) - uint8_t suite_id[5] = {'K', 'E', 'M', static_cast(kem_id >> 8), - static_cast(kem_id & 0xff)}; + auto suite_id = hpke_kem_suite_id(kem_id); uint8_t prk[EVP_MAX_MD_SIZE]; size_t prk_len; - return hpke_labeled_extract(hkdf_md, prk, &prk_len, NULL, 0, suite_id, - sizeof(suite_id), "eae_prk", dh, dh_len) && - hpke_labeled_expand(hkdf_md, out_key, out_len, prk, prk_len, suite_id, - sizeof(suite_id), "shared_secret", kem_context, - kem_context_len); + return hpke_labeled_extract(hkdf_md, prk, &prk_len, nullptr, 0, + suite_id.data(), suite_id.size(), "eae_prk", dh, + dh_len) && + hpke_labeled_expand(hkdf_md, out_key, out_len, prk, prk_len, + suite_id.data(), suite_id.size(), "shared_secret", + kem_context, kem_context_len); } static int x25519_init_key(EVP_HPKE_KEY *key, const uint8_t *priv_key, @@ -165,6 +237,23 @@ static int x25519_generate_key(EVP_HPKE_KEY *key) { return 1; } +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; + } + return x25519_init_key(key, sk, sizeof(sk)); +} + 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, @@ -296,19 +385,29 @@ static int x25519_auth_decap(const EVP_HPKE_KEY *key, return 1; } -const EVP_HPKE_KEM *EVP_hpke_x25519_hkdf_sha256(void) { +const EVP_HPKE_KEM *EVP_hpke_x25519_hkdf_sha256() { static const 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, }; return &kKEM; } @@ -362,17 +461,14 @@ static int p256_init_key(EVP_HPKE_KEY *key, const uint8_t *priv_key, } static int p256_private_key_from_seed(uint8_t out_priv[P256_PRIVATE_KEY_LEN], - const uint8_t seed[P256_SEED_LEN]) { + const uint8_t *seed, size_t seed_len) { // https://www.rfc-editor.org/rfc/rfc9180.html#name-derivekeypair - const uint8_t suite_id[5] = {'K', 'E', 'M', - EVP_HPKE_DHKEM_P256_HKDF_SHA256 >> 8, - EVP_HPKE_DHKEM_P256_HKDF_SHA256 & 0xff}; - + auto suite_id = hpke_kem_suite_id(EVP_HPKE_DHKEM_P256_HKDF_SHA256); uint8_t dkp_prk[32]; size_t dkp_prk_len; - if (!hpke_labeled_extract(EVP_sha256(), dkp_prk, &dkp_prk_len, NULL, 0, - suite_id, sizeof(suite_id), "dkp_prk", seed, - P256_SEED_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; } assert(dkp_prk_len == sizeof(dkp_prk)); @@ -383,15 +479,16 @@ static int p256_private_key_from_seed(uint8_t out_priv[P256_PRIVATE_KEY_LEN], for (unsigned 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, - sizeof(suite_id), "candidate", &counter_byte, + dkp_prk, sizeof(dkp_prk), suite_id.data(), + suite_id.size(), "candidate", &counter_byte, sizeof(counter_byte))) { return 0; } - // This checks that the scalar is less than the order. + // `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)) { + P256_PRIVATE_KEY_LEN) && + !ec_scalar_is_zero(group, &private_scalar)) { return 1; } } @@ -401,16 +498,20 @@ static int p256_private_key_from_seed(uint8_t out_priv[P256_PRIVATE_KEY_LEN], return 0; } -static int p256_generate_key(EVP_HPKE_KEY *key) { - uint8_t seed[P256_SEED_LEN]; - RAND_bytes(seed, sizeof(seed)); - if (!p256_private_key_from_seed(key->private_key, seed) || +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]) { @@ -460,10 +561,10 @@ static int p256_encap_with_seed(const EVP_HPKE_KEM *kem, return 0; } uint8_t private_key[P256_PRIVATE_KEY_LEN]; - if (!p256_private_key_from_seed(private_key, seed)) { + if (!p256_private_key_from_seed(private_key, seed, seed_len) || + !p256_public_from_private(out_enc, private_key)) { return 0; } - p256_public_from_private(out_enc, private_key); uint8_t dh[P256_SHARED_KEY_LEN]; if (peer_public_key_len != P256_PUBLIC_VALUE_LEN || @@ -525,10 +626,10 @@ static int p256_auth_encap_with_seed( return 0; } uint8_t private_key[P256_PRIVATE_KEY_LEN]; - if (!p256_private_key_from_seed(private_key, seed)) { + if (!p256_private_key_from_seed(private_key, seed, seed_len) || + !p256_public_from_private(out_enc, private_key)) { return 0; } - p256_public_from_private(out_enc, private_key); uint8_t dh[2 * P256_SHARED_KEY_LEN]; if (peer_public_key_len != P256_PUBLIC_VALUE_LEN || @@ -584,23 +685,158 @@ static int p256_auth_decap(const EVP_HPKE_KEY *key, uint8_t *out_shared_secret, return 1; } -const EVP_HPKE_KEM *EVP_hpke_p256_hkdf_sha256(void) { +const EVP_HPKE_KEM *EVP_hpke_p256_hkdf_sha256() { static const 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, }; 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 + +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), + "DeriveKeyPair", /*context=*/{}); + return EVP_PKEY_from_private_seed(alg, seed, sizeof(seed)); +} + + +const EVP_HPKE_KEM *EVP_hpke_xwing() { + static const 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, + // 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, + }; + 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)); +} + +const EVP_HPKE_KEM *EVP_hpke_mlkem768() { + static const 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, + // ML-KEM doesn't support authenticated encapsulation/decapsulation: + // https://datatracker.ietf.org/doc/draft-ietf-hpke-pq/01/ + /*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=*/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 = { + /*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, + // ML-KEM doesn't support authenticated encapsulation/decapsulation: + // https://datatracker.ietf.org/doc/draft-ietf-hpke-pq/01/ + /*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=*/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) { @@ -611,46 +847,60 @@ size_t EVP_HPKE_KEM_private_key_len(const EVP_HPKE_KEM *kem) { return kem->private_key_len; } -size_t EVP_HPKE_KEM_enc_len(const EVP_HPKE_KEM *kem) { return kem->enc_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; +} +// 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) { - // Nothing to clean up for now, but we may introduce a cleanup process in the - // future. + EVP_PKEY_free(key->pkey); + key->pkey = nullptr; } -EVP_HPKE_KEY *EVP_HPKE_KEY_new(void) { - EVP_HPKE_KEY *key = - reinterpret_cast(OPENSSL_malloc(sizeof(EVP_HPKE_KEY))); - if (key == NULL) { - return NULL; +EVP_HPKE_KEY *EVP_HPKE_KEY_new() { + EVP_HPKE_KEY *key = New(); + if (key == nullptr) { + return nullptr; } EVP_HPKE_KEY_zero(key); return key; } void EVP_HPKE_KEY_free(EVP_HPKE_KEY *key) { - if (key != NULL) { + if (key != nullptr) { EVP_HPKE_KEY_cleanup(key); - OPENSSL_free(key); + Delete(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) { - // For now, |EVP_HPKE_KEY| is trivially copyable. - OPENSSL_memcpy(dst, src, sizeof(EVP_HPKE_KEY)); + 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; } void EVP_HPKE_KEY_move(EVP_HPKE_KEY *out, EVP_HPKE_KEY *in) { EVP_HPKE_KEY_cleanup(out); - // For now, |EVP_HPKE_KEY| is trivially movable. + // For now, `EVP_HPKE_KEY` is trivially movable. // Note that Rust may move this structure. See // bssl-crypto/src/scoped.rs:EvpHpkeKey. - OPENSSL_memcpy(out, in, sizeof(EVP_HPKE_KEY)); + *out = *in; EVP_HPKE_KEY_zero(in); } @@ -658,8 +908,20 @@ 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)) { - key->kem = NULL; + key->kem = nullptr; return 0; } return 1; @@ -668,8 +930,43 @@ int EVP_HPKE_KEY_init(EVP_HPKE_KEY *key, const EVP_HPKE_KEM *kem, 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)) { - key->kem = NULL; + key->kem = nullptr; + return 0; + } + return 1; +} + +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))) { + key->kem = nullptr; return 0; } return 1; @@ -685,6 +982,12 @@ int EVP_HPKE_KEY_public_key(const EVP_HPKE_KEY *key, uint8_t *out, 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; @@ -696,6 +999,12 @@ int EVP_HPKE_KEY_private_key(const EVP_HPKE_KEY *key, uint8_t *out, 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; @@ -704,30 +1013,35 @@ int EVP_HPKE_KEY_private_key(const EVP_HPKE_KEY *key, uint8_t *out, // Supported KDFs and AEADs. -const EVP_HPKE_KDF *EVP_hpke_hkdf_sha256(void) { +const EVP_HPKE_KDF *EVP_hpke_hkdf_sha256() { static const EVP_HPKE_KDF kKDF = {EVP_HPKE_HKDF_SHA256, &EVP_sha256}; return &kKDF; } +const EVP_HPKE_KDF *EVP_hpke_hkdf_sha384() { + static const EVP_HPKE_KDF kKDF = {EVP_HPKE_HKDF_SHA384, &EVP_sha384}; + return &kKDF; +} + uint16_t EVP_HPKE_KDF_id(const EVP_HPKE_KDF *kdf) { return kdf->id; } const EVP_MD *EVP_HPKE_KDF_hkdf_md(const EVP_HPKE_KDF *kdf) { return kdf->hkdf_md_func(); } -const EVP_HPKE_AEAD *EVP_hpke_aes_128_gcm(void) { +const EVP_HPKE_AEAD *EVP_hpke_aes_128_gcm() { static const EVP_HPKE_AEAD kAEAD = {EVP_HPKE_AES_128_GCM, &EVP_aead_aes_128_gcm}; return &kAEAD; } -const EVP_HPKE_AEAD *EVP_hpke_aes_256_gcm(void) { +const EVP_HPKE_AEAD *EVP_hpke_aes_256_gcm() { static const EVP_HPKE_AEAD kAEAD = {EVP_HPKE_AES_256_GCM, &EVP_aead_aes_256_gcm}; return &kAEAD; } -const EVP_HPKE_AEAD *EVP_hpke_chacha20_poly1305(void) { +const EVP_HPKE_AEAD *EVP_hpke_chacha20_poly1305() { static const EVP_HPKE_AEAD kAEAD = {EVP_HPKE_CHACHA20_POLY1305, &EVP_aead_chacha20_poly1305}; return &kAEAD; @@ -742,19 +1056,19 @@ const EVP_AEAD *EVP_HPKE_AEAD_aead(const EVP_HPKE_AEAD *aead) { // HPKE implementation. -// This is strlen("HPKE") + 3 * sizeof(uint16_t). -#define HPKE_SUITE_ID_LEN 10 - -// The suite_id for non-KEM pieces of HPKE is defined as concat("HPKE", -// I2OSP(kem_id, 2), I2OSP(kdf_id, 2), I2OSP(aead_id, 2)). -static int hpke_build_suite_id(const EVP_HPKE_CTX *ctx, - uint8_t out[HPKE_SUITE_ID_LEN]) { - CBB cbb; - CBB_init_fixed(&cbb, out, HPKE_SUITE_ID_LEN); - return add_label_string(&cbb, "HPKE") && // - CBB_add_u16(&cbb, ctx->kem->id) && // - CBB_add_u16(&cbb, ctx->kdf->id) && // - CBB_add_u16(&cbb, ctx->aead->id); +static std::array hpke_full_suite_id(const EVP_HPKE_CTX *ctx) { + return { + 'H', + 'P', + 'K', + 'E', + static_cast(ctx->kem->id >> 8), + static_cast(ctx->kem->id), + static_cast(ctx->kdf->id >> 8), + static_cast(ctx->kdf->id), + static_cast(ctx->aead->id >> 8), + static_cast(ctx->aead->id), + }; } #define HPKE_MODE_BASE 0 @@ -764,27 +1078,24 @@ 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) { - uint8_t suite_id[HPKE_SUITE_ID_LEN]; - if (!hpke_build_suite_id(ctx, suite_id)) { - return 0; - } + auto suite_id = hpke_full_suite_id(ctx); // psk_id_hash = LabeledExtract("", "psk_id_hash", psk_id) // TODO(davidben): Precompute this value and store it with the EVP_HPKE_KDF. const EVP_MD *hkdf_md = ctx->kdf->hkdf_md_func(); uint8_t psk_id_hash[EVP_MAX_MD_SIZE]; size_t psk_id_hash_len; - if (!hpke_labeled_extract(hkdf_md, psk_id_hash, &psk_id_hash_len, NULL, 0, - suite_id, sizeof(suite_id), "psk_id_hash", NULL, - 0)) { + if (!hpke_labeled_extract(hkdf_md, psk_id_hash, &psk_id_hash_len, nullptr, 0, + suite_id.data(), suite_id.size(), "psk_id_hash", + nullptr, 0)) { return 0; } // info_hash = LabeledExtract("", "info_hash", info) uint8_t info_hash[EVP_MAX_MD_SIZE]; size_t info_hash_len; - if (!hpke_labeled_extract(hkdf_md, info_hash, &info_hash_len, NULL, 0, - suite_id, sizeof(suite_id), "info_hash", info, + if (!hpke_labeled_extract(hkdf_md, info_hash, &info_hash_len, nullptr, 0, + suite_id.data(), suite_id.size(), "info_hash", info, info_len)) { return 0; } @@ -797,7 +1108,7 @@ static int hpke_key_schedule(EVP_HPKE_CTX *ctx, uint8_t mode, if (!CBB_add_u8(&context_cbb, mode) || !CBB_add_bytes(&context_cbb, psk_id_hash, psk_id_hash_len) || !CBB_add_bytes(&context_cbb, info_hash, info_hash_len) || - !CBB_finish(&context_cbb, NULL, &context_len)) { + !CBB_finish(&context_cbb, nullptr, &context_len)) { return 0; } @@ -805,8 +1116,8 @@ static int hpke_key_schedule(EVP_HPKE_CTX *ctx, uint8_t mode, uint8_t secret[EVP_MAX_MD_SIZE]; size_t secret_len; if (!hpke_labeled_extract(hkdf_md, secret, &secret_len, shared_secret, - shared_secret_len, suite_id, sizeof(suite_id), - "secret", NULL, 0)) { + shared_secret_len, suite_id.data(), suite_id.size(), + "secret", nullptr, 0)) { return 0; } @@ -814,24 +1125,25 @@ static int hpke_key_schedule(EVP_HPKE_CTX *ctx, uint8_t mode, const EVP_AEAD *aead = EVP_HPKE_AEAD_aead(ctx->aead); uint8_t key[EVP_AEAD_MAX_KEY_LENGTH]; const size_t kKeyLen = EVP_AEAD_key_length(aead); - if (!hpke_labeled_expand(hkdf_md, key, kKeyLen, secret, secret_len, suite_id, - sizeof(suite_id), "key", context, context_len) || + if (!hpke_labeled_expand(hkdf_md, key, kKeyLen, secret, secret_len, + suite_id.data(), suite_id.size(), "key", context, + context_len) || !EVP_AEAD_CTX_init(&ctx->aead_ctx, aead, key, kKeyLen, - EVP_AEAD_DEFAULT_TAG_LENGTH, NULL)) { + EVP_AEAD_DEFAULT_TAG_LENGTH, nullptr)) { return 0; } // base_nonce = LabeledExpand(secret, "base_nonce", key_schedule_context, Nn) if (!hpke_labeled_expand(hkdf_md, ctx->base_nonce, EVP_AEAD_nonce_length(aead), secret, secret_len, - suite_id, sizeof(suite_id), "base_nonce", context, - context_len)) { + suite_id.data(), suite_id.size(), "base_nonce", + context, context_len)) { return 0; } // exporter_secret = LabeledExpand(secret, "exp", key_schedule_context, Nh) if (!hpke_labeled_expand(hkdf_md, ctx->exporter_secret, EVP_MD_size(hkdf_md), - secret, secret_len, suite_id, sizeof(suite_id), + secret, secret_len, suite_id.data(), suite_id.size(), "exp", context, context_len)) { return 0; } @@ -848,20 +1160,19 @@ void EVP_HPKE_CTX_cleanup(EVP_HPKE_CTX *ctx) { EVP_AEAD_CTX_cleanup(&ctx->aead_ctx); } -EVP_HPKE_CTX *EVP_HPKE_CTX_new(void) { - EVP_HPKE_CTX *ctx = - reinterpret_cast(OPENSSL_malloc(sizeof(EVP_HPKE_CTX))); - if (ctx == NULL) { - return NULL; +EVP_HPKE_CTX *EVP_HPKE_CTX_new() { + EVP_HPKE_CTX *ctx = New(); + if (ctx == nullptr) { + return nullptr; } EVP_HPKE_CTX_zero(ctx); return ctx; } void EVP_HPKE_CTX_free(EVP_HPKE_CTX *ctx) { - if (ctx != NULL) { + if (ctx != nullptr) { EVP_HPKE_CTX_cleanup(ctx); - OPENSSL_free(ctx); + Delete(ctx); } } @@ -872,6 +1183,39 @@ 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( @@ -892,6 +1236,33 @@ int EVP_HPKE_CTX_setup_sender_with_seed_for_testing( 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) || @@ -915,6 +1286,25 @@ int EVP_HPKE_CTX_setup_recipient(EVP_HPKE_CTX *ctx, const EVP_HPKE_KEY *key, 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)) { @@ -930,6 +1320,12 @@ int EVP_HPKE_CTX_setup_auth_sender( 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( @@ -943,7 +1339,7 @@ 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 == NULL) { + 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; @@ -972,7 +1368,7 @@ int EVP_HPKE_CTX_setup_auth_recipient( const EVP_HPKE_AEAD *aead, const uint8_t *enc, size_t enc_len, const uint8_t *info, size_t info_len, const uint8_t *peer_public_key, size_t peer_public_key_len) { - if (key->kem->auth_decap == NULL) { + if (key->kem->auth_decap == nullptr) { // Not all HPKE KEMs support AuthDecap. OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; @@ -999,7 +1395,7 @@ 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|. + // 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++) { @@ -1007,7 +1403,7 @@ static void hpke_nonce(const EVP_HPKE_CTX *ctx, uint8_t *out_nonce, seq_copy >>= 8; } - // XOR the encoded sequence with the |ctx->base_nonce|. + // 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]; } @@ -1064,14 +1460,11 @@ int EVP_HPKE_CTX_seal(EVP_HPKE_CTX *ctx, uint8_t *out, size_t *out_len, int EVP_HPKE_CTX_export(const EVP_HPKE_CTX *ctx, uint8_t *out, size_t secret_len, const uint8_t *context, size_t context_len) { - uint8_t suite_id[HPKE_SUITE_ID_LEN]; - if (!hpke_build_suite_id(ctx, suite_id)) { - return 0; - } + auto suite_id = hpke_full_suite_id(ctx); const EVP_MD *hkdf_md = ctx->kdf->hkdf_md_func(); if (!hpke_labeled_expand(hkdf_md, out, secret_len, ctx->exporter_secret, - EVP_MD_size(hkdf_md), suite_id, sizeof(suite_id), - "sec", context, context_len)) { + EVP_MD_size(hkdf_md), suite_id.data(), + suite_id.size(), "sec", context, context_len)) { return 0; } return 1; diff --git a/Sources/CNIOBoringSSL/crypto/hrss/asm/poly_rq_mul.S b/Sources/CNIOBoringSSL/crypto/hrss/asm/poly_rq_mul.S index fce83979..080ab2f7 100644 --- a/Sources/CNIOBoringSSL/crypto/hrss/asm/poly_rq_mul.S +++ b/Sources/CNIOBoringSSL/crypto/hrss/asm/poly_rq_mul.S @@ -2,17 +2,17 @@ #if defined(__x86_64__) && defined(__linux__) // Copyright (c) 2017, the HRSS authors. // -// Permission to use, copy, modify, and/or distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. +// 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 // -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY -// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION -// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN -// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +// 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 @@ -8477,6 +8477,7 @@ vmovdqu 1320(%rdi), %ymm11 vpaddw 2752(%r8), %ymm11, %ymm11 vpand mask_mod8192(%rip), %ymm11, %ymm11 vmovdqu %ymm11, 1320(%rdi) +vzeroupper pop %r12 .cfi_restore r12 pop %rbp diff --git a/Sources/CNIOBoringSSL/crypto/hrss/hrss.cc b/Sources/CNIOBoringSSL/crypto/hrss/hrss.cc index 86a79f84..f2567126 100644 --- a/Sources/CNIOBoringSSL/crypto/hrss/hrss.cc +++ b/Sources/CNIOBoringSSL/crypto/hrss/hrss.cc @@ -1,16 +1,16 @@ -/* Copyright 2018 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2018 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 @@ -18,13 +18,15 @@ #include #include #include + +#include #include #include #include #include #include -#include +#include #include "../internal.h" #include "internal.h" @@ -37,6 +39,9 @@ #include #endif + +using namespace bssl; + // This is an implementation of [HRSS], but with a KEM transformation based on // [SXY]. The primary references are: @@ -49,12 +54,11 @@ // NTRUCOMP: https://eprint.iacr.org/2018/1174 // SAFEGCD: https://gcd.cr.yp.to/papers.html#safegcd - // Vector operations. // // A couple of functions in this file can use vector operations to meaningful // effect. If we're building for a target that has a supported vector unit, -// |HRSS_HAVE_VECTOR_UNIT| will be defined and |vec_t| will be typedefed to a +// `HRSS_HAVE_VECTOR_UNIT` will be defined and `vec_t` will be typedefed to a // 128-bit vector. The following functions abstract over the differences between // NEON and SSE2 for implementing some vector operations. @@ -63,31 +67,32 @@ #if defined(OPENSSL_SSE2) && (defined(__clang__) || !defined(_MSC_VER)) #define HRSS_HAVE_VECTOR_UNIT + typedef __m128i vec_t; // vec_capable returns one iff the current platform supports SSE2. -static int vec_capable(void) { return 1; } +static int vec_capable() { return 1; } -// vec_add performs a pair-wise addition of four uint16s from |a| and |b|. -static inline vec_t vec_add(vec_t a, vec_t b) { return _mm_add_epi16(a, b); } +// vec_add performs a pair-wise addition of four uint16s from `a` and `b`. +static vec_t vec_add(vec_t a, vec_t b) { return _mm_add_epi16(a, b); } -// vec_sub performs a pair-wise subtraction of four uint16s from |a| and |b|. -static inline vec_t vec_sub(vec_t a, vec_t b) { return _mm_sub_epi16(a, b); } +// vec_sub performs a pair-wise subtraction of four uint16s from `a` and `b`. +static vec_t vec_sub(vec_t a, vec_t b) { return _mm_sub_epi16(a, b); } -// vec_mul multiplies each uint16_t in |a| by |b| and returns the resulting +// vec_mul multiplies each uint16_t in `a` by `b` and returns the resulting // vector. -static inline vec_t vec_mul(vec_t a, uint16_t b) { +static vec_t vec_mul(vec_t a, uint16_t b) { return _mm_mullo_epi16(a, _mm_set1_epi16(b)); } -// vec_fma multiplies each uint16_t in |b| by |c|, adds the result to |a|, and +// vec_fma multiplies each uint16_t in `b` by `c`, adds the result to `a`, and // returns the resulting vector. -static inline vec_t vec_fma(vec_t a, vec_t b, uint16_t c) { +static vec_t vec_fma(vec_t a, vec_t b, uint16_t c) { return _mm_add_epi16(a, _mm_mullo_epi16(b, _mm_set1_epi16(c))); } -// vec3_rshift_word right-shifts the 24 uint16_t's in |v| by one uint16. -static inline void vec3_rshift_word(vec_t v[3]) { +// vec3_rshift_word right-shifts the 24 uint16_t's in `v` by one uint16. +static void vec3_rshift_word(vec_t v[3]) { // Intel's left and right shifting is backwards compared to the order in // memory because they're based on little-endian order of words (and not just // bytes). So the shifts in this function will be backwards from what one @@ -103,8 +108,8 @@ static inline void vec3_rshift_word(vec_t v[3]) { v[2] |= carry1; } -// vec4_rshift_word right-shifts the 32 uint16_t's in |v| by one uint16. -static inline void vec4_rshift_word(vec_t v[4]) { +// vec4_rshift_word right-shifts the 32 uint16_t's in `v` by one uint16. +static void vec4_rshift_word(vec_t v[4]) { // Intel's left and right shifting is backwards compared to the order in // memory because they're based on little-endian order of words (and not just // bytes). So the shifts in this function will be backwards from what one @@ -124,15 +129,15 @@ static inline void vec4_rshift_word(vec_t v[4]) { v[3] |= carry2; } -// vec_merge_3_5 takes the final three uint16_t's from |left|, appends the first -// five from |right|, and returns the resulting vector. -static inline vec_t vec_merge_3_5(vec_t left, vec_t right) { +// vec_merge_3_5 takes the final three uint16_t's from `left`, appends the first +// five from `right`, and returns the resulting vector. +static vec_t vec_merge_3_5(vec_t left, vec_t right) { return _mm_srli_si128(left, 10) | _mm_slli_si128(right, 6); } -// poly3_vec_lshift1 left-shifts the 768 bits in |a_s|, and in |a_a|, by one +// poly3_vec_lshift1 left-shifts the 768 bits in `a_s`, and in `a_a`, by one // bit. -static inline void poly3_vec_lshift1(vec_t a_s[6], vec_t a_a[6]) { +static void poly3_vec_lshift1(vec_t a_s[6], vec_t a_a[6]) { vec_t carry_s = {0}; vec_t carry_a = {0}; @@ -151,9 +156,9 @@ static inline void poly3_vec_lshift1(vec_t a_s[6], vec_t a_a[6]) { } } -// poly3_vec_rshift1 right-shifts the 768 bits in |a_s|, and in |a_a|, by one +// poly3_vec_rshift1 right-shifts the 768 bits in `a_s`, and in `a_a`, by one // bit. -static inline void poly3_vec_rshift1(vec_t a_s[6], vec_t a_a[6]) { +static void poly3_vec_rshift1(vec_t a_s[6], vec_t a_a[6]) { vec_t carry_s = {0}; vec_t carry_a = {0}; @@ -172,15 +177,15 @@ static inline void poly3_vec_rshift1(vec_t a_s[6], vec_t a_a[6]) { } } -// vec_broadcast_bit duplicates the least-significant bit in |a| to all bits in +// vec_broadcast_bit duplicates the least-significant bit in `a` to all bits in // a vector and returns the result. -static inline vec_t vec_broadcast_bit(vec_t a) { +static vec_t vec_broadcast_bit(vec_t a) { return _mm_shuffle_epi32(_mm_srai_epi32(_mm_slli_epi64(a, 63), 31), 0b01010101); } -// vec_get_word returns the |i|th uint16_t in |v|. (This is a macro because the -// compiler requires that |i| be a compile-time constant.) +// vec_get_word returns the `i`th uint16_t in `v`. (This is a macro because the +// compiler requires that `i` be a compile-time constant.) #define vec_get_word(v, i) _mm_extract_epi16(v, i) #elif (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) && defined(__ARM_NEON) @@ -191,26 +196,26 @@ typedef uint16x8_t vec_t; // These functions perform the same actions as the SSE2 function of the same // name, above. -static int vec_capable(void) { return CRYPTO_is_NEON_capable(); } +static int vec_capable() { return CRYPTO_is_NEON_capable(); } -static inline vec_t vec_add(vec_t a, vec_t b) { return a + b; } +static vec_t vec_add(vec_t a, vec_t b) { return a + b; } -static inline vec_t vec_sub(vec_t a, vec_t b) { return a - b; } +static vec_t vec_sub(vec_t a, vec_t b) { return a - b; } -static inline vec_t vec_mul(vec_t a, uint16_t b) { return vmulq_n_u16(a, b); } +static vec_t vec_mul(vec_t a, uint16_t b) { return vmulq_n_u16(a, b); } -static inline vec_t vec_fma(vec_t a, vec_t b, uint16_t c) { +static vec_t vec_fma(vec_t a, vec_t b, uint16_t c) { return vmlaq_n_u16(a, b, c); } -static inline void vec3_rshift_word(vec_t v[3]) { +static void vec3_rshift_word(vec_t v[3]) { const uint16x8_t kZero = {0}; v[2] = vextq_u16(v[1], v[2], 7); v[1] = vextq_u16(v[0], v[1], 7); v[0] = vextq_u16(kZero, v[0], 7); } -static inline void vec4_rshift_word(vec_t v[4]) { +static void vec4_rshift_word(vec_t v[4]) { const uint16x8_t kZero = {0}; v[3] = vextq_u16(v[2], v[3], 7); v[2] = vextq_u16(v[1], v[2], 7); @@ -218,20 +223,20 @@ static inline void vec4_rshift_word(vec_t v[4]) { v[0] = vextq_u16(kZero, v[0], 7); } -static inline vec_t vec_merge_3_5(vec_t left, vec_t right) { +static vec_t vec_merge_3_5(vec_t left, vec_t right) { return vextq_u16(left, right, 5); } -static inline uint16_t vec_get_word(vec_t v, unsigned i) { return v[i]; } +static uint16_t vec_get_word(vec_t v, unsigned i) { return v[i]; } #if !defined(OPENSSL_AARCH64) -static inline vec_t vec_broadcast_bit(vec_t a) { +static vec_t vec_broadcast_bit(vec_t a) { a = (vec_t)vshrq_n_s16(((int16x8_t)a) << 15, 15); return vdupq_lane_u16(vget_low_u16(a), 0); } -static inline void poly3_vec_lshift1(vec_t a_s[6], vec_t a_a[6]) { +static void poly3_vec_lshift1(vec_t a_s[6], vec_t a_a[6]) { vec_t carry_s = {0}; vec_t carry_a = {0}; const vec_t kZero = {0}; @@ -251,7 +256,7 @@ static inline void poly3_vec_lshift1(vec_t a_s[6], vec_t a_a[6]) { } } -static inline void poly3_vec_rshift1(vec_t a_s[6], vec_t a_a[6]) { +static void poly3_vec_rshift1(vec_t a_s[6], vec_t a_a[6]) { vec_t carry_s = {0}; vec_t carry_a = {0}; const vec_t kZero = {0}; @@ -276,7 +281,7 @@ static inline void poly3_vec_rshift1(vec_t a_s[6], vec_t a_a[6]) { #endif // (ARM || AARCH64) && NEON // Polynomials in this scheme have N terms. -// #define N 701 +#define N HRSS_N // Underlying data types and arithmetic operations. // ------------------------------------------------ @@ -296,7 +301,7 @@ static void poly2_zero(struct poly2 *p) { OPENSSL_memset(&p->v[0], 0, sizeof(crypto_word_t) * WORDS_PER_POLY); } -// word_reverse returns |in| with the bits in reverse order. +// word_reverse returns `in` with the bits in reverse order. static crypto_word_t word_reverse(crypto_word_t in) { #if defined(OPENSSL_64_BIT) static const crypto_word_t kMasks[6] = { @@ -310,19 +315,19 @@ static crypto_word_t word_reverse(crypto_word_t in) { }; #endif - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kMasks); i++) { + for (size_t i = 0; i < std::size(kMasks); i++) { in = ((in >> (1 << i)) & kMasks[i]) | ((in & kMasks[i]) << (1 << i)); } return in; } -// lsb_to_all replicates the least-significant bit of |v| to all bits of the +// lsb_to_all replicates the least-significant bit of `v` to all bits of the // word. This is used in bit-slicing operations to make a vector from a fixed // value. static crypto_word_t lsb_to_all(crypto_word_t v) { return 0u - (v & 1); } -// poly2_mod_phiN reduces |p| by Φ(N). +// poly2_mod_phiN reduces `p` by Φ(N). static void poly2_mod_phiN(struct poly2 *p) { // m is the term at x^700, replicated to every bit. const crypto_word_t m = @@ -333,8 +338,8 @@ static void poly2_mod_phiN(struct poly2 *p) { p->v[WORDS_PER_POLY - 1] &= (UINT64_C(1) << (BITS_IN_LAST_WORD - 1)) - 1; } -// poly2_reverse_700 reverses the order of the first 700 bits of |in| and writes -// the result to |out|. +// poly2_reverse_700 reverses the order of the first 700 bits of `in` and writes +// the result to `out`. static void poly2_reverse_700(struct poly2 *out, const struct poly2 *in) { struct poly2 t; for (size_t i = 0; i < WORDS_PER_POLY; i++) { @@ -349,7 +354,7 @@ static void poly2_reverse_700(struct poly2 *out, const struct poly2 *in) { out->v[WORDS_PER_POLY - 1] = t.v[0] >> shift; } -// poly2_cswap exchanges the values of |a| and |b| if |swap| is all ones. +// poly2_cswap exchanges the values of `a` and `b` if `swap` is all ones. static void poly2_cswap(struct poly2 *a, struct poly2 *b, crypto_word_t swap) { for (size_t i = 0; i < WORDS_PER_POLY; i++) { const crypto_word_t sum = swap & (a->v[i] ^ b->v[i]); @@ -358,8 +363,8 @@ static void poly2_cswap(struct poly2 *a, struct poly2 *b, crypto_word_t swap) { } } -// poly2_fmadd sets |out| to |out| + |in| * m, where m is either -// |CONSTTIME_TRUE_W| or |CONSTTIME_FALSE_W|. +// poly2_fmadd sets `out` to `out` + `in` * m, where m is either +// `CONSTTIME_TRUE_W` or `CONSTTIME_FALSE_W`. static void poly2_fmadd(struct poly2 *out, const struct poly2 *in, crypto_word_t m) { for (size_t i = 0; i < WORDS_PER_POLY; i++) { @@ -367,7 +372,7 @@ static void poly2_fmadd(struct poly2 *out, const struct poly2 *in, } } -// poly2_lshift1 left-shifts |p| by one bit. +// poly2_lshift1 left-shifts `p` by one bit. static void poly2_lshift1(struct poly2 *p) { crypto_word_t carry = 0; for (size_t i = 0; i < WORDS_PER_POLY; i++) { @@ -378,7 +383,7 @@ static void poly2_lshift1(struct poly2 *p) { } } -// poly2_rshift1 right-shifts |p| by one bit. +// poly2_rshift1 right-shifts `p` by one bit. static void poly2_rshift1(struct poly2 *p) { crypto_word_t carry = 0; for (size_t i = WORDS_PER_POLY - 1; i < WORDS_PER_POLY; i--) { @@ -398,7 +403,7 @@ static void poly2_clear_top_bits(struct poly2 *p) { // Ternary polynomials. // poly3 represents a degree-N polynomial over GF(3). Each coefficient is -// bitsliced across the |s| and |a| arrays, like this: +// bitsliced across the `s` and `a` arrays, like this: // // s | a | value // ----------------- @@ -437,14 +442,14 @@ static void poly3_zero(struct poly3 *p) { poly2_zero(&p->a); } -// poly3_reverse_700 reverses the order of the first 700 terms of |in| and -// writes them to |out|. +// poly3_reverse_700 reverses the order of the first 700 terms of `in` and +// writes them to `out`. static void poly3_reverse_700(struct poly3 *out, const struct poly3 *in) { poly2_reverse_700(&out->a, &in->a); poly2_reverse_700(&out->s, &in->s); } -// poly3_word_mul sets (|out_s|, |out_a|) to (|s1|, |a1|) × (|s2|, |a2|). +// poly3_word_mul sets (`out_s`, `out_a`) to (`s1`, `a1`) × (`s2`, `a2`). static void poly3_word_mul(crypto_word_t *out_s, crypto_word_t *out_a, const crypto_word_t s1, const crypto_word_t a1, const crypto_word_t s2, const crypto_word_t a2) { @@ -452,7 +457,7 @@ static void poly3_word_mul(crypto_word_t *out_s, crypto_word_t *out_a, *out_s = (s1 ^ s2) & *out_a; } -// poly3_word_add sets (|out_s|, |out_a|) to (|s1|, |a1|) + (|s2|, |a2|). +// poly3_word_add sets (`out_s`, `out_a`) to (`s1`, `a1`) + (`s2`, `a2`). static void poly3_word_add(crypto_word_t *out_s, crypto_word_t *out_a, const crypto_word_t s1, const crypto_word_t a1, const crypto_word_t s2, const crypto_word_t a2) { @@ -461,7 +466,7 @@ static void poly3_word_add(crypto_word_t *out_s, crypto_word_t *out_a, *out_a = (a1 ^ a2) | (t ^ s2); } -// poly3_word_sub sets (|out_s|, |out_a|) to (|s1|, |a1|) - (|s2|, |a2|). +// poly3_word_sub sets (`out_s`, `out_a`) to (`s1`, `a1`) - (`s2`, `a2`). static void poly3_word_sub(crypto_word_t *out_s, crypto_word_t *out_a, const crypto_word_t s1, const crypto_word_t a1, const crypto_word_t s2, const crypto_word_t a2) { @@ -470,7 +475,7 @@ static void poly3_word_sub(crypto_word_t *out_s, crypto_word_t *out_a, *out_a = t | (s1 ^ s2); } -// poly3_mul_const sets |p| to |p|×m, where m = (ms, ma). +// poly3_mul_const sets `p` to `p`×m, where m = (ms, ma). static void poly3_mul_const(struct poly3 *p, crypto_word_t ms, crypto_word_t ma) { ms = lsb_to_all(ms); @@ -481,7 +486,7 @@ static void poly3_mul_const(struct poly3 *p, crypto_word_t ms, } } -// poly3_fmadd sets |out| to |out| - |in|×m, where m is (ms, ma). +// poly3_fmadd sets `out` to `out` - `in`×m, where m is (ms, ma). static void poly3_fmsub(struct poly3 *out, const struct poly3 *in, crypto_word_t ms, crypto_word_t ma) { crypto_word_t product_s, product_a; @@ -498,7 +503,7 @@ static crypto_word_t final_bit_to_all(crypto_word_t v) { return lsb_to_all(v >> (BITS_IN_LAST_WORD - 1)); } -// poly3_mod_phiN reduces |p| by Φ(N). +// poly3_mod_phiN reduces `p` by Φ(N). static void poly3_mod_phiN(struct poly3 *p) { // In order to reduce by Φ(N) we subtract by the value of the greatest // coefficient. @@ -535,8 +540,8 @@ struct poly3_span { crypto_word_t *a; }; -// poly3_span_add adds |n| words of values from |a| and |b| and writes the -// result to |out|. +// poly3_span_add adds `n` words of values from `a` and `b` and writes the +// result to `out`. static void poly3_span_add(const struct poly3_span *out, const struct poly3_span *a, const struct poly3_span *b, size_t n) { @@ -545,7 +550,7 @@ static void poly3_span_add(const struct poly3_span *out, } } -// poly3_span_sub subtracts |n| words of |b| from |n| words of |a|. +// poly3_span_sub subtracts `n` words of `b` from `n` words of `a`. static void poly3_span_sub(const struct poly3_span *a, const struct poly3_span *b, size_t n) { for (size_t i = 0; i < n; i++) { @@ -553,11 +558,11 @@ static void poly3_span_sub(const struct poly3_span *a, } } -// poly3_mul_aux is a recursive function that multiplies |n| words from |a| and -// |b| and writes 2×|n| words to |out|. Each call uses 2*ceil(n/2) elements of -// |scratch| and the function recurses, except if |n| == 1, when |scratch| isn't -// used and the recursion stops. For |n| in {11, 22}, the transitive total -// amount of |scratch| needed happens to be 2n+2. +// poly3_mul_aux is a recursive function that multiplies `n` words from `a` and +// `b` and writes 2×`n` words to `out`. Each call uses 2*ceil(n/2) elements of +// `scratch` and the function recurses, except if `n` == 1, when `scratch` isn't +// used and the recursion stops. For `n` in {11, 22}, the transitive total +// amount of `scratch` needed happens to be 2n+2. static void poly3_mul_aux(const struct poly3_span *out, const struct poly3_span *scratch, const struct poly3_span *a, @@ -604,14 +609,14 @@ static void poly3_mul_aux(const struct poly3_span *out, // Karatsuba multiplication. // https://en.wikipedia.org/wiki/Karatsuba_algorithm - // When |n| is odd, the two "halves" will have different lengths. The first + // When `n` is odd, the two "halves" will have different lengths. The first // is always the smaller. const size_t low_len = n / 2; const size_t high_len = n - low_len; const struct poly3_span a_high = {&a->s[low_len], &a->a[low_len]}; const struct poly3_span b_high = {&b->s[low_len], &b->a[low_len]}; - // Store a_1 + a_0 in the first half of |out| and b_1 + b_0 in the second + // Store a1 + a0 in the first half of `out` and b1 + b0 in the second // half. const struct poly3_span a_cross_sum = *out; const struct poly3_span b_cross_sum = {&out->s[high_len], &out->a[high_len]}; @@ -630,11 +635,11 @@ static void poly3_mul_aux(const struct poly3_span *out, const struct poly3_span out_high = {&out->s[2 * low_len], &out->a[2 * low_len]}; - // Calculate (a_1 + a_0) × (b_1 + b_0) and write to scratch buffer. + // Calculate (a1 + a0) × (b1 + b0) and write to scratch buffer. poly3_mul_aux(scratch, &child_scratch, &a_cross_sum, &b_cross_sum, high_len); - // Calculate a_1 × b_1. + // Calculate a1 × b1. poly3_mul_aux(&out_high, &child_scratch, &a_high, &b_high, high_len); - // Calculate a_0 × b_0. + // Calculate a0 × b0. poly3_mul_aux(out, &child_scratch, a, b, low_len); // Subtract those last two products from the first. @@ -645,9 +650,9 @@ static void poly3_mul_aux(const struct poly3_span *out, poly3_span_add(&out_mid, &out_mid, scratch, high_len * 2); } -// HRSS_poly3_mul sets |*out| to |x|×|y| mod Φ(N). -void HRSS_poly3_mul(struct poly3 *out, const struct poly3 *x, - const struct poly3 *y) { +// HRSS_poly3_mul sets `*out` to `x`×`y` mod Φ(N). +void bssl::HRSS_poly3_mul(struct poly3 *out, const struct poly3 *x, + const struct poly3 *y) { crypto_word_t prod_s[WORDS_PER_POLY * 2]; crypto_word_t prod_a[WORDS_PER_POLY * 2]; crypto_word_t scratch_s[WORDS_PER_POLY * 2 + 2]; @@ -661,7 +666,7 @@ void HRSS_poly3_mul(struct poly3 *out, const struct poly3 *x, poly3_mul_aux(&prod_span, &scratch_span, &x_span, &y_span, WORDS_PER_POLY); - // |prod| needs to be reduced mod (𝑥^n - 1), which just involves adding the + // `prod` needs to be reduced mod (𝑥^n - 1), which just involves adding the // upper-half to the lower-half. However, N is 701, which isn't a multiple of // BITS_PER_WORD, so the upper-half vectors all have to be shifted before // being added to the lower-half. @@ -679,10 +684,10 @@ void HRSS_poly3_mul(struct poly3 *out, const struct poly3 *x, #if defined(HRSS_HAVE_VECTOR_UNIT) && !defined(OPENSSL_AARCH64) -// poly3_vec_cswap swaps (|a_s|, |a_a|) and (|b_s|, |b_a|) if |swap| is -// |0xff..ff|. Otherwise, |swap| must be zero. -static inline void poly3_vec_cswap(vec_t a_s[6], vec_t a_a[6], vec_t b_s[6], - vec_t b_a[6], const vec_t swap) { +// poly3_vec_cswap swaps (`a_s`, `a_a`) and (`b_s`, `b_a`) if `swap` is +// `0xff..ff`. Otherwise, `swap` must be zero. +static void poly3_vec_cswap(vec_t a_s[6], vec_t a_a[6], vec_t b_s[6], + vec_t b_a[6], const vec_t swap) { for (int i = 0; i < 6; i++) { const vec_t sum_s = swap & (a_s[i] ^ b_s[i]); a_s[i] ^= sum_s; @@ -694,10 +699,9 @@ static inline void poly3_vec_cswap(vec_t a_s[6], vec_t a_a[6], vec_t b_s[6], } } -// poly3_vec_fmsub subtracts (|ms|, |ma|) × (|b_s|, |b_a|) from (|a_s|, |a_a|). -static inline void poly3_vec_fmsub(vec_t a_s[6], vec_t a_a[6], vec_t b_s[6], - vec_t b_a[6], const vec_t ms, - const vec_t ma) { +// poly3_vec_fmsub subtracts (`ms`, `ma`) × (`b_s`, `b_a`) from (`a_s`, `a_a`). +static void poly3_vec_fmsub(vec_t a_s[6], vec_t a_a[6], vec_t b_s[6], + vec_t b_a[6], const vec_t ms, const vec_t ma) { for (int i = 0; i < 6; i++) { // See the bitslice formula, above. const vec_t s = b_s[i]; @@ -713,7 +717,7 @@ static inline void poly3_vec_fmsub(vec_t a_s[6], vec_t a_a[6], vec_t b_s[6], } } -// poly3_invert_vec sets |*out| to |in|^-1, i.e. such that |out|×|in| == 1 mod +// poly3_invert_vec sets `*out` to `in`^-1, i.e. such that `out`×`in` == 1 mod // Φ(N). static void poly3_invert_vec(struct poly3 *out, const struct poly3 *in) { // This algorithm is taken from section 7.1 of [SAFEGCD]. @@ -734,7 +738,7 @@ static void poly3_invert_vec(struct poly3 *out, const struct poly3 *in) { memset(f_s, 0, sizeof(f_s)); memset(f_a, 0xff, 5 * sizeof(vec_t)); memcpy(&f_a[5], kBottomSixtyOne, sizeof(kBottomSixtyOne)); - // g is the reversal of |in|. + // g is the reversal of `in`. struct poly3 in_reversed; poly3_reverse_700(&in_reversed, in); g_s[5] = kZero; @@ -752,7 +756,7 @@ static void poly3_invert_vec(struct poly3 *out, const struct poly3 *in) { const crypto_word_t delta_is_non_zero = ~constant_time_is_zero_w(delta); const vec_t g_has_constant_term = vec_broadcast_bit(g_a[0]); const vec_t mask_w = { - static_cast::type>( + static_cast>( delta_is_non_negative & delta_is_non_zero)}; const vec_t mask = vec_broadcast_bit(mask_w) & g_has_constant_term; @@ -779,9 +783,9 @@ static void poly3_invert_vec(struct poly3 *out, const struct poly3 *in) { #endif // HRSS_HAVE_VECTOR_UNIT -// HRSS_poly3_invert sets |*out| to |in|^-1, i.e. such that |out|×|in| == 1 mod +// HRSS_poly3_invert sets `*out` to `in`^-1, i.e. such that `out`×`in` == 1 mod // Φ(N). -void HRSS_poly3_invert(struct poly3 *out, const struct poly3 *in) { +void bssl::HRSS_poly3_invert(struct poly3 *out, const struct poly3 *in) { // The vector version of this function seems slightly slower on AArch64, but // is useful on ARMv7 and x86-64. #if defined(HRSS_HAVE_VECTOR_UNIT) && !defined(OPENSSL_AARCH64) @@ -802,7 +806,7 @@ void HRSS_poly3_invert(struct poly3 *out, const struct poly3 *in) { OPENSSL_memset(&f.s, 0, sizeof(struct poly2)); OPENSSL_memset(&f.a, 0xff, sizeof(struct poly2)); f.a.v[WORDS_PER_POLY - 1] >>= BITS_PER_WORD - BITS_IN_LAST_WORD; - // g is the reversal of |in|. + // g is the reversal of `in`. poly3_reverse_700(&g, in); int delta = 1; @@ -871,14 +875,14 @@ struct poly { }; } // namespace -// poly_normalize zeros out the excess elements of |x| which are included only +// poly_normalize zeros out the excess elements of `x` which are included only // for alignment. static void poly_normalize(struct poly *x) { OPENSSL_memset(&x->v[N], 0, 3 * sizeof(uint16_t)); } -// poly_assert_normalized asserts that the excess elements of |x| are zeroed out -// for the cases that case. (E.g. |poly_mul_vec|.) +// poly_assert_normalized asserts that the excess elements of `x` are zeroed out +// for the cases that case. (E.g. `poly_mul_vec`.) static void poly_assert_normalized(const struct poly *x) { assert(x->v[N] == 0); assert(x->v[N + 1] == 0); @@ -887,20 +891,20 @@ static void poly_assert_normalized(const struct poly *x) { namespace { // POLY_MUL_SCRATCH contains space for the working variables needed by -// |poly_mul|. The contents afterwards may be discarded, but the object may also -// be reused with future |poly_mul| calls to save heap allocations. +// `poly_mul`. The contents afterwards may be discarded, but the object may also +// be reused with future `poly_mul` calls to save heap allocations. // // This object must have 32-byte alignment. struct POLY_MUL_SCRATCH { union { - // This is used by |poly_mul_novec|. + // This is used by `poly_mul_novec`. struct { uint16_t prod[2 * N]; uint16_t scratch[1318]; } novec; #if defined(HRSS_HAVE_VECTOR_UNIT) - // This is used by |poly_mul_vec|. + // This is used by `poly_mul_vec`. struct { vec_t prod[VECS_PER_POLY * 2]; vec_t scratch[172]; @@ -908,7 +912,7 @@ struct POLY_MUL_SCRATCH { #endif #if defined(POLY_RQ_MUL_ASM) - // This is the space used by |poly_Rq_mul|. + // This is the space used by `poly_Rq_mul`. uint8_t rq[POLY_MUL_RQ_SCRATCH_SPACE]; #endif } u; @@ -917,10 +921,10 @@ struct POLY_MUL_SCRATCH { #if defined(HRSS_HAVE_VECTOR_UNIT) -// poly_mul_vec_aux is a recursive function that multiplies |n| words from |a| -// and |b| and writes 2×|n| words to |out|. Each call uses 2*ceil(n/2) elements -// of |scratch| and the function recurses, except if |n| < 3, when |scratch| -// isn't used and the recursion stops. If |n| == |VECS_PER_POLY| then |scratch| +// poly_mul_vec_aux is a recursive function that multiplies `n` words from `a` +// and `b` and writes 2×`n` words to `out`. Each call uses 2*ceil(n/2) elements +// of `scratch` and the function recurses, except if `n` < 3, when `scratch` +// isn't used and the recursion stops. If `n` == `VECS_PER_POLY` then `scratch` // needs 172 elements. static void poly_mul_vec_aux(vec_t *out, vec_t *scratch, const vec_t *a, const vec_t *b, const size_t n) { @@ -1116,14 +1120,14 @@ static void poly_mul_vec_aux(vec_t *out, vec_t *scratch, const vec_t *a, // Karatsuba multiplication. // https://en.wikipedia.org/wiki/Karatsuba_algorithm - // When |n| is odd, the two "halves" will have different lengths. The first is + // When `n` is odd, the two "halves" will have different lengths. The first is // always the smaller. const size_t low_len = n / 2; const size_t high_len = n - low_len; const vec_t *a_high = &a[low_len]; const vec_t *b_high = &b[low_len]; - // Store a_1 + a_0 in the first half of |out| and b_1 + b_0 in the second + // Store a1 + a0 in the first half of `out` and b1 + b0 in the second // half. for (size_t i = 0; i < low_len; i++) { out[i] = vec_add(a_high[i], a[i]); @@ -1135,11 +1139,11 @@ static void poly_mul_vec_aux(vec_t *out, vec_t *scratch, const vec_t *a, } vec_t *const child_scratch = &scratch[2 * high_len]; - // Calculate (a_1 + a_0) × (b_1 + b_0) and write to scratch buffer. + // Calculate (a1 + a0) × (b1 + b0) and write to scratch buffer. poly_mul_vec_aux(scratch, child_scratch, out, &out[high_len], high_len); - // Calculate a_1 × b_1. + // Calculate a1 × b1. poly_mul_vec_aux(&out[low_len * 2], child_scratch, a_high, b_high, high_len); - // Calculate a_0 × b_0. + // Calculate a0 × b0. poly_mul_vec_aux(out, child_scratch, a, b, low_len); // Subtract those last two products from the first. @@ -1158,7 +1162,7 @@ static void poly_mul_vec_aux(vec_t *out, vec_t *scratch, const vec_t *a, } } -// poly_mul_vec sets |*out| to |x|×|y| mod (𝑥^n - 1). +// poly_mul_vec sets `*out` to `x`×`y` mod (𝑥^n - 1). static void poly_mul_vec(struct POLY_MUL_SCRATCH *scratch, struct poly *out, const struct poly *x, const struct poly *y) { static_assert(sizeof(out->v) == sizeof(vec_t) * VECS_PER_POLY, @@ -1172,7 +1176,7 @@ static void poly_mul_vec(struct POLY_MUL_SCRATCH *scratch, struct poly *out, vec_t *const aux_scratch = scratch->u.vec.scratch; poly_mul_vec_aux(prod, aux_scratch, x->vectors, y->vectors, VECS_PER_POLY); - // |prod| needs to be reduced mod (𝑥^n - 1), which just involves adding the + // `prod` needs to be reduced mod (𝑥^n - 1), which just involves adding the // upper-half to the lower-half. However, N is 701, which isn't a multiple of // the vector size, so the upper-half vectors all have to be shifted before // being added to the lower-half. @@ -1189,11 +1193,11 @@ static void poly_mul_vec(struct POLY_MUL_SCRATCH *scratch, struct poly *out, #endif // HRSS_HAVE_VECTOR_UNIT -// poly_mul_novec_aux writes the product of |a| and |b| to |out|, using -// |scratch| as scratch space. It'll use Karatsuba if the inputs are large -// enough to warrant it. Each call uses 2*ceil(n/2) elements of |scratch| and -// the function recurses, except if |n| < 64, when |scratch| isn't used and the -// recursion stops. If |n| == |N| then |scratch| needs 1318 elements. +// poly_mul_novec_aux writes the product of `a` and `b` to `out`, using +// `scratch` as scratch space. It'll use Karatsuba if the inputs are large +// enough to warrant it. Each call uses 2*ceil(n/2) elements of `scratch` and +// the function recurses, except if `n` < 64, when `scratch` isn't used and the +// recursion stops. If `n` == `N` then `scratch` needs 1318 elements. static void poly_mul_novec_aux(uint16_t *out, uint16_t *scratch, const uint16_t *a, const uint16_t *b, size_t n) { static const size_t kSchoolbookLimit = 64; @@ -1211,7 +1215,7 @@ static void poly_mul_novec_aux(uint16_t *out, uint16_t *scratch, // Karatsuba multiplication. // https://en.wikipedia.org/wiki/Karatsuba_algorithm - // When |n| is odd, the two "halves" will have different lengths. The + // When `n` is odd, the two "halves" will have different lengths. The // first is always the smaller. const size_t low_len = n / 2; const size_t high_len = n - low_len; @@ -1246,7 +1250,7 @@ static void poly_mul_novec_aux(uint16_t *out, uint16_t *scratch, } } -// poly_mul_novec sets |*out| to |x|×|y| mod (𝑥^n - 1). +// poly_mul_novec sets `*out` to `x`×`y` mod (𝑥^n - 1). static void poly_mul_novec(struct POLY_MUL_SCRATCH *scratch, struct poly *out, const struct poly *x, const struct poly *y) { uint16_t *const prod = scratch->u.novec.prod; @@ -1282,7 +1286,7 @@ static void poly_mul(struct POLY_MUL_SCRATCH *scratch, struct poly *r, poly_assert_normalized(r); } -// poly_mul_x_minus_1 sets |p| to |p|×(𝑥 - 1) mod (𝑥^n - 1). +// poly_mul_x_minus_1 sets `p` to `p`×(𝑥 - 1) mod (𝑥^n - 1). static void poly_mul_x_minus_1(struct poly *p) { // Multiplying by (𝑥 - 1) means negating each coefficient and adding in // the value of the previous one. @@ -1294,7 +1298,7 @@ static void poly_mul_x_minus_1(struct poly *p) { p->v[0] = orig_final_coefficient - p->v[0]; } -// poly_mod_phiN sets |p| to |p| mod Φ(N). +// poly_mod_phiN sets `p` to `p` mod Φ(N). static void poly_mod_phiN(struct poly *p) { const uint16_t coeff700 = p->v[N - 1]; @@ -1314,7 +1318,7 @@ static void poly_clamp(struct poly *p) { // Conversion functions // -------------------- -// poly2_from_poly sets |*out| to |in| mod 2. +// poly2_from_poly sets `*out` to `in` mod 2. static void poly2_from_poly(struct poly2 *out, const struct poly *in) { crypto_word_t *words = out->v; unsigned shift = 0; @@ -1337,16 +1341,16 @@ static void poly2_from_poly(struct poly2 *out, const struct poly *in) { *words = word; } -// mod3 treats |a| as a signed number and returns |a| mod 3. +// mod3 treats `a` as a signed number and returns `a` mod 3. static uint16_t mod3(int16_t a) { const int16_t q = ((int32_t)a * 21845) >> 16; int16_t ret = a - 3 * q; - // At this point, |ret| is in {0, 1, 2, 3} and that needs to be mapped to {0, + // At this point, `ret` is in {0, 1, 2, 3} and that needs to be mapped to {0, // 1, 2, 0}. return ret & ((ret & (ret >> 1)) - 1); } -// poly3_from_poly sets |*out| to |in|. +// poly3_from_poly sets `*out` to `in`. static void poly3_from_poly(struct poly3 *out, const struct poly *in) { crypto_word_t *words_s = out->s.v; crypto_word_t *words_a = out->a.v; @@ -1382,7 +1386,7 @@ static void poly3_from_poly(struct poly3 *out, const struct poly *in) { *words_a = a; } -// poly3_from_poly_checked sets |*out| to |in|, which has coefficients in {0, 1, +// poly3_from_poly_checked sets `*out` to `in`, which has coefficients in {0, 1, // Q-1}. It returns a mask indicating whether all coefficients were found to be // in that set. static crypto_word_t poly3_from_poly_checked(struct poly3 *out, @@ -1477,7 +1481,7 @@ static void poly_from_poly3(struct poly *out, const struct poly3 *in) { // Polynomial inversion // -------------------- -// poly_invert_mod2 sets |*out| to |in^-1| (i.e. such that |*out|×|in| = 1 mod +// poly_invert_mod2 sets `*out` to `in^-1` (i.e. such that `*out`×`in` = 1 mod // Φ(N)), all mod 2. This isn't useful in itself, but is part of doing inversion // mod Q. static void poly_invert_mod2(struct poly *out, const struct poly *in) { @@ -1492,7 +1496,7 @@ static void poly_invert_mod2(struct poly *out, const struct poly *in) { // f = all ones. OPENSSL_memset(&f, 0xff, sizeof(struct poly2)); f.v[WORDS_PER_POLY - 1] >>= BITS_PER_WORD - BITS_IN_LAST_WORD; - // g is the reversal of |in|. + // g is the reversal of `in`. poly2_from_poly(&g, in); poly2_mod_phiN(&g); poly2_reverse_700(&g, &g); @@ -1528,7 +1532,7 @@ static void poly_invert_mod2(struct poly *out, const struct poly *in) { poly_assert_normalized(out); } -// poly_invert sets |*out| to |in^-1| (i.e. such that |*out|×|in| = 1 mod Φ(N)). +// poly_invert sets `*out` to `in^-1` (i.e. such that `*out`×`in` = 1 mod Φ(N)). static void poly_invert(struct POLY_MUL_SCRATCH *scratch, struct poly *out, const struct poly *in) { // Inversion mod Q, which is done based on the result of inverting mod @@ -1561,7 +1565,7 @@ static void poly_invert(struct POLY_MUL_SCRATCH *scratch, struct poly *out, #define POLY_BYTES 1138 -// poly_marshal serialises all but the final coefficient of |in| to |out|. +// poly_marshal serialises all but the final coefficient of `in` to `out`. static void poly_marshal(uint8_t out[POLY_BYTES], const struct poly *in) { const uint16_t *p = in->v; @@ -1594,10 +1598,10 @@ static void poly_marshal(uint8_t out[POLY_BYTES], const struct poly *in) { out[6] = 0xf & (p[3] >> 9); } -// poly_unmarshal parses the output of |poly_marshal| and sets |out| such that +// poly_unmarshal parses the output of `poly_marshal` and sets `out` such that // all but the final coefficients match, and the final coefficient is calculated -// such that evaluating |out| at one results in zero. It returns one on success -// or zero if |in| is an invalid encoding. +// such that evaluating `out` at one results in zero. It returns one on success +// or zero if `in` is an invalid encoding. static int poly_unmarshal(struct poly *out, const uint8_t in[POLY_BYTES]) { uint16_t *p = out->v; @@ -1636,7 +1640,7 @@ static int poly_unmarshal(struct poly *out, const uint8_t in[POLY_BYTES]) { return 0; } - // Set the final coefficient as specifed in [HRSSNIST] 1.9.2 step 6. + // Set the final coefficient as specified in [HRSSNIST] 1.9.2 step 6. uint32_t sum = 0; for (size_t i = 0; i < N - 1; i++) { sum += out->v[i]; @@ -1648,15 +1652,15 @@ static int poly_unmarshal(struct poly *out, const uint8_t in[POLY_BYTES]) { return 1; } -// mod3_from_modQ maps {0, 1, Q-1, 65535} -> {0, 1, 2, 2}. Note that |v| may +// mod3_from_modQ maps {0, 1, Q-1, 65535} -> {0, 1, 2, 2}. Note that `v` may // have an invalid value when processing attacker-controlled inputs. static uint16_t mod3_from_modQ(uint16_t v) { v &= 3; return v ^ (v >> 1); } -// poly_marshal_mod3 marshals |in| to |out| where the coefficients of |in| are -// all in {0, 1, Q-1, 65535} and |in| is mod Φ(N). (Note that coefficients may +// poly_marshal_mod3 marshals `in` to `out` where the coefficients of `in` are +// all in {0, 1, Q-1, 65535} and `in` is mod Φ(N). (Note that coefficients may // have invalid values when processing attacker-controlled inputs.) static void poly_marshal_mod3(uint8_t out[HRSS_POLY3_BYTES], const struct poly *in) { @@ -1704,7 +1708,7 @@ static void poly_short_sample_plus(struct poly *out, poly_short_sample(out, in); // sum (and the product in the for loop) will overflow. But that's fine - // because |sum| is bound by +/- (N-2), and N < 2^15 so it works out. + // because `sum` is bound by +/- (N-2), and N < 2^15 so it works out. uint16_t sum = 0; for (unsigned i = 0; i < N - 2; i++) { sum += (unsigned)out->v[i] * out->v[i + 1]; @@ -1746,13 +1750,13 @@ static void poly_lift(struct poly *out, const struct poly *a) { // The use of z̅ is that, when working mod (𝑥^701 - 1), vz[0] = , vz[1] = , …. (Where is the inner product: the sum // of the point-wise products.) Although we calculated the inverse mod - // Φ(N), we can work mod (𝑥^N - 1) and reduce mod Φ(N) at the end. - // (That's because (𝑥^N - 1) is a multiple of Φ(N).) + // Φ(N), we can work mod (𝑥ᴺ - 1) and reduce mod Φ(N) at the end. + // (That's because (𝑥ᴺ - 1) is a multiple of Φ(N).) // - // When working mod (𝑥^N - 1), multiplication by 𝑥 is a right-rotation + // When working mod (𝑥ᴺ - 1), multiplication by 𝑥 is a right-rotation // of the list of coefficients. // - // Thus we can consider what the pattern of z̅, 𝑥z̅, 𝑥^2z̅, … looks like: + // Thus we can consider what the pattern of z̅, 𝑥z̅, 𝑥²z̅, … looks like: // // def reverse(xs): // suffix = list(xs[1:]) @@ -1776,11 +1780,11 @@ static void poly_lift(struct poly *out, const struct poly *a) { // (For a formula for z̅, see lemma two of appendix B.) // // After the first three elements have been taken care of, all then have - // a repeating three-element cycle. The next value (𝑥^3z̅) involves + // a repeating three-element cycle. The next value (𝑥³z̅) involves // three rotations of the first pattern, thus the three-element cycle // lines up. However, the discontinuity in the first three elements // obviously moves to a different position. Consider the difference - // between 𝑥^3z̅ and z̅: + // between 𝑥³z̅ and z̅: // // [x-y for (x,y) in zip(zoverbar, x3zoverbar)][:15] // [0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] @@ -1855,7 +1859,7 @@ struct private_key { // but we need 16-byte alignment. We could annotate the external struct with // that alignment but we can only assume that malloced pointers are 8-byte // aligned in any case. (Even if the underlying malloc returns values with -// 16-byte alignment, |OPENSSL_malloc| will store an 8-byte size prefix and mess +// 16-byte alignment, `OPENSSL_malloc` will store an 8-byte size prefix and mess // that up.) static struct public_key *public_key_from_external( struct HRSS_public_key *ext) { @@ -1866,7 +1870,7 @@ static struct public_key *public_key_from_external( return reinterpret_cast(align_pointer(ext->opaque, 16)); } -// private_key_from_external does the same thing as |public_key_from_external|, +// private_key_from_external does the same thing as `public_key_from_external`, // but for private keys. See the comment on that function about alignment // issues. static struct private_key *private_key_from_external( @@ -1878,14 +1882,14 @@ static struct private_key *private_key_from_external( return reinterpret_cast(align_pointer(ext->opaque, 16)); } -// malloc_align32 returns a pointer to |size| bytes of 32-byte-aligned heap and -// sets |*out_ptr| to a value that can be passed to |OPENSSL_free| to release +// malloc_align32 returns a pointer to `size` bytes of 32-byte-aligned heap and +// sets `*out_ptr` to a value that can be passed to `OPENSSL_free` to release // it. It returns NULL if out of memory. static void *malloc_align32(void **out_ptr, size_t size) { void *ptr = OPENSSL_malloc(size + 31); if (!ptr) { - *out_ptr = NULL; - return NULL; + *out_ptr = nullptr; + return nullptr; } *out_ptr = ptr; @@ -1912,7 +1916,7 @@ int HRSS_generate_key( if (!vars) { // If the caller ignores the return value the output will still be safe. // The private key output is randomised in case it's later passed to - // |HRSS_encap|. + // `HRSS_encap`. memset(out_pub, 0, sizeof(struct HRSS_public_key)); RAND_bytes((uint8_t *)out_priv, sizeof(struct HRSS_private_key)); return 0; @@ -2057,7 +2061,7 @@ int HRSS_decap(uint8_t out_shared_key[HRSS_KEY_BYTES], OPENSSL_memset(vars, 0xff, sizeof(struct vars)); #endif - // This is HMAC, expanded inline rather than using the |HMAC| function so that + // This is HMAC, expanded inline rather than using the `HMAC` function so that // we can avoid dealing with possible allocation failures and so keep this // function infallible. static_assert(sizeof(priv->hmac_key) <= sizeof(vars->masked_key), @@ -2116,26 +2120,26 @@ int HRSS_decap(uint8_t out_shared_key[HRSS_KEY_BYTES], ok = poly3_from_poly_checked(&vars->r3, &vars->r); // [NTRUCOMP] section 5.1 includes ReEnc2 and a proof that it's valid. Rather - // than do an expensive |poly_mul|, it rebuilds |c'| from |c - lift(m)| - // (called |b|) with: + // than do an expensive `poly_mul`, it rebuilds `c'` from `c - lift(m)` + // (called `b`) with: // t = (−b(1)/N) mod Q // c' = b + tΦ(N) + lift(m) mod Q // // When polynomials are transmitted, the final coefficient is omitted and - // |poly_unmarshal| sets it such that f(1) == 0. Thus c(1) == 0. Also, - // |poly_lift| multiplies the result by (x-1) and therefore evaluating a + // `poly_unmarshal` sets it such that f(1) == 0. Thus c(1) == 0. Also, + // `poly_lift` multiplies the result by (x-1) and therefore evaluating a // lifted polynomial at 1 is also zero. Thus lift(m)(1) == 0 and so // (c - lift(m))(1) == 0. // - // Although we defer the reduction above, |b| is conceptually reduced mod - // Φ(N). In order to do that reduction one subtracts |c[N-1]| from every - // coefficient. Therefore b(1) = -c[N-1]×N. The value of |t|, above, then is - // just recovering |c[N-1]|, and adding tΦ(N) is simply undoing the reduction. + // Although we defer the reduction above, `b` is conceptually reduced mod + // Φ(N). In order to do that reduction one subtracts `c[N-1]` from every + // coefficient. Therefore b(1) = -c[N-1]×N. The value of `t`, above, then is + // just recovering `c[N-1]`, and adding tΦ(N) is simply undoing the reduction. // Therefore b + tΦ(N) + lift(m) = c by construction and we don't need to - // recover |c| at all so long as we do the checks in - // |poly3_from_poly_checked|. + // recover `c` at all so long as we do the checks in + // `poly3_from_poly_checked`. // - // The |poly_marshal| here then is just confirming that |poly_unmarshal| is + // The `poly_marshal` here then is just confirming that `poly_unmarshal` is // strict and could be omitted. static_assert(HRSS_CIPHERTEXT_BYTES == POLY_BYTES, diff --git a/Sources/CNIOBoringSSL/crypto/hrss/internal.h b/Sources/CNIOBoringSSL/crypto/hrss/internal.h index a9b08d27..47ff5b4a 100644 --- a/Sources/CNIOBoringSSL/crypto/hrss/internal.h +++ b/Sources/CNIOBoringSSL/crypto/hrss/internal.h @@ -1,32 +1,29 @@ -/* Copyright 2018 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2018 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. -#ifndef OPENSSL_HEADER_HRSS_INTERNAL_H -#define OPENSSL_HEADER_HRSS_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_HRSS_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_HRSS_INTERNAL_H #include #include "../internal.h" -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN - -#define N 701 +#define HRSS_N 701 #define BITS_PER_WORD (sizeof(crypto_word_t) * 8) -#define WORDS_PER_POLY ((N + BITS_PER_WORD - 1) / BITS_PER_WORD) -#define BITS_IN_LAST_WORD (N % BITS_PER_WORD) +#define WORDS_PER_POLY ((HRSS_N + BITS_PER_WORD - 1) / BITS_PER_WORD) +#define BITS_IN_LAST_WORD (HRSS_N % BITS_PER_WORD) struct poly2 { crypto_word_t v[WORDS_PER_POLY]; @@ -43,7 +40,7 @@ OPENSSL_EXPORT void HRSS_poly3_invert(struct poly3 *out, // On x86-64, we can use the AVX2 code from [HRSS]. (The authors have given // explicit permission for this and signed a CLA.) However it's 57KB of object -// code, so it's not used if |OPENSSL_SMALL| is defined. +// code, so it's not used if `OPENSSL_SMALL` is defined. #if !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_SMALL) && \ defined(OPENSSL_X86_64) && defined(OPENSSL_LINUX) #define POLY_RQ_MUL_ASM @@ -53,16 +50,15 @@ OPENSSL_EXPORT void HRSS_poly3_invert(struct poly3 *out, // poly_Rq_mul is defined in assembly. Inputs and outputs must be 16-byte- // aligned. -extern void poly_Rq_mul( - uint16_t r[N + 3], const uint16_t a[N + 3], const uint16_t b[N + 3], +extern "C" void poly_Rq_mul( + uint16_t r[HRSS_N + 3], const uint16_t a[HRSS_N + 3], + const uint16_t b[HRSS_N + 3], // The following should be `scratch[POLY_MUL_RQ_SCRATCH_SPACE]` but // GCC 11.1 has a bug with unions that breaks that. uint8_t scratch[]); #endif +BSSL_NAMESPACE_END -#if defined(__cplusplus) -} // extern "C" -#endif -#endif // !OPENSSL_HEADER_HRSS_INTERNAL_H +#endif // !OPENSSL_HEADER_CRYPTO_HRSS_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/internal.h b/Sources/CNIOBoringSSL/crypto/internal.h index 9593c4b8..bf647935 100644 --- a/Sources/CNIOBoringSSL/crypto/internal.h +++ b/Sources/CNIOBoringSSL/crypto/internal.h @@ -1,24 +1,32 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. #ifndef OPENSSL_HEADER_CRYPTO_INTERNAL_H #define OPENSSL_HEADER_CRYPTO_INTERNAL_H -#include +#include #include #include +#include #include -#include #include +#include #include +#include + #if defined(BORINGSSL_CONSTANT_TIME_VALIDATION) #include #endif @@ -40,43 +48,50 @@ #if defined(OPENSSL_THREADS) #include +#else +#include #endif #if defined(OPENSSL_WINDOWS_THREADS) -OPENSSL_MSVC_PRAGMA(warning(push, 3)) #include -OPENSSL_MSVC_PRAGMA(warning(pop)) #endif -#if defined(__cplusplus) -extern "C" { +#if defined(_M_X64) || defined(_M_IX86) +#include "intrin.h" +#endif + +#if defined(BORINGSSL_PREFIX) +#include // IWYU pragma: export #endif -#if !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_STATIC_ARMCAP) && \ - (defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || \ - defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) +BSSL_NAMESPACE_BEGIN + +#if !defined(OPENSSL_NO_ASM) && \ + (defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || \ + (!defined(OPENSSL_STATIC_ARMCAP) && \ + (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)))) // x86, x86_64, and the ARMs need to record the result of a cpuid/getauxval call // for the asm to work correctly, unless compiled without asm code. #define NEED_CPUID // OPENSSL_cpuid_setup initializes the platform-specific feature cache. This -// function should not be called directly. Call |OPENSSL_init_cpuid| instead. -void OPENSSL_cpuid_setup(void); +// function should not be called directly. Call `OPENSSL_init_cpuid` instead. +void OPENSSL_cpuid_setup(); // OPENSSL_init_cpuid initializes the platform-specific feature cache, if // needed. This function is idempotent and may be called concurrently. -void OPENSSL_init_cpuid(void); +void OPENSSL_init_cpuid(); #else -inline void OPENSSL_init_cpuid(void) {} +inline void OPENSSL_init_cpuid() {} #endif #if (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) && \ !defined(OPENSSL_STATIC_ARMCAP) -// OPENSSL_get_armcap_pointer_for_test returns a pointer to |OPENSSL_armcap_P| -// for unit tests. Any modifications to the value must be made before any other -// function call in BoringSSL. -OPENSSL_EXPORT uint32_t *OPENSSL_get_armcap_pointer_for_test(void); +// OPENSSL_get_armcap_pointer_for_test returns a pointer to +// `OPENSSL_armcap_P` for unit tests. Any modifications to the value must be +// made before any other function call in BoringSSL. +OPENSSL_EXPORT uint32_t *OPENSSL_get_armcap_pointer_for_test(); #endif @@ -98,15 +113,7 @@ typedef __uint128_t uint128_t; #endif #endif -#define OPENSSL_ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0])) - -#if defined(__clang__) && __clang_major__ >= 5 -#if __has_attribute(fallthrough) -#define OPENSSL_CAN_USE_ATTR_FALLTHROUGH -#endif -#endif - -// GCC-like compilers indicate SSE2 with |__SSE2__|. MSVC leaves the caller to +// GCC-like compilers indicate SSE2 with `__SSE2__`. MSVC leaves the caller to // know that x86_64 has SSE2, and uses _M_IX86_FP to indicate SSE2 on x86. // https://learn.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=msvc-170 #if defined(__SSE2__) || defined(_M_AMD64) || defined(_M_X64) || \ @@ -120,7 +127,7 @@ typedef __uint128_t uint128_t; #endif // For convenience in testing the fallback code, we allow disabling SSE2 -// intrinsics via |OPENSSL_NO_SSE2_FOR_TESTING|. We require SSE2 on x86 and +// intrinsics via `OPENSSL_NO_SSE2_FOR_TESTING`. We require SSE2 on x86 and // x86_64, so we would otherwise need to test such code on a non-x86 platform. // // This does not remove the above requirement for SSE2 support with assembly @@ -136,26 +143,35 @@ typedef __uint128_t uint128_t; #define OPENSSL_ATTR_CONST #endif +// OPENSSL_ATTR_ALWAYS_INLINE tells the compiler to always attempt inlining the +// function. This has the beneficial side effects that it inherits attributes +// for code generation (e.g. the target attribute) from its callee. +#if defined(__GNUC__) || defined(__clang__) +#define OPENSSL_ATTR_ALWAYS_INLINE __attribute__((always_inline)) +#else +#define OPENSSL_ATTR_ALWAYS_INLINE +#endif + #if defined(BORINGSSL_MALLOC_FAILURE_TESTING) // OPENSSL_reset_malloc_counter_for_testing, when malloc testing is enabled, // resets the internal malloc counter, to simulate further malloc failures. This // should be called in between independent tests, at a point where failure from // a previous test will not impact subsequent ones. -OPENSSL_EXPORT void OPENSSL_reset_malloc_counter_for_testing(void); +OPENSSL_EXPORT void OPENSSL_reset_malloc_counter_for_testing(); // OPENSSL_disable_malloc_failures_for_testing, when malloc testing is enabled, -// disables simulated malloc failures. Calls to |OPENSSL_malloc| will not +// disables simulated malloc failures. Calls to `OPENSSL_malloc` will not // increment the malloc counter or synthesize failures. This may be used to skip // simulating malloc failures in some region of code. -OPENSSL_EXPORT void OPENSSL_disable_malloc_failures_for_testing(void); +OPENSSL_EXPORT void OPENSSL_disable_malloc_failures_for_testing(); // OPENSSL_enable_malloc_failures_for_testing, when malloc testing is enabled, // re-enables simulated malloc failures. -OPENSSL_EXPORT void OPENSSL_enable_malloc_failures_for_testing(void); +OPENSSL_EXPORT void OPENSSL_enable_malloc_failures_for_testing(); #else -inline void OPENSSL_reset_malloc_counter_for_testing(void) {} -inline void OPENSSL_disable_malloc_failures_for_testing(void) {} -inline void OPENSSL_enable_malloc_failures_for_testing(void) {} +inline void OPENSSL_reset_malloc_counter_for_testing() {} +inline void OPENSSL_disable_malloc_failures_for_testing() {} +inline void OPENSSL_enable_malloc_failures_for_testing() {} #endif #if defined(__has_builtin) @@ -167,10 +183,10 @@ inline void OPENSSL_enable_malloc_failures_for_testing(void) {} // Pointer utility functions. -// buffers_alias returns one if |a| and |b| alias and zero otherwise. -static inline int buffers_alias(const void *a, size_t a_bytes, const void *b, - size_t b_bytes) { - // Cast |a| and |b| to integers. In C, pointer comparisons between unrelated +// buffers_alias returns one if `a` and `b` alias and zero otherwise. +inline int buffers_alias(const void *a, size_t a_bytes, const void *b, + size_t b_bytes) { + // Cast `a` and `b` to integers. In C, pointer comparisons between unrelated // objects are undefined whereas pointer to integer conversions are merely // implementation-defined. We assume the implementation defined it in a sane // way. @@ -179,15 +195,22 @@ static inline int buffers_alias(const void *a, size_t a_bytes, const void *b, return a_u + a_bytes > b_u && b_u + b_bytes > a_u; } -// align_pointer returns |ptr|, advanced to |alignment|. |alignment| must be a -// power of two, and |ptr| must have at least |alignment - 1| bytes of scratch +// spans_alias returns one if `a` and `b` alias, and zero otherwise. +template +inline int spans_alias(Span a, Span b) { + return buffers_alias(a.data(), a.size() * sizeof(T), b.data(), + b.size() * sizeof(T)); +} + +// align_pointer returns `ptr`, advanced to `alignment`. `alignment` must be a +// power of two, and `ptr` must have at least `alignment - 1` bytes of scratch // space. -static inline void *align_pointer(void *ptr, size_t alignment) { - // |alignment| must be a power of two. +inline void *align_pointer(void *ptr, size_t alignment) { + // `alignment` must be a power of two. assert(alignment != 0 && (alignment & (alignment - 1)) == 0); - // Instead of aligning |ptr| as a |uintptr_t| and casting back, compute the + // Instead of aligning `ptr` as a `uintptr_t` and casting back, compute the // offset and advance in pointer space. C guarantees that casting from pointer - // to |uintptr_t| and back gives the same pointer, but general + // to `uintptr_t` and back gives the same pointer, but general // integer-to-pointer conversions are implementation-defined. GCC does define // it in the useful way, but this makes fewer assumptions. uintptr_t offset = (0u - (uintptr_t)ptr) & (alignment - 1); @@ -215,10 +238,10 @@ static inline void *align_pointer(void *ptr, size_t alignment) { // c = constant_time_select_w(lt, a, b); // crypto_word_t is the type that most constant-time functions use. Ideally we -// would like it to be |size_t|, but NaCl builds in 64-bit mode with 32-bit -// pointers, which means that |size_t| can be 32 bits when |BN_ULONG| is 64 +// would like it to be `size_t`, but NaCl builds in 64-bit mode with 32-bit +// pointers, which means that `size_t` can be 32 bits when `BN_ULONG` is 64 // bits. Since we want to be able to do constant-time operations on a -// |BN_ULONG|, |crypto_word_t| is defined as an unsigned value with the native +// `BN_ULONG`, `crypto_word_t` is defined as an unsigned value with the native // word length. #if defined(OPENSSL_64_BIT) typedef uint64_t crypto_word_t; @@ -233,48 +256,47 @@ typedef uint32_t crypto_word_t; #define CONSTTIME_TRUE_8 ((uint8_t)0xff) #define CONSTTIME_FALSE_8 ((uint8_t)0) -// value_barrier_w returns |a|, but prevents GCC and Clang from reasoning about +// value_barrier_w returns `a`, but prevents GCC and Clang from reasoning about // the returned value. This is used to mitigate compilers undoing constant-time // code, until we can express our requirements directly in the language. // -// Note the compiler is aware that |value_barrier_w| has no side effects and +// Note the compiler is aware that `value_barrier_w` has no side effects and // always has the same output for a given input. This allows it to eliminate // dead code, move computations across loops, and vectorize. -static inline crypto_word_t value_barrier_w(crypto_word_t a) { +inline crypto_word_t value_barrier_w(crypto_word_t a) { #if defined(__GNUC__) || defined(__clang__) __asm__("" : "+r"(a) : /* no inputs */); #endif return a; } -// value_barrier_u32 behaves like |value_barrier_w| but takes a |uint32_t|. -static inline uint32_t value_barrier_u32(uint32_t a) { +// value_barrier_u32 behaves like `value_barrier_w` but takes a `uint32_t`. +inline uint32_t value_barrier_u32(uint32_t a) { #if defined(__GNUC__) || defined(__clang__) __asm__("" : "+r"(a) : /* no inputs */); #endif return a; } -// value_barrier_u64 behaves like |value_barrier_w| but takes a |uint64_t|. -static inline uint64_t value_barrier_u64(uint64_t a) { +// value_barrier_u64 behaves like `value_barrier_w` but takes a `uint64_t`. +inline uint64_t value_barrier_u64(uint64_t a) { #if defined(__GNUC__) || defined(__clang__) __asm__("" : "+r"(a) : /* no inputs */); #endif return a; } -// |value_barrier_u8| could be defined as above, but compilers other than +// `value_barrier_u8` could be defined as above, but compilers other than // clang seem to still materialize 0x00..00MM instead of reusing 0x??..??MM. // constant_time_msb_w returns the given value with the MSB copied to all the // other bits. -static inline crypto_word_t constant_time_msb_w(crypto_word_t a) { +inline crypto_word_t constant_time_msb_w(crypto_word_t a) { return 0u - (a >> (sizeof(a) * 8 - 1)); } // constant_time_lt_w returns 0xff..f if a < b and 0 otherwise. -static inline crypto_word_t constant_time_lt_w(crypto_word_t a, - crypto_word_t b) { +inline crypto_word_t constant_time_lt_w(crypto_word_t a, crypto_word_t b) { // Consider the two cases of the problem: // msb(a) == msb(b): a < b iff the MSB of a - b is set. // msb(a) != msb(b): a < b iff the MSB of b is set. @@ -308,26 +330,25 @@ static inline crypto_word_t constant_time_lt_w(crypto_word_t a, return constant_time_msb_w(a ^ ((a ^ b) | ((a - b) ^ a))); } -// constant_time_lt_8 acts like |constant_time_lt_w| but returns an 8-bit +// constant_time_lt_8 acts like `constant_time_lt_w` but returns an 8-bit // mask. -static inline uint8_t constant_time_lt_8(crypto_word_t a, crypto_word_t b) { +inline uint8_t constant_time_lt_8(crypto_word_t a, crypto_word_t b) { return (uint8_t)(constant_time_lt_w(a, b)); } // constant_time_ge_w returns 0xff..f if a >= b and 0 otherwise. -static inline crypto_word_t constant_time_ge_w(crypto_word_t a, - crypto_word_t b) { +inline crypto_word_t constant_time_ge_w(crypto_word_t a, crypto_word_t b) { return ~constant_time_lt_w(a, b); } -// constant_time_ge_8 acts like |constant_time_ge_w| but returns an 8-bit +// constant_time_ge_8 acts like `constant_time_ge_w` but returns an 8-bit // mask. -static inline uint8_t constant_time_ge_8(crypto_word_t a, crypto_word_t b) { +inline uint8_t constant_time_ge_8(crypto_word_t a, crypto_word_t b) { return (uint8_t)(constant_time_ge_w(a, b)); } // constant_time_is_zero returns 0xff..f if a == 0 and 0 otherwise. -static inline crypto_word_t constant_time_is_zero_w(crypto_word_t a) { +inline crypto_word_t constant_time_is_zero_w(crypto_word_t a) { // Here is an SMT-LIB verification of this formula: // // (define-fun is_zero ((a (_ BitVec 32))) (_ BitVec 32) @@ -341,42 +362,40 @@ static inline crypto_word_t constant_time_is_zero_w(crypto_word_t a) { return constant_time_msb_w(~a & (a - 1)); } -// constant_time_is_zero_8 acts like |constant_time_is_zero_w| but returns an +// constant_time_is_zero_8 acts like `constant_time_is_zero_w` but returns an // 8-bit mask. -static inline uint8_t constant_time_is_zero_8(crypto_word_t a) { +inline uint8_t constant_time_is_zero_8(crypto_word_t a) { return (uint8_t)(constant_time_is_zero_w(a)); } // constant_time_eq_w returns 0xff..f if a == b and 0 otherwise. -static inline crypto_word_t constant_time_eq_w(crypto_word_t a, - crypto_word_t b) { +inline crypto_word_t constant_time_eq_w(crypto_word_t a, crypto_word_t b) { return constant_time_is_zero_w(a ^ b); } -// constant_time_eq_8 acts like |constant_time_eq_w| but returns an 8-bit +// constant_time_eq_8 acts like `constant_time_eq_w` but returns an 8-bit // mask. -static inline uint8_t constant_time_eq_8(crypto_word_t a, crypto_word_t b) { +inline uint8_t constant_time_eq_8(crypto_word_t a, crypto_word_t b) { return (uint8_t)(constant_time_eq_w(a, b)); } -// constant_time_eq_int acts like |constant_time_eq_w| but works on int +// constant_time_eq_int acts like `constant_time_eq_w` but works on int // values. -static inline crypto_word_t constant_time_eq_int(int a, int b) { +inline crypto_word_t constant_time_eq_int(int a, int b) { return constant_time_eq_w((crypto_word_t)(a), (crypto_word_t)(b)); } -// constant_time_eq_int_8 acts like |constant_time_eq_int| but returns an 8-bit +// constant_time_eq_int_8 acts like `constant_time_eq_int` but returns an 8-bit // mask. -static inline uint8_t constant_time_eq_int_8(int a, int b) { +inline uint8_t constant_time_eq_int_8(int a, int b) { return constant_time_eq_8((crypto_word_t)(a), (crypto_word_t)(b)); } -// constant_time_select_w returns (mask & a) | (~mask & b). When |mask| is all +// constant_time_select_w returns (mask & a) | (~mask & b). When `mask` is all // 1s or all 0s (as returned by the methods above), the select methods return -// either |a| (if |mask| is nonzero) or |b| (if |mask| is zero). -static inline crypto_word_t constant_time_select_w(crypto_word_t mask, - crypto_word_t a, - crypto_word_t b) { +// either `a` (if `mask` is nonzero) or `b` (if `mask` is zero). +inline crypto_word_t constant_time_select_w(crypto_word_t mask, crypto_word_t a, + crypto_word_t b) { // Clang recognizes this pattern as a select. While it usually transforms it // to a cmov, it sometimes further transforms it into a branch, which we do // not want. @@ -386,33 +405,41 @@ static inline crypto_word_t constant_time_select_w(crypto_word_t mask, return (mask & a) | (~mask & b); } -// constant_time_select_8 acts like |constant_time_select| but operates on +// constant_time_select_8 acts like `constant_time_select` but operates on // 8-bit values. -static inline uint8_t constant_time_select_8(crypto_word_t mask, uint8_t a, - uint8_t b) { - // |mask| is a word instead of |uint8_t| to avoid materializing 0x000..0MM - // Making both |mask| and its value barrier |uint8_t| would allow the compiler +inline uint8_t constant_time_select_8(crypto_word_t mask, uint8_t a, + uint8_t b) { + // `mask` is a word instead of `uint8_t` to avoid materializing 0x000..0MM + // Making both `mask` and its value barrier `uint8_t` would allow the compiler // to materialize 0x????..?MM instead, but only clang is that clever. // However, vectorization of bitwise operations seems to work better on - // |uint8_t| than a mix of |uint64_t| and |uint8_t|, so |m| is cast to - // |uint8_t| after the value barrier but before the bitwise operations. + // `uint8_t` than a mix of `uint64_t` and `uint8_t`, so `m` is cast to + // `uint8_t` after the value barrier but before the bitwise operations. uint8_t m = value_barrier_w(mask); return (m & a) | (~m & b); } -// constant_time_select_int acts like |constant_time_select| but operates on +// constant_time_select_int acts like `constant_time_select` but operates on // ints. -static inline int constant_time_select_int(crypto_word_t mask, int a, int b) { - return (int)(constant_time_select_w(mask, (crypto_word_t)(a), - (crypto_word_t)(b))); +inline int constant_time_select_int(crypto_word_t mask, int a, int b) { + return static_cast(constant_time_select_w( + mask, static_cast(a), static_cast(b))); } -// constant_time_conditional_memcpy copies |n| bytes from |src| to |dst| if -// |mask| is 0xff..ff and does nothing if |mask| is 0. The |n|-byte memory -// ranges at |dst| and |src| must not overlap, as when calling |memcpy|. -static inline void constant_time_conditional_memcpy(void *dst, const void *src, - const size_t n, - const crypto_word_t mask) { +// constant_time_select_32 acts like `constant_time_select` but operates on +// 32-bit values. +inline uint32_t constant_time_select_32(crypto_word_t mask, uint32_t a, + uint32_t b) { + return static_cast( + constant_time_select_w(mask, crypto_word_t{a}, crypto_word_t{b})); +} + +// constant_time_conditional_memcpy copies `n` bytes from `src` to `dst` if +// `mask` is 0xff..ff and does nothing if `mask` is 0. The `n`-byte memory +// ranges at `dst` and `src` must not overlap, as when calling `memcpy`. +inline void constant_time_conditional_memcpy(void *dst, const void *src, + const size_t n, + const crypto_word_t mask) { assert(!buffers_alias(dst, n, src, n)); uint8_t *out = (uint8_t *)dst; const uint8_t *in = (const uint8_t *)src; @@ -421,23 +448,26 @@ static inline void constant_time_conditional_memcpy(void *dst, const void *src, } } -// constant_time_conditional_memxor xors |n| bytes from |src| to |dst| if -// |mask| is 0xff..ff and does nothing if |mask| is 0. The |n|-byte memory -// ranges at |dst| and |src| must not overlap, as when calling |memcpy|. -static inline void constant_time_conditional_memxor(void *dst, const void *src, - size_t n, - const crypto_word_t mask) { +// constant_time_conditional_memxor xors `n` bytes from `src` to `dst` if +// `mask` is 0xff..ff and does nothing if `mask` is 0. The `n`-byte memory +// ranges at `dst` and `src` must not overlap, as when calling `memcpy`. +inline void constant_time_conditional_memxor(void *dst, const void *src, + size_t n, + const crypto_word_t mask) { assert(!buffers_alias(dst, n, src, n)); uint8_t *out = (uint8_t *)dst; const uint8_t *in = (const uint8_t *)src; -#if defined(__GNUC__) && !defined(__clang__) +#if defined(__GNUC__) || defined(__clang__) // gcc 13.2.0 doesn't automatically vectorize this loop regardless of barrier + // clang 16.0.6 vectorizes if alias analysis finds src and dst are disjoint, + // but does not conclude that from the !buffers_alias assert. typedef uint8_t v32u8 __attribute__((vector_size(32), aligned(1), may_alias)); size_t n_vec = n & ~(size_t)31; v32u8 masks = ((uint8_t)mask - (v32u8){}); // broadcast for (size_t i = 0; i < n_vec; i += 32) { *(v32u8 *)&out[i] ^= masks & *(v32u8 *)&in[i]; } + in += n_vec; out += n_vec; n -= n_vec; #endif @@ -461,15 +491,24 @@ static inline void constant_time_conditional_memxor(void *dst, const void *src, #else -#define CONSTTIME_SECRET(ptr, len) -#define CONSTTIME_DECLASSIFY(ptr, len) +// Just disable unused warnings for those. +#define CONSTTIME_SECRET(ptr, len) \ + do { \ + (void)(ptr); \ + (void)(len); \ + } while (false) +#define CONSTTIME_DECLASSIFY(ptr, len) \ + do { \ + (void)(ptr); \ + (void)(len); \ + } while (false) #endif // BORINGSSL_CONSTANT_TIME_VALIDATION -static inline crypto_word_t constant_time_declassify_w(crypto_word_t v) { - // Return |v| through a value barrier to be safe. Valgrind-based constant-time +inline crypto_word_t constant_time_declassify_w(crypto_word_t v) { + // Return `v` through a value barrier to be safe. Valgrind-based constant-time // validation is partly to check the compiler has not undone any constant-time - // work. Any place |BORINGSSL_CONSTANT_TIME_VALIDATION| influences + // work. Any place `BORINGSSL_CONSTANT_TIME_VALIDATION` influences // optimizations, this validation is inaccurate. // // However, by sending pointers through valgrind, we likely inhibit escape @@ -482,7 +521,7 @@ static inline crypto_word_t constant_time_declassify_w(crypto_word_t v) { return value_barrier_w(v); } -static inline int constant_time_declassify_int(int v) { +inline int constant_time_declassify_int(int v) { static_assert(sizeof(uint32_t) == sizeof(int), "int is not the same size as uint32_t"); // See comment above. @@ -490,8 +529,8 @@ static inline int constant_time_declassify_int(int v) { return value_barrier_u32(v); } -// declassify_assert behaves like |assert| but declassifies the result of -// evaluating |expr|. This allows the assertion to branch on the (presumably +// declassify_assert behaves like `assert` but declassifies the result of +// evaluating `expr`. This allows the assertion to branch on the (presumably // public) result, but still ensures that values leading up to the computation // were secret. #define declassify_assert(expr) assert(constant_time_declassify_int(expr)) @@ -512,168 +551,159 @@ typedef pthread_once_t CRYPTO_once_t; #error "Unknown threading library" #endif -// CRYPTO_once calls |init| exactly once per process. This is thread-safe: if -// concurrent threads call |CRYPTO_once| with the same |CRYPTO_once_t| argument -// then they will block until |init| completes, but |init| will have only been +// CRYPTO_once calls `init` exactly once per process. This is thread-safe: if +// concurrent threads call `CRYPTO_once` with the same `CRYPTO_once_t` argument +// then they will block until `init` completes, but `init` will have only been // called once. // -// The |once| argument must be a |CRYPTO_once_t| that has been initialised with -// the value |CRYPTO_ONCE_INIT|. -OPENSSL_EXPORT void CRYPTO_once(CRYPTO_once_t *once, void (*init)(void)); +// The `once` argument must be a `CRYPTO_once_t` that has been initialised with +// the value `CRYPTO_ONCE_INIT`. +OPENSSL_EXPORT void CRYPTO_once(CRYPTO_once_t *once, void (*init)()); // Atomics. // -// The following functions provide an API analogous to from C11 -// and abstract between a few variations on atomics we need to support. +// This is a thin wrapper over std::atomic because some embedded platforms do +// not support threads and don't provide a trivial std::atomic implementation. +// For now, this does not wrap std::memory_order. If we ever use non-default +// std::memory_order, we will need to wrap these too, or fix the embedded +// platforms to provide a no-op std::atomic. See https://crbug.com/442112336. #if defined(OPENSSL_THREADS) - -using CRYPTO_atomic_u32 = std::atomic; - -static_assert(sizeof(CRYPTO_atomic_u32) == sizeof(uint32_t), ""); - -inline uint32_t CRYPTO_atomic_load_u32(const CRYPTO_atomic_u32 *val) { - return val->load(std::memory_order_seq_cst); -} - -inline bool CRYPTO_atomic_compare_exchange_weak_u32(CRYPTO_atomic_u32 *val, - uint32_t *expected, - uint32_t desired) { - return val->compare_exchange_weak( - *expected, desired, std::memory_order_seq_cst, std::memory_order_seq_cst); -} - -inline void CRYPTO_atomic_store_u32(CRYPTO_atomic_u32 *val, uint32_t desired) { - val->store(desired, std::memory_order_seq_cst); -} - +template +using Atomic = std::atomic; #else +template +class Atomic { + public: + static_assert(std::is_integral_v || std::is_pointer_v); -typedef uint32_t CRYPTO_atomic_u32; - -inline uint32_t CRYPTO_atomic_load_u32(CRYPTO_atomic_u32 *val) { return *val; } - -inline int CRYPTO_atomic_compare_exchange_weak_u32(CRYPTO_atomic_u32 *val, - uint32_t *expected, - uint32_t desired) { - if (*val != *expected) { - *expected = *val; - return 0; + Atomic() = default; + constexpr Atomic(T value) : value_(value) {} + Atomic(const Atomic &) = delete; + Atomic &operator=(const Atomic &) = delete; + T operator=(T value) { + value_ = value; + return value_; } - *val = desired; - return 1; -} -inline void CRYPTO_atomic_store_u32(CRYPTO_atomic_u32 *val, uint32_t desired) { - *val = desired; -} + T load() const { return value_; } + void store(T desired) { value_ = desired; } + bool compare_exchange_strong(T &expected, T desired) { + if (value_ != expected) { + expected = value_; + return false; + } + value_ = desired; + return true; + } + bool compare_exchange_weak(T &expected, T desired) { + return compare_exchange_strong(expected, desired); + } + + T exchange(T desired) { return std::exchange(value_, desired); } + + private: + T value_; +}; #endif -// See the comment in the |__cplusplus| section above. -static_assert(sizeof(CRYPTO_atomic_u32) == sizeof(uint32_t), - "CRYPTO_atomic_u32 does not match uint32_t size"); -static_assert(alignof(CRYPTO_atomic_u32) == alignof(uint32_t), - "CRYPTO_atomic_u32 does not match uint32_t alignment"); - // Reference counting. // CRYPTO_REFCOUNT_MAX is the value at which the reference count saturates. #define CRYPTO_REFCOUNT_MAX 0xffffffff -// CRYPTO_refcount_inc atomically increments the value at |*count| unless the +using CRYPTO_refcount_t = Atomic; + +// CRYPTO_refcount_inc atomically increments the value at `*count` unless the // value would overflow. It's safe for multiple threads to concurrently call -// this or |CRYPTO_refcount_dec_and_test_zero| on the same -// |CRYPTO_refcount_t|. +// this or `CRYPTO_refcount_dec_and_test_zero` on the same +// `CRYPTO_refcount_t`. OPENSSL_EXPORT void CRYPTO_refcount_inc(CRYPTO_refcount_t *count); -// CRYPTO_refcount_dec_and_test_zero tests the value at |*count|: +// CRYPTO_refcount_dec_and_test_zero tests the value at `*count`: // if it's zero, it crashes the address space. // if it's the maximum value, it returns zero. // otherwise, it atomically decrements it and returns one iff the resulting // value is zero. // // It's safe for multiple threads to concurrently call this or -// |CRYPTO_refcount_inc| on the same |CRYPTO_refcount_t|. +// `CRYPTO_refcount_inc` on the same `CRYPTO_refcount_t`. OPENSSL_EXPORT int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *count); // Locks. +// A Mutex is a read/write lock. It can be constant-initialized, but has a +// destructor. To allocate a global one, use StaticMutex, which skips the +// destructor. +class OPENSSL_EXPORT StaticMutex { + public: + constexpr StaticMutex() = default; + StaticMutex(const StaticMutex &) = delete; + StaticMutex &operator=(const StaticMutex &) = delete; + + // LockRead locks the mutex such that other threads may also have a read lock, + // but none may have a write lock. + void LockRead(); + // UnlockRead releases a read lock. + void UnlockRead(); + + // LockWrite locks the mutex such that no other thread has any type of lock on + // it. + void LockWrite(); + // UnlockWrite releases a write lock. + void UnlockWrite(); + +protected: #if !defined(OPENSSL_THREADS) -typedef struct crypto_mutex_st { - char padding; // Empty structs have different sizes in C and C++. -} CRYPTO_MUTEX; -#define CRYPTO_MUTEX_INIT \ - { 0 } + // Nothing. #elif defined(OPENSSL_WINDOWS_THREADS) -typedef SRWLOCK CRYPTO_MUTEX; -#define CRYPTO_MUTEX_INIT SRWLOCK_INIT + SRWLOCK lock_ = SRWLOCK_INIT; #elif defined(OPENSSL_PTHREADS) -typedef pthread_rwlock_t CRYPTO_MUTEX; -#define CRYPTO_MUTEX_INIT PTHREAD_RWLOCK_INITIALIZER + pthread_rwlock_t lock_ = PTHREAD_RWLOCK_INITIALIZER; #else #error "Unknown threading library" #endif +}; -// CRYPTO_MUTEX_init initialises |lock|. If |lock| is a static variable, use a -// |CRYPTO_MUTEX_INIT|. -OPENSSL_EXPORT void CRYPTO_MUTEX_init(CRYPTO_MUTEX *lock); - -// CRYPTO_MUTEX_lock_read locks |lock| such that other threads may also have a -// read lock, but none may have a write lock. -OPENSSL_EXPORT void CRYPTO_MUTEX_lock_read(CRYPTO_MUTEX *lock); - -// CRYPTO_MUTEX_lock_write locks |lock| such that no other thread has any type -// of lock on it. -OPENSSL_EXPORT void CRYPTO_MUTEX_lock_write(CRYPTO_MUTEX *lock); - -// CRYPTO_MUTEX_unlock_read unlocks |lock| for reading. -OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_read(CRYPTO_MUTEX *lock); - -// CRYPTO_MUTEX_unlock_write unlocks |lock| for writing. -OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_write(CRYPTO_MUTEX *lock); - -// CRYPTO_MUTEX_cleanup releases all resources held by |lock|. -OPENSSL_EXPORT void CRYPTO_MUTEX_cleanup(CRYPTO_MUTEX *lock); - -#if defined(__cplusplus) -extern "C++" { - -BSSL_NAMESPACE_BEGIN +class OPENSSL_EXPORT Mutex : public StaticMutex { + public: + constexpr Mutex() = default; + ~Mutex(); +}; namespace internal { -// MutexLockBase is a RAII helper for CRYPTO_MUTEX locking. -template +// MutexLockBase is a RAII helper for Mutex locking. +template class MutexLockBase { public: - explicit MutexLockBase(CRYPTO_MUTEX *mu) : mu_(mu) { + explicit MutexLockBase(StaticMutex *mu) : mu_(mu) { assert(mu_ != nullptr); - LockFunc(mu_); + (mu_->*LockMethod)(); } - ~MutexLockBase() { ReleaseFunc(mu_); } - MutexLockBase(const MutexLockBase &) = delete; - MutexLockBase &operator=(const MutexLockBase &) = - delete; + ~MutexLockBase() { (mu_->*ReleaseMethod)(); } + MutexLockBase(const MutexLockBase &) = delete; + MutexLockBase &operator=(const MutexLockBase &) = delete; private: - CRYPTO_MUTEX *const mu_; + StaticMutex *const mu_; }; } // namespace internal using MutexWriteLock = - internal::MutexLockBase; + internal::MutexLockBase<&StaticMutex::LockWrite, &StaticMutex::UnlockWrite>; using MutexReadLock = - internal::MutexLockBase; - -BSSL_NAMESPACE_END - -} // extern "C++" -#endif // defined(__cplusplus) + internal::MutexLockBase<&StaticMutex::LockRead, &StaticMutex::UnlockRead>; +using MutexWriteUnlock = + internal::MutexLockBase<&StaticMutex::UnlockWrite, &StaticMutex::LockWrite>; +using MutexReadUnlock = + internal::MutexLockBase<&StaticMutex::UnlockRead, &StaticMutex::LockRead>; // Thread local storage. @@ -699,18 +729,18 @@ OPENSSL_EXPORT void *CRYPTO_get_thread_local(thread_local_data_t value); // CRYPTO_set_thread_local sets a pointer value for the current thread at the // given index. This function should only be called once per thread for a given -// |index|: rather than update the pointer value itself, update the data that +// `index`: rather than update the pointer value itself, update the data that // is pointed to. // // The destructor function will be called when a thread exits to free this -// thread-local data. All calls to |CRYPTO_set_thread_local| with the same -// |index| should have the same |destructor| argument. The destructor may be +// thread-local data. All calls to `CRYPTO_set_thread_local` with the same +// `index` should have the same `destructor` argument. The destructor may be // called with a NULL argument if a thread that never set a thread-local -// pointer for |index|, exits. The destructor may be called concurrently with +// pointer for `index`, exits. The destructor may be called concurrently with // different arguments. // // This function returns one on success or zero on error. If it returns zero -// then |destructor| has been called with |value| already. +// then `destructor` has been called with `value` already. OPENSSL_EXPORT int CRYPTO_set_thread_local( thread_local_data_t index, void *value, thread_local_destructor_t destructor); @@ -718,34 +748,40 @@ OPENSSL_EXPORT int CRYPTO_set_thread_local( // ex_data -typedef struct crypto_ex_data_func_st CRYPTO_EX_DATA_FUNCS; +BSSL_NAMESPACE_END -// CRYPTO_EX_DATA_CLASS tracks the ex_indices registered for a type which +struct crypto_ex_data_st { + STACK_OF(void) *sk; +} /* CRYPTO_EX_DATA */; + +BSSL_NAMESPACE_BEGIN + +struct ExDataFuncs; + +// ExDataClass tracks the ex_indices registered for a type which // supports ex_data. It should defined as a static global within the module // which defines that type. -typedef struct { - CRYPTO_MUTEX lock; - // funcs is a linked list of |CRYPTO_EX_DATA_FUNCS| structures. It may be - // traversed without serialization only up to |num_funcs|. last points to the - // final entry of |funcs|, or NULL if empty. - CRYPTO_EX_DATA_FUNCS *funcs, *last; - // num_funcs is the number of entries in |funcs|. - CRYPTO_atomic_u32 num_funcs; +struct ExDataClass { + explicit constexpr ExDataClass(bool with_app_data = false) + : num_reserved(with_app_data ? 1 : 0) {} + + StaticMutex lock; + // funcs is a linked list of `ExDataFuncs` structures. It may be traversed + // without serialization only up to `num_funcs`. last points to the final + // entry of `funcs`, or nullptr if empty. + ExDataFuncs *funcs = nullptr, *last = nullptr; + // num_funcs is the number of entries in `funcs`. + Atomic num_funcs = 0; // num_reserved is one if the ex_data index zero is reserved for legacy - // |TYPE_get_app_data| functions. - uint8_t num_reserved; -} CRYPTO_EX_DATA_CLASS; + // `TYPE_get_app_data` functions. + uint8_t num_reserved = 0; +}; -#define CRYPTO_EX_DATA_CLASS_INIT \ - { CRYPTO_MUTEX_INIT, NULL, NULL, {}, 0 } -#define CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA \ - { CRYPTO_MUTEX_INIT, NULL, NULL, {}, 1 } - -// CRYPTO_get_ex_new_index_ex allocates a new index for |ex_data_class|. Each +// 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 -// |CRYPTO_EX_DATA_CLASS|. It returns the new index on success and -1 on error. +// `ExDataClass`. It returns the new index on success and -1 on error. OPENSSL_EXPORT int CRYPTO_get_ex_new_index_ex( - CRYPTO_EX_DATA_CLASS *ex_data_class, long argl, void *argp, + 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 @@ -757,49 +793,39 @@ OPENSSL_EXPORT int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int index, void *val); // function. OPENSSL_EXPORT void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int index); -// CRYPTO_new_ex_data initialises a newly allocated |CRYPTO_EX_DATA|. +// CRYPTO_new_ex_data initialises a newly allocated `CRYPTO_EX_DATA`. OPENSSL_EXPORT void CRYPTO_new_ex_data(CRYPTO_EX_DATA *ad); -// CRYPTO_free_ex_data frees |ad|, which is embedded inside |obj|, which is an -// object of the given class. -OPENSSL_EXPORT void CRYPTO_free_ex_data(CRYPTO_EX_DATA_CLASS *ex_data_class, - void *obj, CRYPTO_EX_DATA *ad); +// CRYPTO_free_ex_data frees `ad`, which is an object of the given class. +OPENSSL_EXPORT void CRYPTO_free_ex_data(ExDataClass *ex_data_class, + CRYPTO_EX_DATA *ad); // Endianness conversions. #if defined(__GNUC__) && __GNUC__ >= 2 -static inline uint16_t CRYPTO_bswap2(uint16_t x) { - return __builtin_bswap16(x); -} +inline uint16_t CRYPTO_bswap2(uint16_t x) { return __builtin_bswap16(x); } -static inline uint32_t CRYPTO_bswap4(uint32_t x) { - return __builtin_bswap32(x); -} +inline uint32_t CRYPTO_bswap4(uint32_t x) { return __builtin_bswap32(x); } -static inline uint64_t CRYPTO_bswap8(uint64_t x) { - return __builtin_bswap64(x); -} +inline uint64_t CRYPTO_bswap8(uint64_t x) { return __builtin_bswap64(x); } #elif defined(_MSC_VER) -OPENSSL_MSVC_PRAGMA(warning(push, 3)) -#include -OPENSSL_MSVC_PRAGMA(warning(pop)) #pragma intrinsic(_byteswap_uint64, _byteswap_ulong, _byteswap_ushort) -static inline uint16_t CRYPTO_bswap2(uint16_t x) { return _byteswap_ushort(x); } +inline uint16_t CRYPTO_bswap2(uint16_t x) { return _byteswap_ushort(x); } -static inline uint32_t CRYPTO_bswap4(uint32_t x) { return _byteswap_ulong(x); } +inline uint32_t CRYPTO_bswap4(uint32_t x) { return _byteswap_ulong(x); } -static inline uint64_t CRYPTO_bswap8(uint64_t x) { return _byteswap_uint64(x); } +inline uint64_t CRYPTO_bswap8(uint64_t x) { return _byteswap_uint64(x); } #else -static inline uint16_t CRYPTO_bswap2(uint16_t x) { return (x >> 8) | (x << 8); } +inline uint16_t CRYPTO_bswap2(uint16_t x) { return (x >> 8) | (x << 8); } -static inline uint32_t CRYPTO_bswap4(uint32_t x) { +inline uint32_t CRYPTO_bswap4(uint32_t x) { x = (x >> 16) | (x << 16); x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8); return x; } -static inline uint64_t CRYPTO_bswap8(uint64_t x) { +inline uint64_t CRYPTO_bswap8(uint64_t x) { return CRYPTO_bswap4(x >> 32) | (((uint64_t)CRYPTO_bswap4(x)) << 32); } #endif @@ -816,42 +842,26 @@ static inline uint64_t CRYPTO_bswap8(uint64_t x) { // These wrapper functions behave the same as the corresponding C standard // functions, but behave as expected when passed NULL if the length is zero. // -// Note |OPENSSL_memcmp| is a different function from |CRYPTO_memcmp|. +// Note `OPENSSL_memcmp` is a different function from `CRYPTO_memcmp`. -// C++ defines |memchr| as a const-correct overload. -#if defined(__cplusplus) -extern "C++" { - -static inline const void *OPENSSL_memchr(const void *s, int c, size_t n) { +// C++ defines `memchr` as a const-correct overload. +inline const void *OPENSSL_memchr(const void *s, int c, size_t n) { if (n == 0) { - return NULL; + return nullptr; } return memchr(s, c, n); } -static inline void *OPENSSL_memchr(void *s, int c, size_t n) { +inline void *OPENSSL_memchr(void *s, int c, size_t n) { if (n == 0) { - return NULL; + return nullptr; } return memchr(s, c, n); } -} // extern "C++" -#else // __cplusplus - -static inline void *OPENSSL_memchr(const void *s, int c, size_t n) { - if (n == 0) { - return NULL; - } - - return memchr(s, c, n); -} - -#endif // __cplusplus - -static inline int OPENSSL_memcmp(const void *s1, const void *s2, size_t n) { +inline int OPENSSL_memcmp(const void *s1, const void *s2, size_t n) { if (n == 0) { return 0; } @@ -859,7 +869,7 @@ static inline int OPENSSL_memcmp(const void *s1, const void *s2, size_t n) { return memcmp(s1, s2, n); } -static inline void *OPENSSL_memcpy(void *dst, const void *src, size_t n) { +inline void *OPENSSL_memcpy(void *dst, const void *src, size_t n) { if (n == 0) { return dst; } @@ -867,7 +877,7 @@ static inline void *OPENSSL_memcpy(void *dst, const void *src, size_t n) { return memcpy(dst, src, n); } -static inline void *OPENSSL_memmove(void *dst, const void *src, size_t n) { +inline void *OPENSSL_memmove(void *dst, const void *src, size_t n) { if (n == 0) { return dst; } @@ -875,7 +885,7 @@ static inline void *OPENSSL_memmove(void *dst, const void *src, size_t n) { return memmove(dst, src, n); } -static inline void *OPENSSL_memset(void *dst, int c, size_t n) { +inline void *OPENSSL_memset(void *dst, int c, size_t n) { if (n == 0) { return dst; } @@ -887,73 +897,83 @@ static inline void *OPENSSL_memset(void *dst, int c, size_t n) { // Loads and stores. // // The following functions load and store sized integers with the specified -// endianness. They use |memcpy|, and so avoid alignment or strict aliasing +// endianness. They use `memcpy`, and so avoid alignment or strict aliasing // requirements on the input and output pointers. -static inline uint16_t CRYPTO_load_u16_be(const void *in) { +inline uint16_t CRYPTO_load_u16_le(const void *in) { + uint16_t v; + OPENSSL_memcpy(&v, in, sizeof(v)); + return v; +} + +inline void CRYPTO_store_u16_le(void *out, uint16_t v) { + OPENSSL_memcpy(out, &v, sizeof(v)); +} + +inline uint16_t CRYPTO_load_u16_be(const void *in) { uint16_t v; OPENSSL_memcpy(&v, in, sizeof(v)); return CRYPTO_bswap2(v); } -static inline void CRYPTO_store_u16_be(void *out, uint16_t v) { +inline void CRYPTO_store_u16_be(void *out, uint16_t v) { v = CRYPTO_bswap2(v); OPENSSL_memcpy(out, &v, sizeof(v)); } -static inline uint32_t CRYPTO_load_u32_le(const void *in) { +inline uint32_t CRYPTO_load_u32_le(const void *in) { uint32_t v; OPENSSL_memcpy(&v, in, sizeof(v)); return v; } -static inline void CRYPTO_store_u32_le(void *out, uint32_t v) { +inline void CRYPTO_store_u32_le(void *out, uint32_t v) { OPENSSL_memcpy(out, &v, sizeof(v)); } -static inline uint32_t CRYPTO_load_u32_be(const void *in) { +inline uint32_t CRYPTO_load_u32_be(const void *in) { uint32_t v; OPENSSL_memcpy(&v, in, sizeof(v)); return CRYPTO_bswap4(v); } -static inline void CRYPTO_store_u32_be(void *out, uint32_t v) { +inline void CRYPTO_store_u32_be(void *out, uint32_t v) { v = CRYPTO_bswap4(v); OPENSSL_memcpy(out, &v, sizeof(v)); } -static inline uint64_t CRYPTO_load_u64_le(const void *in) { +inline uint64_t CRYPTO_load_u64_le(const void *in) { uint64_t v; OPENSSL_memcpy(&v, in, sizeof(v)); return v; } -static inline void CRYPTO_store_u64_le(void *out, uint64_t v) { +inline void CRYPTO_store_u64_le(void *out, uint64_t v) { OPENSSL_memcpy(out, &v, sizeof(v)); } -static inline uint64_t CRYPTO_load_u64_be(const void *ptr) { +inline uint64_t CRYPTO_load_u64_be(const void *ptr) { uint64_t ret; OPENSSL_memcpy(&ret, ptr, sizeof(ret)); return CRYPTO_bswap8(ret); } -static inline void CRYPTO_store_u64_be(void *out, uint64_t v) { +inline void CRYPTO_store_u64_be(void *out, uint64_t v) { v = CRYPTO_bswap8(v); OPENSSL_memcpy(out, &v, sizeof(v)); } -static inline crypto_word_t CRYPTO_load_word_le(const void *in) { +inline crypto_word_t CRYPTO_load_word_le(const void *in) { crypto_word_t v; OPENSSL_memcpy(&v, in, sizeof(v)); return v; } -static inline void CRYPTO_store_word_le(void *out, crypto_word_t v) { +inline void CRYPTO_store_word_le(void *out, crypto_word_t v) { OPENSSL_memcpy(out, &v, sizeof(v)); } -static inline crypto_word_t CRYPTO_load_word_be(const void *in) { +inline crypto_word_t CRYPTO_load_word_be(const void *in) { crypto_word_t v; OPENSSL_memcpy(&v, in, sizeof(v)); #if defined(OPENSSL_64_BIT) @@ -968,11 +988,11 @@ static inline crypto_word_t CRYPTO_load_word_be(const void *in) { // Bit rotation functions. // -// Note these functions use |(-shift) & 31|, etc., because shifting by the bit +// Note these functions use `(-shift) & 31`, etc., because shifting by the bit // width is undefined. Both Clang and GCC recognize this pattern as a rotation, // but MSVC does not. Instead, we call MSVC's built-in functions. -static inline uint32_t CRYPTO_rotl_u32(uint32_t value, int shift) { +inline uint32_t CRYPTO_rotl_u32(uint32_t value, int shift) { #if defined(_MSC_VER) return _rotl(value, shift); #else @@ -980,7 +1000,7 @@ static inline uint32_t CRYPTO_rotl_u32(uint32_t value, int shift) { #endif } -static inline uint32_t CRYPTO_rotr_u32(uint32_t value, int shift) { +inline uint32_t CRYPTO_rotr_u32(uint32_t value, int shift) { #if defined(_MSC_VER) return _rotr(value, shift); #else @@ -988,7 +1008,7 @@ static inline uint32_t CRYPTO_rotr_u32(uint32_t value, int shift) { #endif } -static inline uint64_t CRYPTO_rotl_u64(uint64_t value, int shift) { +inline uint64_t CRYPTO_rotl_u64(uint64_t value, int shift) { #if defined(_MSC_VER) return _rotl64(value, shift); #else @@ -996,7 +1016,7 @@ static inline uint64_t CRYPTO_rotl_u64(uint64_t value, int shift) { #endif } -static inline uint64_t CRYPTO_rotr_u64(uint64_t value, int shift) { +inline uint64_t CRYPTO_rotr_u64(uint64_t value, int shift) { #if defined(_MSC_VER) return _rotr64(value, shift); #else @@ -1005,6 +1025,60 @@ static inline uint64_t CRYPTO_rotr_u64(uint64_t value, int shift) { } +// Bit math functions. +// +// Polyfills for C++20. + +// 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) { +#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; +#else + int width = 0; + while (n > 0) { + ++width; + n >>= 1; + } + return width; +#endif +} + +// CRYPTO_popcount returns the number of set bits in `n`'s binary +// representation. +inline int CRYPTO_popcount(uint64_t n) { +#if OPENSSL_HAS_BUILTIN(__builtin_popcountll) + static_assert(sizeof(unsigned long long) >= sizeof(uint64_t)); + return __builtin_popcountll(n); +#else + int count = 0; + while (n > 0) { + n &= (n - 1); // Clears the least significant bit that is set. + ++count; + } + return count; +#endif +} + +// CRYPTO_bit_ceil returns the smallest power of 2 that is greater than or equal +// to `n`. +inline uint64_t CRYPTO_bit_ceil(uint64_t n) { + return n ? uint64_t{1} << CRYPTO_bit_width(n - 1) : uint64_t{1}; +} + +// CRYPTO_bit_floor returns the largest power of 2 that is less than or equal to +// `n`. It returns zero if `n` is zero. +inline uint64_t CRYPTO_bit_floor(uint64_t n) { + return n ? (uint64_t{1} << (CRYPTO_bit_width(n) - 1)) : uint64_t{0}; +} + +// CRYPTO_has_single_bit returns whether `n` is an integral power of 2. +inline bool CRYPTO_has_single_bit(uint64_t n) { + return CRYPTO_popcount(n) == 1; +} + + // FIPS functions. #if defined(BORINGSSL_FIPS) @@ -1012,46 +1086,67 @@ static inline uint64_t CRYPTO_rotr_u64(uint64_t value, int shift) { // BORINGSSL_FIPS_abort is called when a FIPS power-on or continuous test // fails. It prevents any further cryptographic operations by the current // process. -void BORINGSSL_FIPS_abort(void) __attribute__((noreturn)); +void BORINGSSL_FIPS_abort() __attribute__((noreturn)); // boringssl_self_test_startup runs all startup self tests and returns one on // success or zero on error. Startup self tests do not include lazy tests. -// Call |BORINGSSL_self_test| to run every self test. -int boringssl_self_test_startup(void); +// Call `BORINGSSL_self_test` to run every self test. +int boringssl_self_test_startup(); -// boringssl_ensure_rsa_self_test checks whether the RSA self-test has been run -// in this address space. If not, it runs it and crashes the address space if -// unsuccessful. -void boringssl_ensure_rsa_self_test(void); +// boringssl_ensure_rsa_sign_self_test checks whether the RSA signing self-test +// has been run in this address space. If not, it runs it and crashes the +// address space if unsuccessful. +void boringssl_ensure_rsa_sign_self_test(); + +// boringssl_ensure_rsa_verify_self_test checks whether the RSA verification +// self-test has been run in this address space. If not, it runs it and crashes +// the address space if unsuccessful. +void boringssl_ensure_rsa_verify_self_test(); // boringssl_ensure_ecc_self_test checks whether the ECDSA and ECDH self-test // has been run in this address space. If not, it runs it and crashes the // address space if unsuccessful. -void boringssl_ensure_ecc_self_test(void); +void boringssl_ensure_ecc_self_test(); // boringssl_ensure_ffdh_self_test checks whether the FFDH self-test has been // run in this address space. If not, it runs it and crashes the address space // if unsuccessful. -void boringssl_ensure_ffdh_self_test(void); +void boringssl_ensure_ffdh_self_test(); #else // Outside of FIPS mode, the lazy tests are no-ops. -inline void boringssl_ensure_rsa_self_test(void) {} -inline void boringssl_ensure_ecc_self_test(void) {} -inline void boringssl_ensure_ffdh_self_test(void) {} +inline void boringssl_ensure_rsa_sign_self_test() {} +inline void boringssl_ensure_rsa_verify_self_test() {} +inline void boringssl_ensure_ecc_self_test() {} +inline void boringssl_ensure_ffdh_self_test() {} #endif // FIPS +// BORINGSSL_check_test checks that `expected` and `actual` are equal. It +// returns 1 on success and, on failure, it prints an error message that +// includes the hexdumps the two values and returns 0. +int BORINGSSL_check_test(Span expected, + Span actual, const char *name); + // boringssl_self_test_sha256 performs a SHA-256 KAT. -int boringssl_self_test_sha256(void); +int boringssl_self_test_sha256(); // boringssl_self_test_sha512 performs a SHA-512 KAT. -int boringssl_self_test_sha512(void); +int boringssl_self_test_sha512(); // boringssl_self_test_hmac_sha256 performs an HMAC-SHA-256 KAT. -int boringssl_self_test_hmac_sha256(void); +int boringssl_self_test_hmac_sha256(); + +// boringssl_self_test_mlkem performs the ML-KEM KATs. +OPENSSL_EXPORT int boringssl_self_test_mlkem(); + +// boringssl_self_test_mldsa performs the ML-DSA KATs. +OPENSSL_EXPORT int boringssl_self_test_mldsa(); + +// boringssl_self_test_slhdsa performs the SLH-DSA KATs. +OPENSSL_EXPORT int boringssl_self_test_slhdsa(); #if defined(BORINGSSL_FIPS_COUNTERS) void boringssl_fips_inc_counter(enum fips_counter_t counter); @@ -1062,7 +1157,7 @@ inline void boringssl_fips_inc_counter(enum fips_counter_t counter) {} #if defined(BORINGSSL_FIPS_BREAK_TESTS) inline int boringssl_fips_break_test(const char *test) { const char *const value = getenv("BORINGSSL_FIPS_BREAK_TEST"); - return value != NULL && strcmp(value, test) == 0; + return value != nullptr && strcmp(value, test) == 0; } #else inline int boringssl_fips_break_test(const char *test) { return 0; } @@ -1077,13 +1172,9 @@ inline int boringssl_fips_break_test(const char *test) { return 0; } // // Index 0: // EDX for CPUID where EAX = 1 -// Bit 20 is always zero -// Bit 28 is adjusted to reflect whether the data cache is shared between -// multiple logical cores // Bit 30 is used to indicate an Intel CPU // Index 1: // ECX for CPUID where EAX = 1 -// Bit 11 is used to indicate AMD XOP support, not SDBG // Index 2: // EBX for CPUID where EAX = 7, ECX = 0 // Bit 14 (for removed feature MPX) is used to indicate a preference for ymm @@ -1095,32 +1186,29 @@ inline int boringssl_fips_break_test(const char *test) { return 0; } // and AVX512 bits in XCR0, so it is not necessary to check those. (WARNING: See // caveats in cpu_intel.c.) // -// From C, this symbol should only be accessed with |OPENSSL_get_ia32cap|. +// This symbol should only be accessed with `OPENSSL_get_ia32cap`. extern uint32_t OPENSSL_ia32cap_P[4]; -// OPENSSL_get_ia32cap initializes the library if needed and returns the |idx|th -// entry of |OPENSSL_ia32cap_P|. It is marked as a const function so duplicate +// OPENSSL_get_ia32cap initializes the library if needed and returns the `idx`th +// entry of `OPENSSL_ia32cap_P`. It is marked as a const function so duplicate // calls can be merged by the compiler, at least when indices match. OPENSSL_ATTR_CONST uint32_t OPENSSL_get_ia32cap(int idx); +// OPENSSL_adjust_ia32cap adjusts `cap`, which should contain +// `OPENSSL_ia32cap_P`, based on the environment variable value in `env`. This +// function is exposed for unit tests. +void OPENSSL_adjust_ia32cap(uint32_t cap[4], const char *env); + // See Intel manual, volume 2A, table 3-11. -inline int CRYPTO_is_FXSR_capable(void) { -#if defined(__FXSR__) - return 1; -#else - return (OPENSSL_get_ia32cap(0) & (1u << 24)) != 0; -#endif -} - -inline int CRYPTO_is_intel_cpu(void) { +inline int CRYPTO_is_intel_cpu() { // The reserved bit 30 is used to indicate an Intel CPU. return (OPENSSL_get_ia32cap(0) & (1u << 30)) != 0; } // See Intel manual, volume 2A, table 3-10. -inline int CRYPTO_is_PCLMUL_capable(void) { +inline int CRYPTO_is_PCLMUL_capable() { #if defined(__PCLMUL__) return 1; #else @@ -1128,7 +1216,7 @@ inline int CRYPTO_is_PCLMUL_capable(void) { #endif } -inline int CRYPTO_is_SSSE3_capable(void) { +inline int CRYPTO_is_SSSE3_capable() { #if defined(__SSSE3__) return 1; #else @@ -1136,7 +1224,7 @@ inline int CRYPTO_is_SSSE3_capable(void) { #endif } -inline int CRYPTO_is_SSE4_1_capable(void) { +inline int CRYPTO_is_SSE4_1_capable() { #if defined(__SSE4_1__) return 1; #else @@ -1144,7 +1232,7 @@ inline int CRYPTO_is_SSE4_1_capable(void) { #endif } -inline int CRYPTO_is_MOVBE_capable(void) { +inline int CRYPTO_is_MOVBE_capable() { #if defined(__MOVBE__) return 1; #else @@ -1152,7 +1240,7 @@ inline int CRYPTO_is_MOVBE_capable(void) { #endif } -inline int CRYPTO_is_AESNI_capable(void) { +inline int CRYPTO_is_AESNI_capable() { #if defined(__AES__) return 1; #else @@ -1160,10 +1248,10 @@ inline int CRYPTO_is_AESNI_capable(void) { #endif } -// We intentionally avoid defining a |CRYPTO_is_XSAVE_capable| function. See -// |CRYPTO_cpu_perf_is_like_silvermont|. +// We intentionally avoid defining a `CRYPTO_is_XSAVE_capable` function. See +// `CRYPTO_cpu_perf_is_like_silvermont`. -inline int CRYPTO_is_AVX_capable(void) { +inline int CRYPTO_is_AVX_capable() { #if defined(__AVX__) return 1; #else @@ -1171,8 +1259,8 @@ inline int CRYPTO_is_AVX_capable(void) { #endif } -inline int CRYPTO_is_RDRAND_capable(void) { - // We intentionally do not check |__RDRND__| here. On some AMD processors, we +inline int CRYPTO_is_RDRAND_capable() { + // We intentionally do not check `__RDRND__` here. On some AMD processors, we // will act as if the hardware is RDRAND-incapable, even it actually supports // it. See cpu_intel.c. return (OPENSSL_get_ia32cap(1) & (1u << 30)) != 0; @@ -1180,7 +1268,7 @@ inline int CRYPTO_is_RDRAND_capable(void) { // See Intel manual, volume 2A, table 3-8. -inline int CRYPTO_is_BMI1_capable(void) { +inline int CRYPTO_is_BMI1_capable() { #if defined(__BMI__) return 1; #else @@ -1188,7 +1276,7 @@ inline int CRYPTO_is_BMI1_capable(void) { #endif } -inline int CRYPTO_is_AVX2_capable(void) { +inline int CRYPTO_is_AVX2_capable() { #if defined(__AVX2__) return 1; #else @@ -1196,7 +1284,7 @@ inline int CRYPTO_is_AVX2_capable(void) { #endif } -inline int CRYPTO_is_BMI2_capable(void) { +inline int CRYPTO_is_BMI2_capable() { #if defined(__BMI2__) return 1; #else @@ -1204,7 +1292,7 @@ inline int CRYPTO_is_BMI2_capable(void) { #endif } -inline int CRYPTO_is_ADX_capable(void) { +inline int CRYPTO_is_ADX_capable() { #if defined(__ADX__) return 1; #else @@ -1213,28 +1301,12 @@ inline int CRYPTO_is_ADX_capable(void) { } // SHA-1 and SHA-256 are defined as a single extension. -inline int CRYPTO_is_x86_SHA_capable(void) { - // We should check __SHA__ here, but for now we ignore it. We've run into a - // few places where projects build with -march=goldmont, but need a build that - // does not require SHA extensions: - // - // - Some CrOS toolchain definitions are incorrect and build with - // -march=goldmont when targetting boards that are not Goldmont. b/320482539 - // tracks fixing this. - // - // - Sometimes projects build with -march=goldmont as a rough optimized - // baseline. However, Intel CPU capabilities are not strictly linear, so - // this does not quite work. Some combination of -mtune and - // -march=x86-64-v{1,2,3,4} would be a better strategy here. - // - // - QEMU versions before 8.2 do not support SHA extensions and disable it - // with a warning. Projects that target Goldmont and test on QEMU will - // break. The long-term fix is to update to 8.2. A principled short-term fix - // would be -march=goldmont -mno-sha, to reflect that the binary needs to - // run on both QEMU-8.1-Goldmont and actual-Goldmont. - // - // TODO(b/320482539): Once the CrOS toolchain is fixed, try this again. +inline int CRYPTO_is_x86_SHA_capable() { +#if defined(__SHA__) + return 1; +#else return (OPENSSL_get_ia32cap(2) & (1u << 29)) != 0; +#endif } // CRYPTO_cpu_perf_is_like_silvermont returns one if, based on a heuristic, the @@ -1247,7 +1319,7 @@ inline int CRYPTO_is_x86_SHA_capable(void) { // isn't matched by this. Various sources indicate AMD first implemented MOVBE // and XSAVE at the same time in Jaguar, so it seems like AMD chips will not be // matched by this. That seems to be the case for other x86(-64) CPUs. -inline int CRYPTO_cpu_perf_is_like_silvermont(void) { +inline int CRYPTO_cpu_perf_is_like_silvermont() { // WARNING: This MUST NOT be used to guard the execution of the XSAVE // instruction. This is the "hardware supports XSAVE" bit, not the OSXSAVE bit // that indicates whether we can safely execute XSAVE. This bit may be set @@ -1261,7 +1333,7 @@ inline int CRYPTO_cpu_perf_is_like_silvermont(void) { return !hardware_supports_xsave && CRYPTO_is_MOVBE_capable(); } -inline int CRYPTO_is_AVX512BW_capable(void) { +inline int CRYPTO_is_AVX512BW_capable() { #if defined(__AVX512BW__) return 1; #else @@ -1269,7 +1341,7 @@ inline int CRYPTO_is_AVX512BW_capable(void) { #endif } -inline int CRYPTO_is_AVX512VL_capable(void) { +inline int CRYPTO_is_AVX512VL_capable() { #if defined(__AVX512VL__) return 1; #else @@ -1281,11 +1353,11 @@ inline int CRYPTO_is_AVX512VL_capable(void) { // should not be used even if the CPU supports them. // // Note that this reuses the bit for the removed MPX feature. -inline int CRYPTO_cpu_avoid_zmm_registers(void) { +inline int CRYPTO_cpu_avoid_zmm_registers() { return (OPENSSL_get_ia32cap(2) & (1u << 14)) != 0; } -inline int CRYPTO_is_VAES_capable(void) { +inline int CRYPTO_is_VAES_capable() { #if defined(__VAES__) return 1; #else @@ -1293,7 +1365,7 @@ inline int CRYPTO_is_VAES_capable(void) { #endif } -inline int CRYPTO_is_VPCLMULQDQ_capable(void) { +inline int CRYPTO_is_VPCLMULQDQ_capable() { #if defined(__VPCLMULQDQ__) return 1; #else @@ -1305,14 +1377,40 @@ inline int CRYPTO_is_VPCLMULQDQ_capable(void) { #if defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64) -// OPENSSL_armcap_P contains ARM CPU capabilities. From C, this should only be -// accessed with |OPENSSL_get_armcap|. +// ARMV7_NEON indicates support for NEON. +#define ARMV7_NEON (1 << 0) + +// ARMV8_AES indicates support for hardware AES instructions. +#define ARMV8_AES (1 << 2) + +// ARMV8_SHA1 indicates support for hardware SHA-1 instructions. +#define ARMV8_SHA1 (1 << 3) + +// ARMV8_SHA256 indicates support for hardware SHA-256 instructions. +#define ARMV8_SHA256 (1 << 4) + +// ARMV8_PMULL indicates support for carryless multiplication. +#define ARMV8_PMULL (1 << 5) + +// ARMV8_SHA512 indicates support for hardware SHA-512 instructions. +#define ARMV8_SHA512 (1 << 6) + +// ARMV8_SHA3 indicates support for eor3 instructions. +#define ARMV8_SHA3 (1 << 7) + +#if defined(OPENSSL_STATIC_ARMCAP) +// We assume `CRYPTO_is_*_capable` already checked static capabilities. +inline uint32_t OPENSSL_get_armcap() { return 0; } +#else +// OPENSSL_armcap_P contains ARM CPU capabilities as a bitmask of the above +// constants. This should only be accessed with `OPENSSL_get_armcap`. extern uint32_t OPENSSL_armcap_P; // OPENSSL_get_armcap initializes the library if needed and returns ARM CPU // capabilities. It is marked as a const function so duplicate calls can be // merged by the compiler. -OPENSSL_ATTR_CONST uint32_t OPENSSL_get_armcap(void); +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 @@ -1330,73 +1428,72 @@ OPENSSL_ATTR_CONST uint32_t OPENSSL_get_armcap(void); // CRYPTO_is_NEON_capable returns true if the current CPU has a NEON unit. If // this is known statically, it is a constant inline function. -inline int CRYPTO_is_NEON_capable(void) { -#if defined(OPENSSL_STATIC_ARMCAP_NEON) || defined(__ARM_NEON) +inline int CRYPTO_is_NEON_capable() { +#if (defined(OPENSSL_STATIC_ARMCAP_NEON) || defined(__ARM_NEON)) && \ + !defined(OPENSSL_NO_STATIC_NEON_FOR_TESTING) return 1; -#elif defined(OPENSSL_STATIC_ARMCAP) - return 0; #else return (OPENSSL_get_armcap() & ARMV7_NEON) != 0; #endif } -inline int CRYPTO_is_ARMv8_AES_capable(void) { +inline int CRYPTO_is_ARMv8_AES_capable() { #if defined(OPENSSL_STATIC_ARMCAP_AES) || defined(__ARM_FEATURE_AES) return 1; -#elif defined(OPENSSL_STATIC_ARMCAP) - return 0; #else return (OPENSSL_get_armcap() & ARMV8_AES) != 0; #endif } -inline int CRYPTO_is_ARMv8_PMULL_capable(void) { +inline int CRYPTO_is_ARMv8_PMULL_capable() { #if defined(OPENSSL_STATIC_ARMCAP_PMULL) || defined(__ARM_FEATURE_AES) return 1; -#elif defined(OPENSSL_STATIC_ARMCAP) - return 0; #else return (OPENSSL_get_armcap() & ARMV8_PMULL) != 0; #endif } -inline int CRYPTO_is_ARMv8_SHA1_capable(void) { - // SHA-1 and SHA-2 (only) share |__ARM_FEATURE_SHA2| but otherwise +inline int CRYPTO_is_ARMv8_SHA1_capable() { + // SHA-1 and SHA-2 (only) share `__ARM_FEATURE_SHA2` but otherwise // are dealt with independently. #if defined(OPENSSL_STATIC_ARMCAP_SHA1) || defined(__ARM_FEATURE_SHA2) return 1; -#elif defined(OPENSSL_STATIC_ARMCAP) - return 0; #else return (OPENSSL_get_armcap() & ARMV8_SHA1) != 0; #endif } -inline int CRYPTO_is_ARMv8_SHA256_capable(void) { - // SHA-1 and SHA-2 (only) share |__ARM_FEATURE_SHA2| but otherwise +inline int CRYPTO_is_ARMv8_SHA256_capable() { + // SHA-1 and SHA-2 (only) share `__ARM_FEATURE_SHA2` but otherwise // are dealt with independently. #if defined(OPENSSL_STATIC_ARMCAP_SHA256) || defined(__ARM_FEATURE_SHA2) return 1; -#elif defined(OPENSSL_STATIC_ARMCAP) - return 0; #else return (OPENSSL_get_armcap() & ARMV8_SHA256) != 0; #endif } -inline int CRYPTO_is_ARMv8_SHA512_capable(void) { - // There is no |OPENSSL_STATIC_ARMCAP_SHA512|. +inline int CRYPTO_is_ARMv8_SHA512_capable() { + // There is no `OPENSSL_STATIC_ARMCAP_SHA512`. #if defined(__ARM_FEATURE_SHA512) return 1; -#elif defined(OPENSSL_STATIC_ARMCAP) - return 0; #else return (OPENSSL_get_armcap() & ARMV8_SHA512) != 0; #endif } +inline int CRYPTO_is_ARMv8_SHA3_capable() { + // There is no `OPENSSL_STATIC_ARMCAP_SHA3`. +#if defined(__ARM_FEATURE_SHA3) + return 1; +#else + return (OPENSSL_get_armcap() & ARMV8_SHA3) != 0; +#endif +} + #endif // OPENSSL_ARM || OPENSSL_AARCH64 + #if defined(BORINGSSL_DISPATCH_TEST) // Runtime CPU dispatch testing support @@ -1408,28 +1505,40 @@ inline int CRYPTO_is_ARMv8_SHA512_capable(void) { // 3: aes_hw_set_encrypt_key // 4: vpaes_encrypt // 5: vpaes_set_encrypt_key -// 6: aes_gcm_enc_update_vaes_avx10_256 [reserved] -// 7: aes_gcm_enc_update_vaes_avx10_512 -// 8: aes_gcm_enc_update_vaes_avx2 -extern uint8_t BORINGSSL_function_hit[9]; +// 6: aes_gcm_enc_update_vaes_avx2 +// 7: aes_gcm_enc_update_vaes_avx512 +extern "C" uint8_t BORINGSSL_function_hit[8]; #endif // BORINGSSL_DISPATCH_TEST -// OPENSSL_vasprintf_internal is just like |vasprintf(3)|. If |system_malloc| is -// 0, memory will be allocated with |OPENSSL_malloc| and must be freed with -// |OPENSSL_free|. Otherwise the system |malloc| function is used and the memory -// must be freed with the system |free| function. + +// OPENSSL_vasprintf_internal is just like `vasprintf(3)`. If `system_malloc` is +// 0, memory will be allocated with `OPENSSL_malloc` and must be freed with +// `OPENSSL_free`. Otherwise the system `malloc` function is used and the memory +// must be freed with the system `free` function. OPENSSL_EXPORT int OPENSSL_vasprintf_internal(char **str, const char *format, va_list args, int system_malloc) OPENSSL_PRINTF_FORMAT_FUNC(2, 0); -#if defined(__cplusplus) -} // extern C + +// Fuzzer mode. + +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) +// 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(); +#else +inline int CRYPTO_fuzzer_mode_enabled() { return 0; } #endif + // Arithmetic functions. -// CRYPTO_addc_* returns |x + y + carry|, and sets |*out_carry| to the carry -// bit. |carry| must be zero or one. +// CRYPTO_addc_* returns `x + y + carry`, and sets `*out_carry` to the carry +// bit. `carry` must be zero or one. + +// NOTE: Unoptimized GCC builds may compile these builtins to non-constant-time +// code. For correct constant-time behavior, ensure builds are optimized. #if OPENSSL_HAS_BUILTIN(__builtin_addc) inline unsigned int CRYPTO_addc_impl(unsigned int x, unsigned int y, @@ -1463,19 +1572,29 @@ inline uint64_t CRYPTO_addc_u64(uint64_t x, uint64_t y, uint64_t carry, #else -static inline uint32_t CRYPTO_addc_u32(uint32_t x, uint32_t y, uint32_t carry, - uint32_t *out_carry) { +inline uint32_t CRYPTO_addc_u32(uint32_t x, uint32_t y, uint32_t carry, + uint32_t *out_carry) { declassify_assert(carry <= 1); +#if defined(_M_IX86) + uint32_t sum = 0; + *out_carry = _addcarry_u32(carry, x, y, &sum); + return sum; +#else uint64_t ret = carry; ret += (uint64_t)x + y; *out_carry = (uint32_t)(ret >> 32); return (uint32_t)ret; +#endif } -static inline uint64_t CRYPTO_addc_u64(uint64_t x, uint64_t y, uint64_t carry, - uint64_t *out_carry) { +inline uint64_t CRYPTO_addc_u64(uint64_t x, uint64_t y, uint64_t carry, + uint64_t *out_carry) { declassify_assert(carry <= 1); -#if defined(BORINGSSL_HAS_UINT128) +#if defined(_M_X64) + uint64_t sum = 0; + *out_carry = _addcarry_u64(carry, x, y, &sum); + return sum; +#elif defined(BORINGSSL_HAS_UINT128) uint128_t ret = carry; ret += (uint128_t)x + y; *out_carry = (uint64_t)(ret >> 64); @@ -1492,8 +1611,8 @@ static inline uint64_t CRYPTO_addc_u64(uint64_t x, uint64_t y, uint64_t carry, #endif -// CRYPTO_subc_* returns |x - y - borrow|, and sets |*out_borrow| to the borrow -// bit. |borrow| must be zero or one. +// CRYPTO_subc_* returns `x - y - borrow`, and sets `*out_borrow` to the borrow +// bit. `borrow` must be zero or one. #if OPENSSL_HAS_BUILTIN(__builtin_subc) inline unsigned int CRYPTO_subc_impl(unsigned int x, unsigned int y, @@ -1527,20 +1646,32 @@ inline uint64_t CRYPTO_subc_u64(uint64_t x, uint64_t y, uint64_t borrow, #else -static inline uint32_t CRYPTO_subc_u32(uint32_t x, uint32_t y, uint32_t borrow, - uint32_t *out_borrow) { +inline uint32_t CRYPTO_subc_u32(uint32_t x, uint32_t y, uint32_t borrow, + uint32_t *out_borrow) { declassify_assert(borrow <= 1); +#if defined(_M_IX86) + uint32_t diff = 0; + *out_borrow = _subborrow_u32(borrow, x, y, &diff); + return diff; +#else uint32_t ret = x - y - borrow; *out_borrow = (x < y) | ((x == y) & borrow); return ret; +#endif } -static inline uint64_t CRYPTO_subc_u64(uint64_t x, uint64_t y, uint64_t borrow, - uint64_t *out_borrow) { +inline uint64_t CRYPTO_subc_u64(uint64_t x, uint64_t y, uint64_t borrow, + uint64_t *out_borrow) { declassify_assert(borrow <= 1); +#if defined(_M_X64) + uint64_t diff = 0; + *out_borrow = _subborrow_u64(borrow, x, y, &diff); + return diff; +#else uint64_t ret = x - y - borrow; *out_borrow = (x < y) | ((x == y) & borrow); return ret; +#endif } #endif @@ -1553,4 +1684,84 @@ static inline uint64_t CRYPTO_subc_u64(uint64_t x, uint64_t y, uint64_t borrow, #endif +// Cleanup implements a custom scope guard, when the cleanup logic does not fit +// in a destructor. Usage: +// +// bssl::Cleanup cleanup = [&] { SomeCleanupWork(local_var); }; +template +class Cleanup { + public: + static_assert(std::is_invocable_v); + static_assert(std::is_same_v, void>); + + Cleanup(F func) : func_(func) {} + Cleanup(const Cleanup &) = delete; + Cleanup &operator=(const Cleanup &) = delete; + ~Cleanup() { func_(); } + + private: + F func_; +}; +template +Cleanup(F func) -> Cleanup; + +// DECLARE_OPAQUE_STRUCT defines a public struct `public_name` with an +// implementation struct `impl_name`. +// +// To prevent accidents, the `public_name` struct will be neither constructable, +// nor copyable/movable, nor deletable. +// +// It must be used from inside the `bssl` namespace; however, `public_name` will +// be defined outside. +// +// Usage: +// +// DECLARE_OPAQUE_STRUCT(public_st, PublicImpl) +// +// BSSL_NAMESPACE_BEGIN +// +// class PublicImpl : public public_st { +// public: +// PublicImpl(); +// ~PublicImpl(); +// void foo(); +// }; +// +// BSSL_NAMESPACE_END +// +// The implementation struct can be converted to the public struct implicitly; +// to convert the public struct to the implementation struct, call +// `FromOpaque` on it. It is explicitly allowed to call `FromOpaque` on a +// `nullptr`. +#define DECLARE_OPAQUE_STRUCT(public_name, impl_name) \ + BSSL_NAMESPACE_BEGIN \ + class impl_name; \ + BSSL_NAMESPACE_END \ + \ + /* This is unnamespaced but assumed to not create linker symbols. */ \ + struct public_name { \ + using ImplType = bssl::impl_name; \ + \ + private: \ + public_name() = default; \ + ~public_name() = default; \ + public_name(const public_name &) = delete; \ + public_name &operator=(const public_name &) = delete; \ + \ + friend class bssl::impl_name; \ + }; + +template +inline typename Public::ImplType *FromOpaque(Public *p) { + return static_cast(p); +} + +template +inline const typename Public::ImplType *FromOpaque(const Public *p) { + return static_cast(p); +} + +BSSL_NAMESPACE_END + + #endif // OPENSSL_HEADER_CRYPTO_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/kyber/internal.h b/Sources/CNIOBoringSSL/crypto/kyber/internal.h deleted file mode 100644 index bf105f58..00000000 --- a/Sources/CNIOBoringSSL/crypto/kyber/internal.h +++ /dev/null @@ -1,60 +0,0 @@ -/* Copyright 2023 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#ifndef OPENSSL_HEADER_CRYPTO_KYBER_INTERNAL_H -#define OPENSSL_HEADER_CRYPTO_KYBER_INTERNAL_H - -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -// KYBER_ENCAP_ENTROPY is the number of bytes of uniformly random entropy -// necessary to encapsulate a secret. The entropy will be leaked to the -// decapsulating party. -#define KYBER_ENCAP_ENTROPY 32 - -// KYBER_GENERATE_KEY_ENTROPY is the number of bytes of uniformly random entropy -// necessary to generate a key. -#define KYBER_GENERATE_KEY_ENTROPY 64 - -// KYBER_generate_key_external_entropy is a deterministic function to create a -// pair of Kyber768 keys, using the supplied entropy. The entropy needs to be -// uniformly random generated. This function is should only be used for tests, -// regular callers should use the non-deterministic |KYBER_generate_key| -// directly. -OPENSSL_EXPORT void KYBER_generate_key_external_entropy( - uint8_t out_encoded_public_key[KYBER_PUBLIC_KEY_BYTES], - struct KYBER_private_key *out_private_key, - const uint8_t entropy[KYBER_GENERATE_KEY_ENTROPY]); - -// KYBER_encap_external_entropy behaves like |KYBER_encap|, but uses -// |KYBER_ENCAP_ENTROPY| bytes of |entropy| for randomization. The decapsulating -// side will be able to recover |entropy| in full. This function should only be -// used for tests, regular callers should use the non-deterministic -// |KYBER_encap| directly. -OPENSSL_EXPORT void KYBER_encap_external_entropy( - uint8_t out_ciphertext[KYBER_CIPHERTEXT_BYTES], - uint8_t out_shared_secret[KYBER_SHARED_SECRET_BYTES], - const struct KYBER_public_key *public_key, - const uint8_t entropy[KYBER_ENCAP_ENTROPY]); - -#if defined(__cplusplus) -} -#endif - -#endif // OPENSSL_HEADER_CRYPTO_KYBER_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/kyber/kyber.cc b/Sources/CNIOBoringSSL/crypto/kyber/kyber.cc deleted file mode 100644 index 05fd4eca..00000000 --- a/Sources/CNIOBoringSSL/crypto/kyber/kyber.cc +++ /dev/null @@ -1,869 +0,0 @@ -/* Copyright 2023 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#define OPENSSL_UNSTABLE_EXPERIMENTAL_KYBER -#include - -#include -#include - -#include -#include - -#include "../fipsmodule/keccak/internal.h" -#include "../internal.h" -#include "./internal.h" - - -// See -// https://pq-crystals.org/kyber/data/kyber-specification-round3-20210804.pdf - -static void prf(uint8_t *out, size_t out_len, const uint8_t in[33]) { - BORINGSSL_keccak(out, out_len, in, 33, boringssl_shake256); -} - -static void hash_h(uint8_t out[32], const uint8_t *in, size_t len) { - BORINGSSL_keccak(out, 32, in, len, boringssl_sha3_256); -} - -static void hash_g(uint8_t out[64], const uint8_t *in, size_t len) { - BORINGSSL_keccak(out, 64, in, len, boringssl_sha3_512); -} - -static void kdf(uint8_t *out, size_t out_len, const uint8_t *in, size_t len) { - BORINGSSL_keccak(out, out_len, in, len, boringssl_shake256); -} - -#define DEGREE 256 -#define RANK 3 - -static const size_t kBarrettMultiplier = 5039; -static const unsigned kBarrettShift = 24; -static const uint16_t kPrime = 3329; -static const int kLog2Prime = 12; -static const uint16_t kHalfPrime = (/*kPrime=*/3329 - 1) / 2; -static const int kDU = 10; -static const int kDV = 4; -// kInverseDegree is 128^-1 mod 3329; 128 because kPrime does not have a 512th -// root of unity. -static const uint16_t kInverseDegree = 3303; -static const size_t kEncodedVectorSize = - (/*kLog2Prime=*/12 * DEGREE / 8) * RANK; -static const size_t kCompressedVectorSize = /*kDU=*/10 * RANK * DEGREE / 8; - -typedef struct scalar { - // On every function entry and exit, 0 <= c < kPrime. - uint16_t c[DEGREE]; -} scalar; - -typedef struct vector { - scalar v[RANK]; -} vector; - -typedef struct matrix { - scalar v[RANK][RANK]; -} matrix; - -// This bit of Python will be referenced in some of the following comments: -// -// p = 3329 -// -// def bitreverse(i): -// ret = 0 -// for n in range(7): -// bit = i & 1 -// ret <<= 1 -// ret |= bit -// i >>= 1 -// return ret - -// kNTTRoots = [pow(17, bitreverse(i), p) for i in range(128)] -static const uint16_t kNTTRoots[128] = { - 1, 1729, 2580, 3289, 2642, 630, 1897, 848, 1062, 1919, 193, 797, - 2786, 3260, 569, 1746, 296, 2447, 1339, 1476, 3046, 56, 2240, 1333, - 1426, 2094, 535, 2882, 2393, 2879, 1974, 821, 289, 331, 3253, 1756, - 1197, 2304, 2277, 2055, 650, 1977, 2513, 632, 2865, 33, 1320, 1915, - 2319, 1435, 807, 452, 1438, 2868, 1534, 2402, 2647, 2617, 1481, 648, - 2474, 3110, 1227, 910, 17, 2761, 583, 2649, 1637, 723, 2288, 1100, - 1409, 2662, 3281, 233, 756, 2156, 3015, 3050, 1703, 1651, 2789, 1789, - 1847, 952, 1461, 2687, 939, 2308, 2437, 2388, 733, 2337, 268, 641, - 1584, 2298, 2037, 3220, 375, 2549, 2090, 1645, 1063, 319, 2773, 757, - 2099, 561, 2466, 2594, 2804, 1092, 403, 1026, 1143, 2150, 2775, 886, - 1722, 1212, 1874, 1029, 2110, 2935, 885, 2154, -}; - -// kInverseNTTRoots = [pow(17, -bitreverse(i), p) for i in range(128)] -static const uint16_t kInverseNTTRoots[128] = { - 1, 1600, 40, 749, 2481, 1432, 2699, 687, 1583, 2760, 69, 543, - 2532, 3136, 1410, 2267, 2508, 1355, 450, 936, 447, 2794, 1235, 1903, - 1996, 1089, 3273, 283, 1853, 1990, 882, 3033, 2419, 2102, 219, 855, - 2681, 1848, 712, 682, 927, 1795, 461, 1891, 2877, 2522, 1894, 1010, - 1414, 2009, 3296, 464, 2697, 816, 1352, 2679, 1274, 1052, 1025, 2132, - 1573, 76, 2998, 3040, 1175, 2444, 394, 1219, 2300, 1455, 2117, 1607, - 2443, 554, 1179, 2186, 2303, 2926, 2237, 525, 735, 863, 2768, 1230, - 2572, 556, 3010, 2266, 1684, 1239, 780, 2954, 109, 1292, 1031, 1745, - 2688, 3061, 992, 2596, 941, 892, 1021, 2390, 642, 1868, 2377, 1482, - 1540, 540, 1678, 1626, 279, 314, 1173, 2573, 3096, 48, 667, 1920, - 2229, 1041, 2606, 1692, 680, 2746, 568, 3312, -}; - -// kModRoots = [pow(17, 2*bitreverse(i) + 1, p) for i in range(128)] -static const uint16_t kModRoots[128] = { - 17, 3312, 2761, 568, 583, 2746, 2649, 680, 1637, 1692, 723, 2606, - 2288, 1041, 1100, 2229, 1409, 1920, 2662, 667, 3281, 48, 233, 3096, - 756, 2573, 2156, 1173, 3015, 314, 3050, 279, 1703, 1626, 1651, 1678, - 2789, 540, 1789, 1540, 1847, 1482, 952, 2377, 1461, 1868, 2687, 642, - 939, 2390, 2308, 1021, 2437, 892, 2388, 941, 733, 2596, 2337, 992, - 268, 3061, 641, 2688, 1584, 1745, 2298, 1031, 2037, 1292, 3220, 109, - 375, 2954, 2549, 780, 2090, 1239, 1645, 1684, 1063, 2266, 319, 3010, - 2773, 556, 757, 2572, 2099, 1230, 561, 2768, 2466, 863, 2594, 735, - 2804, 525, 1092, 2237, 403, 2926, 1026, 2303, 1143, 2186, 2150, 1179, - 2775, 554, 886, 2443, 1722, 1607, 1212, 2117, 1874, 1455, 1029, 2300, - 2110, 1219, 2935, 394, 885, 2444, 2154, 1175, -}; - -// reduce_once reduces 0 <= x < 2*kPrime, mod kPrime. -static uint16_t reduce_once(uint16_t x) { - declassify_assert(x < 2 * kPrime); - const uint16_t subtracted = x - kPrime; - uint16_t mask = 0u - (subtracted >> 15); - // Although this is a constant-time select, we omit a value barrier here. - // Value barriers impede auto-vectorization (likely because it forces the - // value to transit through a general-purpose register). On AArch64, this is a - // difference of 2x. - // - // We usually add value barriers to selects because Clang turns consecutive - // selects with the same condition into a branch instead of CMOV/CSEL. This - // condition does not occur in Kyber, so omitting it seems to be safe so far, - // but see |scalar_centered_binomial_distribution_eta_2_with_prf|. - return (mask & x) | (~mask & subtracted); -} - -// constant time reduce x mod kPrime using Barrett reduction. x must be less -// than kPrime + 2×kPrime². -static uint16_t reduce(uint32_t x) { - declassify_assert(x < kPrime + 2u * kPrime * kPrime); - uint64_t product = (uint64_t)x * kBarrettMultiplier; - uint32_t quotient = (uint32_t)(product >> kBarrettShift); - uint32_t remainder = x - quotient * kPrime; - return reduce_once(remainder); -} - -static void scalar_zero(scalar *out) { OPENSSL_memset(out, 0, sizeof(*out)); } - -static void vector_zero(vector *out) { OPENSSL_memset(out, 0, sizeof(*out)); } - -// In place number theoretic transform of a given scalar. -// Note that Kyber'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 -// relevant roots of unity being stored in |kNTTRoots|. This means the output -// should be seen as 128 elements in GF(3329^2), with the coefficients of the -// elements being consecutive entries in |s->c|. -static void scalar_ntt(scalar *s) { - int offset = DEGREE; - // `int` is used here because using `size_t` throughout caused a ~5% slowdown - // with Clang 14 on Aarch64. - for (int step = 1; step < DEGREE / 2; step <<= 1) { - offset >>= 1; - int k = 0; - for (int i = 0; i < step; i++) { - const uint32_t step_root = kNTTRoots[i + step]; - for (int j = k; j < k + offset; j++) { - uint16_t odd = reduce(step_root * s->c[j + offset]); - uint16_t even = s->c[j]; - s->c[j] = reduce_once(odd + even); - s->c[j + offset] = reduce_once(even - odd + kPrime); - } - k += 2 * offset; - } - } -} - -static void vector_ntt(vector *a) { - for (int i = 0; i < RANK; i++) { - scalar_ntt(&a->v[i]); - } -} - -// In place inverse number theoretic transform of a given scalar, with pairs of -// entries of s->v being interpreted as elements of GF(3329^2). Just as with the -// number theoretic transform, this leaves off the first step of the normal iFFT -// to account for the fact that 3329 does not have a 512th root of unity, using -// the precomputed 128 roots of unity stored in |kInverseNTTRoots|. -static void scalar_inverse_ntt(scalar *s) { - int step = DEGREE / 2; - // `int` is used here because using `size_t` throughout caused a ~5% slowdown - // with Clang 14 on Aarch64. - for (int offset = 2; offset < DEGREE; offset <<= 1) { - step >>= 1; - int k = 0; - for (int i = 0; i < step; i++) { - uint32_t step_root = kInverseNTTRoots[i + step]; - for (int j = k; j < k + offset; j++) { - uint16_t odd = s->c[j + offset]; - uint16_t even = s->c[j]; - s->c[j] = reduce_once(odd + even); - s->c[j + offset] = reduce(step_root * (even - odd + kPrime)); - } - k += 2 * offset; - } - } - for (int i = 0; i < DEGREE; i++) { - s->c[i] = reduce(s->c[i] * kInverseDegree); - } -} - -static void vector_inverse_ntt(vector *a) { - for (int i = 0; i < RANK; i++) { - scalar_inverse_ntt(&a->v[i]); - } -} - -static void scalar_add(scalar *lhs, const scalar *rhs) { - for (int i = 0; i < DEGREE; i++) { - lhs->c[i] = reduce_once(lhs->c[i] + rhs->c[i]); - } -} - -static void scalar_sub(scalar *lhs, const scalar *rhs) { - for (int i = 0; i < DEGREE; i++) { - lhs->c[i] = reduce_once(lhs->c[i] - rhs->c[i] + kPrime); - } -} - -// Multiplying two scalars in the number theoretically transformed state. Since -// 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 multipy two reduced numbers together, so we need some -// intermediate reduction steps, even if an uint64_t could hold 3 multiplied -// numbers. -static void scalar_mult(scalar *out, const scalar *lhs, const scalar *rhs) { - 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); - } -} - -static void vector_add(vector *lhs, const vector *rhs) { - for (int i = 0; i < RANK; i++) { - scalar_add(&lhs->v[i], &rhs->v[i]); - } -} - -static void matrix_mult(vector *out, const matrix *m, const vector *a) { - vector_zero(out); - for (int i = 0; i < RANK; i++) { - 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); - } - } -} - -static void matrix_mult_transpose(vector *out, const matrix *m, - const vector *a) { - vector_zero(out); - for (int i = 0; i < RANK; i++) { - 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); - } - } -} - -static void scalar_inner_product(scalar *out, const vector *lhs, - const vector *rhs) { - scalar_zero(out); - for (int i = 0; i < RANK; i++) { - scalar product; - scalar_mult(&product, &lhs->v[i], &rhs->v[i]); - scalar_add(out, &product); - } -} - -// Algorithm 1 of the Kyber spec. Rejection samples a Keccak stream to get -// uniformly distributed elements. This is used for matrix expansion and only -// operates on public inputs. -static void scalar_from_keccak_vartime(scalar *out, - struct BORINGSSL_keccak_st *keccak_ctx) { - assert(keccak_ctx->squeeze_offset == 0); - assert(keccak_ctx->rate_bytes == 168); - static_assert(168 % 3 == 0, "block and coefficient boundaries do not align"); - - int done = 0; - while (done < DEGREE) { - uint8_t block[168]; - BORINGSSL_keccak_squeeze(keccak_ctx, block, sizeof(block)); - for (size_t i = 0; i < sizeof(block) && done < DEGREE; i += 3) { - uint16_t d1 = block[i] + 256 * (block[i + 1] % 16); - uint16_t d2 = block[i + 1] / 16 + 16 * block[i + 2]; - if (d1 < kPrime) { - out->c[done++] = d1; - } - if (d2 < kPrime && done < DEGREE) { - out->c[done++] = d2; - } - } - } -} - -// Algorithm 2 of the Kyber spec, with eta fixed to two and the PRF call -// included. Creates binominally distributed elements by sampling 2*|eta| bits, -// and setting the coefficient to the count of the first bits minus the count of -// the second bits, resulting in a centered binomial distribution. Since eta is -// two this gives -2/2 with a probability of 1/16, -1/1 with probability 1/4, -// and 0 with probability 3/8. -static void scalar_centered_binomial_distribution_eta_2_with_prf( - scalar *out, const uint8_t input[33]) { - uint8_t entropy[128]; - static_assert(sizeof(entropy) == 2 * /*kEta=*/2 * DEGREE / 8, ""); - prf(entropy, sizeof(entropy), input); - - for (int i = 0; i < DEGREE; i += 2) { - uint8_t byte = entropy[i / 2]; - - uint16_t value = (byte & 1) + ((byte >> 1) & 1); - value -= ((byte >> 2) & 1) + ((byte >> 3) & 1); - // Add |kPrime| if |value| underflowed. See |reduce_once| for a discussion - // on why the value barrier is omitted. While this could have been written - // reduce_once(value + kPrime), this is one extra addition and small range - // of |value| tempts some versions of Clang to emit a branch. - uint16_t mask = 0u - (value >> 15); - out->c[i] = value + (kPrime & mask); - - byte >>= 4; - value = (byte & 1) + ((byte >> 1) & 1); - value -= ((byte >> 2) & 1) + ((byte >> 3) & 1); - // See above. - mask = 0u - (value >> 15); - out->c[i + 1] = value + (kPrime & mask); - } -} - -// Generates a secret vector by using -// |scalar_centered_binomial_distribution_eta_2_with_prf|, using the given seed -// appending and incrementing |counter| for entry of the vector. -static void vector_generate_secret_eta_2(vector *out, uint8_t *counter, - const uint8_t seed[32]) { - uint8_t input[33]; - OPENSSL_memcpy(input, seed, 32); - for (int i = 0; i < RANK; i++) { - input[32] = (*counter)++; - scalar_centered_binomial_distribution_eta_2_with_prf(&out->v[i], input); - } -} - -// Expands the matrix of a seed for key generation and for encaps-CPA. -static void matrix_expand(matrix *out, const uint8_t rho[32]) { - uint8_t input[34]; - OPENSSL_memcpy(input, rho, 32); - for (int i = 0; i < RANK; i++) { - for (int j = 0; j < RANK; j++) { - input[32] = i; - input[33] = j; - struct BORINGSSL_keccak_st keccak_ctx; - BORINGSSL_keccak_init(&keccak_ctx, boringssl_shake128); - BORINGSSL_keccak_absorb(&keccak_ctx, input, sizeof(input)); - scalar_from_keccak_vartime(&out->v[i][j], &keccak_ctx); - } - } -} - -static const uint8_t kMasks[8] = {0x01, 0x03, 0x07, 0x0f, - 0x1f, 0x3f, 0x7f, 0xff}; - -static void scalar_encode(uint8_t *out, const scalar *s, int bits) { - assert(bits <= (int)sizeof(*s->c) * 8 && bits != 1); - - uint8_t out_byte = 0; - int out_byte_bits = 0; - - for (int i = 0; i < DEGREE; i++) { - uint16_t element = s->c[i]; - int element_bits_done = 0; - - while (element_bits_done < bits) { - int chunk_bits = bits - element_bits_done; - int out_bits_remaining = 8 - out_byte_bits; - if (chunk_bits >= out_bits_remaining) { - chunk_bits = out_bits_remaining; - out_byte |= (element & kMasks[chunk_bits - 1]) << out_byte_bits; - *out = out_byte; - out++; - out_byte_bits = 0; - out_byte = 0; - } else { - out_byte |= (element & kMasks[chunk_bits - 1]) << out_byte_bits; - out_byte_bits += chunk_bits; - } - - element_bits_done += chunk_bits; - element >>= chunk_bits; - } - } - - if (out_byte_bits > 0) { - *out = out_byte; - } -} - -// scalar_encode_1 is |scalar_encode| specialised for |bits| == 1. -static void scalar_encode_1(uint8_t out[32], const scalar *s) { - for (int i = 0; i < DEGREE; i += 8) { - uint8_t out_byte = 0; - for (int j = 0; j < 8; j++) { - out_byte |= (s->c[i + j] & 1) << j; - } - *out = out_byte; - out++; - } -} - -// Encodes an entire vector into 32*|RANK|*|bits| bytes. Note that since 256 -// (DEGREE) is divisible by 8, the individual vector entries will always fill a -// whole number of bytes, so we do not need to worry about bit packing here. -static void vector_encode(uint8_t *out, const vector *a, int bits) { - for (int i = 0; i < RANK; i++) { - scalar_encode(out + i * bits * DEGREE / 8, &a->v[i], bits); - } -} - -// scalar_decode parses |DEGREE * bits| bits from |in| into |DEGREE| values in -// |out|. It returns one on success and zero if any parsed value is >= -// |kPrime|. -static int scalar_decode(scalar *out, const uint8_t *in, int bits) { - assert(bits <= (int)sizeof(*out->c) * 8 && bits != 1); - - uint8_t in_byte = 0; - int in_byte_bits_left = 0; - - for (int i = 0; i < DEGREE; i++) { - uint16_t element = 0; - int element_bits_done = 0; - - while (element_bits_done < bits) { - if (in_byte_bits_left == 0) { - in_byte = *in; - in++; - in_byte_bits_left = 8; - } - - int chunk_bits = bits - element_bits_done; - if (chunk_bits > in_byte_bits_left) { - chunk_bits = in_byte_bits_left; - } - - element |= (in_byte & kMasks[chunk_bits - 1]) << element_bits_done; - in_byte_bits_left -= chunk_bits; - in_byte >>= chunk_bits; - - element_bits_done += chunk_bits; - } - - // An element is only out of range in the case of invalid input, in which - // case it is okay to leak the comparison. - if (constant_time_declassify_int(element >= kPrime)) { - return 0; - } - out->c[i] = element; - } - - return 1; -} - -// scalar_decode_1 is |scalar_decode| specialised for |bits| == 1. -static void scalar_decode_1(scalar *out, const uint8_t in[32]) { - for (int i = 0; i < DEGREE; i += 8) { - uint8_t in_byte = *in; - in++; - for (int j = 0; j < 8; j++) { - out->c[i + j] = in_byte & 1; - in_byte >>= 1; - } - } -} - -// Decodes 32*|RANK|*|bits| bytes from |in| into |out|. It returns one on -// success or zero if any parsed value is >= |kPrime|. -static int vector_decode(vector *out, const uint8_t *in, int bits) { - for (int i = 0; i < RANK; i++) { - if (!scalar_decode(&out->v[i], in + i * bits * DEGREE / 8, bits)) { - return 0; - } - } - return 1; -} - -// Compresses (lossily) an input |x| mod 3329 into |bits| many bits by grouping -// numbers close to each other together. The formula used is -// round(2^|bits|/kPrime*x) mod 2^|bits|. -// Uses Barrett reduction to achieve constant time. Since we need both the -// remainder (for rounding) and the quotient (as the result), we cannot use -// |reduce| here, but need to do the Barrett reduction directly. -static uint16_t compress(uint16_t x, int bits) { - uint32_t shifted = (uint32_t)x << bits; - uint64_t product = (uint64_t)shifted * kBarrettMultiplier; - uint32_t quotient = (uint32_t)(product >> kBarrettShift); - uint32_t remainder = shifted - quotient * kPrime; - - // Adjust the quotient to round correctly: - // 0 <= remainder <= kHalfPrime round to 0 - // kHalfPrime < remainder <= kPrime + kHalfPrime round to 1 - // kPrime + kHalfPrime < remainder < 2 * kPrime round to 2 - declassify_assert(remainder < 2u * kPrime); - quotient += 1 & constant_time_lt_w(kHalfPrime, remainder); - quotient += 1 & constant_time_lt_w(kPrime + kHalfPrime, remainder); - return quotient & ((1 << bits) - 1); -} - -// Decompresses |x| by using an equi-distant representative. The formula is -// round(kPrime/2^|bits|*x). Note that 2^|bits| being the divisor allows us to -// implement this logic using only bit operations. -static uint16_t decompress(uint16_t x, int bits) { - uint32_t product = (uint32_t)x * kPrime; - uint32_t power = 1 << bits; - // This is |product| % power, since |power| is a power of 2. - uint32_t remainder = product & (power - 1); - // This is |product| / power, since |power| is a power of 2. - uint32_t lower = product >> bits; - // The rounding logic works since the first half of numbers mod |power| have a - // 0 as first bit, and the second half has a 1 as first bit, since |power| is - // a power of 2. As a 12 bit number, |remainder| is always positive, so we - // will shift in 0s for a right shift. - return lower + (remainder >> (bits - 1)); -} - -static void scalar_compress(scalar *s, int bits) { - for (int i = 0; i < DEGREE; i++) { - s->c[i] = compress(s->c[i], bits); - } -} - -static void scalar_decompress(scalar *s, int bits) { - for (int i = 0; i < DEGREE; i++) { - s->c[i] = decompress(s->c[i], bits); - } -} - -static void vector_compress(vector *a, int bits) { - for (int i = 0; i < RANK; i++) { - scalar_compress(&a->v[i], bits); - } -} - -static void vector_decompress(vector *a, int bits) { - for (int i = 0; i < RANK; i++) { - scalar_decompress(&a->v[i], bits); - } -} - -namespace { - -struct public_key { - vector t; - uint8_t rho[32]; - uint8_t public_key_hash[32]; - matrix m; -}; - -static struct public_key *public_key_from_external( - const struct KYBER_public_key *external) { - static_assert(sizeof(struct KYBER_public_key) >= sizeof(struct public_key), - "Kyber public key is too small"); - static_assert(alignof(struct KYBER_public_key) >= alignof(struct public_key), - "Kyber public key align incorrect"); - return (struct public_key *)external; -} - -struct private_key { - struct public_key pub; - vector s; - uint8_t fo_failure_secret[32]; -}; - -static struct private_key *private_key_from_external( - const struct KYBER_private_key *external) { - static_assert(sizeof(struct KYBER_private_key) >= sizeof(struct private_key), - "Kyber private key too small"); - static_assert( - alignof(struct KYBER_private_key) >= alignof(struct private_key), - "Kyber private key align incorrect"); - return (struct private_key *)external; -} - -} // namespace - -// Calls |KYBER_generate_key_external_entropy| with random bytes from -// |RAND_bytes|. -void KYBER_generate_key(uint8_t out_encoded_public_key[KYBER_PUBLIC_KEY_BYTES], - struct KYBER_private_key *out_private_key) { - uint8_t entropy[KYBER_GENERATE_KEY_ENTROPY]; - RAND_bytes(entropy, sizeof(entropy)); - CONSTTIME_SECRET(entropy, sizeof(entropy)); - KYBER_generate_key_external_entropy(out_encoded_public_key, out_private_key, - entropy); -} - -static int kyber_marshal_public_key(CBB *out, const struct public_key *pub) { - uint8_t *vector_output; - if (!CBB_add_space(out, &vector_output, kEncodedVectorSize)) { - return 0; - } - vector_encode(vector_output, &pub->t, kLog2Prime); - if (!CBB_add_bytes(out, pub->rho, sizeof(pub->rho))) { - return 0; - } - return 1; -} - -// Algorithms 4 and 7 of the Kyber spec. Algorithms are combined since key -// generation is not part of the FO transform, and the spec uses Algorithm 7 to -// specify the actual key format. -void KYBER_generate_key_external_entropy( - uint8_t out_encoded_public_key[KYBER_PUBLIC_KEY_BYTES], - struct KYBER_private_key *out_private_key, - const uint8_t entropy[KYBER_GENERATE_KEY_ENTROPY]) { - struct private_key *priv = private_key_from_external(out_private_key); - uint8_t hashed[64]; - hash_g(hashed, entropy, 32); - const uint8_t *const rho = hashed; - const uint8_t *const sigma = hashed + 32; - // rho is public. - CONSTTIME_DECLASSIFY(rho, 32); - OPENSSL_memcpy(priv->pub.rho, hashed, sizeof(priv->pub.rho)); - matrix_expand(&priv->pub.m, rho); - uint8_t counter = 0; - vector_generate_secret_eta_2(&priv->s, &counter, sigma); - vector_ntt(&priv->s); - 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_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)); - - CBB cbb; - CBB_init_fixed(&cbb, out_encoded_public_key, KYBER_PUBLIC_KEY_BYTES); - if (!kyber_marshal_public_key(&cbb, &priv->pub)) { - abort(); - } - - hash_h(priv->pub.public_key_hash, out_encoded_public_key, - KYBER_PUBLIC_KEY_BYTES); - OPENSSL_memcpy(priv->fo_failure_secret, entropy + 32, 32); -} - -void KYBER_public_from_private(struct KYBER_public_key *out_public_key, - const struct KYBER_private_key *private_key) { - struct public_key *const pub = public_key_from_external(out_public_key); - const struct private_key *const priv = private_key_from_external(private_key); - *pub = priv->pub; -} - -// Algorithm 5 of the Kyber spec. Encrypts a message with given randomness to -// the ciphertext in |out|. Without applying the Fujisaki-Okamoto transform this -// would not result in a CCA secure scheme, since lattice schemes are vulnerable -// to decryption failure oracles. -static void encrypt_cpa(uint8_t out[KYBER_CIPHERTEXT_BYTES], - const struct public_key *pub, const uint8_t message[32], - const uint8_t randomness[32]) { - uint8_t counter = 0; - vector secret; - vector_generate_secret_eta_2(&secret, &counter, randomness); - vector_ntt(&secret); - vector error; - vector_generate_secret_eta_2(&error, &counter, randomness); - uint8_t input[33]; - OPENSSL_memcpy(input, randomness, 32); - input[32] = counter; - scalar scalar_error; - scalar_centered_binomial_distribution_eta_2_with_prf(&scalar_error, input); - vector u; - matrix_mult(&u, &pub->m, &secret); - vector_inverse_ntt(&u); - vector_add(&u, &error); - scalar v; - scalar_inner_product(&v, &pub->t, &secret); - scalar_inverse_ntt(&v); - scalar_add(&v, &scalar_error); - scalar expanded_message; - scalar_decode_1(&expanded_message, message); - scalar_decompress(&expanded_message, 1); - scalar_add(&v, &expanded_message); - vector_compress(&u, kDU); - vector_encode(out, &u, kDU); - scalar_compress(&v, kDV); - scalar_encode(out + kCompressedVectorSize, &v, kDV); -} - -// Calls KYBER_encap_external_entropy| with random bytes from |RAND_bytes| -void KYBER_encap(uint8_t out_ciphertext[KYBER_CIPHERTEXT_BYTES], - uint8_t out_shared_secret[KYBER_SHARED_SECRET_BYTES], - const struct KYBER_public_key *public_key) { - uint8_t entropy[KYBER_ENCAP_ENTROPY]; - RAND_bytes(entropy, KYBER_ENCAP_ENTROPY); - CONSTTIME_SECRET(entropy, KYBER_ENCAP_ENTROPY); - KYBER_encap_external_entropy(out_ciphertext, out_shared_secret, public_key, - entropy); -} - -// Algorithm 8 of the Kyber spec, safe for line 2 of the spec. The spec there -// hashes the output of the system's random number generator, since the FO -// transform will reveal it to the decrypting party. There is no reason to do -// this when a secure random number generator is used. When an insecure random -// number generator is used, the caller should switch to a secure one before -// calling this method. -void KYBER_encap_external_entropy( - uint8_t out_ciphertext[KYBER_CIPHERTEXT_BYTES], - uint8_t out_shared_secret[KYBER_SHARED_SECRET_BYTES], - const struct KYBER_public_key *public_key, - const uint8_t entropy[KYBER_ENCAP_ENTROPY]) { - const struct public_key *pub = public_key_from_external(public_key); - uint8_t input[64]; - OPENSSL_memcpy(input, entropy, KYBER_ENCAP_ENTROPY); - OPENSSL_memcpy(input + KYBER_ENCAP_ENTROPY, pub->public_key_hash, - sizeof(input) - KYBER_ENCAP_ENTROPY); - uint8_t prekey_and_randomness[64]; - hash_g(prekey_and_randomness, input, sizeof(input)); - encrypt_cpa(out_ciphertext, pub, entropy, prekey_and_randomness + 32); - // The ciphertext is public. - CONSTTIME_DECLASSIFY(out_ciphertext, KYBER_CIPHERTEXT_BYTES); - hash_h(prekey_and_randomness + 32, out_ciphertext, KYBER_CIPHERTEXT_BYTES); - kdf(out_shared_secret, KYBER_SHARED_SECRET_BYTES, prekey_and_randomness, - sizeof(prekey_and_randomness)); -} - -// Algorithm 6 of the Kyber spec. -static void decrypt_cpa(uint8_t out[32], const struct private_key *priv, - const uint8_t ciphertext[KYBER_CIPHERTEXT_BYTES]) { - vector u; - vector_decode(&u, ciphertext, kDU); - vector_decompress(&u, kDU); - vector_ntt(&u); - scalar v; - scalar_decode(&v, ciphertext + kCompressedVectorSize, kDV); - scalar_decompress(&v, kDV); - scalar mask; - scalar_inner_product(&mask, &priv->s, &u); - scalar_inverse_ntt(&mask); - scalar_sub(&v, &mask); - scalar_compress(&v, 1); - scalar_encode_1(out, &v); -} - -// Algorithm 9 of the Kyber spec, performing the FO transform by running -// encrypt_cpa on the decrypted message. The spec does not allow the decryption -// failure to be passed on to the caller, and instead returns a result that is -// deterministic but unpredictable to anyone without knowledge of the private -// key. -void KYBER_decap(uint8_t out_shared_secret[KYBER_SHARED_SECRET_BYTES], - const uint8_t ciphertext[KYBER_CIPHERTEXT_BYTES], - const struct KYBER_private_key *private_key) { - const struct private_key *priv = private_key_from_external(private_key); - uint8_t decrypted[64]; - decrypt_cpa(decrypted, priv, ciphertext); - OPENSSL_memcpy(decrypted + 32, priv->pub.public_key_hash, - sizeof(decrypted) - 32); - uint8_t prekey_and_randomness[64]; - hash_g(prekey_and_randomness, decrypted, sizeof(decrypted)); - uint8_t expected_ciphertext[KYBER_CIPHERTEXT_BYTES]; - encrypt_cpa(expected_ciphertext, &priv->pub, decrypted, - prekey_and_randomness + 32); - uint8_t mask = - constant_time_eq_int_8(CRYPTO_memcmp(ciphertext, expected_ciphertext, - sizeof(expected_ciphertext)), - 0); - uint8_t input[64]; - for (int i = 0; i < 32; i++) { - input[i] = constant_time_select_8(mask, prekey_and_randomness[i], - priv->fo_failure_secret[i]); - } - hash_h(input + 32, ciphertext, KYBER_CIPHERTEXT_BYTES); - kdf(out_shared_secret, KYBER_SHARED_SECRET_BYTES, input, sizeof(input)); -} - -int KYBER_marshal_public_key(CBB *out, - const struct KYBER_public_key *public_key) { - return kyber_marshal_public_key(out, public_key_from_external(public_key)); -} - -// kyber_parse_public_key_no_hash parses |in| into |pub| but doesn't calculate -// the value of |pub->public_key_hash|. -static int kyber_parse_public_key_no_hash(struct public_key *pub, CBS *in) { - CBS t_bytes; - if (!CBS_get_bytes(in, &t_bytes, kEncodedVectorSize) || - !vector_decode(&pub->t, CBS_data(&t_bytes), kLog2Prime) || - !CBS_copy_bytes(in, pub->rho, sizeof(pub->rho))) { - return 0; - } - matrix_expand(&pub->m, pub->rho); - return 1; -} - -int KYBER_parse_public_key(struct KYBER_public_key *public_key, CBS *in) { - struct public_key *pub = public_key_from_external(public_key); - CBS orig_in = *in; - if (!kyber_parse_public_key_no_hash(pub, in) || // - CBS_len(in) != 0) { - return 0; - } - hash_h(pub->public_key_hash, CBS_data(&orig_in), CBS_len(&orig_in)); - return 1; -} - -int KYBER_marshal_private_key(CBB *out, - const struct KYBER_private_key *private_key) { - const struct private_key *const priv = private_key_from_external(private_key); - uint8_t *s_output; - if (!CBB_add_space(out, &s_output, kEncodedVectorSize)) { - return 0; - } - vector_encode(s_output, &priv->s, kLog2Prime); - if (!kyber_marshal_public_key(out, &priv->pub) || - !CBB_add_bytes(out, priv->pub.public_key_hash, - sizeof(priv->pub.public_key_hash)) || - !CBB_add_bytes(out, priv->fo_failure_secret, - sizeof(priv->fo_failure_secret))) { - return 0; - } - return 1; -} - -int KYBER_parse_private_key(struct KYBER_private_key *out_private_key, - CBS *in) { - struct private_key *const priv = private_key_from_external(out_private_key); - - CBS s_bytes; - if (!CBS_get_bytes(in, &s_bytes, kEncodedVectorSize) || - !vector_decode(&priv->s, CBS_data(&s_bytes), kLog2Prime) || - !kyber_parse_public_key_no_hash(&priv->pub, in) || - !CBS_copy_bytes(in, priv->pub.public_key_hash, - sizeof(priv->pub.public_key_hash)) || - !CBS_copy_bytes(in, priv->fo_failure_secret, - sizeof(priv->fo_failure_secret)) || - CBS_len(in) != 0) { - return 0; - } - return 1; -} diff --git a/Sources/CNIOBoringSSL/crypto/lhash/internal.h b/Sources/CNIOBoringSSL/crypto/lhash/internal.h index 391d06ca..16d3fb4c 100644 --- a/Sources/CNIOBoringSSL/crypto/lhash/internal.h +++ b/Sources/CNIOBoringSSL/crypto/lhash/internal.h @@ -1,29 +1,31 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. -#ifndef OPENSSL_HEADER_LHASH_INTERNAL_H -#define OPENSSL_HEADER_LHASH_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_LHASH_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_LHASH_INTERNAL_H -#include +#include -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN // lhash is a traditional, chaining hash table that automatically expands and // contracts as needed. One should not use the lh_* functions directly, rather // use the type-safe macro wrappers: // -// A hash table of a specific type of object has type |LHASH_OF(type)|. This -// can be defined (once) with |DEFINE_LHASH_OF(type)| and declared where needed -// with |DECLARE_LHASH_OF(type)|. For example: +// A hash table of a specific type of object has type `LHASH_OF(type)`. This +// can be defined (once) with `DEFINE_LHASH_OF(type)`. // // struct foo { // int bar; @@ -31,19 +33,24 @@ extern "C" { // // DEFINE_LHASH_OF(struct foo) // -// Although note that the hash table will contain /pointers/ to |foo|. +// Although note that the hash table will contain /pointers/ to `foo`. // -// A macro will be defined for each of the |OPENSSL_lh_*| functions below. For -// |LHASH_OF(foo)|, the macros would be |lh_foo_new|, |lh_foo_num_items| etc. +// A macro will be defined for each of the `OPENSSL_lh_*` functions below. For +// `LHASH_OF(foo)`, the macros would be `lh_foo_new`, `lh_foo_num_items` etc. +// +// TODO(davidben): Now that this type is completely internal, this can just be a +// C++ template without any macros. +#define LHASH_OF(type) struct bssl::type##_lhash_st + // lhash_cmp_func is a comparison function that returns a value equal, or not -// equal, to zero depending on whether |*a| is equal, or not equal to |*b|, -// respectively. Note the difference between this and |stack_cmp_func| in that +// equal, to zero depending on whether `*a` is equal, or not equal to `*b`, +// respectively. Note the difference between this and `stack_cmp_func` in that // this takes pointers to the objects directly. // // This function's actual type signature is int (*)(const T*, const T*). The -// low-level |lh_*| functions will be passed a type-specific wrapper to call it +// low-level `lh_*` functions will be passed a type-specific wrapper to call it // correctly. typedef int (*lhash_cmp_func)(const void *a, const void *b); typedef int (*lhash_cmp_func_helper)(lhash_cmp_func func, const void *a, @@ -53,74 +60,76 @@ typedef int (*lhash_cmp_func_helper)(lhash_cmp_func func, const void *a, // uint32_t. // // This function's actual type signature is uint32_t (*)(const T*). The -// low-level |lh_*| functions will be passed a type-specific wrapper to call it +// low-level `lh_*` functions will be passed a type-specific wrapper to call it // correctly. typedef uint32_t (*lhash_hash_func)(const void *a); typedef uint32_t (*lhash_hash_func_helper)(lhash_hash_func func, const void *a); -typedef struct lhash_st _LHASH; +struct _LHASH; // OPENSSL_lh_new returns a new, empty hash table or NULL on error. OPENSSL_EXPORT _LHASH *OPENSSL_lh_new(lhash_hash_func hash, lhash_cmp_func comp); // OPENSSL_lh_free frees the hash table itself but none of the elements. See -// |OPENSSL_lh_doall|. +// `OPENSSL_lh_doall`. OPENSSL_EXPORT void OPENSSL_lh_free(_LHASH *lh); -// OPENSSL_lh_num_items returns the number of items in |lh|. +// OPENSSL_lh_num_items returns the number of items in `lh`. OPENSSL_EXPORT size_t OPENSSL_lh_num_items(const _LHASH *lh); -// OPENSSL_lh_retrieve finds an element equal to |data| in the hash table and +// OPENSSL_lh_retrieve finds an element equal to `data` in the hash table and // returns it. If no such element exists, it returns NULL. OPENSSL_EXPORT void *OPENSSL_lh_retrieve(const _LHASH *lh, const void *data, lhash_hash_func_helper call_hash_func, lhash_cmp_func_helper call_cmp_func); -// OPENSSL_lh_retrieve_key finds an element matching |key|, given the specified -// hash and comparison function. This differs from |OPENSSL_lh_retrieve| in that -// the key may be a different type than the values stored in |lh|. |key_hash| -// and |cmp_key| must be compatible with the functions passed into -// |OPENSSL_lh_new|. +// OPENSSL_lh_retrieve_key finds an element matching `key`, given the specified +// hash and comparison function. This differs from `OPENSSL_lh_retrieve` in that +// the key may be a different type than the values stored in `lh`. `key_hash` +// and `cmp_key` must be compatible with the functions passed into +// `OPENSSL_lh_new`. OPENSSL_EXPORT void *OPENSSL_lh_retrieve_key(const _LHASH *lh, const void *key, uint32_t key_hash, int (*cmp_key)(const void *key, const void *value)); -// OPENSSL_lh_insert inserts |data| into the hash table. If an existing element -// is equal to |data| (with respect to the comparison function) then |*old_data| +// OPENSSL_lh_insert inserts `data` into the hash table. If an existing element +// is equal to `data` (with respect to the comparison function) then `*old_data` // will be set to that value and it will be replaced. Otherwise, or in the -// event of an error, |*old_data| will be set to NULL. It returns one on +// event of an error, `*old_data` will be set to NULL. It returns one on // success or zero in the case of an allocation error. OPENSSL_EXPORT int OPENSSL_lh_insert(_LHASH *lh, void **old_data, void *data, lhash_hash_func_helper call_hash_func, lhash_cmp_func_helper call_cmp_func); -// OPENSSL_lh_delete removes an element equal to |data| from the hash table and +// OPENSSL_lh_delete removes an element equal to `data` from the hash table and // returns it. If no such element is found, it returns NULL. OPENSSL_EXPORT void *OPENSSL_lh_delete(_LHASH *lh, const void *data, lhash_hash_func_helper call_hash_func, lhash_cmp_func_helper call_cmp_func); -// OPENSSL_lh_doall_arg calls |func| on each element of the hash table and also -// passes |arg| as the second argument. +// OPENSSL_lh_doall_arg calls `func` on each element of the hash table and also +// passes `arg` as the second argument. // TODO(fork): rename this OPENSSL_EXPORT void OPENSSL_lh_doall_arg(_LHASH *lh, void (*func)(void *, void *), void *arg); +// DEFINE_LHASH_OF creates (inline) definitions of hash table. It must be used +// from within the bssl namespace. #define DEFINE_LHASH_OF(type) \ /* We disable MSVC C4191 in this macro, which warns when pointers are cast \ * to the wrong type. While the cast itself is valid, it is often a bug \ * because calling it through the cast is UB. However, we never actually \ - * call functions as |lhash_cmp_func|. The type is just a type-erased \ + * call functions as `lhash_cmp_func`. The type is just a type-erased \ * function pointer. (C does not guarantee function pointers fit in \ - * |void*|, and GCC will warn on this.) Thus we just disable the false \ + * `void*`, and GCC will warn on this.) Thus we just disable the false \ * positive warning. */ \ OPENSSL_MSVC_PRAGMA(warning(push)) \ OPENSSL_MSVC_PRAGMA(warning(disable : 4191)) \ \ - DECLARE_LHASH_OF(type) \ + struct type##_lhash_st; \ \ typedef int (*lhash_##type##_cmp_func)(const type *, const type *); \ typedef uint32_t (*lhash_##type##_hash_func)(const type *); \ @@ -176,7 +185,7 @@ OPENSSL_EXPORT void OPENSSL_lh_doall_arg(_LHASH *lh, \ inline int lh_##type##_insert(LHASH_OF(type) *lh, type **old_data, \ type *data) { \ - void *old_data_void = NULL; \ + void *old_data_void = nullptr; \ int ret = OPENSSL_lh_insert((_LHASH *)lh, &old_data_void, data, \ lh_##type##_call_hash_func, \ lh_##type##_call_cmp_func); \ @@ -208,9 +217,6 @@ OPENSSL_EXPORT void OPENSSL_lh_doall_arg(_LHASH *lh, \ OPENSSL_MSVC_PRAGMA(warning(pop)) +BSSL_NAMESPACE_END -#if defined(__cplusplus) -} // extern C -#endif - -#endif // OPENSSL_HEADER_LHASH_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_LHASH_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/lhash/lhash.cc b/Sources/CNIOBoringSSL/crypto/lhash/lhash.cc index 1f364181..1ed23c67 100644 --- a/Sources/CNIOBoringSSL/crypto/lhash/lhash.cc +++ b/Sources/CNIOBoringSSL/crypto/lhash/lhash.cc @@ -1,13 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ - -#include +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,10 +19,13 @@ #include #include "../internal.h" +#include "../mem_internal.h" #include "internal.h" -// kMinNumBuckets is the minimum size of the buckets array in an |_LHASH|. +BSSL_NAMESPACE_BEGIN + +// kMinNumBuckets is the minimum size of the buckets array in an `_LHASH`. static const size_t kMinNumBuckets = 16; // kMaxAverageChainLength contains the maximum, average chain length. When the @@ -27,47 +33,47 @@ static const size_t kMinNumBuckets = 16; static const size_t kMaxAverageChainLength = 2; static const size_t kMinAverageChainLength = 1; -// lhash_item_st is an element of a hash chain. It points to the opaque data +// LHASH_ITEM is an element of a hash chain. It points to the opaque data // for this element and to the next item in the chain. The linked-list is NULL // terminated. -typedef struct lhash_item_st { - void *data; - struct lhash_item_st *next; - // hash contains the cached, hash value of |data|. - uint32_t hash; -} LHASH_ITEM; +struct LHASH_ITEM { + void *data = nullptr; + LHASH_ITEM *next = nullptr; + // hash contains the cached, hash value of `data`. + uint32_t hash = 0; +}; -struct lhash_st { +struct _LHASH { // num_items contains the total number of items in the hash table. - size_t num_items; - // buckets is an array of |num_buckets| pointers. Each points to the head of + size_t num_items = 0; + // buckets is an array of `num_buckets` pointers. Each points to the head of // a chain of LHASH_ITEM objects that have the same hash value, mod - // |num_buckets|. - LHASH_ITEM **buckets; - // num_buckets contains the length of |buckets|. This value is always >= + // `num_buckets`. + LHASH_ITEM **buckets = nullptr; + // num_buckets contains the length of `buckets`. This value is always >= // kMinNumBuckets. - size_t num_buckets; - // callback_depth contains the current depth of |lh_doall| or |lh_doall_arg| - // calls. If non-zero then this suppresses resizing of the |buckets| array, + size_t num_buckets = 0; + // callback_depth contains the current depth of `lh_doall` or `lh_doall_arg` + // calls. If non-zero then this suppresses resizing of the `buckets` array, // which would otherwise disrupt the iteration. - unsigned callback_depth; + unsigned callback_depth = 0; - lhash_cmp_func comp; - lhash_hash_func hash; + lhash_cmp_func comp = nullptr; + lhash_hash_func hash = nullptr; }; _LHASH *OPENSSL_lh_new(lhash_hash_func hash, lhash_cmp_func comp) { - _LHASH *ret = reinterpret_cast<_LHASH *>(OPENSSL_zalloc(sizeof(_LHASH))); - if (ret == NULL) { - return NULL; + _LHASH *ret = New<_LHASH>(); + if (ret == nullptr) { + return nullptr; } ret->num_buckets = kMinNumBuckets; ret->buckets = reinterpret_cast( OPENSSL_calloc(ret->num_buckets, sizeof(LHASH_ITEM *))); - if (ret->buckets == NULL) { - OPENSSL_free(ret); - return NULL; + if (ret->buckets == nullptr) { + Delete(ret); + return nullptr; } ret->comp = comp; @@ -76,42 +82,42 @@ _LHASH *OPENSSL_lh_new(lhash_hash_func hash, lhash_cmp_func comp) { } void OPENSSL_lh_free(_LHASH *lh) { - if (lh == NULL) { + if (lh == nullptr) { return; } for (size_t i = 0; i < lh->num_buckets; i++) { LHASH_ITEM *next; - for (LHASH_ITEM *n = lh->buckets[i]; n != NULL; n = next) { + for (LHASH_ITEM *n = lh->buckets[i]; n != nullptr; n = next) { next = n->next; - OPENSSL_free(n); + Delete(n); } } OPENSSL_free(lh->buckets); - OPENSSL_free(lh); + Delete(lh); } size_t OPENSSL_lh_num_items(const _LHASH *lh) { return lh->num_items; } // get_next_ptr_and_hash returns a pointer to the pointer that points to the -// item equal to |data|. In other words, it searches for an item equal to |data| +// item equal to `data`. In other words, it searches for an item equal to `data` // and, if it's at the start of a chain, then it returns a pointer to an -// element of |lh->buckets|, otherwise it returns a pointer to the |next| -// element of the previous item in the chain. If an element equal to |data| is -// not found, it returns a pointer that points to a NULL pointer. If |out_hash| -// is not NULL, then it also puts the hash value of |data| in |*out_hash|. +// element of `lh->buckets`, otherwise it returns a pointer to the `next` +// element of the previous item in the chain. If an element equal to `data` is +// not found, it returns a pointer that points to a NULL pointer. If `out_hash` +// is not NULL, then it also puts the hash value of `data` in `*out_hash`. static LHASH_ITEM **get_next_ptr_and_hash(const _LHASH *lh, uint32_t *out_hash, const void *data, lhash_hash_func_helper call_hash_func, lhash_cmp_func_helper call_cmp_func) { const uint32_t hash = call_hash_func(lh->hash, data); - if (out_hash != NULL) { + if (out_hash != nullptr) { *out_hash = hash; } LHASH_ITEM **ret = &lh->buckets[hash % lh->num_buckets]; - for (LHASH_ITEM *cur = *ret; cur != NULL; cur = *ret) { + for (LHASH_ITEM *cur = *ret; cur != nullptr; cur = *ret) { if (call_cmp_func(lh->comp, cur->data, data) == 0) { break; } @@ -121,14 +127,14 @@ static LHASH_ITEM **get_next_ptr_and_hash(const _LHASH *lh, uint32_t *out_hash, return ret; } -// get_next_ptr_by_key behaves like |get_next_ptr_and_hash| but takes a key -// which may be a different type from the values stored in |lh|. +// get_next_ptr_by_key behaves like `get_next_ptr_and_hash` but takes a key +// which may be a different type from the values stored in `lh`. static LHASH_ITEM **get_next_ptr_by_key(const _LHASH *lh, const void *key, uint32_t key_hash, int (*cmp_key)(const void *key, const void *value)) { LHASH_ITEM **ret = &lh->buckets[key_hash % lh->num_buckets]; - for (LHASH_ITEM *cur = *ret; cur != NULL; cur = *ret) { + for (LHASH_ITEM *cur = *ret; cur != nullptr; cur = *ret) { if (cmp_key(key, cur->data) == 0) { break; } @@ -142,8 +148,8 @@ void *OPENSSL_lh_retrieve(const _LHASH *lh, const void *data, lhash_hash_func_helper call_hash_func, lhash_cmp_func_helper call_cmp_func) { LHASH_ITEM **next_ptr = - get_next_ptr_and_hash(lh, NULL, data, call_hash_func, call_cmp_func); - return *next_ptr == NULL ? NULL : (*next_ptr)->data; + get_next_ptr_and_hash(lh, nullptr, data, call_hash_func, call_cmp_func); + return *next_ptr == nullptr ? nullptr : (*next_ptr)->data; } void *OPENSSL_lh_retrieve_key(const _LHASH *lh, const void *key, @@ -151,11 +157,11 @@ void *OPENSSL_lh_retrieve_key(const _LHASH *lh, const void *key, int (*cmp_key)(const void *key, const void *value)) { LHASH_ITEM **next_ptr = get_next_ptr_by_key(lh, key, key_hash, cmp_key); - return *next_ptr == NULL ? NULL : (*next_ptr)->data; + return *next_ptr == nullptr ? nullptr : (*next_ptr)->data; } -// lh_rebucket allocates a new array of |new_num_buckets| pointers and -// redistributes the existing items into it before making it |lh->buckets| and +// lh_rebucket allocates a new array of `new_num_buckets` pointers and +// redistributes the existing items into it before making it `lh->buckets` and // freeing the old array. static void lh_rebucket(_LHASH *lh, const size_t new_num_buckets) { LHASH_ITEM **new_buckets, *cur, *next; @@ -167,12 +173,12 @@ static void lh_rebucket(_LHASH *lh, const size_t new_num_buckets) { } new_buckets = reinterpret_cast(OPENSSL_zalloc(alloc_size)); - if (new_buckets == NULL) { + if (new_buckets == nullptr) { return; } for (i = 0; i < lh->num_buckets; i++) { - for (cur = lh->buckets[i]; cur != NULL; cur = next) { + for (cur = lh->buckets[i]; cur != nullptr; cur = next) { const size_t new_bucket = cur->hash % new_num_buckets; next = cur->next; cur->next = new_buckets[new_bucket]; @@ -186,7 +192,7 @@ static void lh_rebucket(_LHASH *lh, const size_t new_num_buckets) { lh->buckets = new_buckets; } -// lh_maybe_resize resizes the |buckets| array if needed. +// lh_maybe_resize resizes the `buckets` array if needed. static void lh_maybe_resize(_LHASH *lh) { size_t avg_chain_length; @@ -222,28 +228,28 @@ int OPENSSL_lh_insert(_LHASH *lh, void **old_data, void *data, uint32_t hash; LHASH_ITEM **next_ptr, *item; - *old_data = NULL; + *old_data = nullptr; next_ptr = get_next_ptr_and_hash(lh, &hash, data, call_hash_func, call_cmp_func); - if (*next_ptr != NULL) { - // An element equal to |data| already exists in the hash table. It will be + if (*next_ptr != nullptr) { + // An element equal to `data` already exists in the hash table. It will be // replaced. *old_data = (*next_ptr)->data; (*next_ptr)->data = data; return 1; } - // An element equal to |data| doesn't exist in the hash table yet. - item = reinterpret_cast(OPENSSL_malloc(sizeof(LHASH_ITEM))); - if (item == NULL) { + // An element equal to `data` doesn't exist in the hash table yet. + item = New(); + if (item == nullptr) { return 0; } item->data = data; item->hash = hash; - item->next = NULL; + item->next = nullptr; *next_ptr = item; lh->num_items++; lh_maybe_resize(lh); @@ -257,17 +263,17 @@ void *OPENSSL_lh_delete(_LHASH *lh, const void *data, LHASH_ITEM **next_ptr, *item, *ret; next_ptr = - get_next_ptr_and_hash(lh, NULL, data, call_hash_func, call_cmp_func); + get_next_ptr_and_hash(lh, nullptr, data, call_hash_func, call_cmp_func); - if (*next_ptr == NULL) { + if (*next_ptr == nullptr) { // No such element. - return NULL; + return nullptr; } item = *next_ptr; *next_ptr = item->next; ret = reinterpret_cast(item->data); - OPENSSL_free(item); + Delete(item); lh->num_items--; lh_maybe_resize(lh); @@ -276,18 +282,18 @@ void *OPENSSL_lh_delete(_LHASH *lh, const void *data, } void OPENSSL_lh_doall_arg(_LHASH *lh, void (*func)(void *, void *), void *arg) { - if (lh == NULL) { + if (lh == nullptr) { return; } if (lh->callback_depth < UINT_MAX) { - // |callback_depth| is a saturating counter. + // `callback_depth` is a saturating counter. lh->callback_depth++; } for (size_t i = 0; i < lh->num_buckets; i++) { LHASH_ITEM *next; - for (LHASH_ITEM *cur = lh->buckets[i]; cur != NULL; cur = next) { + for (LHASH_ITEM *cur = lh->buckets[i]; cur != nullptr; cur = next) { next = cur->next; func(cur->data, arg); } @@ -298,7 +304,9 @@ void OPENSSL_lh_doall_arg(_LHASH *lh, void (*func)(void *, void *), void *arg) { } // The callback may have added or removed elements and the non-zero value of - // |callback_depth| will have suppressed any resizing. Thus any needed + // `callback_depth` will have suppressed any resizing. Thus any needed // resizing is done here. lh_maybe_resize(lh); } + +BSSL_NAMESPACE_END diff --git a/Sources/CNIOBoringSSL/crypto/md4/md4.cc b/Sources/CNIOBoringSSL/crypto/md4/md4.cc index ac992f85..b3e3b88c 100644 --- a/Sources/CNIOBoringSSL/crypto/md4/md4.cc +++ b/Sources/CNIOBoringSSL/crypto/md4/md4.cc @@ -1,21 +1,30 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../fipsmodule/digest/md32_common.h" #include "../internal.h" +using namespace bssl; + uint8_t *MD4(const uint8_t *data, size_t len, uint8_t out[MD4_DIGEST_LENGTH]) { MD4_CTX ctx; MD4_Init(&ctx); @@ -43,17 +52,26 @@ void MD4_Transform(MD4_CTX *c, const uint8_t data[MD4_CBLOCK]) { md4_block_data_order(c->h, data, 1); } +namespace { +struct MD4Traits { + using HashContext = MD4_CTX; + static constexpr size_t kBlockSize = MD4_CBLOCK; + static constexpr bool kLengthIsBigEndian = false; + static void HashBlocks(uint32_t *state, const uint8_t *data, + size_t num_blocks) { + md4_block_data_order(state, data, num_blocks); + } +}; +} // namespace + int MD4_Update(MD4_CTX *c, const void *data, size_t len) { - crypto_md32_update(&md4_block_data_order, c->h, c->data, MD4_CBLOCK, &c->num, - &c->Nh, &c->Nl, reinterpret_cast(data), - len); + crypto_md32_update(c, + Span(static_cast(data), len)); return 1; } int MD4_Final(uint8_t out[MD4_DIGEST_LENGTH], MD4_CTX *c) { - crypto_md32_final(&md4_block_data_order, c->h, c->data, MD4_CBLOCK, &c->num, - c->Nh, c->Nl, /*is_big_endian=*/0); - + crypto_md32_final(c); CRYPTO_store_u32_le(out, c->h[0]); CRYPTO_store_u32_le(out + 4, c->h[1]); CRYPTO_store_u32_le(out + 8, c->h[2]); diff --git a/Sources/CNIOBoringSSL/crypto/md5/internal.h b/Sources/CNIOBoringSSL/crypto/md5/internal.h index 3c1c2718..ca14c59f 100644 --- a/Sources/CNIOBoringSSL/crypto/md5/internal.h +++ b/Sources/CNIOBoringSSL/crypto/md5/internal.h @@ -1,37 +1,34 @@ -/* Copyright 2018 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2018 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. -#ifndef OPENSSL_HEADER_MD5_INTERNAL_H -#define OPENSSL_HEADER_MD5_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_MD5_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_MD5_INTERNAL_H #include -#if defined(__cplusplus) -extern "C" { -#endif +#include "../internal.h" +BSSL_NAMESPACE_BEGIN + #if !defined(OPENSSL_NO_ASM) && \ (defined(OPENSSL_X86_64) || defined(OPENSSL_X86)) #define MD5_ASM -extern void md5_block_asm_data_order(uint32_t *state, const uint8_t *data, - size_t num); +extern "C" void md5_block_asm_data_order(uint32_t *state, const uint8_t *data, + size_t num); #endif +BSSL_NAMESPACE_END -#if defined(__cplusplus) -} // extern "C" -#endif - -#endif // OPENSSL_HEADER_MD5_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_MD5_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/md5/md5.cc b/Sources/CNIOBoringSSL/crypto/md5/md5.cc index 02c8a381..16a8a89d 100644 --- a/Sources/CNIOBoringSSL/crypto/md5/md5.cc +++ b/Sources/CNIOBoringSSL/crypto/md5/md5.cc @@ -1,23 +1,31 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../fipsmodule/digest/md32_common.h" #include "../internal.h" #include "internal.h" +using namespace bssl; + uint8_t *MD5(const uint8_t *data, size_t len, uint8_t out[MD5_DIGEST_LENGTH]) { MD5_CTX ctx; MD5_Init(&ctx); @@ -47,17 +55,26 @@ void MD5_Transform(MD5_CTX *c, const uint8_t data[MD5_CBLOCK]) { md5_block_data_order(c->h, data, 1); } +namespace { +struct MD5Traits { + using HashContext = MD5_CTX; + static constexpr size_t kBlockSize = MD5_CBLOCK; + static constexpr bool kLengthIsBigEndian = false; + static void HashBlocks(uint32_t *state, const uint8_t *data, + size_t num_blocks) { + md5_block_data_order(state, data, num_blocks); + } +}; +} // namespace + int MD5_Update(MD5_CTX *c, const void *data, size_t len) { - crypto_md32_update(&md5_block_data_order, c->h, c->data, MD5_CBLOCK, &c->num, - &c->Nh, &c->Nl, reinterpret_cast(data), - len); + crypto_md32_update(c, + Span(static_cast(data), len)); return 1; } int MD5_Final(uint8_t out[MD5_DIGEST_LENGTH], MD5_CTX *c) { - crypto_md32_final(&md5_block_data_order, c->h, c->data, MD5_CBLOCK, &c->num, - c->Nh, c->Nl, /*is_big_endian=*/0); - + crypto_md32_final(c); CRYPTO_store_u32_le(out, c->h[0]); CRYPTO_store_u32_le(out + 4, c->h[1]); CRYPTO_store_u32_le(out + 8, c->h[2]); diff --git a/Sources/CNIOBoringSSL/crypto/mem.cc b/Sources/CNIOBoringSSL/crypto/mem.cc index 9d02df26..adf22531 100644 --- a/Sources/CNIOBoringSSL/crypto/mem.cc +++ b/Sources/CNIOBoringSSL/crypto/mem.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -19,9 +24,7 @@ #include #if defined(OPENSSL_WINDOWS) -OPENSSL_MSVC_PRAGMA(warning(push, 3)) #include -OPENSSL_MSVC_PRAGMA(warning(pop)) #endif #if defined(BORINGSSL_MALLOC_FAILURE_TESTING) @@ -33,6 +36,8 @@ OPENSSL_MSVC_PRAGMA(warning(pop)) #include "internal.h" +using namespace bssl; + #define OPENSSL_MALLOC_PREFIX 8 static_assert(OPENSSL_MALLOC_PREFIX >= sizeof(size_t), "size_t too large"); @@ -60,27 +65,27 @@ static void __asan_unpoison_memory_region(const void *addr, size_t size) {} } #else #define WEAK_SYMBOL_FUNC(rettype, name, args) \ - static rettype(*const name) args = NULL; + static rettype(*const name) args = nullptr; #endif #if defined(BORINGSSL_DETECT_SDALLOCX) -// sdallocx is a sized |free| function. By passing the size (which we happen to +// sdallocx is a sized `free` function. By passing the size (which we happen to // always know in BoringSSL), the malloc implementation can save work. We cannot -// depend on |sdallocx| being available, however, so it's a weak symbol. +// depend on `sdallocx` being available, however, so it's a weak symbol. // -// This mechanism is kept opt-in because it assumes that, when |sdallocx| is -// defined, it is part of the same allocator as |malloc|. This is usually true -// but may break if |malloc| does not implement |sdallocx|, but some other -// allocator with |sdallocx| is imported which does. +// This mechanism is kept opt-in because it assumes that, when `sdallocx` is +// defined, it is part of the same allocator as `malloc`. This is usually true +// but may break if `malloc` does not implement `sdallocx`, but some other +// allocator with `sdallocx` is imported which does. WEAK_SYMBOL_FUNC(void, sdallocx, (void *ptr, size_t size, int flags)) #else -static void (*const sdallocx)(void *ptr, size_t size, int flags) = NULL; +static void (*const sdallocx)(void *ptr, size_t size, int flags) = nullptr; #endif // The following three functions can be defined to override default heap // allocation and freeing. If defined, it is the responsibility of -// |OPENSSL_memory_free| to zero out the memory before returning it to the -// system. |OPENSSL_memory_free| will not be passed NULL pointers. +// `OPENSSL_memory_free` to zero out the memory before returning it to the +// system. `OPENSSL_memory_free` will not be passed NULL pointers. // // WARNING: These functions are called on every allocation and free in // BoringSSL across the entire process. They may be called by any code in the @@ -100,25 +105,24 @@ WEAK_SYMBOL_FUNC(void, OPENSSL_memory_free, (void *ptr)) WEAK_SYMBOL_FUNC(size_t, OPENSSL_memory_get_size, (void *ptr)) #if defined(BORINGSSL_MALLOC_FAILURE_TESTING) -static CRYPTO_MUTEX malloc_failure_lock = CRYPTO_MUTEX_INIT; +static StaticMutex malloc_failure_lock; static uint64_t current_malloc_count = 0; static uint64_t malloc_number_to_fail = 0; static int malloc_failure_enabled = 0, break_on_malloc_fail = 0, any_malloc_failed = 0, disable_malloc_failures = 0; -static void malloc_exit_handler(void) { - CRYPTO_MUTEX_lock_read(&malloc_failure_lock); +static void malloc_exit_handler() { + MutexReadLock lock(&malloc_failure_lock); if (any_malloc_failed) { // Signal to the test driver that some allocation failed, so it knows to // increment the counter and continue. _exit(88); } - CRYPTO_MUTEX_unlock_read(&malloc_failure_lock); } -static void init_malloc_failure(void) { +static void init_malloc_failure() { const char *env = getenv("MALLOC_NUMBER_TO_FAIL"); - if (env != NULL && env[0] != 0) { + if (env != nullptr && env[0] != 0) { char *endptr; malloc_number_to_fail = strtoull(env, &endptr, 10); if (*endptr == 0) { @@ -126,7 +130,7 @@ static void init_malloc_failure(void) { atexit(malloc_exit_handler); } } - break_on_malloc_fail = getenv("MALLOC_BREAK_ON_FAIL") != NULL; + break_on_malloc_fail = getenv("MALLOC_BREAK_ON_FAIL") != nullptr; } // should_fail_allocation returns one if the current allocation should fail and @@ -140,11 +144,11 @@ static int should_fail_allocation() { // We lock just so multi-threaded tests are still correct, but we won't test // every malloc exhaustively. - CRYPTO_MUTEX_lock_write(&malloc_failure_lock); + malloc_failure_lock.LockWrite(); int should_fail = current_malloc_count == malloc_number_to_fail; current_malloc_count++; any_malloc_failed = any_malloc_failed || should_fail; - CRYPTO_MUTEX_unlock_write(&malloc_failure_lock); + malloc_failure_lock.UnlockWrite(); if (should_fail && break_on_malloc_fail) { raise(SIGTRAP); @@ -155,28 +159,25 @@ static int should_fail_allocation() { return should_fail; } -void OPENSSL_reset_malloc_counter_for_testing(void) { - CRYPTO_MUTEX_lock_write(&malloc_failure_lock); +void bssl::OPENSSL_reset_malloc_counter_for_testing() { + MutexWriteLock lock(&malloc_failure_lock); current_malloc_count = 0; - CRYPTO_MUTEX_unlock_write(&malloc_failure_lock); } -void OPENSSL_disable_malloc_failures_for_testing(void) { - CRYPTO_MUTEX_lock_write(&malloc_failure_lock); +void bssl::OPENSSL_disable_malloc_failures_for_testing() { + MutexWriteLock lock(&malloc_failure_lock); BSSL_CHECK(!disable_malloc_failures); disable_malloc_failures = 1; - CRYPTO_MUTEX_unlock_write(&malloc_failure_lock); } -void OPENSSL_enable_malloc_failures_for_testing(void) { - CRYPTO_MUTEX_lock_write(&malloc_failure_lock); +void bssl::OPENSSL_enable_malloc_failures_for_testing() { + MutexWriteLock lock(&malloc_failure_lock); BSSL_CHECK(disable_malloc_failures); disable_malloc_failures = 0; - CRYPTO_MUTEX_unlock_write(&malloc_failure_lock); } #else -static int should_fail_allocation(void) { return 0; } +static int should_fail_allocation() { return 0; } #endif void *OPENSSL_malloc(size_t size) { @@ -185,11 +186,11 @@ void *OPENSSL_malloc(size_t size) { goto err; } - if (OPENSSL_memory_alloc != NULL) { - assert(OPENSSL_memory_free != NULL); - assert(OPENSSL_memory_get_size != NULL); + if (OPENSSL_memory_alloc != nullptr) { + assert(OPENSSL_memory_free != nullptr); + assert(OPENSSL_memory_get_size != nullptr); void *ptr2 = OPENSSL_memory_alloc(size); - if (ptr2 == NULL && size != 0) { + if (ptr2 == nullptr && size != 0) { goto err; } return ptr2; @@ -200,7 +201,7 @@ void *OPENSSL_malloc(size_t size) { } ptr = malloc(size + OPENSSL_MALLOC_PREFIX); - if (ptr == NULL) { + if (ptr == nullptr) { goto err; } @@ -212,12 +213,12 @@ void *OPENSSL_malloc(size_t size) { err: // This only works because ERR does not call OPENSSL_malloc. OPENSSL_PUT_ERROR(CRYPTO, ERR_R_MALLOC_FAILURE); - return NULL; + return nullptr; } void *OPENSSL_zalloc(size_t size) { void *ret = OPENSSL_malloc(size); - if (ret != NULL) { + if (ret != nullptr) { OPENSSL_memset(ret, 0, size); } return ret; @@ -226,18 +227,18 @@ void *OPENSSL_zalloc(size_t size) { void *OPENSSL_calloc(size_t num, size_t size) { if (size != 0 && num > SIZE_MAX / size) { OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW); - return NULL; + return nullptr; } return OPENSSL_zalloc(num * size); } void OPENSSL_free(void *orig_ptr) { - if (orig_ptr == NULL) { + if (orig_ptr == nullptr) { return; } - if (OPENSSL_memory_free != NULL) { + if (OPENSSL_memory_free != nullptr) { OPENSSL_memory_free(orig_ptr); return; } @@ -262,12 +263,12 @@ void OPENSSL_free(void *orig_ptr) { } void *OPENSSL_realloc(void *orig_ptr, size_t new_size) { - if (orig_ptr == NULL) { + if (orig_ptr == nullptr) { return OPENSSL_malloc(new_size); } size_t old_size; - if (OPENSSL_memory_get_size != NULL) { + if (OPENSSL_memory_get_size != nullptr) { old_size = OPENSSL_memory_get_size(orig_ptr); } else { void *ptr = ((uint8_t *)orig_ptr) - OPENSSL_MALLOC_PREFIX; @@ -277,8 +278,8 @@ void *OPENSSL_realloc(void *orig_ptr, size_t new_size) { } void *ret = OPENSSL_malloc(new_size); - if (ret == NULL) { - return NULL; + if (ret == nullptr) { + return nullptr; } size_t to_copy = new_size; @@ -297,23 +298,20 @@ void OPENSSL_cleanse(void *ptr, size_t len) { SecureZeroMemory(ptr, len); #else OPENSSL_memset(ptr, 0, len); - -#if !defined(OPENSSL_NO_ASM) - /* As best as we can tell, this is sufficient to break any optimisations that - might try to eliminate "superfluous" memsets. If there's an easy way to - detect memset_s, it would be better to use that. */ + // As best as we can tell, this is sufficient to break any optimisations that + // might try to eliminate "superfluous" memsets. If there's an easy way to + // detect memset_s, it would be better to use that. __asm__ __volatile__("" : : "r"(ptr) : "memory"); #endif -#endif // !OPENSSL_NO_ASM } void OPENSSL_clear_free(void *ptr, size_t unused) { OPENSSL_free(ptr); } int CRYPTO_secure_malloc_init(size_t size, size_t min_size) { return 0; } -int CRYPTO_secure_malloc_initialized(void) { return 0; } +int CRYPTO_secure_malloc_initialized() { return 0; } -size_t CRYPTO_secure_used(void) { return 0; } +size_t CRYPTO_secure_used() { return 0; } void *OPENSSL_secure_malloc(size_t size) { return OPENSSL_malloc(size); } @@ -362,8 +360,8 @@ size_t OPENSSL_strnlen(const char *s, size_t len) { } char *OPENSSL_strdup(const char *s) { - if (s == NULL) { - return NULL; + if (s == nullptr) { + return nullptr; } // Copy the NUL terminator. return reinterpret_cast(OPENSSL_memdup(s, strlen(s) + 1)); @@ -453,17 +451,18 @@ int BIO_vsnprintf(char *buf, size_t n, const char *format, va_list args) { return vsnprintf(buf, n, format, args); } -int OPENSSL_vasprintf_internal(char **str, const char *format, va_list args, - int system_malloc) { +int bssl::OPENSSL_vasprintf_internal(char **str, const char *format, + va_list args, int system_malloc) { void *(*allocate)(size_t) = system_malloc ? malloc : OPENSSL_malloc; void (*deallocate)(void *) = system_malloc ? free : OPENSSL_free; void *(*reallocate)(void *, size_t) = system_malloc ? realloc : OPENSSL_realloc; - char *candidate = NULL; + char *candidate = nullptr; size_t candidate_len = 64; // TODO(bbe) what's the best initial size? int ret; - if ((candidate = reinterpret_cast(allocate(candidate_len))) == NULL) { + if ((candidate = reinterpret_cast(allocate(candidate_len))) == + nullptr) { goto err; } va_list args_copy; @@ -479,7 +478,7 @@ int OPENSSL_vasprintf_internal(char **str, const char *format, va_list args, candidate_len = (size_t)ret + 1; if ((tmp = reinterpret_cast( - reallocate(candidate, candidate_len))) == NULL) { + reallocate(candidate, candidate_len))) == nullptr) { goto err; } candidate = tmp; @@ -494,7 +493,7 @@ int OPENSSL_vasprintf_internal(char **str, const char *format, va_list args, err: deallocate(candidate); - *str = NULL; + *str = nullptr; errno = ENOMEM; return -1; } @@ -518,11 +517,11 @@ char *OPENSSL_strndup(const char *str, size_t size) { if (alloc_size < size) { // overflow OPENSSL_PUT_ERROR(CRYPTO, ERR_R_MALLOC_FAILURE); - return NULL; + return nullptr; } char *ret = reinterpret_cast(OPENSSL_malloc(alloc_size)); - if (ret == NULL) { - return NULL; + if (ret == nullptr) { + return nullptr; } OPENSSL_memcpy(ret, str, size); @@ -555,12 +554,12 @@ size_t OPENSSL_strlcat(char *dst, const char *src, size_t dst_size) { void *OPENSSL_memdup(const void *data, size_t size) { if (size == 0) { - return NULL; + return nullptr; } void *ret = OPENSSL_malloc(size); - if (ret == NULL) { - return NULL; + if (ret == nullptr) { + return nullptr; } OPENSSL_memcpy(ret, data, size); diff --git a/Sources/CNIOBoringSSL/crypto/mem_internal.h b/Sources/CNIOBoringSSL/crypto/mem_internal.h new file mode 100644 index 00000000..0146e875 --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/mem_internal.h @@ -0,0 +1,706 @@ +// Copyright 2025 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. + +#ifndef OPENSSL_HEADER_CRYPTO_MEM_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_MEM_INTERNAL_H + +#include + +#include +#include +#include +#include + +#include +#include + +#include "internal.h" + + +BSSL_NAMESPACE_BEGIN + +// Internal allocation-dependent functions. +// +// This header is separate from crypto/internal.h because there are some files +// which must avoid `OPENSSL_malloc`, to avoid a circular dependency, but +// need other support routines in crypto/internal.h. (See +// `_BORINGSSL_PROHIBIT_OPENSSL_MALLOC`.) + + +// Memory allocation. + +// New behaves like `new` but uses `OPENSSL_malloc` for memory allocation. It +// returns nullptr on allocation error. It only implements single-object +// allocation and not new T[n]. +// +// When called with no arguments, it performs value-initialization, not +// default-initialization. This means that, if it selects a non-user-provided +// constructor, the object will be zero-initialized. (As in any C++ type, once +// `T` gains a user-provided constructor, it is responsible for initializing +// all fields explicitly.) +// +// Note: unlike `new`, this does not support non-public constructors. +template +T *New(Args &&...args) { + void *t = OPENSSL_malloc(sizeof(T)); + if (t == nullptr) { + return nullptr; + } + return new (t) T(std::forward(args)...); +} + +// Delete behaves like `delete` but uses `OPENSSL_free` to release memory. +// +// Note: unlike `delete` this does not support non-public destructors. +template +void Delete(T *t) { + if (t != nullptr) { + t->~T(); + OPENSSL_free(t); + } +} + +namespace internal { + +// All types with kAllowUniquePtr set may be used with UniquePtr. Other types +// may be C structs which require a `BORINGSSL_MAKE_DELETER` registration. Where +// an internal type cannot be annotated (e.g. an alias of std::variant), use +// `BORINGSSL_MAKE_DELETER(T, Delete)`. +template +struct DeleterImpl> { + static void Free(T *t) { Delete(t); } +}; + +// All types with kAllowRefCountedUniquePtr may be used with UniquePtr, which +// then will behave like std::shared_ptr. +template +struct DeleterImpl> { + static void Free(T *t) { t->DecRefInternal(); } +}; + +} // namespace internal + +// All types with kAllowRefCountedUniquePtr types also automatically get an +// UpRef function. Other types may be C structs which require a +// `BORINGSSL_MAKE_UP_REF` registration. +template > +inline UniquePtr UpRef(const T *v) { + if (v != nullptr) { + v->UpRefInternal(); + } + return UniquePtr(const_cast(v)); +} +template > +inline UniquePtr UpRef(const UniquePtr &ptr) { + return UpRef(ptr.get()); +} + +// MakeUnique behaves like `std::make_unique` but returns nullptr on allocation +// error. +template +UniquePtr MakeUnique(Args &&...args) { + return UniquePtr(New(std::forward(args)...)); +} + + +// RefCounted is a common base for ref-counted types. This is an instance of the +// C++ curiously-recurring template pattern, so a type Foo must subclass +// RefCounted. It additionally must friend RefCounted to allow calling +// the destructor. +template +class RefCounted { + public: + static constexpr bool kAllowRefCountedUniquePtr = true; + + RefCounted(const RefCounted &) = delete; + RefCounted &operator=(const RefCounted &) = delete; + + // These methods are intentionally named differently from `bssl::UpRef` to + // avoid a collision. Only the implementations of `FOO_up_ref` and `FOO_free` + // should call these. `DecRefInternal` returns true if the object was freed + // and false if there are still references. + void UpRefInternal() const { + // Safety: the following call does not mutate anything other than the atomic + // ref-count variable. + CRYPTO_refcount_inc(&references_); + } + bool DecRefInternal() { + if (CRYPTO_refcount_dec_and_test_zero(&references_)) { + Derived *d = static_cast(this); + d->~Derived(); + OPENSSL_free(d); + return true; + } + return false; + } + + protected: + // Ensure that only `Derived`, which must inherit from `RefCounted`, + // can call the constructor. This catches bugs where someone inherited from + // the wrong base. + class CheckSubClass { + private: + friend Derived; + CheckSubClass() = default; + }; + RefCounted(CheckSubClass) { + static_assert(std::is_base_of_v, + "Derived must subclass RefCounted"); + } + + ~RefCounted() { BSSL_CHECK(references_.load() == 0); } + + private: + mutable CRYPTO_refcount_t references_ = 1; +}; + + +// Containers. + +// Array is an owning array of elements of `T`. +template +class Array { + public: + using value_type = std::remove_cv_t; + + // Array's default constructor creates an empty array. + Array() {} + Array(const Array &) = delete; + Array(Array &&other) { *this = std::move(other); } + + ~Array() { Reset(); } + + Array &operator=(const Array &) = delete; + Array &operator=(Array &&other) { + Reset(); + other.Release(&data_, &size_); + return *this; + } + + const T *data() const { return data_; } + T *data() { return data_; } + size_t size() const { return size_; } + bool empty() const { return size_ == 0; } + + const T &operator[](size_t i) const { + BSSL_CHECK(i < size_); + return data_[i]; + } + T &operator[](size_t i) { + BSSL_CHECK(i < size_); + return data_[i]; + } + + T &front() { + BSSL_CHECK(size_ != 0); + return data_[0]; + } + const T &front() const { + BSSL_CHECK(size_ != 0); + return data_[0]; + } + T &back() { + BSSL_CHECK(size_ != 0); + return data_[size_ - 1]; + } + const T &back() const { + BSSL_CHECK(size_ != 0); + return data_[size_ - 1]; + } + + T *begin() { return data_; } + const T *begin() const { return data_; } + T *end() { return data_ + size_; } + const T *end() const { return data_ + size_; } + + void Reset() { Reset(nullptr, 0); } + + // Reset releases the current contents of the array and takes ownership of the + // raw pointer supplied by the caller. + void Reset(T *new_data, size_t new_size) { + std::destroy_n(data_, size_); + OPENSSL_free(data_); + data_ = new_data; + size_ = new_size; + } + + // Release releases ownership of the array to a raw pointer supplied by the + // caller. + void Release(T **out, size_t *out_size) { + *out = data_; + *out_size = size_; + data_ = nullptr; + size_ = 0; + } + + // Init replaces the array with a newly-allocated array of `new_size` + // value-constructed copies of `T`. It returns true on success and false on + // error. If `T` is a primitive type like `uint8_t`, value-construction means + // it will be zero-initialized. + [[nodiscard]] bool Init(size_t new_size) { + if (!InitUninitialized(new_size)) { + return false; + } + std::uninitialized_value_construct_n(data_, size_); + return true; + } + + // InitForOverwrite behaves like `Init` but it default-constructs each element + // instead. This means that, if `T` is a primitive type, the array will be + // uninitialized and thus must be filled in by the caller. + [[nodiscard]] bool InitForOverwrite(size_t new_size) { + if (!InitUninitialized(new_size)) { + return false; + } + std::uninitialized_default_construct_n(data_, size_); + return true; + } + + // CopyFrom replaces the array with a newly-allocated copy of `in`. It returns + // true on success and false on error. + // + // `in` may not alias `this`. + [[nodiscard]] bool CopyFrom(Span in) { + BSSL_CHECK(!spans_alias(MakeConstSpan(*this), in)); + if (!InitUninitialized(in.size())) { + return false; + } + std::uninitialized_copy(in.begin(), in.end(), data_); + return true; + } + + // Shrink shrinks the stored size of the array to `new_size`. It crashes if + // the new size is larger. Note this does not shrink the allocation itself. + void Shrink(size_t new_size) { + if (new_size > size_) { + abort(); + } + std::destroy_n(data_ + new_size, size_ - new_size); + size_ = new_size; + } + + private: + // InitUninitialized replaces the array with a newly-allocated array of + // `new_size` elements, but whose constructor has not yet run. On success, the + // elements must be constructed before returning control to the caller. + bool InitUninitialized(size_t new_size) { + Reset(); + if (new_size == 0) { + return true; + } + + if (new_size > SIZE_MAX / sizeof(T)) { + OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW); + return false; + } + data_ = reinterpret_cast(OPENSSL_malloc(new_size * sizeof(T))); + if (data_ == nullptr) { + return false; + } + size_ = new_size; + return true; + } + + T *data_ = nullptr; + size_t size_ = 0; +}; + +// Vector is a resizable array of elements of `T`. +template +class Vector { + public: + Vector() = default; + Vector(const Vector &) = delete; + Vector(Vector &&other) { *this = std::move(other); } + ~Vector() { clear(); } + + Vector &operator=(const Vector &) = delete; + Vector &operator=(Vector &&other) { + clear(); + std::swap(data_, other.data_); + std::swap(size_, other.size_); + std::swap(capacity_, other.capacity_); + return *this; + } + + const T *data() const { return data_; } + T *data() { return data_; } + size_t size() const { return size_; } + bool empty() const { return size_ == 0; } + + const T &operator[](size_t i) const { + BSSL_CHECK(i < size_); + return data_[i]; + } + T &operator[](size_t i) { + BSSL_CHECK(i < size_); + return data_[i]; + } + + T &front() { + BSSL_CHECK(size_ != 0); + return data_[0]; + } + const T &front() const { + BSSL_CHECK(size_ != 0); + return data_[0]; + } + T &back() { + BSSL_CHECK(size_ != 0); + return data_[size_ - 1]; + } + const T &back() const { + BSSL_CHECK(size_ != 0); + return data_[size_ - 1]; + } + + T *begin() { return data_; } + const T *begin() const { return data_; } + T *end() { return data_ + size_; } + const T *end() const { return data_ + size_; } + + void clear() { + std::destroy_n(data_, size_); + OPENSSL_free(data_); + data_ = nullptr; + size_ = 0; + capacity_ = 0; + } + + void pop_back() { + BSSL_CHECK(size_ != 0); + std::destroy_at(&data_[size_ - 1]); + size_--; + } + + // Push adds `elem` at the end of the internal array, growing if necessary. It + // returns false when allocation fails. + [[nodiscard]] bool Push(T elem) { + if (!MaybeGrow(1)) { + return false; + } + new (&data_[size_]) T(std::move(elem)); + size_++; + return true; + } + + // CopyFrom replaces the contents of the array with a copy of `in`. It returns + // true on success and false on allocation error. + [[nodiscard]] bool CopyFrom(Span in) { + Array copy; + if (!copy.CopyFrom(in)) { + return false; + } + + clear(); + copy.Release(&data_, &size_); + capacity_ = size_; + return true; + } + + // Append appends the contents of `in` to the array. It returns true on + // success and false on allocation error. + [[nodiscard]] bool Append(Span in) { + if (!MaybeGrow(in.size())) { + return false; + } + std::uninitialized_copy(in.begin(), in.end(), data_ + size_); + size_ += in.size(); + return true; + } + + // AppendMove moves the contents of `in` and appends them to the array. It + // returns true on success and false on allocation error. + [[nodiscard]] bool AppendMove(Span in) { + if (!MaybeGrow(in.size())) { + return false; + } + std::uninitialized_move(in.begin(), in.end(), data_ + size_); + size_ += in.size(); + return true; + } + + // EraseIf removes all elements that satisfy the predicate `pred`. + template + void EraseIf(Pred pred) { + auto it = std::remove_if(begin(), end(), pred); + std::destroy(it, end()); + size_ = it - begin(); + } + + private: + // If there is no room for `num` elements, creates a new backing array with + // double the size of the old one and copies elements over. + [[nodiscard]] bool MaybeGrow(size_t num) { + constexpr size_t kDefaultSize = 16; + constexpr size_t kMaxCapacity = SIZE_MAX / sizeof(T); + if (num > kMaxCapacity - size_) { + OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW); + return false; + } + size_t new_capacity = size_ + num; + // No need to grow if we have room. + if (capacity_ >= new_capacity) { + return true; + } + // Always grow to at least kDefaultSize to avoid several small mallocs at + // the start. + new_capacity = std::max(new_capacity, std::min(kDefaultSize, kMaxCapacity)); + // At least double the old capacity for linear amortized behavior. + if (capacity_ <= kMaxCapacity / 2) { + new_capacity = std::max(new_capacity, capacity_ * 2); + } + T *new_data = + reinterpret_cast(OPENSSL_malloc(new_capacity * sizeof(T))); + if (new_data == nullptr) { + return false; + } + size_t new_size = size_; + std::uninitialized_move(begin(), end(), new_data); + clear(); + data_ = new_data; + size_ = new_size; + capacity_ = new_capacity; + return true; + } + + // data_ is a pointer to `capacity_` objects of size `T`, the first `size_` of + // which are constructed. + T *data_ = nullptr; + // `size_` is the number of elements stored in this Vector. + size_t size_ = 0; + // `capacity_` is the number of elements allocated in this Vector. + size_t capacity_ = 0; +}; + +// A PackedSize is an integer that can store values from 0 to N, represented as +// a minimal-width integer. +template +using PackedSize = std::conditional_t< + N <= 0xff, uint8_t, + std::conditional_t>>; + +// An InplaceVector is like a Vector, but stores up to N elements inline in the +// object. It is inspired by std::inplace_vector in C++26. +template +class InplaceVector { + public: + using value_type = std::remove_cv_t; + + InplaceVector() = default; + InplaceVector(const InplaceVector &other) { *this = other; } + InplaceVector(InplaceVector &&other) { *this = std::move(other); } + ~InplaceVector() { clear(); } + InplaceVector &operator=(const InplaceVector &other) { + if (this != &other) { + CopyFrom(other); + } + return *this; + } + InplaceVector &operator=(InplaceVector &&other) { + clear(); + std::uninitialized_move(other.begin(), other.end(), data()); + size_ = other.size(); + return *this; + } + + const T *data() const { return reinterpret_cast(storage_); } + T *data() { return reinterpret_cast(storage_); } + size_t size() const { return size_; } + static constexpr size_t capacity() { return N; } + bool empty() const { return size_ == 0; } + + const T &operator[](size_t i) const { + BSSL_CHECK(i < size_); + return data()[i]; + } + T &operator[](size_t i) { + BSSL_CHECK(i < size_); + return data()[i]; + } + + T &front() { + BSSL_CHECK(size_ != 0); + return data()[0]; + } + const T &front() const { + BSSL_CHECK(size_ != 0); + return data()[0]; + } + T &back() { + BSSL_CHECK(size_ != 0); + return data()[size_ - 1]; + } + const T &back() const { + BSSL_CHECK(size_ != 0); + return data()[size_ - 1]; + } + + T *begin() { return data(); } + const T *begin() const { return data(); } + T *end() { return data() + size_; } + const T *end() const { return data() + size_; } + + void clear() { Shrink(0); } + + void pop_back() { + BSSL_CHECK(size_ != 0); + Shrink(size_ - 1); + } + + // Shrink resizes the vector to `new_size`, which must not be larger than the + // current size. Unlike `Resize`, this can be called when `T` is not + // default-constructible. + void Shrink(size_t new_size) { + BSSL_CHECK(new_size <= size_); + std::destroy_n(data() + new_size, size_ - new_size); + size_ = static_cast>(new_size); + } + + // TryResize resizes the vector to `new_size` and returns true, or returns + // false if `new_size` is too large. Any newly-added elements are + // value-initialized. + [[nodiscard]] bool TryResize(size_t new_size) { + if (new_size <= size_) { + Shrink(new_size); + return true; + } + if (new_size > capacity()) { + return false; + } + std::uninitialized_value_construct_n(data() + size_, new_size - size_); + size_ = static_cast>(new_size); + return true; + } + + // TryResizeForOverwrite behaves like `TryResize`, but newly-added elements + // are default-initialized, so POD types may contain uninitialized values that + // the caller is responsible for filling in. + [[nodiscard]] bool TryResizeForOverwrite(size_t new_size) { + if (new_size <= size_) { + Shrink(new_size); + return true; + } + if (new_size > capacity()) { + return false; + } + std::uninitialized_default_construct_n(data() + size_, new_size - size_); + size_ = static_cast>(new_size); + return true; + } + + // TryCopyFrom sets the vector to a copy of `in` and returns true, or returns + // false if `in` is too large. + // + // `in` may not alias `this`. + [[nodiscard]] bool TryCopyFrom(Span in) { + BSSL_CHECK(!spans_alias(MakeConstSpan(*this), in)); + if (in.size() > capacity()) { + return false; + } + clear(); + std::uninitialized_copy(in.begin(), in.end(), data()); + size_ = in.size(); + return true; + } + + // TryAppend appends the vector by a copy of `in` and returns true, or + // returns false if `in` is too large. + [[nodiscard]] bool TryAppend(Span in) { + if (in.size() > capacity() - size()) { + return false; + } + std::uninitialized_copy(in.begin(), in.end(), &data()[size_]); + size_ += in.size(); + return true; + } + + // TryPushBack appends `val` to the vector and returns a pointer to the + // newly-inserted value, or nullptr if the vector is at capacity. + [[nodiscard]] T *TryPushBack(T val) { + if (size() >= capacity()) { + return nullptr; + } + T *ret = &data()[size_]; + new (ret) T(std::move(val)); + size_++; + return ret; + } + + // The following methods behave like their `Try*` counterparts, but abort the + // program on failure. + void Resize(size_t size) { BSSL_CHECK(TryResize(size)); } + void ResizeForOverwrite(size_t size) { + BSSL_CHECK(TryResizeForOverwrite(size)); + } + void CopyFrom(Span in) { BSSL_CHECK(TryCopyFrom(in)); } + void Append(Span in) { BSSL_CHECK(TryAppend(in)); } + T &PushBack(T val) { + T *ret = TryPushBack(std::move(val)); + BSSL_CHECK(ret != nullptr); + return *ret; + } + + // EraseIf removes all elements that satisfy the predicate `pred`. + template + void EraseIf(Pred pred) { + auto it = std::remove_if(begin(), end(), pred); + Shrink(it - begin()); + } + + private: + alignas(T) char storage_[sizeof(T[N])]; + PackedSize size_ = 0; +}; + +// A MaybeInplaceArray is like an `Array`, but backed by an `InplaceVector` if +// `size() <= N`, and by an `Array` if `size() > N`. +template +class MaybeInplaceArray { + public: + // CopyFrom replaces the array with a newly-allocated copy of `in`. It returns + // true on success and false on error. + // + // `in` may not alias `this`. + [[nodiscard]] bool CopyFrom(Span in) { + if (in.size() <= N) { + small_.CopyFrom(in); + large_.Reset(); + } else { + if (!large_.CopyFrom(in)) { + return false; + } + small_.clear(); + } + return true; + } + + // Minimal methods to allow conversion to a `Span`. + const T *data() const { return IsSmall() ? small_.data() : large_.data(); } + T *data() { return IsSmall() ? small_.data() : large_.data(); } + size_t size() const { return IsSmall() ? small_.size() : large_.size(); } + + private: + bool IsSmall() const { return large_.empty(); } + + // TODO(crbug.com/548222332): Optimize storage by putting this on the stack. + // Invariant: at least one of these two is empty. + Array large_; + InplaceVector small_; +}; + +BSSL_NAMESPACE_END + +#endif // OPENSSL_HEADER_CRYPTO_MEM_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/mldsa/mldsa.cc b/Sources/CNIOBoringSSL/crypto/mldsa/mldsa.cc index 56151e3a..ae27cf1e 100644 --- a/Sources/CNIOBoringSSL/crypto/mldsa/mldsa.cc +++ b/Sources/CNIOBoringSSL/crypto/mldsa/mldsa.cc @@ -1,56 +1,44 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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 "../fipsmodule/bcm_interface.h" -static_assert(sizeof(BCM_mldsa65_private_key) == sizeof(MLDSA65_private_key), - ""); -static_assert(alignof(BCM_mldsa65_private_key) == alignof(MLDSA65_private_key), - ""); -static_assert(sizeof(BCM_mldsa65_public_key) == sizeof(MLDSA65_public_key), ""); -static_assert(alignof(BCM_mldsa65_public_key) == alignof(MLDSA65_public_key), - ""); -static_assert(MLDSA_SEED_BYTES == BCM_MLDSA_SEED_BYTES, ""); -static_assert(MLDSA65_PRIVATE_KEY_BYTES == BCM_MLDSA65_PRIVATE_KEY_BYTES, ""); -static_assert(MLDSA65_PUBLIC_KEY_BYTES == BCM_MLDSA65_PUBLIC_KEY_BYTES, ""); -static_assert(MLDSA65_SIGNATURE_BYTES == BCM_MLDSA65_SIGNATURE_BYTES, ""); + +using namespace bssl; int MLDSA65_generate_key( uint8_t out_encoded_public_key[MLDSA65_PUBLIC_KEY_BYTES], uint8_t out_seed[MLDSA_SEED_BYTES], struct MLDSA65_private_key *out_private_key) { - return bcm_success(BCM_mldsa65_generate_key( - out_encoded_public_key, out_seed, - reinterpret_cast(out_private_key))); + return bcm_success(BCM_mldsa65_generate_key(out_encoded_public_key, out_seed, + out_private_key)); } int MLDSA65_private_key_from_seed(struct MLDSA65_private_key *out_private_key, const uint8_t *seed, size_t seed_len) { - if (seed_len != BCM_MLDSA_SEED_BYTES) { + if (seed_len != MLDSA_SEED_BYTES) { return 0; } - return bcm_success(BCM_mldsa65_private_key_from_seed( - reinterpret_cast(out_private_key), seed)); + return bcm_success(BCM_mldsa65_private_key_from_seed(out_private_key, seed)); } int MLDSA65_public_from_private(struct MLDSA65_public_key *out_public_key, const struct MLDSA65_private_key *private_key) { - return bcm_success(BCM_mldsa65_public_from_private( - reinterpret_cast(out_public_key), - reinterpret_cast(private_key))); + return bcm_success( + BCM_mldsa65_public_from_private(out_public_key, private_key)); } int MLDSA65_sign(uint8_t out_encoded_signature[MLDSA65_SIGNATURE_BYTES], @@ -60,31 +48,249 @@ int MLDSA65_sign(uint8_t out_encoded_signature[MLDSA65_SIGNATURE_BYTES], if (context_len > 255) { return 0; } - return bcm_success(BCM_mldsa65_sign( - out_encoded_signature, - reinterpret_cast(private_key), msg, - msg_len, context, context_len)); + return bcm_success(BCM_mldsa65_sign(out_encoded_signature, private_key, msg, + msg_len, context, context_len)); } int MLDSA65_verify(const struct MLDSA65_public_key *public_key, const uint8_t *signature, size_t signature_len, const uint8_t *msg, size_t msg_len, const uint8_t *context, size_t context_len) { - if (context_len > 255 || signature_len != BCM_MLDSA65_SIGNATURE_BYTES) { + if (context_len > 255 || signature_len != MLDSA65_SIGNATURE_BYTES) { return 0; } - return bcm_success(BCM_mldsa65_verify( - reinterpret_cast(public_key), signature, - msg, msg_len, context, context_len)); + return bcm_success(BCM_mldsa65_verify(public_key, signature, msg, msg_len, + context, context_len)); +} + +int MLDSA65_prehash_init(struct MLDSA65_prehash *out_state, + const struct MLDSA65_public_key *public_key, + const uint8_t *context, size_t context_len) { + if (context_len > 255) { + return 0; + } + BCM_mldsa65_prehash_init(out_state, public_key, context, context_len); + return 1; +} + +void MLDSA65_prehash_update(struct MLDSA65_prehash *inout_state, + const uint8_t *msg, size_t msg_len) { + BCM_mldsa65_prehash_update(inout_state, msg, msg_len); +} + +void MLDSA65_prehash_finalize(uint8_t out_msg_rep[MLDSA_MU_BYTES], + struct MLDSA65_prehash *inout_state) { + BCM_mldsa65_prehash_finalize(out_msg_rep, inout_state); +} + +int MLDSA65_sign_message_representative( + uint8_t out_encoded_signature[MLDSA65_SIGNATURE_BYTES], + const struct MLDSA65_private_key *private_key, + const uint8_t msg_rep[MLDSA_MU_BYTES]) { + return bcm_success(BCM_mldsa65_sign_message_representative( + out_encoded_signature, private_key, msg_rep)); +} + +int MLDSA65_verify_message_representative( + const struct MLDSA65_public_key *public_key, + const uint8_t *signature, size_t signature_len, + const uint8_t msg_rep[MLDSA_MU_BYTES]) { + if (signature_len != MLDSA65_SIGNATURE_BYTES) { + return 0; + } + return bcm_success(BCM_mldsa65_verify_message_representative( + public_key, signature, msg_rep)); } int MLDSA65_marshal_public_key(CBB *out, const struct MLDSA65_public_key *public_key) { - return bcm_success(BCM_mldsa65_marshal_public_key( - out, reinterpret_cast(public_key))); + return bcm_success(BCM_mldsa65_marshal_public_key(out, public_key)); } int MLDSA65_parse_public_key(struct MLDSA65_public_key *public_key, CBS *in) { - return bcm_success(BCM_mldsa65_parse_public_key( - reinterpret_cast(public_key), in)); + return bcm_success(BCM_mldsa65_parse_public_key(public_key, in)); +} + +int MLDSA87_generate_key( + uint8_t out_encoded_public_key[MLDSA87_PUBLIC_KEY_BYTES], + uint8_t out_seed[MLDSA_SEED_BYTES], + struct MLDSA87_private_key *out_private_key) { + return bcm_success(BCM_mldsa87_generate_key(out_encoded_public_key, out_seed, + out_private_key)); +} + +int MLDSA87_private_key_from_seed(struct MLDSA87_private_key *out_private_key, + const uint8_t *seed, size_t seed_len) { + if (seed_len != MLDSA_SEED_BYTES) { + return 0; + } + return bcm_success(BCM_mldsa87_private_key_from_seed(out_private_key, seed)); +} + +int MLDSA87_public_from_private(struct MLDSA87_public_key *out_public_key, + const struct MLDSA87_private_key *private_key) { + return bcm_success( + BCM_mldsa87_public_from_private(out_public_key, private_key)); +} + +int MLDSA87_sign(uint8_t out_encoded_signature[MLDSA87_SIGNATURE_BYTES], + const struct MLDSA87_private_key *private_key, + const uint8_t *msg, size_t msg_len, const uint8_t *context, + size_t context_len) { + if (context_len > 255) { + return 0; + } + return bcm_success(BCM_mldsa87_sign(out_encoded_signature, private_key, msg, + msg_len, context, context_len)); +} + +int MLDSA87_verify(const struct MLDSA87_public_key *public_key, + const uint8_t *signature, size_t signature_len, + const uint8_t *msg, size_t msg_len, const uint8_t *context, + size_t context_len) { + if (context_len > 255 || signature_len != MLDSA87_SIGNATURE_BYTES) { + return 0; + } + return bcm_success(BCM_mldsa87_verify(public_key, signature, msg, msg_len, + context, context_len)); +} + +int MLDSA87_prehash_init(struct MLDSA87_prehash *out_state, + const struct MLDSA87_public_key *public_key, + const uint8_t *context, size_t context_len) { + if (context_len > 255) { + return 0; + } + BCM_mldsa87_prehash_init(out_state, public_key, context, context_len); + return 1; +} + +void MLDSA87_prehash_update(struct MLDSA87_prehash *inout_state, + const uint8_t *msg, size_t msg_len) { + BCM_mldsa87_prehash_update(inout_state, msg, msg_len); +} + +void MLDSA87_prehash_finalize(uint8_t out_msg_rep[MLDSA_MU_BYTES], + struct MLDSA87_prehash *inout_state) { + BCM_mldsa87_prehash_finalize(out_msg_rep, inout_state); +} + +int MLDSA87_sign_message_representative( + uint8_t out_encoded_signature[MLDSA87_SIGNATURE_BYTES], + const struct MLDSA87_private_key *private_key, + const uint8_t msg_rep[MLDSA_MU_BYTES]) { + return bcm_success(BCM_mldsa87_sign_message_representative( + out_encoded_signature, private_key, msg_rep)); +} + +int MLDSA87_verify_message_representative( + const struct MLDSA87_public_key *public_key, + const uint8_t *signature, size_t signature_len, + const uint8_t msg_rep[MLDSA_MU_BYTES]) { + if (signature_len != MLDSA87_SIGNATURE_BYTES) { + return 0; + } + return bcm_success(BCM_mldsa87_verify_message_representative( + public_key, signature, msg_rep)); +} + +int MLDSA87_marshal_public_key(CBB *out, + const struct MLDSA87_public_key *public_key) { + return bcm_success(BCM_mldsa87_marshal_public_key(out, public_key)); +} + +int MLDSA87_parse_public_key(struct MLDSA87_public_key *public_key, CBS *in) { + return bcm_success(BCM_mldsa87_parse_public_key(public_key, in)); +} + +int MLDSA44_generate_key( + uint8_t out_encoded_public_key[MLDSA44_PUBLIC_KEY_BYTES], + uint8_t out_seed[MLDSA_SEED_BYTES], + struct MLDSA44_private_key *out_private_key) { + return bcm_success(BCM_mldsa44_generate_key(out_encoded_public_key, out_seed, + out_private_key)); +} + +int MLDSA44_private_key_from_seed(struct MLDSA44_private_key *out_private_key, + const uint8_t *seed, size_t seed_len) { + if (seed_len != MLDSA_SEED_BYTES) { + return 0; + } + return bcm_success(BCM_mldsa44_private_key_from_seed(out_private_key, seed)); +} + +int MLDSA44_public_from_private(struct MLDSA44_public_key *out_public_key, + const struct MLDSA44_private_key *private_key) { + return bcm_success( + BCM_mldsa44_public_from_private(out_public_key, private_key)); +} + +int MLDSA44_sign(uint8_t out_encoded_signature[MLDSA44_SIGNATURE_BYTES], + const struct MLDSA44_private_key *private_key, + const uint8_t *msg, size_t msg_len, const uint8_t *context, + size_t context_len) { + if (context_len > 255) { + return 0; + } + return bcm_success(BCM_mldsa44_sign(out_encoded_signature, private_key, msg, + msg_len, context, context_len)); +} + +int MLDSA44_verify(const struct MLDSA44_public_key *public_key, + const uint8_t *signature, size_t signature_len, + const uint8_t *msg, size_t msg_len, const uint8_t *context, + size_t context_len) { + if (context_len > 255 || signature_len != MLDSA44_SIGNATURE_BYTES) { + return 0; + } + return bcm_success(BCM_mldsa44_verify(public_key, signature, msg, msg_len, + context, context_len)); +} + +int MLDSA44_prehash_init(struct MLDSA44_prehash *out_state, + const struct MLDSA44_public_key *public_key, + const uint8_t *context, size_t context_len) { + if (context_len > 255) { + return 0; + } + BCM_mldsa44_prehash_init(out_state, public_key, context, context_len); + return 1; +} + +void MLDSA44_prehash_update(struct MLDSA44_prehash *inout_state, + const uint8_t *msg, size_t msg_len) { + BCM_mldsa44_prehash_update(inout_state, msg, msg_len); +} + +void MLDSA44_prehash_finalize(uint8_t out_msg_rep[MLDSA_MU_BYTES], + struct MLDSA44_prehash *inout_state) { + BCM_mldsa44_prehash_finalize(out_msg_rep, inout_state); +} + +int MLDSA44_sign_message_representative( + uint8_t out_encoded_signature[MLDSA44_SIGNATURE_BYTES], + const struct MLDSA44_private_key *private_key, + const uint8_t msg_rep[MLDSA_MU_BYTES]) { + return bcm_success(BCM_mldsa44_sign_message_representative( + out_encoded_signature, private_key, msg_rep)); +} + +int MLDSA44_verify_message_representative( + const struct MLDSA44_public_key *public_key, + const uint8_t *signature, size_t signature_len, + const uint8_t msg_rep[MLDSA_MU_BYTES]) { + if (signature_len != MLDSA44_SIGNATURE_BYTES) { + return 0; + } + return bcm_success(BCM_mldsa44_verify_message_representative( + public_key, signature, msg_rep)); +} + +int MLDSA44_marshal_public_key(CBB *out, + const struct MLDSA44_public_key *public_key) { + return bcm_success(BCM_mldsa44_marshal_public_key(out, public_key)); +} + +int MLDSA44_parse_public_key(struct MLDSA44_public_key *public_key, CBS *in) { + return bcm_success(BCM_mldsa44_parse_public_key(public_key, in)); } diff --git a/Sources/CNIOBoringSSL/crypto/mlkem/mlkem.cc b/Sources/CNIOBoringSSL/crypto/mlkem/mlkem.cc index 699389d3..e764a9d1 100644 --- a/Sources/CNIOBoringSSL/crypto/mlkem/mlkem.cc +++ b/Sources/CNIOBoringSSL/crypto/mlkem/mlkem.cc @@ -1,152 +1,108 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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 "../fipsmodule/bcm_interface.h" -static_assert(sizeof(BCM_mlkem768_private_key) <= sizeof(MLKEM768_private_key), - ""); -static_assert(alignof(BCM_mlkem768_private_key) <= - alignof(MLKEM768_private_key), - ""); -static_assert(sizeof(BCM_mlkem768_public_key) <= sizeof(MLKEM768_public_key), - ""); -static_assert(alignof(BCM_mlkem768_public_key) <= alignof(MLKEM768_public_key), - ""); -static_assert(MLKEM768_PUBLIC_KEY_BYTES == BCM_MLKEM768_PUBLIC_KEY_BYTES, ""); -static_assert(MLKEM_SEED_BYTES == BCM_MLKEM_SEED_BYTES, ""); -static_assert(MLKEM768_CIPHERTEXT_BYTES == BCM_MLKEM768_CIPHERTEXT_BYTES, ""); -static_assert(MLKEM_SHARED_SECRET_BYTES == BCM_MLKEM_SHARED_SECRET_BYTES, ""); -static_assert(MLKEM1024_PUBLIC_KEY_BYTES == BCM_MLKEM1024_PUBLIC_KEY_BYTES, ""); -static_assert(MLKEM1024_CIPHERTEXT_BYTES == BCM_MLKEM1024_CIPHERTEXT_BYTES, ""); +using namespace bssl; void MLKEM768_generate_key( uint8_t out_encoded_public_key[MLKEM768_PUBLIC_KEY_BYTES], uint8_t optional_out_seed[MLKEM_SEED_BYTES], struct MLKEM768_private_key *out_private_key) { - BCM_mlkem768_generate_key( - out_encoded_public_key, optional_out_seed, - reinterpret_cast(out_private_key)); + BCM_mlkem768_generate_key(out_encoded_public_key, optional_out_seed, + out_private_key); } int MLKEM768_private_key_from_seed(struct MLKEM768_private_key *out_private_key, const uint8_t *seed, size_t seed_len) { - return bcm_success(BCM_mlkem768_private_key_from_seed( - reinterpret_cast(out_private_key), seed, - seed_len)); + return bcm_success( + BCM_mlkem768_private_key_from_seed(out_private_key, seed, seed_len)); } void MLKEM768_public_from_private( struct MLKEM768_public_key *out_public_key, const struct MLKEM768_private_key *private_key) { - (void)BCM_mlkem768_public_from_private( - reinterpret_cast(out_public_key), - reinterpret_cast(private_key)); + (void)BCM_mlkem768_public_from_private(out_public_key, private_key); } void MLKEM768_encap(uint8_t out_ciphertext[MLKEM768_CIPHERTEXT_BYTES], uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], const struct MLKEM768_public_key *public_key) { - (void)BCM_mlkem768_encap( - out_ciphertext, out_shared_secret, - reinterpret_cast(public_key)); + (void)BCM_mlkem768_encap(out_ciphertext, out_shared_secret, public_key); } int MLKEM768_decap(uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], const uint8_t *ciphertext, size_t ciphertext_len, const struct MLKEM768_private_key *private_key) { - return bcm_success(BCM_mlkem768_decap( - out_shared_secret, ciphertext, ciphertext_len, - reinterpret_cast(private_key))); + return bcm_success(BCM_mlkem768_decap(out_shared_secret, ciphertext, + ciphertext_len, private_key)); } int MLKEM768_marshal_public_key(CBB *out, const struct MLKEM768_public_key *public_key) { - return bcm_success(BCM_mlkem768_marshal_public_key( - out, reinterpret_cast(public_key))); + return bcm_success(BCM_mlkem768_marshal_public_key(out, public_key)); } int MLKEM768_parse_public_key(struct MLKEM768_public_key *out_public_key, CBS *in) { - return bcm_success(BCM_mlkem768_parse_public_key( - reinterpret_cast(out_public_key), in)); + return bcm_success(BCM_mlkem768_parse_public_key(out_public_key, in)); } -static_assert(sizeof(BCM_mlkem1024_private_key) <= - sizeof(MLKEM1024_private_key), - ""); -static_assert(alignof(BCM_mlkem1024_private_key) <= - alignof(MLKEM1024_private_key), - ""); -static_assert(sizeof(BCM_mlkem1024_public_key) <= sizeof(MLKEM1024_public_key), - ""); -static_assert(alignof(BCM_mlkem1024_public_key) <= - alignof(MLKEM1024_public_key), - ""); - void MLKEM1024_generate_key( uint8_t out_encoded_public_key[MLKEM1024_PUBLIC_KEY_BYTES], uint8_t optional_out_seed[MLKEM_SEED_BYTES], struct MLKEM1024_private_key *out_private_key) { - (void)BCM_mlkem1024_generate_key( - out_encoded_public_key, optional_out_seed, - reinterpret_cast(out_private_key)); + (void)BCM_mlkem1024_generate_key(out_encoded_public_key, optional_out_seed, + out_private_key); } int MLKEM1024_private_key_from_seed( struct MLKEM1024_private_key *out_private_key, const uint8_t *seed, size_t seed_len) { - return bcm_success(BCM_mlkem1024_private_key_from_seed( - reinterpret_cast(out_private_key), seed, - seed_len)); + return bcm_success( + BCM_mlkem1024_private_key_from_seed(out_private_key, seed, seed_len)); } void MLKEM1024_public_from_private( struct MLKEM1024_public_key *out_public_key, const struct MLKEM1024_private_key *private_key) { - (void)BCM_mlkem1024_public_from_private( - reinterpret_cast(out_public_key), - reinterpret_cast(private_key)); + (void)BCM_mlkem1024_public_from_private(out_public_key, private_key); } void MLKEM1024_encap(uint8_t out_ciphertext[MLKEM1024_CIPHERTEXT_BYTES], uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], const struct MLKEM1024_public_key *public_key) { - (void)BCM_mlkem1024_encap( - out_ciphertext, out_shared_secret, - reinterpret_cast(public_key)); + (void)BCM_mlkem1024_encap(out_ciphertext, out_shared_secret, public_key); } int MLKEM1024_decap(uint8_t out_shared_secret[MLKEM_SHARED_SECRET_BYTES], const uint8_t *ciphertext, size_t ciphertext_len, const struct MLKEM1024_private_key *private_key) { - return bcm_success(BCM_mlkem1024_decap( - out_shared_secret, ciphertext, ciphertext_len, - reinterpret_cast(private_key))); + return bcm_success(BCM_mlkem1024_decap(out_shared_secret, ciphertext, + ciphertext_len, private_key)); } int MLKEM1024_marshal_public_key( CBB *out, const struct MLKEM1024_public_key *public_key) { - return bcm_success(BCM_mlkem1024_marshal_public_key( - out, reinterpret_cast(public_key))); + return bcm_success(BCM_mlkem1024_marshal_public_key(out, public_key)); } int MLKEM1024_parse_public_key(struct MLKEM1024_public_key *out_public_key, CBS *in) { - return bcm_success(BCM_mlkem1024_parse_public_key( - reinterpret_cast(out_public_key), in)); + return bcm_success(BCM_mlkem1024_parse_public_key(out_public_key, in)); } diff --git a/Sources/CNIOBoringSSL/crypto/obj/obj.cc b/Sources/CNIOBoringSSL/crypto/obj/obj.cc index 72c04469..6eecaa14 100644 --- a/Sources/CNIOBoringSSL/crypto/obj/obj.cc +++ b/Sources/CNIOBoringSSL/crypto/obj/obj.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -13,98 +18,87 @@ #include #include +#include + #include #include #include -#include #include -#include #include "../asn1/internal.h" #include "../internal.h" #include "../lhash/internal.h" -// obj_data.h must be included after the definition of |ASN1_OBJECT|. +// obj_data.h must be included after the definition of `ASN1_OBJECT`. #include "obj_dat.h" +using namespace bssl; + +BSSL_NAMESPACE_BEGIN + DEFINE_LHASH_OF(ASN1_OBJECT) -static CRYPTO_MUTEX global_added_lock = CRYPTO_MUTEX_INIT; -// These globals are protected by |global_added_lock|. -static LHASH_OF(ASN1_OBJECT) *global_added_by_data = NULL; -static LHASH_OF(ASN1_OBJECT) *global_added_by_nid = NULL; -static LHASH_OF(ASN1_OBJECT) *global_added_by_short_name = NULL; -static LHASH_OF(ASN1_OBJECT) *global_added_by_long_name = NULL; +BSSL_NAMESPACE_END -static CRYPTO_MUTEX global_next_nid_lock = CRYPTO_MUTEX_INIT; +static StaticMutex global_added_lock; +// These globals are protected by `global_added_lock`. +static LHASH_OF(ASN1_OBJECT) *global_added_by_data = nullptr; +static LHASH_OF(ASN1_OBJECT) *global_added_by_nid = nullptr; +static LHASH_OF(ASN1_OBJECT) *global_added_by_short_name = nullptr; +static LHASH_OF(ASN1_OBJECT) *global_added_by_long_name = nullptr; + +static StaticMutex global_next_nid_lock; static unsigned global_next_nid = NUM_NID; -static int obj_next_nid(void) { - CRYPTO_MUTEX_lock_write(&global_next_nid_lock); - int ret = global_next_nid++; - CRYPTO_MUTEX_unlock_write(&global_next_nid_lock); - return ret; +static int obj_next_nid() { + MutexWriteLock lock(&global_next_nid_lock); + return global_next_nid++; } ASN1_OBJECT *OBJ_dup(const ASN1_OBJECT *o) { - ASN1_OBJECT *r; - unsigned char *data = NULL; - char *sn = NULL, *ln = NULL; - - if (o == NULL) { - return NULL; + if (o == nullptr) { + return nullptr; } if (!(o->flags & ASN1_OBJECT_FLAG_DYNAMIC)) { // TODO(fork): this is a little dangerous. - return (ASN1_OBJECT *)o; + return const_cast(o); } - r = ASN1_OBJECT_new(); - if (r == NULL) { + UniquePtr r(ASN1_OBJECT_new()); + if (r == nullptr) { OPENSSL_PUT_ERROR(OBJ, ERR_R_ASN1_LIB); - return NULL; + return nullptr; } - r->ln = r->sn = NULL; - // once data is attached to an object, it remains const + // All fields of the object will be allocated. + r->flags = o->flags | ASN1_OBJECT_FLAG_DYNAMIC | + ASN1_OBJECT_FLAG_DYNAMIC_STRINGS | ASN1_OBJECT_FLAG_DYNAMIC_DATA; + r->data = reinterpret_cast(OPENSSL_memdup(o->data, o->length)); - if (o->length != 0 && r->data == NULL) { - goto err; + if (o->length != 0 && r->data == nullptr) { + return nullptr; } r->length = o->length; r->nid = o->nid; - if (o->ln != NULL) { - ln = OPENSSL_strdup(o->ln); - if (ln == NULL) { - goto err; + if (o->ln != nullptr) { + r->ln = OPENSSL_strdup(o->ln); + if (r->ln == nullptr) { + return nullptr; } } - if (o->sn != NULL) { - sn = OPENSSL_strdup(o->sn); - if (sn == NULL) { - goto err; + if (o->sn != nullptr) { + r->sn = OPENSSL_strdup(o->sn); + if (r->sn == nullptr) { + return nullptr; } } - r->sn = sn; - r->ln = ln; - - r->flags = - o->flags | (ASN1_OBJECT_FLAG_DYNAMIC | ASN1_OBJECT_FLAG_DYNAMIC_STRINGS | - ASN1_OBJECT_FLAG_DYNAMIC_DATA); - return r; - -err: - OPENSSL_free(ln); - OPENSSL_free(sn); - OPENSSL_free(data); - OPENSSL_free(r); - return NULL; + return r.release(); } int OBJ_cmp(const ASN1_OBJECT *a, const ASN1_OBJECT *b) { @@ -117,15 +111,15 @@ int OBJ_cmp(const ASN1_OBJECT *a, const ASN1_OBJECT *b) { } const uint8_t *OBJ_get0_data(const ASN1_OBJECT *obj) { - if (obj == NULL) { - return NULL; + if (obj == nullptr) { + return nullptr; } return obj->data; } size_t OBJ_length(const ASN1_OBJECT *obj) { - if (obj == NULL || obj->length < 0) { + if (obj == nullptr || obj->length < 0) { return 0; } @@ -133,14 +127,14 @@ size_t OBJ_length(const ASN1_OBJECT *obj) { } static const ASN1_OBJECT *get_builtin_object(int nid) { - // |NID_undef| is stored separately, so all the indices are off by one. The + // `NID_undef` is stored separately, so all the indices are off by one. The // caller of this function must have a valid built-in, non-undef NID. BSSL_CHECK(nid > 0 && nid < NUM_NID); return &kObjects[nid - 1]; } -// obj_cmp is called to search the kNIDsInOIDOrder array. The |key| argument is -// an |ASN1_OBJECT|* that we're looking for and |element| is a pointer to an +// obj_cmp is called to search the kNIDsInOIDOrder array. The `key` argument is +// an `ASN1_OBJECT`* that we're looking for and `element` is a pointer to an // unsigned int in the array. static int obj_cmp(const void *key, const void *element) { uint16_t nid = *((const uint16_t *)element); @@ -149,7 +143,7 @@ static int obj_cmp(const void *key, const void *element) { } int OBJ_obj2nid(const ASN1_OBJECT *obj) { - if (obj == NULL) { + if (obj == nullptr) { return NID_undef; } @@ -157,22 +151,20 @@ int OBJ_obj2nid(const ASN1_OBJECT *obj) { return obj->nid; } - CRYPTO_MUTEX_lock_read(&global_added_lock); - if (global_added_by_data != NULL) { - ASN1_OBJECT *match; - - match = lh_ASN1_OBJECT_retrieve(global_added_by_data, obj); - if (match != NULL) { - CRYPTO_MUTEX_unlock_read(&global_added_lock); - return match->nid; + { + MutexReadLock lock(&global_added_lock); + if (global_added_by_data != nullptr) { + ASN1_OBJECT *match = lh_ASN1_OBJECT_retrieve(global_added_by_data, obj); + if (match != nullptr) { + return match->nid; + } } } - CRYPTO_MUTEX_unlock_read(&global_added_lock); const uint16_t *nid_ptr = reinterpret_cast( - bsearch(obj, kNIDsInOIDOrder, OPENSSL_ARRAY_SIZE(kNIDsInOIDOrder), + bsearch(obj, kNIDsInOIDOrder, std::size(kNIDsInOIDOrder), sizeof(kNIDsInOIDOrder[0]), obj_cmp)); - if (nid_ptr == NULL) { + if (nid_ptr == nullptr) { return NID_undef; } @@ -193,7 +185,7 @@ int OBJ_cbs2nid(const CBS *cbs) { } // short_name_cmp is called to search the kNIDsInShortNameOrder array. The -// |key| argument is name that we're looking for and |element| is a pointer to +// `key` argument is name that we're looking for and `element` is a pointer to // an unsigned int in the array. static int short_name_cmp(const void *key, const void *element) { const char *name = (const char *)key; @@ -203,24 +195,23 @@ static int short_name_cmp(const void *key, const void *element) { } int OBJ_sn2nid(const char *short_name) { - CRYPTO_MUTEX_lock_read(&global_added_lock); - if (global_added_by_short_name != NULL) { - ASN1_OBJECT *match, templ; - - templ.sn = short_name; - match = lh_ASN1_OBJECT_retrieve(global_added_by_short_name, &templ); - if (match != NULL) { - CRYPTO_MUTEX_unlock_read(&global_added_lock); - return match->nid; + { + MutexReadLock lock(&global_added_lock); + if (global_added_by_short_name != nullptr) { + ASN1_OBJECT templ; + templ.sn = short_name; + ASN1_OBJECT *match = + lh_ASN1_OBJECT_retrieve(global_added_by_short_name, &templ); + if (match != nullptr) { + return match->nid; + } } } - CRYPTO_MUTEX_unlock_read(&global_added_lock); - const uint16_t *nid_ptr = reinterpret_cast( - bsearch(short_name, kNIDsInShortNameOrder, - OPENSSL_ARRAY_SIZE(kNIDsInShortNameOrder), - sizeof(kNIDsInShortNameOrder[0]), short_name_cmp)); - if (nid_ptr == NULL) { + const uint16_t *nid_ptr = reinterpret_cast(bsearch( + short_name, kNIDsInShortNameOrder, std::size(kNIDsInShortNameOrder), + sizeof(kNIDsInShortNameOrder[0]), short_name_cmp)); + if (nid_ptr == nullptr) { return NID_undef; } @@ -228,7 +219,7 @@ int OBJ_sn2nid(const char *short_name) { } // long_name_cmp is called to search the kNIDsInLongNameOrder array. The -// |key| argument is name that we're looking for and |element| is a pointer to +// `key` argument is name that we're looking for and `element` is a pointer to // an unsigned int in the array. static int long_name_cmp(const void *key, const void *element) { const char *name = (const char *)key; @@ -238,23 +229,23 @@ static int long_name_cmp(const void *key, const void *element) { } int OBJ_ln2nid(const char *long_name) { - CRYPTO_MUTEX_lock_read(&global_added_lock); - if (global_added_by_long_name != NULL) { - ASN1_OBJECT *match, templ; - - templ.ln = long_name; - match = lh_ASN1_OBJECT_retrieve(global_added_by_long_name, &templ); - if (match != NULL) { - CRYPTO_MUTEX_unlock_read(&global_added_lock); - return match->nid; + { + MutexReadLock lock(&global_added_lock); + if (global_added_by_long_name != nullptr) { + ASN1_OBJECT templ; + templ.ln = long_name; + ASN1_OBJECT *match = + lh_ASN1_OBJECT_retrieve(global_added_by_long_name, &templ); + if (match != nullptr) { + return match->nid; + } } } - CRYPTO_MUTEX_unlock_read(&global_added_lock); - const uint16_t *nid_ptr = reinterpret_cast(bsearch( - long_name, kNIDsInLongNameOrder, OPENSSL_ARRAY_SIZE(kNIDsInLongNameOrder), - sizeof(kNIDsInLongNameOrder[0]), long_name_cmp)); - if (nid_ptr == NULL) { + const uint16_t *nid_ptr = reinterpret_cast( + bsearch(long_name, kNIDsInLongNameOrder, std::size(kNIDsInLongNameOrder), + sizeof(kNIDsInLongNameOrder[0]), long_name_cmp)); + if (nid_ptr == nullptr) { return NID_undef; } @@ -273,23 +264,17 @@ int OBJ_txt2nid(const char *s) { OPENSSL_EXPORT int OBJ_nid2cbb(CBB *out, int nid) { const ASN1_OBJECT *obj = OBJ_nid2obj(nid); - CBB oid; - - if (obj == NULL || !CBB_add_asn1(out, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, obj->data, obj->length) || !CBB_flush(out)) { - return 0; - } - - return 1; + return obj != nullptr && + CBB_add_asn1_element(out, CBS_ASN1_OBJECT, obj->data, obj->length); } -const ASN1_OBJECT *OBJ_get_undef(void) { +const ASN1_OBJECT *OBJ_get_undef() { static const ASN1_OBJECT kUndef = { /*sn=*/SN_undef, /*ln=*/LN_undef, /*nid=*/NID_undef, /*length=*/0, - /*data=*/NULL, + /*data=*/nullptr, /*flags=*/0, }; return &kUndef; @@ -303,33 +288,32 @@ ASN1_OBJECT *OBJ_nid2obj(int nid) { if (nid > 0 && nid < NUM_NID) { const ASN1_OBJECT *obj = get_builtin_object(nid); if (nid != NID_undef && obj->nid == NID_undef) { - goto err; + OPENSSL_PUT_ERROR(OBJ, OBJ_R_UNKNOWN_NID); + return nullptr; } return (ASN1_OBJECT *)obj; } - CRYPTO_MUTEX_lock_read(&global_added_lock); - if (global_added_by_nid != NULL) { - ASN1_OBJECT *match, templ; - - templ.nid = nid; - match = lh_ASN1_OBJECT_retrieve(global_added_by_nid, &templ); - if (match != NULL) { - CRYPTO_MUTEX_unlock_read(&global_added_lock); - return match; + { + MutexReadLock lock(&global_added_lock); + if (global_added_by_nid != nullptr) { + ASN1_OBJECT templ; + templ.nid = nid; + ASN1_OBJECT *match = lh_ASN1_OBJECT_retrieve(global_added_by_nid, &templ); + if (match != nullptr) { + return match; + } } } - CRYPTO_MUTEX_unlock_read(&global_added_lock); -err: OPENSSL_PUT_ERROR(OBJ, OBJ_R_UNKNOWN_NID); - return NULL; + return nullptr; } const char *OBJ_nid2sn(int nid) { const ASN1_OBJECT *obj = OBJ_nid2obj(nid); - if (obj == NULL) { - return NULL; + if (obj == nullptr) { + return nullptr; } return obj->sn; @@ -337,14 +321,14 @@ const char *OBJ_nid2sn(int nid) { const char *OBJ_nid2ln(int nid) { const ASN1_OBJECT *obj = OBJ_nid2obj(nid); - if (obj == NULL) { - return NULL; + if (obj == nullptr) { + return nullptr; } return obj->ln; } -static ASN1_OBJECT *create_object_with_text_oid(int (*get_nid)(void), +static ASN1_OBJECT *create_object_with_text_oid(int (*get_nid)(), const char *oid, const char *short_name, const char *long_name) { @@ -356,7 +340,7 @@ static ASN1_OBJECT *create_object_with_text_oid(int (*get_nid)(void), !CBB_finish(&cbb, &buf, &len)) { OPENSSL_PUT_ERROR(OBJ, OBJ_R_INVALID_OID_STRING); CBB_cleanup(&cbb); - return NULL; + return nullptr; } ASN1_OBJECT *ret = ASN1_OBJECT_create(get_nid ? get_nid() : NID_undef, buf, @@ -377,7 +361,7 @@ ASN1_OBJECT *OBJ_txt2obj(const char *s, int dont_search_names) { } } - return create_object_with_text_oid(NULL, s, NULL, NULL); + return create_object_with_text_oid(nullptr, s, nullptr, nullptr); } static int strlcpy_int(char *dst, const char *src, int dst_size) { @@ -393,7 +377,7 @@ int OBJ_obj2txt(char *out, int out_len, const ASN1_OBJECT *obj, int always_return_oid) { // Python depends on the empty OID successfully encoding as the empty // string. - if (obj == NULL || obj->length == 0) { + if (obj == nullptr || obj->length == 0) { return strlcpy_int(out, "", out_len); } @@ -401,10 +385,10 @@ int OBJ_obj2txt(char *out, int out_len, const ASN1_OBJECT *obj, int nid = OBJ_obj2nid(obj); if (nid != NID_undef) { const char *name = OBJ_nid2ln(nid); - if (name == NULL) { + if (name == nullptr) { name = OBJ_nid2sn(nid); } - if (name != NULL) { + if (name != nullptr) { return strlcpy_int(out, name, out_len); } } @@ -413,7 +397,7 @@ int OBJ_obj2txt(char *out, int out_len, const ASN1_OBJECT *obj, CBS cbs; CBS_init(&cbs, obj->data, obj->length); char *txt = CBS_asn1_oid_to_text(&cbs); - if (txt == NULL) { + if (txt == nullptr) { if (out_len > 0) { out[0] = '\0'; } @@ -451,64 +435,60 @@ static int cmp_long_name(const ASN1_OBJECT *a, const ASN1_OBJECT *b) { return strcmp(a->ln, b->ln); } -// obj_add_object inserts |obj| into the various global hashes for run-time +// obj_add_object inserts `obj` into the various global hashes for run-time // added objects. It returns one on success or zero otherwise. static int obj_add_object(ASN1_OBJECT *obj) { obj->flags &= ~(ASN1_OBJECT_FLAG_DYNAMIC | ASN1_OBJECT_FLAG_DYNAMIC_STRINGS | ASN1_OBJECT_FLAG_DYNAMIC_DATA); - CRYPTO_MUTEX_lock_write(&global_added_lock); - if (global_added_by_nid == NULL) { + MutexWriteLock lock(&global_added_lock); + if (global_added_by_nid == nullptr) { global_added_by_nid = lh_ASN1_OBJECT_new(hash_nid, cmp_nid); } - if (global_added_by_data == NULL) { + if (global_added_by_data == nullptr) { global_added_by_data = lh_ASN1_OBJECT_new(hash_data, OBJ_cmp); } - if (global_added_by_short_name == NULL) { + if (global_added_by_short_name == nullptr) { global_added_by_short_name = lh_ASN1_OBJECT_new(hash_short_name, cmp_short_name); } - if (global_added_by_long_name == NULL) { + if (global_added_by_long_name == nullptr) { global_added_by_long_name = lh_ASN1_OBJECT_new(hash_long_name, cmp_long_name); } - int ok = 0; - if (global_added_by_nid == NULL || // - global_added_by_data == NULL || // - global_added_by_short_name == NULL || // - global_added_by_long_name == NULL) { - goto err; + if (global_added_by_nid == nullptr || // + global_added_by_data == nullptr || // + global_added_by_short_name == nullptr || // + global_added_by_long_name == nullptr) { + return 0; } - // We don't pay attention to |old_object| (which contains any previous object + // We don't pay attention to `old_object` (which contains any previous object // that was evicted from the hashes) because we don't have a reference count // on ASN1_OBJECT values. Also, we should never have duplicates nids and so - // should always have objects in |global_added_by_nid|. + // should always have objects in `global_added_by_nid`. ASN1_OBJECT *old_object; - ok = lh_ASN1_OBJECT_insert(global_added_by_nid, &old_object, obj); - if (obj->length != 0 && obj->data != NULL) { + int ok = lh_ASN1_OBJECT_insert(global_added_by_nid, &old_object, obj); + if (obj->length != 0 && obj->data != nullptr) { ok &= lh_ASN1_OBJECT_insert(global_added_by_data, &old_object, obj); } - if (obj->sn != NULL) { + if (obj->sn != nullptr) { ok &= lh_ASN1_OBJECT_insert(global_added_by_short_name, &old_object, obj); } - if (obj->ln != NULL) { + if (obj->ln != nullptr) { ok &= lh_ASN1_OBJECT_insert(global_added_by_long_name, &old_object, obj); } - -err: - CRYPTO_MUTEX_unlock_write(&global_added_lock); return ok; } int OBJ_create(const char *oid, const char *short_name, const char *long_name) { ASN1_OBJECT *op = create_object_with_text_oid(obj_next_nid, oid, short_name, long_name); - if (op == NULL || !obj_add_object(op)) { + if (op == nullptr || !obj_add_object(op)) { return NID_undef; } return op->nid; } -void OBJ_cleanup(void) {} +void OBJ_cleanup() {} diff --git a/Sources/CNIOBoringSSL/crypto/obj/obj_dat.h b/Sources/CNIOBoringSSL/crypto/obj/obj_dat.h index de5c4a54..ced3582f 100644 --- a/Sources/CNIOBoringSSL/crypto/obj/obj_dat.h +++ b/Sources/CNIOBoringSSL/crypto/obj/obj_dat.h @@ -1,16 +1,22 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. -/* This file is generated by crypto/obj/objects.go. */ +// This file is generated by crypto/obj/objects.go. -#define NUM_NID 966 +BSSL_NAMESPACE_BEGIN +#define NUM_NID 982 static const uint8_t kObjectData[] = { /* NID_rsadsi */ @@ -7090,6 +7096,119 @@ static const uint8_t kObjectData[] = { 0x04, 0x02, 0x06, + /* NID_ML_KEM_1024 */ + 0x60, + 0x86, + 0x48, + 0x01, + 0x65, + 0x03, + 0x04, + 0x04, + 0x03, + /* NID_ML_DSA_44 */ + 0x60, + 0x86, + 0x48, + 0x01, + 0x65, + 0x03, + 0x04, + 0x03, + 0x11, + /* NID_ML_DSA_65 */ + 0x60, + 0x86, + 0x48, + 0x01, + 0x65, + 0x03, + 0x04, + 0x03, + 0x12, + /* NID_ML_DSA_87 */ + 0x60, + 0x86, + 0x48, + 0x01, + 0x65, + 0x03, + 0x04, + 0x03, + 0x13, + /* NID_ML_KEM_768 */ + 0x60, + 0x86, + 0x48, + 0x01, + 0x65, + 0x03, + 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, + 0x48, + 0x01, + 0x65, + 0x03, + 0x04, + 0x03, + 0x14, + /* NID_SLH_DSA_SHAKE_256f */ + 0x60, + 0x86, + 0x48, + 0x01, + 0x65, + 0x03, + 0x04, + 0x03, + 0x1f, + /* NID_SLH_DSA_SHA2_128s_WITH_SHA256 */ + 0x60, + 0x86, + 0x48, + 0x01, + 0x65, + 0x03, + 0x04, + 0x03, + 0x23, }; static const ASN1_OBJECT kObjects[NUM_NID] = { @@ -8737,6 +8856,30 @@ static const ASN1_OBJECT kObjects[NUM_NID] = { {"X25519Kyber768Draft00", "X25519Kyber768Draft00", NID_X25519Kyber768Draft00, 0, NULL, 0}, {"X25519MLKEM768", "X25519MLKEM768", NID_X25519MLKEM768, 0, NULL, 0}, + {"id-alg-ml-kem-1024", "ML-KEM-1024", NID_ML_KEM_1024, 9, + &kObjectData[6196], 0}, + {"id-ml-dsa-44", "ML-DSA-44", NID_ML_DSA_44, 9, &kObjectData[6205], 0}, + {"id-ml-dsa-65", "ML-DSA-65", NID_ML_DSA_65, 9, &kObjectData[6214], 0}, + {"id-ml-dsa-87", "ML-DSA-87", NID_ML_DSA_87, 9, &kObjectData[6223], 0}, + {"id-alg-ml-kem-768", "ML-KEM-768", NID_ML_KEM_768, 9, &kObjectData[6232], + 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}, + {"id-slh-dsa-shake-256f", "SLH-DSA-SHAKE-256f", NID_SLH_DSA_SHAKE_256f, 9, + &kObjectData[6280], 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}, }; static const uint16_t kNIDsInShortNameOrder[] = { @@ -8933,6 +9076,7 @@ static const uint16_t kNIDsInShortNameOrder[] = { 16 /* ST */, 143 /* SXNetID */, 458 /* UID */, + 972 /* X-Wing */, 948 /* X25519 */, 964 /* X25519Kyber768Draft00 */, 965 /* X25519MLKEM768 */, @@ -8951,6 +9095,7 @@ static const uint16_t kNIDsInShortNameOrder[] = { 368 /* acceptableResponses */, 446 /* account */, 363 /* ad_timestamping */, + 976 /* alg-mtcProof-draft */, 376 /* algorithm */, 405 /* ansi-X9-62 */, 910 /* anyExtendedKeyUsage */, @@ -9174,6 +9319,8 @@ static const uint16_t kNIDsInShortNameOrder[] = { 323 /* id-alg-des40 */, 326 /* id-alg-dh-pop */, 325 /* id-alg-dh-sig-hmac-sha1 */, + 966 /* id-alg-ml-kem-1024 */, + 970 /* id-alg-ml-kem-768 */, 324 /* id-alg-noSignature */, 907 /* id-camellia128-wrap */, 908 /* id-camellia192-wrap */, @@ -9207,6 +9354,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 */, 508 /* id-hex-multipart-message */, 507 /* id-hex-partial-message */, 260 /* id-it */, @@ -9227,6 +9375,9 @@ static const uint16_t kNIDsInShortNameOrder[] = { 784 /* id-it-suppLangTags */, 304 /* id-it-unsupportedOIDs */, 128 /* id-kp */, + 967 /* id-ml-dsa-44 */, + 968 /* id-ml-dsa-65 */, + 969 /* id-ml-dsa-87 */, 280 /* id-mod-attribute-cert */, 274 /* id-mod-cmc */, 277 /* id-mod-cmp */, @@ -9275,6 +9426,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 */, 191 /* id-smime-aa */, 215 /* id-smime-aa-contentHint */, 218 /* id-smime-aa-contentIdentifier */, @@ -9407,6 +9560,7 @@ static const uint16_t kNIDsInShortNameOrder[] = { 489 /* pagerTelephoneNumber */, 374 /* path */, 112 /* pbeWithMD5AndCast5CBC */, + 978 /* pe-mtcCertificationAuthority-draft */, 499 /* personalSignature */, 487 /* personalTitle */, 464 /* photo */, @@ -9460,6 +9614,7 @@ static const uint16_t kNIDsInShortNameOrder[] = { 286 /* qcStatements */, 457 /* qualityLabelledData */, 450 /* rFC822localPart */, + 977 /* rdna-trustAnchorID-draft */, 870 /* registeredAddress */, 400 /* role */, 877 /* roleOccupant */, @@ -9750,6 +9905,11 @@ static const uint16_t kNIDsInLongNameOrder[] = { 647 /* International Organizations */, 142 /* Invalidity Date */, 504 /* MIME MHS */, + 967 /* ML-DSA-44 */, + 968 /* ML-DSA-65 */, + 969 /* ML-DSA-87 */, + 966 /* ML-KEM-1024 */, + 970 /* ML-KEM-768 */, 388 /* Mail */, 383 /* Management */, 417 /* Microsoft CSP Name */, @@ -9795,6 +9955,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 */, 387 /* SNMPv2 */, 512 /* Secure Electronic Transactions */, 386 /* Security */, @@ -9805,6 +9968,7 @@ static const uint16_t kNIDsInLongNameOrder[] = { 129 /* TLS Web Server Authentication */, 133 /* Time Stamping */, 375 /* Trust Root */, + 972 /* X-Wing */, 948 /* X25519 */, 964 /* X25519Kyber768Draft00 */, 965 /* X25519MLKEM768 */, @@ -9877,6 +10041,7 @@ static const uint16_t kNIDsInLongNameOrder[] = { 901 /* aes-256-gcm */, 428 /* aes-256-ofb */, 914 /* aes-256-xts */, + 976 /* alg-mtcProof-draft */, 376 /* algorithm */, 484 /* associatedDomain */, 485 /* associatedName */, @@ -10355,6 +10520,7 @@ static const uint16_t kNIDsInLongNameOrder[] = { 145 /* pbeWithSHA1And40BitRC4 */, 170 /* pbeWithSHA1AndDES-CBC */, 68 /* pbeWithSHA1AndRC2-CBC */, + 978 /* pe-mtcCertificationAuthority-draft */, 499 /* personalSignature */, 487 /* personalTitle */, 464 /* photo */, @@ -10414,6 +10580,7 @@ static const uint16_t kNIDsInLongNameOrder[] = { 122 /* rc5-cfb */, 121 /* rc5-ecb */, 123 /* rc5-ofb */, + 977 /* rdna-trustAnchorID-draft */, 870 /* registeredAddress */, 460 /* rfc822Mailbox */, 117 /* ripemd160 */, @@ -11365,6 +11532,14 @@ static const uint16_t kNIDsInOIDOrder[] = { 962 /* 2.16.840.1.101.3.4.2.6 (OBJ_sha512_256) */, 802 /* 2.16.840.1.101.3.4.3.1 (OBJ_dsa_with_SHA224) */, 803 /* 2.16.840.1.101.3.4.3.2 (OBJ_dsa_with_SHA256) */, + 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) */, + 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) */, 72 /* 2.16.840.1.113730.1.2 (OBJ_netscape_base_url) */, 73 /* 2.16.840.1.113730.1.3 (OBJ_netscape_revocation_url) */, @@ -11462,6 +11637,9 @@ 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) */, @@ -11541,3 +11719,4 @@ static const uint16_t kNIDsInOIDOrder[] = { 155 /* 1.2.840.113549.1.12.10.1.6 (OBJ_safeContentsBag) */, 34 /* 1.3.6.1.4.1.188.7.1.1.2 (OBJ_idea_cbc) */, }; +BSSL_NAMESPACE_END diff --git a/Sources/CNIOBoringSSL/crypto/obj/obj_xref.cc b/Sources/CNIOBoringSSL/crypto/obj/obj_xref.cc index 75dccf20..f15aa978 100644 --- a/Sources/CNIOBoringSSL/crypto/obj/obj_xref.cc +++ b/Sources/CNIOBoringSSL/crypto/obj/obj_xref.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -42,16 +47,19 @@ static const nid_triple kTriples[] = { // digest "undef" indicates the caller should handle this explicitly. {NID_rsassaPss, NID_undef, NID_rsaEncryption}, {NID_ED25519, NID_undef, NID_ED25519}, + {NID_ML_DSA_44, NID_undef, NID_ML_DSA_44}, + {NID_ML_DSA_65, NID_undef, NID_ML_DSA_65}, + {NID_ML_DSA_87, NID_undef, NID_ML_DSA_87}, }; int OBJ_find_sigid_algs(int sign_nid, int *out_digest_nid, int *out_pkey_nid) { - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kTriples); i++) { - if (kTriples[i].sign_nid == sign_nid) { - if (out_digest_nid != NULL) { - *out_digest_nid = kTriples[i].digest_nid; + for (const auto &triple : kTriples) { + if (triple.sign_nid == sign_nid) { + if (out_digest_nid != nullptr) { + *out_digest_nid = triple.digest_nid; } - if (out_pkey_nid != NULL) { - *out_pkey_nid = kTriples[i].pkey_nid; + if (out_pkey_nid != nullptr) { + *out_pkey_nid = triple.pkey_nid; } return 1; } @@ -61,11 +69,11 @@ int OBJ_find_sigid_algs(int sign_nid, int *out_digest_nid, int *out_pkey_nid) { } int OBJ_find_sigid_by_algs(int *out_sign_nid, int digest_nid, int pkey_nid) { - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kTriples); i++) { - if (kTriples[i].digest_nid == digest_nid && - kTriples[i].pkey_nid == pkey_nid) { - if (out_sign_nid != NULL) { - *out_sign_nid = kTriples[i].sign_nid; + for (const auto &triple : kTriples) { + if (triple.digest_nid == digest_nid && + triple.pkey_nid == pkey_nid) { + if (out_sign_nid != nullptr) { + *out_sign_nid = triple.sign_nid; } return 1; } diff --git a/Sources/CNIOBoringSSL/crypto/params_internal.h b/Sources/CNIOBoringSSL/crypto/params_internal.h new file mode 100644 index 00000000..1fa414c1 --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/params_internal.h @@ -0,0 +1,30 @@ +// 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. + +#ifndef OPENSSL_HEADER_CRYPTO_PARAMS_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_PARAMS_INTERNAL_H + +#include + + +BSSL_NAMESPACE_BEGIN + +// IsEndParam returns whether `param` is a terminating element. +inline bool IsEndParam(const OSSL_PARAM ¶m) { + return param.key == nullptr; +} + +BSSL_NAMESPACE_END + +#endif // OPENSSL_HEADER_CRYPTO_PARAMS_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/pem/internal.h b/Sources/CNIOBoringSSL/crypto/pem/internal.h index 1017efeb..4f14832c 100644 --- a/Sources/CNIOBoringSSL/crypto/pem/internal.h +++ b/Sources/CNIOBoringSSL/crypto/pem/internal.h @@ -1,39 +1,135 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. -#ifndef OPENSSL_HEADER_PEM_INTERNAL_H -#define OPENSSL_HEADER_PEM_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_PEM_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_PEM_INTERNAL_H +#include #include -#ifdef __cplusplus -extern "C" { -#endif +#include "../mem_internal.h" -// PEM_get_EVP_CIPHER_INFO decodes |header| as a PEM header block and writes the -// specified cipher and IV to |cipher|. It returns one on success and zero on -// error. |header| must be a NUL-terminated string. If |header| does not +BSSL_NAMESPACE_BEGIN + +// These macros make the PEM_read/PEM_write functions easier to maintain and +// write. Now they are all implemented with either: +// IMPLEMENT_PEM_rw(...) or IMPLEMENT_PEM_rw_cb(...) + +#define IMPLEMENT_PEM_read_fp(name, type, str, asn1) \ + static void *pem_read_##name##_d2i(void **x, const unsigned char **inp, \ + long len) { \ + return d2i_##asn1((type **)x, inp, len); \ + } \ + OPENSSL_EXPORT type *PEM_read_##name(FILE *fp, type **x, \ + pem_password_cb *cb, void *u) { \ + return (type *)PEM_ASN1_read(pem_read_##name##_d2i, str, fp, (void **)x, \ + cb, u); \ + } + +#define IMPLEMENT_PEM_write_fp(name, type, str, asn1) \ + static int pem_write_##name##_i2d(const void *x, unsigned char **outp) { \ + return i2d_##asn1((const type *)x, outp); \ + } \ + OPENSSL_EXPORT int PEM_write_##name(FILE *fp, const type *x) { \ + return PEM_ASN1_write(pem_write_##name##_i2d, str, fp, x, NULL, NULL, 0, \ + NULL, NULL); \ + } + +#define IMPLEMENT_PEM_write_cb_fp(name, type, str, asn1) \ + static int pem_write_##name##_i2d(const void *x, unsigned char **outp) { \ + return i2d_##asn1((const type *)x, outp); \ + } \ + OPENSSL_EXPORT int PEM_write_##name( \ + FILE *fp, const type *x, const EVP_CIPHER *enc, \ + const unsigned char *pass, int pass_len, pem_password_cb *cb, void *u) { \ + return PEM_ASN1_write(pem_write_##name##_i2d, str, fp, x, enc, pass, \ + pass_len, cb, u); \ + } + +#define IMPLEMENT_PEM_read_bio(name, type, str, asn1) \ + static void *pem_read_bio_##name##_d2i(void **x, const unsigned char **inp, \ + long len) { \ + return d2i_##asn1((type **)x, inp, len); \ + } \ + OPENSSL_EXPORT type *PEM_read_bio_##name(BIO *bp, type **x, \ + pem_password_cb *cb, void *u) { \ + return (type *)PEM_ASN1_read_bio(pem_read_bio_##name##_d2i, str, bp, \ + (void **)x, cb, u); \ + } + +#define IMPLEMENT_PEM_write_bio(name, type, str, asn1) \ + static int pem_write_bio_##name##_i2d(const void *x, unsigned char **outp) { \ + return i2d_##asn1((const type *)x, outp); \ + } \ + OPENSSL_EXPORT int PEM_write_bio_##name(BIO *bp, const type *x) { \ + return PEM_ASN1_write_bio(pem_write_bio_##name##_i2d, str, bp, x, NULL, \ + NULL, 0, NULL, NULL); \ + } + +#define IMPLEMENT_PEM_write_cb_bio(name, type, str, asn1) \ + static int pem_write_bio_##name##_i2d(const void *x, unsigned char **outp) { \ + return i2d_##asn1((const type *)x, outp); \ + } \ + OPENSSL_EXPORT int PEM_write_bio_##name( \ + BIO *bp, const type *x, const EVP_CIPHER *enc, \ + const unsigned char *pass, int pass_len, pem_password_cb *cb, void *u) { \ + return PEM_ASN1_write_bio(pem_write_bio_##name##_i2d, str, bp, x, enc, \ + pass, pass_len, cb, u); \ + } + +#define IMPLEMENT_PEM_write(name, type, str, asn1) \ + IMPLEMENT_PEM_write_bio(name, type, str, asn1) \ + IMPLEMENT_PEM_write_fp(name, type, str, asn1) + +#define IMPLEMENT_PEM_write_cb(name, type, str, asn1) \ + IMPLEMENT_PEM_write_cb_bio(name, type, str, asn1) \ + IMPLEMENT_PEM_write_cb_fp(name, type, str, asn1) + +#define IMPLEMENT_PEM_read(name, type, str, asn1) \ + IMPLEMENT_PEM_read_bio(name, type, str, asn1) \ + IMPLEMENT_PEM_read_fp(name, type, str, asn1) + +#define IMPLEMENT_PEM_rw(name, type, str, asn1) \ + IMPLEMENT_PEM_read(name, type, str, asn1) \ + IMPLEMENT_PEM_write(name, type, str, asn1) + +#define IMPLEMENT_PEM_rw_cb(name, type, str, asn1) \ + IMPLEMENT_PEM_read(name, type, str, asn1) \ + IMPLEMENT_PEM_write_cb(name, type, str, asn1) + +// PEM_get_EVP_CIPHER_INFO decodes `header` as a PEM header block and writes the +// specified cipher and IV to `cipher`. It returns one on success and zero on +// error. `header` must be a NUL-terminated string. If `header` does not // specify encryption, this function will return success and set -// |cipher->cipher| to NULL. +// `cipher->cipher` to NULL. int PEM_get_EVP_CIPHER_INFO(const char *header, EVP_CIPHER_INFO *cipher); -// PEM_do_header decrypts |*len| bytes from |data| in-place according to the -// information in |cipher|. On success, it returns one and sets |*len| to the -// length of the plaintext. Otherwise, it returns zero. If |cipher| specifies -// encryption, the key is derived from a password returned from |callback|. -int PEM_do_header(const EVP_CIPHER_INFO *cipher, uint8_t *data, long *len, +// PEM_do_header decrypts `*len` bytes from `data` in-place according to the +// information in `cipher`. On success, it returns one and sets `*len` to the +// length of the plaintext. Otherwise, it returns zero. If `cipher` specifies +// encryption, the key is derived from a password returned from `callback`. +int PEM_do_header(const EVP_CIPHER_INFO *cipher, uint8_t *data, size_t *len, pem_password_cb *callback, void *u); +// PEM_read_bio_inner differs from `PEM_read_bio` on the out pointer `len` +// so that it guarantee non-negativeness on this output and it takes in +// owned types. +int PEM_read_bio_inner(BIO *bp, bssl::UniquePtr *name, + bssl::UniquePtr *header, + bssl::Array *data); -#ifdef __cplusplus -} // extern "C" -#endif +BSSL_NAMESPACE_END -#endif // OPENSSL_HEADER_PEM_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_PEM_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/pem/pem_all.cc b/Sources/CNIOBoringSSL/crypto/pem/pem_all.cc index 348f31ad..a11da60e 100644 --- a/Sources/CNIOBoringSSL/crypto/pem/pem_all.cc +++ b/Sources/CNIOBoringSSL/crypto/pem/pem_all.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -18,6 +23,9 @@ #include #include +#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); @@ -33,14 +41,17 @@ IMPLEMENT_PEM_rw(PKCS7, PKCS7, PEM_STRING_PKCS7, PKCS7) // 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 *rtmp; if (!key) { - return NULL; + return nullptr; } - rtmp = EVP_PKEY_get1_RSA(key); - EVP_PKEY_free(key); + if (EVP_PKEY_id(key) != EVP_PKEY_RSA) { + // Don't accept RSA-PSS keys in this function. + OPENSSL_PUT_ERROR(EVP, EVP_R_EXPECTING_AN_RSA_KEY); + return nullptr; + } + RSA *rtmp = EVP_PKEY_get1_RSA(key); if (!rtmp) { - return NULL; + return nullptr; } if (rsa) { RSA_free(*rsa); @@ -51,32 +62,30 @@ static RSA *pkey_get_rsa(EVP_PKEY *key, RSA **rsa) { RSA *PEM_read_bio_RSAPrivateKey(BIO *bp, RSA **rsa, pem_password_cb *cb, void *u) { - EVP_PKEY *pktmp; - pktmp = PEM_read_bio_PrivateKey(bp, NULL, cb, u); - return pkey_get_rsa(pktmp, rsa); + bssl::UniquePtr pkey(PEM_read_bio_PrivateKey(bp, nullptr, cb, u)); + return pkey_get_rsa(pkey.get(), rsa); } RSA *PEM_read_RSAPrivateKey(FILE *fp, RSA **rsa, pem_password_cb *cb, void *u) { - EVP_PKEY *pktmp; - pktmp = PEM_read_PrivateKey(fp, NULL, cb, u); - return pkey_get_rsa(pktmp, rsa); + bssl::UniquePtr pkey(PEM_read_PrivateKey(fp, nullptr, cb, u)); + return pkey_get_rsa(pkey.get(), rsa); } -IMPLEMENT_PEM_write_cb_const(RSAPrivateKey, RSA, PEM_STRING_RSA, RSAPrivateKey) +IMPLEMENT_PEM_write_cb(RSAPrivateKey, RSA, PEM_STRING_RSA, RSAPrivateKey) -IMPLEMENT_PEM_rw_const(RSAPublicKey, RSA, PEM_STRING_RSA_PUBLIC, RSAPublicKey) +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) { DSA *dtmp; if (!key) { - return NULL; + return nullptr; } dtmp = EVP_PKEY_get1_DSA(key); EVP_PKEY_free(key); if (!dtmp) { - return NULL; + return nullptr; } if (dsa) { DSA_free(*dsa); @@ -88,30 +97,30 @@ static DSA *pkey_get_dsa(EVP_PKEY *key, DSA **dsa) { DSA *PEM_read_bio_DSAPrivateKey(BIO *bp, DSA **dsa, pem_password_cb *cb, void *u) { EVP_PKEY *pktmp; - pktmp = PEM_read_bio_PrivateKey(bp, NULL, cb, u); + pktmp = PEM_read_bio_PrivateKey(bp, nullptr, cb, u); return pkey_get_dsa(pktmp, dsa); // will free pktmp } -IMPLEMENT_PEM_write_cb_const(DSAPrivateKey, DSA, PEM_STRING_DSA, DSAPrivateKey) +IMPLEMENT_PEM_write_cb(DSAPrivateKey, DSA, PEM_STRING_DSA, DSAPrivateKey) IMPLEMENT_PEM_rw(DSA_PUBKEY, DSA, PEM_STRING_PUBLIC, DSA_PUBKEY) DSA *PEM_read_DSAPrivateKey(FILE *fp, DSA **dsa, pem_password_cb *cb, void *u) { EVP_PKEY *pktmp; - pktmp = PEM_read_PrivateKey(fp, NULL, cb, u); + pktmp = PEM_read_PrivateKey(fp, nullptr, cb, u); return pkey_get_dsa(pktmp, dsa); // will free pktmp } -IMPLEMENT_PEM_rw_const(DSAparams, DSA, PEM_STRING_DSAPARAMS, DSAparams) +IMPLEMENT_PEM_rw(DSAparams, DSA, PEM_STRING_DSAPARAMS, DSAparams) #endif static EC_KEY *pkey_get_eckey(EVP_PKEY *key, EC_KEY **eckey) { EC_KEY *dtmp; if (!key) { - return NULL; + return nullptr; } dtmp = EVP_PKEY_get1_EC_KEY(key); EVP_PKEY_free(key); if (!dtmp) { - return NULL; + return nullptr; } if (eckey) { EC_KEY_free(*eckey); @@ -123,7 +132,7 @@ static EC_KEY *pkey_get_eckey(EVP_PKEY *key, EC_KEY **eckey) { EC_KEY *PEM_read_bio_ECPrivateKey(BIO *bp, EC_KEY **key, pem_password_cb *cb, void *u) { EVP_PKEY *pktmp; - pktmp = PEM_read_bio_PrivateKey(bp, NULL, cb, u); + pktmp = PEM_read_bio_PrivateKey(bp, nullptr, cb, u); return pkey_get_eckey(pktmp, key); // will free pktmp } @@ -134,11 +143,11 @@ IMPLEMENT_PEM_rw(EC_PUBKEY, EC_KEY, PEM_STRING_PUBLIC, EC_PUBKEY) EC_KEY *PEM_read_ECPrivateKey(FILE *fp, EC_KEY **eckey, pem_password_cb *cb, void *u) { EVP_PKEY *pktmp; - pktmp = PEM_read_PrivateKey(fp, NULL, cb, u); + pktmp = PEM_read_PrivateKey(fp, nullptr, cb, u); return pkey_get_eckey(pktmp, eckey); // will free pktmp } -IMPLEMENT_PEM_rw_const(DHparams, DH, PEM_STRING_DHPARAMS, DHparams) +IMPLEMENT_PEM_rw(DHparams, DH, PEM_STRING_DHPARAMS, DHparams) IMPLEMENT_PEM_rw(PUBKEY, EVP_PKEY, PEM_STRING_PUBLIC, PUBKEY) diff --git a/Sources/CNIOBoringSSL/crypto/pem/pem_info.cc b/Sources/CNIOBoringSSL/crypto/pem/pem_info.cc index 73f7c5df..88723266 100644 --- a/Sources/CNIOBoringSSL/crypto/pem/pem_info.cc +++ b/Sources/CNIOBoringSSL/crypto/pem/pem_info.cc @@ -1,18 +1,24 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -21,28 +27,27 @@ #include #include +#include "../mem_internal.h" #include "internal.h" -static X509_PKEY *X509_PKEY_new(void) { - return reinterpret_cast(OPENSSL_zalloc(sizeof(X509_PKEY))); -} +using namespace bssl; + +static X509_PKEY *X509_PKEY_new() { return New(); } static void X509_PKEY_free(X509_PKEY *x) { - if (x == NULL) { + if (x == nullptr) { return; } EVP_PKEY_free(x->dec_pkey); - OPENSSL_free(x); + Delete(x); } -static X509_INFO *X509_INFO_new(void) { - return reinterpret_cast(OPENSSL_zalloc(sizeof(X509_INFO))); -} +static X509_INFO *X509_INFO_new() { return New(); } void X509_INFO_free(X509_INFO *x) { - if (x == NULL) { + if (x == nullptr) { return; } @@ -50,16 +55,16 @@ void X509_INFO_free(X509_INFO *x) { X509_CRL_free(x->crl); X509_PKEY_free(x->x_pkey); OPENSSL_free(x->enc_data); - OPENSSL_free(x); + Delete(x); } STACK_OF(X509_INFO) *PEM_X509_INFO_read(FILE *fp, STACK_OF(X509_INFO) *sk, pem_password_cb *cb, void *u) { BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); - if (b == NULL) { + if (b == nullptr) { OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB); - return 0; + return nullptr; } STACK_OF(X509_INFO) *ret = PEM_X509_INFO_read_bio(b, sk, cb, u); BIO_free(b); @@ -74,57 +79,57 @@ enum parse_result_t { static enum parse_result_t parse_x509(X509_INFO *info, const uint8_t *data, size_t len, int key_type) { - if (info->x509 != NULL) { + if (info->x509 != nullptr) { return parse_new_entry; } - info->x509 = d2i_X509(NULL, &data, len); - return info->x509 != NULL ? parse_ok : parse_error; + info->x509 = d2i_X509(nullptr, &data, len); + 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) { - if (info->x509 != NULL) { + if (info->x509 != nullptr) { return parse_new_entry; } - info->x509 = d2i_X509_AUX(NULL, &data, len); - return info->x509 != NULL ? parse_ok : parse_error; + info->x509 = d2i_X509_AUX(nullptr, &data, len); + 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) { - if (info->crl != NULL) { + if (info->crl != nullptr) { return parse_new_entry; } - info->crl = d2i_X509_CRL(NULL, &data, len); - return info->crl != NULL ? parse_ok : parse_error; + info->crl = d2i_X509_CRL(nullptr, &data, len); + 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) { - if (info->x_pkey != NULL) { + if (info->x_pkey != nullptr) { return parse_new_entry; } info->x_pkey = X509_PKEY_new(); - if (info->x_pkey == NULL) { + if (info->x_pkey == nullptr) { return parse_error; } - info->x_pkey->dec_pkey = d2i_PrivateKey(key_type, NULL, &data, len); - return info->x_pkey->dec_pkey != NULL ? parse_ok : parse_error; + info->x_pkey->dec_pkey = d2i_PrivateKey(key_type, nullptr, &data, len); + return info->x_pkey->dec_pkey != nullptr ? parse_ok : parse_error; } 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 = NULL; - char *name = NULL, *header = NULL; - unsigned char *data = NULL; - long len; + X509_INFO *info = nullptr; + UniquePtr name; + UniquePtr header; + Array data; int ok = 0; - STACK_OF(X509_INFO) *ret = NULL; + STACK_OF(X509_INFO) *ret = nullptr; - if (sk == NULL) { + if (sk == nullptr) { ret = sk_X509_INFO_new_null(); - if (ret == NULL) { - return NULL; + if (ret == nullptr) { + return nullptr; } } else { ret = sk; @@ -132,15 +137,13 @@ STACK_OF(X509_INFO) *PEM_X509_INFO_read_bio(BIO *bp, STACK_OF(X509_INFO) *sk, size_t orig_num = sk_X509_INFO_num(ret); info = X509_INFO_new(); - if (info == NULL) { + if (info == nullptr) { goto err; } for (;;) { - if (!PEM_read_bio(bp, &name, &header, &data, &len)) { - uint32_t error = ERR_peek_last_error(); - if (ERR_GET_LIB(error) == ERR_LIB_PEM && - ERR_GET_REASON(error) == PEM_R_NO_START_LINE) { + if (!PEM_read_bio_inner(bp, &name, &header, &data)) { + if (ERR_equals(ERR_peek_last_error(), ERR_LIB_PEM, PEM_R_NO_START_LINE)) { ERR_clear_error(); break; } @@ -148,84 +151,86 @@ STACK_OF(X509_INFO) *PEM_X509_INFO_read_bio(BIO *bp, STACK_OF(X509_INFO) *sk, } enum parse_result_t (*parse_function)(X509_INFO *, const uint8_t *, size_t, - int) = NULL; + int) = nullptr; int key_type = EVP_PKEY_NONE; - if (strcmp(name, PEM_STRING_X509) == 0 || - strcmp(name, PEM_STRING_X509_OLD) == 0) { + std::string_view name_view = name.get(); + if (name_view == PEM_STRING_X509 || name_view == PEM_STRING_X509_OLD) { parse_function = parse_x509; - } else if (strcmp(name, PEM_STRING_X509_TRUSTED) == 0) { + } else if (name_view == PEM_STRING_X509_TRUSTED) { parse_function = parse_x509_aux; - } else if (strcmp(name, PEM_STRING_X509_CRL) == 0) { + } else if (name_view == PEM_STRING_X509_CRL) { parse_function = parse_crl; - } else if (strcmp(name, PEM_STRING_RSA) == 0) { + } else if (name_view == PEM_STRING_RSA) { parse_function = parse_key; key_type = EVP_PKEY_RSA; - } else if (strcmp(name, PEM_STRING_DSA) == 0) { + } else if (name_view == PEM_STRING_DSA) { parse_function = parse_key; key_type = EVP_PKEY_DSA; - } else if (strcmp(name, PEM_STRING_ECPRIVATEKEY) == 0) { + } else if (name_view == PEM_STRING_ECPRIVATEKEY) { parse_function = parse_key; key_type = EVP_PKEY_EC; } // If a private key has a header, assume it is encrypted. This function does // not decrypt private keys. - if (key_type != EVP_PKEY_NONE && strlen(header) > 10) { - if (info->x_pkey != NULL) { + if (key_type != EVP_PKEY_NONE && strlen(header.get()) > 10) { + if (data.size() > INT_MAX) { + // We need the data to fit in `info` which forces the size to + // fit in one int type. + goto err; + } + if (info->x_pkey != nullptr) { if (!sk_X509_INFO_push(ret, info)) { goto err; } info = X509_INFO_new(); - if (info == NULL) { + if (info == nullptr) { goto err; } } // Use an empty key as a placeholder. info->x_pkey = X509_PKEY_new(); - if (info->x_pkey == NULL || - !PEM_get_EVP_CIPHER_INFO(header, &info->enc_cipher)) { + if (info->x_pkey == nullptr || + !PEM_get_EVP_CIPHER_INFO(header.get(), &info->enc_cipher)) { goto err; } - info->enc_data = (char *)data; - info->enc_len = (int)len; - data = NULL; - } else if (parse_function != NULL) { + size_t size; + data.Release(reinterpret_cast(&info->enc_data), &size); + // Safety: we checked that `size` <= `INT_MAX`. + info->enc_len = static_cast(size); + } else if (parse_function != nullptr) { EVP_CIPHER_INFO cipher; - if (!PEM_get_EVP_CIPHER_INFO(header, &cipher) || - !PEM_do_header(&cipher, data, &len, cb, u)) { + size_t len = data.size(); + if (!PEM_get_EVP_CIPHER_INFO(header.get(), &cipher) || + !PEM_do_header(&cipher, data.data(), &len, cb, u)) { goto err; } - enum parse_result_t result = parse_function(info, data, len, key_type); + enum parse_result_t result = + parse_function(info, data.data(), len, key_type); if (result == parse_new_entry) { if (!sk_X509_INFO_push(ret, info)) { goto err; } info = X509_INFO_new(); - if (info == NULL) { + if (info == nullptr) { goto err; } - result = parse_function(info, data, len, key_type); + result = parse_function(info, data.data(), len, key_type); } if (result != parse_ok) { OPENSSL_PUT_ERROR(PEM, ERR_R_ASN1_LIB); goto err; } } - OPENSSL_free(name); - OPENSSL_free(header); - OPENSSL_free(data); - name = NULL; - header = NULL; - data = NULL; } // Push the last entry on the stack if not empty. - if (info->x509 != NULL || info->crl != NULL || info->x_pkey != NULL || - info->enc_data != NULL) { + if (info->x509 != nullptr || info->crl != nullptr || + info->x_pkey != nullptr || info->enc_data != nullptr) { if (!sk_X509_INFO_push(ret, info)) { goto err; } - info = NULL; + info = nullptr; } ok = 1; @@ -239,11 +244,7 @@ err: if (ret != sk) { sk_X509_INFO_free(ret); } - ret = NULL; + ret = nullptr; } - - OPENSSL_free(name); - OPENSSL_free(header); - OPENSSL_free(data); return ret; } diff --git a/Sources/CNIOBoringSSL/crypto/pem/pem_lib.cc b/Sources/CNIOBoringSSL/crypto/pem/pem_lib.cc index 73698a38..87c945cb 100644 --- a/Sources/CNIOBoringSSL/crypto/pem/pem_lib.cc +++ b/Sources/CNIOBoringSSL/crypto/pem/pem_lib.cc @@ -1,21 +1,30 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 #include #include @@ -31,30 +40,13 @@ #define MIN_LENGTH 4 +using namespace bssl; + static int load_iv(const char **fromp, unsigned char *to, size_t num); -static int check_pem(const char *nm, const char *name); +static bool check_pem(std::string_view name, std::string_view expected); -// PEM_proc_type appends a Proc-Type header to |buf|, determined by |type|. -static void PEM_proc_type(char buf[PEM_BUFSIZE], int type) { - const char *str; - - if (type == PEM_TYPE_ENCRYPTED) { - str = "ENCRYPTED"; - } else if (type == PEM_TYPE_MIC_CLEAR) { - str = "MIC-CLEAR"; - } else if (type == PEM_TYPE_MIC_ONLY) { - str = "MIC-ONLY"; - } else { - str = "BAD-TYPE"; - } - - OPENSSL_strlcat(buf, "Proc-Type: 4,", PEM_BUFSIZE); - OPENSSL_strlcat(buf, str, PEM_BUFSIZE); - OPENSSL_strlcat(buf, "\n", PEM_BUFSIZE); -} - -// 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|. +// 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) { static const unsigned char map[17] = "0123456789ABCDEF"; @@ -80,74 +72,58 @@ static void PEM_dek_info(char buf[PEM_BUFSIZE], const char *type, size_t len, 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 == NULL) { + if (b == nullptr) { OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB); - return NULL; + return nullptr; } void *ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u); BIO_free(b); return ret; } -static int check_pem(const char *nm, const char *name) { - // Normal matching nm and name - if (!strcmp(nm, name)) { - return 1; +static 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) { + return name == PEM_STRING_PKCS8 || name == PEM_STRING_PKCS8INF || + name == PEM_STRING_RSA || name == PEM_STRING_EC || + name == PEM_STRING_DSA; } - // Make PEM_STRING_EVP_PKEY match any private key - - if (!strcmp(name, PEM_STRING_EVP_PKEY)) { - return !strcmp(nm, PEM_STRING_PKCS8) || !strcmp(nm, PEM_STRING_PKCS8INF) || - !strcmp(nm, PEM_STRING_RSA) || !strcmp(nm, PEM_STRING_EC) || - !strcmp(nm, PEM_STRING_DSA); + // Normal name matching. + if (name == expected) { + return true; } - // Permit older strings - - if (!strcmp(nm, PEM_STRING_X509_OLD) && !strcmp(name, PEM_STRING_X509)) { - return 1; + // Permit older strings. + if (name == PEM_STRING_X509_OLD && expected == PEM_STRING_X509) { + return true; + } + if (name == PEM_STRING_X509_REQ_OLD && expected == PEM_STRING_X509_REQ) { + return true; } - if (!strcmp(nm, PEM_STRING_X509_REQ_OLD) && - !strcmp(name, PEM_STRING_X509_REQ)) { - return 1; + // Allow normal certs to be read as trusted certs. + if (name == PEM_STRING_X509 && expected == PEM_STRING_X509_TRUSTED) { + return true; + } + if (name == PEM_STRING_X509_OLD && expected == PEM_STRING_X509_TRUSTED) { + return true; } - // Allow normal certs to be read as trusted certs - if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_X509_TRUSTED)) { - return 1; + // Some CAs use PKCS#7 with CERTIFICATE headers. + if (name == PEM_STRING_X509 && expected == PEM_STRING_PKCS7) { + return true; + } + if (name == PEM_STRING_PKCS7_SIGNED && expected == PEM_STRING_PKCS7) { + return true; } - if (!strcmp(nm, PEM_STRING_X509_OLD) && - !strcmp(name, PEM_STRING_X509_TRUSTED)) { - return 1; - } - - // Some CAs use PKCS#7 with CERTIFICATE headers - if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_PKCS7)) { - return 1; - } - - if (!strcmp(nm, PEM_STRING_PKCS7_SIGNED) && !strcmp(name, PEM_STRING_PKCS7)) { - return 1; - } - -#ifndef OPENSSL_NO_CMS - if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_CMS)) { - return 1; - } - // Allow CMS to be read from PKCS#7 headers - if (!strcmp(nm, PEM_STRING_PKCS7) && !strcmp(name, PEM_STRING_CMS)) { - return 1; - } -#endif - - return 0; + return false; } -static const EVP_CIPHER *cipher_by_name(std::string_view name) { - // This is similar to the (deprecated) function |EVP_get_cipherbyname|. Note +static 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. if (name == SN_des_cbc) { @@ -161,67 +137,63 @@ static const EVP_CIPHER *cipher_by_name(std::string_view name) { } else if (name == SN_aes_256_cbc) { return EVP_aes_256_cbc(); } else { - return NULL; + return nullptr; } } int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm, - const char *name, BIO *bp, pem_password_cb *cb, + const char *expected_name, BIO *bp, pem_password_cb *cb, void *u) { EVP_CIPHER_INFO cipher; - char *nm = NULL, *header = NULL; - unsigned char *data = NULL; - long len; - int ret = 0; + UniquePtr nm; + UniquePtr header; + Array data; + size_t ulen; + size_t unused = 0; for (;;) { - if (!PEM_read_bio(bp, &nm, &header, &data, &len)) { - uint32_t error = ERR_peek_error(); - if (ERR_GET_LIB(error) == ERR_LIB_PEM && - ERR_GET_REASON(error) == PEM_R_NO_START_LINE) { - ERR_add_error_data(2, "Expecting: ", name); + if (!PEM_read_bio_inner(bp, &nm, &header, &data)) { + if (ERR_equals(ERR_peek_error(), ERR_LIB_PEM, PEM_R_NO_START_LINE)) { + ERR_add_error_data(2, "Expecting: ", expected_name); } return 0; } - if (check_pem(nm, name)) { + if (data.size() > LONG_MAX) { + OPENSSL_PUT_ERROR(PEM, ERR_R_OVERFLOW); + return 0; + } + if (check_pem(nm.get(), expected_name)) { break; } - OPENSSL_free(nm); - OPENSSL_free(header); - OPENSSL_free(data); } - if (!PEM_get_EVP_CIPHER_INFO(header, &cipher)) { - goto err; + if (!PEM_get_EVP_CIPHER_INFO(header.get(), &cipher)) { + return 0; } - if (!PEM_do_header(&cipher, data, &len, cb, u)) { - goto err; + ulen = data.size(); + if (!PEM_do_header(&cipher, data.data(), &ulen, cb, u)) { + return 0; } - *pdata = data; - *plen = len; + // Release the buffer to the caller. + // Note that `PEM_do_header` may have reduced the length after decrypting + // in-place. + // This will not overflow because `data.size()` was checked to fit in `long` + // above. + data.Release(pdata, &unused); + *plen = static_cast(ulen); if (pnm) { - *pnm = nm; + *pnm = nm.release(); } - ret = 1; - -err: - if (!ret || !pnm) { - OPENSSL_free(nm); - } - OPENSSL_free(header); - if (!ret) { - OPENSSL_free(data); - } - return ret; + return 1; } -int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp, void *x, +int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp, const void *x, const EVP_CIPHER *enc, const unsigned char *pass, int pass_len, pem_password_cb *callback, void *u) { BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); - if (b == NULL) { + if (b == nullptr) { OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB); return 0; } @@ -231,48 +203,51 @@ int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp, void *x, return ret; } -int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, void *x, - const EVP_CIPHER *enc, const unsigned char *pass, - int pass_len, pem_password_cb *callback, void *u) { - EVP_CIPHER_CTX ctx; - int dsize = 0, i, j, ret = 0; - unsigned char *p, *data = NULL; - const char *objstr = NULL; +int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, + const void *x, const EVP_CIPHER *enc, + const unsigned char *pass, int pass_len, + pem_password_cb *callback, void *u) { + ScopedEVP_CIPHER_CTX ctx; + int dsize = 0, ret = 0; + size_t i, j, data_size; + unsigned char *p, *data = nullptr; + const char *objstr = nullptr; char buf[PEM_BUFSIZE]; unsigned char key[EVP_MAX_KEY_LENGTH]; unsigned char iv[EVP_MAX_IV_LENGTH]; - if (enc != NULL) { + if (enc != nullptr) { objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc)); - if (objstr == NULL || cipher_by_name(objstr) == NULL || + if (objstr == nullptr || cipher_by_name(objstr) == nullptr || EVP_CIPHER_iv_length(enc) < 8) { OPENSSL_PUT_ERROR(PEM, PEM_R_UNSUPPORTED_CIPHER); goto err; } } - if ((dsize = i2d(x, NULL)) < 0) { + if ((dsize = i2d(x, nullptr)) < 0) { OPENSSL_PUT_ERROR(PEM, ERR_R_ASN1_LIB); dsize = 0; goto err; } // dzise + 8 bytes are needed // actually it needs the cipher block size extra... - data = (unsigned char *)OPENSSL_malloc((unsigned int)dsize + 20); - if (data == NULL) { + data_size = static_cast(dsize) + 20; + data = (unsigned char *)OPENSSL_malloc(data_size); + if (data == nullptr) { goto err; } p = data; i = i2d(x, &p); - if (enc != NULL) { + if (enc != nullptr) { const unsigned iv_len = EVP_CIPHER_iv_length(enc); - if (pass == NULL) { + if (pass == nullptr) { if (!callback) { callback = PEM_def_callback; } - pass_len = (*callback)(buf, PEM_BUFSIZE, 1, u); + pass_len = (*callback)(buf, PEM_BUFSIZE, /*enc=*/1, u); if (pass_len < 0) { OPENSSL_PUT_ERROR(PEM, PEM_R_READ_KEY); goto err; @@ -285,7 +260,7 @@ int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, void *x, } // The 'iv' is used as the iv and as a salt. It is NOT taken from // the BytesToKey function - if (!EVP_BytesToKey(enc, EVP_md5(), iv, pass, pass_len, 1, key, NULL)) { + if (!EVP_BytesToKey(enc, EVP_md5(), iv, pass, pass_len, 1, key, nullptr)) { goto err; } @@ -295,21 +270,17 @@ int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, void *x, assert(strlen(objstr) + 23 + 2 * iv_len + 13 <= sizeof(buf)); - buf[0] = '\0'; - PEM_proc_type(buf, PEM_TYPE_ENCRYPTED); + OPENSSL_strlcpy(buf, "Proc-Type: 4,ENCRYPTED\n", sizeof(buf)); PEM_dek_info(buf, objstr, iv_len, (char *)iv); - // k=strlen(buf); - EVP_CIPHER_CTX_init(&ctx); ret = 1; - if (!EVP_EncryptInit_ex(&ctx, enc, NULL, key, iv) || - !EVP_EncryptUpdate(&ctx, data, &j, data, i) || - !EVP_EncryptFinal_ex(&ctx, &(data[j]), &i)) { + if (!EVP_EncryptInit_ex(ctx.get(), enc, nullptr, key, iv) || + !EVP_EncryptUpdate_ex(ctx.get(), data, &j, data_size, data, i) || + !EVP_EncryptFinal_ex2(ctx.get(), &(data[j]), &i, data_size - j)) { ret = 0; } else { i += j; } - EVP_CIPHER_CTX_cleanup(&ctx); if (ret == 0) { goto err; } @@ -324,23 +295,20 @@ int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, void *x, err: OPENSSL_cleanse(key, sizeof(key)); OPENSSL_cleanse(iv, sizeof(iv)); - OPENSSL_cleanse((char *)&ctx, sizeof(ctx)); OPENSSL_cleanse(buf, PEM_BUFSIZE); OPENSSL_free(data); return ret; } -int PEM_do_header(const EVP_CIPHER_INFO *cipher, unsigned char *data, - long *plen, pem_password_cb *callback, void *u) { - int i = 0, j, o, pass_len; - long len; - EVP_CIPHER_CTX ctx; +int bssl::PEM_do_header(const EVP_CIPHER_INFO *cipher, unsigned char *data, + size_t *len, pem_password_cb *callback, void *u) { + int pass_len; + ScopedEVP_CIPHER_CTX ctx; unsigned char key[EVP_MAX_KEY_LENGTH]; char buf[PEM_BUFSIZE]; + const size_t in_len = *len; - len = *plen; - - if (cipher->cipher == NULL) { + if (cipher->cipher == nullptr) { return 1; } @@ -348,42 +316,37 @@ int PEM_do_header(const EVP_CIPHER_INFO *cipher, unsigned char *data, if (!callback) { callback = PEM_def_callback; } - pass_len = callback(buf, PEM_BUFSIZE, 0, u); + pass_len = callback(buf, PEM_BUFSIZE, /*enc=*/0, u); if (pass_len < 0) { OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_PASSWORD_READ); return 0; } if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), cipher->iv, - (unsigned char *)buf, pass_len, 1, key, NULL)) { + (unsigned char *)buf, pass_len, 1, key, nullptr)) { return 0; } - j = (int)len; - EVP_CIPHER_CTX_init(&ctx); - o = EVP_DecryptInit_ex(&ctx, cipher->cipher, NULL, key, cipher->iv); - if (o) { - o = EVP_DecryptUpdate(&ctx, data, &i, data, j); - } - if (o) { - o = EVP_DecryptFinal_ex(&ctx, &(data[i]), &j); - } - EVP_CIPHER_CTX_cleanup(&ctx); - OPENSSL_cleanse((char *)buf, sizeof(buf)); - OPENSSL_cleanse((char *)key, sizeof(key)); - if (!o) { + // Safety: we have checked `*len` before narrowing so that `EVP_DecryptUpdate` + // can safely work with it. + size_t out_len1 = 0; + size_t out_len2 = 0; + if (!EVP_DecryptInit_ex(ctx.get(), cipher->cipher, nullptr, key, + cipher->iv) || + !EVP_DecryptUpdate_ex(ctx.get(), data, &out_len1, in_len, data, in_len) || + !EVP_DecryptFinal_ex2(ctx.get(), data + out_len1, &out_len2, + in_len - out_len1)) { OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_DECRYPT); return 0; } - j += i; - *plen = j; + *len = out_len1 + out_len2; return 1; } -int PEM_get_EVP_CIPHER_INFO(const char *header, EVP_CIPHER_INFO *cipher) { - cipher->cipher = NULL; +int bssl::PEM_get_EVP_CIPHER_INFO(const char *header, EVP_CIPHER_INFO *cipher) { + cipher->cipher = nullptr; OPENSSL_memset(cipher->iv, 0, sizeof(cipher->iv)); - if ((header == NULL) || (*header == '\0') || (*header == '\n')) { + if ((header == nullptr) || (*header == '\0') || (*header == '\n')) { return 1; } if (strncmp(header, "Proc-Type: ", 11) != 0) { @@ -424,12 +387,12 @@ int PEM_get_EVP_CIPHER_INFO(const char *header, EVP_CIPHER_INFO *cipher) { } cipher->cipher = cipher_by_name(std::string_view(p, header - p)); header++; - if (cipher->cipher == NULL) { + if (cipher->cipher == nullptr) { OPENSSL_PUT_ERROR(PEM, PEM_R_UNSUPPORTED_ENCRYPTION); return 0; } // The IV parameter must be at least 8 bytes long to be used as the salt in - // the KDF. (This should not happen given |cipher_by_name|.) + // the KDF. (This should not happen given `cipher_by_name`.) if (EVP_CIPHER_iv_length(cipher->cipher) < 8) { assert(0); OPENSSL_PUT_ERROR(PEM, PEM_R_UNSUPPORTED_ENCRYPTION); @@ -468,7 +431,7 @@ static int load_iv(const char **fromp, unsigned char *to, size_t num) { 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); - if (b == NULL) { + if (b == nullptr) { OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB); return 0; } @@ -480,7 +443,7 @@ int PEM_write(FILE *fp, const char *name, const char *header, int PEM_write_bio(BIO *bp, const char *name, const char *header, const unsigned char *data, long len) { int nlen, n, i, j, outl; - unsigned char *buf = NULL; + unsigned char *buf = nullptr; EVP_ENCODE_CTX ctx; int reason = ERR_R_BUF_LIB; int retval = 0; @@ -502,7 +465,7 @@ int PEM_write_bio(BIO *bp, const char *name, const char *header, } buf = reinterpret_cast(OPENSSL_malloc(PEM_BUFSIZE * 8)); - if (buf == NULL) { + if (buf == nullptr) { goto err; } @@ -539,7 +502,7 @@ err: int PEM_read(FILE *fp, char **name, char **header, unsigned char **data, long *len) { BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); - if (b == NULL) { + if (b == nullptr) { OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB); return 0; } @@ -548,32 +511,24 @@ int PEM_read(FILE *fp, char **name, char **header, unsigned char **data, return ret; } -int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data, - long *len) { - EVP_ENCODE_CTX ctx; - int end = 0, i, k, bl = 0, hl = 0, nohead = 0; - char buf[256]; - BUF_MEM *nameB; - BUF_MEM *headerB; - BUF_MEM *dataB, *tmpB; - - nameB = BUF_MEM_new(); - headerB = BUF_MEM_new(); - dataB = BUF_MEM_new(); - if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL)) { - BUF_MEM_free(nameB); - BUF_MEM_free(headerB); - BUF_MEM_free(dataB); +int bssl::PEM_read_bio_inner(BIO *bp, UniquePtr *name, + UniquePtr *header, Array *data) { + bssl::UniquePtr nameB(BUF_MEM_new()); + bssl::UniquePtr headerB(BUF_MEM_new()); + bssl::UniquePtr dataB(BUF_MEM_new()); + if ((nameB == nullptr) || (headerB == nullptr) || (dataB == nullptr)) { + OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE); return 0; } + char buf[256]; // 254 characters + newline + \0. buf[254] = '\0'; + // Invariant: buf[254] < ' '. It may get overwritten by '\n' or '\0' only. for (;;) { - i = BIO_gets(bp, buf, 254); - + int i = BIO_gets(bp, buf, 254); if (i <= 0) { OPENSSL_PUT_ERROR(PEM, PEM_R_NO_START_LINE); - goto err; + return 0; } while ((i >= 0) && (buf[i] <= ' ')) { @@ -588,142 +543,158 @@ int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data, if (strncmp(&(buf[11 + i - 6]), "-----\n", 6) != 0) { continue; } - if (!BUF_MEM_grow(nameB, i + 9)) { - goto err; + if (!BUF_MEM_grow(nameB.get(), i - 5)) { + OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE); + return 0; } OPENSSL_memcpy(nameB->data, &(buf[11]), i - 6); nameB->data[i - 6] = '\0'; break; } } - hl = 0; - if (!BUF_MEM_grow(headerB, 256)) { - goto err; + + size_t hl = 0; + if (!BUF_MEM_grow(headerB.get(), 256)) { + OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE); + return 0; } headerB->data[0] = '\0'; - for (;;) { - i = BIO_gets(bp, buf, 254); - if (i <= 0) { - break; - } - while ((i >= 0) && (buf[i] <= ' ')) { - i--; - } - buf[++i] = '\n'; - buf[++i] = '\0'; - - if (buf[0] == '\n') { - break; - } - if (!BUF_MEM_grow(headerB, hl + i + 9)) { - goto err; - } - if (strncmp(buf, "-----END ", 9) == 0) { - nohead = 1; - break; - } - OPENSSL_memcpy(&(headerB->data[hl]), buf, i); - headerB->data[hl + i] = '\0'; - hl += i; - } - - bl = 0; - if (!BUF_MEM_grow(dataB, 1024)) { - goto err; + size_t bl = 0; + if (!BUF_MEM_grow(dataB.get(), 1024)) { + OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE); + return 0; } dataB->data[0] = '\0'; - if (!nohead) { + + bool failed = false; // Set to true (and error put into queue) on failure. + auto read_until_end = [&](BUF_MEM *out, size_t &out_len, + bool stop_at_newline) { + // Invariant: buf[254] < ' '. It may get overwritten by '\n' or '\0' only. for (;;) { - i = BIO_gets(bp, buf, 254); + int i = BIO_gets(bp, buf, 254); if (i <= 0) { break; } - while ((i >= 0) && (buf[i] <= ' ')) { i--; } buf[++i] = '\n'; buf[++i] = '\0'; - if (i != 65) { - end = 1; + if (stop_at_newline && buf[0] == '\n') { + // End of header, start of body. + return true; } if (strncmp(buf, "-----END ", 9) == 0) { - break; + return false; } - if (i > 65) { - break; + if (static_cast(i) > SIZE_MAX - hl - 1) { + OPENSSL_PUT_ERROR(PEM, ERR_R_OVERFLOW); + failed = true; + return false; } - if (!BUF_MEM_grow_clean(dataB, i + bl + 9)) { - goto err; + size_t new_len = out_len + i; + if (new_len > INT_MAX / 2) { + // Arbitrarily limit PEM data to INT_MAX / 2 bytes, which "ought to be + // enough for anyone". Hardens against possible integer overflows + // downstream. + OPENSSL_PUT_ERROR(PEM, ERR_R_OVERFLOW); + failed = true; + return false; } - OPENSSL_memcpy(&(dataB->data[bl]), buf, i); - dataB->data[bl + i] = '\0'; - bl += i; - if (end) { - buf[0] = '\0'; - i = BIO_gets(bp, buf, 254); - if (i <= 0) { - break; - } - - while ((i >= 0) && (buf[i] <= ' ')) { - i--; - } - buf[++i] = '\n'; - buf[++i] = '\0'; - - break; + if (!BUF_MEM_grow(out, new_len + 1)) { + OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE); + failed = true; + return false; } + OPENSSL_memcpy(&(out->data[out_len]), buf, i); + out->data[new_len] = '\0'; + out_len = new_len; } + return false; + }; + + if (read_until_end(headerB.get(), hl, /*stop_at_newline=*/true)) { + read_until_end(dataB.get(), bl, /*stop_at_newline=*/false); } else { - tmpB = headerB; - headerB = dataB; - dataB = tmpB; - bl = hl; + // Actually we've read the body, as there is no header. + std::swap(hl, bl); + std::swap(headerB, dataB); } - i = strlen(nameB->data); + if (failed) { + return 0; + } + + size_t name_len = strlen(nameB->data); if ((strncmp(buf, "-----END ", 9) != 0) || - (strncmp(nameB->data, &(buf[9]), i) != 0) || - (strncmp(&(buf[9 + i]), "-----\n", 6) != 0)) { + (strncmp(&(buf[9]), nameB->data, name_len) != 0) || + (strncmp(&(buf[9 + name_len]), "-----\n", 6) != 0)) { OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_END_LINE); - goto err; + return 0; } + EVP_ENCODE_CTX ctx; EVP_DecodeInit(&ctx); - i = EVP_DecodeUpdate(&ctx, (unsigned char *)dataB->data, &bl, + int decoded_length; + int status = + EVP_DecodeUpdate(&ctx, (unsigned char *)dataB->data, &decoded_length, (unsigned char *)dataB->data, bl); - if (i < 0) { + if (status < 0) { OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_BASE64_DECODE); - goto err; + return 0; } - i = EVP_DecodeFinal(&ctx, (unsigned char *)&(dataB->data[bl]), &k); - if (i < 0) { + int k; + status = EVP_DecodeFinal(&ctx, + (unsigned char *)&(dataB->data[decoded_length]), &k); + if (status < 0) { OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_BASE64_DECODE); - goto err; + return 0; } - bl += k; + if (k > INT_MAX - decoded_length) { + OPENSSL_PUT_ERROR(PEM, ERR_R_OVERFLOW); + return 0; + } + decoded_length += k; - if (bl == 0) { - goto err; + if (decoded_length == 0) { + OPENSSL_PUT_ERROR(PEM, PEM_R_NO_DATA); + return 0; } - *name = nameB->data; - *header = headerB->data; - *data = (unsigned char *)dataB->data; - *len = bl; - OPENSSL_free(nameB); - OPENSSL_free(headerB); - OPENSSL_free(dataB); + + // Transfer ownership of buffers + name->reset(nameB->data); + nameB->data = nullptr; + header->reset(headerB->data); + headerB->data = nullptr; + data->Reset((uint8_t *)dataB->data, decoded_length); + dataB->data = nullptr; + return 1; -err: - BUF_MEM_free(nameB); - BUF_MEM_free(headerB); - BUF_MEM_free(dataB); - return 0; } -int PEM_def_callback(char *buf, int size, int rwflag, void *userdata) { +int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data, + long *len) { + UniquePtr owned_name; + UniquePtr owned_header; + Array owned_data; + if (!PEM_read_bio_inner(bp, &owned_name, &owned_header, &owned_data)) { + return 0; + } + if (owned_data.size() > LONG_MAX) { + OPENSSL_PUT_ERROR(PEM, ERR_R_OVERFLOW); + return 0; + } + size_t ulen = 0; + *name = owned_name.release(); + *header = owned_header.release(); + owned_data.Release(data, &ulen); + // Safety: we checked that `ulen` <= `LONG_MAX`. + *len = static_cast(ulen); + return 1; +} + +int PEM_def_callback(char *buf, int size, int enc, void *userdata) { if (!buf || !userdata || size < 0) { return -1; } diff --git a/Sources/CNIOBoringSSL/crypto/pem/pem_oth.cc b/Sources/CNIOBoringSSL/crypto/pem/pem_oth.cc index e4b91525..9bcdfe40 100644 --- a/Sources/CNIOBoringSSL/crypto/pem/pem_oth.cc +++ b/Sources/CNIOBoringSSL/crypto/pem/pem_oth.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -22,17 +27,17 @@ void *PEM_ASN1_read_bio(d2i_of_void *d2i, const char *name, BIO *bp, void **x, pem_password_cb *cb, void *u) { - const unsigned char *p = NULL; - unsigned char *data = NULL; + const unsigned char *p = nullptr; + unsigned char *data = nullptr; long len; - char *ret = NULL; + char *ret = nullptr; - if (!PEM_bytes_read_bio(&data, &len, NULL, name, bp, cb, u)) { - return NULL; + if (!PEM_bytes_read_bio(&data, &len, nullptr, name, bp, cb, u)) { + return nullptr; } p = data; ret = reinterpret_cast(d2i(x, &p, len)); - if (ret == NULL) { + if (ret == nullptr) { OPENSSL_PUT_ERROR(PEM, ERR_R_ASN1_LIB); } OPENSSL_free(data); diff --git a/Sources/CNIOBoringSSL/crypto/pem/pem_pk8.cc b/Sources/CNIOBoringSSL/crypto/pem/pem_pk8.cc index bf57dacf..b73d9a7d 100644 --- a/Sources/CNIOBoringSSL/crypto/pem/pem_pk8.cc +++ b/Sources/CNIOBoringSSL/crypto/pem/pem_pk8.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,6 +22,9 @@ #include #include +#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); @@ -32,7 +40,7 @@ static int do_pk8pkey_fp(FILE *bp, const EVP_PKEY *x, int isder, int nid, 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, NULL, pass, pass_len, cb, 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, @@ -50,7 +58,7 @@ int i2d_PKCS8PrivateKey_bio(BIO *bp, const EVP_PKEY *x, const EVP_CIPHER *enc, 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, NULL, pass, pass_len, cb, 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, @@ -78,7 +86,7 @@ static int do_pk8pkey(BIO *bp, const EVP_PKEY *x, int isder, int nid, pass = buf; } - p8 = PKCS8_encrypt(nid, enc, pass, pass_len, NULL, 0, 0, p8inf); + p8 = PKCS8_encrypt(nid, enc, pass, pass_len, nullptr, 0, 0, p8inf); if (pass == buf) { OPENSSL_cleanse(buf, pass_len); } @@ -103,14 +111,14 @@ static int do_pk8pkey(BIO *bp, const EVP_PKEY *x, int isder, int nid, EVP_PKEY *d2i_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u) { - PKCS8_PRIV_KEY_INFO *p8inf = NULL; - X509_SIG *p8 = NULL; + PKCS8_PRIV_KEY_INFO *p8inf = nullptr; + X509_SIG *p8 = nullptr; int pass_len; EVP_PKEY *ret; char psbuf[PEM_BUFSIZE]; - p8 = d2i_PKCS8_bio(bp, NULL); + p8 = d2i_PKCS8_bio(bp, nullptr); if (!p8) { - return NULL; + return nullptr; } pass_len = 0; @@ -121,18 +129,18 @@ EVP_PKEY *d2i_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, if (pass_len < 0) { OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_PASSWORD_READ); X509_SIG_free(p8); - return NULL; + return nullptr; } p8inf = PKCS8_decrypt(p8, psbuf, pass_len); X509_SIG_free(p8); OPENSSL_cleanse(psbuf, pass_len); if (!p8inf) { - return NULL; + return nullptr; } ret = EVP_PKCS82PKEY(p8inf); PKCS8_PRIV_KEY_INFO_free(p8inf); if (!ret) { - return NULL; + return nullptr; } if (x) { if (*x) { @@ -153,13 +161,13 @@ int i2d_PKCS8PrivateKey_fp(FILE *fp, const EVP_PKEY *x, const EVP_CIPHER *enc, int i2d_PKCS8PrivateKey_nid_fp(FILE *fp, const EVP_PKEY *x, int nid, const char *pass, int pass_len, pem_password_cb *cb, void *u) { - return do_pk8pkey_fp(fp, x, 1, nid, NULL, pass, pass_len, cb, u); + return do_pk8pkey_fp(fp, x, 1, nid, nullptr, pass, pass_len, cb, u); } int PEM_write_PKCS8PrivateKey_nid(FILE *fp, const EVP_PKEY *x, int nid, const char *pass, int pass_len, pem_password_cb *cb, void *u) { - return do_pk8pkey_fp(fp, x, 0, nid, NULL, pass, pass_len, cb, u); + return do_pk8pkey_fp(fp, x, 0, nid, nullptr, pass, pass_len, cb, u); } int PEM_write_PKCS8PrivateKey(FILE *fp, const EVP_PKEY *x, @@ -188,7 +196,7 @@ EVP_PKEY *d2i_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, EVP_PKEY *ret; if (!(bp = BIO_new_fp(fp, BIO_NOCLOSE))) { OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB); - return NULL; + return nullptr; } ret = d2i_PKCS8PrivateKey_bio(bp, x, cb, u); BIO_free(bp); diff --git a/Sources/CNIOBoringSSL/crypto/pem/pem_pkey.cc b/Sources/CNIOBoringSSL/crypto/pem/pem_pkey.cc index 22bfc901..ee6678d9 100644 --- a/Sources/CNIOBoringSSL/crypto/pem/pem_pkey.cc +++ b/Sources/CNIOBoringSSL/crypto/pem/pem_pkey.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -23,20 +28,20 @@ EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u) { - char *nm = NULL; - const unsigned char *p = NULL; - unsigned char *data = NULL; + char *nm = nullptr; + const unsigned char *p = nullptr; + unsigned char *data = nullptr; long len; - EVP_PKEY *ret = NULL; + EVP_PKEY *ret = nullptr; if (!PEM_bytes_read_bio(&data, &len, &nm, PEM_STRING_EVP_PKEY, bp, cb, u)) { - return NULL; + return nullptr; } p = data; if (strcmp(nm, PEM_STRING_PKCS8INF) == 0) { PKCS8_PRIV_KEY_INFO *p8inf; - p8inf = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, len); + p8inf = d2i_PKCS8_PRIV_KEY_INFO(nullptr, &p, len); if (!p8inf) { goto p8err; } @@ -53,7 +58,7 @@ EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, X509_SIG *p8; int pass_len; char psbuf[PEM_BUFSIZE]; - p8 = d2i_X509_SIG(NULL, &p, len); + p8 = d2i_X509_SIG(nullptr, &p, len); if (!p8) { goto p8err; } @@ -62,7 +67,7 @@ EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, if (!cb) { cb = PEM_def_callback; } - pass_len = cb(psbuf, PEM_BUFSIZE, 0, u); + pass_len = cb(psbuf, PEM_BUFSIZE, /*enc=*/0, u); if (pass_len < 0) { OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_PASSWORD_READ); X509_SIG_free(p8); @@ -77,7 +82,7 @@ EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, ret = EVP_PKCS82PKEY(p8inf); if (x) { if (*x) { - EVP_PKEY_free((EVP_PKEY *)*x); + EVP_PKEY_free(*x); } *x = ret; } @@ -91,9 +96,15 @@ EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, ret = d2i_PrivateKey(EVP_PKEY_EC, x, &p, len); } else if (strcmp(nm, PEM_STRING_DSA) == 0) { ret = d2i_PrivateKey(EVP_PKEY_DSA, x, &p, len); + } else { + // `PEM_bytes_read_bio` should not have returned a PEM type this function + // does not recognized. + OPENSSL_PUT_ERROR(PEM, ERR_R_INTERNAL_ERROR); + goto err; } + p8err: - if (ret == NULL) { + if (ret == nullptr) { OPENSSL_PUT_ERROR(PEM, ERR_R_ASN1_LIB); } @@ -103,7 +114,7 @@ err: return ret; } -int PEM_write_bio_PrivateKey(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc, +int PEM_write_bio_PrivateKey(BIO *bp, const EVP_PKEY *x, const EVP_CIPHER *enc, const unsigned char *pass, int pass_len, pem_password_cb *cb, void *u) { return PEM_write_bio_PKCS8PrivateKey(bp, x, enc, (const char *)pass, pass_len, @@ -113,20 +124,20 @@ int PEM_write_bio_PrivateKey(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc, EVP_PKEY *PEM_read_PrivateKey(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u) { BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); - if (b == NULL) { + if (b == nullptr) { OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB); - return NULL; + return nullptr; } EVP_PKEY *ret = PEM_read_bio_PrivateKey(b, x, cb, u); BIO_free(b); return ret; } -int PEM_write_PrivateKey(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc, +int PEM_write_PrivateKey(FILE *fp, const EVP_PKEY *x, const EVP_CIPHER *enc, const unsigned char *pass, int pass_len, pem_password_cb *cb, void *u) { BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); - if (b == NULL) { + if (b == nullptr) { OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB); return 0; } diff --git a/Sources/CNIOBoringSSL/crypto/pem/pem_x509.cc b/Sources/CNIOBoringSSL/crypto/pem/pem_x509.cc index f625f7b3..84f35c2d 100644 --- a/Sources/CNIOBoringSSL/crypto/pem/pem_x509.cc +++ b/Sources/CNIOBoringSSL/crypto/pem/pem_x509.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,4 +19,7 @@ #include #include +#include "internal.h" + + IMPLEMENT_PEM_rw(X509, X509, PEM_STRING_X509, X509) diff --git a/Sources/CNIOBoringSSL/crypto/pem/pem_xaux.cc b/Sources/CNIOBoringSSL/crypto/pem/pem_xaux.cc index 34a2fd40..61e5b9b2 100644 --- a/Sources/CNIOBoringSSL/crypto/pem/pem_xaux.cc +++ b/Sources/CNIOBoringSSL/crypto/pem/pem_xaux.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,4 +19,7 @@ #include #include +#include "internal.h" + + IMPLEMENT_PEM_rw(X509_AUX, X509, PEM_STRING_X509_TRUSTED, X509_AUX) diff --git a/Sources/CNIOBoringSSL/crypto/pkcs7/internal.h b/Sources/CNIOBoringSSL/crypto/pkcs7/internal.h index 8d0044d8..46b39a0a 100644 --- a/Sources/CNIOBoringSSL/crypto/pkcs7/internal.h +++ b/Sources/CNIOBoringSSL/crypto/pkcs7/internal.h @@ -1,58 +1,67 @@ -/* Copyright 2017 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2017 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. -#ifndef OPENSSL_HEADER_PKCS7_INTERNAL_H -#define OPENSSL_HEADER_PKCS7_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_PKCS7_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_PKCS7_INTERNAL_H #include -#if defined(__cplusplus) -extern "C" { -#endif +BSSL_NAMESPACE_BEGIN // 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 +// 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 // pointer that needs to be freed by the caller once they have finished -// processing |*out| (which will be pointing into |*der_bytes|). +// processing `*out` (which will be pointing into `*der_bytes`). // -// It returns one on success or zero on error. On error, |*der_bytes| is +// It returns one on success or zero on error. On error, `*der_bytes` is // NULL. int pkcs7_parse_header(uint8_t **der_bytes, CBS *out, CBS *cbs); -// pkcs7_add_signed_data writes a PKCS#7, SignedData structure to |out|. While +// pkcs7_add_signed_data writes a PKCS#7, SignedData structure to `out`. While // doing so it makes callbacks to let the caller fill in parts of the structure. // All callbacks are ignored if NULL and return one on success or zero on error. // +// signed_data_version: version number of the SignedData structure. In PKCS#7, +// it is always 1. In CMS, it depends on the features used. // digest_algos_cb: may write AlgorithmIdentifiers into the given CBB, which // is a SET of digest algorithms. -// cert_crl_cb: may write the |certificates| or |crls| fields. +// cert_crl_cb: may write the `certificates` or `crls` fields. // (See https://datatracker.ietf.org/doc/html/rfc2315#section-9.1) -// signer_infos_cb: may write the contents of the |signerInfos| field. +// signer_infos_cb: may write the contents of the `signerInfos` field. // (See https://datatracker.ietf.org/doc/html/rfc2315#section-9.1) // // pkcs7_add_signed_data returns one on success or zero on error. -int pkcs7_add_signed_data(CBB *out, - int (*digest_algos_cb)(CBB *out, const void *arg), - int (*cert_crl_cb)(CBB *out, const void *arg), - int (*signer_infos_cb)(CBB *out, const void *arg), - const void *arg); +int pkcs7_add_signed_data(CBB *out, uint64_t signed_data_version, + int (*digest_algos_cb)(CBB *out, void *arg), + int (*cert_crl_cb)(CBB *out, void *arg), + int (*signer_infos_cb)(CBB *out, void *arg), + void *arg); +// pkcs7_add_external_signature writes a PKCS#7 or CMS SignedData structure to +// `out`, containing an external (i.e. the contents are not included) signature, +// using `sign_cert` and `key` to sign the contents of `data` with `md`. If +// `use_key_id` is true (CMS-only), the SignerInfo specifies the signer with key +// identifier. Otherwise, it uses issuer and serial number (PKCS#7 or CMS v1). +// The SignedData will have no embedded certificates and no attributes. +// +// 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); -#if defined(__cplusplus) -} // extern C -#endif +BSSL_NAMESPACE_END -#endif // OPENSSL_HEADER_PKCS7_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_PKCS7_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/pkcs7/pkcs7.cc b/Sources/CNIOBoringSSL/crypto/pkcs7/pkcs7.cc index 66efdbe0..d535bf3b 100644 --- a/Sources/CNIOBoringSSL/crypto/pkcs7/pkcs7.cc +++ b/Sources/CNIOBoringSSL/crypto/pkcs7/pkcs7.cc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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 @@ -24,6 +24,8 @@ #include "internal.h" +using namespace bssl; + // 1.2.840.113549.1.7.1 static const uint8_t kPKCS7Data[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01}; @@ -33,19 +35,19 @@ static const uint8_t kPKCS7SignedData[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02}; // 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 +// 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 // pointer that needs to be freed by the caller once they have finished -// processing |*out| (which will be pointing into |*der_bytes|). +// processing `*out` (which will be pointing into `*der_bytes`). // -// It returns one on success or zero on error. On error, |*der_bytes| is +// It returns one on success or zero on error. On error, `*der_bytes` is // NULL. -int pkcs7_parse_header(uint8_t **der_bytes, CBS *out, CBS *cbs) { +int bssl::pkcs7_parse_header(uint8_t **der_bytes, CBS *out, CBS *cbs) { CBS in, content_info, content_type, wrapped_signed_data, signed_data; uint64_t version; // The input may be in BER format. - *der_bytes = NULL; + *der_bytes = nullptr; if (!CBS_asn1_ber_to_der(cbs, &in, der_bytes) || // See https://tools.ietf.org/html/rfc2315#section-7 !CBS_get_asn1(&in, &content_info, CBS_ASN1_SEQUENCE) || @@ -64,8 +66,8 @@ int pkcs7_parse_header(uint8_t **der_bytes, CBS *out, CBS *cbs) { CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) || !CBS_get_asn1(&wrapped_signed_data, &signed_data, CBS_ASN1_SEQUENCE) || !CBS_get_asn1_uint64(&signed_data, &version) || - !CBS_get_asn1(&signed_data, NULL /* digests */, CBS_ASN1_SET) || - !CBS_get_asn1(&signed_data, NULL /* content */, CBS_ASN1_SEQUENCE)) { + !CBS_get_asn1(&signed_data, nullptr /* digests */, CBS_ASN1_SET) || + !CBS_get_asn1(&signed_data, nullptr /* content */, CBS_ASN1_SEQUENCE)) { goto err; } @@ -79,14 +81,14 @@ int pkcs7_parse_header(uint8_t **der_bytes, CBS *out, CBS *cbs) { err: OPENSSL_free(*der_bytes); - *der_bytes = NULL; + *der_bytes = nullptr; return 0; } int PKCS7_get_raw_certificates(STACK_OF(CRYPTO_BUFFER) *out_certs, CBS *cbs, CRYPTO_BUFFER_POOL *pool) { CBS signed_data, certificates; - uint8_t *der_bytes = NULL; + uint8_t *der_bytes = nullptr; int ret = 0, has_certificates; const size_t initial_certs_len = sk_CRYPTO_BUFFER_num(out_certs); @@ -99,7 +101,7 @@ int PKCS7_get_raw_certificates(STACK_OF(CRYPTO_BUFFER) *out_certs, CBS *cbs, } if (!has_certificates) { - CBS_init(&certificates, NULL, 0); + CBS_init(&certificates, nullptr, 0); } while (CBS_len(&certificates) > 0) { @@ -109,7 +111,7 @@ int PKCS7_get_raw_certificates(STACK_OF(CRYPTO_BUFFER) *out_certs, CBS *cbs, } CRYPTO_BUFFER *buf = CRYPTO_BUFFER_new_from_CBS(&cert, pool); - if (buf == NULL || !sk_CRYPTO_BUFFER_push(out_certs, buf)) { + if (buf == nullptr || !sk_CRYPTO_BUFFER_push(out_certs, buf)) { CRYPTO_BUFFER_free(buf); goto err; } @@ -130,7 +132,7 @@ err: return ret; } -static int pkcs7_bundle_raw_certificates_cb(CBB *out, const void *arg) { +static int pkcs7_bundle_raw_certificates_cb(CBB *out, void *arg) { const STACK_OF(CRYPTO_BUFFER) *certs = reinterpret_cast(arg); CBB certificates; @@ -149,43 +151,46 @@ static int pkcs7_bundle_raw_certificates_cb(CBB *out, const void *arg) { } } - // |certificates| is a implicitly-tagged SET OF. + // `certificates` is an implicitly-tagged SET OF. return CBB_flush_asn1_set_of(&certificates) && CBB_flush(out); } int PKCS7_bundle_raw_certificates(CBB *out, const STACK_OF(CRYPTO_BUFFER) *certs) { - return pkcs7_add_signed_data(out, /*digest_algos_cb=*/NULL, + return pkcs7_add_signed_data(out, /*signed_data_version=*/1, + /*digest_algos_cb=*/nullptr, pkcs7_bundle_raw_certificates_cb, - /*signer_infos_cb=*/NULL, certs); + /*signer_infos_cb=*/nullptr, + const_cast(certs)); } -int pkcs7_add_signed_data(CBB *out, - int (*digest_algos_cb)(CBB *out, const void *arg), - int (*cert_crl_cb)(CBB *out, const void *arg), - int (*signer_infos_cb)(CBB *out, const void *arg), - const void *arg) { - CBB outer_seq, oid, wrapped_seq, seq, version_bytes, digest_algos_set, - content_info, signer_infos; +int bssl::pkcs7_add_signed_data(CBB *out, uint64_t signed_data_version, + int (*digest_algos_cb)(CBB *out, void *arg), + int (*cert_crl_cb)(CBB *out, void *arg), + int (*signer_infos_cb)(CBB *out, void *arg), + void *arg) { + CBB outer_seq, wrapped_seq, seq, digest_algos_set, content_info, signer_infos; // See https://tools.ietf.org/html/rfc2315#section-7 if (!CBB_add_asn1(out, &outer_seq, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&outer_seq, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, kPKCS7SignedData, sizeof(kPKCS7SignedData)) || + !CBB_add_asn1_element(&outer_seq, CBS_ASN1_OBJECT, kPKCS7SignedData, + sizeof(kPKCS7SignedData)) || !CBB_add_asn1(&outer_seq, &wrapped_seq, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) || // See https://tools.ietf.org/html/rfc2315#section-9.1 !CBB_add_asn1(&wrapped_seq, &seq, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&seq, &version_bytes, CBS_ASN1_INTEGER) || - !CBB_add_u8(&version_bytes, 1) || + !CBB_add_asn1_uint64(&seq, signed_data_version) || !CBB_add_asn1(&seq, &digest_algos_set, CBS_ASN1_SET) || - (digest_algos_cb != NULL && !digest_algos_cb(&digest_algos_set, arg)) || + (digest_algos_cb != nullptr && + !digest_algos_cb(&digest_algos_set, arg)) || + !CBB_flush_asn1_set_of(&digest_algos_set) || !CBB_add_asn1(&seq, &content_info, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&content_info, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, kPKCS7Data, sizeof(kPKCS7Data)) || - (cert_crl_cb != NULL && !cert_crl_cb(&seq, arg)) || + !CBB_add_asn1_element(&content_info, CBS_ASN1_OBJECT, kPKCS7Data, + sizeof(kPKCS7Data)) || + (cert_crl_cb != nullptr && !cert_crl_cb(&seq, arg)) || !CBB_add_asn1(&seq, &signer_infos, CBS_ASN1_SET) || - (signer_infos_cb != NULL && !signer_infos_cb(&signer_infos, arg))) { + (signer_infos_cb != nullptr && !signer_infos_cb(&signer_infos, arg)) || + !CBB_flush_asn1_set_of(&signer_infos)) { return 0; } diff --git a/Sources/CNIOBoringSSL/crypto/pkcs7/pkcs7_x509.cc b/Sources/CNIOBoringSSL/crypto/pkcs7/pkcs7_x509.cc index e68593e0..cedf4841 100644 --- a/Sources/CNIOBoringSSL/crypto/pkcs7/pkcs7_x509.cc +++ b/Sources/CNIOBoringSSL/crypto/pkcs7/pkcs7_x509.cc @@ -1,24 +1,28 @@ -/* Copyright 2017 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2017 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 @@ -26,22 +30,27 @@ #include #include +#include "../asn1/internal.h" #include "../internal.h" +#include "../mem_internal.h" +#include "../x509/internal.h" #include "internal.h" +using namespace bssl; + int PKCS7_get_certificates(STACK_OF(X509) *out_certs, CBS *cbs) { int ret = 0; const size_t initial_certs_len = sk_X509_num(out_certs); STACK_OF(CRYPTO_BUFFER) *raw = sk_CRYPTO_BUFFER_new_null(); - if (raw == NULL || !PKCS7_get_raw_certificates(raw, cbs, NULL)) { + if (raw == nullptr || !PKCS7_get_raw_certificates(raw, cbs, nullptr)) { goto err; } for (size_t i = 0; i < sk_CRYPTO_BUFFER_num(raw); i++) { CRYPTO_BUFFER *buf = sk_CRYPTO_BUFFER_value(raw, i); X509 *x509 = X509_parse_from_buffer(buf); - if (x509 == NULL || !sk_X509_push(out_certs, x509)) { + if (x509 == nullptr || !sk_X509_push(out_certs, x509)) { X509_free(x509); goto err; } @@ -63,7 +72,7 @@ err: int PKCS7_get_CRLs(STACK_OF(X509_CRL) *out_crls, CBS *cbs) { CBS signed_data, crls; - uint8_t *der_bytes = NULL; + uint8_t *der_bytes = nullptr; int ret = 0, has_crls; const size_t initial_crls_len = sk_X509_CRL_num(out_crls); @@ -72,7 +81,7 @@ int PKCS7_get_CRLs(STACK_OF(X509_CRL) *out_crls, CBS *cbs) { // Even if only CRLs are included, there may be an empty certificates // block. OpenSSL does this, for example. !CBS_get_optional_asn1( - &signed_data, NULL, NULL, + &signed_data, nullptr, nullptr, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) || !CBS_get_optional_asn1( &signed_data, &crls, &has_crls, @@ -81,7 +90,7 @@ int PKCS7_get_CRLs(STACK_OF(X509_CRL) *out_crls, CBS *cbs) { } if (!has_crls) { - CBS_init(&crls, NULL, 0); + CBS_init(&crls, nullptr, 0); } while (CBS_len(&crls) > 0) { @@ -97,7 +106,7 @@ int PKCS7_get_CRLs(STACK_OF(X509_CRL) *out_crls, CBS *cbs) { goto err; } inp = CBS_data(&crl_data); - crl = d2i_X509_CRL(NULL, &inp, (long)CBS_len(&crl_data)); + crl = d2i_X509_CRL(nullptr, &inp, (long)CBS_len(&crl_data)); if (!crl) { goto err; } @@ -132,10 +141,10 @@ int PKCS7_get_PEM_certificates(STACK_OF(X509) *out_certs, BIO *pem_bio) { // Even though we pass PEM_STRING_PKCS7 as the expected PEM type here, PEM // internally will actually allow several other values too, including // "CERTIFICATE". - if (!PEM_bytes_read_bio(&data, &len, NULL /* PEM type output */, + if (!PEM_bytes_read_bio(&data, &len, nullptr /* PEM type output */, PEM_STRING_PKCS7, pem_bio, - NULL /* password callback */, - NULL /* password callback argument */)) { + nullptr /* password callback */, + nullptr /* password callback argument */)) { return 0; } @@ -154,10 +163,10 @@ int PKCS7_get_PEM_CRLs(STACK_OF(X509_CRL) *out_crls, BIO *pem_bio) { // Even though we pass PEM_STRING_PKCS7 as the expected PEM type here, PEM // internally will actually allow several other values too, including // "CERTIFICATE". - if (!PEM_bytes_read_bio(&data, &len, NULL /* PEM type output */, + if (!PEM_bytes_read_bio(&data, &len, nullptr /* PEM type output */, PEM_STRING_PKCS7, pem_bio, - NULL /* password callback */, - NULL /* password callback argument */)) { + nullptr /* password callback */, + nullptr /* password callback argument */)) { return 0; } @@ -168,8 +177,8 @@ int PKCS7_get_PEM_CRLs(STACK_OF(X509_CRL) *out_crls, BIO *pem_bio) { return ret; } -static int pkcs7_bundle_certificates_cb(CBB *out, const void *arg) { - const STACK_OF(X509) *certs = reinterpret_cast(arg); +static int pkcs7_bundle_certificates_cb(CBB *out, void *arg) { + auto *certs = static_cast(arg); size_t i; CBB certificates; @@ -182,7 +191,7 @@ static int pkcs7_bundle_certificates_cb(CBB *out, const void *arg) { for (i = 0; i < sk_X509_num(certs); i++) { X509 *x509 = sk_X509_value(certs, i); uint8_t *buf; - int len = i2d_X509(x509, NULL); + int len = i2d_X509(x509, nullptr); if (len < 0 || !CBB_add_space(&certificates, &buf, len) || i2d_X509(x509, &buf) < 0) { @@ -190,19 +199,19 @@ static int pkcs7_bundle_certificates_cb(CBB *out, const void *arg) { } } - // |certificates| is a implicitly-tagged SET OF. + // `certificates` is an implicitly-tagged SET OF. return CBB_flush_asn1_set_of(&certificates) && CBB_flush(out); } int PKCS7_bundle_certificates(CBB *out, const STACK_OF(X509) *certs) { - return pkcs7_add_signed_data(out, /*digest_algos_cb=*/NULL, - pkcs7_bundle_certificates_cb, - /*signer_infos_cb=*/NULL, certs); + return pkcs7_add_signed_data( + out, /*signed_data_version=*/1, + /*digest_algos_cb=*/nullptr, pkcs7_bundle_certificates_cb, + /*signer_infos_cb=*/nullptr, const_cast(certs)); } -static int pkcs7_bundle_crls_cb(CBB *out, const void *arg) { - const STACK_OF(X509_CRL) *crls = - reinterpret_cast(arg); +static int pkcs7_bundle_crls_cb(CBB *out, void *arg) { + auto *crls = static_cast(arg); size_t i; CBB crl_data; @@ -215,7 +224,7 @@ static int pkcs7_bundle_crls_cb(CBB *out, const void *arg) { for (i = 0; i < sk_X509_CRL_num(crls); i++) { X509_CRL *crl = sk_X509_CRL_value(crls, i); uint8_t *buf; - int len = i2d_X509_CRL(crl, NULL); + int len = i2d_X509_CRL(crl, nullptr); if (len < 0 || !CBB_add_space(&crl_data, &buf, len) || i2d_X509_CRL(crl, &buf) < 0) { @@ -223,31 +232,31 @@ static int pkcs7_bundle_crls_cb(CBB *out, const void *arg) { } } - // |crl_data| is a implicitly-tagged SET OF. + // `crl_data` is an implicitly-tagged SET OF. return CBB_flush_asn1_set_of(&crl_data) && CBB_flush(out); } int PKCS7_bundle_CRLs(CBB *out, const STACK_OF(X509_CRL) *crls) { - return pkcs7_add_signed_data(out, /*digest_algos_cb=*/NULL, - pkcs7_bundle_crls_cb, - /*signer_infos_cb=*/NULL, crls); + return pkcs7_add_signed_data( + out, /*signed_data_version=*/1, + /*digest_algos_cb=*/nullptr, pkcs7_bundle_crls_cb, + /*signer_infos_cb=*/nullptr, const_cast(crls)); } static PKCS7 *pkcs7_new(CBS *cbs) { CBS copy = *cbs, copy2 = *cbs; - PKCS7 *ret = reinterpret_cast(OPENSSL_zalloc(sizeof(PKCS7))); - if (ret == NULL) { - return NULL; + PKCS7 *ret = New(); + if (ret == nullptr) { + return nullptr; } ret->type = OBJ_nid2obj(NID_pkcs7_signed); - ret->d.sign = - reinterpret_cast(OPENSSL_malloc(sizeof(PKCS7_SIGNED))); - if (ret->d.sign == NULL) { + ret->d.sign = New(); + if (ret->d.sign == nullptr) { goto err; } ret->d.sign->cert = sk_X509_new_null(); ret->d.sign->crl = sk_X509_CRL_new_null(); - if (ret->d.sign->cert == NULL || ret->d.sign->crl == NULL || + if (ret->d.sign->cert == nullptr || ret->d.sign->crl == nullptr || !PKCS7_get_certificates(ret->d.sign->cert, ©) || !PKCS7_get_CRLs(ret->d.sign->crl, cbs)) { goto err; @@ -255,18 +264,18 @@ static PKCS7 *pkcs7_new(CBS *cbs) { if (sk_X509_num(ret->d.sign->cert) == 0) { sk_X509_free(ret->d.sign->cert); - ret->d.sign->cert = NULL; + ret->d.sign->cert = nullptr; } if (sk_X509_CRL_num(ret->d.sign->crl) == 0) { sk_X509_CRL_free(ret->d.sign->crl); - ret->d.sign->crl = NULL; + ret->d.sign->crl = nullptr; } ret->ber_len = CBS_len(©2) - CBS_len(cbs); ret->ber_bytes = reinterpret_cast( OPENSSL_memdup(CBS_data(©2), ret->ber_len)); - if (ret->ber_bytes == NULL) { + if (ret->ber_bytes == nullptr) { goto err; } @@ -274,18 +283,18 @@ static PKCS7 *pkcs7_new(CBS *cbs) { err: PKCS7_free(ret); - return NULL; + return nullptr; } PKCS7 *d2i_PKCS7(PKCS7 **out, const uint8_t **inp, size_t len) { CBS cbs; CBS_init(&cbs, *inp, len); PKCS7 *ret = pkcs7_new(&cbs); - if (ret == NULL) { - return NULL; + if (ret == nullptr) { + return nullptr; } *inp = CBS_data(&cbs); - if (out != NULL) { + if (out != nullptr) { PKCS7_free(*out); *out = ret; } @@ -298,14 +307,14 @@ PKCS7 *d2i_PKCS7_bio(BIO *bio, PKCS7 **out) { uint8_t *data; size_t len; if (!BIO_read_asn1(bio, &data, &len, kMaxSize)) { - return NULL; + return nullptr; } CBS cbs; CBS_init(&cbs, data, len); PKCS7 *ret = pkcs7_new(&cbs); OPENSSL_free(data); - if (out != NULL && ret != NULL) { + if (out != nullptr && ret != nullptr) { PKCS7_free(*out); *out = ret; } @@ -318,14 +327,14 @@ int i2d_PKCS7(const PKCS7 *p7, uint8_t **out) { return -1; } - if (out == NULL) { + if (out == nullptr) { return (int)p7->ber_len; } - if (*out == NULL) { + if (*out == nullptr) { *out = reinterpret_cast(OPENSSL_memdup(p7->ber_bytes, p7->ber_len)); - if (*out == NULL) { + if (*out == nullptr) { return -1; } } else { @@ -340,19 +349,19 @@ int i2d_PKCS7_bio(BIO *bio, const PKCS7 *p7) { } void PKCS7_free(PKCS7 *p7) { - if (p7 == NULL) { + if (p7 == nullptr) { return; } OPENSSL_free(p7->ber_bytes); ASN1_OBJECT_free(p7->type); // We only supported signed data. - if (p7->d.sign != NULL) { + if (p7->d.sign != nullptr) { sk_X509_pop_free(p7->d.sign->cert, X509_free); sk_X509_CRL_pop_free(p7->d.sign->crl, X509_CRL_free); - OPENSSL_free(p7->d.sign); + Delete(p7->d.sign); } - OPENSSL_free(p7); + Delete(p7); } // We only support signed data, so these getters are no-ops. @@ -363,164 +372,156 @@ 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; } -// write_sha256_ai writes an AlgorithmIdentifier for SHA-256 to -// |digest_algos_set|. -static int write_sha256_ai(CBB *digest_algos_set, const void *arg) { - CBB seq; - return CBB_add_asn1(digest_algos_set, &seq, CBS_ASN1_SEQUENCE) && - OBJ_nid2cbb(&seq, NID_sha256) && // - // https://datatracker.ietf.org/doc/html/rfc5754#section-2 - // "Implementations MUST generate SHA2 AlgorithmIdentifiers with absent - // parameters." - CBB_flush(digest_algos_set); -} - -// sign_sha256 writes at most |max_out_sig| bytes of the signature of |data| by -// |pkey| to |out_sig| and sets |*out_sig_len| to the number of bytes written. -// It returns one on success or zero on error. -static int sign_sha256(uint8_t *out_sig, size_t *out_sig_len, - size_t max_out_sig, EVP_PKEY *pkey, BIO *data) { - static const size_t kBufSize = 4096; - uint8_t *buffer = reinterpret_cast(OPENSSL_malloc(kBufSize)); - if (!buffer) { - return 0; - } - - EVP_MD_CTX ctx; - EVP_MD_CTX_init(&ctx); - - int ret = 0; - if (!EVP_DigestSignInit(&ctx, NULL, EVP_sha256(), NULL, pkey)) { - goto out; - } - +static bool digest_sign_update(EVP_MD_CTX *ctx, BIO *data) { for (;;) { - const int n = BIO_read(data, buffer, kBufSize); + uint8_t buf[4096]; + const int n = BIO_read(data, buf, sizeof(buf)); if (n == 0) { - break; - } else if (n < 0 || !EVP_DigestSignUpdate(&ctx, buffer, n)) { - goto out; + return true; + } else if (n < 0 || !EVP_DigestSignUpdate(ctx, buf, n)) { + return false; } } - - *out_sig_len = max_out_sig; - if (!EVP_DigestSignFinal(&ctx, out_sig, out_sig_len)) { - goto out; - } - - ret = 1; - -out: - EVP_MD_CTX_cleanup(&ctx); - OPENSSL_free(buffer); - return ret; } namespace { struct signer_info_data { - const X509 *sign_cert; - uint8_t *signature; - size_t signature_len; + 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) { + auto *si_data = static_cast(arg); + // https://www.rfc-editor.org/rfc/rfc5754.html#section-2 + // "Implementations MUST generate SHA2 AlgorithmIdentifiers with absent + // parameters." + return EVP_marshal_digest_algorithm_no_params( + digest_algos_set, EVP_MD_CTX_get0_md(si_data->sign_ctx.get())); +} + // write_signer_info writes the SignerInfo structure from -// https://datatracker.ietf.org/doc/html/rfc2315#section-9.2 to |out|. It -// returns one on success or zero on error. -static int write_signer_info(CBB *out, const void *arg) { - const struct signer_info_data *const si_data = - reinterpret_cast(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) { + auto *si_data = static_cast(arg); - int ret = 0; - uint8_t *subject_bytes = NULL; - uint8_t *serial_bytes = NULL; - - const int subject_len = - i2d_X509_NAME(X509_get_subject_name(si_data->sign_cert), &subject_bytes); - const int serial_len = i2d_ASN1_INTEGER( - (ASN1_INTEGER *)X509_get0_serialNumber(si_data->sign_cert), - &serial_bytes); - - CBB seq, issuer_and_serial, signing_algo, null, signature; - if (subject_len < 0 || serial_len < 0 || - !CBB_add_asn1(out, &seq, CBS_ASN1_SEQUENCE) || - // version - !CBB_add_asn1_uint64(&seq, 1) || - !CBB_add_asn1(&seq, &issuer_and_serial, CBS_ASN1_SEQUENCE) || - !CBB_add_bytes(&issuer_and_serial, subject_bytes, subject_len) || - !CBB_add_bytes(&issuer_and_serial, serial_bytes, serial_len) || - !write_sha256_ai(&seq, NULL) || - !CBB_add_asn1(&seq, &signing_algo, CBS_ASN1_SEQUENCE) || - !OBJ_nid2cbb(&signing_algo, NID_rsaEncryption) || - !CBB_add_asn1(&signing_algo, &null, CBS_ASN1_NULL) || - !CBB_add_asn1(&seq, &signature, CBS_ASN1_OCTETSTRING) || - !CBB_add_bytes(&signature, si_data->signature, si_data->signature_len) || - !CBB_flush(out)) { - goto out; + uint64_t version = si_data->use_key_id ? 3u : 1u; + CBB seq, child, signing_algo, null, signature; + if (!CBB_add_asn1(out, &seq, CBS_ASN1_SEQUENCE) || + !CBB_add_asn1_uint64(&seq, version)) { + return 0; } - ret = 1; + // Output the SignerIdentifier. + if (si_data->use_key_id) { + const ASN1_OCTET_STRING *skid = + X509_get0_subject_key_id(si_data->sign_cert); + if (skid == nullptr) { + OPENSSL_PUT_ERROR(CMS, CMS_R_CERTIFICATE_HAS_NO_KEYID); + return 0; + } + // subjectKeyIdentifier is implicitly-tagged. + if (!CBB_add_asn1_element(&seq, CBS_ASN1_CONTEXT_SPECIFIC | 0, + ASN1_STRING_get0_data(skid), + ASN1_STRING_length(skid))) { + return 0; + } + } else { + if (!CBB_add_asn1(&seq, &child, CBS_ASN1_SEQUENCE) || + !x509_marshal_name(&child, X509_get_issuer_name(si_data->sign_cert)) || + !asn1_marshal_integer(&child, + X509_get0_serialNumber(si_data->sign_cert), + /*tag=*/0)) { + return 0; + } + } -out: - OPENSSL_free(subject_bytes); - OPENSSL_free(serial_bytes); - return ret; + // Output the digest and signature algorithm. This cannot use X.509 signature + // algorithms because CMS incorrectly decomposes signature algorithms into a + // combination of digesting and "encrypting" the digest, then uses the plain + // rsaEncryption OID instead of the hash-specific RSA OIDs. For now, we only + // support RSA. + EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(si_data->sign_ctx->pctx); + if (EVP_PKEY_id(pkey) != EVP_PKEY_RSA) { + OPENSSL_PUT_ERROR(PKCS7, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return 0; + } + if (!EVP_marshal_digest_algorithm_no_params( + &seq, EVP_MD_CTX_get0_md(si_data->sign_ctx.get())) || + !CBB_add_asn1(&seq, &signing_algo, CBS_ASN1_SEQUENCE) || + !OBJ_nid2cbb(&signing_algo, NID_rsaEncryption) || + !CBB_add_asn1(&signing_algo, &null, CBS_ASN1_NULL)) { + return 0; + } + + // Output the signature. + uint8_t *ptr; + size_t sig_len; + if (!EVP_DigestSignFinal(si_data->sign_ctx.get(), nullptr, &sig_len) || + !CBB_add_asn1(&seq, &signature, CBS_ASN1_OCTETSTRING) || + !CBB_reserve(&signature, &ptr, sig_len) || + !EVP_DigestSignFinal(si_data->sign_ctx.get(), ptr, &sig_len) || + !CBB_did_write(&signature, sig_len) || // + !CBB_flush(out)) { + return 0; + } + + 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) { + signer_info_data si_data; + si_data.use_key_id = use_key_id; + si_data.sign_cert = sign_cert; + + // Set up the signature. + if (!EVP_DigestSignInit(si_data.sign_ctx.get(), nullptr, md, nullptr, key) || + !digest_sign_update(si_data.sign_ctx.get(), data)) { + return 0; + } + + // See RFC 5652, Section 5.1. When no certificates are present, the version + // comes from the highest SignerInfo version, which will be 3 (CMS) for a key + // ID, and 1 (CMS or PKCS#7) for issuer and serial. + uint64_t signed_data_version = use_key_id ? 3u : 1u; + return pkcs7_add_signed_data( + out, signed_data_version, write_signer_digest_algos, + /*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) { - CBB cbb; - if (!CBB_init(&cbb, 2048)) { - return NULL; + ScopedCBB cbb; + if (!CBB_init(cbb.get(), 2048)) { + return nullptr; } - uint8_t *der = NULL; - size_t len; - PKCS7 *ret = NULL; - - if (sign_cert == NULL && pkey == NULL && flags == PKCS7_DETACHED) { + if (sign_cert == nullptr && pkey == nullptr && flags == PKCS7_DETACHED) { // Caller just wants to bundle certificates. - if (!PKCS7_bundle_certificates(&cbb, certs)) { - goto out; + if (!PKCS7_bundle_certificates(cbb.get(), certs)) { + return nullptr; } - } else if (sign_cert != NULL && pkey != NULL && certs == NULL && - data != NULL && + } else if (sign_cert != nullptr && pkey != nullptr && certs == nullptr && + data != nullptr && flags == (PKCS7_NOATTR | PKCS7_BINARY | PKCS7_NOCERTS | - PKCS7_DETACHED) && - EVP_PKEY_id(pkey) == NID_rsaEncryption) { - // sign-file.c from the Linux kernel. - const size_t signature_max_len = EVP_PKEY_size(pkey); - struct signer_info_data si_data = { - /*sign_cert=*/sign_cert, - /*signature=*/ - reinterpret_cast(OPENSSL_malloc(signature_max_len)), - /*signature_len=*/0, - }; - - if (!si_data.signature || - !sign_sha256(si_data.signature, &si_data.signature_len, - signature_max_len, pkey, data) || - !pkcs7_add_signed_data(&cbb, write_sha256_ai, /*cert_crl_cb=*/NULL, - write_signer_info, &si_data)) { - OPENSSL_free(si_data.signature); - goto out; + PKCS7_DETACHED)) { + // In OpenSSL, this API signs with some default hash. That default has been + // SHA-256 since 2015. + if (!pkcs7_add_external_signature(cbb.get(), sign_cert, pkey, EVP_sha256(), + data, /*use_key_id=*/false)) { + return nullptr; } - OPENSSL_free(si_data.signature); } else { OPENSSL_PUT_ERROR(PKCS7, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); - goto out; - } - - if (!CBB_finish(&cbb, &der, &len)) { - goto out; + return nullptr; } CBS cbs; - CBS_init(&cbs, der, len); - ret = pkcs7_new(&cbs); - -out: - CBB_cleanup(&cbb); - OPENSSL_free(der); - return ret; + CBS_init(&cbs, CBB_data(cbb.get()), CBB_len(cbb.get())); + return pkcs7_new(&cbs); } diff --git a/Sources/CNIOBoringSSL/crypto/pkcs8/internal.h b/Sources/CNIOBoringSSL/crypto/pkcs8/internal.h index 67a69667..a56fe34a 100644 --- a/Sources/CNIOBoringSSL/crypto/pkcs8/internal.h +++ b/Sources/CNIOBoringSSL/crypto/pkcs8/internal.h @@ -1,22 +1,23 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. -#ifndef OPENSSL_HEADER_PKCS8_INTERNAL_H -#define OPENSSL_HEADER_PKCS8_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_PKCS8_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_PKCS8_INTERNAL_H #include #include -#if defined(__cplusplus) -extern "C" { -#endif - struct pkcs8_priv_key_info_st { ASN1_INTEGER *version; @@ -25,9 +26,11 @@ struct pkcs8_priv_key_info_st { STACK_OF(X509_ATTRIBUTE) *attributes; }; -// pkcs8_pbe_decrypt decrypts |in| using the PBE scheme described by -// |algorithm|, which should be a serialized AlgorithmIdentifier structure. On -// success, it sets |*out| to a newly-allocated buffer containing the decrypted +BSSL_NAMESPACE_BEGIN + +// pkcs8_pbe_decrypt decrypts `in` using the PBE scheme described by +// `algorithm`, which should be a serialized AlgorithmIdentifier structure. On +// success, it sets `*out` to a newly-allocated buffer containing the decrypted // result and returns one. Otherwise, it returns zero. int pkcs8_pbe_decrypt(uint8_t **out, size_t *out_len, CBS *algorithm, const char *pass, size_t pass_len, const uint8_t *in, @@ -38,28 +41,30 @@ int pkcs8_pbe_decrypt(uint8_t **out, size_t *out_len, CBS *algorithm, #define PKCS12_MAC_ID 3 // pkcs12_key_gen runs the PKCS#12 key derivation function as specified in -// RFC 7292, appendix B. On success, it writes the resulting |out_len| bytes of -// key material to |out| and returns one. Otherwise, it returns zero. |id| -// should be one of the |PKCS12_*_ID| values. +// RFC 7292, appendix B. On success, it writes the resulting `out_len` bytes of +// key material to `out` and returns one. Otherwise, it returns zero. `id` +// should be one of the `PKCS12_*_ID` values. int 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); -// pkcs12_pbe_encrypt_init configures |ctx| for encrypting with a PBES1 scheme -// defined in PKCS#12. It writes the corresponding AlgorithmIdentifier to |out|. -int pkcs12_pbe_encrypt_init(CBB *out, EVP_CIPHER_CTX *ctx, int alg, - uint32_t iterations, const char *pass, - size_t pass_len, const uint8_t *salt, - size_t salt_len); +// pkcs12_pbe_encrypt_init configures `ctx` for encrypting with a PBES1 scheme +// defined in PKCS#12, or a PBES2 scheme defined in PKCS#5. The algorithm is +// determined as in `PKCS8_encrypt`. It writes the corresponding +// AlgorithmIdentifier to `out`. +int pkcs12_pbe_encrypt_init(CBB *out, EVP_CIPHER_CTX *ctx, int alg_nid, + const EVP_CIPHER *alg_cipher, uint32_t iterations, + const char *pass, size_t pass_len, + const uint8_t *salt, size_t salt_len); struct pbe_suite { int pbe_nid; uint8_t oid[10]; uint8_t oid_len; - const EVP_CIPHER *(*cipher_func)(void); - const EVP_MD *(*md_func)(void); - // decrypt_init initialize |ctx| for decrypting. The password is specified by - // |pass| and |pass_len|. |param| contains the serialized parameters field of + const EVP_CIPHER *(*cipher_func)(); + const EVP_MD *(*md_func)(); + // decrypt_init initialize `ctx` for decrypting. The password is specified by + // `pass` and `pass_len`. `param` contains the serialized parameters field of // the AlgorithmIdentifier. // // It returns one on success and zero on error. @@ -67,26 +72,27 @@ struct pbe_suite { const char *pass, size_t pass_len, CBS *param); }; -#define PKCS5_SALT_LEN 8 +#define PKCS5_SALT_LEN 16 + +// pkcs5_pbe2_nid_to_cipher returns the `EVP_CIPHER` for `nid` if `nid` is +// supported with PKCS#5 PBES2, and nullptr otherwise. +const EVP_CIPHER *pkcs5_pbe2_nid_to_cipher(int nid); int PKCS5_pbe2_decrypt_init(const struct pbe_suite *suite, EVP_CIPHER_CTX *ctx, const char *pass, size_t pass_len, CBS *param); -// PKCS5_pbe2_encrypt_init configures |ctx| for encrypting with PKCS #5 PBES2, +// PKCS5_pbe2_encrypt_init configures `ctx` for encrypting with PKCS #5 PBES2, // as defined in RFC 2998, with the specified parameters. It writes the -// corresponding AlgorithmIdentifier to |out|. +// corresponding AlgorithmIdentifier to `out`. int PKCS5_pbe2_encrypt_init(CBB *out, EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, uint32_t iterations, const char *pass, size_t pass_len, const uint8_t *salt, size_t salt_len); -// pkcs12_iterations_acceptable returns one if |iterations| is a reasonable +// pkcs12_iterations_acceptable returns one if `iterations` is a reasonable // number of PBKDF2 iterations and zero otherwise. int pkcs12_iterations_acceptable(uint64_t iterations); +BSSL_NAMESPACE_END -#if defined(__cplusplus) -} // extern C -#endif - -#endif // OPENSSL_HEADER_PKCS8_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_PKCS8_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/pkcs8/p5_pbev2.cc b/Sources/CNIOBoringSSL/crypto/pkcs8/p5_pbev2.cc index 36e1f0d3..90607e53 100644 --- a/Sources/CNIOBoringSSL/crypto/pkcs8/p5_pbev2.cc +++ b/Sources/CNIOBoringSSL/crypto/pkcs8/p5_pbev2.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,15 +19,18 @@ #include #include +#include #include #include #include #include -#include "internal.h" #include "../internal.h" +#include "internal.h" +using namespace bssl; + // 1.2.840.113549.1.5.12 static const uint8_t kPBKDF2[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0c}; @@ -43,7 +51,7 @@ static const struct { uint8_t oid[9]; uint8_t oid_len; int nid; - const EVP_CIPHER *(*cipher_func)(void); + const EVP_CIPHER *(*cipher_func)(); } kCipherOIDs[] = { // 1.2.840.113549.3.2 {{0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x03, 0x02}, @@ -73,23 +81,20 @@ static const struct { }; static const EVP_CIPHER *cbs_to_cipher(const CBS *cbs) { - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kCipherOIDs); i++) { - if (CBS_mem_equal(cbs, kCipherOIDs[i].oid, kCipherOIDs[i].oid_len)) { - return kCipherOIDs[i].cipher_func(); + for (const auto &cipher : kCipherOIDs) { + if (CBS_mem_equal(cbs, cipher.oid, cipher.oid_len)) { + return cipher.cipher_func(); } } - return NULL; + return nullptr; } static int add_cipher_oid(CBB *out, int nid) { - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kCipherOIDs); i++) { - if (kCipherOIDs[i].nid == nid) { - CBB child; - return CBB_add_asn1(out, &child, CBS_ASN1_OBJECT) && - CBB_add_bytes(&child, kCipherOIDs[i].oid, - kCipherOIDs[i].oid_len) && - CBB_flush(out); + for (const auto &cipher : kCipherOIDs) { + if (cipher.nid == nid) { + return CBB_add_asn1_element(out, CBS_ASN1_OBJECT, cipher.oid, + cipher.oid_len); } } @@ -97,6 +102,15 @@ 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, @@ -110,15 +124,15 @@ static int pkcs5_pbe2_cipher_init(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, uint8_t key[EVP_MAX_KEY_LENGTH]; int ret = PKCS5_PBKDF2_HMAC(pass, pass_len, salt, salt_len, iterations, pbkdf2_md, EVP_CIPHER_key_length(cipher), key) && - EVP_CipherInit_ex(ctx, cipher, NULL /* engine */, key, iv, enc); + EVP_CipherInit_ex(ctx, cipher, nullptr /* engine */, key, iv, enc); OPENSSL_cleanse(key, EVP_MAX_KEY_LENGTH); return ret; } -int PKCS5_pbe2_encrypt_init(CBB *out, EVP_CIPHER_CTX *ctx, - const EVP_CIPHER *cipher, uint32_t iterations, - const char *pass, size_t pass_len, - const uint8_t *salt, size_t salt_len) { +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, + const uint8_t *salt, size_t salt_len) { int cipher_nid = EVP_CIPHER_nid(cipher); if (cipher_nid == NID_undef) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER); @@ -131,41 +145,43 @@ int PKCS5_pbe2_encrypt_init(CBB *out, EVP_CIPHER_CTX *ctx, return 0; } - // See RFC 2898, appendix A. - CBB algorithm, oid, param, kdf, kdf_oid, kdf_param, salt_cbb, cipher_cbb, - iv_cbb; + // See RFC 8018, appendix A. + CBB algorithm, param, kdf, kdf_param, prf, cipher_cbb; if (!CBB_add_asn1(out, &algorithm, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&algorithm, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, kPBES2, sizeof(kPBES2)) || + !CBB_add_asn1_element(&algorithm, CBS_ASN1_OBJECT, kPBES2, + sizeof(kPBES2)) || !CBB_add_asn1(&algorithm, ¶m, CBS_ASN1_SEQUENCE) || !CBB_add_asn1(¶m, &kdf, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&kdf, &kdf_oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&kdf_oid, kPBKDF2, sizeof(kPBKDF2)) || + !CBB_add_asn1_element(&kdf, CBS_ASN1_OBJECT, kPBKDF2, sizeof(kPBKDF2)) || !CBB_add_asn1(&kdf, &kdf_param, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&kdf_param, &salt_cbb, CBS_ASN1_OCTETSTRING) || - !CBB_add_bytes(&salt_cbb, salt, salt_len) || + !CBB_add_asn1_octet_string(&kdf_param, salt, salt_len) || !CBB_add_asn1_uint64(&kdf_param, iterations) || // Specify a key length for RC2. (cipher_nid == NID_rc2_cbc && !CBB_add_asn1_uint64(&kdf_param, EVP_CIPHER_key_length(cipher))) || - // Omit the PRF. We use the default hmacWithSHA1. + // Use hmacWithSHA256 for the PRF. + !CBB_add_asn1(&kdf_param, &prf, CBS_ASN1_SEQUENCE) || + !CBB_add_asn1_element(&prf, CBS_ASN1_OBJECT, kHMACWithSHA256, + sizeof(kHMACWithSHA256)) || + !CBB_add_asn1_element(&prf, CBS_ASN1_NULL, nullptr, 0) || !CBB_add_asn1(¶m, &cipher_cbb, CBS_ASN1_SEQUENCE) || !add_cipher_oid(&cipher_cbb, cipher_nid) || - // RFC 2898 says RC2-CBC and RC5-CBC-Pad use a SEQUENCE with version and + // RFC 8018 says RC2-CBC and RC5-CBC-Pad use a SEQUENCE with version and // IV, but OpenSSL always uses an OCTET STRING IV, so we do the same. - !CBB_add_asn1(&cipher_cbb, &iv_cbb, CBS_ASN1_OCTETSTRING) || - !CBB_add_bytes(&iv_cbb, iv, EVP_CIPHER_iv_length(cipher)) || + !CBB_add_asn1_octet_string(&cipher_cbb, iv, + EVP_CIPHER_iv_length(cipher)) || !CBB_flush(out)) { return 0; } - return pkcs5_pbe2_cipher_init(ctx, cipher, EVP_sha1(), iterations, pass, + return pkcs5_pbe2_cipher_init(ctx, cipher, EVP_sha256(), iterations, pass, pass_len, salt, salt_len, iv, EVP_CIPHER_iv_length(cipher), 1 /* encrypt */); } -int PKCS5_pbe2_decrypt_init(const struct pbe_suite *suite, EVP_CIPHER_CTX *ctx, - const char *pass, size_t pass_len, CBS *param) { +int bssl::PKCS5_pbe2_decrypt_init(const struct pbe_suite *suite, + EVP_CIPHER_CTX *ctx, const char *pass, + size_t pass_len, CBS *param) { CBS pbe_param, kdf, kdf_obj, enc_scheme, enc_obj; if (!CBS_get_asn1(param, &pbe_param, CBS_ASN1_SEQUENCE) || CBS_len(param) != 0 || @@ -186,7 +202,7 @@ int PKCS5_pbe2_decrypt_init(const struct pbe_suite *suite, EVP_CIPHER_CTX *ctx, // See if we recognise the encryption algorithm. const EVP_CIPHER *cipher = cbs_to_cipher(&enc_obj); - if (cipher == NULL) { + if (cipher == nullptr) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNSUPPORTED_CIPHER); return 0; } @@ -254,7 +270,7 @@ int PKCS5_pbe2_decrypt_init(const struct pbe_suite *suite, EVP_CIPHER_CTX *ctx, } // Parse the encryption scheme parameters. Note OpenSSL does not match the - // specification. Per RFC 2898, this should depend on the encryption scheme. + // specification. Per RFC 8018, this should depend on the encryption scheme. // In particular, RC2-CBC uses a SEQUENCE with version and IV. We align with // OpenSSL. CBS iv; diff --git a/Sources/CNIOBoringSSL/crypto/pkcs8/pkcs8.cc b/Sources/CNIOBoringSSL/crypto/pkcs8/pkcs8.cc index 86851b64..bd8bd46a 100644 --- a/Sources/CNIOBoringSSL/crypto/pkcs8/pkcs8.cc +++ b/Sources/CNIOBoringSSL/crypto/pkcs8/pkcs8.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -26,10 +31,12 @@ #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) { - CBB cbb; - if (!CBB_init(&cbb, in_len * 2)) { + ScopedCBB cbb; + if (!CBB_init(cbb.get(), in_len * 2)) { return 0; } @@ -39,27 +46,23 @@ static int pkcs12_encode_password(const char *in, size_t in_len, uint8_t **out, CBS_init(&cbs, (const uint8_t *)in, in_len); while (CBS_len(&cbs) != 0) { uint32_t c; - if (!CBS_get_utf8(&cbs, &c) || !CBB_add_ucs2_be(&cbb, c)) { + if (!CBS_get_utf8(&cbs, &c) || !CBB_add_ucs2_be(cbb.get(), c)) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_INVALID_CHARACTERS); - goto err; + return 0; } } // Terminate the result with a UCS-2 NUL. - if (!CBB_add_ucs2_be(&cbb, 0) || !CBB_finish(&cbb, out, out_len)) { - goto err; + if (!CBB_add_ucs2_be(cbb.get(), 0) || !CBB_finish(cbb.get(), out, out_len)) { + return 0; } return 1; - -err: - CBB_cleanup(&cbb); - return 0; } -int 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) { +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) { // See https://tools.ietf.org/html/rfc7292#appendix-B. Quoted parts of the // specification have errata applied and other typos fixed. @@ -71,18 +74,18 @@ int pkcs12_key_gen(const char *pass, size_t pass_len, const uint8_t *salt, int ret = 0; EVP_MD_CTX ctx; EVP_MD_CTX_init(&ctx); - uint8_t *pass_raw = NULL, *I = NULL; + uint8_t *pass_raw = nullptr, *I = nullptr; size_t pass_raw_len = 0, I_len = 0; { - // If |pass| is NULL, we use the empty string rather than {0, 0} as the raw + // If `pass` is NULL, we use the empty string rather than {0, 0} as the raw // password. - if (pass != NULL && + if (pass != nullptr && !pkcs12_encode_password(pass, pass_len, &pass_raw, &pass_raw_len)) { goto err; } - // In the spec, |block_size| is called "v", but measured in bits. + // In the spec, `block_size` is called "v", but measured in bits. size_t block_size = EVP_MD_block_size(md); // 1. Construct a string, D (the "diversifier"), by concatenating v/8 copies @@ -114,7 +117,7 @@ int pkcs12_key_gen(const char *pass, size_t pass_len, const uint8_t *salt, } I = reinterpret_cast(OPENSSL_malloc(I_len)); - if (I_len != 0 && I == NULL) { + if (I_len != 0 && I == nullptr) { goto err; } @@ -130,14 +133,14 @@ int pkcs12_key_gen(const char *pass, size_t pass_len, const uint8_t *salt, // H(H(H(... H(D||I)))) uint8_t A[EVP_MAX_MD_SIZE]; unsigned A_len; - if (!EVP_DigestInit_ex(&ctx, md, NULL) || + if (!EVP_DigestInit_ex(&ctx, md, nullptr) || !EVP_DigestUpdate(&ctx, D, block_size) || !EVP_DigestUpdate(&ctx, I, I_len) || !EVP_DigestFinal_ex(&ctx, A, &A_len)) { goto err; } for (uint32_t iter = 1; iter < iterations; iter++) { - if (!EVP_DigestInit_ex(&ctx, md, NULL) || + if (!EVP_DigestInit_ex(&ctx, md, nullptr) || !EVP_DigestUpdate(&ctx, A, A_len) || !EVP_DigestFinal_ex(&ctx, A, &A_len)) { goto err; @@ -201,7 +204,7 @@ static int pkcs12_pbe_cipher_init(const struct pbe_suite *suite, return 0; } - int ret = EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, is_encrypt); + int ret = EVP_CipherInit_ex(ctx, cipher, nullptr, key, iv, is_encrypt); OPENSSL_cleanse(key, EVP_MAX_KEY_LENGTH); OPENSSL_cleanse(iv, EVP_MAX_IV_LENGTH); return ret; @@ -230,7 +233,7 @@ static int pkcs12_pbe_decrypt_init(const struct pbe_suite *suite, 0 /* decrypt */); } -static const struct pbe_suite kBuiltinPBE[] = { +static const struct bssl::pbe_suite kBuiltinPBE[] = { { NID_pbe_WithSHA1And40BitRC2_CBC, // 1.2.840.113549.1.12.1.6 @@ -263,42 +266,54 @@ static const struct pbe_suite kBuiltinPBE[] = { // 1.2.840.113549.1.5.13 {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0d}, 9, - NULL, - NULL, + nullptr, + nullptr, PKCS5_pbe2_decrypt_init, }, }; -static const struct pbe_suite *get_pkcs12_pbe_suite(int pbe_nid) { - for (unsigned i = 0; i < OPENSSL_ARRAY_SIZE(kBuiltinPBE); i++) { - if (kBuiltinPBE[i].pbe_nid == pbe_nid && - // If |cipher_func| or |md_func| are missing, this is a PBES2 scheme. - kBuiltinPBE[i].cipher_func != NULL && kBuiltinPBE[i].md_func != NULL) { - return &kBuiltinPBE[i]; +static const struct bssl::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. + pbe.cipher_func != nullptr && pbe.md_func != nullptr) { + return &pbe; } } - return NULL; + return nullptr; } -int pkcs12_pbe_encrypt_init(CBB *out, EVP_CIPHER_CTX *ctx, int alg, - uint32_t iterations, const char *pass, - size_t pass_len, const uint8_t *salt, - size_t salt_len) { - const struct pbe_suite *suite = get_pkcs12_pbe_suite(alg); - if (suite == NULL) { +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, + size_t pass_len, const uint8_t *salt, + size_t salt_len) { + // TODO(davidben): OpenSSL has since extended `pbe_nid` to control either + // the PBES1 scheme or the PBES2 PRF. E.g. passing `NID_hmacWithSHA256` will + // select PBES2 with HMAC-SHA256 as the PRF. Implement this if anything uses + // it. See 5693a30813a031d3921a016a870420e7eb93ec90 in OpenSSL. + if (alg_nid == -1) { + return PKCS5_pbe2_encrypt_init(out, ctx, alg_cipher, iterations, pass, + pass_len, salt, salt_len); + } + + const struct pbe_suite *suite = get_pkcs12_pbe_suite(alg_nid); + if (suite == nullptr) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNKNOWN_ALGORITHM); return 0; } - // See RFC 2898, appendix A.3. - CBB algorithm, oid, param, salt_cbb; + // See RFC 7292, appendix C. All our supported "PBES1" schemes are the PKCS#12 + // schemes, which use a different KDF. The true PBES1 schemes in RFC 8018 use + // PBKDF1, which use a very similar PBEParameter structure, but require the + // salt be exactly 8 bytes. + CBB algorithm, param; if (!CBB_add_asn1(out, &algorithm, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&algorithm, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, suite->oid, suite->oid_len) || + !CBB_add_asn1_element(&algorithm, CBS_ASN1_OBJECT, suite->oid, + suite->oid_len) || !CBB_add_asn1(&algorithm, ¶m, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(¶m, &salt_cbb, CBS_ASN1_OCTETSTRING) || - !CBB_add_bytes(&salt_cbb, salt, salt_len) || + !CBB_add_asn1_octet_string(¶m, salt, salt_len) || !CBB_add_asn1_uint64(¶m, iterations) || !CBB_flush(out)) { return 0; } @@ -307,62 +322,54 @@ int pkcs12_pbe_encrypt_init(CBB *out, EVP_CIPHER_CTX *ctx, int alg, salt_len, 1 /* encrypt */); } -int pkcs8_pbe_decrypt(uint8_t **out, size_t *out_len, CBS *algorithm, - const char *pass, size_t pass_len, const uint8_t *in, - size_t in_len) { +int bssl::pkcs8_pbe_decrypt(uint8_t **out, size_t *out_len, CBS *algorithm, + const char *pass, size_t pass_len, + const uint8_t *in, size_t in_len) { int ret = 0; - uint8_t *buf = NULL; - ; - EVP_CIPHER_CTX ctx; - EVP_CIPHER_CTX_init(&ctx); + uint8_t *buf = nullptr; + ScopedEVP_CIPHER_CTX ctx; CBS obj; - const struct pbe_suite *suite = NULL; + const struct pbe_suite *suite = nullptr; if (!CBS_get_asn1(algorithm, &obj, CBS_ASN1_OBJECT)) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR); goto err; } - for (unsigned i = 0; i < OPENSSL_ARRAY_SIZE(kBuiltinPBE); i++) { - if (CBS_mem_equal(&obj, kBuiltinPBE[i].oid, kBuiltinPBE[i].oid_len)) { - suite = &kBuiltinPBE[i]; + for (const auto &pbe : kBuiltinPBE) { + if (CBS_mem_equal(&obj, pbe.oid, pbe.oid_len)) { + suite = &pbe; break; } } - if (suite == NULL) { + if (suite == nullptr) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNKNOWN_ALGORITHM); goto err; } - if (!suite->decrypt_init(suite, &ctx, pass, pass_len, algorithm)) { + if (!suite->decrypt_init(suite, ctx.get(), pass, pass_len, algorithm)) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_KEYGEN_FAILURE); goto err; } buf = reinterpret_cast(OPENSSL_malloc(in_len)); - if (buf == NULL) { + if (buf == nullptr) { goto err; } - if (in_len > INT_MAX) { - OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW); - goto err; - } - - int n1, n2; - if (!EVP_DecryptUpdate(&ctx, buf, &n1, in, (int)in_len) || - !EVP_DecryptFinal_ex(&ctx, buf + n1, &n2)) { + size_t n1, n2; + if (!EVP_DecryptUpdate_ex(ctx.get(), buf, &n1, in_len, in, in_len) || + !EVP_DecryptFinal_ex2(ctx.get(), buf + n1, &n2, in_len - n1)) { goto err; } *out = buf; *out_len = n1 + n2; ret = 1; - buf = NULL; + buf = nullptr; err: OPENSSL_free(buf); - EVP_CIPHER_CTX_cleanup(&ctx); return ret; } @@ -375,14 +382,14 @@ EVP_PKEY *PKCS8_parse_encrypted_private_key(CBS *cbs, const char *pass, !CBS_get_asn1(&epki, &ciphertext, CBS_ASN1_OCTETSTRING) || CBS_len(&epki) != 0) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR); - return 0; + return nullptr; } uint8_t *out; size_t out_len; if (!pkcs8_pbe_decrypt(&out, &out_len, &algorithm, pass, pass_len, CBS_data(&ciphertext), CBS_len(&ciphertext))) { - return 0; + return nullptr; } CBS pki; @@ -398,20 +405,19 @@ int PKCS8_marshal_encrypted_private_key(CBB *out, int pbe_nid, const uint8_t *salt, size_t salt_len, int iterations, const EVP_PKEY *pkey) { int ret = 0; - uint8_t *plaintext = NULL, *salt_buf = NULL; + uint8_t *plaintext = nullptr, *salt_buf = nullptr; size_t plaintext_len = 0; - EVP_CIPHER_CTX ctx; - EVP_CIPHER_CTX_init(&ctx); + ScopedEVP_CIPHER_CTX ctx; { // Generate a random salt if necessary. - if (salt == NULL) { + if (salt == nullptr) { if (salt_len == 0) { salt_len = PKCS5_SALT_LEN; } salt_buf = reinterpret_cast(OPENSSL_malloc(salt_len)); - if (salt_buf == NULL || !RAND_bytes(salt_buf, salt_len)) { + if (salt_buf == nullptr || !RAND_bytes(salt_buf, salt_len)) { goto err; } @@ -432,29 +438,14 @@ int PKCS8_marshal_encrypted_private_key(CBB *out, int pbe_nid, } CBB epki; - if (!CBB_add_asn1(out, &epki, CBS_ASN1_SEQUENCE)) { + if (!CBB_add_asn1(out, &epki, CBS_ASN1_SEQUENCE) || + !pkcs12_pbe_encrypt_init(&epki, ctx.get(), pbe_nid, cipher, + (uint32_t)iterations, pass, pass_len, salt, + salt_len)) { goto err; } - // TODO(davidben): OpenSSL has since extended |pbe_nid| to control either - // the PBES1 scheme or the PBES2 PRF. E.g. passing |NID_hmacWithSHA256| will - // select PBES2 with HMAC-SHA256 as the PRF. Implement this if anything uses - // it. See 5693a30813a031d3921a016a870420e7eb93ec90 in OpenSSL. - int alg_ok; - if (pbe_nid == -1) { - alg_ok = - PKCS5_pbe2_encrypt_init(&epki, &ctx, cipher, (uint32_t)iterations, - pass, pass_len, salt, salt_len); - } else { - alg_ok = - pkcs12_pbe_encrypt_init(&epki, &ctx, pbe_nid, (uint32_t)iterations, - pass, pass_len, salt, salt_len); - } - if (!alg_ok) { - goto err; - } - - size_t max_out = plaintext_len + EVP_CIPHER_CTX_block_size(&ctx); + size_t max_out = plaintext_len + EVP_CIPHER_CTX_block_size(ctx.get()); if (max_out < plaintext_len) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_TOO_LONG); goto err; @@ -462,11 +453,12 @@ int PKCS8_marshal_encrypted_private_key(CBB *out, int pbe_nid, CBB ciphertext; uint8_t *ptr; - int n1, n2; + size_t n1, n2; if (!CBB_add_asn1(&epki, &ciphertext, CBS_ASN1_OCTETSTRING) || !CBB_reserve(&ciphertext, &ptr, max_out) || - !EVP_CipherUpdate(&ctx, ptr, &n1, plaintext, plaintext_len) || - !EVP_CipherFinal_ex(&ctx, ptr + n1, &n2) || + !EVP_CipherUpdate_ex(ctx.get(), ptr, &n1, max_out, plaintext, + plaintext_len) || + !EVP_CipherFinal_ex2(ctx.get(), ptr + n1, &n2, max_out - n1) || !CBB_did_write(&ciphertext, n1 + n2) || !CBB_flush(out)) { goto err; } @@ -477,6 +469,5 @@ int PKCS8_marshal_encrypted_private_key(CBB *out, int pbe_nid, err: OPENSSL_free(plaintext); OPENSSL_free(salt_buf); - EVP_CIPHER_CTX_cleanup(&ctx); return ret; } diff --git a/Sources/CNIOBoringSSL/crypto/pkcs8/pkcs8_x509.cc b/Sources/CNIOBoringSSL/crypto/pkcs8/pkcs8_x509.cc index b4ab828b..f1452eaa 100644 --- a/Sources/CNIOBoringSSL/crypto/pkcs8/pkcs8_x509.cc +++ b/Sources/CNIOBoringSSL/crypto/pkcs8/pkcs8_x509.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,22 +21,27 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include #include "../bytestring/internal.h" #include "../internal.h" +#include "../mem_internal.h" #include "../x509/internal.h" #include "internal.h" -int pkcs12_iterations_acceptable(uint64_t iterations) { -#if defined(BORINGSSL_UNSAFE_FUZZER_MODE) +using namespace bssl; + +int bssl::pkcs12_iterations_acceptable(uint64_t iterations) { +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) static const uint64_t kIterationsLimit = 2048; #else // Windows imposes a limit of 600K. Mozilla say: “so them increasing @@ -50,26 +60,27 @@ ASN1_SEQUENCE(PKCS8_PRIV_KEY_INFO) = { ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, version, ASN1_INTEGER), ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, pkeyalg, X509_ALGOR), ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, pkey, ASN1_OCTET_STRING), - ASN1_IMP_SET_OF_OPT(PKCS8_PRIV_KEY_INFO, attributes, X509_ATTRIBUTE, 0), + ASN1_IMP_SET_OF_OPT(PKCS8_PRIV_KEY_INFO, attributes, bssl::X509_ATTRIBUTE, + 0), } ASN1_SEQUENCE_END(PKCS8_PRIV_KEY_INFO) IMPLEMENT_ASN1_FUNCTIONS_const(PKCS8_PRIV_KEY_INFO) EVP_PKEY *EVP_PKCS82PKEY(const PKCS8_PRIV_KEY_INFO *p8) { - uint8_t *der = NULL; + uint8_t *der = nullptr; int der_len = i2d_PKCS8_PRIV_KEY_INFO(p8, &der); if (der_len < 0) { - return NULL; + return nullptr; } CBS cbs; CBS_init(&cbs, der, (size_t)der_len); EVP_PKEY *ret = EVP_parse_private_key(&cbs); - if (ret == NULL || CBS_len(&cbs) != 0) { + if (ret == nullptr || CBS_len(&cbs) != 0) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR); EVP_PKEY_free(ret); OPENSSL_free(der); - return NULL; + return nullptr; } OPENSSL_free(der); @@ -78,19 +89,19 @@ EVP_PKEY *EVP_PKCS82PKEY(const PKCS8_PRIV_KEY_INFO *p8) { PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(const EVP_PKEY *pkey) { CBB cbb; - uint8_t *der = NULL; + uint8_t *der = nullptr; size_t der_len; if (!CBB_init(&cbb, 0) || !EVP_marshal_private_key(&cbb, pkey) || !CBB_finish(&cbb, &der, &der_len) || der_len > LONG_MAX) { CBB_cleanup(&cbb); OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_ENCODE_ERROR); OPENSSL_free(der); - return NULL; + return nullptr; } const uint8_t *p = der; - PKCS8_PRIV_KEY_INFO *p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, (long)der_len); - if (p8 == NULL || p != der + der_len) { + PKCS8_PRIV_KEY_INFO *p8 = d2i_PKCS8_PRIV_KEY_INFO(nullptr, &p, (long)der_len); + if (p8 == nullptr || p != der + der_len) { PKCS8_PRIV_KEY_INFO_free(p8); OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR); goto err; @@ -101,21 +112,21 @@ PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(const EVP_PKEY *pkey) { err: OPENSSL_free(der); - return NULL; + return nullptr; } PKCS8_PRIV_KEY_INFO *PKCS8_decrypt(X509_SIG *pkcs8, const char *pass, int pass_len_in) { size_t pass_len; - if (pass_len_in == -1 && pass != NULL) { + if (pass_len_in == -1 && pass != nullptr) { pass_len = strlen(pass); } else { pass_len = (size_t)pass_len_in; } - PKCS8_PRIV_KEY_INFO *ret = NULL; - EVP_PKEY *pkey = NULL; - uint8_t *in = NULL; + PKCS8_PRIV_KEY_INFO *ret = nullptr; + EVP_PKEY *pkey = nullptr; + uint8_t *in = nullptr; // Convert the legacy ASN.1 object to a byte string. int in_len = i2d_X509_SIG(pkcs8, &in); @@ -126,7 +137,7 @@ PKCS8_PRIV_KEY_INFO *PKCS8_decrypt(X509_SIG *pkcs8, const char *pass, CBS cbs; CBS_init(&cbs, in, in_len); pkey = PKCS8_parse_encrypted_private_key(&cbs, pass, pass_len); - if (pkey == NULL || CBS_len(&cbs) != 0) { + if (pkey == nullptr || CBS_len(&cbs) != 0) { goto err; } @@ -142,7 +153,7 @@ X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher, const char *pass, int pass_len_in, const uint8_t *salt, size_t salt_len, int iterations, PKCS8_PRIV_KEY_INFO *p8inf) { size_t pass_len; - if (pass_len_in == -1 && pass != NULL) { + if (pass_len_in == -1 && pass != nullptr) { pass_len = strlen(pass); } else { pass_len = (size_t)pass_len_in; @@ -150,12 +161,12 @@ X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher, const char *pass, // Parse out the private key. EVP_PKEY *pkey = EVP_PKCS82PKEY(p8inf); - if (pkey == NULL) { - return NULL; + if (pkey == nullptr) { + return nullptr; } - X509_SIG *ret = NULL; - uint8_t *der = NULL; + X509_SIG *ret = nullptr; + uint8_t *der = nullptr; const uint8_t *ptr; size_t der_len; CBB cbb; @@ -170,11 +181,11 @@ X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher, const char *pass, // Convert back to legacy ASN.1 objects. ptr = der; - ret = d2i_X509_SIG(NULL, &ptr, der_len); - if (ret == NULL || ptr != der + der_len) { + ret = d2i_X509_SIG(nullptr, &ptr, der_len); + if (ret == nullptr || ptr != der + der_len) { OPENSSL_PUT_ERROR(PKCS8, ERR_R_INTERNAL_ERROR); X509_SIG_free(ret); - ret = NULL; + ret = nullptr; } err: @@ -195,11 +206,11 @@ struct pkcs12_context { static int PKCS12_handle_sequence( CBS *sequence, struct pkcs12_context *ctx, int (*handle_element)(CBS *cbs, struct pkcs12_context *ctx)) { - uint8_t *storage = NULL; + uint8_t *storage = nullptr; CBS in; int ret = 0; - // Although a BER->DER conversion is done at the beginning of |PKCS12_parse|, + // Although a BER->DER conversion is done at the beginning of `PKCS12_parse`, // the ASN.1 data gets wrapped in OCTETSTRINGs and/or encrypted and the // conversion cannot see through those wrappings. So each time we step // through one we need to convert to DER again. @@ -258,12 +269,12 @@ static const uint8_t kX509Certificate[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x16, 0x01}; // parse_bag_attributes parses the bagAttributes field of a SafeBag structure. -// It sets |*out_friendly_name| to a newly-allocated copy of the friendly name, +// 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) { - *out_friendly_name = NULL; + *out_friendly_name = nullptr; *out_friendly_name_len = 0; // See https://tools.ietf.org/html/rfc7292#section-4.2. @@ -278,7 +289,7 @@ static int parse_bag_attributes(CBS *attrs, uint8_t **out_friendly_name, if (CBS_mem_equal(&oid, kFriendlyName, sizeof(kFriendlyName))) { // See https://tools.ietf.org/html/rfc2985, section 5.5.1. CBS value; - if (*out_friendly_name != NULL || + if (*out_friendly_name != nullptr || !CBS_get_asn1(&values, &value, CBS_ASN1_BMPSTRING) || CBS_len(&values) != 0 || CBS_len(&value) == 0) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA); @@ -308,7 +319,7 @@ static int parse_bag_attributes(CBS *attrs, uint8_t **out_friendly_name, err: OPENSSL_free(*out_friendly_name); - *out_friendly_name = NULL; + *out_friendly_name = nullptr; *out_friendly_name_len = 0; return 0; } @@ -324,7 +335,7 @@ static int PKCS12_handle_safe_bag(CBS *safe_bag, struct pkcs12_context *ctx) { return 0; } if (CBS_len(safe_bag) == 0) { - CBS_init(&bag_attrs, NULL, 0); + CBS_init(&bag_attrs, nullptr, 0); } else if (!CBS_get_asn1(safe_bag, &bag_attrs, CBS_ASN1_SET) || CBS_len(safe_bag) != 0) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA); @@ -345,7 +356,7 @@ static int PKCS12_handle_safe_bag(CBS *safe_bag, struct pkcs12_context *ctx) { is_key_bag ? EVP_parse_private_key(&wrapped_value) : PKCS8_parse_encrypted_private_key( &wrapped_value, ctx->password, ctx->password_len); - if (pkey == NULL) { + if (pkey == nullptr) { return 0; } @@ -383,7 +394,7 @@ static int PKCS12_handle_safe_bag(CBS *safe_bag, struct pkcs12_context *ctx) { } const uint8_t *inp = CBS_data(&cert); - X509 *x509 = d2i_X509(NULL, &inp, (long)CBS_len(&cert)); + X509 *x509 = d2i_X509(nullptr, &inp, (long)CBS_len(&cert)); if (!x509) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA); return 0; @@ -430,7 +441,7 @@ static int PKCS12_handle_content_info(CBS *content_info, struct pkcs12_context *ctx) { CBS content_type, wrapped_contents, contents; int ret = 0; - uint8_t *storage = NULL; + uint8_t *storage = nullptr; if (!CBS_get_asn1(content_info, &content_type, CBS_ASN1_OBJECT) || !CBS_get_asn1(content_info, &wrapped_contents, @@ -517,15 +528,15 @@ static int pkcs12_check_mac(int *out_mac_ok, const char *password, uint8_t hmac[EVP_MAX_MD_SIZE]; unsigned hmac_len; - if (NULL == HMAC(md, hmac_key, EVP_MD_size(md), CBS_data(authsafes), - CBS_len(authsafes), hmac, &hmac_len)) { + if (nullptr == HMAC(md, hmac_key, EVP_MD_size(md), CBS_data(authsafes), + CBS_len(authsafes), hmac, &hmac_len)) { goto err; } *out_mac_ok = CBS_mem_equal(expected_mac, hmac, hmac_len); -#if defined(BORINGSSL_UNSAFE_FUZZER_MODE) - *out_mac_ok = 1; -#endif + if (CRYPTO_fuzzer_mode_enabled()) { + *out_mac_ok = 1; + } ret = 1; err: @@ -536,7 +547,7 @@ err: int PKCS12_get_key_and_certs(EVP_PKEY **out_key, STACK_OF(X509) *out_certs, CBS *ber_in, const char *password) { - uint8_t *storage = NULL; + uint8_t *storage = nullptr; CBS in, pfx, mac_data, authsafe, content_type, wrapped_authsafes, authsafes; uint64_t version; int ret = 0; @@ -549,7 +560,7 @@ int PKCS12_get_key_and_certs(EVP_PKEY **out_key, STACK_OF(X509) *out_certs, return 0; } - *out_key = NULL; + *out_key = nullptr; OPENSSL_memset(&ctx, 0, sizeof(ctx)); // See ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1.pdf, section @@ -604,7 +615,7 @@ int PKCS12_get_key_and_certs(EVP_PKEY **out_key, STACK_OF(X509) *out_certs, ctx.out_key = out_key; ctx.out_certs = out_certs; ctx.password = password; - ctx.password_len = password != NULL ? strlen(password) : 0; + ctx.password_len = password != nullptr ? strlen(password) : 0; // Verify the MAC. { @@ -615,7 +626,7 @@ int PKCS12_get_key_and_certs(EVP_PKEY **out_key, STACK_OF(X509) *out_certs, } const EVP_MD *md = EVP_parse_digest_algorithm(&mac); - if (md == NULL) { + if (md == nullptr) { goto err; } @@ -648,7 +659,7 @@ int PKCS12_get_key_and_certs(EVP_PKEY **out_key, STACK_OF(X509) *out_certs, // array for "no password". OpenSSL considers a non-NULL password as {0, // 0} and a NULL password as {}. It then, in high-level PKCS#12 parsing // code, tries both options. We match this behavior. - ctx.password = ctx.password != NULL ? NULL : ""; + ctx.password = ctx.password != nullptr ? nullptr : ""; if (!pkcs12_check_mac(&mac_ok, ctx.password, ctx.password_len, &salt, iterations, md, &authsafes, &expected_mac)) { goto err; @@ -671,7 +682,7 @@ err: OPENSSL_free(storage); if (!ret) { EVP_PKEY_free(*out_key); - *out_key = NULL; + *out_key = nullptr; while (sk_X509_num(out_certs) > original_out_certs_len) { X509 *x509 = sk_X509_pop(out_certs); X509_free(x509); @@ -681,7 +692,7 @@ err: return ret; } -void PKCS12_PBE_add(void) {} +void PKCS12_PBE_add() {} struct pkcs12_st { uint8_t *ber_bytes; @@ -690,16 +701,16 @@ struct pkcs12_st { PKCS12 *d2i_PKCS12(PKCS12 **out_p12, const uint8_t **ber_bytes, size_t ber_len) { - PKCS12 *p12 = reinterpret_cast(OPENSSL_malloc(sizeof(PKCS12))); + PKCS12 *p12 = New(); if (!p12) { - return NULL; + return nullptr; } p12->ber_bytes = reinterpret_cast(OPENSSL_memdup(*ber_bytes, ber_len)); if (!p12->ber_bytes) { - OPENSSL_free(p12); - return NULL; + Delete(p12); + return nullptr; } p12->ber_len = ber_len; @@ -718,11 +729,11 @@ PKCS12 *d2i_PKCS12_bio(BIO *bio, PKCS12 **out_p12) { BUF_MEM *buf; const uint8_t *dummy; static const size_t kMaxSize = 256 * 1024; - PKCS12 *ret = NULL; + PKCS12 *ret = nullptr; buf = BUF_MEM_new(); - if (buf == NULL) { - return NULL; + if (buf == nullptr) { + return nullptr; } if (BUF_MEM_grow(buf, 8192) == 0) { goto out; @@ -769,7 +780,7 @@ PKCS12 *d2i_PKCS12_fp(FILE *fp, PKCS12 **out_p12) { bio = BIO_new_fp(fp, 0 /* don't take ownership */); if (!bio) { - return NULL; + return nullptr; } ret = d2i_PKCS12_bio(bio, out_p12); @@ -783,14 +794,14 @@ int i2d_PKCS12(const PKCS12 *p12, uint8_t **out) { return -1; } - if (out == NULL) { + if (out == nullptr) { return (int)p12->ber_len; } - if (*out == NULL) { + if (*out == nullptr) { *out = reinterpret_cast( OPENSSL_memdup(p12->ber_bytes, p12->ber_len)); - if (*out == NULL) { + if (*out == nullptr) { return -1; } } else { @@ -806,7 +817,7 @@ int i2d_PKCS12_bio(BIO *bio, const PKCS12 *p12) { int i2d_PKCS12_fp(FILE *fp, const PKCS12 *p12) { BIO *bio = BIO_new_fp(fp, 0 /* don't take ownership */); - if (bio == NULL) { + if (bio == nullptr) { return 0; } @@ -818,16 +829,16 @@ int i2d_PKCS12_fp(FILE *fp, const PKCS12 *p12) { int PKCS12_parse(const PKCS12 *p12, const char *password, EVP_PKEY **out_pkey, X509 **out_cert, STACK_OF(X509) **out_ca_certs) { CBS ber_bytes; - STACK_OF(X509) *ca_certs = NULL; + STACK_OF(X509) *ca_certs = nullptr; char ca_certs_alloced = 0; - if (out_ca_certs != NULL && *out_ca_certs != NULL) { + if (out_ca_certs != nullptr && *out_ca_certs != nullptr) { ca_certs = *out_ca_certs; } if (!ca_certs) { ca_certs = sk_X509_new_null(); - if (ca_certs == NULL) { + if (ca_certs == nullptr) { return 0; } ca_certs_alloced = 1; @@ -842,10 +853,10 @@ int PKCS12_parse(const PKCS12 *p12, const char *password, EVP_PKEY **out_pkey, } // OpenSSL selects the last certificate which matches the private key as - // |out_cert|. - *out_cert = NULL; + // `out_cert`. + *out_cert = nullptr; size_t num_certs = sk_X509_num(ca_certs); - if (*out_pkey != NULL && num_certs > 0) { + if (*out_pkey != nullptr && num_certs > 0) { for (size_t i = num_certs - 1; i < num_certs; i--) { X509 *cert = sk_X509_value(ca_certs, i); if (X509_check_private_key(cert, *out_pkey)) { @@ -868,19 +879,19 @@ int PKCS12_parse(const PKCS12 *p12, const char *password, EVP_PKEY **out_pkey, int PKCS12_verify_mac(const PKCS12 *p12, const char *password, int password_len) { - if (password == NULL) { + if (password == nullptr) { if (password_len != 0) { return 0; } } else if (password_len != -1 && (password[password_len] != 0 || - OPENSSL_memchr(password, 0, password_len) != NULL)) { + OPENSSL_memchr(password, 0, password_len) != nullptr)) { return 0; } - EVP_PKEY *pkey = NULL; - X509 *cert = NULL; - if (!PKCS12_parse(p12, password, &pkey, &cert, NULL)) { + EVP_PKEY *pkey = nullptr; + X509 *cert = nullptr; + if (!PKCS12_parse(p12, password, &pkey, &cert, nullptr)) { ERR_clear_error(); return 0; } @@ -895,19 +906,19 @@ int PKCS12_verify_mac(const PKCS12 *p12, const char *password, // 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) { - if (name == NULL && key_id_len == 0) { + if (name == nullptr && key_id_len == 0) { return 1; // Omit the OPTIONAL SET. } // See https://tools.ietf.org/html/rfc7292#section-4.2. - CBB attrs, attr, oid, values, value; + CBB attrs, attr, values, value; if (!CBB_add_asn1(bag, &attrs, CBS_ASN1_SET)) { return 0; } if (name_len != 0) { // See https://tools.ietf.org/html/rfc2985, section 5.5.1. if (!CBB_add_asn1(&attrs, &attr, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&attr, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, kFriendlyName, sizeof(kFriendlyName)) || + !CBB_add_asn1_element(&attr, CBS_ASN1_OBJECT, kFriendlyName, + sizeof(kFriendlyName)) || !CBB_add_asn1(&attr, &values, CBS_ASN1_SET) || !CBB_add_asn1(&values, &value, CBS_ASN1_BMPSTRING)) { return 0; @@ -926,11 +937,10 @@ static int add_bag_attributes(CBB *bag, const char *name, size_t name_len, if (key_id_len != 0) { // See https://tools.ietf.org/html/rfc2985, section 5.5.2. if (!CBB_add_asn1(&attrs, &attr, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&attr, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, kLocalKeyID, sizeof(kLocalKeyID)) || + !CBB_add_asn1_element(&attr, CBS_ASN1_OBJECT, kLocalKeyID, + sizeof(kLocalKeyID)) || !CBB_add_asn1(&attr, &values, CBS_ASN1_SET) || - !CBB_add_asn1(&values, &value, CBS_ASN1_OCTETSTRING) || - !CBB_add_bytes(&value, key_id, key_id_len)) { + !CBB_add_asn1_octet_string(&values, key_id, key_id_len)) { return 0; } } @@ -939,24 +949,24 @@ static int add_bag_attributes(CBB *bag, const char *name, size_t name_len, static int add_cert_bag(CBB *cbb, X509 *cert, const char *name, const uint8_t *key_id, size_t key_id_len) { - CBB bag, bag_oid, bag_contents, cert_bag, cert_type, wrapped_cert, cert_value; + 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) || - !CBB_add_asn1(&bag, &bag_oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&bag_oid, kCertBag, sizeof(kCertBag)) || + !CBB_add_asn1_element(&bag, CBS_ASN1_OBJECT, kCertBag, + sizeof(kCertBag)) || !CBB_add_asn1(&bag, &bag_contents, CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) || // See https://tools.ietf.org/html/rfc7292#section-4.2.3. !CBB_add_asn1(&bag_contents, &cert_bag, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&cert_bag, &cert_type, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&cert_type, kX509Certificate, sizeof(kX509Certificate)) || + !CBB_add_asn1_element(&cert_bag, CBS_ASN1_OBJECT, kX509Certificate, + sizeof(kX509Certificate)) || !CBB_add_asn1(&cert_bag, &wrapped_cert, CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) || !CBB_add_asn1(&wrapped_cert, &cert_value, CBS_ASN1_OCTETSTRING)) { return 0; } uint8_t *buf; - int len = i2d_X509(cert, NULL); + int len = i2d_X509(cert, nullptr); int int_name_len = 0; const char *cert_name = (const char *)X509_alias_get0(cert, &int_name_len); @@ -985,14 +995,15 @@ static int add_cert_safe_contents(CBB *cbb, X509 *cert, const uint8_t *key_id, size_t key_id_len) { CBB safe_contents; if (!CBB_add_asn1(cbb, &safe_contents, CBS_ASN1_SEQUENCE) || - (cert != NULL && + (cert != nullptr && !add_cert_bag(&safe_contents, cert, name, key_id, key_id_len))) { return 0; } for (size_t i = 0; i < sk_X509_num(chain); i++) { // Only the leaf certificate gets attributes. - if (!add_cert_bag(&safe_contents, sk_X509_value(chain, i), NULL, NULL, 0)) { + if (!add_cert_bag(&safe_contents, sk_X509_value(chain, i), nullptr, nullptr, + 0)) { return 0; } } @@ -1000,23 +1011,26 @@ static int add_cert_safe_contents(CBB *cbb, X509 *cert, return CBB_flush(cbb); } -static int add_encrypted_data(CBB *out, int pbe_nid, const char *password, - size_t password_len, uint32_t iterations, - const uint8_t *in, size_t in_len) { +// 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) { uint8_t salt[PKCS5_SALT_LEN]; if (!RAND_bytes(salt, sizeof(salt))) { return 0; } - int ret = 0; - EVP_CIPHER_CTX ctx; - EVP_CIPHER_CTX_init(&ctx); - CBB content_info, type, wrapper, encrypted_data, encrypted_content_info, - inner_type, encrypted_content; + ScopedEVP_CIPHER_CTX ctx; + CBB content_info, wrapper, encrypted_data, encrypted_content_info, + encrypted_content; if ( // Add the ContentInfo wrapping. !CBB_add_asn1(out, &content_info, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&content_info, &type, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&type, kPKCS7EncryptedData, sizeof(kPKCS7EncryptedData)) || + !CBB_add_asn1_element(&content_info, CBS_ASN1_OBJECT, kPKCS7EncryptedData, + sizeof(kPKCS7EncryptedData)) || !CBB_add_asn1(&content_info, &wrapper, CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) || // See https://tools.ietf.org/html/rfc2315#section-13. @@ -1025,41 +1039,35 @@ static int add_encrypted_data(CBB *out, int pbe_nid, const char *password, // See https://tools.ietf.org/html/rfc2315#section-10.1. !CBB_add_asn1(&encrypted_data, &encrypted_content_info, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&encrypted_content_info, &inner_type, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&inner_type, kPKCS7Data, sizeof(kPKCS7Data)) || + !CBB_add_asn1_element(&encrypted_content_info, CBS_ASN1_OBJECT, + kPKCS7Data, sizeof(kPKCS7Data)) || // Set up encryption and fill in contentEncryptionAlgorithm. - !pkcs12_pbe_encrypt_init(&encrypted_content_info, &ctx, pbe_nid, - iterations, password, password_len, salt, - sizeof(salt)) || + !pkcs12_pbe_encrypt_init(&encrypted_content_info, ctx.get(), pbe_nid, + pbe_cipher, iterations, password, password_len, + salt, sizeof(salt)) || // Note this tag is primitive. It is an implicitly-tagged OCTET_STRING, so // it inherits the inner tag's constructed bit. !CBB_add_asn1(&encrypted_content_info, &encrypted_content, CBS_ASN1_CONTEXT_SPECIFIC | 0)) { - goto err; + return 0; } - { - size_t max_out = in_len + EVP_CIPHER_CTX_block_size(&ctx); - if (max_out < in_len) { - OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_TOO_LONG); - goto err; - } - - uint8_t *ptr; - int n1, n2; - if (!CBB_reserve(&encrypted_content, &ptr, max_out) || - !EVP_CipherUpdate(&ctx, ptr, &n1, in, in_len) || - !EVP_CipherFinal_ex(&ctx, ptr + n1, &n2) || - !CBB_did_write(&encrypted_content, n1 + n2) || !CBB_flush(out)) { - goto err; - } + size_t max_out = in_len + EVP_CIPHER_CTX_block_size(ctx.get()); + if (max_out < in_len) { + OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_TOO_LONG); + return 0; } - ret = 1; + uint8_t *ptr; + size_t n1, n2; + if (!CBB_reserve(&encrypted_content, &ptr, max_out) || + !EVP_CipherUpdate_ex(ctx.get(), ptr, &n1, max_out, in, in_len) || + !EVP_CipherFinal_ex2(ctx.get(), ptr + n1, &n2, max_out - n1) || + !CBB_did_write(&encrypted_content, n1 + n2) || !CBB_flush(out)) { + return 0; + } -err: - EVP_CIPHER_CTX_cleanup(&ctx); - return ret; + return 1; } PKCS12 *PKCS12_create(const char *password, const char *name, @@ -1067,16 +1075,16 @@ PKCS12 *PKCS12_create(const char *password, const char *name, const STACK_OF(X509) *chain, int key_nid, int cert_nid, int iterations, int mac_iterations, int key_type) { if (key_nid == 0) { - key_nid = NID_pbe_WithSHA1And3_Key_TripleDES_CBC; + key_nid = NID_aes_256_cbc; } if (cert_nid == 0) { - cert_nid = NID_pbe_WithSHA1And40BitRC2_CBC; + cert_nid = NID_aes_256_cbc; } if (iterations == 0) { iterations = PKCS12_DEFAULT_ITER; } if (mac_iterations == 0) { - mac_iterations = 1; + mac_iterations = PKCS12_DEFAULT_ITER; } if ( // In OpenSSL, this specifies a non-standard Microsoft key usage // extension which we do not currently support. @@ -1086,16 +1094,16 @@ PKCS12 *PKCS12_create(const char *password, const char *name, // PKCS#12 file. mac_iterations < 0 || // Don't encode empty objects. - (pkey == NULL && cert == NULL && sk_X509_num(chain) == 0)) { + (pkey == nullptr && cert == nullptr && sk_X509_num(chain) == 0)) { OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNSUPPORTED_OPTIONS); - return 0; + return nullptr; } // PKCS#12 is a very confusing recursive data format, built out of another // recursive data format. Section 5.1 of RFC 7292 describes the encoding // algorithm, but there is no clear overview. A quick summary: // - // PKCS#7 defines a ContentInfo structure, which is a overgeneralized typed + // PKCS#7 defines a ContentInfo structure, which is an overgeneralized typed // combinator structure for applying cryptography. We care about two types. A // data ContentInfo contains an OCTET STRING and is a leaf node of the // combinator tree. An encrypted-data ContentInfo contains encryption @@ -1121,39 +1129,38 @@ PKCS12 *PKCS12_create(const char *password, const char *name, // key-specific encryption container, PKCS8ShroudedKeyBag, which is used // instead. - // Note that |password| may be NULL to specify no password, rather than the + // Note that `password` may be NULL to specify no password, rather than the // empty string. They are encoded differently in PKCS#12. (One is the empty // byte array and the other is NUL-terminated UCS-2.) - size_t password_len = password != NULL ? strlen(password) : 0; + size_t password_len = password != nullptr ? strlen(password) : 0; uint8_t key_id[EVP_MAX_MD_SIZE]; unsigned key_id_len = 0; - if (cert != NULL && pkey != NULL) { + if (cert != nullptr && pkey != nullptr) { if (!X509_check_private_key(cert, pkey) || // Matching OpenSSL, use the SHA-1 hash of the certificate as the local // key ID. Some PKCS#12 consumers require one to connect the private key // and certificate. !X509_digest(cert, EVP_sha1(), key_id, &key_id_len)) { - return 0; + return nullptr; } } // See https://tools.ietf.org/html/rfc7292#section-4. - PKCS12 *ret = NULL; - CBB cbb, pfx, auth_safe, auth_safe_oid, auth_safe_wrapper, auth_safe_data, - content_infos; + PKCS12 *ret = nullptr; + CBB cbb, pfx, auth_safe, auth_safe_wrapper, auth_safe_data, content_infos; uint8_t mac_key[EVP_MAX_MD_SIZE]; if (!CBB_init(&cbb, 0) || !CBB_add_asn1(&cbb, &pfx, CBS_ASN1_SEQUENCE) || !CBB_add_asn1_uint64(&pfx, 3) || // auth_safe is a data ContentInfo. !CBB_add_asn1(&pfx, &auth_safe, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&auth_safe, &auth_safe_oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&auth_safe_oid, kPKCS7Data, sizeof(kPKCS7Data)) || + !CBB_add_asn1_element(&auth_safe, CBS_ASN1_OBJECT, kPKCS7Data, + sizeof(kPKCS7Data)) || !CBB_add_asn1(&auth_safe, &auth_safe_wrapper, CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) || !CBB_add_asn1(&auth_safe_wrapper, &auth_safe_data, CBS_ASN1_OCTETSTRING) || - // See https://tools.ietf.org/html/rfc7292#section-4.1. |auth_safe|'s + // See https://tools.ietf.org/html/rfc7292#section-4.1. `auth_safe`'s // contains a SEQUENCE of ContentInfos. !CBB_add_asn1(&auth_safe_data, &content_infos, CBS_ASN1_SEQUENCE)) { goto err; @@ -1161,17 +1168,17 @@ PKCS12 *PKCS12_create(const char *password, const char *name, // If there are any certificates, place them in CertBags wrapped in a single // encrypted ContentInfo. - if (cert != NULL || sk_X509_num(chain) > 0) { + if (cert != nullptr || sk_X509_num(chain) > 0) { if (cert_nid < 0) { // Place the certificates in an unencrypted ContentInfo. This could be // more compactly-encoded by reusing the same ContentInfo as the key, but // OpenSSL does not do this. We keep them separate for consistency. (Keys, // even when encrypted, are always placed in unencrypted ContentInfos. // PKCS#12 defines bag-level encryption for keys.) - CBB content_info, oid, wrapper, data; + CBB content_info, wrapper, data; if (!CBB_add_asn1(&content_infos, &content_info, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&content_info, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, kPKCS7Data, sizeof(kPKCS7Data)) || + !CBB_add_asn1_element(&content_info, CBS_ASN1_OBJECT, kPKCS7Data, + sizeof(kPKCS7Data)) || !CBB_add_asn1(&content_info, &wrapper, CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) || !CBB_add_asn1(&wrapper, &data, CBS_ASN1_OCTETSTRING) || @@ -1181,13 +1188,21 @@ PKCS12 *PKCS12_create(const char *password, const char *name, goto err; } } else { + // This function differs from other OpenSSL functions in how PBES1 and + // PBES2 schemes are selected. If the NID matches a cipher, treat this as + // PBES2 instead. Convert to the other convention. + const EVP_CIPHER *cipher = pkcs5_pbe2_nid_to_cipher(cert_nid); + if (cipher != nullptr) { + cert_nid = -1; + } CBB plaintext_cbb; - int ok = CBB_init(&plaintext_cbb, 0) && - add_cert_safe_contents(&plaintext_cbb, cert, chain, name, key_id, - key_id_len) && - add_encrypted_data( - &content_infos, cert_nid, password, password_len, iterations, - CBB_data(&plaintext_cbb), CBB_len(&plaintext_cbb)); + int ok = + CBB_init(&plaintext_cbb, 0) && + add_cert_safe_contents(&plaintext_cbb, cert, chain, name, key_id, + key_id_len) && + add_encrypted_data(&content_infos, cert_nid, cipher, password, + password_len, iterations, CBB_data(&plaintext_cbb), + CBB_len(&plaintext_cbb)); CBB_cleanup(&plaintext_cbb); if (!ok) { goto err; @@ -1199,37 +1214,43 @@ PKCS12 *PKCS12_create(const char *password, const char *name, // wrapped in an unencrypted ContentInfo. (One could also place it in a KeyBag // inside an encrypted ContentInfo, but OpenSSL does not do this and some // PKCS#12 consumers do not support KeyBags.) - if (pkey != NULL) { - CBB content_info, oid, wrapper, data, safe_contents, bag, bag_oid, - bag_contents; + if (pkey != nullptr) { + CBB content_info, wrapper, data, safe_contents, bag, bag_contents; if ( // Add another data ContentInfo. !CBB_add_asn1(&content_infos, &content_info, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&content_info, &oid, CBS_ASN1_OBJECT) || - !CBB_add_bytes(&oid, kPKCS7Data, sizeof(kPKCS7Data)) || + !CBB_add_asn1_element(&content_info, CBS_ASN1_OBJECT, kPKCS7Data, + sizeof(kPKCS7Data)) || !CBB_add_asn1(&content_info, &wrapper, CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) || !CBB_add_asn1(&wrapper, &data, CBS_ASN1_OCTETSTRING) || !CBB_add_asn1(&data, &safe_contents, CBS_ASN1_SEQUENCE) || // Add a SafeBag containing a PKCS8ShroudedKeyBag. - !CBB_add_asn1(&safe_contents, &bag, CBS_ASN1_SEQUENCE) || - !CBB_add_asn1(&bag, &bag_oid, CBS_ASN1_OBJECT)) { + !CBB_add_asn1(&safe_contents, &bag, CBS_ASN1_SEQUENCE)) { goto err; } if (key_nid < 0) { - if (!CBB_add_bytes(&bag_oid, kKeyBag, sizeof(kKeyBag)) || + if (!CBB_add_asn1_element(&bag, CBS_ASN1_OBJECT, kKeyBag, + sizeof(kKeyBag)) || !CBB_add_asn1(&bag, &bag_contents, CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) || !EVP_marshal_private_key(&bag_contents, pkey)) { goto err; } } else { - if (!CBB_add_bytes(&bag_oid, kPKCS8ShroudedKeyBag, - sizeof(kPKCS8ShroudedKeyBag)) || + // This function differs from other OpenSSL functions in how PBES1 and + // PBES2 schemes are selected. If the NID matches a cipher, treat this as + // PBES2 instead. Convert to the other convention. + const EVP_CIPHER *cipher = pkcs5_pbe2_nid_to_cipher(key_nid); + if (cipher != nullptr) { + key_nid = -1; + } + if (!CBB_add_asn1_element(&bag, CBS_ASN1_OBJECT, kPKCS8ShroudedKeyBag, + sizeof(kPKCS8ShroudedKeyBag)) || !CBB_add_asn1(&bag, &bag_contents, CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) || !PKCS8_marshal_encrypted_private_key( - &bag_contents, key_nid, NULL, password, password_len, - NULL /* generate a random salt */, + &bag_contents, key_nid, cipher, password, password_len, + nullptr /* generate a random salt */, 0 /* use default salt length */, iterations, pkey)) { goto err; } @@ -1246,7 +1267,7 @@ PKCS12 *PKCS12_create(const char *password, const char *name, { // Compute the MAC. Match OpenSSL in using SHA-1 as the hash function. The - // MAC covers |auth_safe_data|. + // MAC covers `auth_safe_data`. const EVP_MD *mac_md = EVP_sha1(); uint8_t mac_salt[PKCS5_SALT_LEN]; uint8_t mac[EVP_MAX_MD_SIZE]; @@ -1261,14 +1282,22 @@ PKCS12 *PKCS12_create(const char *password, const char *name, goto err; } - CBB mac_data, digest_info, mac_cbb, mac_salt_cbb; + CBB mac_data, digest_info; if (!CBB_add_asn1(&pfx, &mac_data, CBS_ASN1_SEQUENCE) || !CBB_add_asn1(&mac_data, &digest_info, CBS_ASN1_SEQUENCE) || + // OpenSSL and NSS always include a NULL parameter with the digest + // algorithm. Windows does not. RFC 7292 imports DigestInfo from PKCS + // #7. PKCS #7 does not actually use DigestInfo. It just describes + // RSASSA-PKCS1-v1_5 signing as encoding a DigestInfo and then + // "encrypting" it with the private key. In that context, NULL should be + // included. Confusingly, there is also a digestAlgorithm field in + // SignerInfo. There, RFC 5754 says to omit the NULL. But that field + // does not use DigestInfo per se. + // + // We match OpenSSL, NSS, and RSASSA-PKCS1-v1_5 in including the NULL. !EVP_marshal_digest_algorithm(&digest_info, mac_md) || - !CBB_add_asn1(&digest_info, &mac_cbb, CBS_ASN1_OCTETSTRING) || - !CBB_add_bytes(&mac_cbb, mac, mac_len) || - !CBB_add_asn1(&mac_data, &mac_salt_cbb, CBS_ASN1_OCTETSTRING) || - !CBB_add_bytes(&mac_salt_cbb, mac_salt, sizeof(mac_salt)) || + !CBB_add_asn1_octet_string(&digest_info, mac, mac_len) || + !CBB_add_asn1_octet_string(&mac_data, mac_salt, sizeof(mac_salt)) || // The iteration count has a DEFAULT of 1, but RFC 7292 says "The // default is for historical reasons and its use is deprecated." Thus we // explicitly encode the iteration count, though it is not valid DER. @@ -1276,10 +1305,10 @@ PKCS12 *PKCS12_create(const char *password, const char *name, goto err; } - ret = reinterpret_cast(OPENSSL_malloc(sizeof(PKCS12))); - if (ret == NULL || !CBB_finish(&cbb, &ret->ber_bytes, &ret->ber_len)) { - OPENSSL_free(ret); - ret = NULL; + ret = New(); + if (ret == nullptr || !CBB_finish(&cbb, &ret->ber_bytes, &ret->ber_len)) { + Delete(ret); + ret = nullptr; goto err; } } @@ -1291,9 +1320,9 @@ err: } void PKCS12_free(PKCS12 *p12) { - if (p12 == NULL) { + if (p12 == nullptr) { return; } OPENSSL_free(p12->ber_bytes); - OPENSSL_free(p12); + Delete(p12); } diff --git a/Sources/CNIOBoringSSL/crypto/poly1305/internal.h b/Sources/CNIOBoringSSL/crypto/poly1305/internal.h index fe7895a5..5230f88e 100644 --- a/Sources/CNIOBoringSSL/crypto/poly1305/internal.h +++ b/Sources/CNIOBoringSSL/crypto/poly1305/internal.h @@ -1,30 +1,46 @@ -/* Copyright 2016 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2016 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. -#ifndef OPENSSL_HEADER_POLY1305_INTERNAL_H -#define OPENSSL_HEADER_POLY1305_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_POLY1305_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_POLY1305_INTERNAL_H #include #include -#if defined(__cplusplus) -extern "C" { -#endif + +BSSL_NAMESPACE_BEGIN #if defined(OPENSSL_ARM) && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_APPLE) #define OPENSSL_POLY1305_NEON +struct alignas(16) fe1305x2 { + uint32_t v[12]; // for alignment; only using 10 +}; + +extern "C" { +// openssl_poly1305_neon2_addmulmod computes (x * y) + c and writes the result +// to `r`. +void openssl_poly1305_neon2_addmulmod(fe1305x2 *r, const fe1305x2 *x, + const fe1305x2 *y, const fe1305x2 *c); + +// openssl_poly1305_neon2_blocks processes `inlen` bytes from `in` and updates +// the hash state in `h` using the precomputed powers in `precomp`. It returns +// the number of bytes that were not processed (i.e. the remainder < 32 bytes). +int openssl_poly1305_neon2_blocks(fe1305x2 *h, const fe1305x2 precomp[2], + const uint8_t *in, size_t inlen); +} + void CRYPTO_poly1305_init_neon(poly1305_state *state, const uint8_t key[32]); void CRYPTO_poly1305_update_neon(poly1305_state *state, const uint8_t *in, @@ -33,9 +49,6 @@ void CRYPTO_poly1305_update_neon(poly1305_state *state, const uint8_t *in, void CRYPTO_poly1305_finish_neon(poly1305_state *state, uint8_t mac[16]); #endif +BSSL_NAMESPACE_END -#if defined(__cplusplus) -} // extern C -#endif - -#endif // OPENSSL_HEADER_POLY1305_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_POLY1305_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/poly1305/poly1305.cc b/Sources/CNIOBoringSSL/crypto/poly1305/poly1305.cc index f06f5ede..50fddf3c 100644 --- a/Sources/CNIOBoringSSL/crypto/poly1305/poly1305.cc +++ b/Sources/CNIOBoringSSL/crypto/poly1305/poly1305.cc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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. // This implementation of poly1305 is by Andrew Moon // (https://github.com/floodyberry/poly1305-donna) and released as public @@ -25,6 +25,8 @@ #include "internal.h" +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; } @@ -42,13 +44,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 inline struct poly1305_state_st *poly1305_aligned_state( - poly1305_state *state) { +static 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 +// 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) { diff --git a/Sources/CNIOBoringSSL/crypto/poly1305/poly1305_arm.cc b/Sources/CNIOBoringSSL/crypto/poly1305/poly1305_arm.cc index 00bb8c5b..9818394c 100644 --- a/Sources/CNIOBoringSSL/crypto/poly1305/poly1305_arm.cc +++ b/Sources/CNIOBoringSSL/crypto/poly1305/poly1305_arm.cc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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. // This implementation was taken from the public domain, neon2 version in // SUPERCOP by D. J. Bernstein and Peter Schwabe. @@ -24,23 +24,13 @@ #include "internal.h" -#if defined(OPENSSL_POLY1305_NEON) +BSSL_NAMESPACE_BEGIN -typedef struct { - uint32_t v[12]; // for alignment; only using 10 -} fe1305x2; +#if defined(OPENSSL_POLY1305_NEON) #define addmulmod openssl_poly1305_neon2_addmulmod #define blocks openssl_poly1305_neon2_blocks -extern "C" { -extern void addmulmod(fe1305x2 *r, const fe1305x2 *x, const fe1305x2 *y, - const fe1305x2 *c); - -extern int blocks(fe1305x2 *h, const fe1305x2 *precomp, const uint8_t *in, - size_t inlen); -} - static void freeze(fe1305x2 *r) { int i; @@ -106,16 +96,6 @@ static void freeze(fe1305x2 *r) { r->v[8] = y4; } -static void store32(uint8_t out[4], uint32_t v) { OPENSSL_memcpy(out, &v, 4); } - -// load32 exists to avoid breaking strict aliasing rules in -// fe1305x2_frombytearray. -static uint32_t load32(const uint8_t t[4]) { - uint32_t tmp; - OPENSSL_memcpy(&tmp, t, sizeof(tmp)); - return tmp; -} - static void fe1305x2_tobytearray(uint8_t r[16], fe1305x2 *x) { uint32_t x0 = x->v[0]; uint32_t x1 = x->v[2]; @@ -132,10 +112,10 @@ static void fe1305x2_tobytearray(uint8_t r[16], fe1305x2 *x) { x4 += x3 >> 26; x3 &= 0x3ffffff; - store32(r, x0 + (x1 << 26)); - store32(r + 4, (x1 >> 6) + (x2 << 20)); - store32(r + 8, (x2 >> 12) + (x3 << 14)); - store32(r + 12, (x3 >> 18) + (x4 << 8)); + CRYPTO_store_u32_le(r, x0 + (x1 << 26)); + CRYPTO_store_u32_le(r + 4, (x1 >> 6) + (x2 << 20)); + CRYPTO_store_u32_le(r + 8, (x2 >> 12) + (x3 << 14)); + CRYPTO_store_u32_le(r + 12, (x3 >> 18) + (x4 << 8)); } static void fe1305x2_frombytearray(fe1305x2 *r, const uint8_t *x, size_t xlen) { @@ -152,11 +132,11 @@ static void fe1305x2_frombytearray(fe1305x2 *r, const uint8_t *x, size_t xlen) { t[i] = 0; } - r->v[0] = 0x3ffffff & load32(t); - r->v[2] = 0x3ffffff & (load32(t + 3) >> 2); - r->v[4] = 0x3ffffff & (load32(t + 6) >> 4); - r->v[6] = 0x3ffffff & (load32(t + 9) >> 6); - r->v[8] = load32(t + 13); + r->v[0] = 0x3ffffff & CRYPTO_load_u32_le(t); + r->v[2] = 0x3ffffff & (CRYPTO_load_u32_le(t + 3) >> 2); + r->v[4] = 0x3ffffff & (CRYPTO_load_u32_le(t + 6) >> 4); + r->v[6] = 0x3ffffff & (CRYPTO_load_u32_le(t + 9) >> 6); + r->v[8] = CRYPTO_load_u32_le(t + 13); if (xlen) { for (i = 0; (i < 16) && (i < xlen); i++) { @@ -167,20 +147,20 @@ static void fe1305x2_frombytearray(fe1305x2 *r, const uint8_t *x, size_t xlen) { t[i] = 0; } - r->v[1] = 0x3ffffff & load32(t); - r->v[3] = 0x3ffffff & (load32(t + 3) >> 2); - r->v[5] = 0x3ffffff & (load32(t + 6) >> 4); - r->v[7] = 0x3ffffff & (load32(t + 9) >> 6); - r->v[9] = load32(t + 13); + r->v[1] = 0x3ffffff & CRYPTO_load_u32_le(t); + r->v[3] = 0x3ffffff & (CRYPTO_load_u32_le(t + 3) >> 2); + r->v[5] = 0x3ffffff & (CRYPTO_load_u32_le(t + 6) >> 4); + r->v[7] = 0x3ffffff & (CRYPTO_load_u32_le(t + 9) >> 6); + r->v[9] = CRYPTO_load_u32_le(t + 13); } else { r->v[1] = r->v[3] = r->v[5] = r->v[7] = r->v[9] = 0; } } -static const fe1305x2 zero alignas(16) = {0}; +static const fe1305x2 zero = {0}; struct poly1305_state_st { - uint8_t data[sizeof(fe1305x2[5]) + 128]; + fe1305x2 r, h, c, precomp[2]; uint8_t buf[32]; size_t buf_used; uint8_t key[16]; @@ -190,18 +170,21 @@ static_assert( sizeof(struct poly1305_state_st) + 63 <= sizeof(poly1305_state), "poly1305_state isn't large enough to hold aligned poly1305_state_st."); -void CRYPTO_poly1305_init_neon(poly1305_state *state, const uint8_t key[32]) { - struct poly1305_state_st *st = (struct poly1305_state_st *)(state); - fe1305x2 *const r = (fe1305x2 *)(st->data + (15 & (-(int)st->data))); - fe1305x2 *const h = r + 1; - fe1305x2 *const c = h + 1; - fe1305x2 *const precomp = c + 1; +static poly1305_state_st *poly1305_aligned_state(poly1305_state *state) { + return reinterpret_cast(align_pointer(state, 64)); +} - r->v[1] = r->v[0] = 0x3ffffff & load32(key); - r->v[3] = r->v[2] = 0x3ffff03 & (load32(key + 3) >> 2); - r->v[5] = r->v[4] = 0x3ffc0ff & (load32(key + 6) >> 4); - r->v[7] = r->v[6] = 0x3f03fff & (load32(key + 9) >> 6); - r->v[9] = r->v[8] = 0x00fffff & (load32(key + 12) >> 8); +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; + fe1305x2 *const h = &st->h; + fe1305x2 *const precomp = st->precomp; + + r->v[1] = r->v[0] = 0x3ffffff & CRYPTO_load_u32_le(key); + r->v[3] = r->v[2] = 0x3ffff03 & (CRYPTO_load_u32_le(key + 3) >> 2); + r->v[5] = r->v[4] = 0x3ffc0ff & (CRYPTO_load_u32_le(key + 6) >> 4); + r->v[7] = r->v[6] = 0x3f03fff & (CRYPTO_load_u32_le(key + 9) >> 6); + r->v[9] = r->v[8] = 0x00fffff & (CRYPTO_load_u32_le(key + 12) >> 8); for (size_t j = 0; j < 10; j++) { h->v[j] = 0; // XXX: should fast-forward a bit @@ -216,11 +199,10 @@ void CRYPTO_poly1305_init_neon(poly1305_state *state, const uint8_t key[32]) { void CRYPTO_poly1305_update_neon(poly1305_state *state, const uint8_t *in, size_t in_len) { - struct poly1305_state_st *st = (struct poly1305_state_st *)(state); - fe1305x2 *const r = (fe1305x2 *)(st->data + (15 & (-(int)st->data))); - fe1305x2 *const h = r + 1; - fe1305x2 *const c = h + 1; - fe1305x2 *const precomp = c + 1; + poly1305_state_st *st = poly1305_aligned_state(state); + fe1305x2 *const h = &st->h; + fe1305x2 *const c = &st->c; + fe1305x2 *const precomp = st->precomp; if (st->buf_used) { size_t todo = 32 - st->buf_used; @@ -263,11 +245,11 @@ void CRYPTO_poly1305_update_neon(poly1305_state *state, const uint8_t *in, } void CRYPTO_poly1305_finish_neon(poly1305_state *state, uint8_t mac[16]) { - struct poly1305_state_st *st = (struct poly1305_state_st *)(state); - fe1305x2 *const r = (fe1305x2 *)(st->data + (15 & (-(int)st->data))); - fe1305x2 *const h = r + 1; - fe1305x2 *const c = h + 1; - fe1305x2 *const precomp = c + 1; + poly1305_state_st *st = poly1305_aligned_state(state); + fe1305x2 *const r = &st->r; + fe1305x2 *const h = &st->h; + fe1305x2 *const c = &st->c; + fe1305x2 *const precomp = st->precomp; addmulmod(h, h, precomp, &zero); @@ -308,3 +290,5 @@ void CRYPTO_poly1305_finish_neon(poly1305_state *state, uint8_t mac[16]) { } #endif // OPENSSL_POLY1305_NEON + +BSSL_NAMESPACE_END diff --git a/Sources/CNIOBoringSSL/crypto/poly1305/poly1305_vec.cc b/Sources/CNIOBoringSSL/crypto/poly1305/poly1305_vec.cc index a4fde48b..a2f1d254 100644 --- a/Sources/CNIOBoringSSL/crypto/poly1305/poly1305_vec.cc +++ b/Sources/CNIOBoringSSL/crypto/poly1305/poly1305_vec.cc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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. // This implementation of poly1305 is by Andrew Moon // (https://github.com/floodyberry/poly1305-donna) and released as public @@ -29,29 +29,30 @@ #include + +using namespace bssl; + +namespace { + typedef __m128i xmmi; -alignas(16) static const uint32_t poly1305_x64_sse2_message_mask[4] = { +alignas(16) const uint32_t poly1305_x64_sse2_message_mask[4] = { (1 << 26) - 1, 0, (1 << 26) - 1, 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}; +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}; -static inline uint128_t add128(uint128_t a, uint128_t b) { return a + b; } +uint128_t add128(uint128_t a, uint128_t b) { return a + b; } -static inline uint128_t add128_64(uint128_t a, uint64_t b) { return a + b; } +uint128_t add128_64(uint128_t a, uint64_t b) { return a + b; } -static inline uint128_t mul64x64_128(uint64_t a, uint64_t b) { - return (uint128_t)a * b; -} +uint128_t mul64x64_128(uint64_t a, uint64_t b) { return (uint128_t)a * b; } -static inline uint64_t lo128(uint128_t a) { return (uint64_t)a; } +uint64_t lo128(uint128_t a) { return (uint64_t)a; } -static inline uint64_t shr128(uint128_t v, const int shift) { - return (uint64_t)(v >> shift); -} +uint64_t shr128(uint128_t v, const int shift) { return (uint64_t)(v >> shift); } -static inline uint64_t shr128_pair(uint64_t hi, uint64_t lo, const int shift) { +uint64_t shr128_pair(uint64_t hi, uint64_t lo, const int shift) { return (uint64_t)((((uint128_t)hi << 64) | lo) >> shift); } @@ -83,14 +84,13 @@ static_assert(sizeof(struct poly1305_state_internal_t) + 63 <= "poly1305_state isn't large enough to hold aligned " "poly1305_state_internal_t"); -static inline poly1305_state_internal *poly1305_aligned_state( - poly1305_state *state) { - return (poly1305_state_internal *)(((uint64_t)state + 63) & ~63); +poly1305_state_internal *poly1305_aligned_state(poly1305_state *state) { + return reinterpret_cast(align_pointer(state, 64)); } -static inline size_t poly1305_min(size_t a, size_t b) { - return (a < b) ? a : b; -} +size_t poly1305_min(size_t a, size_t b) { return (a < b) ? a : b; } + +} // namespace void CRYPTO_poly1305_init(poly1305_state *state, const uint8_t key[32]) { poly1305_state_internal *st = poly1305_aligned_state(state); @@ -134,8 +134,9 @@ void CRYPTO_poly1305_init(poly1305_state *state, const uint8_t key[32]) { st->leftover = 0; } -static void poly1305_first_block(poly1305_state_internal *st, - const uint8_t *m) { +namespace { + +void poly1305_first_block(poly1305_state_internal *st, const uint8_t *m) { const xmmi MMASK = _mm_load_si128((const xmmi *)poly1305_x64_sse2_message_mask); const xmmi FIVE = _mm_load_si128((const xmmi *)poly1305_x64_sse2_5); @@ -158,7 +159,7 @@ static void poly1305_first_block(poly1305_state_internal *st, pad0 = ((uint64_t)p->R23.d[3] << 32) | (uint64_t)p->R23.d[1]; pad1 = ((uint64_t)p->R24.d[3] << 32) | (uint64_t)p->R24.d[1]; - // compute powers r^2,r^4 + // compute powers r², r⁴ r20 = r0; r21 = r1; r22 = r2; @@ -228,8 +229,8 @@ static void poly1305_first_block(poly1305_state_internal *st, st->H[4] = _mm_or_si128(_mm_srli_epi64(T6, 40), HIBIT); } -static void poly1305_blocks(poly1305_state_internal *st, const uint8_t *m, - size_t bytes) { +void poly1305_blocks(poly1305_state_internal *st, const uint8_t *m, + size_t bytes) { const xmmi MMASK = _mm_load_si128((const xmmi *)poly1305_x64_sse2_message_mask); const xmmi FIVE = _mm_load_si128((const xmmi *)poly1305_x64_sse2_5); @@ -248,7 +249,7 @@ static void poly1305_blocks(poly1305_state_internal *st, const uint8_t *m, H4 = st->H[4]; while (bytes >= 64) { - // H *= [r^4,r^4] + // H *= [r⁴, r⁴] p = &st->P[0]; T0 = _mm_mul_epu32(H0, p->R20.v); T1 = _mm_mul_epu32(H0, p->R21.v); @@ -296,7 +297,7 @@ static void poly1305_blocks(poly1305_state_internal *st, const uint8_t *m, T5 = _mm_mul_epu32(H4, p->R20.v); T4 = _mm_add_epi64(T4, T5); - // H += [Mx,My]*[r^2,r^2] + // H += [Mx,My]⋅[r², r²] T5 = _mm_unpacklo_epi64(_mm_loadl_epi64((const xmmi *)(m + 0)), _mm_loadl_epi64((const xmmi *)(m + 16))); T6 = _mm_unpacklo_epi64(_mm_loadl_epi64((const xmmi *)(m + 8)), @@ -419,8 +420,8 @@ static void poly1305_blocks(poly1305_state_internal *st, const uint8_t *m, st->H[4] = H4; } -static size_t poly1305_combine(poly1305_state_internal *st, const uint8_t *m, - size_t bytes) { +size_t poly1305_combine(poly1305_state_internal *st, const uint8_t *m, + size_t bytes) { const xmmi MMASK = _mm_load_si128((const xmmi *)poly1305_x64_sse2_message_mask); const xmmi HIBIT = _mm_load_si128((const xmmi *)poly1305_x64_sse2_1shl128); @@ -663,6 +664,8 @@ static size_t poly1305_combine(poly1305_state_internal *st, const uint8_t *m, return consumed; } +} // namespace + void CRYPTO_poly1305_update(poly1305_state *state, const uint8_t *m, size_t bytes) { poly1305_state_internal *st = poly1305_aligned_state(state); diff --git a/Sources/CNIOBoringSSL/crypto/pool/internal.h b/Sources/CNIOBoringSSL/crypto/pool/internal.h index c829bc1a..49d9b8fe 100644 --- a/Sources/CNIOBoringSSL/crypto/pool/internal.h +++ b/Sources/CNIOBoringSSL/crypto/pool/internal.h @@ -1,51 +1,95 @@ -/* Copyright 2016 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2016 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. -#ifndef OPENSSL_HEADER_POOL_INTERNAL_H -#define OPENSSL_HEADER_POOL_INTERNAL_H - -#include -#include +#ifndef OPENSSL_HEADER_CRYPTO_POOL_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_POOL_INTERNAL_H #include "../internal.h" #include "../lhash/internal.h" +#include "../mem_internal.h" -#if defined(__cplusplus) -extern "C" { -#endif +DECLARE_OPAQUE_STRUCT(crypto_buffer_st, CryptoBuffer) +DECLARE_OPAQUE_STRUCT(crypto_buffer_pool_st, CryptoBufferPool) +BSSL_NAMESPACE_BEGIN -DEFINE_LHASH_OF(CRYPTO_BUFFER) +// A CryptoBufferPoolHandle is the portion of the pool that lasts as long as any +// live buffer or pool. This allows buffers to outlive the pool. (The pool is +// only needed as long as callers wish to create new buffers.) +class CryptoBufferPoolHandle : public RefCounted { + public: + explicit CryptoBufferPoolHandle(CryptoBufferPool *pool) + : RefCounted(CheckSubClass()), pool_(pool) {} -struct crypto_buffer_st { - CRYPTO_BUFFER_POOL *pool; - uint8_t *data; - size_t len; - CRYPTO_refcount_t references; - int data_is_static; + // pool_ is protected by lock_. + Mutex lock_; + CryptoBufferPool *pool_ = nullptr; + + private: + friend RefCounted; + ~CryptoBufferPoolHandle() = default; }; -struct crypto_buffer_pool_st { - LHASH_OF(CRYPTO_BUFFER) *bufs; - CRYPTO_MUTEX lock; - const uint64_t hash_key[2]; +class CryptoBuffer : public crypto_buffer_st { + public: + CryptoBuffer() = default; + CryptoBuffer(const CryptoBuffer &) = delete; + CryptoBuffer &operator=(const CryptoBuffer &) = delete; + + Span span() const { return Span(data_, len_); } + + // Instead of subclassing RefCounted, implement refcounting by hand. + // CryptoBuffer's refcounting must synchronize with CryptoBufferPool. + static constexpr bool kAllowRefCountedUniquePtr = true; + void UpRefInternal() const; + void DecRefInternal(); + + UniquePtr pool_handle_; + uint8_t *data_ = nullptr; + size_t len_ = 0; + mutable CRYPTO_refcount_t references_ = 1; + bool data_is_static_ = false; + + private: + ~CryptoBuffer(); }; +DEFINE_LHASH_OF(CryptoBuffer) -#if defined(__cplusplus) -} // extern C -#endif +class CryptoBufferPool : public crypto_buffer_pool_st, + public RefCounted { + public: + CryptoBufferPool(); -#endif // OPENSSL_HEADER_POOL_INTERNAL_H + // Hash returns the hash of `data`. + uint32_t Hash(Span data) const; + + // FindBufferLocked looks for a buffer with hash `hash` and contents `data`. + // It returns it if found and nullptr otherwise. `handle_->lock_` must be + // locked for reading or writing before calling this. + CryptoBuffer *FindBufferLocked(uint32_t hash, Span data); + + UniquePtr handle_; + LHASH_OF(CryptoBuffer) *bufs_ = nullptr; + uint64_t hash_key_[2]; + + private: + friend RefCounted; + ~CryptoBufferPool(); +}; + +BSSL_NAMESPACE_END + +#endif // OPENSSL_HEADER_CRYPTO_POOL_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/pool/pool.cc b/Sources/CNIOBoringSSL/crypto/pool/pool.cc index c7a669d7..36acc304 100644 --- a/Sources/CNIOBoringSSL/crypto/pool/pool.cc +++ b/Sources/CNIOBoringSSL/crypto/pool/pool.cc @@ -1,16 +1,16 @@ -/* Copyright 2016 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2016 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 @@ -21,171 +21,223 @@ #include #include #include -#include #include "../internal.h" +#include "../mem_internal.h" #include "internal.h" -static uint32_t CRYPTO_BUFFER_hash(const CRYPTO_BUFFER *buf) { - return (uint32_t)SIPHASH_24(buf->pool->hash_key, buf->data, buf->len); +using namespace bssl; + +static uint32_t CRYPTO_BUFFER_hash(const CryptoBuffer *buf) { + // This function must be called while there is a read or write lock on the + // pool, so it is safe to read `pool_`. + return buf->pool_handle_->pool_->Hash(buf->span()); } -static int CRYPTO_BUFFER_cmp(const CRYPTO_BUFFER *a, const CRYPTO_BUFFER *b) { - // Only |CRYPTO_BUFFER|s from the same pool have compatible hashes. - assert(a->pool != NULL); - assert(a->pool == b->pool); - if (a->len != b->len) { - return 1; - } - return OPENSSL_memcmp(a->data, b->data, a->len); +static int CRYPTO_BUFFER_cmp(const CryptoBuffer *a, const CryptoBuffer *b) { + // Only `CRYPTO_BUFFER`s from the same pool have compatible hashes. + assert(a->pool_handle_ != nullptr); + assert(a->pool_handle_ == b->pool_handle_); + return a->span() == b->span() ? 0 : 1; } -CRYPTO_BUFFER_POOL *CRYPTO_BUFFER_POOL_new(void) { - CRYPTO_BUFFER_POOL *pool = reinterpret_cast( - OPENSSL_zalloc(sizeof(CRYPTO_BUFFER_POOL))); - if (pool == NULL) { - return NULL; +CryptoBufferPool::CryptoBufferPool() : RefCounted(CheckSubClass()) { + RAND_bytes(reinterpret_cast(&hash_key_), sizeof(hash_key_)); +} + +CryptoBufferPool::~CryptoBufferPool() { + if (handle_) { + MutexWriteLock lock(&handle_->lock_); + handle_->pool_ = nullptr; + } + lh_CryptoBuffer_free(bufs_); +} + +uint32_t CryptoBufferPool::Hash(Span data) const { + return static_cast(SIPHASH_24(hash_key_, data.data(), data.size())); +} + +CryptoBuffer *CryptoBufferPool::FindBufferLocked(uint32_t hash, + Span data) { + return lh_CryptoBuffer_retrieve_key( + bufs_, &data, hash, + [](const void *key_v, const CryptoBuffer *buf) -> int { + Span key = + *static_cast *>(key_v); + return key == buf->span() ? 0 : 1; + }); +} + +CRYPTO_BUFFER_POOL *CRYPTO_BUFFER_POOL_new() { + auto pool = MakeUnique(); + if (pool == nullptr) { + return nullptr; } - pool->bufs = lh_CRYPTO_BUFFER_new(CRYPTO_BUFFER_hash, CRYPTO_BUFFER_cmp); - if (pool->bufs == NULL) { - OPENSSL_free(pool); - return NULL; + pool->bufs_ = lh_CryptoBuffer_new(CRYPTO_BUFFER_hash, CRYPTO_BUFFER_cmp); + pool->handle_ = MakeUnique(pool.get()); + if (pool->bufs_ == nullptr || pool->handle_ == nullptr) { + return nullptr; } - CRYPTO_MUTEX_init(&pool->lock); - RAND_bytes((uint8_t *)&pool->hash_key, sizeof(pool->hash_key)); - - return pool; + return pool.release(); } void CRYPTO_BUFFER_POOL_free(CRYPTO_BUFFER_POOL *pool) { - if (pool == NULL) { - return; + if (pool != nullptr) { + FromOpaque(pool)->DecRefInternal(); } - -#if !defined(NDEBUG) - CRYPTO_MUTEX_lock_write(&pool->lock); - assert(lh_CRYPTO_BUFFER_num_items(pool->bufs) == 0); - CRYPTO_MUTEX_unlock_write(&pool->lock); -#endif - - lh_CRYPTO_BUFFER_free(pool->bufs); - CRYPTO_MUTEX_cleanup(&pool->lock); - OPENSSL_free(pool); } -static void crypto_buffer_free_object(CRYPTO_BUFFER *buf) { - if (!buf->data_is_static) { - OPENSSL_free(buf->data); - } - OPENSSL_free(buf); +int CRYPTO_BUFFER_POOL_up_ref(CRYPTO_BUFFER_POOL *pool) { + FromOpaque(pool)->UpRefInternal(); + return 1; } -static CRYPTO_BUFFER *crypto_buffer_new(const uint8_t *data, size_t len, - int data_is_static, - CRYPTO_BUFFER_POOL *pool) { - if (pool != NULL) { - CRYPTO_BUFFER tmp; - tmp.data = (uint8_t *)data; - tmp.len = len; - tmp.pool = pool; +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. + // + // This is also safe if `buf->pool` is non-NULL because, if it were racing + // with `CRYPTO_BUFFER_free` then the two callers must have independent + // references already and so the reference count will never hit zero. + CRYPTO_refcount_inc(&references_); +} - CRYPTO_MUTEX_lock_read(&pool->lock); - CRYPTO_BUFFER *duplicate = lh_CRYPTO_BUFFER_retrieve(pool->bufs, &tmp); - if (data_is_static && duplicate != NULL && !duplicate->data_is_static) { - // If the new |CRYPTO_BUFFER| would have static data, but the duplicate - // does not, we replace the old one with the new static version. - duplicate = NULL; +void CryptoBuffer::DecRefInternal() { + // If there is a pool, decrementing the refcount must synchronize with it. + if (pool_handle_ == nullptr) { + if (!CRYPTO_refcount_dec_and_test_zero(&references_)) { + return; } - if (duplicate != NULL) { - CRYPTO_refcount_inc(&duplicate->references); + } else { + MutexWriteLock lock(&pool_handle_->lock_); + if (!CRYPTO_refcount_dec_and_test_zero(&references_)) { + return; } - CRYPTO_MUTEX_unlock_read(&pool->lock); - if (duplicate != NULL) { - return duplicate; + // We have an exclusive lock on the pool handle, therefore no concurrent + // lookups can find this buffer and increment the reference count. Thus, if + // the count is zero there are and can never be any more references and thus + // we can free this buffer. It is possible the pool was already destroyed, + // but it cannot be destroyed concurrently. + // + // Note it is possible `buf` is no longer in the pool, if it was replaced by + // a static version. If that static version was since removed, it is even + // possible for `found` to be NULL. + if (CryptoBufferPool *pool = pool_handle_->pool_; pool != nullptr) { + CryptoBuffer *found = lh_CryptoBuffer_retrieve(pool->bufs_, this); + if (found == this) { + found = lh_CryptoBuffer_delete(pool->bufs_, this); + assert(found == this); + (void)found; + } } } - CRYPTO_BUFFER *const buf = - reinterpret_cast(OPENSSL_zalloc(sizeof(CRYPTO_BUFFER))); - if (buf == NULL) { - return NULL; + this->~CryptoBuffer(); + OPENSSL_free(this); +} + +CryptoBuffer::~CryptoBuffer() { + if (!data_is_static_) { + OPENSSL_free(data_); + } +} + +static UniquePtr crypto_buffer_new(Span data, + bool data_is_static) { + UniquePtr buf = MakeUnique(); + if (buf == nullptr) { + return nullptr; } if (data_is_static) { - buf->data = (uint8_t *)data; - buf->data_is_static = 1; + buf->data_ = const_cast(data.data()); + buf->data_is_static_ = true; } else { - buf->data = reinterpret_cast(OPENSSL_memdup(data, len)); - if (len != 0 && buf->data == NULL) { - OPENSSL_free(buf); - return NULL; + buf->data_ = + static_cast(OPENSSL_memdup(data.data(), data.size())); + if (!data.empty() && buf->data_ == nullptr) { + return nullptr; } } - buf->len = len; - buf->references = 1; + buf->len_ = data.size(); + return buf; +} - if (pool == NULL) { - return buf; +static UniquePtr crypto_buffer_new_with_pool( + Span data, bool data_is_static, CryptoBufferPool *pool) { + if (pool == nullptr) { + return crypto_buffer_new(data, data_is_static); } - buf->pool = pool; + const uint32_t hash = pool->Hash(data); + { + // Look for a matching buffer in the pool. + MutexReadLock lock(&pool->handle_->lock_); + CryptoBuffer *duplicate = pool->FindBufferLocked(hash, data); + if (data_is_static && duplicate != nullptr && !duplicate->data_is_static_) { + // If the new `CRYPTO_BUFFER` would have static data, but the duplicate + // does not, we replace the old one with the new static version. + duplicate = nullptr; + } + if (duplicate != nullptr) { + return UpRef(duplicate); + } + } - CRYPTO_MUTEX_lock_write(&pool->lock); - CRYPTO_BUFFER *duplicate = lh_CRYPTO_BUFFER_retrieve(pool->bufs, buf); - if (data_is_static && duplicate != NULL && !duplicate->data_is_static) { - // If the new |CRYPTO_BUFFER| would have static data, but the duplicate does + UniquePtr buf = crypto_buffer_new(data, data_is_static); + if (buf == nullptr) { + return nullptr; + } + + MutexWriteLock lock(&pool->handle_->lock_); + CryptoBuffer *duplicate = pool->FindBufferLocked(hash, data); + if (data_is_static && duplicate != nullptr && !duplicate->data_is_static_) { + // If the new `CRYPTO_BUFFER` would have static data, but the duplicate does // not, we replace the old one with the new static version. - duplicate = NULL; + duplicate = nullptr; } - int inserted = 0; - if (duplicate == NULL) { - CRYPTO_BUFFER *old = NULL; - inserted = lh_CRYPTO_BUFFER_insert(pool->bufs, &old, buf); - // |old| may be non-NULL if a match was found but ignored. |pool->bufs| does - // not increment refcounts, so there is no need to clean up after the - // replacement. - } else { - CRYPTO_refcount_inc(&duplicate->references); - } - CRYPTO_MUTEX_unlock_write(&pool->lock); - - if (!inserted) { - // We raced to insert |buf| into the pool and lost, or else there was an - // error inserting. - crypto_buffer_free_object(buf); - return duplicate; + if (duplicate != nullptr) { + return UpRef(duplicate); } + // Insert `buf` into the pool. Note `old` may be non-NULL if a match was found + // but ignored. `pool->bufs_` does not increment refcounts, so there is no + // need to clean up after the replacement. + buf->pool_handle_ = UpRef(pool->handle_); + CryptoBuffer *old = nullptr; + if (!lh_CryptoBuffer_insert(pool->bufs_, &old, buf.get())) { + buf->pool_handle_ = nullptr; // No need to synchronize with the pool. + return nullptr; + } return buf; } CRYPTO_BUFFER *CRYPTO_BUFFER_new(const uint8_t *data, size_t len, CRYPTO_BUFFER_POOL *pool) { - return crypto_buffer_new(data, len, /*data_is_static=*/0, pool); + return crypto_buffer_new_with_pool(Span(data, len), /*data_is_static=*/false, + FromOpaque(pool)) + .release(); } CRYPTO_BUFFER *CRYPTO_BUFFER_alloc(uint8_t **out_data, size_t len) { - CRYPTO_BUFFER *const buf = - reinterpret_cast(OPENSSL_zalloc(sizeof(CRYPTO_BUFFER))); - if (buf == NULL) { - return NULL; + auto buf = MakeUnique(); + if (buf == nullptr) { + return nullptr; } - buf->data = reinterpret_cast(OPENSSL_malloc(len)); - if (len != 0 && buf->data == NULL) { - OPENSSL_free(buf); - return NULL; + buf->data_ = reinterpret_cast(OPENSSL_malloc(len)); + if (len != 0 && buf->data_ == nullptr) { + return nullptr; } - buf->len = len; - buf->references = 1; + buf->len_ = len; - *out_data = buf->data; - return buf; + *out_data = buf->data_; + return buf.release(); } CRYPTO_BUFFER *CRYPTO_BUFFER_new_from_CBS(const CBS *cbs, @@ -195,68 +247,36 @@ CRYPTO_BUFFER *CRYPTO_BUFFER_new_from_CBS(const CBS *cbs, CRYPTO_BUFFER *CRYPTO_BUFFER_new_from_static_data_unsafe( const uint8_t *data, size_t len, CRYPTO_BUFFER_POOL *pool) { - return crypto_buffer_new(data, len, /*data_is_static=*/1, pool); + return crypto_buffer_new_with_pool(Span(data, len), /*data_is_static=*/true, + FromOpaque(pool)) + .release(); } void CRYPTO_BUFFER_free(CRYPTO_BUFFER *buf) { - if (buf == NULL) { - return; + if (buf != nullptr) { + FromOpaque(buf)->DecRefInternal(); } - - CRYPTO_BUFFER_POOL *const pool = buf->pool; - if (pool == NULL) { - if (CRYPTO_refcount_dec_and_test_zero(&buf->references)) { - // If a reference count of zero is observed, there cannot be a reference - // from any pool to this buffer and thus we are able to free this - // buffer. - crypto_buffer_free_object(buf); - } - - return; - } - - CRYPTO_MUTEX_lock_write(&pool->lock); - if (!CRYPTO_refcount_dec_and_test_zero(&buf->references)) { - CRYPTO_MUTEX_unlock_write(&buf->pool->lock); - return; - } - - // We have an exclusive lock on the pool, therefore no concurrent lookups can - // find this buffer and increment the reference count. Thus, if the count is - // zero there are and can never be any more references and thus we can free - // this buffer. - // - // Note it is possible |buf| is no longer in the pool, if it was replaced by a - // static version. If that static version was since removed, it is even - // possible for |found| to be NULL. - CRYPTO_BUFFER *found = lh_CRYPTO_BUFFER_retrieve(pool->bufs, buf); - if (found == buf) { - found = lh_CRYPTO_BUFFER_delete(pool->bufs, buf); - assert(found == buf); - (void)found; - } - - CRYPTO_MUTEX_unlock_write(&buf->pool->lock); - crypto_buffer_free_object(buf); } int CRYPTO_BUFFER_up_ref(CRYPTO_BUFFER *buf) { - // This is safe in the case that |buf->pool| is NULL because it's just - // standard reference counting in that case. - // - // This is also safe if |buf->pool| is non-NULL because, if it were racing - // with |CRYPTO_BUFFER_free| then the two callers must have independent - // references already and so the reference count will never hit zero. - CRYPTO_refcount_inc(&buf->references); + FromOpaque(buf)->UpRefInternal(); return 1; } -const uint8_t *CRYPTO_BUFFER_data(const CRYPTO_BUFFER *buf) { - return buf->data; +CRYPTO_BUFFER *CRYPTO_BUFFER_dup_ref(const CRYPTO_BUFFER *buf) { + auto *buf_ = const_cast(buf); + FromOpaque(buf_)->UpRefInternal(); + return buf_; } -size_t CRYPTO_BUFFER_len(const CRYPTO_BUFFER *buf) { return buf->len; } +const uint8_t *CRYPTO_BUFFER_data(const CRYPTO_BUFFER *buf) { + return FromOpaque(buf)->data_; +} + +size_t CRYPTO_BUFFER_len(const CRYPTO_BUFFER *buf) { + return FromOpaque(buf)->len_; +} void CRYPTO_BUFFER_init_CBS(const CRYPTO_BUFFER *buf, CBS *out) { - CBS_init(out, buf->data, buf->len); + *out = FromOpaque(buf)->span(); } diff --git a/Sources/CNIOBoringSSL/crypto/rand/deterministic.cc b/Sources/CNIOBoringSSL/crypto/rand/deterministic.cc index a0075758..59d7df70 100644 --- a/Sources/CNIOBoringSSL/crypto/rand/deterministic.cc +++ b/Sources/CNIOBoringSSL/crypto/rand/deterministic.cc @@ -1,21 +1,21 @@ -/* Copyright 2016 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2016 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 "../bcm_support.h" -#include "sysrand_internal.h" +#include "internal.h" #if defined(OPENSSL_RAND_DETERMINISTIC) @@ -26,24 +26,26 @@ #include "../internal.h" -// g_num_calls is the number of calls to |CRYPTO_sysrand| that have occurred. +using namespace bssl; + +// 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 CRYPTO_MUTEX g_num_calls_lock = CRYPTO_MUTEX_INIT; +static StaticMutex g_num_calls_lock; -void RAND_reset_for_fuzzing(void) { g_num_calls = 0; } +void RAND_reset_for_fuzzing() { g_num_calls = 0; } -void CRYPTO_init_sysrand(void) {} +void bssl::CRYPTO_init_sysrand() {} -void CRYPTO_sysrand(uint8_t *out, size_t requested) { +void bssl::CRYPTO_sysrand(uint8_t *out, size_t requested) { static const uint8_t kZeroKey[32] = {0}; - CRYPTO_MUTEX_lock_write(&g_num_calls_lock); + g_num_calls_lock.LockWrite(); uint64_t num_calls = g_num_calls++; - CRYPTO_MUTEX_unlock_write(&g_num_calls_lock); + g_num_calls_lock.UnlockWrite(); uint8_t nonce[12]; OPENSSL_memset(nonce, 0, sizeof(nonce)); @@ -53,13 +55,4 @@ void CRYPTO_sysrand(uint8_t *out, size_t requested) { CRYPTO_chacha_20(out, out, requested, kZeroKey, nonce, 0); } -int CRYPTO_sysrand_if_available(uint8_t *buf, size_t len) { - CRYPTO_sysrand(buf, len); - return 1; -} - -void CRYPTO_sysrand_for_seed(uint8_t *out, size_t requested) { - CRYPTO_sysrand(out, requested); -} - #endif // OPENSSL_RAND_DETERMINISTIC diff --git a/Sources/CNIOBoringSSL/crypto/rand/fork_detect.cc b/Sources/CNIOBoringSSL/crypto/rand/fork_detect.cc index 537f8285..4216887f 100644 --- a/Sources/CNIOBoringSSL/crypto/rand/fork_detect.cc +++ b/Sources/CNIOBoringSSL/crypto/rand/fork_detect.cc @@ -1,50 +1,88 @@ -/* Copyright 2020 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2020 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. #if !defined(_GNU_SOURCE) #define _GNU_SOURCE // needed for madvise() and MAP_ANONYMOUS on Linux. #endif #include "../bcm_support.h" +#include "../internal.h" +#include "internal.h" + +#if defined(OPENSSL_FORK_DETECTION_WIPEONFORK) + +#if defined(OPENSSL_LINUX) -#if defined(OPENSSL_FORK_DETECTION_MADVISE) #include #include #include #include #if defined(MADV_WIPEONFORK) -static_assert(MADV_WIPEONFORK == 18, "MADV_WIPEONFORK is not 18"); +static_assert(MADV_WIPEONFORK == 18); #else #define MADV_WIPEONFORK 18 #endif + +#else + +// Otherwise assume a BSD style API. +#include +#include +#include + +#endif + #elif defined(OPENSSL_FORK_DETECTION_PTHREAD_ATFORK) + #include #include #include + #endif // OPENSSL_FORK_DETECTION_PTHREAD_ATFORK -#include "../internal.h" -#if defined(OPENSSL_FORK_DETECTION_MADVISE) +using namespace bssl; + +#if defined(OPENSSL_FORK_DETECTION_WIPEONFORK) + +static 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) + // ignore `madvise` calls and just return zero (i.e. success). But we need to + // know whether MADV_WIPEONFORK actually took effect. Therefore try an invalid + // call to check that the implementation of `madvise` is actually rejecting + // unknown `advice` values. + return madvise(addr, page_size, -1) != 0 && + madvise(addr, page_size, MADV_WIPEONFORK) == 0; +#elif defined(MAP_INHERIT_ZERO) + // OpenBSD flavor, >=5.6. + return minherit(addr, page_size, MAP_INHERIT_ZERO) == 0; +#else + // FreeBSD flavor, >=12.0. + return minherit(addr, page_size, INHERIT_ZERO) == 0; +#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 CRYPTO_MUTEX g_fork_detect_lock = CRYPTO_MUTEX_INIT; -static CRYPTO_atomic_u32 *g_fork_detect_addr; +static StaticMutex g_fork_detect_lock; +static Atomic *g_fork_detect_addr; static uint64_t g_fork_generation; -static void init_fork_detect(void) { +static void init_fork_detect() { if (g_force_madv_wipeonfork) { return; } @@ -54,36 +92,28 @@ static void init_fork_detect(void) { return; } - void *addr = mmap(NULL, (size_t)page_size, PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + void *addr = mmap(nullptr, static_cast(page_size), + PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (addr == MAP_FAILED) { return; } - // Some versions of qemu (up to at least 5.0.0-rc4, see linux-user/syscall.c) - // ignore |madvise| calls and just return zero (i.e. success). But we need to - // know whether MADV_WIPEONFORK actually took effect. Therefore try an invalid - // call to check that the implementation of |madvise| is actually rejecting - // unknown |advice| values. - if (madvise(addr, (size_t)page_size, -1) == 0 || - madvise(addr, (size_t)page_size, MADV_WIPEONFORK) != 0) { - munmap(addr, (size_t)page_size); + if (!wipeonfork(addr, static_cast(page_size))) { + munmap(addr, static_cast(page_size)); return; } - CRYPTO_atomic_u32 *const atomic = reinterpret_cast(addr); - CRYPTO_atomic_store_u32(atomic, 1); - g_fork_detect_addr = atomic; + g_fork_detect_addr = new (addr) Atomic(1); g_fork_generation = 1; } -uint64_t CRYPTO_get_fork_generation(void) { +uint64_t bssl::CRYPTO_get_fork_generation() { CRYPTO_once(&g_fork_detect_once, init_fork_detect); // In a single-threaded process, there are obviously no races because there's // only a single mutator in the address space. // - // In a multi-threaded environment, |CRYPTO_once| ensures that the flag byte + // In a multi-threaded environment, `CRYPTO_once` ensures that the flag byte // is initialised atomically, even if multiple threads enter this function // concurrently. // @@ -91,10 +121,10 @@ uint64_t CRYPTO_get_fork_generation(void) { // child process is single-threaded, the child may become multi-threaded // before it observes this. Therefore, we must synchronize the logic below. - CRYPTO_atomic_u32 *const flag_ptr = g_fork_detect_addr; - if (flag_ptr == NULL) { - // Our kernel is too old to support |MADV_WIPEONFORK| or - // |g_force_madv_wipeonfork| is set. + Atomic *const flag_ptr = g_fork_detect_addr; + if (flag_ptr == nullptr) { + // Our kernel is too old to support `MADV_WIPEONFORK` or + // `g_force_madv_wipeonfork` is set. if (g_force_madv_wipeonfork && g_force_madv_wipeonfork_enabled) { // A constant generation number to simulate support, even if the kernel // doesn't support it. @@ -112,8 +142,8 @@ uint64_t CRYPTO_get_fork_generation(void) { // In the common case, try to observe the flag without taking a lock. This // avoids cacheline contention in the PRNG. uint64_t *const generation_ptr = &g_fork_generation; - if (CRYPTO_atomic_load_u32(flag_ptr) != 0) { - // If we observe a non-zero flag, it is safe to read |generation_ptr| + if (flag_ptr->load() != 0) { + // If we observe a non-zero flag, it is safe to read `generation_ptr` // without a lock. The flag and generation number are fixed for this copy of // the address space. return *generation_ptr; @@ -122,10 +152,9 @@ uint64_t CRYPTO_get_fork_generation(void) { // The flag was zero. The generation number must be incremented, but other // threads may have concurrently observed the zero, so take a lock before // incrementing. - CRYPTO_MUTEX *const lock = &g_fork_detect_lock; - CRYPTO_MUTEX_lock_write(lock); + MutexWriteLock lock(&g_fork_detect_lock); uint64_t current_generation = *generation_ptr; - if (CRYPTO_atomic_load_u32(flag_ptr) == 0) { + if (flag_ptr->load() == 0) { // A fork has occurred. current_generation++; if (current_generation == 0) { @@ -133,17 +162,16 @@ uint64_t CRYPTO_get_fork_generation(void) { current_generation = 1; } - // We must update |generation_ptr| before |flag_ptr|. Other threads may - // observe |flag_ptr| without taking a lock. + // We must update `generation_ptr` before `flag_ptr`. Other threads may + // observe `flag_ptr` without taking a lock. *generation_ptr = current_generation; - CRYPTO_atomic_store_u32(flag_ptr, 1); + flag_ptr->store(1); } - CRYPTO_MUTEX_unlock_write(lock); return current_generation; } -void CRYPTO_fork_detect_force_madv_wipeonfork_for_testing(int on) { +void bssl::CRYPTO_fork_detect_force_madv_wipeonfork_for_testing(int on) { g_force_madv_wipeonfork = 1; g_force_madv_wipeonfork_enabled = on; } @@ -153,7 +181,7 @@ void CRYPTO_fork_detect_force_madv_wipeonfork_for_testing(int on) { static CRYPTO_once_t g_pthread_fork_detection_once = CRYPTO_ONCE_INIT; static uint64_t g_atfork_fork_generation; -static void we_are_forked(void) { +static 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) { @@ -162,14 +190,14 @@ static void we_are_forked(void) { g_atfork_fork_generation = value; } -static void init_pthread_fork_detection(void) { - if (pthread_atfork(NULL, NULL, we_are_forked) != 0) { +static void init_pthread_fork_detection() { + if (pthread_atfork(nullptr, nullptr, we_are_forked) != 0) { abort(); } g_atfork_fork_generation = 1; } -uint64_t CRYPTO_get_fork_generation(void) { +uint64_t bssl::CRYPTO_get_fork_generation() { CRYPTO_once(&g_pthread_fork_detection_once, init_pthread_fork_detection); return g_atfork_fork_generation; @@ -181,14 +209,14 @@ uint64_t CRYPTO_get_fork_generation(void) { // fork detection support. Returning a constant non zero value makes BoringSSL // assume address space duplication is not a concern and adding entropy to // every RAND_bytes call is not needed. -uint64_t CRYPTO_get_fork_generation(void) { return 0xc0ffee; } +uint64_t bssl::CRYPTO_get_fork_generation() { return 0xc0ffee; } #else // These platforms may fork, but we do not have a mitigation mechanism in // place. Returning a constant zero value makes BoringSSL assume that address -// space duplication could have occured on any call entropy must be added to +// space duplication could have occurred on any call entropy must be added to // every RAND_bytes call. -uint64_t CRYPTO_get_fork_generation(void) { return 0; } +uint64_t bssl::CRYPTO_get_fork_generation() { return 0; } #endif diff --git a/Sources/CNIOBoringSSL/crypto/rand/forkunsafe.cc b/Sources/CNIOBoringSSL/crypto/rand/forkunsafe.cc index 9ed99c3d..ce4a584c 100644 --- a/Sources/CNIOBoringSSL/crypto/rand/forkunsafe.cc +++ b/Sources/CNIOBoringSSL/crypto/rand/forkunsafe.cc @@ -1,16 +1,16 @@ -/* Copyright 2017 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2017 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 @@ -20,9 +20,11 @@ #include "../internal.h" +using namespace bssl; + // g_buffering_enabled is one if fork-unsafe buffering has been enabled and zero // otherwise. -static CRYPTO_atomic_u32 g_buffering_enabled; +static bssl::Atomic g_buffering_enabled; #if !defined(OPENSSL_WINDOWS) void RAND_enable_fork_unsafe_buffering(int fd) { @@ -31,14 +33,12 @@ void RAND_enable_fork_unsafe_buffering(int fd) { abort(); } - CRYPTO_atomic_store_u32(&g_buffering_enabled, 1); + g_buffering_enabled.store(1); } -void RAND_disable_fork_unsafe_buffering(void) { - CRYPTO_atomic_store_u32(&g_buffering_enabled, 0); -} +void RAND_disable_fork_unsafe_buffering() { g_buffering_enabled.store(0); } #endif -int rand_fork_unsafe_buffering_enabled(void) { - return CRYPTO_atomic_load_u32(&g_buffering_enabled) != 0; +int bssl::rand_fork_unsafe_buffering_enabled() { + return g_buffering_enabled.load() != 0; } diff --git a/Sources/CNIOBoringSSL/crypto/rand/getentropy.cc b/Sources/CNIOBoringSSL/crypto/rand/getentropy.cc index e6a7520d..9541344a 100644 --- a/Sources/CNIOBoringSSL/crypto/rand/getentropy.cc +++ b/Sources/CNIOBoringSSL/crypto/rand/getentropy.cc @@ -1,16 +1,16 @@ -/* Copyright 2023 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2023 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. #if !defined(_DEFAULT_SOURCE) #define _DEFAULT_SOURCE // Needed for getentropy on musl and glibc @@ -19,7 +19,7 @@ #include #include "../bcm_support.h" -#include "sysrand_internal.h" +#include "internal.h" #if defined(OPENSSL_RAND_GETENTROPY) @@ -31,12 +31,14 @@ #include #endif -void CRYPTO_init_sysrand(void) {} +using namespace bssl; -// CRYPTO_sysrand puts |requested| random bytes into |out|. -void CRYPTO_sysrand(uint8_t *out, size_t requested) { +void bssl::CRYPTO_init_sysrand() {} + +// CRYPTO_sysrand puts `requested` random bytes into `out`. +void bssl::CRYPTO_sysrand(uint8_t *out, size_t requested) { while (requested > 0) { - // |getentropy| can only request 256 bytes at a time. + // `getentropy` can only request 256 bytes at a time. size_t todo = requested <= 256 ? requested : 256; if (getentropy(out, todo) != 0) { perror("getentropy() failed"); @@ -48,13 +50,4 @@ void CRYPTO_sysrand(uint8_t *out, size_t requested) { } } -int CRYPTO_sysrand_if_available(uint8_t *buf, size_t len) { - CRYPTO_sysrand(buf, len); - return 1; -} - -void CRYPTO_sysrand_for_seed(uint8_t *out, size_t requested) { - CRYPTO_sysrand(out, requested); -} - #endif // OPENSSL_RAND_GETENTROPY diff --git a/Sources/CNIOBoringSSL/crypto/rand/getrandom_fillin.h b/Sources/CNIOBoringSSL/crypto/rand/getrandom_fillin.h deleted file mode 100644 index 2276a481..00000000 --- a/Sources/CNIOBoringSSL/crypto/rand/getrandom_fillin.h +++ /dev/null @@ -1,64 +0,0 @@ -/* Copyright 2020 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#ifndef OPENSSL_HEADER_CRYPTO_RAND_GETRANDOM_FILLIN_H -#define OPENSSL_HEADER_CRYPTO_RAND_GETRANDOM_FILLIN_H - -#include - - -#if defined(OPENSSL_LINUX) - -#include - -#if defined(OPENSSL_X86_64) -#define EXPECTED_NR_getrandom 318 -#elif defined(OPENSSL_X86) -#define EXPECTED_NR_getrandom 355 -#elif defined(OPENSSL_AARCH64) -#define EXPECTED_NR_getrandom 278 -#elif defined(OPENSSL_ARM) -#define EXPECTED_NR_getrandom 384 -#elif defined(OPENSSL_RISCV64) -#define EXPECTED_NR_getrandom 278 -#endif - -#if defined(EXPECTED_NR_getrandom) -#define USE_NR_getrandom - -#if defined(__NR_getrandom) - -#if __NR_getrandom != EXPECTED_NR_getrandom -#error "system call number for getrandom is not the expected value" -#endif - -#else // __NR_getrandom - -#define __NR_getrandom EXPECTED_NR_getrandom - -#endif // __NR_getrandom - -#endif // EXPECTED_NR_getrandom - -#if !defined(GRND_NONBLOCK) -#define GRND_NONBLOCK 1 -#endif -#if !defined(GRND_RANDOM) -#define GRND_RANDOM 2 -#endif - -#endif // OPENSSL_LINUX - - -#endif // OPENSSL_HEADER_CRYPTO_RAND_GETRANDOM_FILLIN_H diff --git a/Sources/CNIOBoringSSL/crypto/rand/internal.h b/Sources/CNIOBoringSSL/crypto/rand/internal.h new file mode 100644 index 00000000..91c547cb --- /dev/null +++ b/Sources/CNIOBoringSSL/crypto/rand/internal.h @@ -0,0 +1,67 @@ +// Copyright 2024 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. + +#ifndef OPENSSL_HEADER_CRYPTO_RAND_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_RAND_INTERNAL_H + +#include + + +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) +#define OPENSSL_RAND_DETERMINISTIC +#elif defined(OPENSSL_TRUSTY) +#define OPENSSL_RAND_TRUSTY +#elif defined(OPENSSL_WINDOWS) +#define OPENSSL_RAND_WINDOWS +#elif defined(OPENSSL_LINUX) +#define OPENSSL_RAND_URANDOM +#elif defined(OPENSSL_APPLE) && !defined(OPENSSL_MACOS) +// Unlike macOS, iOS and similar hide away getentropy(). +#define OPENSSL_RAND_IOS +#else +// By default if you are integrating BoringSSL we expect you to +// provide getentropy from the header file. +#define OPENSSL_RAND_GETENTROPY +#endif + +#if defined(OPENSSL_LINUX) || defined(OPENSSL_FREEBSD) || \ + defined(OPENSSL_OPENBSD) + +// On linux we use MADVISE instead of pthread_atfork(), due +// to concerns about clone() being used for address space +// duplication. +#define OPENSSL_FORK_DETECTION +#define OPENSSL_FORK_DETECTION_WIPEONFORK + +#elif defined(OPENSSL_MACOS) || defined(OPENSSL_IOS) + +// These platforms may detect address space duplication with pthread_atfork. +// iOS doesn't normally allow fork in apps, but it's there. +#define OPENSSL_FORK_DETECTION +#define OPENSSL_FORK_DETECTION_PTHREAD_ATFORK + +#elif defined(OPENSSL_WINDOWS) || defined(OPENSSL_TRUSTY) || \ + defined(__ZEPHYR__) || defined(CROS_EC) + +// These platforms do not fork. +#define OPENSSL_DOES_NOT_FORK + +#else + +// Other platforms may fork, but BoringSSL cannot reliably detect it happening. +// So instead, new entropy will be drawn on every RNG call. + +#endif + +#endif // OPENSSL_HEADER_CRYPTO_RAND_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/rand/ios.cc b/Sources/CNIOBoringSSL/crypto/rand/ios.cc index 992606b6..55e441aa 100644 --- a/Sources/CNIOBoringSSL/crypto/rand/ios.cc +++ b/Sources/CNIOBoringSSL/crypto/rand/ios.cc @@ -1,42 +1,35 @@ -/* Copyright 2023 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2023 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 "../bcm_support.h" -#include "sysrand_internal.h" +#include "internal.h" #if defined(OPENSSL_RAND_IOS) #include #include -void CRYPTO_init_sysrand(void) {} +using namespace bssl; -void CRYPTO_sysrand(uint8_t *out, size_t requested) { +void bssl::CRYPTO_init_sysrand() {} + +void bssl::CRYPTO_sysrand(uint8_t *out, size_t requested) { if (CCRandomGenerateBytes(out, requested) != kCCSuccess) { abort(); } } -int CRYPTO_sysrand_if_available(uint8_t *buf, size_t len) { - CRYPTO_sysrand(buf, len); - return 1; -} - -void CRYPTO_sysrand_for_seed(uint8_t *out, size_t requested) { - CRYPTO_sysrand(out, requested); -} - #endif // OPENSSL_RAND_IOS diff --git a/Sources/CNIOBoringSSL/crypto/rand/passive.cc b/Sources/CNIOBoringSSL/crypto/rand/passive.cc index 0f0640f1..e69de29b 100644 --- a/Sources/CNIOBoringSSL/crypto/rand/passive.cc +++ b/Sources/CNIOBoringSSL/crypto/rand/passive.cc @@ -1,178 +0,0 @@ -/* Copyright 2020 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#include - -#include "../bcm_support.h" -#include "../fipsmodule/bcm_interface.h" -#include "../internal.h" - -#if defined(BORINGSSL_FIPS) - -#include - -// passive_get_seed_entropy writes |out_entropy_len| bytes of entropy, suitable -// for seeding a DRBG, to |out_entropy|. It sets |*out_used_cpu| to one if the -// entropy came directly from the CPU and zero if it came from the OS. It -// actively obtains entropy from the CPU/OS -static void passive_get_seed_entropy(uint8_t *out_entropy, - size_t out_entropy_len, - int *out_want_additional_input) { - *out_want_additional_input = 0; - if (bcm_success(BCM_rand_bytes_hwrng(out_entropy, out_entropy_len))) { - *out_want_additional_input = 1; - } else { - CRYPTO_sysrand_for_seed(out_entropy, out_entropy_len); - } -} - -#define ENTROPY_READ_LEN \ - (/* last_block size */ 16 + CTR_DRBG_ENTROPY_LEN * BORINGSSL_FIPS_OVERREAD) - -#if defined(OPENSSL_ANDROID) - -#include -#include -#include -#include -#include - -// socket_history_t enumerates whether the entropy daemon should be contacted -// for a given entropy request. Values other than socket_not_yet_attempted are -// sticky so if the first attempt to read from the daemon fails it's assumed -// that the daemon is not present and no more attempts will be made. If the -// first attempt is successful then attempts will be made forever more. -enum class socket_history_t { - // initial value, no connections to the entropy daemon have been made yet. - socket_not_yet_attempted = 0, - // reading from the entropy daemon was successful - socket_success, - // reading from the entropy daemon failed. - socket_failed, -}; - -static std::atomic g_socket_history{ - socket_history_t::socket_not_yet_attempted}; - -// DAEMON_RESPONSE_LEN is the number of bytes that the entropy daemon replies -// with. -#define DAEMON_RESPONSE_LEN 496 - -static_assert(ENTROPY_READ_LEN == DAEMON_RESPONSE_LEN, - "entropy daemon response length mismatch"); - -static int get_seed_from_daemon(uint8_t *out_entropy, size_t out_entropy_len) { - // |RAND_need_entropy| should never call this function for more than - // |DAEMON_RESPONSE_LEN| bytes. - if (out_entropy_len > DAEMON_RESPONSE_LEN) { - abort(); - } - - const socket_history_t socket_history = - g_socket_history.load(std::memory_order_acquire); - if (socket_history == socket_history_t::socket_failed) { - return 0; - } - - int ret = 0; - static const char kSocketPath[] = "/dev/socket/prng_seeder"; - struct sockaddr_un sun; - uint8_t buffer[DAEMON_RESPONSE_LEN]; - size_t done = 0; - const int sock = socket(AF_UNIX, SOCK_STREAM, 0); - if (sock < 0) { - goto out; - } - - memset(&sun, 0, sizeof(sun)); - sun.sun_family = AF_UNIX; - static_assert(sizeof(kSocketPath) <= UNIX_PATH_MAX, "kSocketPath too long"); - OPENSSL_memcpy(sun.sun_path, kSocketPath, sizeof(kSocketPath)); - - if (connect(sock, (struct sockaddr *)&sun, sizeof(sun))) { - goto out; - } - - while (done < sizeof(buffer)) { - ssize_t n; - do { - n = read(sock, buffer + done, sizeof(buffer) - done); - } while (n == -1 && errno == EINTR); - - if (n < 1) { - goto out; - } - done += n; - } - - if (done != DAEMON_RESPONSE_LEN) { - // The daemon should always write |DAEMON_RESPONSE_LEN| bytes on every - // connection. - goto out; - } - - assert(out_entropy_len <= DAEMON_RESPONSE_LEN); - OPENSSL_memcpy(out_entropy, buffer, out_entropy_len); - ret = 1; - -out: - if (socket_history == socket_history_t::socket_not_yet_attempted) { - socket_history_t expected = socket_history_t::socket_not_yet_attempted; - // If another thread has already updated |g_socket_history| then we defer - // to their value. - g_socket_history.compare_exchange_strong( - expected, - (ret == 0) ? socket_history_t::socket_failed - : socket_history_t::socket_success, - std::memory_order_release, std::memory_order_relaxed); - } - - close(sock); - return ret; -} - -#else - -static int get_seed_from_daemon(uint8_t *out_entropy, size_t out_entropy_len) { - return 0; -} - -#endif // OPENSSL_ANDROID - -// RAND_need_entropy is called by the FIPS module when it has blocked because of -// a lack of entropy. This signal is used as an indication to feed it more. -void RAND_need_entropy(size_t bytes_needed) { - uint8_t buf[ENTROPY_READ_LEN]; - size_t todo = sizeof(buf); - if (todo > bytes_needed) { - todo = bytes_needed; - } - - int want_additional_input; - if (get_seed_from_daemon(buf, todo)) { - want_additional_input = 1; - } else { - passive_get_seed_entropy(buf, todo, &want_additional_input); - } - - if (boringssl_fips_break_test("CRNG")) { - // This breaks the "continuous random number generator test" defined in FIPS - // 140-2, section 4.9.2, and implemented in |rand_get_seed|. - OPENSSL_memset(buf, 0, todo); - } - - BCM_rand_load_entropy(buf, todo, want_additional_input); -} - -#endif // FIPS diff --git a/Sources/CNIOBoringSSL/crypto/rand/rand.cc b/Sources/CNIOBoringSSL/crypto/rand/rand.cc index 67a21ef9..c81fa51f 100644 --- a/Sources/CNIOBoringSSL/crypto/rand/rand.cc +++ b/Sources/CNIOBoringSSL/crypto/rand/rand.cc @@ -1,16 +1,16 @@ -/* Copyright 2017 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2017 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 @@ -20,6 +20,8 @@ #include "../fipsmodule/bcm_interface.h" +using namespace bssl; + int RAND_bytes(uint8_t *buf, size_t len) { BCM_rand_bytes(buf, len); return 1; @@ -28,7 +30,7 @@ int RAND_bytes(uint8_t *buf, size_t len) { int RAND_pseudo_bytes(uint8_t *buf, size_t len) { return RAND_bytes(buf, len); } void RAND_seed(const void *buf, int num) { - // OpenSSH calls |RAND_seed| before jailing on the assumption that any needed + // OpenSSH calls `RAND_seed` before jailing on the assumption that any needed // file descriptors etc will be opened. uint8_t unused; RAND_bytes(&unused, sizeof(unused)); @@ -44,34 +46,34 @@ int RAND_load_file(const char *path, long num) { } } -const char *RAND_file_name(char *buf, size_t num) { return NULL; } +const char *RAND_file_name(char *buf, size_t num) { return nullptr; } void RAND_add(const void *buf, int num, double entropy) {} int RAND_egd(const char *path) { return 255; } -int RAND_poll(void) { return 1; } +int RAND_poll() { return 1; } -int RAND_status(void) { return 1; } +int RAND_status() { return 1; } static const struct rand_meth_st kSSLeayMethod = { RAND_seed, RAND_bytes, RAND_cleanup, RAND_add, RAND_pseudo_bytes, RAND_status, }; -RAND_METHOD *RAND_SSLeay(void) { return (RAND_METHOD *)&kSSLeayMethod; } +RAND_METHOD *RAND_SSLeay() { return (RAND_METHOD *)&kSSLeayMethod; } -RAND_METHOD *RAND_OpenSSL(void) { return RAND_SSLeay(); } +RAND_METHOD *RAND_OpenSSL() { return RAND_SSLeay(); } -const RAND_METHOD *RAND_get_rand_method(void) { return RAND_SSLeay(); } +const RAND_METHOD *RAND_get_rand_method() { return RAND_SSLeay(); } int RAND_set_rand_method(const RAND_METHOD *method) { return 1; } -void RAND_cleanup(void) {} +void RAND_cleanup() {} void RAND_get_system_entropy_for_custom_prng(uint8_t *buf, size_t len) { if (len > 256) { abort(); } - CRYPTO_sysrand_for_seed(buf, len); + CRYPTO_sysrand(buf, len); } diff --git a/Sources/CNIOBoringSSL/crypto/rand/sysrand_internal.h b/Sources/CNIOBoringSSL/crypto/rand/sysrand_internal.h deleted file mode 100644 index 06632dbf..00000000 --- a/Sources/CNIOBoringSSL/crypto/rand/sysrand_internal.h +++ /dev/null @@ -1,37 +0,0 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#ifndef OPENSSL_HEADER_CRYPTO_SYSRAND_INTERNAL_H -#define OPENSSL_HEADER_CRYPTO_SYSRAND_INTERNAL_H - -#include - -#if defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE) -#define OPENSSL_RAND_DETERMINISTIC -#elif defined(OPENSSL_TRUSTY) -#define OPENSSL_RAND_TRUSTY -#elif defined(OPENSSL_WINDOWS) -#define OPENSSL_RAND_WINDOWS -#elif defined(OPENSSL_LINUX) -#define OPENSSL_RAND_URANDOM -#elif defined(OPENSSL_APPLE) && !defined(OPENSSL_MACOS) -// Unlike macOS, iOS and similar hide away getentropy(). -#define OPENSSL_RAND_IOS -#else -// By default if you are integrating BoringSSL we expect you to -// provide getentropy from the header file. -#define OPENSSL_RAND_GETENTROPY -#endif - -#endif // OPENSSL_HEADER_CRYPTO__SYSRAND_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/rand/trusty.cc b/Sources/CNIOBoringSSL/crypto/rand/trusty.cc index 28ea4fcb..59df4149 100644 --- a/Sources/CNIOBoringSSL/crypto/rand/trusty.cc +++ b/Sources/CNIOBoringSSL/crypto/rand/trusty.cc @@ -1,21 +1,21 @@ -/* Copyright 2023 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2023 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 "../bcm_support.h" -#include "sysrand_internal.h" +#include "internal.h" #if defined(OPENSSL_RAND_TRUSTY) #include @@ -26,21 +26,14 @@ #include -void CRYPTO_init_sysrand(void) {} +using namespace bssl; -void CRYPTO_sysrand(uint8_t *out, size_t requested) { +void bssl::CRYPTO_init_sysrand() {} + +void bssl::CRYPTO_sysrand(uint8_t *out, size_t requested) { if (trusty_rng_hw_rand(out, requested) != NO_ERROR) { abort(); } } -int CRYPTO_sysrand_if_available(uint8_t *buf, size_t len) { - CRYPTO_sysrand(buf, len); - return 1; -} - -void CRYPTO_sysrand_for_seed(uint8_t *out, size_t requested) { - CRYPTO_sysrand(out, requested); -} - #endif // OPENSSL_RAND_TRUSTY diff --git a/Sources/CNIOBoringSSL/crypto/rand/urandom.cc b/Sources/CNIOBoringSSL/crypto/rand/urandom.cc index 72272b4d..d4975cfa 100644 --- a/Sources/CNIOBoringSSL/crypto/rand/urandom.cc +++ b/Sources/CNIOBoringSSL/crypto/rand/urandom.cc @@ -1,16 +1,16 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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. #if !defined(_GNU_SOURCE) #define _GNU_SOURCE // needed for syscall() on Linux. @@ -19,54 +19,21 @@ #include #include "../bcm_support.h" -#include "sysrand_internal.h" +#include "internal.h" #if defined(OPENSSL_RAND_URANDOM) -#include #include #include +#include #include -#include +#include #include -#if defined(OPENSSL_LINUX) -#if defined(BORINGSSL_FIPS) -#include -#include -#endif -#include - -#if defined(OPENSSL_ANDROID) -#include -#endif - -#if !defined(OPENSSL_ANDROID) -#define OPENSSL_HAS_GETAUXVAL -#endif -// glibc prior to 2.16 does not have getauxval and sys/auxv.h. Android has some -// host builds (i.e. not building for Android itself, so |OPENSSL_ANDROID| is -// unset) which are still using a 2.15 sysroot. -// -// TODO(davidben): Remove this once Android updates their sysroot. -#if defined(__GLIBC_PREREQ) -#if !__GLIBC_PREREQ(2, 16) -#undef OPENSSL_HAS_GETAUXVAL -#endif -#endif -#if defined(OPENSSL_HAS_GETAUXVAL) -#include -#endif -#endif // OPENSSL_LINUX - -#include -#include - #include "../internal.h" -#include "getrandom_fillin.h" -#if defined(USE_NR_getrandom) +using namespace bssl; #if defined(OPENSSL_MSAN) extern "C" { @@ -82,7 +49,7 @@ static ssize_t boringssl_getrandom(void *buf, size_t buf_len, unsigned flags) { #if defined(OPENSSL_MSAN) if (ret > 0) { - // MSAN doesn't recognise |syscall| and thus doesn't notice that we have + // MSAN doesn't recognise `syscall` and thus doesn't notice that we have // initialised the output buffer. __msan_unpoison(buf, ret); } @@ -91,60 +58,24 @@ static ssize_t boringssl_getrandom(void *buf, size_t buf_len, unsigned flags) { return ret; } -#endif // USE_NR_getrandom - -// kHaveGetrandom in |urandom_fd| signals that |getrandom| or |getentropy| is +// kHaveGetrandom in `urandom_fd` signals that `getrandom` or `getentropy` is // available and should be used instead. static const int kHaveGetrandom = -3; -// urandom_fd is a file descriptor to /dev/urandom. It's protected by |once|. +// urandom_fd is a file descriptor to /dev/urandom. It's protected by `once`. static int urandom_fd; -#if defined(USE_NR_getrandom) - -// getrandom_ready is one if |getrandom| had been initialized by the time -// |init_once| was called and zero otherwise. -static int getrandom_ready; - -// extra_getrandom_flags_for_seed contains a value that is ORed into the flags -// for getrandom() when reading entropy for a seed. -static int extra_getrandom_flags_for_seed; - -// On Android, check a system property to decide whether to set -// |extra_getrandom_flags_for_seed| otherwise they will default to zero. If -// ro.oem_boringcrypto_hwrand is true then |extra_getrandom_flags_for_seed| will -// be set to GRND_RANDOM, causing all random data to be drawn from the same -// source as /dev/random. -static void maybe_set_extra_getrandom_flags(void) { -#if defined(BORINGSSL_FIPS) && defined(OPENSSL_ANDROID) - char value[PROP_VALUE_MAX + 1]; - int length = __system_property_get("ro.boringcrypto.hwrand", value); - if (length < 0 || length > PROP_VALUE_MAX) { - return; - } - - value[length] = 0; - if (OPENSSL_strcasecmp(value, "true") == 0) { - extra_getrandom_flags_for_seed = GRND_RANDOM; - } -#endif -} - -#endif // USE_NR_getrandom - static CRYPTO_once_t 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 +// requested. This is the only function that modifies `urandom_fd`, which may be // read safely after calling the once. -static void init_once(void) { -#if defined(USE_NR_getrandom) +static void init_once() { int have_getrandom; uint8_t dummy; ssize_t getrandom_ret = boringssl_getrandom(&dummy, sizeof(dummy), GRND_NONBLOCK); if (getrandom_ret == 1) { - getrandom_ready = 1; have_getrandom = 1; } else if (getrandom_ret == -1 && errno == EAGAIN) { // We have getrandom, but the entropy pool has not been initialized yet. @@ -160,18 +91,10 @@ static void init_once(void) { if (have_getrandom) { urandom_fd = kHaveGetrandom; - maybe_set_extra_getrandom_flags(); return; } -#endif // USE_NR_getrandom // FIPS builds must support getrandom. - // - // Historically, only Android FIPS builds required getrandom, while Linux FIPS - // builds had a /dev/urandom fallback which used RNDGETENTCNT as a poor - // approximation for getrandom's blocking behavior. This is now removed, but - // avoid making assumptions on this removal until March 2023, in case it needs - // to be restored. This comment can be deleted after March 2023. #if defined(BORINGSSL_FIPS) perror("getrandom not found"); abort(); @@ -190,96 +113,24 @@ static void init_once(void) { urandom_fd = fd; } -static CRYPTO_once_t wait_for_entropy_once = CRYPTO_ONCE_INIT; +void bssl::CRYPTO_init_sysrand() { CRYPTO_once(&rand_once, init_once); } -static void wait_for_entropy(void) { - int fd = urandom_fd; - if (fd == kHaveGetrandom) { - // |getrandom| and |getentropy| support blocking in |fill_with_entropy| - // directly. For |getrandom|, we first probe with a non-blocking call to aid - // debugging. -#if defined(USE_NR_getrandom) - if (getrandom_ready) { - // The entropy pool was already initialized in |init_once|. - return; - } - - uint8_t dummy; - ssize_t getrandom_ret = - boringssl_getrandom(&dummy, sizeof(dummy), GRND_NONBLOCK); - if (getrandom_ret == -1 && errno == EAGAIN) { - // Attempt to get the path of the current process to aid in debugging when - // something blocks. - const char *current_process = ""; -#if defined(OPENSSL_HAS_GETAUXVAL) - const unsigned long getauxval_ret = getauxval(AT_EXECFN); - if (getauxval_ret != 0) { - current_process = (const char *)getauxval_ret; - } -#endif - - fprintf( - stderr, - "%s: getrandom indicates that the entropy pool has not been " - "initialized. Rather than continue with poor entropy, this process " - "will block until entropy is available.\n", - current_process); - - getrandom_ret = - boringssl_getrandom(&dummy, sizeof(dummy), 0 /* no flags */); - } - - if (getrandom_ret != 1) { - perror("getrandom"); - abort(); - } -#endif // USE_NR_getrandom +// CRYPTO_sysrand writes `len` bytes of entropy into `out`. +void bssl::CRYPTO_sysrand(uint8_t *out, size_t len) { + if (len == 0) { return; } -} - -// fill_with_entropy writes |len| bytes of entropy into |out|. It returns one -// on success and zero on error. If |block| is one, this function will block -// until the entropy pool is initialized. Otherwise, this function may fail, -// setting |errno| to |EAGAIN| if the entropy pool has not yet been initialized. -// If |seed| is one, this function will OR in the value of -// |*extra_getrandom_flags_for_seed()| when using |getrandom|. -static int fill_with_entropy(uint8_t *out, size_t len, int block, int seed) { - if (len == 0) { - return 1; - } - -#if defined(USE_NR_getrandom) || defined(FREEBSD_GETRANDOM) - int getrandom_flags = 0; - if (!block) { - getrandom_flags |= GRND_NONBLOCK; - } -#endif - -#if defined(USE_NR_getrandom) - if (seed) { - getrandom_flags |= extra_getrandom_flags_for_seed; - } -#endif CRYPTO_init_sysrand(); - if (block) { - CRYPTO_once(&wait_for_entropy_once, wait_for_entropy); - } - // Clear |errno| so it has defined value if |read| or |getrandom| + // Clear `errno` so it has defined value if `read` or `getrandom` // "successfully" returns zero. errno = 0; while (len > 0) { ssize_t r; if (urandom_fd == kHaveGetrandom) { -#if defined(USE_NR_getrandom) - r = boringssl_getrandom(out, len, getrandom_flags); -#else // USE_NR_getrandom - fprintf(stderr, "urandom fd corrupt.\n"); - abort(); -#endif + r = boringssl_getrandom(out, len, 0); } else { do { r = read(urandom_fd, out, len); @@ -287,42 +138,12 @@ static int fill_with_entropy(uint8_t *out, size_t len, int block, int seed) { } if (r <= 0) { - return 0; + perror("entropy fill failed"); + abort(); } out += r; len -= r; } - - return 1; -} - -void CRYPTO_init_sysrand(void) { CRYPTO_once(&rand_once, init_once); } - -// CRYPTO_sysrand puts |requested| random bytes into |out|. -void CRYPTO_sysrand(uint8_t *out, size_t requested) { - if (!fill_with_entropy(out, requested, /*block=*/1, /*seed=*/0)) { - perror("entropy fill failed"); - abort(); - } -} - -void CRYPTO_sysrand_for_seed(uint8_t *out, size_t requested) { - if (!fill_with_entropy(out, requested, /*block=*/1, /*seed=*/1)) { - perror("entropy fill failed"); - abort(); - } -} - -int CRYPTO_sysrand_if_available(uint8_t *out, size_t requested) { - if (fill_with_entropy(out, requested, /*block=*/0, /*seed=*/0)) { - return 1; - } else if (errno == EAGAIN) { - OPENSSL_memset(out, 0, requested); - return 0; - } else { - perror("opportunistic entropy fill failed"); - abort(); - } } #endif // OPENSSL_RAND_URANDOM diff --git a/Sources/CNIOBoringSSL/crypto/rand/windows.cc b/Sources/CNIOBoringSSL/crypto/rand/windows.cc index 2b012889..bdde02ea 100644 --- a/Sources/CNIOBoringSSL/crypto/rand/windows.cc +++ b/Sources/CNIOBoringSSL/crypto/rand/windows.cc @@ -1,53 +1,51 @@ -/* Copyright 2014 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2014 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 "../bcm_support.h" #include "../internal.h" -#include "sysrand_internal.h" +#include "internal.h" #if defined(OPENSSL_RAND_WINDOWS) #include #include -OPENSSL_MSVC_PRAGMA(warning(push, 3)) - #include +using namespace bssl; + #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \ !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #include OPENSSL_MSVC_PRAGMA(comment(lib, "bcrypt.lib")) #endif // WINAPI_PARTITION_APP && !WINAPI_PARTITION_DESKTOP -OPENSSL_MSVC_PRAGMA(warning(pop)) - #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \ !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) -void CRYPTO_init_sysrand(void) {} +void bssl::CRYPTO_init_sysrand() {} -void CRYPTO_sysrand(uint8_t *out, size_t requested) { +void bssl::CRYPTO_sysrand(uint8_t *out, size_t requested) { while (requested > 0) { ULONG output_bytes_this_pass = ULONG_MAX; if (requested < output_bytes_this_pass) { output_bytes_this_pass = (ULONG)requested; } if (!BCRYPT_SUCCESS(BCryptGenRandom( - /*hAlgorithm=*/NULL, out, output_bytes_this_pass, + /*hAlgorithm=*/nullptr, out, output_bytes_this_pass, BCRYPT_USE_SYSTEM_PREFERRED_RNG))) { abort(); } @@ -59,26 +57,26 @@ void CRYPTO_sysrand(uint8_t *out, size_t requested) { #else // 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 = NULL; +typedef BOOL(WINAPI *ProcessPrngFunction)(PBYTE pbData, SIZE_T cbData); +static ProcessPrngFunction g_processprng_fn = nullptr; -static void init_processprng(void) { +static void init_processprng() { HMODULE hmod = LoadLibraryW(L"bcryptprimitives"); - if (hmod == NULL) { + if (hmod == nullptr) { abort(); } g_processprng_fn = (ProcessPrngFunction)GetProcAddress(hmod, "ProcessPrng"); - if (g_processprng_fn == NULL) { + if (g_processprng_fn == nullptr) { abort(); } } -void CRYPTO_init_sysrand(void) { +void bssl::CRYPTO_init_sysrand() { static CRYPTO_once_t once = CRYPTO_ONCE_INIT; CRYPTO_once(&once, init_processprng); } -void CRYPTO_sysrand(uint8_t *out, size_t requested) { +void bssl::CRYPTO_sysrand(uint8_t *out, size_t requested) { CRYPTO_init_sysrand(); // On non-UWP configurations, use ProcessPrng instead of BCryptGenRandom // to avoid accessing resources that may be unavailable inside the @@ -90,13 +88,4 @@ void CRYPTO_sysrand(uint8_t *out, size_t requested) { #endif // WINAPI_PARTITION_APP && !WINAPI_PARTITION_DESKTOP -int CRYPTO_sysrand_if_available(uint8_t *buf, size_t len) { - CRYPTO_sysrand(buf, len); - return 1; -} - -void CRYPTO_sysrand_for_seed(uint8_t *out, size_t requested) { - CRYPTO_sysrand(out, requested); -} - #endif // OPENSSL_RAND_WINDOWS diff --git a/Sources/CNIOBoringSSL/crypto/rc4/rc4.cc b/Sources/CNIOBoringSSL/crypto/rc4/rc4.cc index 2c00ffe4..093e9b7b 100644 --- a/Sources/CNIOBoringSSL/crypto/rc4/rc4.cc +++ b/Sources/CNIOBoringSSL/crypto/rc4/rc4.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 diff --git a/Sources/CNIOBoringSSL/crypto/refcount.cc b/Sources/CNIOBoringSSL/crypto/refcount.cc index 9cfa2843..d5589db0 100644 --- a/Sources/CNIOBoringSSL/crypto/refcount.cc +++ b/Sources/CNIOBoringSSL/crypto/refcount.cc @@ -1,16 +1,16 @@ -/* Copyright 2015 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2015 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 "internal.h" @@ -18,30 +18,21 @@ #include -// See comment above the typedef of CRYPTO_refcount_t about these tests. -static_assert(alignof(CRYPTO_refcount_t) == alignof(CRYPTO_atomic_u32), - "CRYPTO_refcount_t does not match CRYPTO_atomic_u32 alignment"); -static_assert(sizeof(CRYPTO_refcount_t) == sizeof(CRYPTO_atomic_u32), - "CRYPTO_refcount_t does not match CRYPTO_atomic_u32 size"); +using namespace bssl; -static_assert((CRYPTO_refcount_t)-1 == CRYPTO_REFCOUNT_MAX, - "CRYPTO_REFCOUNT_MAX is incorrect"); - -void CRYPTO_refcount_inc(CRYPTO_refcount_t *in_count) { - CRYPTO_atomic_u32 *count = (CRYPTO_atomic_u32 *)in_count; - uint32_t expected = CRYPTO_atomic_load_u32(count); +void bssl::CRYPTO_refcount_inc(CRYPTO_refcount_t *count) { + uint32_t expected = count->load(); while (expected != CRYPTO_REFCOUNT_MAX) { uint32_t new_value = expected + 1; - if (CRYPTO_atomic_compare_exchange_weak_u32(count, &expected, new_value)) { + if (count->compare_exchange_weak(expected, new_value)) { break; } } } -int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *in_count) { - CRYPTO_atomic_u32 *count = (CRYPTO_atomic_u32 *)in_count; - uint32_t expected = CRYPTO_atomic_load_u32(count); +int bssl::CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *count) { + uint32_t expected = count->load(); for (;;) { if (expected == 0) { @@ -50,8 +41,7 @@ int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *in_count) { return 0; } else { const uint32_t new_value = expected - 1; - if (CRYPTO_atomic_compare_exchange_weak_u32(count, &expected, - new_value)) { + if (count->compare_exchange_weak(expected, new_value)) { return new_value == 0; } } diff --git a/Sources/CNIOBoringSSL/crypto/rsa/internal.h b/Sources/CNIOBoringSSL/crypto/rsa/internal.h index cf6f2161..7c5b4d22 100644 --- a/Sources/CNIOBoringSSL/crypto/rsa/internal.h +++ b/Sources/CNIOBoringSSL/crypto/rsa/internal.h @@ -1,31 +1,51 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. -#ifndef OPENSSL_HEADER_RSA_EXTRA_INTERNAL_H -#define OPENSSL_HEADER_RSA_EXTRA_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_RSA_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_RSA_INTERNAL_H #include -#if defined(__cplusplus) -extern "C" { -#endif +#include "../fipsmodule/rsa/internal.h" +BSSL_NAMESPACE_BEGIN + int RSA_padding_check_PKCS1_OAEP_mgf1(uint8_t *out, size_t *out_len, size_t max_out, const uint8_t *from, size_t from_len, const uint8_t *param, size_t param_len, const EVP_MD *md, const EVP_MD *mgf1md); +// rsa_pss_params_get_md returns the hash function used with `params`. This also +// specifies the MGF-1 hash and the salt length because we do not support other +// configurations. +const EVP_MD *rsa_pss_params_get_md(rsa_pss_params_t params); -#if defined(__cplusplus) -} // extern C -#endif +// rsa_marshal_pss_params marshals `params` as a DER-encoded RSASSA-PSS-params +// (RFC 4055). It returns one on success and zero on error. If `params` is +// `rsa_pss_params_none`, this function gives an error. +int rsa_marshal_pss_params(CBB *cbb, rsa_pss_params_t params); -#endif // OPENSSL_HEADER_RSA_EXTRA_INTERNAL_H +// rsa_marshal_pss_params decodes a DER-encoded RSASSA-PSS-params +// (RFC 4055). It returns one on success and zero on error. On success, it sets +// `*out` to the result. If `allow_explicit_trailer` is non-zero, an explicit +// encoding of the trailerField is allowed, although it is not valid DER. This +// function never outputs `rsa_pss_params_none`. +int rsa_parse_pss_params(CBS *cbs, rsa_pss_params_t *out, + int allow_explicit_trailer); + +BSSL_NAMESPACE_END + +#endif // OPENSSL_HEADER_CRYPTO_RSA_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/rsa/rsa_asn1.cc b/Sources/CNIOBoringSSL/crypto/rsa/rsa_asn1.cc index 73a53997..aa9157ba 100644 --- a/Sources/CNIOBoringSSL/crypto/rsa/rsa_asn1.cc +++ b/Sources/CNIOBoringSSL/crypto/rsa/rsa_asn1.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -15,25 +20,32 @@ #include #include +#include #include #include +#include +#include +#include -#include "../fipsmodule/rsa/internal.h" #include "../bytestring/internal.h" +#include "../fipsmodule/rsa/internal.h" #include "../internal.h" +#include "internal.h" -static int parse_integer(CBS *cbs, BIGNUM **out) { - assert(*out == NULL); - *out = BN_new(); - if (*out == NULL) { +using namespace bssl; + +static int parse_integer(CBS *cbs, UniquePtr *out) { + assert(*out == nullptr); + out->reset(BN_new()); + if (*out == nullptr) { return 0; } - return BN_parse_asn1_unsigned(cbs, *out); + return BN_parse_asn1_unsigned(cbs, out->get()); } -static int marshal_integer(CBB *cbb, BIGNUM *bn) { - if (bn == NULL) { +static 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); return 0; @@ -42,9 +54,9 @@ static int marshal_integer(CBB *cbb, BIGNUM *bn) { } RSA *RSA_parse_public_key(CBS *cbs) { - RSA *ret = RSA_new(); - if (ret == NULL) { - return NULL; + RSAImpl *ret = FromOpaque(RSA_new()); + if (ret == nullptr) { + return nullptr; } CBS child; if (!CBS_get_asn1(cbs, &child, CBS_ASN1_SEQUENCE) || @@ -53,13 +65,13 @@ RSA *RSA_parse_public_key(CBS *cbs) { CBS_len(&child) != 0) { OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_ENCODING); RSA_free(ret); - return NULL; + return nullptr; } if (!RSA_check_key(ret)) { OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_RSA_PARAMETERS); RSA_free(ret); - return NULL; + return nullptr; } return ret; @@ -69,19 +81,20 @@ RSA *RSA_public_key_from_bytes(const uint8_t *in, size_t in_len) { CBS cbs; CBS_init(&cbs, in, in_len); RSA *ret = RSA_parse_public_key(&cbs); - if (ret == NULL || CBS_len(&cbs) != 0) { + if (ret == nullptr || CBS_len(&cbs) != 0) { OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_ENCODING); RSA_free(ret); - return NULL; + return nullptr; } return ret; } 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, rsa->n) || - !marshal_integer(&child, rsa->e) || + !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; @@ -104,13 +117,13 @@ int RSA_public_key_to_bytes(uint8_t **out_bytes, size_t *out_len, } // kVersionTwoPrime is the value of the version field for a two-prime -// RSAPrivateKey structure (RFC 3447). +// RSAPrivateKey structure (RFC 8017). static const uint64_t kVersionTwoPrime = 0; RSA *RSA_parse_private_key(CBS *cbs) { - RSA *ret = RSA_new(); - if (ret == NULL) { - return NULL; + RSAImpl *ret = FromOpaque(RSA_new()); + if (ret == nullptr) { + return nullptr; } CBS child; @@ -151,33 +164,34 @@ RSA *RSA_parse_private_key(CBS *cbs) { err: RSA_free(ret); - return NULL; + return nullptr; } RSA *RSA_private_key_from_bytes(const uint8_t *in, size_t in_len) { CBS cbs; CBS_init(&cbs, in, in_len); RSA *ret = RSA_parse_private_key(&cbs); - if (ret == NULL || CBS_len(&cbs) != 0) { + if (ret == nullptr || CBS_len(&cbs) != 0) { OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_ENCODING); RSA_free(ret); - return NULL; + return nullptr; } return ret; } 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, rsa->n) || - !marshal_integer(&child, rsa->e) || - !marshal_integer(&child, rsa->d) || - !marshal_integer(&child, rsa->p) || - !marshal_integer(&child, rsa->q) || - !marshal_integer(&child, rsa->dmp1) || - !marshal_integer(&child, rsa->dmq1) || - !marshal_integer(&child, rsa->iqmp) || + !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; @@ -200,66 +214,30 @@ int RSA_private_key_to_bytes(uint8_t **out_bytes, size_t *out_len, } RSA *d2i_RSAPublicKey(RSA **out, const uint8_t **inp, long len) { - if (len < 0) { - return NULL; - } - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - RSA *ret = RSA_parse_public_key(&cbs); - if (ret == NULL) { - return NULL; - } - if (out != NULL) { - RSA_free(*out); - *out = ret; - } - *inp = CBS_data(&cbs); - return ret; + return D2IFromCBS(out, inp, len, RSA_parse_public_key); } int i2d_RSAPublicKey(const RSA *in, uint8_t **outp) { - CBB cbb; - if (!CBB_init(&cbb, 0) || - !RSA_marshal_public_key(&cbb, in)) { - CBB_cleanup(&cbb); - return -1; - } - return CBB_finish_i2d(&cbb, outp); + return I2DFromCBB( + /*initial_capacity=*/256, outp, + [&](CBB *cbb) -> bool { return RSA_marshal_public_key(cbb, in); }); } RSA *d2i_RSAPrivateKey(RSA **out, const uint8_t **inp, long len) { - if (len < 0) { - return NULL; - } - CBS cbs; - CBS_init(&cbs, *inp, (size_t)len); - RSA *ret = RSA_parse_private_key(&cbs); - if (ret == NULL) { - return NULL; - } - if (out != NULL) { - RSA_free(*out); - *out = ret; - } - *inp = CBS_data(&cbs); - return ret; + return D2IFromCBS(out, inp, len, RSA_parse_private_key); } int i2d_RSAPrivateKey(const RSA *in, uint8_t **outp) { - CBB cbb; - if (!CBB_init(&cbb, 0) || - !RSA_marshal_private_key(&cbb, in)) { - CBB_cleanup(&cbb); - return -1; - } - return CBB_finish_i2d(&cbb, outp); + return I2DFromCBB( + /*initial_capacity=*/512, outp, + [&](CBB *cbb) -> bool { return RSA_marshal_private_key(cbb, in); }); } RSA *RSAPublicKey_dup(const RSA *rsa) { uint8_t *der; size_t der_len; if (!RSA_public_key_to_bytes(&der, &der_len, rsa)) { - return NULL; + return nullptr; } RSA *ret = RSA_public_key_from_bytes(der, der_len); OPENSSL_free(der); @@ -270,9 +248,157 @@ RSA *RSAPrivateKey_dup(const RSA *rsa) { uint8_t *der; size_t der_len; if (!RSA_private_key_to_bytes(&der, &der_len, rsa)) { - return NULL; + return nullptr; } RSA *ret = RSA_private_key_from_bytes(der, der_len); OPENSSL_free(der); return ret; } + +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, + 0x1a, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, + 0x08, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, + 0x04, 0x02, 0x01, 0x05, 0x00, 0xa2, 0x03, 0x02, 0x01, 0x20}; + +static const uint8_t kPSSParamsSHA384[] = { + 0x30, 0x34, 0xa0, 0x0f, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, + 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0xa1, 0x1c, 0x30, + 0x1a, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, + 0x08, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, + 0x04, 0x02, 0x02, 0x05, 0x00, 0xa2, 0x03, 0x02, 0x01, 0x30}; + +static const uint8_t kPSSParamsSHA512[] = { + 0x30, 0x34, 0xa0, 0x0f, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, + 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0xa1, 0x1c, 0x30, + 0x1a, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, + 0x08, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, + 0x04, 0x02, 0x03, 0x05, 0x00, 0xa2, 0x03, 0x02, 0x01, 0x40}; + +const EVP_MD *bssl::rsa_pss_params_get_md(rsa_pss_params_t params) { + switch (params) { + case rsa_pss_none: + return nullptr; + case rsa_pss_sha256: + return EVP_sha256(); + case rsa_pss_sha384: + return EVP_sha384(); + case rsa_pss_sha512: + return EVP_sha512(); + } + abort(); +} + +int bssl::rsa_marshal_pss_params(CBB *cbb, rsa_pss_params_t params) { + Span bytes; + switch (params) { + case rsa_pss_none: + OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); + return 0; + case rsa_pss_sha256: + bytes = kPSSParamsSHA256; + break; + case rsa_pss_sha384: + bytes = kPSSParamsSHA384; + break; + case rsa_pss_sha512: + bytes = kPSSParamsSHA512; + break; + } + + return CBB_add_bytes(cbb, bytes.data(), bytes.size()); +} + +// 1.2.840.113549.1.1.8 +static const uint8_t kMGF1OID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, + 0x0d, 0x01, 0x01, 0x08}; + +int bssl::rsa_parse_pss_params(CBS *cbs, rsa_pss_params_t *out, + int allow_explicit_trailer) { + // See RFC 4055, section 3.1. + // + // hashAlgorithm, maskGenAlgorithm, and saltLength all have DEFAULTs + // corresponding to SHA-1. We do not support SHA-1 with PSS, so we do not + // bother recognizing the omitted versions. + CBS params, hash_wrapper, mask_wrapper, mask_alg, mask_oid, salt_wrapper; + uint64_t salt_len; + if (!CBS_get_asn1(cbs, ¶ms, CBS_ASN1_SEQUENCE) || + !CBS_get_asn1(¶ms, &hash_wrapper, + CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) || + // `hash_wrapper` will be parsed below. + !CBS_get_asn1(¶ms, &mask_wrapper, + CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 1) || + !CBS_get_asn1(&mask_wrapper, &mask_alg, CBS_ASN1_SEQUENCE) || + !CBS_get_asn1(&mask_alg, &mask_oid, CBS_ASN1_OBJECT) || + // We only support MGF-1. + Span(mask_oid) != kMGF1OID || + // The remainder of `mask_alg` will be parsed below. + CBS_len(&mask_wrapper) != 0 || + !CBS_get_asn1(¶ms, &salt_wrapper, + CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 2) || + !CBS_get_asn1_uint64(&salt_wrapper, &salt_len) || + CBS_len(&salt_wrapper) != 0) { + OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_ENCODING); + return 0; + } + + // The trailer field must be 1 (0xbc). This value is DEFAULT, so the structure + // is required to omit it in DER. + if (CBS_len(¶ms) != 0 && allow_explicit_trailer) { + CBS trailer_wrapper; + uint64_t trailer; + if (!CBS_get_asn1(¶ms, &trailer_wrapper, + CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 3) || + !CBS_get_asn1_uint64(&trailer_wrapper, &trailer) || // + trailer != 1) { + OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_ENCODING); + return 0; + } + } + if (CBS_len(¶ms) != 0) { + OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_ENCODING); + return 0; + } + + int hash_nid = EVP_parse_digest_algorithm_nid(&hash_wrapper); + if (hash_nid == NID_undef || CBS_len(&hash_wrapper) != 0) { + OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_ENCODING); + return 0; + } + + // We only support combinations where the MGF-1 hash matches the overall hash. + int mgf1_hash_nid = EVP_parse_digest_algorithm_nid(&mask_alg); + if (mgf1_hash_nid != hash_nid || CBS_len(&mask_alg) != 0) { + OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_ENCODING); + return 0; + } + + // We only support salt lengths that match the hash length. + rsa_pss_params_t ret; + uint64_t hash_len; + switch (hash_nid) { + case NID_sha256: + ret = rsa_pss_sha256; + hash_len = 32; + break; + case NID_sha384: + ret = rsa_pss_sha384; + hash_len = 48; + break; + case NID_sha512: + ret = rsa_pss_sha512; + hash_len = 64; + break; + default: + OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_ENCODING); + return 0; + } + if (salt_len != hash_len) { + OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_ENCODING); + return 0; + } + + *out = ret; + return 1; +} diff --git a/Sources/CNIOBoringSSL/crypto/rsa/rsa_crypt.cc b/Sources/CNIOBoringSSL/crypto/rsa/rsa_crypt.cc index 1cf73d3b..44828aea 100644 --- a/Sources/CNIOBoringSSL/crypto/rsa/rsa_crypt.cc +++ b/Sources/CNIOBoringSSL/crypto/rsa/rsa_crypt.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -24,6 +29,8 @@ #include "internal.h" +using namespace bssl; + static void rand_nonzero(uint8_t *out, size_t len) { RAND_bytes(out, len); @@ -40,10 +47,10 @@ 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, const EVP_MD *md, const EVP_MD *mgf1md) { - if (md == NULL) { + if (md == nullptr) { md = EVP_sha1(); } - if (mgf1md == NULL) { + if (mgf1md == nullptr) { mgf1md = md; } @@ -69,9 +76,9 @@ int RSA_padding_add_PKCS1_OAEP_mgf1(uint8_t *to, size_t to_len, uint8_t *seed = to + 1; uint8_t *db = to + mdlen + 1; - uint8_t *dbmask = NULL; + uint8_t *dbmask = nullptr; int ret = 0; - if (!EVP_Digest(param, param_len, db, NULL, md, NULL)) { + if (!EVP_Digest(param, param_len, db, nullptr, md, nullptr)) { goto out; } OPENSSL_memset(db + mdlen, 0, emlen - from_len - 2 * mdlen - 1); @@ -82,7 +89,7 @@ int RSA_padding_add_PKCS1_OAEP_mgf1(uint8_t *to, size_t to_len, } dbmask = reinterpret_cast(OPENSSL_malloc(emlen - mdlen)); - if (dbmask == NULL) { + if (dbmask == nullptr) { goto out; } @@ -107,18 +114,19 @@ out: return ret; } -int RSA_padding_check_PKCS1_OAEP_mgf1(uint8_t *out, size_t *out_len, - size_t max_out, const uint8_t *from, - size_t from_len, const uint8_t *param, - size_t param_len, const EVP_MD *md, - const EVP_MD *mgf1md) { - uint8_t *db = NULL; +int bssl::RSA_padding_check_PKCS1_OAEP_mgf1(uint8_t *out, size_t *out_len, + size_t max_out, const uint8_t *from, + size_t from_len, + const uint8_t *param, + size_t param_len, const EVP_MD *md, + const EVP_MD *mgf1md) { + uint8_t *db = nullptr; { - if (md == NULL) { + if (md == nullptr) { md = EVP_sha1(); } - if (mgf1md == NULL) { + if (mgf1md == nullptr) { mgf1md = md; } @@ -135,7 +143,7 @@ int RSA_padding_check_PKCS1_OAEP_mgf1(uint8_t *out, size_t *out_len, size_t dblen = from_len - mdlen - 1; db = reinterpret_cast(OPENSSL_malloc(dblen)); - if (db == NULL) { + if (db == nullptr) { goto err; } @@ -158,7 +166,7 @@ int RSA_padding_check_PKCS1_OAEP_mgf1(uint8_t *out, size_t *out_len, } uint8_t phash[EVP_MAX_MD_SIZE]; - if (!EVP_Digest(param, param_len, phash, NULL, md, NULL)) { + if (!EVP_Digest(param, param_len, phash, nullptr, md, nullptr)) { goto err; } @@ -246,7 +254,7 @@ static int rsa_padding_check_PKCS1_type_2(uint8_t *out, size_t *out_len, // PKCS#1 v1.5 decryption. See "PKCS #1 v2.2: RSA Cryptography // Standard", section 7.2.2. if (from_len < RSA_PKCS1_PADDING_SIZE) { - // |from| is zero-padded to the size of the RSA modulus, a public value, so + // `from` is zero-padded to the size of the RSA modulus, a public value, so // this can be rejected in non-constant time. OPENSSL_PUT_ERROR(RSA, RSA_R_KEY_SIZE_TOO_SMALL); return 0; @@ -270,16 +278,16 @@ static int rsa_padding_check_PKCS1_type_2(uint8_t *out, size_t *out_len, // We must have found the end of PS. valid_index &= ~looking_for_index; - // PS must be at least 8 bytes long, and it starts two bytes into |from|. + // PS must be at least 8 bytes long, and it starts two bytes into `from`. valid_index &= constant_time_ge_w(zero_index, 2 + 8); // Skip the zero byte. zero_index++; // NOTE: Although this logic attempts to be constant time, the API contracts - // of this function and |RSA_decrypt| with |RSA_PKCS1_PADDING| make it + // of this function and `RSA_decrypt` with `RSA_PKCS1_PADDING` make it // impossible to completely avoid Bleichenbacher's attack. Consumers should - // use |RSA_PADDING_NONE| and perform the padding check in constant-time + // use `RSA_PADDING_NONE` and perform the padding check in constant-time // combined with a swap to a random session key or other mitigation. CONSTTIME_DECLASSIFY(&valid_index, sizeof(valid_index)); CONSTTIME_DECLASSIFY(&zero_index, sizeof(zero_index)); @@ -292,7 +300,7 @@ static int rsa_padding_check_PKCS1_type_2(uint8_t *out, size_t *out_len, const size_t msg_len = from_len - zero_index; if (msg_len > max_out) { // This shouldn't happen because this function is always called with - // |max_out| as the key size and |from_len| is bounded by the key size. + // `max_out` as the key size and `from_len` is bounded by the key size. OPENSSL_PUT_ERROR(RSA, RSA_R_PKCS_DECODING_ERROR); return 0; } @@ -334,7 +342,9 @@ int RSA_private_encrypt(size_t flen, const uint8_t *from, uint8_t *to, RSA *rsa, int RSA_encrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, const uint8_t *in, size_t in_len, int padding) { - if (rsa->n == NULL || rsa->e == NULL) { + auto *impl = FromOpaque(rsa); + + if (impl->n == nullptr || impl->e == nullptr) { OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING); return 0; } @@ -344,25 +354,21 @@ int RSA_encrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, } const unsigned rsa_size = RSA_size(rsa); - BIGNUM *f, *result; - uint8_t *buf = NULL; - BN_CTX *ctx = NULL; - int i, ret = 0; - if (max_out < rsa_size) { OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL); return 0; } - ctx = BN_CTX_new(); - if (ctx == NULL) { - goto err; + UniquePtr ctx(BN_CTX_new()); + if (ctx == nullptr) { + return 0; } - BN_CTX_start(ctx); - f = BN_CTX_get(ctx); - result = BN_CTX_get(ctx); - buf = reinterpret_cast(OPENSSL_malloc(rsa_size)); + BN_CTXScope scope(ctx.get()); + BIGNUM *f = BN_CTX_get(ctx.get()); + BIGNUM *result = BN_CTX_get(ctx.get()); + uint8_t *buf = reinterpret_cast(OPENSSL_malloc(rsa_size)); + int i, ret = 0; if (!f || !result || !buf) { goto err; } @@ -373,8 +379,8 @@ int RSA_encrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, break; case RSA_PKCS1_OAEP_PADDING: // Use the default parameters: SHA-1 for both hashes and no label. - i = RSA_padding_add_PKCS1_OAEP_mgf1(buf, rsa_size, in, in_len, NULL, 0, - NULL, NULL); + i = RSA_padding_add_PKCS1_OAEP_mgf1(buf, rsa_size, in, in_len, nullptr, 0, + nullptr, nullptr); break; case RSA_NO_PADDING: i = RSA_padding_add_none(buf, rsa_size, in, in_len); @@ -388,18 +394,20 @@ int RSA_encrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, goto err; } - if (BN_bin2bn(buf, rsa_size, f) == NULL) { + if (BN_bin2bn(buf, rsa_size, f) == nullptr) { goto err; } - if (BN_ucmp(f, rsa->n) >= 0) { + if (BN_ucmp(f, impl->n.get()) >= 0) { // usually the padding functions would catch this OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE_FOR_MODULUS); goto err; } - if (!BN_MONT_CTX_set_locked(&rsa->mont_n, &rsa->lock, rsa->n, ctx) || - !BN_mod_exp_mont(result, f, rsa->e, &rsa->mont_n->N, ctx, rsa->mont_n)) { + if (!BN_MONT_CTX_set_locked(&impl->mont_n, &impl->lock, impl->n.get(), + ctx.get()) || + !BN_mod_exp_mont(result, f, impl->e.get(), &impl->mont_n->N, ctx.get(), + impl->mont_n.get())) { goto err; } @@ -414,12 +422,7 @@ int RSA_encrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, ret = 1; err: - if (ctx != NULL) { - BN_CTX_end(ctx); - BN_CTX_free(ctx); - } OPENSSL_free(buf); - return ret; } @@ -427,7 +430,7 @@ 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) { const unsigned rsa_size = RSA_size(rsa); - uint8_t *buf = NULL; + uint8_t *buf = nullptr; int ret = 0; if (max_out < rsa_size) { @@ -440,7 +443,7 @@ static int rsa_default_decrypt(RSA *rsa, size_t *out_len, uint8_t *out, } else { // Allocate a temporary buffer to hold the padded plaintext. buf = reinterpret_cast(OPENSSL_malloc(rsa_size)); - if (buf == NULL) { + if (buf == nullptr) { goto err; } } @@ -461,8 +464,8 @@ static int rsa_default_decrypt(RSA *rsa, size_t *out_len, uint8_t *out, break; case RSA_PKCS1_OAEP_PADDING: // Use the default parameters: SHA-1 for both hashes and no label. - ret = RSA_padding_check_PKCS1_OAEP_mgf1(out, out_len, rsa_size, buf, - rsa_size, NULL, 0, NULL, NULL); + ret = RSA_padding_check_PKCS1_OAEP_mgf1( + out, out_len, rsa_size, buf, rsa_size, nullptr, 0, nullptr, nullptr); break; case RSA_NO_PADDING: *out_len = rsa_size; @@ -490,8 +493,9 @@ err: 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) { - if (rsa->meth->decrypt) { - return rsa->meth->decrypt(rsa, out_len, out, max_out, in, in_len, padding); + auto *impl = FromOpaque(rsa); + if (impl->meth->decrypt) { + return impl->meth->decrypt(rsa, out_len, out, max_out, in, in_len, padding); } return rsa_default_decrypt(rsa, out_len, out, max_out, in, in_len, padding); diff --git a/Sources/CNIOBoringSSL/crypto/rsa/rsa_extra.cc b/Sources/CNIOBoringSSL/crypto/rsa/rsa_extra.cc index f56ac104..c4051d26 100644 --- a/Sources/CNIOBoringSSL/crypto/rsa/rsa_extra.cc +++ b/Sources/CNIOBoringSSL/crypto/rsa/rsa_extra.cc @@ -1,19 +1,30 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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 int RSA_blinding_on(RSA *rsa, BN_CTX *ctx) { return 1; } void RSA_blinding_off(RSA *rsa) {} + +const RSA_PSS_PARAMS *RSA_get0_pss_params(const RSA *rsa) { + // We do not currently implement this function. By default, we will not parse + // `EVP_PKEY_RSA_PSS`. Callers that opt in with a BoringSSL-specific API are + // currently assumed to not need this function. Callers that need that opt-in + // and this functionality should contact the BoringSSL team. + // + // If we do add support later, the `maskHash` field should be filled in for + // OpenSSL compatibility. + return nullptr; +} diff --git a/Sources/CNIOBoringSSL/crypto/rsa/rsa_print.cc b/Sources/CNIOBoringSSL/crypto/rsa/rsa_print.cc index 8d82a9ef..bfd10c1c 100644 --- a/Sources/CNIOBoringSSL/crypto/rsa/rsa_print.cc +++ b/Sources/CNIOBoringSSL/crypto/rsa/rsa_print.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2006-2017 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2006-2017 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -13,10 +18,8 @@ int RSA_print(BIO *bio, const RSA *rsa, int indent) { - EVP_PKEY *pkey = EVP_PKEY_new(); - int ret = pkey != NULL && - EVP_PKEY_set1_RSA(pkey, (RSA *)rsa) && - EVP_PKEY_print_private(bio, pkey, indent, NULL); - EVP_PKEY_free(pkey); - return ret; + bssl::UniquePtr pkey(EVP_PKEY_new()); + return pkey != nullptr && + EVP_PKEY_set1_RSA(pkey.get(), const_cast(rsa)) && + EVP_PKEY_print_private(bio, pkey.get(), indent, nullptr); } diff --git a/Sources/CNIOBoringSSL/crypto/sha/sha1.cc b/Sources/CNIOBoringSSL/crypto/sha/sha1.cc index 820ffb8a..3bde8873 100644 --- a/Sources/CNIOBoringSSL/crypto/sha/sha1.cc +++ b/Sources/CNIOBoringSSL/crypto/sha/sha1.cc @@ -1,16 +1,16 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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 @@ -18,6 +18,9 @@ #include "../fipsmodule/bcm_interface.h" + +using namespace bssl; + int SHA1_Init(SHA_CTX *sha) { BCM_sha1_init(sha); return 1; diff --git a/Sources/CNIOBoringSSL/crypto/sha/sha256.cc b/Sources/CNIOBoringSSL/crypto/sha/sha256.cc index dfcf4a0d..1c043964 100644 --- a/Sources/CNIOBoringSSL/crypto/sha/sha256.cc +++ b/Sources/CNIOBoringSSL/crypto/sha/sha256.cc @@ -1,24 +1,26 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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 "../fipsmodule/bcm_interface.h" +using namespace bssl; + int SHA224_Init(SHA256_CTX *sha) { BCM_sha224_init(sha); return 1; diff --git a/Sources/CNIOBoringSSL/crypto/sha/sha512.cc b/Sources/CNIOBoringSSL/crypto/sha/sha512.cc index fbf5afef..96b5c816 100644 --- a/Sources/CNIOBoringSSL/crypto/sha/sha512.cc +++ b/Sources/CNIOBoringSSL/crypto/sha/sha512.cc @@ -1,24 +1,26 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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 "../fipsmodule/bcm_interface.h" +using namespace bssl; + int SHA384_Init(SHA512_CTX *sha) { BCM_sha384_init(sha); return 1; @@ -80,9 +82,9 @@ int SHA512_Update(SHA512_CTX *sha, const void *data, size_t len) { } int SHA512_Final(uint8_t out[SHA512_DIGEST_LENGTH], SHA512_CTX *sha) { - // Historically this function retured failure if passed NULL, even - // though other final functions do not. - if (out == NULL) { + // Historically this function returned failure if passed NULL, even though + // other final functions do not. + if (out == nullptr) { return 0; } BCM_sha512_final(out, sha); diff --git a/Sources/CNIOBoringSSL/crypto/siphash/siphash.cc b/Sources/CNIOBoringSSL/crypto/siphash/siphash.cc index d27a09f8..5371ce5e 100644 --- a/Sources/CNIOBoringSSL/crypto/siphash/siphash.cc +++ b/Sources/CNIOBoringSSL/crypto/siphash/siphash.cc @@ -1,16 +1,16 @@ -/* Copyright 2019 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2019 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 @@ -20,6 +20,8 @@ #include "../internal.h" +using namespace bssl; + static void siphash_round(uint64_t v[4]) { v[0] += v[1]; v[2] += v[3]; diff --git a/Sources/CNIOBoringSSL/crypto/slhdsa/slhdsa.cc b/Sources/CNIOBoringSSL/crypto/slhdsa/slhdsa.cc index a2fa7f02..d50cc5d6 100644 --- a/Sources/CNIOBoringSSL/crypto/slhdsa/slhdsa.cc +++ b/Sources/CNIOBoringSSL/crypto/slhdsa/slhdsa.cc @@ -1,16 +1,16 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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 @@ -19,15 +19,38 @@ #include "../fipsmodule/bcm_interface.h" +using namespace bssl; + +static_assert(SLHDSA_SHA2_128S_SEED_BYTES == 3 * BCM_SLHDSA_SHA2_128S_N); static_assert(SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES == - BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES, - ""); + BCM_SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES); static_assert(SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES == - BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES, - ""); + BCM_SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES); static_assert(SLHDSA_SHA2_128S_SIGNATURE_BYTES == - BCM_SLHDSA_SHA2_128S_SIGNATURE_BYTES, - ""); + BCM_SLHDSA_SHA2_128S_SIGNATURE_BYTES); +static_assert(SLHDSA_SHAKE_256F_SEED_BYTES == 3 * BCM_SLHDSA_SHAKE_256F_N); +static_assert(SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES == + BCM_SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES); +static_assert(SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES == + BCM_SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES); +static_assert(SLHDSA_SHAKE_256F_SIGNATURE_BYTES == + BCM_SLHDSA_SHAKE_256F_SIGNATURE_BYTES); + +void SLHDSA_SHA2_128S_generate_key_from_seed( + uint8_t out_public_key[SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], + uint8_t out_private_key[SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES], + const uint8_t seed[SLHDSA_SHA2_128S_SEED_BYTES]) { + BCM_slhdsa_sha2_128s_generate_key_from_seed(out_public_key, out_private_key, + seed); +} + +void SLHDSA_SHAKE_256F_generate_key_from_seed( + uint8_t out_public_key[SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], + uint8_t out_private_key[SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES], + const uint8_t seed[SLHDSA_SHAKE_256F_SEED_BYTES]) { + BCM_slhdsa_shake_256f_generate_key_from_seed(out_public_key, out_private_key, + seed); +} void SLHDSA_SHA2_128S_generate_key( uint8_t out_public_key[SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], @@ -35,12 +58,24 @@ void SLHDSA_SHA2_128S_generate_key( BCM_slhdsa_sha2_128s_generate_key(out_public_key, out_private_key); } +void SLHDSA_SHAKE_256F_generate_key( + uint8_t out_public_key[SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], + uint8_t out_private_key[SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES]) { + BCM_slhdsa_shake_256f_generate_key(out_public_key, out_private_key); +} + void SLHDSA_SHA2_128S_public_from_private( uint8_t out_public_key[SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], const uint8_t private_key[SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES]) { BCM_slhdsa_sha2_128s_public_from_private(out_public_key, private_key); } +void SLHDSA_SHAKE_256F_public_from_private( + uint8_t out_public_key[SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], + const uint8_t private_key[SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES]) { + BCM_slhdsa_shake_256f_public_from_private(out_public_key, private_key); +} + int SLHDSA_SHA2_128S_sign( uint8_t out_signature[SLHDSA_SHA2_128S_SIGNATURE_BYTES], const uint8_t private_key[SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES], @@ -50,6 +85,15 @@ int SLHDSA_SHA2_128S_sign( msg_len, context, context_len)); } +int SLHDSA_SHAKE_256F_sign( + uint8_t out_signature[SLHDSA_SHAKE_256F_SIGNATURE_BYTES], + const uint8_t private_key[SLHDSA_SHAKE_256F_PRIVATE_KEY_BYTES], + const uint8_t *msg, size_t msg_len, const uint8_t *context, + size_t context_len) { + return bcm_success(BCM_slhdsa_shake_256f_sign(out_signature, private_key, msg, + msg_len, context, context_len)); +} + int SLHDSA_SHA2_128S_verify( const uint8_t *signature, size_t signature_len, const uint8_t public_key[SLHDSA_SHA2_128S_PUBLIC_KEY_BYTES], @@ -60,6 +104,16 @@ int SLHDSA_SHA2_128S_verify( context, context_len)); } +int SLHDSA_SHAKE_256F_verify( + const uint8_t *signature, size_t signature_len, + const uint8_t public_key[SLHDSA_SHAKE_256F_PUBLIC_KEY_BYTES], + const uint8_t *msg, size_t msg_len, const uint8_t *context, + size_t context_len) { + return bcm_success(BCM_slhdsa_shake_256f_verify(signature, signature_len, + public_key, msg, msg_len, + context, context_len)); +} + int SLHDSA_SHA2_128S_prehash_sign( uint8_t out_signature[SLHDSA_SHA2_128S_SIGNATURE_BYTES], const uint8_t private_key[SLHDSA_SHA2_128S_PRIVATE_KEY_BYTES], diff --git a/Sources/CNIOBoringSSL/crypto/spake2plus/internal.h b/Sources/CNIOBoringSSL/crypto/spake2plus/internal.h index bb3a2ed3..7a2fffbe 100644 --- a/Sources/CNIOBoringSSL/crypto/spake2plus/internal.h +++ b/Sources/CNIOBoringSSL/crypto/spake2plus/internal.h @@ -1,25 +1,25 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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. -#ifndef OPENSSL_HEADER_SPAKE2PLUS_INTERNAL_H -#define OPENSSL_HEADER_SPAKE2PLUS_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_SPAKE2PLUS_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_SPAKE2PLUS_INTERNAL_H #include #include -#include +#include #include #include "../fipsmodule/ec/internal.h" @@ -64,14 +64,14 @@ constexpr size_t kSecretSize = 32; // step of the SPAKE2+ protocol. See the following for more details: // https://www.rfc-editor.org/rfc/rfc9383.html#section-3.2 // -// The |password| argument is the mandatory prover password. The |out_w0|, -// |out_w1|, and |out_registration_record| arguments are where the password +// The `password` argument is the mandatory prover password. The `out_w0`, +// `out_w1`, and `out_registration_record` arguments are where the password // verifiers (w0 and w1) and registration record (L) are stored, respectively. -// The prover is given |out_w0| and |out_w1| while the verifier is given -// |out_w0| and |out_registration_record|. +// The prover is given `out_w0` and `out_w1` while the verifier is given +// `out_w0` and `out_registration_record`. // -// To ensure success, |out_w0| and |out_w1| must be of length |kVerifierSize|, -// and |out_registration_record| of size |kRegistrationRecordSize|. +// To ensure success, `out_w0` and `out_w1` must be of length `kVerifierSize`, +// and `out_registration_record` of size `kRegistrationRecordSize`. [[nodiscard]] OPENSSL_EXPORT bool Register( Span out_w0, Span out_w1, Span out_registration_record, Span password, @@ -87,10 +87,10 @@ class OPENSSL_EXPORT Prover { // Init creates a new prover, which can only be used for a single execution of // the protocol. // - // The |context| argument is an application-specific value meant to constrain - // the protocol execution. The |w0| and |w1| arguments are password verifier + // The `context` argument is an application-specific value meant to constrain + // the protocol execution. The `w0` and `w1` arguments are password verifier // values computed during the offline registration phase of the protocol. The - // |id_prover| and |id_verifier| arguments allow optional, opaque names to be + // `id_prover` and `id_verifier` arguments allow optional, opaque names to be // bound into the protocol. See the following for more information about how // these identities may be chosen: // https://www.rfc-editor.org/rfc/rfc9383.html#name-definition-of-spake2 @@ -100,20 +100,20 @@ class OPENSSL_EXPORT Prover { Span w0, Span w1, Span x = Span()); - // GenerateShare computes a SPAKE2+ share and writes it to |out_share|. + // GenerateShare computes a SPAKE2+ share and writes it to `out_share`. // - // This function can only be called once for a given |Prover|. To ensure - // success, |out_share| must be |kShareSize| bytes. + // This function can only be called once for a given `Prover`. To ensure + // success, `out_share` must be `kShareSize` bytes. [[nodiscard]] bool GenerateShare(Span out_share); // ComputeConfirmation computes a SPAKE2+ key confirmation - // message and writes it to |out_confirm|. It also computes the shared secret - // and writes it to |out_secret|. + // message and writes it to `out_confirm`. It also computes the shared secret + // and writes it to `out_secret`. // - // This function can only be called once for a given |Prover|. + // This function can only be called once for a given `Prover`. // - // To ensure success, |out_confirm| must be |kConfirmSize| bytes - // and |out_secret| must be |kSecretSize| bytes. + // To ensure success, `out_confirm` must be `kConfirmSize` bytes + // and `out_secret` must be `kSecretSize` bytes. [[nodiscard]] bool ComputeConfirmation(Span out_confirm, Span out_secret, Span peer_share, @@ -146,12 +146,12 @@ class OPENSSL_EXPORT Verifier { // Init creates a new verifier, which can only be used for a single execution // of the protocol. // - // The |context| argument is an application-specific value meant to constrain - // the protocol execution. The |w0| and |registration_record| arguments are - // required, and are computed by the prover via |Register|. Only the prover - // can produce |w0| and |registration_record|, as they require + // The `context` argument is an application-specific value meant to constrain + // the protocol execution. The `w0` and `registration_record` arguments are + // required, and are computed by the prover via `Register`. Only the prover + // can produce `w0` and `registration_record`, as they require // knowledge of the password. The prover must securely transmit this to the - // verifier out-of-band. The |id_prover| and |id_verifier| arguments allow + // verifier out-of-band. The `id_prover` and `id_verifier` arguments allow // optional, opaque names to be bound into the protocol. See the following for // more information about how these identities may be chosen: // https://www.rfc-editor.org/rfc/rfc9383.html#name-definition-of-spake2 @@ -163,23 +163,23 @@ class OPENSSL_EXPORT Verifier { Span y = Span()); // ProcessProverShare computes a SPAKE2+ share from an input share, - // |prover_share|, and writes it to |out_share|. It also computes the key - // confirmation message and writes it to |out_confirm|. Finally, it computes - // the shared secret and writes it to |out_secret|. + // `prover_share`, and writes it to `out_share`. It also computes the key + // confirmation message and writes it to `out_confirm`. Finally, it computes + // the shared secret and writes it to `out_secret`. // - // This function can only be called once for a given |Verifier|. + // This function can only be called once for a given `Verifier`. // - // To ensure success, |out_share| must be |kShareSize| bytes, |out_confirm| - // must be |kConfirmSize| bytes, and |out_secret| must be |kSecretSize| bytes. + // To ensure success, `out_share` must be `kShareSize` bytes, `out_confirm` + // must be `kConfirmSize` bytes, and `out_secret` must be `kSecretSize` bytes. [[nodiscard]] bool ProcessProverShare(Span out_share, Span out_confirm, Span out_secret, Span prover_share); // VerifyProverConfirmation verifies a SPAKE2+ key confirmation message, - // |prover_confirm|. + // `prover_confirm`. // - // This function can only be called once for a given |Verifier|. + // This function can only be called once for a given `Verifier`. [[nodiscard]] bool VerifyProverConfirmation(Span peer_confirm); private: @@ -201,4 +201,4 @@ class OPENSSL_EXPORT Verifier { BSSL_NAMESPACE_END -#endif // OPENSSL_HEADER_SPAKE2PLUS_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_SPAKE2PLUS_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/spake2plus/spake2plus.cc b/Sources/CNIOBoringSSL/crypto/spake2plus/spake2plus.cc index 6575b072..223f1779 100644 --- a/Sources/CNIOBoringSSL/crypto/spake2plus/spake2plus.cc +++ b/Sources/CNIOBoringSSL/crypto/spake2plus/spake2plus.cc @@ -1,16 +1,16 @@ -/* Copyright 2024 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2024 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 @@ -21,18 +21,18 @@ #include #include #include +#include #include #include #include #include #include -#include +#include #include "../fipsmodule/bn/internal.h" #include "../fipsmodule/ec/internal.h" #include "../internal.h" #include "./internal.h" -#include "CNIOBoringSSL_err.h" BSSL_NAMESPACE_BEGIN namespace spake2plus { diff --git a/Sources/CNIOBoringSSL/crypto/stack/stack.cc b/Sources/CNIOBoringSSL/crypto/stack/stack.cc index 53ea3031..45c7f936 100644 --- a/Sources/CNIOBoringSSL/crypto/stack/stack.cc +++ b/Sources/CNIOBoringSSL/crypto/stack/stack.cc @@ -1,32 +1,42 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../internal.h" +#include "../mem_internal.h" +using namespace bssl; + struct stack_st { - // num contains the number of valid pointers in |data|. + // num contains the number of valid pointers in `data`. size_t num; void **data; - // sorted is non-zero if the values pointed to by |data| are in ascending - // order, based on |comp|. + // sorted is non-zero if the values pointed to by `data` are in ascending + // order, based on `comp`. int sorted; // num_alloc contains the number of pointers allocated in the buffer pointed - // to by |data|, which may be larger than |num|. + // to by `data`, which may be larger than `num`. size_t num_alloc; // comp is an optional comparison function. OPENSSL_sk_cmp_func comp; @@ -37,15 +47,14 @@ struct stack_st { static const size_t kMinSize = 4; OPENSSL_STACK *OPENSSL_sk_new(OPENSSL_sk_cmp_func comp) { - OPENSSL_STACK *ret = - reinterpret_cast(OPENSSL_zalloc(sizeof(OPENSSL_STACK))); - if (ret == NULL) { - return NULL; + OPENSSL_STACK *ret = New(); + if (ret == nullptr) { + return nullptr; } ret->data = reinterpret_cast(OPENSSL_calloc(kMinSize, sizeof(void *))); - if (ret->data == NULL) { + if (ret->data == nullptr) { goto err; } @@ -55,21 +64,21 @@ OPENSSL_STACK *OPENSSL_sk_new(OPENSSL_sk_cmp_func comp) { return ret; err: - OPENSSL_free(ret); - return NULL; + Delete(ret); + return nullptr; } -OPENSSL_STACK *OPENSSL_sk_new_null(void) { return OPENSSL_sk_new(NULL); } +OPENSSL_STACK *OPENSSL_sk_new_null() { return OPENSSL_sk_new(nullptr); } size_t OPENSSL_sk_num(const OPENSSL_STACK *sk) { - if (sk == NULL) { + if (sk == nullptr) { return 0; } return sk->num; } void OPENSSL_sk_zero(OPENSSL_STACK *sk) { - if (sk == NULL || sk->num == 0) { + if (sk == nullptr || sk->num == 0) { return; } OPENSSL_memset(sk->data, 0, sizeof(void *) * sk->num); @@ -79,43 +88,51 @@ void OPENSSL_sk_zero(OPENSSL_STACK *sk) { void *OPENSSL_sk_value(const OPENSSL_STACK *sk, size_t i) { if (!sk || i >= sk->num) { - return NULL; + return nullptr; } return sk->data[i]; } +void *OPENSSL_sk_last(const OPENSSL_STACK *sk) { + if (!sk || sk->num == 0) { + return nullptr; + } + return sk->data[sk->num - 1]; +} + void *OPENSSL_sk_set(OPENSSL_STACK *sk, size_t i, void *value) { if (!sk || i >= sk->num) { - return NULL; + return nullptr; } + sk->sorted = 0; return sk->data[i] = value; } void OPENSSL_sk_free(OPENSSL_STACK *sk) { - if (sk == NULL) { + if (sk == nullptr) { return; } OPENSSL_free(sk->data); - OPENSSL_free(sk); + Delete(sk); } void OPENSSL_sk_pop_free_ex(OPENSSL_STACK *sk, OPENSSL_sk_call_free_func call_free_func, OPENSSL_sk_free_func free_func) { - if (sk == NULL) { + if (sk == nullptr) { return; } for (size_t i = 0; i < sk->num; i++) { - if (sk->data[i] != NULL) { + if (sk->data[i] != nullptr) { call_free_func(free_func, sk->data[i]); } } OPENSSL_sk_free(sk); } -// Historically, |sk_pop_free| called the function as |OPENSSL_sk_free_func| -// directly. This is undefined in C. Some callers called |sk_pop_free| directly, +// Historically, `sk_pop_free` called the function as `OPENSSL_sk_free_func` +// directly. This is undefined in C. Some callers called `sk_pop_free` directly, // so we must maintain a compatibility version for now. static void call_free_func_legacy(OPENSSL_sk_free_func func, void *ptr) { func(ptr); @@ -126,7 +143,7 @@ void sk_pop_free(OPENSSL_STACK *sk, OPENSSL_sk_free_func free_func) { } size_t OPENSSL_sk_insert(OPENSSL_STACK *sk, void *p, size_t where) { - if (sk == NULL) { + if (sk == nullptr) { return 0; } @@ -153,7 +170,7 @@ size_t OPENSSL_sk_insert(OPENSSL_STACK *sk, void *p, size_t where) { } data = reinterpret_cast(OPENSSL_realloc(sk->data, alloc_size)); - if (data == NULL) { + if (data == nullptr) { return 0; } @@ -179,7 +196,7 @@ void *OPENSSL_sk_delete(OPENSSL_STACK *sk, size_t where) { void *ret; if (!sk || where >= sk->num) { - return NULL; + return nullptr; } ret = sk->data[where]; @@ -194,8 +211,8 @@ void *OPENSSL_sk_delete(OPENSSL_STACK *sk, size_t where) { } void *OPENSSL_sk_delete_ptr(OPENSSL_STACK *sk, const void *p) { - if (sk == NULL) { - return NULL; + if (sk == nullptr) { + return nullptr; } for (size_t i = 0; i < sk->num; i++) { @@ -204,13 +221,13 @@ void *OPENSSL_sk_delete_ptr(OPENSSL_STACK *sk, const void *p) { } } - return NULL; + return nullptr; } void OPENSSL_sk_delete_if(OPENSSL_STACK *sk, OPENSSL_sk_call_delete_if_func call_func, OPENSSL_sk_delete_if_func func, void *data) { - if (sk == NULL) { + if (sk == nullptr) { return; } @@ -226,11 +243,11 @@ void OPENSSL_sk_delete_if(OPENSSL_STACK *sk, int OPENSSL_sk_find(const OPENSSL_STACK *sk, size_t *out_index, const void *p, OPENSSL_sk_call_cmp_func call_cmp_func) { - if (sk == NULL) { + if (sk == nullptr) { return 0; } - if (sk->comp == NULL) { + if (sk->comp == nullptr) { // Use pointer equality when no comparison function has been set. for (size_t i = 0; i < sk->num; i++) { if (sk->data[i] == p) { @@ -243,7 +260,7 @@ int OPENSSL_sk_find(const OPENSSL_STACK *sk, size_t *out_index, const void *p, return 0; } - if (p == NULL) { + if (p == nullptr) { return 0; } @@ -261,29 +278,29 @@ int OPENSSL_sk_find(const OPENSSL_STACK *sk, size_t *out_index, const void *p, // The stack is sorted, so binary search to find the element. // - // |lo| and |hi| maintain a half-open interval of where the answer may be. All - // indices such that |lo <= idx < hi| are candidates. + // `lo` and `hi` maintain a half-open interval of where the answer may be. All + // indices such that `lo <= idx < hi` are candidates. size_t lo = 0, hi = sk->num; while (lo < hi) { - // Bias |mid| towards |lo|. See the |r == 0| case below. + // Bias `mid` towards `lo`. See the `r == 0` case below. size_t mid = lo + (hi - lo - 1) / 2; assert(lo <= mid && mid < hi); int r = call_cmp_func(sk->comp, p, sk->data[mid]); if (r > 0) { - lo = mid + 1; // |mid| is too low. + lo = mid + 1; // `mid` is too low. } else if (r < 0) { - hi = mid; // |mid| is too high. + hi = mid; // `mid` is too high. } else { - // |mid| matches. However, this function returns the earliest match, so we + // `mid` matches. However, this function returns the earliest match, so we // can only return if the range has size one. if (hi - lo == 1) { - if (out_index != NULL) { + if (out_index != nullptr) { *out_index = mid; } return 1; } - // The sample is biased towards |lo|. |mid| can only be |hi - 1| if - // |hi - lo| was one, so this makes forward progress. + // The sample is biased towards `lo`. `mid` can only be `hi - 1` if + // `hi - lo` was one, so this makes forward progress. assert(mid + 1 < hi); hi = mid + 1; } @@ -294,11 +311,11 @@ int OPENSSL_sk_find(const OPENSSL_STACK *sk, size_t *out_index, const void *p, } void *OPENSSL_sk_shift(OPENSSL_STACK *sk) { - if (sk == NULL) { - return NULL; + if (sk == nullptr) { + return nullptr; } if (sk->num == 0) { - return NULL; + return nullptr; } return OPENSSL_sk_delete(sk, 0); } @@ -308,29 +325,28 @@ size_t OPENSSL_sk_push(OPENSSL_STACK *sk, void *p) { } void *OPENSSL_sk_pop(OPENSSL_STACK *sk) { - if (sk == NULL) { - return NULL; + if (sk == nullptr) { + return nullptr; } if (sk->num == 0) { - return NULL; + return nullptr; } return OPENSSL_sk_delete(sk, sk->num - 1); } OPENSSL_STACK *OPENSSL_sk_dup(const OPENSSL_STACK *sk) { - if (sk == NULL) { - return NULL; + if (sk == nullptr) { + return nullptr; } - OPENSSL_STACK *ret = - reinterpret_cast(OPENSSL_zalloc(sizeof(OPENSSL_STACK))); - if (ret == NULL) { - return NULL; + OPENSSL_STACK *ret = New(); + if (ret == nullptr) { + return nullptr; } ret->data = reinterpret_cast( OPENSSL_memdup(sk->data, sizeof(void *) * sk->num_alloc)); - if (ret->data == NULL) { + if (ret->data == nullptr) { goto err; } @@ -342,84 +358,39 @@ OPENSSL_STACK *OPENSSL_sk_dup(const OPENSSL_STACK *sk) { err: OPENSSL_sk_free(ret); - return NULL; -} - -static size_t parent_idx(size_t idx) { - assert(idx > 0); - return (idx - 1) / 2; -} - -static size_t left_idx(size_t idx) { - // The largest possible index is |PTRDIFF_MAX|, not |SIZE_MAX|. If - // |ptrdiff_t|, a signed type, is the same size as |size_t|, this cannot - // overflow. - assert(idx <= PTRDIFF_MAX); - static_assert(PTRDIFF_MAX <= (SIZE_MAX - 1) / 2, "2 * idx + 1 may oveflow"); - return 2 * idx + 1; -} - -// down_heap fixes the subtree rooted at |i|. |i|'s children must each satisfy -// the heap property. Only the first |num| elements of |sk| are considered. -static void down_heap(OPENSSL_STACK *sk, OPENSSL_sk_call_cmp_func call_cmp_func, - size_t i, size_t num) { - assert(i < num && num <= sk->num); - for (;;) { - size_t left = left_idx(i); - if (left >= num) { - break; // No left child. - } - - // Swap |i| with the largest of its children. - size_t next = i; - if (call_cmp_func(sk->comp, sk->data[next], sk->data[left]) < 0) { - next = left; - } - size_t right = left + 1; // Cannot overflow because |left < num|. - if (right < num && - call_cmp_func(sk->comp, sk->data[next], sk->data[right]) < 0) { - next = right; - } - - if (i == next) { - break; // |i| is already larger than its children. - } - - void *tmp = sk->data[i]; - sk->data[i] = sk->data[next]; - sk->data[next] = tmp; - i = next; - } + return nullptr; } void OPENSSL_sk_sort(OPENSSL_STACK *sk, OPENSSL_sk_call_cmp_func call_cmp_func) { - if (sk == NULL || sk->comp == NULL || sk->sorted) { + if (sk == nullptr || sk->comp == nullptr || sk->sorted) { return; } - if (sk->num >= 2) { - // |qsort| lacks a context parameter in the comparison function for us to - // pass in |call_cmp_func| and |sk->comp|. While we could cast |sk->comp| to - // the expected type, it is undefined behavior in C can trip sanitizers. - // |qsort_r| and |qsort_s| avoid this, but using them is impractical. See - // https://stackoverflow.com/a/39561369 - // - // Use our own heap sort instead. This is not performance-sensitive, so we - // optimize for simplicity and size. First, build a max-heap in place. - for (size_t i = parent_idx(sk->num - 1); i < sk->num; i--) { - down_heap(sk, call_cmp_func, i, sk->num); - } + std::sort(sk->data, sk->data + sk->num, [&](void *a, void *b) { + return call_cmp_func(sk->comp, a, b) < 0; + }); + sk->sorted = 1; +} - // Iteratively remove the maximum element to populate the result in reverse. - for (size_t i = sk->num - 1; i > 0; i--) { - void *tmp = sk->data[0]; - sk->data[0] = sk->data[i]; - sk->data[i] = tmp; - down_heap(sk, call_cmp_func, 0, i); +void OPENSSL_sk_sort_and_dedup( + OPENSSL_STACK *sk, OPENSSL_sk_call_cmp_func call_cmp_func, + OPENSSL_sk_call_free_func call_free_func, OPENSSL_sk_free_func free_func) { + OPENSSL_sk_sort(sk, call_cmp_func); + if (sk == nullptr || sk->comp == nullptr || sk->num <= 1) { + return; + } + + size_t new_num = 1; + for (size_t i = 1; i < sk->num; i++) { + if (call_cmp_func(sk->comp, sk->data[i], sk->data[new_num - 1]) != 0) { + sk->data[new_num] = sk->data[i]; + new_num++; + } else if (free_func != nullptr) { + call_free_func(free_func, sk->data[i]); } } - sk->sorted = 1; + sk->num = new_num; } int OPENSSL_sk_is_sorted(const OPENSSL_STACK *sk) { @@ -427,7 +398,7 @@ int OPENSSL_sk_is_sorted(const OPENSSL_STACK *sk) { return 1; } // Zero- and one-element lists are always sorted. - return sk->sorted || (sk->comp != NULL && sk->num < 2); + return sk->sorted || (sk->comp != nullptr && sk->num < 2); } OPENSSL_sk_cmp_func OPENSSL_sk_set_cmp_func(OPENSSL_STACK *sk, @@ -448,30 +419,30 @@ OPENSSL_STACK *OPENSSL_sk_deep_copy(const OPENSSL_STACK *sk, OPENSSL_sk_call_free_func call_free_func, OPENSSL_sk_free_func free_func) { OPENSSL_STACK *ret = OPENSSL_sk_dup(sk); - if (ret == NULL) { - return NULL; + if (ret == nullptr) { + return nullptr; } for (size_t i = 0; i < ret->num; i++) { - if (ret->data[i] == NULL) { + if (ret->data[i] == nullptr) { continue; } ret->data[i] = call_copy_func(copy_func, ret->data[i]); - if (ret->data[i] == NULL) { + if (ret->data[i] == nullptr) { for (size_t j = 0; j < i; j++) { - if (ret->data[j] != NULL) { + if (ret->data[j] != nullptr) { call_free_func(free_func, ret->data[j]); } } OPENSSL_sk_free(ret); - return NULL; + return nullptr; } } return ret; } -OPENSSL_STACK *sk_new_null(void) { return OPENSSL_sk_new_null(); } +OPENSSL_STACK *sk_new_null() { return OPENSSL_sk_new_null(); } size_t sk_num(const OPENSSL_STACK *sk) { return OPENSSL_sk_num(sk); } diff --git a/Sources/CNIOBoringSSL/crypto/thread.cc b/Sources/CNIOBoringSSL/crypto/thread.cc index 506c665a..b5a27d1c 100644 --- a/Sources/CNIOBoringSSL/crypto/thread.cc +++ b/Sources/CNIOBoringSSL/crypto/thread.cc @@ -1,23 +1,28 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 -int CRYPTO_num_locks(void) { return 1; } +int CRYPTO_num_locks() { return 1; } void CRYPTO_set_locking_callback(void (*func)(int mode, int lock_num, const char *file, int line)) {} -void (*CRYPTO_get_locking_callback(void))(int mode, int lock_num, - const char *file, int line) { - return NULL; +void (*CRYPTO_get_locking_callback())(int mode, int lock_num, const char *file, + int line) { + return nullptr; } void CRYPTO_set_add_lock_callback(int (*func)(int *num, int mount, int lock_num, @@ -35,7 +40,7 @@ void CRYPTO_THREADID_set_pointer(CRYPTO_THREADID *id, void *ptr) {} void CRYPTO_THREADID_current(CRYPTO_THREADID *id) {} -void CRYPTO_set_id_callback(unsigned long (*func)(void)) {} +void CRYPTO_set_id_callback(unsigned long (*func)()) {} void CRYPTO_set_dynlock_create_callback(struct CRYPTO_dynlock_value *( *dyn_create_function)(const char *file, int line)) {} @@ -46,18 +51,18 @@ void CRYPTO_set_dynlock_lock_callback(void (*dyn_lock_function)( void CRYPTO_set_dynlock_destroy_callback(void (*dyn_destroy_function)( struct CRYPTO_dynlock_value *l, const char *file, int line)) {} -struct CRYPTO_dynlock_value *(*CRYPTO_get_dynlock_create_callback(void))( +struct CRYPTO_dynlock_value *(*CRYPTO_get_dynlock_create_callback())( const char *file, int line) { - return NULL; + return nullptr; } -void (*CRYPTO_get_dynlock_lock_callback(void))(int mode, - struct CRYPTO_dynlock_value *l, - const char *file, int line) { - return NULL; +void (*CRYPTO_get_dynlock_lock_callback())(int mode, + struct CRYPTO_dynlock_value *l, + const char *file, int line) { + return nullptr; } -void (*CRYPTO_get_dynlock_destroy_callback(void))( - struct CRYPTO_dynlock_value *l, const char *file, int line) { - return NULL; +void (*CRYPTO_get_dynlock_destroy_callback())(struct CRYPTO_dynlock_value *l, + const char *file, int line) { + return nullptr; } diff --git a/Sources/CNIOBoringSSL/crypto/thread_none.cc b/Sources/CNIOBoringSSL/crypto/thread_none.cc index c43928b2..432e4cf1 100644 --- a/Sources/CNIOBoringSSL/crypto/thread_none.cc +++ b/Sources/CNIOBoringSSL/crypto/thread_none.cc @@ -1,34 +1,31 @@ -/* Copyright 2015 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2015 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 "internal.h" #if !defined(OPENSSL_THREADS) -void CRYPTO_MUTEX_init(CRYPTO_MUTEX *lock) {} -void CRYPTO_MUTEX_lock_read(CRYPTO_MUTEX *lock) {} +using namespace bssl; -void CRYPTO_MUTEX_lock_write(CRYPTO_MUTEX *lock) {} +void StaticMutex::LockRead() {} +void StaticMutex::UnlockRead() {} +void StaticMutex::LockWrite() {} +void StaticMutex::UnlockWrite() {} +Mutex::~Mutex() {} -void CRYPTO_MUTEX_unlock_read(CRYPTO_MUTEX *lock) {} - -void CRYPTO_MUTEX_unlock_write(CRYPTO_MUTEX *lock) {} - -void CRYPTO_MUTEX_cleanup(CRYPTO_MUTEX *lock) {} - -void CRYPTO_once(CRYPTO_once_t *once, void (*init)(void)) { +void bssl::CRYPTO_once(CRYPTO_once_t *once, void (*init)()) { if (*once) { return; } @@ -38,12 +35,12 @@ void CRYPTO_once(CRYPTO_once_t *once, void (*init)(void)) { static void *g_thread_locals[NUM_OPENSSL_THREAD_LOCALS]; -void *CRYPTO_get_thread_local(thread_local_data_t index) { +void *bssl::CRYPTO_get_thread_local(thread_local_data_t index) { return g_thread_locals[index]; } -int CRYPTO_set_thread_local(thread_local_data_t index, void *value, - thread_local_destructor_t destructor) { +int bssl::CRYPTO_set_thread_local(thread_local_data_t index, void *value, + thread_local_destructor_t destructor) { g_thread_locals[index] = value; return 1; } diff --git a/Sources/CNIOBoringSSL/crypto/thread_pthread.cc b/Sources/CNIOBoringSSL/crypto/thread_pthread.cc index 2dcb409b..4e132fb7 100644 --- a/Sources/CNIOBoringSSL/crypto/thread_pthread.cc +++ b/Sources/CNIOBoringSSL/crypto/thread_pthread.cc @@ -1,16 +1,16 @@ -/* Copyright 2015 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2015 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. // Ensure we can't call OPENSSL_malloc circularly. #define _BORINGSSL_PROHIBIT_OPENSSL_MALLOC @@ -23,42 +23,27 @@ #include #include -void CRYPTO_MUTEX_init(CRYPTO_MUTEX *lock) { - if (pthread_rwlock_init(lock, NULL) != 0) { - abort(); - } + +BSSL_NAMESPACE_BEGIN + +void StaticMutex::LockRead() { BSSL_CHECK(pthread_rwlock_rdlock(&lock_) == 0); } + +void StaticMutex::UnlockRead() { + BSSL_CHECK(pthread_rwlock_unlock(&lock_) == 0); } -void CRYPTO_MUTEX_lock_read(CRYPTO_MUTEX *lock) { - if (pthread_rwlock_rdlock(lock) != 0) { - abort(); - } +void StaticMutex::LockWrite() { + BSSL_CHECK(pthread_rwlock_wrlock(&lock_) == 0); } -void CRYPTO_MUTEX_lock_write(CRYPTO_MUTEX *lock) { - if (pthread_rwlock_wrlock(lock) != 0) { - abort(); - } +void StaticMutex::UnlockWrite() { + BSSL_CHECK(pthread_rwlock_unlock(&lock_) == 0); } -void CRYPTO_MUTEX_unlock_read(CRYPTO_MUTEX *lock) { - if (pthread_rwlock_unlock(lock) != 0) { - abort(); - } -} +Mutex::~Mutex() { pthread_rwlock_destroy(&lock_); } -void CRYPTO_MUTEX_unlock_write(CRYPTO_MUTEX *lock) { - if (pthread_rwlock_unlock(lock) != 0) { - abort(); - } -} - -void CRYPTO_MUTEX_cleanup(CRYPTO_MUTEX *lock) { pthread_rwlock_destroy(lock); } - -void CRYPTO_once(CRYPTO_once_t *once, void (*init)(void)) { - if (pthread_once(once, init) != 0) { - abort(); - } +void CRYPTO_once(CRYPTO_once_t *once, void (*init)()) { + BSSL_CHECK(pthread_once(once, init) == 0); } static pthread_mutex_t g_destructors_lock = PTHREAD_MUTEX_INITIALIZER; @@ -67,7 +52,7 @@ static thread_local_destructor_t g_destructors[NUM_OPENSSL_THREAD_LOCALS]; // thread_local_destructor is called when a thread exits. It releases thread // local data for that thread only. static void thread_local_destructor(void *arg) { - if (arg == NULL) { + if (arg == nullptr) { return; } @@ -81,7 +66,7 @@ static void thread_local_destructor(void *arg) { unsigned i; void **pointers = reinterpret_cast(arg); for (i = 0; i < NUM_OPENSSL_THREAD_LOCALS; i++) { - if (destructors[i] != NULL) { + if (destructors[i] != nullptr) { destructors[i](pointers[i]); } } @@ -93,7 +78,7 @@ static pthread_once_t g_thread_local_init_once = PTHREAD_ONCE_INIT; static pthread_key_t g_thread_local_key; static int g_thread_local_key_created = 0; -static void thread_local_init(void) { +static void thread_local_init() { g_thread_local_key_created = pthread_key_create(&g_thread_local_key, thread_local_destructor) == 0; } @@ -101,13 +86,13 @@ static void thread_local_init(void) { void *CRYPTO_get_thread_local(thread_local_data_t index) { CRYPTO_once(&g_thread_local_init_once, thread_local_init); if (!g_thread_local_key_created) { - return NULL; + return nullptr; } void **pointers = reinterpret_cast(pthread_getspecific(g_thread_local_key)); - if (pointers == NULL) { - return NULL; + if (pointers == nullptr) { + return nullptr; } return pointers[index]; } @@ -122,10 +107,10 @@ int CRYPTO_set_thread_local(thread_local_data_t index, void *value, void **pointers = reinterpret_cast(pthread_getspecific(g_thread_local_key)); - if (pointers == NULL) { + if (pointers == nullptr) { pointers = reinterpret_cast( malloc(sizeof(void *) * NUM_OPENSSL_THREAD_LOCALS)); - if (pointers == NULL) { + if (pointers == nullptr) { destructor(value); return 0; } @@ -148,4 +133,6 @@ int CRYPTO_set_thread_local(thread_local_data_t index, void *value, return 1; } +BSSL_NAMESPACE_END + #endif // OPENSSL_PTHREADS diff --git a/Sources/CNIOBoringSSL/crypto/thread_win.cc b/Sources/CNIOBoringSSL/crypto/thread_win.cc index 855b1b00..d87c2963 100644 --- a/Sources/CNIOBoringSSL/crypto/thread_win.cc +++ b/Sources/CNIOBoringSSL/crypto/thread_win.cc @@ -1,16 +1,16 @@ -/* Copyright 2015 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2015 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. // Ensure we can't call OPENSSL_malloc circularly. #define _BORINGSSL_PROHIBIT_OPENSSL_MALLOC @@ -18,45 +18,30 @@ #if defined(OPENSSL_WINDOWS_THREADS) -OPENSSL_MSVC_PRAGMA(warning(push, 3)) #include -OPENSSL_MSVC_PRAGMA(warning(pop)) #include #include #include + +BSSL_NAMESPACE_BEGIN + static BOOL CALLBACK call_once_init(INIT_ONCE *once, void *arg, void **out) { - void (**init)(void) = (void (**)(void))arg; + void (**init)() = (void (**)())arg; (**init)(); return TRUE; } -void CRYPTO_once(CRYPTO_once_t *once, void (*init)(void)) { - if (!InitOnceExecuteOnce(once, call_once_init, &init, NULL)) { - abort(); - } +void CRYPTO_once(CRYPTO_once_t *once, void (*init)()) { + BSSL_CHECK(InitOnceExecuteOnce(once, call_once_init, &init, nullptr)); } -void CRYPTO_MUTEX_init(CRYPTO_MUTEX *lock) { InitializeSRWLock(lock); } - -void CRYPTO_MUTEX_lock_read(CRYPTO_MUTEX *lock) { AcquireSRWLockShared(lock); } - -void CRYPTO_MUTEX_lock_write(CRYPTO_MUTEX *lock) { - AcquireSRWLockExclusive(lock); -} - -void CRYPTO_MUTEX_unlock_read(CRYPTO_MUTEX *lock) { - ReleaseSRWLockShared(lock); -} - -void CRYPTO_MUTEX_unlock_write(CRYPTO_MUTEX *lock) { - ReleaseSRWLockExclusive(lock); -} - -void CRYPTO_MUTEX_cleanup(CRYPTO_MUTEX *lock) { - // SRWLOCKs require no cleanup. -} +void StaticMutex::LockRead() { AcquireSRWLockShared(&lock_); } +void StaticMutex::UnlockRead() { ReleaseSRWLockShared(&lock_); } +void StaticMutex::LockWrite() { AcquireSRWLockExclusive(&lock_); } +void StaticMutex::UnlockWrite() { ReleaseSRWLockExclusive(&lock_); } +Mutex::~Mutex() { /* SRWLOCKs require no cleanup. */ } static SRWLOCK g_destructors_lock = SRWLOCK_INIT; static thread_local_destructor_t g_destructors[NUM_OPENSSL_THREAD_LOCALS]; @@ -65,17 +50,17 @@ static CRYPTO_once_t g_thread_local_init_once = CRYPTO_ONCE_INIT; static DWORD g_thread_local_key; static int g_thread_local_failed; -static void thread_local_init(void) { +static void thread_local_init() { g_thread_local_key = TlsAlloc(); g_thread_local_failed = (g_thread_local_key == TLS_OUT_OF_INDEXES); } static void NTAPI thread_local_destructor(PVOID module, DWORD reason, PVOID reserved) { - // Only free memory on |DLL_THREAD_DETACH|, not |DLL_PROCESS_DETACH|. In + // Only free memory on `DLL_THREAD_DETACH`, not `DLL_PROCESS_DETACH`. In // VS2015's debug runtime, the C runtime has been unloaded by the time - // |DLL_PROCESS_DETACH| runs. See https://crbug.com/575795. This is consistent - // with |pthread_key_create| which does not call destructors on process exit, + // `DLL_PROCESS_DETACH` runs. See https://crbug.com/575795. This is consistent + // with `pthread_key_create` which does not call destructors on process exit, // only thread exit. if (reason != DLL_THREAD_DETACH) { return; @@ -87,7 +72,7 @@ static void NTAPI thread_local_destructor(PVOID module, DWORD reason, } void **pointers = (void **)TlsGetValue(g_thread_local_key); - if (pointers == NULL) { + if (pointers == nullptr) { return; } @@ -98,7 +83,7 @@ static void NTAPI thread_local_destructor(PVOID module, DWORD reason, ReleaseSRWLockExclusive(&g_destructors_lock); for (unsigned i = 0; i < NUM_OPENSSL_THREAD_LOCALS; i++) { - if (destructors[i] != NULL) { + if (destructors[i] != nullptr) { destructors[i](pointers[i]); } } @@ -118,7 +103,7 @@ static void NTAPI thread_local_destructor(PVOID module, DWORD reason, // a reference to p_thread_callback_boringssl to prevent whole program // optimization from discarding the variable. // -// Note, in the prefixed build, |p_thread_callback_boringssl| may be a macro. +// Note, in the prefixed build, `p_thread_callback_boringssl` may be a macro. #define STRINGIFY(x) #x #define EXPAND_AND_STRINGIFY(x) STRINGIFY(x) #ifdef _WIN64 @@ -174,14 +159,14 @@ PIMAGE_TLS_CALLBACK p_thread_callback_boringssl = thread_local_destructor; #endif // _WIN64 -static void **get_thread_locals(void) { - // |TlsGetValue| clears the last error even on success, so that callers may +static void **get_thread_locals() { + // `TlsGetValue` clears the last error even on success, so that callers may // distinguish it successfully returning NULL or failing. It is documented to - // never fail if the argument is a valid index from |TlsAlloc|, so we do not + // never fail if the argument is a valid index from `TlsAlloc`, so we do not // need to handle this. // // However, this error-mangling behavior interferes with the caller's use of - // |GetLastError|. In particular |SSL_get_error| queries the error queue to + // `GetLastError`. In particular `SSL_get_error` queries the error queue to // determine whether the caller should look at the OS's errors. To avoid // destroying state, save and restore the Windows error. // @@ -195,12 +180,12 @@ static void **get_thread_locals(void) { void *CRYPTO_get_thread_local(thread_local_data_t index) { CRYPTO_once(&g_thread_local_init_once, thread_local_init); if (g_thread_local_failed) { - return NULL; + return nullptr; } void **pointers = get_thread_locals(); - if (pointers == NULL) { - return NULL; + if (pointers == nullptr) { + return nullptr; } return pointers[index]; } @@ -214,10 +199,10 @@ int CRYPTO_set_thread_local(thread_local_data_t index, void *value, } void **pointers = get_thread_locals(); - if (pointers == NULL) { + if (pointers == nullptr) { pointers = reinterpret_cast( malloc(sizeof(void *) * NUM_OPENSSL_THREAD_LOCALS)); - if (pointers == NULL) { + if (pointers == nullptr) { destructor(value); return 0; } @@ -237,4 +222,6 @@ int CRYPTO_set_thread_local(thread_local_data_t index, void *value, return 1; } +BSSL_NAMESPACE_END + #endif // OPENSSL_WINDOWS_THREADS diff --git a/Sources/CNIOBoringSSL/crypto/trust_token/internal.h b/Sources/CNIOBoringSSL/crypto/trust_token/internal.h index f6a6df2b..43c4f1c0 100644 --- a/Sources/CNIOBoringSSL/crypto/trust_token/internal.h +++ b/Sources/CNIOBoringSSL/crypto/trust_token/internal.h @@ -1,19 +1,19 @@ -/* Copyright 2019 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2019 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. -#ifndef OPENSSL_HEADER_TRUST_TOKEN_INTERNAL_H -#define OPENSSL_HEADER_TRUST_TOKEN_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_TRUST_TOKEN_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_TRUST_TOKEN_INTERNAL_H #include #include @@ -25,10 +25,7 @@ #include -#if defined(__cplusplus) -extern "C" { -#endif - +BSSL_NAMESPACE_BEGIN // For the following cryptographic schemes, we use P-384 instead of our usual // choice of P-256. See Appendix I of @@ -46,26 +43,27 @@ extern "C" { #define TRUST_TOKEN_NONCE_SIZE 64 typedef struct { - // TODO(https://crbug.com/boringssl/334): These should store |EC_PRECOMP| so - // that |TRUST_TOKEN_finish_issuance| can use |ec_point_mul_scalar_precomp|. - EC_AFFINE pub0; - EC_AFFINE pub1; - EC_AFFINE pubs; + // TODO(https://crbug.com/boringssl/334): These should store + // `bssl::EC_PRECOMP` so that `TRUST_TOKEN_finish_issuance` can use + // `ec_point_mul_scalar_precomp`. + bssl::EC_AFFINE pub0; + bssl::EC_AFFINE pub1; + bssl::EC_AFFINE pubs; } TRUST_TOKEN_CLIENT_KEY; typedef struct { - EC_SCALAR x0; - EC_SCALAR y0; - EC_SCALAR x1; - EC_SCALAR y1; - EC_SCALAR xs; - EC_SCALAR ys; - EC_AFFINE pub0; - EC_PRECOMP pub0_precomp; - EC_AFFINE pub1; - EC_PRECOMP pub1_precomp; - EC_AFFINE pubs; - EC_PRECOMP pubs_precomp; + bssl::EC_SCALAR x0; + bssl::EC_SCALAR y0; + bssl::EC_SCALAR x1; + bssl::EC_SCALAR y1; + bssl::EC_SCALAR xs; + bssl::EC_SCALAR ys; + bssl::EC_AFFINE pub0; + bssl::EC_PRECOMP pub0_precomp; + bssl::EC_AFFINE pub1; + bssl::EC_PRECOMP pub1_precomp; + bssl::EC_AFFINE pubs; + bssl::EC_PRECOMP pubs_precomp; } TRUST_TOKEN_ISSUER_KEY; // TRUST_TOKEN_PRETOKEN represents the intermediate state a client keeps during @@ -73,14 +71,14 @@ typedef struct { typedef struct pmb_pretoken_st { uint8_t salt[TRUST_TOKEN_NONCE_SIZE]; uint8_t t[TRUST_TOKEN_NONCE_SIZE]; - EC_SCALAR r; - EC_AFFINE Tp; + bssl::EC_SCALAR r; + bssl::EC_AFFINE Tp; } TRUST_TOKEN_PRETOKEN; -// TRUST_TOKEN_PRETOKEN_free releases the memory associated with |token|. +// TRUST_TOKEN_PRETOKEN_free releases the memory associated with `token`. OPENSSL_EXPORT void TRUST_TOKEN_PRETOKEN_free(TRUST_TOKEN_PRETOKEN *token); -DEFINE_STACK_OF(TRUST_TOKEN_PRETOKEN) +DEFINE_NAMESPACED_STACK_OF(TRUST_TOKEN_PRETOKEN) // PMBTokens. @@ -90,8 +88,8 @@ DEFINE_STACK_OF(TRUST_TOKEN_PRETOKEN) // construction with validity verification, described in appendix H, // construction 6. -// The following functions implement the corresponding |TRUST_TOKENS_METHOD| -// functions for |TRUST_TOKENS_experiment_v1|'s PMBTokens construction which +// The following functions implement the corresponding `TRUST_TOKENS_METHOD` +// functions for `TRUST_TOKENS_experiment_v1`'s PMBTokens construction which // uses P-384. int pmbtoken_exp1_generate_key(CBB *out_private, CBB *out_public); int pmbtoken_exp1_derive_key_from_secret(CBB *out_private, CBB *out_public, @@ -122,8 +120,8 @@ int pmbtoken_exp1_read(const TRUST_TOKEN_ISSUER_KEY *key, // function is used to confirm H was computed as expected. OPENSSL_EXPORT int pmbtoken_exp1_get_h_for_testing(uint8_t out[97]); -// The following functions implement the corresponding |TRUST_TOKENS_METHOD| -// functions for |TRUST_TOKENS_experiment_v2|'s PMBTokens construction which +// The following functions implement the corresponding `TRUST_TOKENS_METHOD` +// functions for `TRUST_TOKENS_experiment_v2`'s PMBTokens construction which // uses P-384. int pmbtoken_exp2_generate_key(CBB *out_private, CBB *out_public); int pmbtoken_exp2_derive_key_from_secret(CBB *out_private, CBB *out_public, @@ -154,8 +152,8 @@ int pmbtoken_exp2_read(const TRUST_TOKEN_ISSUER_KEY *key, // function is used to confirm H was computed as expected. OPENSSL_EXPORT int pmbtoken_exp2_get_h_for_testing(uint8_t out[97]); -// The following functions implement the corresponding |TRUST_TOKENS_METHOD| -// functions for |TRUST_TOKENS_pst_v1|'s PMBTokens construction which uses +// The following functions implement the corresponding `TRUST_TOKENS_METHOD` +// functions for `TRUST_TOKENS_pst_v1`'s PMBTokens construction which uses // P-384. int pmbtoken_pst1_generate_key(CBB *out_private, CBB *out_public); int pmbtoken_pst1_derive_key_from_secret(CBB *out_private, CBB *out_public, @@ -193,11 +191,11 @@ OPENSSL_EXPORT int pmbtoken_pst1_get_h_for_testing(uint8_t out[97]); // and provide anonymous tokens. This implementation uses TrustToken DSTs and // the DLEQ batching primitive from // https://eprint.iacr.org/2020/072/20200324:214215. -// VOPRF only uses the |pub|' field of the TRUST_TOKEN_CLIENT_KEY and -// |xs|/|pubs| fields of the TRUST_TOKEN_ISSUER_KEY. +// VOPRF only uses the `pub`' field of the TRUST_TOKEN_CLIENT_KEY and +// `xs`/`pubs` fields of the TRUST_TOKEN_ISSUER_KEY. -// The following functions implement the corresponding |TRUST_TOKENS_METHOD| -// functions for |TRUST_TOKENS_experiment_v2|'s VOPRF construction which uses +// The following functions implement the corresponding `TRUST_TOKENS_METHOD` +// functions for `TRUST_TOKENS_experiment_v2`'s VOPRF construction which uses // P-384. int voprf_exp2_generate_key(CBB *out_private, CBB *out_public); int voprf_exp2_derive_key_from_secret(CBB *out_private, CBB *out_public, @@ -223,8 +221,8 @@ int voprf_exp2_read(const TRUST_TOKEN_ISSUER_KEY *key, size_t token_len, int include_message, const uint8_t *msg, size_t msg_len); -// The following functions implement the corresponding |TRUST_TOKENS_METHOD| -// functions for |TRUST_TOKENS_pst_v1|'s VOPRF construction which uses P-384. +// The following functions implement the corresponding `TRUST_TOKENS_METHOD` +// functions for `TRUST_TOKENS_pst_v1`'s VOPRF construction which uses P-384. int voprf_pst1_generate_key(CBB *out_private, CBB *out_public); int voprf_pst1_derive_key_from_secret(CBB *out_private, CBB *out_public, const uint8_t *secret, size_t secret_len); @@ -253,75 +251,78 @@ int voprf_pst1_read(const TRUST_TOKEN_ISSUER_KEY *key, size_t token_len, int include_message, const uint8_t *msg, size_t msg_len); +using StackOfTrustTokenPretoken = STACK_OF(TRUST_TOKEN_PRETOKEN); + +BSSL_NAMESPACE_END // Trust Tokens internals. struct trust_token_method_st { // generate_key generates a fresh keypair and writes their serialized - // forms into |out_private| and |out_public|. It returns one on success and + // forms into `out_private` and `out_public`. It returns one on success and // zero on failure. int (*generate_key)(CBB *out_private, CBB *out_public); // derive_key_from_secret deterministically derives a keypair based on - // |secret| and writes their serialized forms into |out_private| and - // |out_public|. It returns one on success and zero on failure. + // `secret` and writes their serialized forms into `out_private` and + // `out_public`. It returns one on success and zero on failure. int (*derive_key_from_secret)(CBB *out_private, CBB *out_public, const uint8_t *secret, size_t secret_len); - // client_key_from_bytes decodes a client key from |in| and sets |key| + // client_key_from_bytes decodes a client key from `in` and sets `key` // to the resulting key. It returns one on success and zero // on failure. - int (*client_key_from_bytes)(TRUST_TOKEN_CLIENT_KEY *key, const uint8_t *in, - size_t len); + int (*client_key_from_bytes)(bssl::TRUST_TOKEN_CLIENT_KEY *key, + const uint8_t *in, size_t len); - // issuer_key_from_bytes decodes a issuer key from |in| and sets |key| + // issuer_key_from_bytes decodes an issuer key from `in` and sets `key` // to the resulting key. It returns one on success and zero // on failure. - int (*issuer_key_from_bytes)(TRUST_TOKEN_ISSUER_KEY *key, const uint8_t *in, - size_t len); + int (*issuer_key_from_bytes)(bssl::TRUST_TOKEN_ISSUER_KEY *key, + const uint8_t *in, size_t len); - // blind generates a new issuance request for |count| tokens. If - // |include_message| is set, then |msg| is used to derive the token nonces. On - // success, it returns a newly-allocated |STACK_OF(TRUST_TOKEN_PRETOKEN)| and - // writes a request to the issuer to |cbb|. On failure, it returns NULL. The - // |STACK_OF(TRUST_TOKEN_PRETOKEN)|s should be passed to |pmbtoken_unblind| + // blind generates a new issuance request for `count` tokens. If + // `include_message` is set, then `msg` is used to derive the token nonces. On + // success, it returns a newly-allocated `STACK_OF(TRUST_TOKEN_PRETOKEN)` and + // writes a request to the issuer to `cbb`. On failure, it returns NULL. The + // `STACK_OF(TRUST_TOKEN_PRETOKEN)`s should be passed to `pmbtoken_unblind` // when the server responds. // // This function implements the AT.Usr0 operation. - STACK_OF(TRUST_TOKEN_PRETOKEN) *(*blind)(CBB *cbb, size_t count, - int include_message, - const uint8_t *msg, size_t msg_len); + bssl::StackOfTrustTokenPretoken *(*blind)(CBB *cbb, size_t count, + int include_message, + const uint8_t *msg, size_t msg_len); - // sign parses a request for |num_requested| tokens from |cbs| and - // issues |num_to_issue| tokens with |key| and a private metadata value of - // |private_metadata|. It then writes the response to |cbb|. It returns one on + // sign parses a request for `num_requested` tokens from `cbs` and + // issues `num_to_issue` tokens with `key` and a private metadata value of + // `private_metadata`. It then writes the response to `cbb`. It returns one on // success and zero on failure. // // This function implements the AT.Sig operation. - int (*sign)(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs, + int (*sign)(const bssl::TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs, size_t num_requested, size_t num_to_issue, uint8_t private_metadata); - // unblind processes an issuance response for |count| tokens from |cbs| - // and unblinds the signed tokens. |pretokens| are the pre-tokens returned - // from the corresponding |blind| call. On success, the function returns a - // newly-allocated |STACK_OF(TRUST_TOKEN)| containing the resulting tokens. - // Each token's serialization will have |key_id| prepended. Otherwise, it + // unblind processes an issuance response for `count` tokens from `cbs` + // and unblinds the signed tokens. `pretokens` are the pre-tokens returned + // from the corresponding `blind` call. On success, the function returns a + // newly-allocated `STACK_OF(TRUST_TOKEN)` containing the resulting tokens. + // Each token's serialization will have `key_id` prepended. Otherwise, it // returns NULL. // // This function implements the AT.Usr1 operation. STACK_OF(TRUST_TOKEN) *(*unblind)( - const TRUST_TOKEN_CLIENT_KEY *key, - const STACK_OF(TRUST_TOKEN_PRETOKEN) *pretokens, CBS *cbs, size_t count, + const bssl::TRUST_TOKEN_CLIENT_KEY *key, + const bssl::StackOfTrustTokenPretoken *pretokens, CBS *cbs, size_t count, uint32_t key_id); - // read parses a token from |token| and verifies it using |key|. If - // |include_message| is set, then the nonce is derived from |msg| and the salt + // read parses a token from `token` and verifies it using `key`. If + // `include_message` is set, then the nonce is derived from `msg` and the salt // in the token. On success, it returns one and stores the nonce and private - // metadata bit in |out_nonce| and |*out_private_metadata|. Otherwise, it - // returns zero. Note that, unlike the output of |unblind|, |token| does not + // metadata bit in `out_nonce` and `*out_private_metadata`. Otherwise, it + // returns zero. Note that, unlike the output of `unblind`, `token` does not // have a four-byte key ID prepended. - int (*read)(const TRUST_TOKEN_ISSUER_KEY *key, + int (*read)(const bssl::TRUST_TOKEN_ISSUER_KEY *key, uint8_t out_nonce[TRUST_TOKEN_NONCE_SIZE], uint8_t *out_private_metadata, const uint8_t *token, size_t token_len, int include_message, const uint8_t *msg, @@ -337,6 +338,8 @@ struct trust_token_method_st { int has_srr; }; +BSSL_NAMESPACE_BEGIN + // Structure representing a single Trust Token public key with the specified ID. struct trust_token_client_key_st { uint32_t id; @@ -350,6 +353,8 @@ struct trust_token_issuer_key_st { TRUST_TOKEN_ISSUER_KEY key; }; +BSSL_NAMESPACE_END + struct trust_token_client_st { const TRUST_TOKEN_METHOD *method; @@ -358,13 +363,15 @@ struct trust_token_client_st { // keys is the set of public keys that are supported by the client for // issuance/redemptions. - struct trust_token_client_key_st keys[6]; + // TODO(crbug.com/42290036): Replace this and `num_keys` with an + // InplaceVector. + struct bssl::trust_token_client_key_st keys[6]; // num_keys is the number of keys currently configured. size_t num_keys; // pretokens is the intermediate state during an active issuance. - STACK_OF(TRUST_TOKEN_PRETOKEN) *pretokens; + bssl::StackOfTrustTokenPretoken *pretokens; // srr_key is the public key used to verify the signature of the SRR. EVP_PKEY *srr_key; @@ -380,33 +387,19 @@ struct trust_token_issuer_st { // keys is the set of private keys that are supported by the issuer for // issuance/redemptions. The public metadata is an index into this list of // keys. - struct trust_token_issuer_key_st keys[6]; + struct bssl::trust_token_issuer_key_st keys[6]; // num_keys is the number of keys currently configured. size_t num_keys; // srr_key is the private key used to sign the SRR. EVP_PKEY *srr_key; - - // metadata_key is the secret material used to encode the private metadata bit - // in the SRR. - uint8_t *metadata_key; - size_t metadata_key_len; }; - -#if defined(__cplusplus) -} // extern C - -extern "C++" { - BSSL_NAMESPACE_BEGIN BORINGSSL_MAKE_DELETER(TRUST_TOKEN_PRETOKEN, TRUST_TOKEN_PRETOKEN_free) BSSL_NAMESPACE_END -} // extern C++ -#endif - -#endif // OPENSSL_HEADER_TRUST_TOKEN_INTERNAL_H +#endif // OPENSSL_HEADER_CRYPTO_TRUST_TOKEN_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/trust_token/pmbtoken.cc b/Sources/CNIOBoringSSL/crypto/trust_token/pmbtoken.cc index 8b2c143a..1693d47b 100644 --- a/Sources/CNIOBoringSSL/crypto/trust_token/pmbtoken.cc +++ b/Sources/CNIOBoringSSL/crypto/trust_token/pmbtoken.cc @@ -1,16 +1,16 @@ -/* Copyright 2020 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2020 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 @@ -21,15 +21,18 @@ #include #include #include -#include +#include #include "../ec/internal.h" #include "../fipsmodule/bn/internal.h" #include "../fipsmodule/ec/internal.h" +#include "../mem_internal.h" #include "internal.h" +using namespace bssl; + typedef int (*hash_t_func_t)(const EC_GROUP *group, EC_JACOBIAN *out, const uint8_t t[TRUST_TOKEN_NONCE_SIZE]); typedef int (*hash_s_func_t)(const EC_GROUP *group, EC_JACOBIAN *out, @@ -97,7 +100,7 @@ static int derive_scalar_from_secret(const PMBTOKEN_METHOD *method, int ok = 0; CBB cbb; CBB_zero(&cbb); - uint8_t *buf = NULL; + uint8_t *buf = nullptr; size_t len; if (!CBB_init(&cbb, 0) || !CBB_add_bytes(&cbb, kKeygenLabel, sizeof(kKeygenLabel)) || @@ -173,8 +176,8 @@ static int mul_public_3(const EC_GROUP *group, EC_JACOBIAN *out, const EC_JACOBIAN *p2, const EC_SCALAR *scalar2) { EC_JACOBIAN points[3] = {*p0, *p1, *p2}; EC_SCALAR scalars[3] = {*scalar0, *scalar1, *scalar2}; - return ec_point_mul_scalar_public_batch(group, out, /*g_scalar=*/NULL, points, - scalars, 3); + return ec_point_mul_scalar_public_batch(group, out, /*g_scalar=*/nullptr, + points, scalars, 3); } static int pmbtoken_compute_keys(const PMBTOKEN_METHOD *method, @@ -185,24 +188,25 @@ static int pmbtoken_compute_keys(const PMBTOKEN_METHOD *method, const EC_GROUP *group = method->group; EC_JACOBIAN pub[3]; if (!ec_point_mul_scalar_precomp(group, &pub[0], &method->g_precomp, x0, - &method->h_precomp, y0, NULL, NULL) || + &method->h_precomp, y0, nullptr, nullptr) || !ec_point_mul_scalar_precomp(group, &pub[1], &method->g_precomp, x1, - &method->h_precomp, y1, NULL, NULL) || + &method->h_precomp, y1, nullptr, nullptr) || !ec_point_mul_scalar_precomp(method->group, &pub[2], &method->g_precomp, - xs, &method->h_precomp, ys, NULL, NULL)) { + xs, &method->h_precomp, ys, nullptr, + nullptr)) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_KEYGEN_FAILURE); return 0; } const EC_SCALAR *scalars[] = {x0, y0, x1, y1, xs, ys}; size_t scalar_len = BN_num_bytes(EC_GROUP_get0_order(group)); - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(scalars); i++) { + for (const EC_SCALAR *scalar : scalars) { uint8_t *buf; if (!CBB_add_space(out_private, &buf, scalar_len)) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_BUFFER_TOO_SMALL); return 0; } - ec_scalar_to_bytes(group, buf, &scalar_len, scalars[i]); + ec_scalar_to_bytes(group, buf, &scalar_len, scalar); } EC_AFFINE pub_affine[3]; @@ -287,10 +291,9 @@ static int pmbtoken_issuer_key_from_bytes(const PMBTOKEN_METHOD *method, size_t scalar_len = BN_num_bytes(EC_GROUP_get0_order(group)); EC_SCALAR *scalars[] = {&key->x0, &key->y0, &key->x1, &key->y1, &key->xs, &key->ys}; - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(scalars); i++) { + for (EC_SCALAR *scalar : scalars) { if (!CBS_get_bytes(&cbs, &tmp, scalar_len) || - !ec_scalar_from_bytes(group, scalars[i], CBS_data(&tmp), - CBS_len(&tmp))) { + !ec_scalar_from_bytes(group, scalar, CBS_data(&tmp), CBS_len(&tmp))) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_DECODE_FAILURE); return 0; } @@ -300,13 +303,16 @@ static int pmbtoken_issuer_key_from_bytes(const PMBTOKEN_METHOD *method, EC_JACOBIAN pub[3]; EC_AFFINE pub_affine[3]; if (!ec_point_mul_scalar_precomp(group, &pub[0], &method->g_precomp, &key->x0, - &method->h_precomp, &key->y0, NULL, NULL) || + &method->h_precomp, &key->y0, nullptr, + nullptr) || !ec_init_precomp(group, &key->pub0_precomp, &pub[0]) || !ec_point_mul_scalar_precomp(group, &pub[1], &method->g_precomp, &key->x1, - &method->h_precomp, &key->y1, NULL, NULL) || + &method->h_precomp, &key->y1, nullptr, + nullptr) || !ec_init_precomp(group, &key->pub1_precomp, &pub[1]) || !ec_point_mul_scalar_precomp(group, &pub[2], &method->g_precomp, &key->xs, - &method->h_precomp, &key->ys, NULL, NULL) || + &method->h_precomp, &key->ys, nullptr, + nullptr) || !ec_init_precomp(group, &key->pubs_precomp, &pub[2]) || !ec_jacobian_to_affine_batch(group, pub_affine, pub, 3)) { return 0; @@ -326,15 +332,14 @@ static STACK_OF(TRUST_TOKEN_PRETOKEN) *pmbtoken_blind( const EC_GROUP *group = method->group; STACK_OF(TRUST_TOKEN_PRETOKEN) *pretokens = sk_TRUST_TOKEN_PRETOKEN_new_null(); - if (pretokens == NULL) { + if (pretokens == nullptr) { goto err; } for (size_t i = 0; i < count; i++) { - // Insert |pretoken| into |pretokens| early to simplify error-handling. - TRUST_TOKEN_PRETOKEN *pretoken = reinterpret_cast( - OPENSSL_malloc(sizeof(TRUST_TOKEN_PRETOKEN))); - if (pretoken == NULL || + // Insert `pretoken` into `pretokens` early to simplify error-handling. + TRUST_TOKEN_PRETOKEN *pretoken = New(); + if (pretoken == nullptr || !sk_TRUST_TOKEN_PRETOKEN_push(pretokens, pretoken)) { TRUST_TOKEN_PRETOKEN_free(pretoken); goto err; @@ -351,7 +356,7 @@ static STACK_OF(TRUST_TOKEN_PRETOKEN) *pmbtoken_blind( OPENSSL_memcpy(pretoken->t, pretoken->salt, TRUST_TOKEN_NONCE_SIZE); } - // We sample |pretoken->r| in Montgomery form to simplify inverting. + // We sample `pretoken->r` in Montgomery form to simplify inverting. if (!ec_random_nonzero_scalar(group, &pretoken->r, kDefaultAdditionalData)) { goto err; @@ -380,7 +385,7 @@ static STACK_OF(TRUST_TOKEN_PRETOKEN) *pmbtoken_blind( err: sk_TRUST_TOKEN_PRETOKEN_pop_free(pretokens, TRUST_TOKEN_PRETOKEN_free); - return NULL; + return nullptr; } static int scalar_to_cbb(CBB *out, const EC_GROUP *group, @@ -415,7 +420,7 @@ static int hash_c_dleq(const PMBTOKEN_METHOD *method, EC_SCALAR *out, int ok = 0; CBB cbb; CBB_zero(&cbb); - uint8_t *buf = NULL; + uint8_t *buf = nullptr; size_t len; if (!CBB_init(&cbb, 0) || !CBB_add_bytes(&cbb, kDLEQ2Label, sizeof(kDLEQ2Label)) || @@ -448,7 +453,7 @@ static int hash_c_dleqor(const PMBTOKEN_METHOD *method, EC_SCALAR *out, int ok = 0; CBB cbb; CBB_zero(&cbb); - uint8_t *buf = NULL; + uint8_t *buf = nullptr; size_t len; if (!CBB_init(&cbb, 0) || !CBB_add_bytes(&cbb, kDLEQOR2Label, sizeof(kDLEQOR2Label)) || @@ -486,7 +491,7 @@ static int hash_c_batch(const PMBTOKEN_METHOD *method, EC_SCALAR *out, int ok = 0; CBB cbb; CBB_zero(&cbb); - uint8_t *buf = NULL; + uint8_t *buf = nullptr; size_t len; if (!CBB_init(&cbb, 0) || !CBB_add_bytes(&cbb, kDLEQBatchLabel, sizeof(kDLEQBatchLabel)) || @@ -541,9 +546,9 @@ static int dleq_generate(const PMBTOKEN_METHOD *method, CBB *cbb, // Ks = ks0*(G;T) + ks1*(H;S) !ec_point_mul_scalar_precomp(group, &jacobians[idx_Ks0], &method->g_precomp, &ks0, &method->h_precomp, - &ks1, NULL, NULL) || + &ks1, nullptr, nullptr) || !ec_point_mul_scalar_batch(group, &jacobians[idx_Ks1], T, &ks0, S, &ks1, - NULL, NULL)) { + nullptr, nullptr)) { return 0; } @@ -565,9 +570,9 @@ static int dleq_generate(const PMBTOKEN_METHOD *method, CBB *cbb, // Kb = k0*(G;T) + k1*(H;S) !ec_point_mul_scalar_precomp(group, &jacobians[idx_Kb0], &method->g_precomp, &k0, &method->h_precomp, - &k1, NULL, NULL) || + &k1, nullptr, nullptr) || !ec_point_mul_scalar_batch(group, &jacobians[idx_Kb1], T, &k0, S, &k1, - NULL, NULL) || + nullptr, nullptr) || // co, uo, vo <- Zp !ec_random_nonzero_scalar(group, &minus_co, kDefaultAdditionalData) || !ec_random_nonzero_scalar(group, &uo, kDefaultAdditionalData) || @@ -828,14 +833,15 @@ static int pmbtoken_sign(const PMBTOKEN_METHOD *method, uint8_t s[TRUST_TOKEN_NONCE_SIZE]; RAND_bytes(s, TRUST_TOKEN_NONCE_SIZE); - // The |jacobians| and |affines| contain Sp, Wp, and Wsp. + // The `jacobians` and `affines` contain Sp, Wp, and Wsp. EC_JACOBIAN jacobians[3]; EC_AFFINE affines[3]; if (!method->hash_s(group, &jacobians[0], &Tp_affine, s) || !ec_point_mul_scalar_batch(group, &jacobians[1], &Tp, &xb, - &jacobians[0], &yb, NULL, NULL) || + &jacobians[0], &yb, nullptr, nullptr) || !ec_point_mul_scalar_batch(group, &jacobians[2], &Tp, &key->xs, - &jacobians[0], &key->ys, NULL, NULL) || + &jacobians[0], &key->ys, nullptr, + nullptr) || !ec_jacobian_to_affine_batch(group, affines, jacobians, 3) || !CBB_add_bytes(cbb, s, TRUST_TOKEN_NONCE_SIZE) || !cbb_add_prefixed_point(cbb, group, &affines[1], @@ -872,16 +878,16 @@ static int pmbtoken_sign(const PMBTOKEN_METHOD *method, EC_JACOBIAN Tp_batch, Sp_batch, Wp_batch, Wsp_batch; if (!ec_point_mul_scalar_public_batch(group, &Tp_batch, - /*g_scalar=*/NULL, Tps, es, + /*g_scalar=*/nullptr, Tps, es, num_to_issue) || !ec_point_mul_scalar_public_batch(group, &Sp_batch, - /*g_scalar=*/NULL, Sps, es, + /*g_scalar=*/nullptr, Sps, es, num_to_issue) || !ec_point_mul_scalar_public_batch(group, &Wp_batch, - /*g_scalar=*/NULL, Wps, es, + /*g_scalar=*/nullptr, Wps, es, num_to_issue) || !ec_point_mul_scalar_public_batch(group, &Wsp_batch, - /*g_scalar=*/NULL, Wsps, es, + /*g_scalar=*/nullptr, Wsps, es, num_to_issue)) { goto err; } @@ -909,11 +915,11 @@ static int pmbtoken_sign(const PMBTOKEN_METHOD *method, } err: - OPENSSL_free(Tps); - OPENSSL_free(Sps); - OPENSSL_free(Wps); - OPENSSL_free(Wsps); - OPENSSL_free(es); + Delete(Tps); + Delete(Sps); + Delete(Wps); + Delete(Wsps); + Delete(es); CBB_cleanup(&batch_cbb); return ret; } @@ -925,7 +931,7 @@ static STACK_OF(TRUST_TOKEN) *pmbtoken_unblind( const EC_GROUP *group = method->group; if (count > sk_TRUST_TOKEN_PRETOKEN_num(pretokens)) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_DECODE_FAILURE); - return NULL; + return nullptr; } int ok = 0; @@ -942,8 +948,8 @@ static STACK_OF(TRUST_TOKEN) *pmbtoken_unblind( reinterpret_cast(OPENSSL_calloc(count, sizeof(EC_SCALAR))); CBB batch_cbb; CBB_zero(&batch_cbb); - if (ret == NULL || Tps == NULL || Sps == NULL || Wps == NULL || - Wsps == NULL || es == NULL || !CBB_init(&batch_cbb, 0) || + if (ret == nullptr || Tps == nullptr || Sps == nullptr || Wps == nullptr || + Wsps == nullptr || es == nullptr || !CBB_init(&batch_cbb, 0) || !point_to_cbb(&batch_cbb, method->group, &key->pubs) || !point_to_cbb(&batch_cbb, method->group, &key->pub0) || !point_to_cbb(&batch_cbb, method->group, &key->pub1)) { @@ -990,7 +996,7 @@ static STACK_OF(TRUST_TOKEN) *pmbtoken_unblind( goto err; } - // Serialize the token. Include |key_id| to avoid an extra copy in the layer + // Serialize the token. Include `key_id` to avoid an extra copy in the layer // above. CBB token_cbb; size_t point_len = ec_point_byte_len(group, POINT_CONVERSION_UNCOMPRESSED); @@ -1012,7 +1018,7 @@ static STACK_OF(TRUST_TOKEN) *pmbtoken_unblind( TRUST_TOKEN *token = TRUST_TOKEN_new(CBB_data(&token_cbb), CBB_len(&token_cbb)); CBB_cleanup(&token_cbb); - if (token == NULL || !sk_TRUST_TOKEN_push(ret, token)) { + if (token == nullptr || !sk_TRUST_TOKEN_push(ret, token)) { TRUST_TOKEN_free(token); goto err; } @@ -1029,13 +1035,14 @@ static STACK_OF(TRUST_TOKEN) *pmbtoken_unblind( EC_JACOBIAN Tp_batch, Sp_batch, Wp_batch, Wsp_batch; if (!ec_point_mul_scalar_public_batch(group, &Tp_batch, - /*g_scalar=*/NULL, Tps, es, count) || + /*g_scalar=*/nullptr, Tps, es, count) || !ec_point_mul_scalar_public_batch(group, &Sp_batch, - /*g_scalar=*/NULL, Sps, es, count) || + /*g_scalar=*/nullptr, Sps, es, count) || !ec_point_mul_scalar_public_batch(group, &Wp_batch, - /*g_scalar=*/NULL, Wps, es, count) || + /*g_scalar=*/nullptr, Wps, es, count) || !ec_point_mul_scalar_public_batch(group, &Wsp_batch, - /*g_scalar=*/NULL, Wsps, es, count)) { + /*g_scalar=*/nullptr, Wsps, es, + count)) { goto err; } @@ -1050,15 +1057,15 @@ static STACK_OF(TRUST_TOKEN) *pmbtoken_unblind( ok = 1; err: - OPENSSL_free(Tps); - OPENSSL_free(Sps); - OPENSSL_free(Wps); - OPENSSL_free(Wsps); - OPENSSL_free(es); + Delete(Tps); + Delete(Sps); + Delete(Wps); + Delete(Wsps); + Delete(es); CBB_cleanup(&batch_cbb); if (!ok) { sk_TRUST_TOKEN_pop_free(ret, TRUST_TOKEN_free); - ret = NULL; + ret = nullptr; } return ret; } @@ -1099,7 +1106,7 @@ static int pmbtoken_read(const PMBTOKEN_METHOD *method, } // We perform three multiplications with S and T. This is enough that it is - // worth using |ec_point_mul_scalar_precomp|. + // worth using `ec_point_mul_scalar_precomp`. EC_JACOBIAN S_jacobian; EC_PRECOMP S_precomp, T_precomp; ec_affine_to_jacobian(group, &S_jacobian, &S); @@ -1111,7 +1118,7 @@ static int pmbtoken_read(const PMBTOKEN_METHOD *method, EC_JACOBIAN Ws_calculated; // Check the validity of the token. if (!ec_point_mul_scalar_precomp(group, &Ws_calculated, &T_precomp, &key->xs, - &S_precomp, &key->ys, NULL, NULL) || + &S_precomp, &key->ys, nullptr, nullptr) || !ec_affine_jacobian_equal(group, &Ws, &Ws_calculated)) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_BAD_VALIDITY_CHECK); return 0; @@ -1119,9 +1126,9 @@ static int pmbtoken_read(const PMBTOKEN_METHOD *method, EC_JACOBIAN W0, W1; if (!ec_point_mul_scalar_precomp(group, &W0, &T_precomp, &key->x0, &S_precomp, - &key->y0, NULL, NULL) || + &key->y0, nullptr, nullptr) || !ec_point_mul_scalar_precomp(group, &W1, &T_precomp, &key->x1, &S_precomp, - &key->y1, NULL, NULL)) { + &key->y1, nullptr, nullptr)) { return 0; } @@ -1154,7 +1161,7 @@ static int pmbtoken_exp1_hash_s(const EC_GROUP *group, EC_JACOBIAN *out, const uint8_t kHashSLabel[] = "PMBTokens Experiment V1 HashS"; int ret = 0; CBB cbb; - uint8_t *buf = NULL; + uint8_t *buf = nullptr; size_t len; if (!CBB_init(&cbb, 0) || !point_to_cbb(&cbb, group, t) || !CBB_add_bytes(&cbb, s, TRUST_TOKEN_NONCE_SIZE) || @@ -1190,8 +1197,8 @@ static int pmbtoken_exp1_ok = 0; static PMBTOKEN_METHOD pmbtoken_exp1_method; static CRYPTO_once_t pmbtoken_exp1_method_once = CRYPTO_ONCE_INIT; -static void pmbtoken_exp1_init_method_impl(void) { - // This is the output of |ec_hash_to_scalar_p384_xmd_sha512_draft07| with DST +static void pmbtoken_exp1_init_method_impl() { + // This is the output of `ec_hash_to_scalar_p384_xmd_sha512_draft07` with DST // "PMBTokens Experiment V1 HashH" and message "generator". static const uint8_t kH[] = { 0x04, 0x82, 0xd5, 0x68, 0xf5, 0x39, 0xf6, 0x08, 0x19, 0xa1, 0x75, @@ -1211,7 +1218,7 @@ static void pmbtoken_exp1_init_method_impl(void) { pmbtoken_exp1_hash_to_scalar, 1); } -static int pmbtoken_exp1_init_method(void) { +static int pmbtoken_exp1_init_method() { CRYPTO_once(&pmbtoken_exp1_method_once, pmbtoken_exp1_init_method_impl); if (!pmbtoken_exp1_ok) { OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_INTERNAL_ERROR); @@ -1220,7 +1227,7 @@ static int pmbtoken_exp1_init_method(void) { return 1; } -int pmbtoken_exp1_generate_key(CBB *out_private, CBB *out_public) { +int bssl::pmbtoken_exp1_generate_key(CBB *out_private, CBB *out_public) { if (!pmbtoken_exp1_init_method()) { return 0; } @@ -1228,9 +1235,10 @@ int pmbtoken_exp1_generate_key(CBB *out_private, CBB *out_public) { return pmbtoken_generate_key(&pmbtoken_exp1_method, out_private, out_public); } -int pmbtoken_exp1_derive_key_from_secret(CBB *out_private, CBB *out_public, - const uint8_t *secret, - size_t secret_len) { +int bssl::pmbtoken_exp1_derive_key_from_secret(CBB *out_private, + CBB *out_public, + const uint8_t *secret, + size_t secret_len) { if (!pmbtoken_exp1_init_method()) { return 0; } @@ -1239,36 +1247,37 @@ int pmbtoken_exp1_derive_key_from_secret(CBB *out_private, CBB *out_public, out_public, secret, secret_len); } -int pmbtoken_exp1_client_key_from_bytes(TRUST_TOKEN_CLIENT_KEY *key, - const uint8_t *in, size_t len) { +int bssl::pmbtoken_exp1_client_key_from_bytes(TRUST_TOKEN_CLIENT_KEY *key, + const uint8_t *in, size_t len) { if (!pmbtoken_exp1_init_method()) { return 0; } return pmbtoken_client_key_from_bytes(&pmbtoken_exp1_method, key, in, len); } -int pmbtoken_exp1_issuer_key_from_bytes(TRUST_TOKEN_ISSUER_KEY *key, - const uint8_t *in, size_t len) { +int bssl::pmbtoken_exp1_issuer_key_from_bytes(TRUST_TOKEN_ISSUER_KEY *key, + const uint8_t *in, size_t len) { if (!pmbtoken_exp1_init_method()) { return 0; } return pmbtoken_issuer_key_from_bytes(&pmbtoken_exp1_method, key, in, len); } -STACK_OF(TRUST_TOKEN_PRETOKEN) *pmbtoken_exp1_blind(CBB *cbb, size_t count, - int include_message, - const uint8_t *msg, - size_t msg_len) { +STACK_OF(TRUST_TOKEN_PRETOKEN) *bssl::pmbtoken_exp1_blind(CBB *cbb, + size_t count, + int include_message, + const uint8_t *msg, + size_t msg_len) { if (!pmbtoken_exp1_init_method()) { - return NULL; + return nullptr; } return pmbtoken_blind(&pmbtoken_exp1_method, cbb, count, include_message, msg, msg_len); } -int pmbtoken_exp1_sign(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs, - size_t num_requested, size_t num_to_issue, - uint8_t private_metadata) { +int bssl::pmbtoken_exp1_sign(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, + CBS *cbs, size_t num_requested, + size_t num_to_issue, uint8_t private_metadata) { if (!pmbtoken_exp1_init_method()) { return 0; } @@ -1276,22 +1285,23 @@ int pmbtoken_exp1_sign(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs, num_to_issue, private_metadata); } -STACK_OF(TRUST_TOKEN) *pmbtoken_exp1_unblind( +STACK_OF(TRUST_TOKEN) *bssl::pmbtoken_exp1_unblind( const TRUST_TOKEN_CLIENT_KEY *key, const STACK_OF(TRUST_TOKEN_PRETOKEN) *pretokens, CBS *cbs, size_t count, uint32_t key_id) { if (!pmbtoken_exp1_init_method()) { - return NULL; + return nullptr; } return pmbtoken_unblind(&pmbtoken_exp1_method, key, pretokens, cbs, count, key_id); } -int pmbtoken_exp1_read(const TRUST_TOKEN_ISSUER_KEY *key, - uint8_t out_nonce[TRUST_TOKEN_NONCE_SIZE], - uint8_t *out_private_metadata, const uint8_t *token, - size_t token_len, int include_message, - const uint8_t *msg, size_t msg_len) { +int bssl::pmbtoken_exp1_read(const TRUST_TOKEN_ISSUER_KEY *key, + uint8_t out_nonce[TRUST_TOKEN_NONCE_SIZE], + uint8_t *out_private_metadata, + const uint8_t *token, size_t token_len, + int include_message, const uint8_t *msg, + size_t msg_len) { if (!pmbtoken_exp1_init_method()) { return 0; } @@ -1300,7 +1310,7 @@ int pmbtoken_exp1_read(const TRUST_TOKEN_ISSUER_KEY *key, msg, msg_len); } -int pmbtoken_exp1_get_h_for_testing(uint8_t out[97]) { +int bssl::pmbtoken_exp1_get_h_for_testing(uint8_t out[97]) { if (!pmbtoken_exp1_init_method()) { return 0; } @@ -1326,7 +1336,7 @@ static int pmbtoken_exp2_hash_s(const EC_GROUP *group, EC_JACOBIAN *out, const uint8_t kHashSLabel[] = "PMBTokens Experiment V2 HashS"; int ret = 0; CBB cbb; - uint8_t *buf = NULL; + uint8_t *buf = nullptr; size_t len; if (!CBB_init(&cbb, 0) || !point_to_cbb(&cbb, group, t) || !CBB_add_bytes(&cbb, s, TRUST_TOKEN_NONCE_SIZE) || @@ -1362,8 +1372,8 @@ static int pmbtoken_exp2_ok = 0; static PMBTOKEN_METHOD pmbtoken_exp2_method; static CRYPTO_once_t pmbtoken_exp2_method_once = CRYPTO_ONCE_INIT; -static void pmbtoken_exp2_init_method_impl(void) { - // This is the output of |ec_hash_to_scalar_p384_xmd_sha512_draft07| with DST +static void pmbtoken_exp2_init_method_impl() { + // This is the output of `ec_hash_to_scalar_p384_xmd_sha512_draft07` with DST // "PMBTokens Experiment V2 HashH" and message "generator". static const uint8_t kH[] = { 0x04, 0xbc, 0x27, 0x24, 0x99, 0xfa, 0xc9, 0xa4, 0x74, 0x6f, 0xf9, @@ -1382,7 +1392,7 @@ static void pmbtoken_exp2_init_method_impl(void) { pmbtoken_exp2_hash_to_scalar, 0); } -static int pmbtoken_exp2_init_method(void) { +static int pmbtoken_exp2_init_method() { CRYPTO_once(&pmbtoken_exp2_method_once, pmbtoken_exp2_init_method_impl); if (!pmbtoken_exp2_ok) { OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_INTERNAL_ERROR); @@ -1391,7 +1401,7 @@ static int pmbtoken_exp2_init_method(void) { return 1; } -int pmbtoken_exp2_generate_key(CBB *out_private, CBB *out_public) { +int bssl::pmbtoken_exp2_generate_key(CBB *out_private, CBB *out_public) { if (!pmbtoken_exp2_init_method()) { return 0; } @@ -1400,9 +1410,10 @@ int pmbtoken_exp2_generate_key(CBB *out_private, CBB *out_public) { } -int pmbtoken_exp2_derive_key_from_secret(CBB *out_private, CBB *out_public, - const uint8_t *secret, - size_t secret_len) { +int bssl::pmbtoken_exp2_derive_key_from_secret(CBB *out_private, + CBB *out_public, + const uint8_t *secret, + size_t secret_len) { if (!pmbtoken_exp2_init_method()) { return 0; } @@ -1411,36 +1422,37 @@ int pmbtoken_exp2_derive_key_from_secret(CBB *out_private, CBB *out_public, out_public, secret, secret_len); } -int pmbtoken_exp2_client_key_from_bytes(TRUST_TOKEN_CLIENT_KEY *key, - const uint8_t *in, size_t len) { +int bssl::pmbtoken_exp2_client_key_from_bytes(TRUST_TOKEN_CLIENT_KEY *key, + const uint8_t *in, size_t len) { if (!pmbtoken_exp2_init_method()) { return 0; } return pmbtoken_client_key_from_bytes(&pmbtoken_exp2_method, key, in, len); } -int pmbtoken_exp2_issuer_key_from_bytes(TRUST_TOKEN_ISSUER_KEY *key, - const uint8_t *in, size_t len) { +int bssl::pmbtoken_exp2_issuer_key_from_bytes(TRUST_TOKEN_ISSUER_KEY *key, + const uint8_t *in, size_t len) { if (!pmbtoken_exp2_init_method()) { return 0; } return pmbtoken_issuer_key_from_bytes(&pmbtoken_exp2_method, key, in, len); } -STACK_OF(TRUST_TOKEN_PRETOKEN) *pmbtoken_exp2_blind(CBB *cbb, size_t count, - int include_message, - const uint8_t *msg, - size_t msg_len) { +STACK_OF(TRUST_TOKEN_PRETOKEN) *bssl::pmbtoken_exp2_blind(CBB *cbb, + size_t count, + int include_message, + const uint8_t *msg, + size_t msg_len) { if (!pmbtoken_exp2_init_method()) { - return NULL; + return nullptr; } return pmbtoken_blind(&pmbtoken_exp2_method, cbb, count, include_message, msg, msg_len); } -int pmbtoken_exp2_sign(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs, - size_t num_requested, size_t num_to_issue, - uint8_t private_metadata) { +int bssl::pmbtoken_exp2_sign(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, + CBS *cbs, size_t num_requested, + size_t num_to_issue, uint8_t private_metadata) { if (!pmbtoken_exp2_init_method()) { return 0; } @@ -1448,22 +1460,23 @@ int pmbtoken_exp2_sign(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs, num_to_issue, private_metadata); } -STACK_OF(TRUST_TOKEN) *pmbtoken_exp2_unblind( +STACK_OF(TRUST_TOKEN) *bssl::pmbtoken_exp2_unblind( const TRUST_TOKEN_CLIENT_KEY *key, const STACK_OF(TRUST_TOKEN_PRETOKEN) *pretokens, CBS *cbs, size_t count, uint32_t key_id) { if (!pmbtoken_exp2_init_method()) { - return NULL; + return nullptr; } return pmbtoken_unblind(&pmbtoken_exp2_method, key, pretokens, cbs, count, key_id); } -int pmbtoken_exp2_read(const TRUST_TOKEN_ISSUER_KEY *key, - uint8_t out_nonce[TRUST_TOKEN_NONCE_SIZE], - uint8_t *out_private_metadata, const uint8_t *token, - size_t token_len, int include_message, - const uint8_t *msg, size_t msg_len) { +int bssl::pmbtoken_exp2_read(const TRUST_TOKEN_ISSUER_KEY *key, + uint8_t out_nonce[TRUST_TOKEN_NONCE_SIZE], + uint8_t *out_private_metadata, + const uint8_t *token, size_t token_len, + int include_message, const uint8_t *msg, + size_t msg_len) { if (!pmbtoken_exp2_init_method()) { return 0; } @@ -1472,7 +1485,7 @@ int pmbtoken_exp2_read(const TRUST_TOKEN_ISSUER_KEY *key, msg, msg_len); } -int pmbtoken_exp2_get_h_for_testing(uint8_t out[97]) { +int bssl::pmbtoken_exp2_get_h_for_testing(uint8_t out[97]) { if (!pmbtoken_exp2_init_method()) { return 0; } @@ -1498,7 +1511,7 @@ static int pmbtoken_pst1_hash_s(const EC_GROUP *group, EC_JACOBIAN *out, const uint8_t kHashSLabel[] = "PMBTokens PST V1 HashS"; int ret = 0; CBB cbb; - uint8_t *buf = NULL; + uint8_t *buf = nullptr; size_t len; if (!CBB_init(&cbb, 0) || !point_to_cbb(&cbb, group, t) || !CBB_add_bytes(&cbb, s, TRUST_TOKEN_NONCE_SIZE) || @@ -1534,8 +1547,8 @@ static int pmbtoken_pst1_ok = 0; static PMBTOKEN_METHOD pmbtoken_pst1_method; static CRYPTO_once_t pmbtoken_pst1_method_once = CRYPTO_ONCE_INIT; -static void pmbtoken_pst1_init_method_impl(void) { - // This is the output of |ec_hash_to_scalar_p384_xmd_sha384| with DST +static void pmbtoken_pst1_init_method_impl() { + // This is the output of `ec_hash_to_scalar_p384_xmd_sha384` with DST // "PMBTokens PST V1 HashH" and message "generator". static const uint8_t kH[] = { 0x04, 0x4c, 0xfa, 0xd4, 0x33, 0x6d, 0x8c, 0x4e, 0x18, 0xce, 0x1a, @@ -1554,7 +1567,7 @@ static void pmbtoken_pst1_init_method_impl(void) { pmbtoken_pst1_hash_to_scalar, 0); } -static int pmbtoken_pst1_init_method(void) { +static int pmbtoken_pst1_init_method() { CRYPTO_once(&pmbtoken_pst1_method_once, pmbtoken_pst1_init_method_impl); if (!pmbtoken_pst1_ok) { OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_INTERNAL_ERROR); @@ -1563,7 +1576,7 @@ static int pmbtoken_pst1_init_method(void) { return 1; } -int pmbtoken_pst1_generate_key(CBB *out_private, CBB *out_public) { +int bssl::pmbtoken_pst1_generate_key(CBB *out_private, CBB *out_public) { if (!pmbtoken_pst1_init_method()) { return 0; } @@ -1572,9 +1585,10 @@ int pmbtoken_pst1_generate_key(CBB *out_private, CBB *out_public) { } -int pmbtoken_pst1_derive_key_from_secret(CBB *out_private, CBB *out_public, - const uint8_t *secret, - size_t secret_len) { +int bssl::pmbtoken_pst1_derive_key_from_secret(CBB *out_private, + CBB *out_public, + const uint8_t *secret, + size_t secret_len) { if (!pmbtoken_pst1_init_method()) { return 0; } @@ -1583,36 +1597,37 @@ int pmbtoken_pst1_derive_key_from_secret(CBB *out_private, CBB *out_public, out_public, secret, secret_len); } -int pmbtoken_pst1_client_key_from_bytes(TRUST_TOKEN_CLIENT_KEY *key, - const uint8_t *in, size_t len) { +int bssl::pmbtoken_pst1_client_key_from_bytes(TRUST_TOKEN_CLIENT_KEY *key, + const uint8_t *in, size_t len) { if (!pmbtoken_pst1_init_method()) { return 0; } return pmbtoken_client_key_from_bytes(&pmbtoken_pst1_method, key, in, len); } -int pmbtoken_pst1_issuer_key_from_bytes(TRUST_TOKEN_ISSUER_KEY *key, - const uint8_t *in, size_t len) { +int bssl::pmbtoken_pst1_issuer_key_from_bytes(TRUST_TOKEN_ISSUER_KEY *key, + const uint8_t *in, size_t len) { if (!pmbtoken_pst1_init_method()) { return 0; } return pmbtoken_issuer_key_from_bytes(&pmbtoken_pst1_method, key, in, len); } -STACK_OF(TRUST_TOKEN_PRETOKEN) *pmbtoken_pst1_blind(CBB *cbb, size_t count, - int include_message, - const uint8_t *msg, - size_t msg_len) { +STACK_OF(TRUST_TOKEN_PRETOKEN) *bssl::pmbtoken_pst1_blind(CBB *cbb, + size_t count, + int include_message, + const uint8_t *msg, + size_t msg_len) { if (!pmbtoken_pst1_init_method()) { - return NULL; + return nullptr; } return pmbtoken_blind(&pmbtoken_pst1_method, cbb, count, include_message, msg, msg_len); } -int pmbtoken_pst1_sign(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs, - size_t num_requested, size_t num_to_issue, - uint8_t private_metadata) { +int bssl::pmbtoken_pst1_sign(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, + CBS *cbs, size_t num_requested, + size_t num_to_issue, uint8_t private_metadata) { if (!pmbtoken_pst1_init_method()) { return 0; } @@ -1620,22 +1635,23 @@ int pmbtoken_pst1_sign(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs, num_to_issue, private_metadata); } -STACK_OF(TRUST_TOKEN) *pmbtoken_pst1_unblind( +STACK_OF(TRUST_TOKEN) *bssl::pmbtoken_pst1_unblind( const TRUST_TOKEN_CLIENT_KEY *key, const STACK_OF(TRUST_TOKEN_PRETOKEN) *pretokens, CBS *cbs, size_t count, uint32_t key_id) { if (!pmbtoken_pst1_init_method()) { - return NULL; + return nullptr; } return pmbtoken_unblind(&pmbtoken_pst1_method, key, pretokens, cbs, count, key_id); } -int pmbtoken_pst1_read(const TRUST_TOKEN_ISSUER_KEY *key, - uint8_t out_nonce[TRUST_TOKEN_NONCE_SIZE], - uint8_t *out_private_metadata, const uint8_t *token, - size_t token_len, int include_message, - const uint8_t *msg, size_t msg_len) { +int bssl::pmbtoken_pst1_read(const TRUST_TOKEN_ISSUER_KEY *key, + uint8_t out_nonce[TRUST_TOKEN_NONCE_SIZE], + uint8_t *out_private_metadata, + const uint8_t *token, size_t token_len, + int include_message, const uint8_t *msg, + size_t msg_len) { if (!pmbtoken_pst1_init_method()) { return 0; } @@ -1644,7 +1660,7 @@ int pmbtoken_pst1_read(const TRUST_TOKEN_ISSUER_KEY *key, msg, msg_len); } -int pmbtoken_pst1_get_h_for_testing(uint8_t out[97]) { +int bssl::pmbtoken_pst1_get_h_for_testing(uint8_t out[97]) { if (!pmbtoken_pst1_init_method()) { return 0; } diff --git a/Sources/CNIOBoringSSL/crypto/trust_token/trust_token.cc b/Sources/CNIOBoringSSL/crypto/trust_token/trust_token.cc index 57b2d91f..e649d2d2 100644 --- a/Sources/CNIOBoringSSL/crypto/trust_token/trust_token.cc +++ b/Sources/CNIOBoringSSL/crypto/trust_token/trust_token.cc @@ -1,24 +1,28 @@ -/* Copyright 2019 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2019 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 "../mem_internal.h" #include "internal.h" @@ -27,7 +31,9 @@ // protocol for issuing and redeeming tokens built on top of the PMBTokens // construction. -const TRUST_TOKEN_METHOD *TRUST_TOKEN_experiment_v1(void) { +using namespace bssl; + +const TRUST_TOKEN_METHOD *TRUST_TOKEN_experiment_v1() { static const TRUST_TOKEN_METHOD kMethod = { pmbtoken_exp1_generate_key, pmbtoken_exp1_derive_key_from_secret, @@ -44,7 +50,7 @@ const TRUST_TOKEN_METHOD *TRUST_TOKEN_experiment_v1(void) { return &kMethod; } -const TRUST_TOKEN_METHOD *TRUST_TOKEN_experiment_v2_voprf(void) { +const TRUST_TOKEN_METHOD *TRUST_TOKEN_experiment_v2_voprf() { static const TRUST_TOKEN_METHOD kMethod = { voprf_exp2_generate_key, voprf_exp2_derive_key_from_secret, @@ -61,7 +67,7 @@ const TRUST_TOKEN_METHOD *TRUST_TOKEN_experiment_v2_voprf(void) { return &kMethod; } -const TRUST_TOKEN_METHOD *TRUST_TOKEN_experiment_v2_pmb(void) { +const TRUST_TOKEN_METHOD *TRUST_TOKEN_experiment_v2_pmb() { static const TRUST_TOKEN_METHOD kMethod = { pmbtoken_exp2_generate_key, pmbtoken_exp2_derive_key_from_secret, @@ -78,7 +84,7 @@ const TRUST_TOKEN_METHOD *TRUST_TOKEN_experiment_v2_pmb(void) { return &kMethod; } -const TRUST_TOKEN_METHOD *TRUST_TOKEN_pst_v1_voprf(void) { +const TRUST_TOKEN_METHOD *TRUST_TOKEN_pst_v1_voprf() { static const TRUST_TOKEN_METHOD kMethod = { voprf_pst1_generate_key, voprf_pst1_derive_key_from_secret, @@ -95,7 +101,7 @@ const TRUST_TOKEN_METHOD *TRUST_TOKEN_pst_v1_voprf(void) { return &kMethod; } -const TRUST_TOKEN_METHOD *TRUST_TOKEN_pst_v1_pmb(void) { +const TRUST_TOKEN_METHOD *TRUST_TOKEN_pst_v1_pmb() { static const TRUST_TOKEN_METHOD kMethod = { pmbtoken_pst1_generate_key, pmbtoken_pst1_derive_key_from_secret, @@ -113,31 +119,30 @@ const TRUST_TOKEN_METHOD *TRUST_TOKEN_pst_v1_pmb(void) { } -void TRUST_TOKEN_PRETOKEN_free(TRUST_TOKEN_PRETOKEN *pretoken) { - OPENSSL_free(pretoken); +void bssl::TRUST_TOKEN_PRETOKEN_free(TRUST_TOKEN_PRETOKEN *pretoken) { + Delete(pretoken); } TRUST_TOKEN *TRUST_TOKEN_new(const uint8_t *data, size_t len) { - TRUST_TOKEN *ret = - reinterpret_cast(OPENSSL_zalloc(sizeof(TRUST_TOKEN))); - if (ret == NULL) { - return NULL; + TRUST_TOKEN *ret = New(); + if (ret == nullptr) { + return nullptr; } ret->data = reinterpret_cast(OPENSSL_memdup(data, len)); - if (len != 0 && ret->data == NULL) { - OPENSSL_free(ret); - return NULL; + if (len != 0 && ret->data == nullptr) { + Delete(ret); + return nullptr; } ret->len = len; return ret; } void TRUST_TOKEN_free(TRUST_TOKEN *token) { - if (token == NULL) { + if (token == nullptr) { return; } OPENSSL_free(token->data); - OPENSSL_free(token); + Delete(token); } int TRUST_TOKEN_generate_key(const TRUST_TOKEN_METHOD *method, @@ -159,8 +164,8 @@ int TRUST_TOKEN_generate_key(const TRUST_TOKEN_METHOD *method, return 0; } - if (!CBB_finish(&priv_cbb, NULL, out_priv_key_len) || - !CBB_finish(&pub_cbb, NULL, out_pub_key_len)) { + if (!CBB_finish(&priv_cbb, nullptr, out_priv_key_len) || + !CBB_finish(&pub_cbb, nullptr, out_pub_key_len)) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_BUFFER_TOO_SMALL); return 0; } @@ -188,8 +193,8 @@ int TRUST_TOKEN_derive_key_from_secret( return 0; } - if (!CBB_finish(&priv_cbb, NULL, out_priv_key_len) || - !CBB_finish(&pub_cbb, NULL, out_pub_key_len)) { + if (!CBB_finish(&priv_cbb, nullptr, out_priv_key_len) || + !CBB_finish(&pub_cbb, nullptr, out_pub_key_len)) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_BUFFER_TOO_SMALL); return 0; } @@ -202,13 +207,12 @@ TRUST_TOKEN_CLIENT *TRUST_TOKEN_CLIENT_new(const TRUST_TOKEN_METHOD *method, if (max_batchsize > 0xffff) { // The protocol supports only two-byte token counts. OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_OVERFLOW); - return NULL; + return nullptr; } - TRUST_TOKEN_CLIENT *ret = reinterpret_cast( - OPENSSL_zalloc(sizeof(TRUST_TOKEN_CLIENT))); - if (ret == NULL) { - return NULL; + TRUST_TOKEN_CLIENT *ret = New(); + if (ret == nullptr) { + return nullptr; } ret->method = method; ret->max_batchsize = (uint16_t)max_batchsize; @@ -216,17 +220,44 @@ TRUST_TOKEN_CLIENT *TRUST_TOKEN_CLIENT_new(const TRUST_TOKEN_METHOD *method, } void TRUST_TOKEN_CLIENT_free(TRUST_TOKEN_CLIENT *ctx) { - if (ctx == NULL) { + if (ctx == nullptr) { return; } EVP_PKEY_free(ctx->srr_key); sk_TRUST_TOKEN_PRETOKEN_pop_free(ctx->pretokens, TRUST_TOKEN_PRETOKEN_free); - OPENSSL_free(ctx); + Delete(ctx); +} + +static TRUST_TOKEN_PRETOKEN *dup_pretoken(const TRUST_TOKEN_PRETOKEN *in) { + return static_cast( + OPENSSL_memdup(in, sizeof(TRUST_TOKEN_PRETOKEN))); +} + +TRUST_TOKEN_CLIENT *TRUST_TOKEN_CLIENT_dup_for_testing( + const TRUST_TOKEN_CLIENT *ctx) { + bssl::UniquePtr ret( + TRUST_TOKEN_CLIENT_new(ctx->method, ctx->max_batchsize)); + if (ret == nullptr) { + return nullptr; + } + for (size_t i = 0; i < std::size(ret->keys); i++) { + ret->keys[i] = ctx->keys[i]; + } + ret->num_keys = ctx->num_keys; + if (ctx->pretokens != nullptr) { + ret->pretokens = sk_TRUST_TOKEN_PRETOKEN_deep_copy( + ctx->pretokens, dup_pretoken, TRUST_TOKEN_PRETOKEN_free); + if (ret->pretokens == nullptr) { + return nullptr; + } + } + ret->srr_key = bssl::UpRef(ctx->srr_key).release(); + return ret.release(); } int TRUST_TOKEN_CLIENT_add_key(TRUST_TOKEN_CLIENT *ctx, size_t *out_key_index, const uint8_t *key, size_t key_len) { - if (ctx->num_keys == OPENSSL_ARRAY_SIZE(ctx->keys) || + if (ctx->num_keys == std::size(ctx->keys) || ctx->num_keys >= ctx->method->max_keys) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_TOO_MANY_KEYS); return 0; @@ -267,14 +298,14 @@ static int trust_token_client_begin_issuance_impl( int ret = 0; CBB request; - STACK_OF(TRUST_TOKEN_PRETOKEN) *pretokens = NULL; + STACK_OF(TRUST_TOKEN_PRETOKEN) *pretokens = nullptr; if (!CBB_init(&request, 0) || !CBB_add_u16(&request, count)) { goto err; } pretokens = ctx->method->blind(&request, count, include_message, msg, msg_len); - if (pretokens == NULL) { + if (pretokens == nullptr) { goto err; } @@ -284,7 +315,7 @@ static int trust_token_client_begin_issuance_impl( sk_TRUST_TOKEN_PRETOKEN_pop_free(ctx->pretokens, TRUST_TOKEN_PRETOKEN_free); ctx->pretokens = pretokens; - pretokens = NULL; + pretokens = nullptr; ret = 1; err: @@ -296,7 +327,8 @@ err: int TRUST_TOKEN_CLIENT_begin_issuance(TRUST_TOKEN_CLIENT *ctx, uint8_t **out, size_t *out_len, size_t count) { return trust_token_client_begin_issuance_impl(ctx, out, out_len, count, - /*include_message=*/0, NULL, 0); + /*include_message=*/0, nullptr, + 0); } int TRUST_TOKEN_CLIENT_begin_issuance_over_message( @@ -316,11 +348,11 @@ STACK_OF(TRUST_TOKEN) *TRUST_TOKEN_CLIENT_finish_issuance( uint32_t key_id; if (!CBS_get_u16(&in, &count) || !CBS_get_u32(&in, &key_id)) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_DECODE_FAILURE); - return NULL; + return nullptr; } size_t key_index = 0; - const struct trust_token_client_key_st *key = NULL; + const struct trust_token_client_key_st *key = nullptr; for (size_t i = 0; i < ctx->num_keys; i++) { if (ctx->keys[i].id == key_id) { key_index = i; @@ -329,30 +361,30 @@ STACK_OF(TRUST_TOKEN) *TRUST_TOKEN_CLIENT_finish_issuance( } } - if (key == NULL) { + if (key == nullptr) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_INVALID_KEY_ID); - return NULL; + return nullptr; } if (count > sk_TRUST_TOKEN_PRETOKEN_num(ctx->pretokens)) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_DECODE_FAILURE); - return NULL; + return nullptr; } STACK_OF(TRUST_TOKEN) *tokens = ctx->method->unblind(&key->key, ctx->pretokens, &in, count, key_id); - if (tokens == NULL) { - return NULL; + if (tokens == nullptr) { + return nullptr; } if (CBS_len(&in) != 0) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_DECODE_FAILURE); sk_TRUST_TOKEN_pop_free(tokens, TRUST_TOKEN_free); - return NULL; + return nullptr; } sk_TRUST_TOKEN_PRETOKEN_pop_free(ctx->pretokens, TRUST_TOKEN_PRETOKEN_free); - ctx->pretokens = NULL; + ctx->pretokens = nullptr; *out_key_index = key_index; return tokens; @@ -389,7 +421,7 @@ int TRUST_TOKEN_CLIENT_finish_redemption(TRUST_TOKEN_CLIENT *ctx, return 0; } - *out_sig = NULL; + *out_sig = nullptr; *out_sig_len = 0; return 1; } @@ -400,16 +432,17 @@ int TRUST_TOKEN_CLIENT_finish_redemption(TRUST_TOKEN_CLIENT *ctx, return 0; } - if (ctx->srr_key == NULL) { + if (ctx->srr_key == nullptr) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_NO_SRR_KEY_CONFIGURED); return 0; } EVP_MD_CTX md_ctx; EVP_MD_CTX_init(&md_ctx); - int sig_ok = EVP_DigestVerifyInit(&md_ctx, NULL, NULL, NULL, ctx->srr_key) && - EVP_DigestVerify(&md_ctx, CBS_data(&sig), CBS_len(&sig), - CBS_data(&srr), CBS_len(&srr)); + int sig_ok = + EVP_DigestVerifyInit(&md_ctx, nullptr, nullptr, nullptr, ctx->srr_key) && + EVP_DigestVerify(&md_ctx, CBS_data(&sig), CBS_len(&sig), CBS_data(&srr), + CBS_len(&srr)); EVP_MD_CTX_cleanup(&md_ctx); if (!sig_ok) { @@ -417,7 +450,7 @@ int TRUST_TOKEN_CLIENT_finish_redemption(TRUST_TOKEN_CLIENT *ctx, return 0; } - uint8_t *srr_buf = NULL, *sig_buf = NULL; + uint8_t *srr_buf = nullptr, *sig_buf = nullptr; size_t srr_len, sig_len; if (!CBS_stow(&srr, &srr_buf, &srr_len) || !CBS_stow(&sig, &sig_buf, &sig_len)) { @@ -438,13 +471,12 @@ TRUST_TOKEN_ISSUER *TRUST_TOKEN_ISSUER_new(const TRUST_TOKEN_METHOD *method, if (max_batchsize > 0xffff) { // The protocol supports only two-byte token counts. OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_OVERFLOW); - return NULL; + return nullptr; } - TRUST_TOKEN_ISSUER *ret = reinterpret_cast( - OPENSSL_zalloc(sizeof(TRUST_TOKEN_ISSUER))); - if (ret == NULL) { - return NULL; + TRUST_TOKEN_ISSUER *ret = New(); + if (ret == nullptr) { + return nullptr; } ret->method = method; ret->max_batchsize = (uint16_t)max_batchsize; @@ -452,17 +484,16 @@ TRUST_TOKEN_ISSUER *TRUST_TOKEN_ISSUER_new(const TRUST_TOKEN_METHOD *method, } void TRUST_TOKEN_ISSUER_free(TRUST_TOKEN_ISSUER *ctx) { - if (ctx == NULL) { + if (ctx == nullptr) { return; } EVP_PKEY_free(ctx->srr_key); - OPENSSL_free(ctx->metadata_key); - OPENSSL_free(ctx); + Delete(ctx); } int TRUST_TOKEN_ISSUER_add_key(TRUST_TOKEN_ISSUER *ctx, const uint8_t *key, size_t key_len) { - if (ctx->num_keys == OPENSSL_ARRAY_SIZE(ctx->keys) || + if (ctx->num_keys == std::size(ctx->keys) || ctx->num_keys >= ctx->method->max_keys) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_TOO_MANY_KEYS); return 0; @@ -491,29 +522,14 @@ int TRUST_TOKEN_ISSUER_set_srr_key(TRUST_TOKEN_ISSUER *ctx, EVP_PKEY *key) { return 1; } -int TRUST_TOKEN_ISSUER_set_metadata_key(TRUST_TOKEN_ISSUER *ctx, - const uint8_t *key, size_t len) { - if (len < 32) { - OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_INVALID_METADATA_KEY); - } - OPENSSL_free(ctx->metadata_key); - ctx->metadata_key_len = 0; - ctx->metadata_key = reinterpret_cast(OPENSSL_memdup(key, len)); - if (ctx->metadata_key == NULL) { - return 0; - } - ctx->metadata_key_len = len; - return 1; -} - -static const struct trust_token_issuer_key_st *trust_token_issuer_get_key( +static const struct bssl::trust_token_issuer_key_st *trust_token_issuer_get_key( const TRUST_TOKEN_ISSUER *ctx, uint32_t key_id) { for (size_t i = 0; i < ctx->num_keys; i++) { if (ctx->keys[i].id == key_id) { return &ctx->keys[i]; } } - return NULL; + return nullptr; } int TRUST_TOKEN_ISSUER_issue(const TRUST_TOKEN_ISSUER *ctx, uint8_t **out, @@ -527,7 +543,7 @@ int TRUST_TOKEN_ISSUER_issue(const TRUST_TOKEN_ISSUER *ctx, uint8_t **out, const struct trust_token_issuer_key_st *key = trust_token_issuer_get_key(ctx, public_metadata); - if (key == NULL || private_metadata > 1 || + if (key == nullptr || private_metadata > 1 || (!ctx->method->has_private_metadata && private_metadata != 0)) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_INVALID_METADATA); return 0; @@ -599,7 +615,7 @@ static int trust_token_issuer_redeem_impl( const struct trust_token_issuer_key_st *key = trust_token_issuer_get_key(ctx, public_metadata); uint8_t nonce[TRUST_TOKEN_NONCE_SIZE]; - if (key == NULL || + if (key == nullptr || !ctx->method->read(&key->key, nonce, &private_metadata, CBS_data(&token_cbs), CBS_len(&token_cbs), include_message, msg, msg_len)) { @@ -615,7 +631,7 @@ static int trust_token_issuer_redeem_impl( return 0; } - uint8_t *client_data_buf = NULL; + uint8_t *client_data_buf = nullptr; size_t client_data_len = 0; TRUST_TOKEN *token; if (!CBS_stow(&client_data, &client_data_buf, &client_data_len)) { @@ -623,7 +639,7 @@ static int trust_token_issuer_redeem_impl( } token = TRUST_TOKEN_new(nonce, TRUST_TOKEN_NONCE_SIZE); - if (token == NULL) { + if (token == nullptr) { goto err; } *out_public = public_metadata; @@ -648,7 +664,7 @@ int TRUST_TOKEN_ISSUER_redeem(const TRUST_TOKEN_ISSUER *ctx, const uint8_t *request, size_t request_len) { return trust_token_issuer_redeem_impl(ctx, out_public, out_private, out_token, out_client_data, out_client_data_len, - request, request_len, 0, NULL, 0); + request, request_len, 0, nullptr, 0); } int TRUST_TOKEN_ISSUER_redeem_over_message( diff --git a/Sources/CNIOBoringSSL/crypto/trust_token/voprf.cc b/Sources/CNIOBoringSSL/crypto/trust_token/voprf.cc index 953c0a86..b3543260 100644 --- a/Sources/CNIOBoringSSL/crypto/trust_token/voprf.cc +++ b/Sources/CNIOBoringSSL/crypto/trust_token/voprf.cc @@ -1,16 +1,16 @@ -/* Copyright 2020 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2020 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 @@ -21,21 +21,24 @@ #include #include #include -#include +#include #include "../ec/internal.h" #include "../fipsmodule/ec/internal.h" +#include "../mem_internal.h" #include "internal.h" +using namespace bssl; + typedef int (*hash_to_group_func_t)(const EC_GROUP *group, EC_JACOBIAN *out, const uint8_t t[TRUST_TOKEN_NONCE_SIZE]); typedef int (*hash_to_scalar_func_t)(const EC_GROUP *group, EC_SCALAR *out, uint8_t *buf, size_t len); typedef struct { - const EC_GROUP *(*group_func)(void); + const EC_GROUP *(*group_func)(); // hash_to_group implements the HashToGroup operation for VOPRFs. It returns // one on success and zero on error. @@ -143,7 +146,7 @@ static int voprf_derive_key_from_secret(const VOPRF_METHOD *method, int ok = 0; CBB cbb; CBB_zero(&cbb); - uint8_t *buf = NULL; + uint8_t *buf = nullptr; size_t len; if (!CBB_init(&cbb, 0) || !CBB_add_bytes(&cbb, kKeygenLabel, sizeof(kKeygenLabel)) || @@ -203,15 +206,14 @@ static STACK_OF(TRUST_TOKEN_PRETOKEN) *voprf_blind(const VOPRF_METHOD *method, const EC_GROUP *group = method->group_func(); STACK_OF(TRUST_TOKEN_PRETOKEN) *pretokens = sk_TRUST_TOKEN_PRETOKEN_new_null(); - if (pretokens == NULL) { + if (pretokens == nullptr) { goto err; } for (size_t i = 0; i < count; i++) { - // Insert |pretoken| into |pretokens| early to simplify error-handling. - TRUST_TOKEN_PRETOKEN *pretoken = reinterpret_cast( - OPENSSL_malloc(sizeof(TRUST_TOKEN_PRETOKEN))); - if (pretoken == NULL || + // Insert `pretoken` into `pretokens` early to simplify error-handling. + TRUST_TOKEN_PRETOKEN *pretoken = New(); + if (pretoken == nullptr || !sk_TRUST_TOKEN_PRETOKEN_push(pretokens, pretoken)) { TRUST_TOKEN_PRETOKEN_free(pretoken); goto err; @@ -257,7 +259,7 @@ static STACK_OF(TRUST_TOKEN_PRETOKEN) *voprf_blind(const VOPRF_METHOD *method, err: sk_TRUST_TOKEN_PRETOKEN_pop_free(pretokens, TRUST_TOKEN_PRETOKEN_free); - return NULL; + return nullptr; } static int hash_to_scalar_dleq(const VOPRF_METHOD *method, EC_SCALAR *out, @@ -270,7 +272,7 @@ static int hash_to_scalar_dleq(const VOPRF_METHOD *method, EC_SCALAR *out, int ok = 0; CBB cbb; CBB_zero(&cbb); - uint8_t *buf = NULL; + uint8_t *buf = nullptr; size_t len; if (!CBB_init(&cbb, 0) || !CBB_add_bytes(&cbb, kDLEQLabel, sizeof(kDLEQLabel)) || @@ -306,7 +308,7 @@ static int hash_to_scalar_challenge(const VOPRF_METHOD *method, EC_SCALAR *out, !cbb_serialize_point(&cbb, group, a2) || !cbb_serialize_point(&cbb, group, a3) || !CBB_add_bytes(&cbb, kChallengeLabel, sizeof(kChallengeLabel) - 1) || - !CBB_finish(&cbb, NULL, &len) || + !CBB_finish(&cbb, nullptr, &len) || !method->hash_to_scalar(group, out, transcript, len)) { return 0; } @@ -326,7 +328,7 @@ static int hash_to_scalar_batch(const VOPRF_METHOD *method, EC_SCALAR *out, int ok = 0; CBB cbb; CBB_zero(&cbb); - uint8_t *buf = NULL; + uint8_t *buf = nullptr; size_t len; if (!CBB_init(&cbb, 0) || !CBB_add_bytes(&cbb, kDLEQBatchLabel, sizeof(kDLEQBatchLabel)) || @@ -405,8 +407,8 @@ static int mul_public_2(const EC_GROUP *group, EC_JACOBIAN *out, const EC_JACOBIAN *p1, const EC_SCALAR *scalar1) { EC_JACOBIAN points[2] = {*p0, *p1}; EC_SCALAR scalars[2] = {*scalar0, *scalar1}; - return ec_point_mul_scalar_public_batch(group, out, /*g_scalar=*/NULL, points, - scalars, 2); + return ec_point_mul_scalar_public_batch(group, out, /*g_scalar=*/nullptr, + points, scalars, 2); } static int dleq_verify(const VOPRF_METHOD *method, CBS *cbs, @@ -529,10 +531,10 @@ static int voprf_sign_tt(const VOPRF_METHOD *method, EC_JACOBIAN BT_batch, Z_batch; if (!ec_point_mul_scalar_public_batch(group, &BT_batch, - /*g_scalar=*/NULL, BTs, es, + /*g_scalar=*/nullptr, BTs, es, num_to_issue) || !ec_point_mul_scalar_public_batch(group, &Z_batch, - /*g_scalar=*/NULL, Zs, es, + /*g_scalar=*/nullptr, Zs, es, num_to_issue)) { goto err; } @@ -555,9 +557,9 @@ static int voprf_sign_tt(const VOPRF_METHOD *method, } err: - OPENSSL_free(BTs); - OPENSSL_free(Zs); - OPENSSL_free(es); + Delete(BTs); + Delete(Zs); + Delete(es); CBB_cleanup(&batch_cbb); return ret; } @@ -569,7 +571,7 @@ static STACK_OF(TRUST_TOKEN) *voprf_unblind_tt( const EC_GROUP *group = method->group_func(); if (count > sk_TRUST_TOKEN_PRETOKEN_num(pretokens)) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_DECODE_FAILURE); - return NULL; + return nullptr; } int ok = 0; @@ -582,7 +584,7 @@ static STACK_OF(TRUST_TOKEN) *voprf_unblind_tt( reinterpret_cast(OPENSSL_calloc(count, sizeof(EC_SCALAR))); CBB batch_cbb; CBB_zero(&batch_cbb); - if (ret == NULL || BTs == NULL || Zs == NULL || es == NULL || + if (ret == nullptr || BTs == nullptr || Zs == nullptr || es == nullptr || !CBB_init(&batch_cbb, 0) || !cbb_add_point(&batch_cbb, group, &key->pubs)) { goto err; @@ -615,7 +617,7 @@ static STACK_OF(TRUST_TOKEN) *voprf_unblind_tt( goto err; } - // Serialize the token. Include |key_id| to avoid an extra copy in the layer + // Serialize the token. Include `key_id` to avoid an extra copy in the layer // above. CBB token_cbb; size_t point_len = ec_point_byte_len(group, POINT_CONVERSION_UNCOMPRESSED); @@ -631,7 +633,7 @@ static STACK_OF(TRUST_TOKEN) *voprf_unblind_tt( TRUST_TOKEN *token = TRUST_TOKEN_new(CBB_data(&token_cbb), CBB_len(&token_cbb)); CBB_cleanup(&token_cbb); - if (token == NULL || !sk_TRUST_TOKEN_push(ret, token)) { + if (token == nullptr || !sk_TRUST_TOKEN_push(ret, token)) { TRUST_TOKEN_free(token); goto err; } @@ -648,9 +650,9 @@ static STACK_OF(TRUST_TOKEN) *voprf_unblind_tt( EC_JACOBIAN BT_batch, Z_batch; if (!ec_point_mul_scalar_public_batch(group, &BT_batch, - /*g_scalar=*/NULL, BTs, es, count) || + /*g_scalar=*/nullptr, BTs, es, count) || !ec_point_mul_scalar_public_batch(group, &Z_batch, - /*g_scalar=*/NULL, Zs, es, count)) { + /*g_scalar=*/nullptr, Zs, es, count)) { goto err; } @@ -664,13 +666,13 @@ static STACK_OF(TRUST_TOKEN) *voprf_unblind_tt( ok = 1; err: - OPENSSL_free(BTs); - OPENSSL_free(Zs); - OPENSSL_free(es); + Delete(BTs); + Delete(Zs); + Delete(es); CBB_cleanup(&batch_cbb); if (!ok) { sk_TRUST_TOKEN_pop_free(ret, TRUST_TOKEN_free); - ret = NULL; + ret = nullptr; } return ret; } @@ -729,7 +731,7 @@ static int compute_composite_element(const VOPRF_METHOD *method, !CBB_add_u16(&cbb, index) || !cbb_serialize_point(&cbb, group, C) || !cbb_serialize_point(&cbb, group, D) || !CBB_add_bytes(&cbb, kCompositeLabel, sizeof(kCompositeLabel) - 1) || - !CBB_finish(&cbb, NULL, &len) || + !CBB_finish(&cbb, nullptr, &len) || !method->hash_to_scalar(group, di, transcript, len)) { return 0; } @@ -898,7 +900,7 @@ static int voprf_sign_impl(const VOPRF_METHOD *method, EC_JACOBIAN M, Z; if (!ec_point_mul_scalar_public_batch(group, &M, - /*g_scalar=*/NULL, BTs, dis, + /*g_scalar=*/nullptr, BTs, dis, num_to_issue) || !ec_point_mul_scalar(group, &Z, &M, &key->xs)) { goto err; @@ -922,9 +924,9 @@ static int voprf_sign_impl(const VOPRF_METHOD *method, } err: - OPENSSL_free(BTs); - OPENSSL_free(Zs); - OPENSSL_free(dis); + Delete(BTs); + Delete(Zs); + Delete(dis); return ret; } @@ -961,7 +963,7 @@ static STACK_OF(TRUST_TOKEN) *voprf_unblind( const EC_GROUP *group = method->group_func(); if (count > sk_TRUST_TOKEN_PRETOKEN_num(pretokens)) { OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_DECODE_FAILURE); - return NULL; + return nullptr; } int ok = 0; @@ -972,7 +974,7 @@ static STACK_OF(TRUST_TOKEN) *voprf_unblind( OPENSSL_calloc(count, sizeof(EC_JACOBIAN))); EC_SCALAR *dis = reinterpret_cast(OPENSSL_calloc(count, sizeof(EC_SCALAR))); - if (ret == NULL || !BTs || !Zs || !dis) { + if (ret == nullptr || !BTs || !Zs || !dis) { goto err; } @@ -1007,7 +1009,7 @@ static STACK_OF(TRUST_TOKEN) *voprf_unblind( goto err; } - // Serialize the token. Include |key_id| to avoid an extra copy in the layer + // Serialize the token. Include `key_id` to avoid an extra copy in the layer // above. CBB token_cbb; size_t point_len = ec_point_byte_len(group, POINT_CONVERSION_UNCOMPRESSED); @@ -1023,7 +1025,7 @@ static STACK_OF(TRUST_TOKEN) *voprf_unblind( TRUST_TOKEN *token = TRUST_TOKEN_new(CBB_data(&token_cbb), CBB_len(&token_cbb)); CBB_cleanup(&token_cbb); - if (token == NULL || !sk_TRUST_TOKEN_push(ret, token)) { + if (token == nullptr || !sk_TRUST_TOKEN_push(ret, token)) { TRUST_TOKEN_free(token); goto err; } @@ -1031,9 +1033,10 @@ static STACK_OF(TRUST_TOKEN) *voprf_unblind( EC_JACOBIAN M, Z; if (!ec_point_mul_scalar_public_batch(group, &M, - /*g_scalar=*/NULL, BTs, dis, count) || + /*g_scalar=*/nullptr, BTs, dis, + count) || !ec_point_mul_scalar_public_batch(group, &Z, - /*g_scalar=*/NULL, Zs, dis, count)) { + /*g_scalar=*/nullptr, Zs, dis, count)) { goto err; } @@ -1046,12 +1049,12 @@ static STACK_OF(TRUST_TOKEN) *voprf_unblind( ok = 1; err: - OPENSSL_free(BTs); - OPENSSL_free(Zs); - OPENSSL_free(dis); + Delete(BTs); + Delete(Zs); + Delete(dis); if (!ok) { sk_TRUST_TOKEN_pop_free(ret, TRUST_TOKEN_free); - ret = NULL; + ret = nullptr; } return ret; } @@ -1118,38 +1121,38 @@ static int voprf_exp2_hash_to_scalar(const EC_GROUP *group, EC_SCALAR *out, static VOPRF_METHOD voprf_exp2_method = { EC_group_p384, voprf_exp2_hash_to_group, voprf_exp2_hash_to_scalar}; -int voprf_exp2_generate_key(CBB *out_private, CBB *out_public) { +int bssl::voprf_exp2_generate_key(CBB *out_private, CBB *out_public) { return voprf_generate_key(&voprf_exp2_method, out_private, out_public); } -int voprf_exp2_derive_key_from_secret(CBB *out_private, CBB *out_public, - const uint8_t *secret, - size_t secret_len) { +int bssl::voprf_exp2_derive_key_from_secret(CBB *out_private, CBB *out_public, + const uint8_t *secret, + size_t secret_len) { return voprf_derive_key_from_secret(&voprf_exp2_method, out_private, out_public, secret, secret_len); } -int voprf_exp2_client_key_from_bytes(TRUST_TOKEN_CLIENT_KEY *key, - const uint8_t *in, size_t len) { +int bssl::voprf_exp2_client_key_from_bytes(TRUST_TOKEN_CLIENT_KEY *key, + const uint8_t *in, size_t len) { return voprf_client_key_from_bytes(&voprf_exp2_method, key, in, len); } -int voprf_exp2_issuer_key_from_bytes(TRUST_TOKEN_ISSUER_KEY *key, - const uint8_t *in, size_t len) { +int bssl::voprf_exp2_issuer_key_from_bytes(TRUST_TOKEN_ISSUER_KEY *key, + const uint8_t *in, size_t len) { return voprf_issuer_key_from_bytes(&voprf_exp2_method, key, in, len); } -STACK_OF(TRUST_TOKEN_PRETOKEN) *voprf_exp2_blind(CBB *cbb, size_t count, - int include_message, - const uint8_t *msg, - size_t msg_len) { +STACK_OF(TRUST_TOKEN_PRETOKEN) *bssl::voprf_exp2_blind(CBB *cbb, size_t count, + int include_message, + const uint8_t *msg, + size_t msg_len) { return voprf_blind(&voprf_exp2_method, cbb, count, include_message, msg, msg_len); } -int voprf_exp2_sign(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs, - size_t num_requested, size_t num_to_issue, - uint8_t private_metadata) { +int bssl::voprf_exp2_sign(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs, + size_t num_requested, size_t num_to_issue, + uint8_t private_metadata) { if (private_metadata != 0) { return 0; } @@ -1157,7 +1160,7 @@ int voprf_exp2_sign(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs, num_to_issue); } -STACK_OF(TRUST_TOKEN) *voprf_exp2_unblind( +STACK_OF(TRUST_TOKEN) *bssl::voprf_exp2_unblind( const TRUST_TOKEN_CLIENT_KEY *key, const STACK_OF(TRUST_TOKEN_PRETOKEN) *pretokens, CBS *cbs, size_t count, uint32_t key_id) { @@ -1165,11 +1168,11 @@ STACK_OF(TRUST_TOKEN) *voprf_exp2_unblind( key_id); } -int voprf_exp2_read(const TRUST_TOKEN_ISSUER_KEY *key, - uint8_t out_nonce[TRUST_TOKEN_NONCE_SIZE], - uint8_t *out_private_metadata, const uint8_t *token, - size_t token_len, int include_message, const uint8_t *msg, - size_t msg_len) { +int bssl::voprf_exp2_read(const TRUST_TOKEN_ISSUER_KEY *key, + uint8_t out_nonce[TRUST_TOKEN_NONCE_SIZE], + uint8_t *out_private_metadata, const uint8_t *token, + size_t token_len, int include_message, + const uint8_t *msg, size_t msg_len) { return voprf_read(&voprf_exp2_method, key, out_nonce, token, token_len, include_message, msg, msg_len); } @@ -1194,38 +1197,38 @@ static int voprf_pst1_hash_to_scalar(const EC_GROUP *group, EC_SCALAR *out, static VOPRF_METHOD voprf_pst1_method = { EC_group_p384, voprf_pst1_hash_to_group, voprf_pst1_hash_to_scalar}; -int voprf_pst1_generate_key(CBB *out_private, CBB *out_public) { +int bssl::voprf_pst1_generate_key(CBB *out_private, CBB *out_public) { return voprf_generate_key(&voprf_pst1_method, out_private, out_public); } -int voprf_pst1_derive_key_from_secret(CBB *out_private, CBB *out_public, - const uint8_t *secret, - size_t secret_len) { +int bssl::voprf_pst1_derive_key_from_secret(CBB *out_private, CBB *out_public, + const uint8_t *secret, + size_t secret_len) { return voprf_derive_key_from_secret(&voprf_pst1_method, out_private, out_public, secret, secret_len); } -int voprf_pst1_client_key_from_bytes(TRUST_TOKEN_CLIENT_KEY *key, - const uint8_t *in, size_t len) { +int bssl::voprf_pst1_client_key_from_bytes(TRUST_TOKEN_CLIENT_KEY *key, + const uint8_t *in, size_t len) { return voprf_client_key_from_bytes(&voprf_pst1_method, key, in, len); } -int voprf_pst1_issuer_key_from_bytes(TRUST_TOKEN_ISSUER_KEY *key, - const uint8_t *in, size_t len) { +int bssl::voprf_pst1_issuer_key_from_bytes(TRUST_TOKEN_ISSUER_KEY *key, + const uint8_t *in, size_t len) { return voprf_issuer_key_from_bytes(&voprf_pst1_method, key, in, len); } -STACK_OF(TRUST_TOKEN_PRETOKEN) *voprf_pst1_blind(CBB *cbb, size_t count, - int include_message, - const uint8_t *msg, - size_t msg_len) { +STACK_OF(TRUST_TOKEN_PRETOKEN) *bssl::voprf_pst1_blind(CBB *cbb, size_t count, + int include_message, + const uint8_t *msg, + size_t msg_len) { return voprf_blind(&voprf_pst1_method, cbb, count, include_message, msg, msg_len); } -int voprf_pst1_sign(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs, - size_t num_requested, size_t num_to_issue, - uint8_t private_metadata) { +int bssl::voprf_pst1_sign(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs, + size_t num_requested, size_t num_to_issue, + uint8_t private_metadata) { if (private_metadata != 0) { return 0; } @@ -1234,7 +1237,7 @@ int voprf_pst1_sign(const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs, } -int voprf_pst1_sign_with_proof_scalar_for_testing( +int bssl::voprf_pst1_sign_with_proof_scalar_for_testing( const TRUST_TOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs, size_t num_requested, size_t num_to_issue, uint8_t private_metadata, const uint8_t *proof_scalar_buf, size_t proof_scalar_len) { @@ -1246,18 +1249,18 @@ int voprf_pst1_sign_with_proof_scalar_for_testing( proof_scalar_buf, proof_scalar_len); } -STACK_OF(TRUST_TOKEN) *voprf_pst1_unblind( +STACK_OF(TRUST_TOKEN) *bssl::voprf_pst1_unblind( const TRUST_TOKEN_CLIENT_KEY *key, const STACK_OF(TRUST_TOKEN_PRETOKEN) *pretokens, CBS *cbs, size_t count, uint32_t key_id) { return voprf_unblind(&voprf_pst1_method, key, pretokens, cbs, count, key_id); } -int voprf_pst1_read(const TRUST_TOKEN_ISSUER_KEY *key, - uint8_t out_nonce[TRUST_TOKEN_NONCE_SIZE], - uint8_t *out_private_metadata, const uint8_t *token, - size_t token_len, int include_message, const uint8_t *msg, - size_t msg_len) { +int bssl::voprf_pst1_read(const TRUST_TOKEN_ISSUER_KEY *key, + uint8_t out_nonce[TRUST_TOKEN_NONCE_SIZE], + uint8_t *out_private_metadata, const uint8_t *token, + size_t token_len, int include_message, + const uint8_t *msg, size_t msg_len) { return voprf_read(&voprf_pst1_method, key, out_nonce, token, token_len, include_message, msg, msg_len); } diff --git a/Sources/CNIOBoringSSL/crypto/x509/a_digest.cc b/Sources/CNIOBoringSSL/crypto/x509/a_digest.cc index 1748375b..f7d297e2 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/a_digest.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/a_digest.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -19,14 +24,14 @@ int ASN1_digest(i2d_of_void *i2d, const EVP_MD *type, char *data, int i, ret; unsigned char *str, *p; - i = i2d(data, NULL); - if ((str = (unsigned char *)OPENSSL_malloc(i)) == NULL) { + i = i2d(data, nullptr); + if ((str = (unsigned char *)OPENSSL_malloc(i)) == nullptr) { return 0; } p = str; i2d(data, &p); - ret = EVP_Digest(str, i, md, len, type, NULL); + ret = EVP_Digest(str, i, md, len, type, nullptr); OPENSSL_free(str); return ret; } @@ -34,14 +39,14 @@ int ASN1_digest(i2d_of_void *i2d, const EVP_MD *type, char *data, int ASN1_item_digest(const ASN1_ITEM *it, const EVP_MD *type, void *asn, unsigned char *md, unsigned int *len) { int i, ret; - unsigned char *str = NULL; + unsigned char *str = nullptr; i = ASN1_item_i2d(reinterpret_cast(asn), &str, it); if (!str) { return 0; } - ret = EVP_Digest(str, i, md, len, type, NULL); + ret = EVP_Digest(str, i, md, len, type, nullptr); OPENSSL_free(str); return ret; } diff --git a/Sources/CNIOBoringSSL/crypto/x509/a_sign.cc b/Sources/CNIOBoringSSL/crypto/x509/a_sign.cc index 94afb44e..ff3a20f3 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/a_sign.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/a_sign.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -13,12 +18,18 @@ #include #include #include +#include #include #include +#include "../internal.h" +#include "../mem_internal.h" #include "internal.h" + +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, const EVP_MD *type) { @@ -26,67 +37,64 @@ int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2, OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE); return 0; } - EVP_MD_CTX ctx; - EVP_MD_CTX_init(&ctx); - if (!EVP_DigestSignInit(&ctx, NULL, type, NULL, pkey)) { - EVP_MD_CTX_cleanup(&ctx); + ScopedEVP_MD_CTX ctx; + if (!EVP_DigestSignInit(ctx.get(), nullptr, type, nullptr, pkey)) { return 0; } - return ASN1_item_sign_ctx(it, algor1, algor2, signature, asn, &ctx); + return ASN1_item_sign_ctx(it, algor1, algor2, signature, asn, ctx.get()); } int ASN1_item_sign_ctx(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2, ASN1_BIT_STRING *signature, void *asn, EVP_MD_CTX *ctx) { - int ret = 0; - uint8_t *in = NULL, *out = NULL; + // Historically, this function called `EVP_MD_CTX_cleanup` on return. Some + // callers rely on this to avoid memory leaks. + Cleanup cleanup = [&] { EVP_MD_CTX_cleanup(ctx); }; - { - if (signature->type != V_ASN1_BIT_STRING) { - OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE); - goto err; - } - - // Write out the requested copies of the AlgorithmIdentifier. - if (algor1 && !x509_digest_sign_algorithm(ctx, algor1)) { - goto err; - } - if (algor2 && !x509_digest_sign_algorithm(ctx, algor2)) { - goto err; - } - - int in_len = ASN1_item_i2d(reinterpret_cast(asn), &in, it); - if (in_len < 0) { - goto err; - } - - EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx->pctx); - size_t out_len = EVP_PKEY_size(pkey); - if (out_len > INT_MAX) { - OPENSSL_PUT_ERROR(X509, ERR_R_OVERFLOW); - goto err; - } - - out = reinterpret_cast(OPENSSL_malloc(out_len)); - if (out == NULL) { - goto err; - } - - if (!EVP_DigestSign(ctx, out, &out_len, in, in_len)) { - OPENSSL_PUT_ERROR(X509, ERR_R_EVP_LIB); - goto err; - } - - ASN1_STRING_set0(signature, out, (int)out_len); - out = NULL; - signature->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); - signature->flags |= ASN1_STRING_FLAG_BITS_LEFT; - ret = (int)out_len; + // Write out the requested copies of the AlgorithmIdentifier. This may modify + // `asn`, so we must do it first. + if ((algor1 != nullptr && !x509_digest_sign_algorithm(ctx, algor1)) || + (algor2 != nullptr && !x509_digest_sign_algorithm(ctx, algor2))) { + return 0; } -err: - EVP_MD_CTX_cleanup(ctx); - OPENSSL_free(in); - OPENSSL_free(out); - return ret; + uint8_t *in = nullptr; + int in_len = ASN1_item_i2d(reinterpret_cast(asn), &in, it); + if (in_len < 0) { + return 0; + } + UniquePtr free_in(in); + + return x509_sign_to_bit_string(ctx, signature, Span(in, in_len)); +} + +int bssl::x509_sign_to_bit_string(EVP_MD_CTX *ctx, ASN1_BIT_STRING *out, + Span in) { + if (out->type != V_ASN1_BIT_STRING) { + OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE); + return 0; + } + + EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx->pctx); + size_t sig_len = EVP_PKEY_size(pkey); + if (sig_len > INT_MAX) { + // Ensure the signature will fit in `out`. + OPENSSL_PUT_ERROR(X509, ERR_R_OVERFLOW); + return 0; + } + Array sig; + if (!sig.Init(sig_len)) { + return 0; + } + + if (!EVP_DigestSign(ctx, sig.data(), &sig_len, in.data(), in.size())) { + OPENSSL_PUT_ERROR(X509, ERR_R_EVP_LIB); + return 0; + } + sig.Shrink(sig_len); + + uint8_t *sig_data; + sig.Release(&sig_data, &sig_len); + ASN1_STRING_set0(out, sig_data, static_cast(sig_len)); + return static_cast(sig_len); } diff --git a/Sources/CNIOBoringSSL/crypto/x509/a_verify.cc b/Sources/CNIOBoringSSL/crypto/x509/a_verify.cc index e1d6a163..37929602 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/a_verify.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/a_verify.cc @@ -1,69 +1,77 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "internal.h" -int ASN1_item_verify(const ASN1_ITEM *it, const X509_ALGOR *a, - const ASN1_BIT_STRING *signature, void *asn, - EVP_PKEY *pkey) { + +using namespace bssl; + +int bssl::x509_verify_signature(const X509_ALGOR *sigalg, + const ASN1_BIT_STRING *signature, + Span in, 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); + return 0; + } + Span signature_bytes(ASN1_STRING_get0_data(signature), + ASN1_STRING_length(signature)); + return x509_verify_signature_bytes(sigalg, signature_bytes, in, pkey); +} + +int bssl::x509_verify_signature_bytes(const X509_ALGOR *sigalg, + Span signature, + Span in, EVP_PKEY *pkey) { if (!pkey) { OPENSSL_PUT_ERROR(X509, ERR_R_PASSED_NULL_PARAMETER); return 0; } - size_t sig_len; - if (signature->type == V_ASN1_BIT_STRING) { - if (!ASN1_BIT_STRING_num_bytes(signature, &sig_len)) { - OPENSSL_PUT_ERROR(X509, X509_R_INVALID_BIT_STRING_BITS_LEFT); - return 0; - } - } else { - sig_len = (size_t)ASN1_STRING_length(signature); + ScopedEVP_MD_CTX ctx; + if (!x509_digest_verify_init(ctx.get(), sigalg, pkey)) { + return 0; } - - EVP_MD_CTX ctx; - uint8_t *buf_in = NULL; - int ret = 0, inl = 0; - EVP_MD_CTX_init(&ctx); - - if (!x509_digest_verify_init(&ctx, a, pkey)) { - goto err; - } - - inl = ASN1_item_i2d(reinterpret_cast(asn), &buf_in, it); - - if (buf_in == NULL) { - goto err; - } - - if (!EVP_DigestVerify(&ctx, ASN1_STRING_get0_data(signature), sig_len, buf_in, - inl)) { + if (!EVP_DigestVerify(ctx.get(), signature.data(), signature.size(), + in.data(), in.size())) { OPENSSL_PUT_ERROR(X509, ERR_R_EVP_LIB); - goto err; + return 0; } - - ret = 1; - -err: - OPENSSL_free(buf_in); - EVP_MD_CTX_cleanup(&ctx); - return ret; + return 1; +} + +int ASN1_item_verify(const ASN1_ITEM *it, const X509_ALGOR *sigalg, + const ASN1_BIT_STRING *signature, void *asn, + EVP_PKEY *pkey) { + uint8_t *in = nullptr; + int in_len = ASN1_item_i2d(reinterpret_cast(asn), &in, it); + if (in_len < 0) { + return 0; + } + UniquePtr free_in(in); + return x509_verify_signature(sigalg, signature, Span(in, in_len), pkey); } diff --git a/Sources/CNIOBoringSSL/crypto/x509/algorithm.cc b/Sources/CNIOBoringSSL/crypto/x509/algorithm.cc index 728a11a7..2387dc45 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/algorithm.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/algorithm.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,6 +22,14 @@ #include "internal.h" + +using namespace bssl; + +// TODO(crbug.com/42290422): Rewrite this logic to recognize signature +// algorithms without pulling in the OID table. We can enumerate every supported +// signature algorithm into a small enum and convert them to/from `EVP_PKEY_CTX` +// and `X509_ALGOR`. + // Restrict the digests that are allowed in X509 certificates static int x509_digest_nid_ok(const int digest_nid) { switch (digest_nid) { @@ -27,14 +40,15 @@ static int x509_digest_nid_ok(const int digest_nid) { return 1; } -int x509_digest_sign_algorithm(EVP_MD_CTX *ctx, X509_ALGOR *algor) { +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 == NULL) { + if (pkey == nullptr) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_CONTEXT_NOT_INITIALISED); return 0; } - if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) { + if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA || + EVP_PKEY_id(pkey) == EVP_PKEY_RSA_PSS) { int pad_mode; if (!EVP_PKEY_CTX_get_rsa_padding(ctx->pctx, &pad_mode)) { return 0; @@ -45,14 +59,30 @@ int x509_digest_sign_algorithm(EVP_MD_CTX *ctx, X509_ALGOR *algor) { } } - if (EVP_PKEY_id(pkey) == EVP_PKEY_ED25519) { - return X509_ALGOR_set0(algor, OBJ_nid2obj(NID_ED25519), V_ASN1_UNDEF, NULL); + // Check for signing algorithms with an internal hash. + ASN1_OBJECT *algo_obj = nullptr; + switch (EVP_PKEY_id(pkey)) { + case EVP_PKEY_ED25519: + algo_obj = OBJ_nid2obj(NID_ED25519); + break; + case EVP_PKEY_ML_DSA_44: + algo_obj = OBJ_nid2obj(NID_ML_DSA_44); + break; + case EVP_PKEY_ML_DSA_65: + algo_obj = OBJ_nid2obj(NID_ML_DSA_65); + break; + case EVP_PKEY_ML_DSA_87: + algo_obj = OBJ_nid2obj(NID_ML_DSA_87); + break; + } + if (algo_obj != nullptr) { + return X509_ALGOR_set0(algor, algo_obj, V_ASN1_UNDEF, nullptr); } // Default behavior: look up the OID for the algorithm/hash pair and encode // that. const EVP_MD *digest = EVP_MD_CTX_get0_md(ctx); - if (digest == NULL) { + if (digest == nullptr) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_CONTEXT_NOT_INITIALISED); return 0; } @@ -69,11 +99,11 @@ int x509_digest_sign_algorithm(EVP_MD_CTX *ctx, X509_ALGOR *algor) { // it. int paramtype = (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) ? V_ASN1_NULL : V_ASN1_UNDEF; - return X509_ALGOR_set0(algor, OBJ_nid2obj(sign_nid), paramtype, NULL); + return X509_ALGOR_set0(algor, OBJ_nid2obj(sign_nid), paramtype, nullptr); } -int x509_digest_verify_init(EVP_MD_CTX *ctx, const X509_ALGOR *sigalg, - EVP_PKEY *pkey) { +int bssl::x509_digest_verify_init(EVP_MD_CTX *ctx, const X509_ALGOR *sigalg, + 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; @@ -83,7 +113,10 @@ int x509_digest_verify_init(EVP_MD_CTX *ctx, const X509_ALGOR *sigalg, } // Check the public key OID matches the public key type. - if (pkey_nid != EVP_PKEY_id(pkey)) { + const bool pkey_matches = + pkey_nid == EVP_PKEY_id(pkey) || + (sigalg_nid == NID_rsassaPss && EVP_PKEY_id(pkey) == EVP_PKEY_RSA_PSS); + if (!pkey_matches) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_PUBLIC_KEY_TYPE); return 0; } @@ -99,12 +132,15 @@ int x509_digest_verify_init(EVP_MD_CTX *ctx, const X509_ALGOR *sigalg, if (sigalg_nid == NID_rsassaPss) { return x509_rsa_pss_to_ctx(ctx, sigalg, pkey); } - if (sigalg_nid == NID_ED25519) { - if (sigalg->parameter != NULL) { + if (sigalg_nid == NID_ED25519 || sigalg_nid == NID_ML_DSA_44 || + sigalg_nid == NID_ML_DSA_65 || sigalg_nid == NID_ML_DSA_87) { + // These algorithms require that parameters be absent (Ed25519: RFC 8410 + // section 3, ML-DSA: RFC 9881 section 2). + if (sigalg->parameter != nullptr) { OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PARAMETER); return 0; } - return EVP_DigestVerifyInit(ctx, NULL, NULL, NULL, pkey); + return EVP_DigestVerifyInit(ctx, nullptr, nullptr, nullptr, pkey); } OPENSSL_PUT_ERROR(ASN1, ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); return 0; @@ -115,17 +151,17 @@ int x509_digest_verify_init(EVP_MD_CTX *ctx, const X509_ALGOR *sigalg, // // TODO(davidben): Chromium's verifier allows both forms for RSA, but enforces // ECDSA more strictly. Align with Chromium and add a flag for b/167375496. - if (sigalg->parameter != NULL && sigalg->parameter->type != V_ASN1_NULL) { + if (sigalg->parameter != nullptr && sigalg->parameter->type != V_ASN1_NULL) { OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PARAMETER); return 0; } // Otherwise, initialize with the digest from the OID. const EVP_MD *digest = EVP_get_digestbynid(digest_nid); - if (digest == NULL) { + if (digest == nullptr) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); return 0; } - return EVP_DigestVerifyInit(ctx, NULL, digest, NULL, pkey); + return EVP_DigestVerifyInit(ctx, nullptr, digest, nullptr, pkey); } diff --git a/Sources/CNIOBoringSSL/crypto/x509/asn1_gen.cc b/Sources/CNIOBoringSSL/crypto/x509/asn1_gen.cc index b09b4472..5058e488 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/asn1_gen.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/asn1_gen.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -24,6 +29,8 @@ #include "internal.h" +using namespace bssl; + // Although this file is in crypto/x509 for layering purposes, it emits // errors from the ASN.1 module for OpenSSL compatibility. @@ -41,39 +48,35 @@ #define ASN1_GEN_FORMAT_HEX 3 #define ASN1_GEN_FORMAT_BITLIST 4 -// 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. +// 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| +// 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 *ASN1_generate_v3(const char *str, const X509V3_CTX *cnf) { - CBB cbb; - if (!CBB_init(&cbb, 0) || // - !generate_v3(&cbb, str, cnf, /*tag=*/0, ASN1_GEN_FORMAT_ASCII, +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)) { - CBB_cleanup(&cbb); - return NULL; + 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) > ASN1_GEN_MAX_OUTPUT) { + // `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); - CBB_cleanup(&cbb); - return NULL; + return nullptr; } - const uint8_t *der = CBB_data(&cbb); - ASN1_TYPE *ret = d2i_ASN1_TYPE(NULL, &der, CBB_len(&cbb)); - CBB_cleanup(&cbb); - return ret; + const uint8_t *der = CBB_data(cbb.get()); + return d2i_ASN1_TYPE(nullptr, &der, CBB_len(cbb.get())); } static int cbs_str_equal(const CBS *cbs, const char *str) { @@ -81,7 +84,7 @@ static int cbs_str_equal(const CBS *cbs, const char *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 +// 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 copy = *cbs; @@ -148,7 +151,7 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, } // Process modifiers. This function uses a mix of NUL-terminated strings and - // |CBS|. Several functions only work with NUL-terminated strings, so we need + // `CBS`. Several functions only work with NUL-terminated strings, so we need // to keep track of when a slice spans the whole buffer. for (;;) { // Skip whitespace. @@ -158,7 +161,7 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, // Modifiers end at commas. const char *comma = strchr(str, ','); - if (comma == NULL) { + if (comma == nullptr) { break; } @@ -186,7 +189,7 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, CBS_skip(&modifier, 1); // Skip the colon. } else { name = modifier; - CBS_init(&modifier, NULL, 0); + CBS_init(&modifier, nullptr, 0); } if (cbs_str_equal(&name, "FORMAT") || cbs_str_equal(&name, "FORM")) { @@ -238,7 +241,7 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, tag = tag == 0 ? CBS_ASN1_SET : (tag | CBS_ASN1_CONSTRUCTED); return generate_wrapped(cbb, str, cnf, tag, /*padding=*/0, format, depth); } else { - // If this was not a recognized modifier, rewind |str| to before splitting + // If this was not a recognized modifier, rewind `str` to before splitting // on the comma. The type itself consumes all remaining input. str = str_old; break; @@ -250,7 +253,7 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, const char *colon = strchr(str, ':'); CBS name; const char *value; - int has_value = colon != NULL; + int has_value = colon != nullptr; if (has_value) { CBS_init(&name, (const uint8_t *)str, colon - str); value = colon + 1; @@ -298,9 +301,9 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, {"SET", CBS_ASN1_SET}, }; CBS_ASN1_TAG type = 0; - for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kTypes); i++) { - if (cbs_str_equal(&name, kTypes[i].name)) { - type = kTypes[i].type; + for (const auto &t : kTypes) { + if (cbs_str_equal(&name, t.name)) { + type = t.type; break; } } @@ -343,12 +346,12 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, OPENSSL_PUT_ERROR(ASN1, ASN1_R_INTEGER_NOT_ASCII_FORMAT); return 0; } - ASN1_INTEGER *obj = s2i_ASN1_INTEGER(NULL, value); - if (obj == NULL) { + ASN1_INTEGER *obj = s2i_ASN1_INTEGER(nullptr, value); + if (obj == nullptr) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_INTEGER); return 0; } - int len = i2c_ASN1_INTEGER(obj, NULL); + int len = i2c_ASN1_INTEGER(obj, nullptr); uint8_t *out; int ok = len > 0 && // CBB_add_space(&child, &out, len) && @@ -363,7 +366,7 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, return 0; } ASN1_OBJECT *obj = OBJ_txt2obj(value, /*dont_search_names=*/0); - if (obj == NULL || obj->length == 0) { + if (obj == nullptr || obj->length == 0) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OBJECT); return 0; } @@ -381,9 +384,9 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, CBS value_cbs; CBS_init(&value_cbs, (const uint8_t *)value, strlen(value)); int ok = type == CBS_ASN1_UTCTIME - ? CBS_parse_utc_time(&value_cbs, NULL, + ? CBS_parse_utc_time(&value_cbs, nullptr, /*allow_timezone_offset=*/0) - : CBS_parse_generalized_time(&value_cbs, NULL, + : CBS_parse_generalized_time(&value_cbs, nullptr, /*allow_timezone_offset=*/0); if (!ok) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_TIME_VALUE); @@ -409,11 +412,11 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, return 0; } - // |maxsize| is measured in code points, rather than bytes, but pass it in + // `maxsize` is measured in code points, rather than bytes, but pass it in // as a loose cap so fuzzers can exit from excessively long inputs - // earlier. This limit is not load-bearing because |ASN1_mbstring_ncopy|'s + // earlier. This limit is not load-bearing because `ASN1_mbstring_ncopy`'s // output is already linear in the input. - ASN1_STRING *obj = NULL; + ASN1_STRING *obj = nullptr; if (ASN1_mbstring_ncopy(&obj, (const uint8_t *)value, -1, encoding, ASN1_tag2bit(type), /*minsize=*/0, /*maxsize=*/ASN1_GEN_MAX_OUTPUT) <= 0) { @@ -427,7 +430,7 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, case CBS_ASN1_BITSTRING: if (format == ASN1_GEN_FORMAT_BITLIST) { ASN1_BIT_STRING *obj = ASN1_BIT_STRING_new(); - if (obj == NULL) { + if (obj == nullptr) { return 0; } if (!CONF_parse_list(value, ',', 1, bitstr_cb, obj)) { @@ -435,7 +438,7 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, ASN1_BIT_STRING_free(obj); return 0; } - int len = i2c_ASN1_BIT_STRING(obj, NULL); + int len = i2c_ASN1_BIT_STRING(obj, nullptr); uint8_t *out; int ok = len > 0 && // CBB_add_space(&child, &out, len) && @@ -460,7 +463,7 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, if (format == ASN1_GEN_FORMAT_HEX) { size_t len; uint8_t *data = x509v3_hex_to_bytes(value, &len); - if (data == NULL) { + if (data == nullptr) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_HEX); return 0; } @@ -475,12 +478,12 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, case CBS_ASN1_SEQUENCE: case CBS_ASN1_SET: if (has_value) { - if (cnf == NULL) { + if (cnf == nullptr) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_SEQUENCE_OR_SET_NEEDS_CONFIG); return 0; } const STACK_OF(CONF_VALUE) *section = X509V3_get_section(cnf, value); - if (section == NULL) { + if (section == nullptr) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_SEQUENCE_OR_SET_NEEDS_CONFIG); return 0; } @@ -490,8 +493,8 @@ static int generate_v3(CBB *cbb, const char *str, const X509V3_CTX *cnf, ASN1_GEN_FORMAT_ASCII, depth + 1)) { return 0; } - // This recursive call, by referencing |section|, is the one place - // where |generate_v3|'s output can be super-linear in the input. + // This recursive call, by referencing `section`, is the one place + // where `generate_v3`'s output can be super-linear in the input. // Check bounds here. if (CBB_len(&child) > ASN1_GEN_MAX_OUTPUT) { OPENSSL_PUT_ERROR(ASN1, ASN1_R_TOO_LONG); diff --git a/Sources/CNIOBoringSSL/crypto/x509/by_dir.cc b/Sources/CNIOBoringSSL/crypto/x509/by_dir.cc index fd81f672..984f941a 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/by_dir.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/by_dir.cc @@ -1,49 +1,105 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "../internal.h" +#include "../mem_internal.h" #include "internal.h" -typedef struct lookup_dir_hashes_st { - uint32_t hash; - int suffix; -} BY_DIR_HASH; -typedef struct lookup_dir_entry_st { - CRYPTO_MUTEX lock; - char *dir; - int dir_type; - STACK_OF(BY_DIR_HASH) *hashes; -} BY_DIR_ENTRY; +BSSL_NAMESPACE_BEGIN -typedef struct lookup_dir_st { - STACK_OF(BY_DIR_ENTRY) *dirs; -} BY_DIR; +// A ByDirEntry tracks state for a single directory, notably the starting suffix +// for CRL lookups. +class ByDirEntry { + public: + static constexpr bool kAllowUniquePtr = true; -DEFINE_STACK_OF(BY_DIR_HASH) -DEFINE_STACK_OF(BY_DIR_ENTRY) + ByDirEntry() = default; + + static UniquePtr Create(int dir_type, std::string_view dir) { + auto ret = MakeUnique(); + ret->dir_type_ = dir_type; + ret->dir_.reset(OPENSSL_strndup(dir.data(), dir.size())); + if (ret->dir_ == nullptr) { + return nullptr; + } + return ret; + } + + int dir_type() const { return dir_type_; } + const char *dir() const { return dir_.get(); } + + int GetCRLSuffix(uint32_t hash) const { + MutexReadLock lock(&lock_); + auto it = std::lower_bound(crl_suffixes_.begin(), crl_suffixes_.end(), hash); + if (it == crl_suffixes_.end() || it->hash != hash) { + return 0; + } + return it->suffix; + } + + bool UpdateCRLSuffix(uint32_t hash, int suffix) { + MutexWriteLock lock(&lock_); + 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; + } + if (!crl_suffixes_.Push(CRLSuffix{hash, suffix})) { + return false; + } + std::sort(crl_suffixes_.begin(), crl_suffixes_.end()); + return true; + } + + private: + struct CRLSuffix { + uint32_t hash; + int suffix; + bool operator<(uint32_t h) const { return hash < h; } + bool operator<(const CRLSuffix &other) const { return hash < other.hash; } + }; + + UniquePtr dir_; + int dir_type_ = 0; + mutable Mutex lock_; + // crl_suffixes_ is kept sorted. + // TODO(davidben): This should be a hash table. Insertions are O(N log N). + Vector crl_suffixes_; +}; + +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(BY_DIR *ctx, const char *dir, int type); -static int get_cert_by_subject(X509_LOOKUP *xl, int type, X509_NAME *name, +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 @@ -52,77 +108,36 @@ static const X509_LOOKUP_METHOD x509_dir_lookup = { get_cert_by_subject, // get_by_subject }; -const X509_LOOKUP_METHOD *X509_LOOKUP_hash_dir(void) { - return &x509_dir_lookup; -} - static int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, char **retp) { - int ret = 0; - char *dir = NULL; - - BY_DIR *ld = reinterpret_cast(ctx->method_data); - + ByDir *ld = reinterpret_cast(ctx->method_data); switch (cmd) { case X509_L_ADD_DIR: if (argl == X509_FILETYPE_DEFAULT) { - dir = (char *)getenv(X509_get_default_cert_dir_env()); - if (dir) { - ret = add_cert_dir(ld, dir, X509_FILETYPE_PEM); - } else { - ret = - add_cert_dir(ld, X509_get_default_cert_dir(), X509_FILETYPE_PEM); - } - if (!ret) { + 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; } - } else { - ret = add_cert_dir(ld, argp, (int)argl); + return 1; } - break; - } - return ret; -} - -static int new_dir(X509_LOOKUP *lu) { - BY_DIR *a; - - if ((a = (BY_DIR *)OPENSSL_malloc(sizeof(BY_DIR))) == NULL) { - return 0; - } - a->dirs = NULL; - lu->method_data = a; - return 1; -} - -static void by_dir_hash_free(BY_DIR_HASH *hash) { OPENSSL_free(hash); } - -static int by_dir_hash_cmp(const BY_DIR_HASH *const *a, - const BY_DIR_HASH *const *b) { - if ((*a)->hash > (*b)->hash) { - return 1; - } - if ((*a)->hash < (*b)->hash) { - return -1; + return add_cert_dir(ld, argp, (int)argl); } return 0; } -static void by_dir_entry_free(BY_DIR_ENTRY *ent) { - if (ent != NULL) { - CRYPTO_MUTEX_cleanup(&ent->lock); - OPENSSL_free(ent->dir); - sk_BY_DIR_HASH_pop_free(ent->hashes, by_dir_hash_free); - OPENSSL_free(ent); +static int new_dir(X509_LOOKUP *lu) { + ByDir *a = New(); + if (a == nullptr) { + return 0; } + lu->method_data = a; + return 1; } static void free_dir(X509_LOOKUP *lu) { - BY_DIR *a = reinterpret_cast(lu->method_data); - if (a != NULL) { - sk_BY_DIR_ENTRY_pop_free(a->dirs, by_dir_entry_free); - OPENSSL_free(a); - } + Delete(reinterpret_cast(lu->method_data)); } #if defined(OPENSSL_WINDOWS) @@ -131,220 +146,156 @@ static void free_dir(X509_LOOKUP *lu) { #define DIR_HASH_SEPARATOR ':' #endif -static int add_cert_dir(BY_DIR *ctx, const char *dir, int type) { - size_t j, len; - const char *s, *ss, *p; - - if (dir == NULL || !*dir) { +static 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; } - s = dir; - p = s; + std::string_view rest = inp; do { - if (*p == DIR_HASH_SEPARATOR || *p == '\0') { - BY_DIR_ENTRY *ent; - ss = s; - s = p + 1; - len = p - ss; - if (len == 0) { - continue; - } - for (j = 0; j < sk_BY_DIR_ENTRY_num(ctx->dirs); j++) { - ent = sk_BY_DIR_ENTRY_value(ctx->dirs, j); - if (strlen(ent->dir) == len && strncmp(ent->dir, ss, len) == 0) { - break; - } - } - if (j < sk_BY_DIR_ENTRY_num(ctx->dirs)) { - continue; - } - if (ctx->dirs == NULL) { - ctx->dirs = sk_BY_DIR_ENTRY_new_null(); - if (!ctx->dirs) { - return 0; - } - } - ent = reinterpret_cast( - OPENSSL_malloc(sizeof(BY_DIR_ENTRY))); - if (!ent) { - return 0; - } - CRYPTO_MUTEX_init(&ent->lock); - ent->dir_type = type; - ent->hashes = sk_BY_DIR_HASH_new(by_dir_hash_cmp); - ent->dir = OPENSSL_strndup(ss, len); - if (ent->dir == NULL || ent->hashes == NULL || - !sk_BY_DIR_ENTRY_push(ctx->dirs, ent)) { - by_dir_entry_free(ent); - return 0; - } + // Split by `DIR_HASH_SEPARATOR`. + size_t sep = rest.find(DIR_HASH_SEPARATOR); + std::string_view dir; + if (sep == std::string_view::npos) { + dir = rest; + rest = std::string_view(); + } else { + dir = rest.substr(0, sep); + rest = rest.substr(sep + 1); } - } while (*p++ != '\0'); + if (dir.empty()) { + continue; + } + // Ignore duplicates. + if (std::any_of(ctx->dirs.begin(), ctx->dirs.end(), + [&](const auto &ent) { return ent->dir() == dir; })) { + continue; + } + auto ent = ByDirEntry::Create(type, dir); + if (ent == nullptr || !ctx->dirs.Push(std::move(ent))) { + return 0; + } + } while (!rest.empty()); return 1; } -static int get_cert_by_subject(X509_LOOKUP *xl, int type, X509_NAME *name, +static int get_cert_by_subject(X509_LOOKUP *xl, int type, const X509_NAME *name, X509_OBJECT *ret) { - union { - struct { - X509 st_x509; - X509_CINF st_x509_cinf; - } x509; - struct { - X509_CRL st_crl; - X509_CRL_INFO st_crl_info; - } crl; - } data; - int ok = 0; - size_t i; - int k; - uint32_t h; - uint32_t hash_array[2]; - int hash_index; - char *b = NULL; - X509_OBJECT stmp, *tmp; - const char *postfix = ""; - - if (name == NULL) { + if (name == nullptr) { return 0; } + // Set up an `X509_OBJECT` to compare against. + UniquePtr lookup_cert; + UniquePtr lookup_crl; + X509_OBJECT stmp; + const char *postfix = ""; stmp.type = type; - BY_DIR *ctx = reinterpret_cast(xl->method_data); + ByDir *ctx = reinterpret_cast(xl->method_data); if (type == X509_LU_X509) { - data.x509.st_x509.cert_info = &data.x509.st_x509_cinf; - data.x509.st_x509_cinf.subject = name; - stmp.data.x509 = &data.x509.st_x509; + lookup_cert.reset(X509_new()); + if (lookup_cert == nullptr || + !X509_set_subject_name(lookup_cert.get(), name)) { + return 0; + } + stmp.data.x509 = lookup_cert.get(); postfix = ""; } else if (type == X509_LU_CRL) { - data.crl.st_crl.crl = &data.crl.st_crl_info; - data.crl.st_crl_info.issuer = name; - stmp.data.crl = &data.crl.st_crl; + lookup_crl.reset(X509_CRL_new()); + if (lookup_crl == nullptr || + !X509_CRL_set_issuer_name(lookup_crl.get(), name)) { + return 0; + } + stmp.data.crl = lookup_crl.get(); postfix = "r"; } else { OPENSSL_PUT_ERROR(X509, X509_R_WRONG_LOOKUP_TYPE); - goto finish; + return 0; } - hash_array[0] = X509_NAME_hash(name); - hash_array[1] = X509_NAME_hash_old(name); - for (hash_index = 0; hash_index < 2; ++hash_index) { - h = hash_array[hash_index]; - for (i = 0; i < sk_BY_DIR_ENTRY_num(ctx->dirs); i++) { - BY_DIR_ENTRY *ent; - size_t idx; - BY_DIR_HASH htmp, *hent; - ent = sk_BY_DIR_ENTRY_value(ctx->dirs, i); - if (type == X509_LU_CRL && ent->hashes) { - htmp.hash = h; - CRYPTO_MUTEX_lock_read(&ent->lock); - if (sk_BY_DIR_HASH_find(ent->hashes, &idx, &htmp)) { - hent = sk_BY_DIR_HASH_value(ent->hashes, idx); - k = hent->suffix; - } else { - hent = NULL; - k = 0; - } - CRYPTO_MUTEX_unlock_read(&ent->lock); - } else { - k = 0; - hent = NULL; + // Try both new and old hashes. + const uint32_t hashes[] = {X509_NAME_hash(name), X509_NAME_hash_old(name)}; + for (uint32_t hash : hashes) { + for (UniquePtr &ent : ctx->dirs) { + // If a CRL, start from the previously saved suffix. Updated CRLs are + // expected to be added until new filenames. + // TODO(crbug.com/42290566): Is this what we want? + int suffix = 0; + if (type == X509_LU_CRL) { + suffix = ent->GetCRLSuffix(hash); } + + // The directory format handles hash collections by incrementing a suffix + // on the file name. Load every suffix into the cache. for (;;) { - OPENSSL_free(b); - if (OPENSSL_asprintf(&b, "%s/%08" PRIx32 ".%s%d", ent->dir, h, postfix, - k) == -1) { + char *path = nullptr; + if (OPENSSL_asprintf(&path, "%s/%08" PRIx32 ".%s%d", ent->dir(), hash, + postfix, suffix) == -1) { OPENSSL_PUT_ERROR(X509, ERR_R_BUF_LIB); - b = nullptr; - goto finish; + return 0; } + UniquePtr free_path(path); if (type == X509_LU_X509) { - if ((X509_load_cert_file(xl, b, ent->dir_type)) == 0) { - // Don't expose the lower level error, All of these boil - // down to "we could not find a CA". + if ((X509_load_cert_file(xl, path, ent->dir_type())) == 0) { + // Don't expose the lower level error, All of these boil down to "we + // could not find a CA". ERR_clear_error(); break; } } else if (type == X509_LU_CRL) { - if ((X509_load_crl_file(xl, b, ent->dir_type)) == 0) { - // Don't expose the lower level error, All of these boil - // down to "we could not find a CRL". + if ((X509_load_crl_file(xl, path, ent->dir_type())) == 0) { + // Don't expose the lower level error, All of these boil down to "we + // could not find a CRL". ERR_clear_error(); break; } } - // The lack of a CA or CRL will be caught higher up - k++; + // The lack of a CA or CRL will be caught higher up. + suffix++; } - // we have added it to the cache so now pull it out again - CRYPTO_MUTEX_lock_write(&xl->store_ctx->objs_lock); - tmp = NULL; - sk_X509_OBJECT_sort(xl->store_ctx->objs); - if (sk_X509_OBJECT_find(xl->store_ctx->objs, &idx, &stmp)) { - tmp = sk_X509_OBJECT_value(xl->store_ctx->objs, idx); + // We have added it to the cache so now pull it out again. + auto *store_impl = FromOpaque(xl->store_ctx); + store_impl->objs_lock.LockWrite(); + const X509_OBJECT *found = nullptr; + sk_X509_OBJECT_sort(store_impl->objs.get()); + size_t idx; + if (sk_X509_OBJECT_find(store_impl->objs.get(), &idx, &stmp)) { + found = sk_X509_OBJECT_value(store_impl->objs.get(), idx); } - CRYPTO_MUTEX_unlock_write(&xl->store_ctx->objs_lock); + store_impl->objs_lock.UnlockWrite(); - // If a CRL, update the last file suffix added for this - - if (type == X509_LU_CRL) { - CRYPTO_MUTEX_lock_write(&ent->lock); - // Look for entry again in case another thread added an entry - // first. - if (!hent) { - htmp.hash = h; - sk_BY_DIR_HASH_sort(ent->hashes); - if (sk_BY_DIR_HASH_find(ent->hashes, &idx, &htmp)) { - hent = sk_BY_DIR_HASH_value(ent->hashes, idx); - } - } - if (!hent) { - hent = reinterpret_cast( - OPENSSL_malloc(sizeof(BY_DIR_HASH))); - if (hent == NULL) { - CRYPTO_MUTEX_unlock_write(&ent->lock); - ok = 0; - goto finish; - } - hent->hash = h; - hent->suffix = k; - if (!sk_BY_DIR_HASH_push(ent->hashes, hent)) { - CRYPTO_MUTEX_unlock_write(&ent->lock); - OPENSSL_free(hent); - ok = 0; - goto finish; - } - sk_BY_DIR_HASH_sort(ent->hashes); - } else if (hent->suffix < k) { - hent->suffix = k; - } - - CRYPTO_MUTEX_unlock_write(&ent->lock); + // If a CRL, store the last suffix we saw, to skip already loaded files + // next time. + // TODO(crbug.com/42290566): Is this what we want? + if (type == X509_LU_CRL && !ent->UpdateCRLSuffix(hash, suffix)) { + return 0; } - if (tmp != NULL) { - ok = 1; - ret->type = tmp->type; - OPENSSL_memcpy(&ret->data, &tmp->data, sizeof(ret->data)); - - // Clear any errors that might have been raised processing empty - // or malformed files. + if (found != nullptr) { + // Clear any errors that might have been raised processing empty or + // malformed files. ERR_clear_error(); - // If we were going to up the reference count, we would need - // to do it on a perl 'type' basis - goto finish; + // TODO(crbug.com/42290561): This should manage the reference counts + // correctly but does not. + ret->type = found->type; + OPENSSL_memcpy(&ret->data, &found->data, sizeof(ret->data)); + return 1; } } } -finish: - OPENSSL_free(b); - return ok; + + return 0; +} + +BSSL_NAMESPACE_END + +const X509_LOOKUP_METHOD *X509_LOOKUP_hash_dir() { + return &bssl::x509_dir_lookup; } int X509_LOOKUP_add_dir(X509_LOOKUP *lookup, const char *name, int type) { - return X509_LOOKUP_ctrl(lookup, X509_L_ADD_DIR, name, type, NULL); + return X509_LOOKUP_ctrl(lookup, X509_L_ADD_DIR, name, type, nullptr); } diff --git a/Sources/CNIOBoringSSL/crypto/x509/by_file.cc b/Sources/CNIOBoringSSL/crypto/x509/by_file.cc index 47c842b3..53caad30 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/by_file.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/by_file.cc @@ -1,17 +1,21 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "internal.h" @@ -19,13 +23,13 @@ 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 = { - NULL, // new - NULL, // free + nullptr, // new + nullptr, // free by_file_ctrl, // ctrl - NULL, // get_by_subject + nullptr, // get_by_subject }; -const X509_LOOKUP_METHOD *X509_LOOKUP_file(void) { return &x509_file_lookup; } +const X509_LOOKUP_METHOD *X509_LOOKUP_file() { return &x509_file_lookup; } static int by_file_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, char **ret) { @@ -35,7 +39,7 @@ static int by_file_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, const char *file = argp; int type = argl; if (argl == X509_FILETYPE_DEFAULT) { - if ((file = getenv(X509_get_default_cert_file_env())) == NULL) { + if ((file = getenv(X509_get_default_cert_file_env())) == nullptr) { file = X509_get_default_cert_file(); } type = X509_FILETYPE_PEM; @@ -51,24 +55,24 @@ static int by_file_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, int X509_load_cert_file(X509_LOOKUP *ctx, const char *file, int type) { int ret = 0; - BIO *in = NULL; + BIO *in = nullptr; int i, count = 0; - X509 *x = NULL; + X509 *x = nullptr; in = BIO_new(BIO_s_file()); - if ((in == NULL) || (BIO_read_filename(in, file) <= 0)) { + if ((in == nullptr) || (BIO_read_filename(in, file) <= 0)) { OPENSSL_PUT_ERROR(X509, ERR_R_SYS_LIB); goto err; } if (type == X509_FILETYPE_PEM) { for (;;) { - x = PEM_read_bio_X509_AUX(in, NULL, NULL, NULL); - if (x == NULL) { - uint32_t error = ERR_peek_last_error(); - if (ERR_GET_LIB(error) == ERR_LIB_PEM && - ERR_GET_REASON(error) == PEM_R_NO_START_LINE && count > 0) { + x = PEM_read_bio_X509_AUX(in, nullptr, nullptr, nullptr); + if (x == nullptr) { + if (ERR_equals(ERR_peek_last_error(), ERR_LIB_PEM, + PEM_R_NO_START_LINE) && + count > 0) { ERR_clear_error(); break; } @@ -81,12 +85,12 @@ int X509_load_cert_file(X509_LOOKUP *ctx, const char *file, int type) { } count++; X509_free(x); - x = NULL; + x = nullptr; } ret = count; } else if (type == X509_FILETYPE_ASN1) { - x = d2i_X509_bio(in, NULL); - if (x == NULL) { + x = d2i_X509_bio(in, nullptr); + if (x == nullptr) { OPENSSL_PUT_ERROR(X509, ERR_R_ASN1_LIB); goto err; } @@ -112,24 +116,24 @@ err: int X509_load_crl_file(X509_LOOKUP *ctx, const char *file, int type) { int ret = 0; - BIO *in = NULL; + BIO *in = nullptr; int i, count = 0; - X509_CRL *x = NULL; + X509_CRL *x = nullptr; in = BIO_new(BIO_s_file()); - if ((in == NULL) || (BIO_read_filename(in, file) <= 0)) { + if ((in == nullptr) || (BIO_read_filename(in, file) <= 0)) { OPENSSL_PUT_ERROR(X509, ERR_R_SYS_LIB); goto err; } if (type == X509_FILETYPE_PEM) { for (;;) { - x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL); - if (x == NULL) { - uint32_t error = ERR_peek_last_error(); - if (ERR_GET_LIB(error) == ERR_LIB_PEM && - ERR_GET_REASON(error) == PEM_R_NO_START_LINE && count > 0) { + x = PEM_read_bio_X509_CRL(in, nullptr, nullptr, nullptr); + if (x == nullptr) { + if (ERR_equals(ERR_peek_last_error(), ERR_LIB_PEM, + PEM_R_NO_START_LINE) && + count > 0) { ERR_clear_error(); break; } @@ -142,12 +146,12 @@ int X509_load_crl_file(X509_LOOKUP *ctx, const char *file, int type) { } count++; X509_CRL_free(x); - x = NULL; + x = nullptr; } ret = count; } else if (type == X509_FILETYPE_ASN1) { - x = d2i_X509_CRL_bio(in, NULL); - if (x == NULL) { + x = d2i_X509_CRL_bio(in, nullptr); + if (x == nullptr) { OPENSSL_PUT_ERROR(X509, ERR_R_ASN1_LIB); goto err; } @@ -186,7 +190,7 @@ int X509_load_cert_crl_file(X509_LOOKUP *ctx, const char *file, int type) { OPENSSL_PUT_ERROR(X509, ERR_R_SYS_LIB); return 0; } - inf = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL); + inf = PEM_X509_INFO_read_bio(in, nullptr, nullptr, nullptr); BIO_free(in); if (!inf) { OPENSSL_PUT_ERROR(X509, ERR_R_PEM_LIB); @@ -218,5 +222,5 @@ err: } int X509_LOOKUP_load_file(X509_LOOKUP *lookup, const char *name, int type) { - return X509_LOOKUP_ctrl(lookup, X509_L_FILE_LOAD, name, type, NULL); + return X509_LOOKUP_ctrl(lookup, X509_L_FILE_LOAD, name, type, nullptr); } diff --git a/Sources/CNIOBoringSSL/crypto/x509/ext_dat.h b/Sources/CNIOBoringSSL/crypto/x509/ext_dat.h deleted file mode 100644 index ec7a7fec..00000000 --- a/Sources/CNIOBoringSSL/crypto/x509/ext_dat.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ - -// This file contains a table of "standard" extensions - -#if defined(__cplusplus) -extern "C" { -#endif - -extern const X509V3_EXT_METHOD v3_bcons, v3_nscert, v3_key_usage, v3_ext_ku; -extern const X509V3_EXT_METHOD v3_info, v3_sinfo; -extern const X509V3_EXT_METHOD v3_ns_ia5_list[], v3_alt[], v3_skey_id, - v3_akey_id; -extern const X509V3_EXT_METHOD v3_crl_num, v3_crl_reason, v3_crl_invdate; -extern const X509V3_EXT_METHOD v3_delta_crl, v3_cpols, v3_crld, v3_freshest_crl; -extern const X509V3_EXT_METHOD v3_ocsp_nonce, v3_ocsp_accresp, v3_ocsp_acutoff; -extern const X509V3_EXT_METHOD v3_ocsp_crlid, v3_ocsp_nocheck, - v3_ocsp_serviceloc; -extern const X509V3_EXT_METHOD v3_crl_hold; -extern const X509V3_EXT_METHOD v3_policy_mappings, v3_policy_constraints; -extern const X509V3_EXT_METHOD v3_name_constraints, v3_inhibit_anyp, v3_idp; -extern const X509V3_EXT_METHOD v3_addr, v3_asid; - -// This table will be searched using OBJ_bsearch so it *must* kept in order -// of the ext_nid values. - -// TODO(fork): OCSP support -#define OPENSSL_NO_OCSP - -static const X509V3_EXT_METHOD *const standard_exts[] = { - &v3_nscert, - &v3_ns_ia5_list[0], - &v3_ns_ia5_list[1], - &v3_ns_ia5_list[2], - &v3_ns_ia5_list[3], - &v3_ns_ia5_list[4], - &v3_ns_ia5_list[5], - &v3_ns_ia5_list[6], - &v3_skey_id, - &v3_key_usage, - &v3_alt[0], - &v3_alt[1], - &v3_bcons, - &v3_crl_num, - &v3_cpols, - &v3_akey_id, - &v3_crld, - &v3_ext_ku, - &v3_delta_crl, - &v3_crl_reason, - &v3_crl_invdate, - &v3_info, -#ifndef OPENSSL_NO_OCSP - &v3_ocsp_nonce, - &v3_ocsp_crlid, - &v3_ocsp_accresp, - &v3_ocsp_acutoff, - &v3_ocsp_serviceloc, -#endif - &v3_ocsp_nocheck, - &v3_sinfo, - &v3_policy_constraints, -#ifndef OPENSSL_NO_OCSP - &v3_crl_hold, -#endif - &v3_name_constraints, - &v3_policy_mappings, - &v3_inhibit_anyp, - &v3_idp, - &v3_alt[2], - &v3_freshest_crl, -}; - -// Number of standard extensions - -#define STANDARD_EXTENSION_COUNT \ - (sizeof(standard_exts) / sizeof(X509V3_EXT_METHOD *)) - -#if defined(__cplusplus) -} // extern C -#endif diff --git a/Sources/CNIOBoringSSL/crypto/x509/i2d_pr.cc b/Sources/CNIOBoringSSL/crypto/x509/i2d_pr.cc index 5869cc81..2bd57d08 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/i2d_pr.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/i2d_pr.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 diff --git a/Sources/CNIOBoringSSL/crypto/x509/internal.h b/Sources/CNIOBoringSSL/crypto/x509/internal.h index b3608cfd..b867ae6e 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/internal.h +++ b/Sources/CNIOBoringSSL/crypto/x509/internal.h @@ -1,72 +1,120 @@ -/* - * Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. -#ifndef OPENSSL_HEADER_X509_INTERNAL_H -#define OPENSSL_HEADER_X509_INTERNAL_H +#ifndef OPENSSL_HEADER_CRYPTO_X509_INTERNAL_H +#define OPENSSL_HEADER_CRYPTO_X509_INTERNAL_H #include #include +#include #include #include "../asn1/internal.h" #include "../internal.h" - -#if defined(__cplusplus) -extern "C" { -#endif - +#include "../mem_internal.h" // Internal structures. -typedef struct X509_val_st { - ASN1_TIME *notBefore; - ASN1_TIME *notAfter; -} X509_VAL; +DECLARE_OPAQUE_STRUCT(x509_st, X509Impl) +DECLARE_OPAQUE_STRUCT(x509_store_st, X509Store) +DECLARE_OPAQUE_STRUCT(X509_name_st, X509Name) +DECLARE_OPAQUE_STRUCT(X509_name_entry_st, X509NameEntry) +DECLARE_OPAQUE_STRUCT(X509_pubkey_st, X509Pubkey) -DECLARE_ASN1_FUNCTIONS_const(X509_VAL) +BSSL_NAMESPACE_BEGIN -struct X509_pubkey_st { - X509_ALGOR *algor; - ASN1_BIT_STRING *public_key; - EVP_PKEY *pkey; -} /* X509_PUBKEY */; +void x509_algor_init(X509_ALGOR *alg); +void x509_algor_cleanup(X509_ALGOR *alg); -// X509_PUBKEY is an |ASN1_ITEM| whose ASN.1 type is SubjectPublicKeyInfo and C -// type is |X509_PUBKEY*|. +// A ScopedX509Algor is a stack-allocatable `X509_ALGOR` with managed lifetime. +// This cannot use `DECLARE_OPAQUE_STRUCT` because `X509_ALGOR` is a public +// struct. +BORINGSSL_MAKE_STACK_TRAITS(X509_ALGOR, x509_algor_init, x509_algor_cleanup) +using ScopedX509Algor = internal::StackAllocated; + +// x509_parse_algorithm parses a DER-encoded, AlgorithmIdentifier from `cbs` and +// writes the result to `*out`. It returns one on success and zero on error. +int x509_parse_algorithm(CBS *cbs, X509_ALGOR *out); + +// x509_marshal_algorithm marshals `in` as a DER-encoded, AlgorithmIdentifier +// and writes the result to `out`. It returns one on success and zero on error. +int x509_marshal_algorithm(CBB *out, const X509_ALGOR *in); + +class X509Pubkey : public X509_pubkey_st { + public: + ScopedX509Algor algor; + ScopedASN1String public_key{V_ASN1_BIT_STRING}; + UniquePtr pkey; +}; + +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); + +// X509_PUBKEY is an `ASN1_ITEM` whose ASN.1 type is SubjectPublicKeyInfo and C +// type is `X509_PUBKEY*`. +// TODO(crbug.com/42290417): Remove this when `X509` and `X509_REQ` no longer +// depend on the tables. DECLARE_ASN1_ITEM(X509_PUBKEY) -struct X509_name_entry_st { - ASN1_OBJECT *object; - ASN1_STRING *value; - int set; -} /* X509_NAME_ENTRY */; +class X509NameEntry : public X509_name_entry_st { + public: + static constexpr bool kAllowUniquePtr = true; + X509NameEntry(); -// X509_NAME_ENTRY is an |ASN1_ITEM| whose ASN.1 type is AttributeTypeAndValue -// (RFC 5280) and C type is |X509_NAME_ENTRY*|. + UniquePtr object; + ScopedASN1String value{-1}; + int set = 0; +}; + +// X509_NAME_ENTRY is an `ASN1_ITEM` whose ASN.1 type is AttributeTypeAndValue +// (RFC 5280) and C type is `X509_NAME_ENTRY*`. DECLARE_ASN1_ITEM(X509_NAME_ENTRY) -// we always keep X509_NAMEs in 2 forms. -struct X509_name_st { - STACK_OF(X509_NAME_ENTRY) *entries; - int modified; // true if 'bytes' needs to be built - BUF_MEM *bytes; - unsigned char *canon_enc; - int canon_enclen; +struct X509NameCache { + static constexpr bool kAllowUniquePtr = true; + // canon contains the DER-encoded canonicalized X.509 Name, not including the + // outermost TLV. + Array canon; + // der contains the DER-encoded X.509 Name, including the outermost TLV. + Array der; +}; + +class X509Name : public X509_name_st { + public: + ~X509Name(); + + // TODO(crbug.com/42290036): Switch to `Vector>`, + // which would save an allocation. Potentially `Vector` if we + // are willing to break pointer stability of entries after + // `X509_NAME_add_entry` or `X509_NAME_delete_entry`. + UniquePtr entries; + mutable Atomic cache = nullptr; } /* X509_NAME */; +BSSL_NAMESPACE_END + struct x509_attributes_st { ASN1_OBJECT *object; STACK_OF(ASN1_TYPE) *set; } /* X509_ATTRIBUTE */; -// X509_ATTRIBUTE is an |ASN1_ITEM| whose ASN.1 type is Attribute (RFC 2986) and -// C type is |X509_ATTRIBUTE*|. +BSSL_NAMESPACE_BEGIN + +// X509_ATTRIBUTE is an `ASN1_ITEM` whose ASN.1 type is Attribute (RFC 2986) and +// C type is `X509_ATTRIBUTE*`. DECLARE_ASN1_ITEM(X509_ATTRIBUTE) typedef struct x509_cert_aux_st { @@ -78,65 +126,88 @@ typedef struct x509_cert_aux_st { DECLARE_ASN1_FUNCTIONS_const(X509_CERT_AUX) +BSSL_NAMESPACE_END + struct X509_extension_st { ASN1_OBJECT *object; ASN1_BOOLEAN critical; ASN1_OCTET_STRING *value; } /* X509_EXTENSION */; -// X509_EXTENSION is an |ASN1_ITEM| whose ASN.1 type is X.509 Extension (RFC -// 5280) and C type is |X509_EXTENSION*|. +// X509_EXTENSION is an `ASN1_ITEM` whose ASN.1 type is X.509 Extension (RFC +// 5280) and C type is `X509_EXTENSION*`. DECLARE_ASN1_ITEM(X509_EXTENSION) -// X509_EXTENSIONS is an |ASN1_ITEM| whose ASN.1 type is SEQUENCE of Extension -// (RFC 5280) and C type is |STACK_OF(X509_EXTENSION)*|. +BSSL_NAMESPACE_BEGIN + +// X509_EXTENSIONS is an `ASN1_ITEM` whose ASN.1 type is SEQUENCE of Extension +// (RFC 5280) and C type is `STACK_OF(X509_EXTENSION)*`. DECLARE_ASN1_ITEM(X509_EXTENSIONS) -typedef struct { - ASN1_INTEGER *version; // [ 0 ] default of v1 - ASN1_INTEGER *serialNumber; - X509_ALGOR *signature; - X509_NAME *issuer; - X509_VAL *validity; - X509_NAME *subject; - X509_PUBKEY *key; - ASN1_BIT_STRING *issuerUID; // [ 1 ] optional in v2 - ASN1_BIT_STRING *subjectUID; // [ 2 ] optional in v2 - STACK_OF(X509_EXTENSION) *extensions; // [ 3 ] optional in v3 - ASN1_ENCODING enc; -} X509_CINF; +class X509Impl : public x509_st, public RefCounted { + public: + X509Impl(); -// TODO(https://crbug.com/boringssl/407): This is not const because it contains -// an |X509_NAME|. -DECLARE_ASN1_FUNCTIONS(X509_CINF) - -struct x509_st { - X509_CINF *cert_info; - X509_ALGOR *sig_alg; - ASN1_BIT_STRING *signature; - CRYPTO_refcount_t references; + // TBSCertificate fields: + uint8_t version = X509_VERSION_1; // One of the `X509_VERSION_*` constants. + ScopedASN1String serialNumber{V_ASN1_INTEGER}; + ScopedX509Algor tbs_sig_alg; + X509Name issuer; + ScopedASN1String notBefore{-1}; + ScopedASN1String notAfter{-1}; + X509Name subject; + X509Pubkey key; + UniquePtr issuerUID; // [ 1 ] optional in v2 + UniquePtr subjectUID; // [ 2 ] optional in v2 + STACK_OF(X509_EXTENSION) *extensions = nullptr; // [ 3 ] optional in v3 + // Certificate fields: + ScopedX509Algor sig_alg; + ScopedASN1String signature{V_ASN1_BIT_STRING}; + // Other state: + // buf, if not nullptr, contains a copy of the serialized Certificate. + // TODO(davidben): Now every parsed `X509` has an underlying `CRYPTO_BUFFER`, + // but `X509`s created peacemeal do not. Can we make this more uniform? + UniquePtr buf; CRYPTO_EX_DATA ex_data; // These contain copies of various extension values - long ex_pathlen; - uint32_t ex_flags; - uint32_t ex_kusage; - uint32_t ex_xkusage; - ASN1_OCTET_STRING *skid; - AUTHORITY_KEYID *akid; - STACK_OF(DIST_POINT) *crldp; - STACK_OF(GENERAL_NAME) *altname; - NAME_CONSTRAINTS *nc; - unsigned char cert_hash[SHA256_DIGEST_LENGTH]; - X509_CERT_AUX *aux; - CRYPTO_MUTEX lock; + 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] = {}; + bssl::X509_CERT_AUX *aux = nullptr; + Mutex lock; + + private: + friend RefCounted; + ~X509Impl(); } /* X509 */; -// X509 is an |ASN1_ITEM| whose ASN.1 type is X.509 Certificate (RFC 5280) and C -// type is |X509*|. +// x509_marshal_tbs_cert sets `cbb` to the serialized TBSCertificate of `x509`. +// It either replays the saved TBSCertificate encoding from the `CRYPTO_BUFFER`, +// or marshals the TBSCertificate from fields set on `x509`. It returns one on +// success or zero on error. +int x509_marshal_tbs_cert(CBB *cbb, const X509 *x509); + +// x509_get_or_marshal_tbs_cert sets `out` to the serialized TBSCertificate of +// `x509`. If possible, it gets the saved TBSCertificate encoding from the +// `CRYPTO_BUFFER` of `x509`, otherwise it marshals the TBSCertificate from +// fields set on `x509` into `scratch`. It returns one on success or zero on +// error. +int x509_get_or_marshal_tbs_cert(CBS *out, Array *scratch, + const X509 *x509); + +// X509 is an `ASN1_ITEM` whose ASN.1 type is X.509 Certificate (RFC 5280) and C +// type is `X509*`. DECLARE_ASN1_ITEM(X509) typedef struct { - ASN1_ENCODING enc; + bssl::ASN1_ENCODING enc; ASN1_INTEGER *version; X509_NAME *subject; X509_PUBKEY *pubkey; @@ -144,20 +215,24 @@ typedef struct { STACK_OF(X509_ATTRIBUTE) *attributes; // [ 0 ] } X509_REQ_INFO; -// TODO(https://crbug.com/boringssl/407): This is not const because it contains -// an |X509_NAME|. -DECLARE_ASN1_FUNCTIONS(X509_REQ_INFO) +DECLARE_ASN1_FUNCTIONS_const(X509_REQ_INFO) + +BSSL_NAMESPACE_END struct X509_req_st { - X509_REQ_INFO *req_info; + bssl::X509_REQ_INFO *req_info; X509_ALGOR *sig_alg; ASN1_BIT_STRING *signature; } /* X509_REQ */; -// X509_REQ is an |ASN1_ITEM| whose ASN.1 type is CertificateRequest (RFC 2986) -// and C type is |X509_REQ*|. +BSSL_NAMESPACE_BEGIN + +// X509_REQ is an `ASN1_ITEM` whose ASN.1 type is CertificateRequest (RFC 2986) +// and C type is `X509_REQ*`. DECLARE_ASN1_ITEM(X509_REQ) +BSSL_NAMESPACE_END + struct x509_revoked_st { ASN1_INTEGER *serialNumber; ASN1_TIME *revocationDate; @@ -166,9 +241,11 @@ struct x509_revoked_st { int reason; } /* X509_REVOKED */; -// X509_REVOKED is an |ASN1_ITEM| whose ASN.1 type is an element of the +BSSL_NAMESPACE_BEGIN + +// X509_REVOKED is an `ASN1_ITEM` whose ASN.1 type is an element of the // revokedCertificates field of TBSCertList (RFC 5280) and C type is -// |X509_REVOKED*|. +// `X509_REVOKED*`. DECLARE_ASN1_ITEM(X509_REVOKED) typedef struct { @@ -179,12 +256,12 @@ typedef struct { ASN1_TIME *nextUpdate; STACK_OF(X509_REVOKED) *revoked; STACK_OF(X509_EXTENSION) /* [0] */ *extensions; - ASN1_ENCODING enc; + bssl::ASN1_ENCODING enc; } X509_CRL_INFO; -// TODO(https://crbug.com/boringssl/407): This is not const because it contains -// an |X509_NAME|. -DECLARE_ASN1_FUNCTIONS(X509_CRL_INFO) +DECLARE_ASN1_FUNCTIONS_const(X509_CRL_INFO) + +BSSL_NAMESPACE_END // Values in idp_flags field // IDP present @@ -204,10 +281,10 @@ DECLARE_ASN1_FUNCTIONS(X509_CRL_INFO) struct X509_crl_st { // actual signature - X509_CRL_INFO *crl; + bssl::X509_CRL_INFO *crl; X509_ALGOR *sig_alg; ASN1_BIT_STRING *signature; - CRYPTO_refcount_t references; + bssl::CRYPTO_refcount_t references; int flags; // Copies of various extensions AUTHORITY_KEYID *akid; @@ -217,18 +294,22 @@ struct X509_crl_st { unsigned char crl_hash[SHA256_DIGEST_LENGTH]; } /* X509_CRL */; -// X509_CRL is an |ASN1_ITEM| whose ASN.1 type is X.509 CertificateList (RFC -// 5280) and C type is |X509_CRL*|. +BSSL_NAMESPACE_BEGIN + +// X509_CRL is an `ASN1_ITEM` whose ASN.1 type is X.509 CertificateList (RFC +// 5280) and C type is `X509_CRL*`. DECLARE_ASN1_ITEM(X509_CRL) -// GENERAL_NAME is an |ASN1_ITEM| whose ASN.1 type is GeneralName and C type is -// |GENERAL_NAME*|. +// GENERAL_NAME is an `ASN1_ITEM` whose ASN.1 type is GeneralName and C type is +// `GENERAL_NAME*`. DECLARE_ASN1_ITEM(GENERAL_NAME) -// GENERAL_NAMES is an |ASN1_ITEM| whose ASN.1 type is SEQUENCE OF GeneralName -// and C type is |GENERAL_NAMES*|, aka |STACK_OF(GENERAL_NAME)*|. +// GENERAL_NAMES is an `ASN1_ITEM` whose ASN.1 type is SEQUENCE OF GeneralName +// and C type is `GENERAL_NAMES*`, aka `STACK_OF(GENERAL_NAME)*`. DECLARE_ASN1_ITEM(GENERAL_NAMES) +BSSL_NAMESPACE_END + struct X509_VERIFY_PARAM_st { int64_t check_time; // POSIX time to use unsigned long flags; // Various verify flags @@ -257,54 +338,65 @@ struct x509_object_st { } data; } /* X509_OBJECT */; -// NETSCAPE_SPKI is an |ASN1_ITEM| whose ASN.1 type is -// SignedPublicKeyAndChallenge and C type is |NETSCAPE_SPKI*|. +BSSL_NAMESPACE_BEGIN + +// NETSCAPE_SPKI is an `ASN1_ITEM` whose ASN.1 type is +// SignedPublicKeyAndChallenge and C type is `NETSCAPE_SPKI*`. DECLARE_ASN1_ITEM(NETSCAPE_SPKI) -// NETSCAPE_SPKAC is an |ASN1_ITEM| whose ASN.1 type is PublicKeyAndChallenge -// and C type is |NETSCAPE_SPKAC*|. +// NETSCAPE_SPKAC is an `ASN1_ITEM` whose ASN.1 type is PublicKeyAndChallenge +// and C type is `NETSCAPE_SPKAC*`. DECLARE_ASN1_ITEM(NETSCAPE_SPKAC) +BSSL_NAMESPACE_END + // This is a static that defines the function interface struct x509_lookup_method_st { int (*new_item)(X509_LOOKUP *ctx); void (*free)(X509_LOOKUP *ctx); int (*ctrl)(X509_LOOKUP *ctx, int cmd, const char *argc, long argl, char **ret); - int (*get_by_subject)(X509_LOOKUP *ctx, int type, X509_NAME *name, + int (*get_by_subject)(X509_LOOKUP *ctx, int type, const X509_NAME *name, X509_OBJECT *ret); } /* X509_LOOKUP_METHOD */; -DEFINE_STACK_OF(X509_LOOKUP) +BSSL_NAMESPACE_BEGIN // This is used to hold everything. It is used for all certificate // validation. Once we have a certificate chain, the 'verify' // function is then called to actually check the cert chain. -struct x509_store_st { +class X509Store : public x509_store_st, public RefCounted { + public: + X509Store(); + // The following is a cache of trusted certs - STACK_OF(X509_OBJECT) *objs; // Cache of all objects - CRYPTO_MUTEX objs_lock; + UniquePtr objs; // Cache of all objects + Mutex objs_lock; // These are external lookup methods - STACK_OF(X509_LOOKUP) *get_cert_methods; + Vector> get_cert_methods; - X509_VERIFY_PARAM *param; + UniquePtr param; // Callbacks for various operations - X509_STORE_CTX_verify_cb verify_cb; // error callback + X509_STORE_CTX_verify_cb verify_cb = nullptr; // error callback - CRYPTO_refcount_t references; + private: + friend RefCounted; + ~X509Store() = default; } /* X509_STORE */; +BSSL_NAMESPACE_END + // This is the functions plus an instance of the local variables. struct x509_lookup_st { const X509_LOOKUP_METHOD *method; // the functions - void *method_data; // method data + void *method_data; // method data X509_STORE *store_ctx; // who owns us } /* X509_LOOKUP */; -// This is a used when verifying cert chains. Since the +// This is used when verifying cert chains. Since the // gathering of the cert chain can take some time (and have to be // 'retried', this needs to be kept and passed around. struct x509_store_ctx_st { @@ -318,11 +410,11 @@ struct x509_store_ctx_st { X509_VERIFY_PARAM *param; // trusted_stack, if non-NULL, is a set of trusted certificates to consider - // instead of those from |X509_STORE|. + // instead of those from `X509_STORE`. STACK_OF(X509) *trusted_stack; // Callbacks for various operations - X509_STORE_CTX_verify_cb verify_cb; // error callback + X509_STORE_CTX_verify_cb verify_cb; // error callback // The following is built up int last_untrusted; // index of last untrusted cert @@ -340,6 +432,8 @@ struct x509_store_ctx_st { CRYPTO_EX_DATA ex_data; } /* X509_STORE_CTX */; +BSSL_NAMESPACE_BEGIN + ASN1_TYPE *ASN1_generate_v3(const char *str, const X509V3_CTX *cnf); int X509_CERT_AUX_print(BIO *bp, X509_CERT_AUX *x, int indent); @@ -347,20 +441,20 @@ int X509_CERT_AUX_print(BIO *bp, X509_CERT_AUX *x, int indent); // RSA-PSS functions. -// x509_rsa_pss_to_ctx configures |ctx| for an RSA-PSS operation based on -// signature algorithm parameters in |sigalg| (which must have type -// |NID_rsassaPss|) and key |pkey|. It returns one on success and zero on +// x509_rsa_pss_to_ctx configures `ctx` for an RSA-PSS operation based on +// signature algorithm parameters in `sigalg` (which must have type +// `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); -// 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 +// 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 // returns one on success and zero on error. int x509_rsa_ctx_to_pss(EVP_MD_CTX *ctx, X509_ALGOR *algor); // x509_print_rsa_pss_params prints a human-readable representation of RSA-PSS -// parameters in |sigalg| to |bp|. It returns one on success and zero on +// parameters in `sigalg` to `bp`. It returns one on success and zero on // error. int x509_print_rsa_pss_params(BIO *bp, const X509_ALGOR *sigalg, int indent, ASN1_PCTX *pctx); @@ -368,138 +462,157 @@ int x509_print_rsa_pss_params(BIO *bp, const X509_ALGOR *sigalg, int indent, // Signature algorithm functions. -// x509_digest_sign_algorithm encodes the signing parameters of |ctx| as an -// AlgorithmIdentifier and saves the result in |algor|. It returns one on +// x509_digest_sign_algorithm encodes the signing parameters of `ctx` as an +// AlgorithmIdentifier and saves the result in `algor`. It returns one on // success, or zero on error. int x509_digest_sign_algorithm(EVP_MD_CTX *ctx, X509_ALGOR *algor); -// x509_digest_verify_init sets up |ctx| for a signature verification operation -// with public key |pkey| and parameters from |algor|. The |ctx| argument must -// have been initialised with |EVP_MD_CTX_init|. It returns one on success, or +// x509_digest_verify_init sets up `ctx` for a signature verification operation +// with public key `pkey` and parameters from `algor`. The `ctx` argument must +// 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); +// 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); + +// 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); + +// 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); + // Path-building functions. -// X509_policy_check checks certificate policies in |certs|. |user_policies| is -// 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 +// X509_policy_check checks certificate policies in `certs`. `user_policies` is +// 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. +// chain, it sets `*out_current_cert` to NULL. int X509_policy_check(const STACK_OF(X509) *certs, const STACK_OF(ASN1_OBJECT) *user_policies, unsigned long flags, X509 **out_current_cert); -// x509_check_issued_with_callback calls |X509_check_issued|, but allows the +// 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 // error. // // TODO(davidben): Reduce the scope of the verify callback and remove this. The -// callback only runs with |X509_V_FLAG_CB_ISSUER_CHECK|, which is only used by +// callback only runs with `X509_V_FLAG_CB_ISSUER_CHECK`, which is only used by // one internal project and rust-openssl, who use it by mistake. -int x509_check_issued_with_callback(X509_STORE_CTX *ctx, X509 *x, X509 *issuer); +int x509_check_issued_with_callback(X509_STORE_CTX *ctx, const X509 *x, + const X509 *issuer); -// x509v3_bytes_to_hex encodes |len| bytes from |in| to hex and returns a +// x509v3_bytes_to_hex encodes `len` bytes from `in` to hex and returns a // newly-allocated NUL-terminated string containing the result, or NULL on // allocation error. // -// This function was historically named |hex_to_string| in OpenSSL. Despite the -// name, |hex_to_string| converted to hex. +// This function was historically named `hex_to_string` in OpenSSL. Despite the +// name, `hex_to_string` converted to hex. OPENSSL_EXPORT char *x509v3_bytes_to_hex(const uint8_t *in, size_t len); -// x509v3_hex_string_to_bytes decodes |str| in hex and returns a newly-allocated -// array containing the result, or NULL on error. On success, it sets |*len| to +// x509v3_hex_string_to_bytes decodes `str` in hex and returns a newly-allocated +// array containing the result, or NULL on error. On success, it sets `*len` to // the length of the result. Colon separators between bytes in the input are // allowed and ignored. // -// This function was historically named |string_to_hex| in OpenSSL. Despite the -// name, |string_to_hex| converted from hex. +// This function was historically named `string_to_hex` in OpenSSL. Despite the +// name, `string_to_hex` converted from hex. unsigned char *x509v3_hex_to_bytes(const char *str, size_t *len); -// x509v3_conf_name_matches returns one if |name| is equal to |cmp| or begins -// with |cmp| followed by '.', and zero otherwise. +// x509v3_conf_name_matches returns one if `name` is equal to `cmp` or begins +// with `cmp` followed by '.', and zero otherwise. int x509v3_conf_name_matches(const char *name, const char *cmp); -// x509v3_looks_like_dns_name returns one if |in| looks like a DNS name and zero +// x509v3_looks_like_dns_name returns one if `in` looks like a DNS name and zero // otherwise. OPENSSL_EXPORT int x509v3_looks_like_dns_name(const unsigned char *in, size_t len); // 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 +// extensions in `x`. It returns one on success and zero if some extensions were // invalid. OPENSSL_EXPORT int x509v3_cache_extensions(X509 *x); -// x509v3_a2i_ipadd decodes |ipasc| as an IPv4 or IPv6 address. IPv6 addresses +// 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 // it decodes an IPv4 address, it writes the result to the first four bytes of -// |ipout| and returns four. If it decodes an IPv6 address, it writes the result -// to all 16 bytes of |ipout| and returns 16. Otherwise, it returns zero. +// `ipout` and returns four. If it decodes an IPv6 address, it writes the result +// to all 16 bytes of `ipout` and returns 16. Otherwise, it returns zero. int x509v3_a2i_ipadd(unsigned char ipout[16], const char *ipasc); -// A |BIT_STRING_BITNAME| is used to contain a list of bit names. +// A `BIT_STRING_BITNAME` is used to contain a list of bit names. typedef struct { int bitnum; const char *lname; const char *sname; } BIT_STRING_BITNAME; -// x509V3_add_value_asn1_string appends a |CONF_VALUE| with the specified name -// and value to |*extlist|. if |*extlist| is NULL, it sets |*extlist| to a -// newly-allocated |STACK_OF(CONF_VALUE)| first. It returns one on success and +// x509V3_add_value_asn1_string appends a `CONF_VALUE` with the specified name +// and value to `*extlist`. if `*extlist` is NULL, it sets `*extlist` to a +// newly-allocated `STACK_OF(CONF_VALUE)` first. It returns one on success and // zero on error. int x509V3_add_value_asn1_string(const char *name, const ASN1_STRING *value, STACK_OF(CONF_VALUE) **extlist); -// X509V3_NAME_from_section adds attributes to |nm| by interpreting the -// key/value pairs in |dn_sk|. It returns one on success and zero on error. -// |chtype|, which should be one of |MBSTRING_*| constants, determines the +// X509V3_NAME_from_section adds attributes to `nm` by interpreting the +// key/value pairs in `dn_sk`. It returns one on success and zero on error. +// `chtype`, which should be one of `MBSTRING_*` constants, determines the // character encoding used to interpret values. int X509V3_NAME_from_section(X509_NAME *nm, const STACK_OF(CONF_VALUE) *dn_sk, int chtype); -// X509V3_bool_from_string decodes |str| as a boolean. On success, it returns -// one and sets |*out_bool| to resulting value. Otherwise, it returns zero. +// X509V3_bool_from_string decodes `str` as a boolean. On success, it returns +// one and sets `*out_bool` to resulting value. Otherwise, it returns zero. int X509V3_bool_from_string(const char *str, ASN1_BOOLEAN *out_bool); -// X509V3_get_value_bool decodes |value| as a boolean. On success, it returns -// one and sets |*out_bool| to the resulting value. Otherwise, it returns zero. +// X509V3_get_value_bool decodes `value` as a boolean. On success, it returns +// one and sets `*out_bool` to the resulting value. Otherwise, it returns zero. int X509V3_get_value_bool(const CONF_VALUE *value, ASN1_BOOLEAN *out_bool); -// X509V3_get_value_int decodes |value| as an integer. On success, it returns -// one and sets |*aint| to the resulting value. Otherwise, it returns zero. If -// |*aint| was non-NULL at the start of the function, it frees the previous +// X509V3_get_value_int decodes `value` as an integer. On success, it returns +// one and sets `*aint` to the resulting value. Otherwise, it returns zero. If +// `*aint` was non-NULL at the start of the function, it frees the previous // value before writing a new one. int X509V3_get_value_int(const CONF_VALUE *value, ASN1_INTEGER **aint); -// X509V3_get_section behaves like |NCONF_get_section| but queries |ctx|'s +// X509V3_get_section behaves like `NCONF_get_section` but queries `ctx`'s // config database. const STACK_OF(CONF_VALUE) *X509V3_get_section(const X509V3_CTX *ctx, const char *section); -// X509V3_add_value appends a |CONF_VALUE| containing |name| and |value| to -// |*extlist|. It returns one on success and zero on error. If |*extlist| is -// NULL, it sets |*extlist| to a newly-allocated |STACK_OF(CONF_VALUE)| -// containing the result. Either |name| or |value| may be NULL to omit the +// X509V3_add_value appends a `CONF_VALUE` containing `name` and `value` to +// `*extlist`. It returns one on success and zero on error. If `*extlist` is +// NULL, it sets `*extlist` to a newly-allocated `STACK_OF(CONF_VALUE)` +// containing the result. Either `name` or `value` may be NULL to omit the // field. // -// On failure, if |*extlist| was NULL, |*extlist| will remain NULL when the +// On failure, if `*extlist` was NULL, `*extlist` will remain NULL when the // function returns. int X509V3_add_value(const char *name, const char *value, STACK_OF(CONF_VALUE) **extlist); -// X509V3_add_value_bool behaves like |X509V3_add_value| but stores the value -// "TRUE" if |asn1_bool| is non-zero and "FALSE" otherwise. +// X509V3_add_value_bool behaves like `X509V3_add_value` but stores the value +// "TRUE" if `asn1_bool` is non-zero and "FALSE" otherwise. int X509V3_add_value_bool(const char *name, int asn1_bool, STACK_OF(CONF_VALUE) **extlist); -// X509V3_add_value_bool behaves like |X509V3_add_value| but stores a string -// representation of |aint|. Note this string representation may be decimal or -// hexadecimal, depending on the size of |aint|. +// X509V3_add_value_bool behaves like `X509V3_add_value` but stores a string +// representation of `aint`. Note this string representation may be decimal or +// hexadecimal, depending on the size of `aint`. int X509V3_add_value_int(const char *name, const ASN1_INTEGER *aint, STACK_OF(CONF_VALUE) **extlist); @@ -509,7 +622,7 @@ 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 +// 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. // @@ -517,8 +630,8 @@ STACK_OF(CONF_VALUE) *X509V3_parse_list(const char *line); OPENSSL_EXPORT 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. +// X509_VERIFY_PARAM_lookup returns a pre-defined `X509_VERIFY_PARAM` named by +// `name`, or NULL if no such name is defined. const X509_VERIFY_PARAM *X509_VERIFY_PARAM_lookup(const char *name); GENERAL_NAME *v2i_GENERAL_NAME(const X509V3_EXT_METHOD *method, @@ -531,9 +644,7 @@ GENERAL_NAMES *v2i_GENERAL_NAMES(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, const STACK_OF(CONF_VALUE) *nval); -// TODO(https://crbug.com/boringssl/407): Make |issuer| const once the -// |X509_NAME| issue is resolved. -int X509_check_akid(X509 *issuer, const AUTHORITY_KEYID *akid); +int X509_check_akid(const X509 *issuer, const AUTHORITY_KEYID *akid); int X509_is_valid_trust_id(int trust); @@ -542,9 +653,69 @@ 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); -#if defined(__cplusplus) -} // extern C -#endif +// x509_marshal_name marshals `in` as a DER-encoded, X.509 Name and writes the +// result to `out`. It returns one on success and zero on error. +int x509_marshal_name(CBB *out, const X509_NAME *in); -#endif // OPENSSL_HEADER_X509_INTERNAL_H +const X509NameCache *x509_name_get_cache(const X509_NAME *name); +void x509_name_invalidate_cache(X509_NAME *name); + +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. +bool x509_is_merkle_tree_ca(const X509 *x509); + +// x509_evaluate_mtc_subtree_inclusion_proof carries out the procedure in +// section 4.3.2 of draft-ietf-plants-merkle-tree-certs to evaluate a subtree +// inclusion proof for an entry at index `index` with hash `entry_hash` of a +// subtree defined by [`subtree_start`, `subtree_end`). The `inclusion_proof` to +// be evaluated is passed as a byte array consisting of concatenated hashes +// produced from the `log_hash` algorithm. This function returns true if +// inclusion proof evaluation succeeded, and if so, writes the expected subtree +// hash for the specified subtree containing the entry to `out`, which must be +// the right size for `log_hash`. It returns false on error, including if the +// inclusion proof fails to evaluate. +bool x509_evaluate_mtc_subtree_inclusion_proof( + Span out, const EVP_MD *log_hash, + Span inclusion_proof, uint64_t index, + Span entry_hash, uint64_t subtree_start, + 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); + + +// Standard extensions. + +extern const X509V3_EXT_METHOD v3_bcons, v3_nscert, v3_key_usage, v3_ext_ku; +extern const X509V3_EXT_METHOD v3_info, v3_sinfo; +extern const X509V3_EXT_METHOD v3_skey_id, v3_akey_id; +extern const X509V3_EXT_METHOD v3_subject_alt_name, v3_issuer_alt_name, + v3_certificate_issuer; +extern const X509V3_EXT_METHOD v3_netscape_base_url, v3_netscape_revocation_url, + v3_netscape_ca_revocation_url, v3_netscape_renewal_url, + v3_netscape_ca_policy_url, v3_netscape_ssl_server_name, v3_netscape_comment; +extern const X509V3_EXT_METHOD v3_crl_num, v3_crl_reason, v3_crl_invdate; +extern const X509V3_EXT_METHOD v3_delta_crl, v3_cpols, v3_crld, v3_freshest_crl; +extern const X509V3_EXT_METHOD v3_ocsp_nocheck; +extern const X509V3_EXT_METHOD v3_crl_hold; +extern const X509V3_EXT_METHOD v3_policy_mappings, v3_policy_constraints; +extern const X509V3_EXT_METHOD v3_name_constraints, v3_inhibit_anyp, v3_idp; +extern const X509V3_EXT_METHOD v3_addr, v3_asid; + +BSSL_NAMESPACE_END + + +#endif // OPENSSL_HEADER_CRYPTO_X509_INTERNAL_H diff --git a/Sources/CNIOBoringSSL/crypto/x509/name_print.cc b/Sources/CNIOBoringSSL/crypto/x509/name_print.cc index a913ca65..c2f20b2e 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/name_print.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/name_print.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -19,11 +24,11 @@ static int maybe_write(BIO *out, const void *buf, int len) { - // If |out| is NULL, ignore the output but report the length. - return out == NULL || BIO_write(out, buf, len) == 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|. +// do_indent prints `indent` spaces to `out`. static int do_indent(BIO *out, int indent) { for (int i = 0; i < indent; i++) { if (!maybe_write(out, " ", 1)) { @@ -39,8 +44,6 @@ static int do_indent(BIO *out, int indent) { static int do_name_ex(BIO *out, const X509_NAME *n, int indent, unsigned long flags) { int prev = -1, orflags; - char objtmp[80]; - const char *objbuf; int outlen, len; const char *sep_dn, *sep_mv, *sep_eq; int sep_dn_len, sep_mv_len, sep_eq_len; @@ -124,13 +127,17 @@ static int do_name_ex(BIO *out, const X509_NAME *n, int indent, const ASN1_OBJECT *fn = X509_NAME_ENTRY_get_object(ent); const ASN1_STRING *val = X509_NAME_ENTRY_get_data(ent); assert((flags & XN_FLAG_FN_MASK) == XN_FLAG_FN_SN); + // Print the short name if available, otherwise serialize the OID. + char objtmp[80]; + const char *objbuf = nullptr; int fn_nid = OBJ_obj2nid(fn); - if (fn_nid == NID_undef) { - OBJ_obj2txt(objtmp, sizeof(objtmp), fn, 1); - objbuf = objtmp; - } else { + if (fn_nid != NID_undef) { objbuf = OBJ_nid2sn(fn_nid); } + if (objbuf == nullptr) { + OBJ_obj2txt(objtmp, sizeof(objtmp), fn, /*always_return_oid=*/1); + objbuf = objtmp; + } int objlen = strlen(objbuf); if (!maybe_write(out, objbuf, objlen) || !maybe_write(out, sep_eq, sep_eq_len)) { @@ -165,12 +172,12 @@ int X509_NAME_print_ex(BIO *out, const X509_NAME *nm, int indent, int X509_NAME_print_ex_fp(FILE *fp, const X509_NAME *nm, int indent, unsigned long flags) { - BIO *bio = NULL; - if (fp != NULL) { - // If |fp| is NULL, this function returns the number of bytes without + BIO *bio = nullptr; + if (fp != nullptr) { + // If `fp` is NULL, this function returns the number of bytes without // writing. bio = BIO_new_fp(fp, BIO_NOCLOSE); - if (bio == NULL) { + if (bio == nullptr) { return -1; } } diff --git a/Sources/CNIOBoringSSL/crypto/x509/policy.cc b/Sources/CNIOBoringSSL/crypto/x509/policy.cc index 72d40347..16df1e79 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/policy.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/policy.cc @@ -1,54 +1,78 @@ -/* Copyright 2022 The BoringSSL Authors - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +// Copyright 2022 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 "../internal.h" +#include "../mem_internal.h" #include "internal.h" -// This file computes the X.509 policy tree, as described in RFC 5280, section -// 6.1. It differs in that: +BSSL_NAMESPACE_BEGIN +namespace { + +// This file computes the X.509 policy graph, as described in RFC 9618. +// Implementation notes: // // (1) It does not track "qualifier_set". This is not needed as it is not // output by this implementation. // -// (2) It builds a directed acyclic graph, rather than a tree. When a given -// policy matches multiple parents, RFC 5280 makes a separate node for -// each parent. This representation condenses them into one node with -// multiple parents. Thus we refer to this structure as a "policy graph", -// rather than a "policy tree". -// -// (3) "expected_policy_set" is not tracked explicitly and built temporarily +// (2) "expected_policy_set" is not tracked explicitly and built temporarily // as part of building the graph. // -// (4) anyPolicy nodes are not tracked explicitly. +// (3) anyPolicy nodes are not tracked explicitly. // -// (5) Some pruning steps are deferred to when policies are evaluated, as a +// (4) Some pruning steps are deferred to when policies are evaluated, as a // reachability pass. -// An X509_POLICY_NODE is a node in the policy graph. It corresponds to a node +bool is_any_policy(const ASN1_OBJECT *obj) { + return OBJ_obj2nid(obj) == NID_any_policy; +} + +// An X509PolicyNode is a node in the policy graph. It corresponds to a node // from RFC 5280, section 6.1.2, step (a), but we store some fields differently. -typedef struct x509_policy_node_st { +struct X509PolicyNode { + static std::optional Create(const ASN1_OBJECT *policy) { + assert(!is_any_policy(policy)); + X509PolicyNode node; + node.policy.reset(OBJ_dup(policy)); + if (node.policy == nullptr) { + return std::nullopt; + } + return node; + } + + bool operator<(const X509PolicyNode &other) const { + return OBJ_cmp(policy.get(), other.policy.get()) < 0; + } + + bool parent_is_any_policy() const { return parent_policies.empty(); } + // policy is the "valid_policy" field from RFC 5280. - ASN1_OBJECT *policy; + UniquePtr policy; // parent_policies, if non-empty, is the list of "valid_policy" values for all // nodes which are a parent of this node. In this case, no entry in this list @@ -56,625 +80,502 @@ typedef struct x509_policy_node_st { // duplicates if the corresponding certificate had duplicate mappings. // // If empty, this node has a single parent, anyPolicy. The node is then a root - // policies, and is in authorities-constrained-policy-set if it has a path to - // a leaf node. + // policy, and is in authorities-constrained-policy-set if it has a path to a + // leaf node. // // Note it is not possible for a policy to have both anyPolicy and a // concrete policy as a parent. Section 6.1.3, step (d.1.ii) only runs if // there was no match in step (d.1.i). We do not need to represent a parent // list of, say, {anyPolicy, OID1, OID2}. - STACK_OF(ASN1_OBJECT) *parent_policies; + Vector> parent_policies; - // mapped is one if this node matches a policy mapping in the certificate and - // zero otherwise. - int mapped; + // mapped is whether this node matches a policy mapping in the certificate. + bool mapped = false; - // reachable is one if this node is reachable from some valid policy in the - // end-entity certificate. It is computed during |has_explicit_policy|. - int reachable; -} X509_POLICY_NODE; + // reachable is whether this node is reachable from some valid policy in the + // end-entity certificate. It is computed during `has_explicit_policy`. + bool reachable = false; +}; -DEFINE_STACK_OF(X509_POLICY_NODE) - -// An X509_POLICY_LEVEL is the collection of nodes at the same depth in the +// An X509PolicyLevel is the collection of nodes at the same depth in the // policy graph. This structure can also be used to represent a level's -// "expected_policy_set" values. See |process_policy_mappings|. -typedef struct x509_policy_level_st { +// "expected_policy_set" values. See `process_policy_mappings`. +class X509PolicyLevel { + public: + bool has_any_policy() const { return has_any_policy_; } + bool is_empty() const { return !has_any_policy_ && nodes_.empty(); } + Span nodes() const { return nodes_; } + + void set_has_any_policy(bool v) { has_any_policy_ = v; } + + // Although this is mutable, callers may not modify the node's policy. + Span nodes() { return Span(nodes_); } + + void Clear() { + has_any_policy_ = false; + nodes_.clear(); + } + + // Find returns the node corresponding to `policy`, or nullptr if none exists. + X509PolicyNode *Find(const ASN1_OBJECT *policy) { + // The list is sorted, so we can binary search. + auto it = std::lower_bound( + nodes_.begin(), nodes_.end(), policy, + [](const X509PolicyNode &node, const ASN1_OBJECT *obj) { + return OBJ_cmp(node.policy.get(), obj) < 0; + }); + if (it == nodes_.end() || OBJ_cmp(it->policy.get(), policy) != 0) { + return nullptr; + } + return &*it; + } + + // AddNodes adds the nodes in `nodes`. It returns true on success and false on + // error. No policy in `nodes` may already be present. This method leaves + // the objects in `nodes` in a moved-from state. + // + // This method re-sorts the nodes, so it runs in time proportional to the + // total size of the level. However, each level is only added to three times + // in the course of policy validation. + bool AddNodes(Span nodes) { + if (!nodes_.AppendMove(nodes)) { + return false; + } + std::sort(nodes_.begin(), nodes_.end()); +#if !defined(NDEBUG) + // There should be no duplicate nodes. + for (size_t i = 1; i < nodes_.size(); i++) { + assert(OBJ_cmp(nodes_[i - 1].policy.get(), nodes_[i].policy.get()) != 0); + } +#endif + return true; + } + + // EraseNodesIf removes all nodes that satisfy the predicate `pred`. + template + void EraseNodesIf(Pred pred) { + nodes_.EraseIf(pred); + } + + private: // nodes is the list of nodes at this depth, except for the anyPolicy node, if // any. This list is sorted by policy OID for efficient lookup. - STACK_OF(X509_POLICY_NODE) *nodes; + Vector nodes_; - // has_any_policy is one if there is an anyPolicy node at this depth, and zero - // otherwise. - int has_any_policy; -} X509_POLICY_LEVEL; + // has_any_policy is whether there is an anyPolicy node at this depth. + bool has_any_policy_ = false; +}; -DEFINE_STACK_OF(X509_POLICY_LEVEL) - -static int is_any_policy(const ASN1_OBJECT *obj) { - return OBJ_obj2nid(obj) == NID_any_policy; -} - -static void x509_policy_node_free(X509_POLICY_NODE *node) { - if (node != NULL) { - ASN1_OBJECT_free(node->policy); - sk_ASN1_OBJECT_pop_free(node->parent_policies, ASN1_OBJECT_free); - OPENSSL_free(node); - } -} - -static X509_POLICY_NODE *x509_policy_node_new(const ASN1_OBJECT *policy) { - assert(!is_any_policy(policy)); - X509_POLICY_NODE *node = reinterpret_cast( - OPENSSL_zalloc(sizeof(X509_POLICY_NODE))); - if (node == NULL) { - return NULL; - } - node->policy = OBJ_dup(policy); - node->parent_policies = sk_ASN1_OBJECT_new_null(); - if (node->policy == NULL || node->parent_policies == NULL) { - x509_policy_node_free(node); - return NULL; - } - return node; -} - -static int x509_policy_node_cmp(const X509_POLICY_NODE *const *a, - const X509_POLICY_NODE *const *b) { - return OBJ_cmp((*a)->policy, (*b)->policy); -} - -static void x509_policy_level_free(X509_POLICY_LEVEL *level) { - if (level != NULL) { - sk_X509_POLICY_NODE_pop_free(level->nodes, x509_policy_node_free); - OPENSSL_free(level); - } -} - -static X509_POLICY_LEVEL *x509_policy_level_new(void) { - X509_POLICY_LEVEL *level = reinterpret_cast( - OPENSSL_zalloc(sizeof(X509_POLICY_LEVEL))); - if (level == NULL) { - return NULL; - } - level->nodes = sk_X509_POLICY_NODE_new(x509_policy_node_cmp); - if (level->nodes == NULL) { - x509_policy_level_free(level); - return NULL; - } - return level; -} - -static int x509_policy_level_is_empty(const X509_POLICY_LEVEL *level) { - return !level->has_any_policy && sk_X509_POLICY_NODE_num(level->nodes) == 0; -} - -static void x509_policy_level_clear(X509_POLICY_LEVEL *level) { - level->has_any_policy = 0; - for (size_t i = 0; i < sk_X509_POLICY_NODE_num(level->nodes); i++) { - x509_policy_node_free(sk_X509_POLICY_NODE_value(level->nodes, i)); - } - sk_X509_POLICY_NODE_zero(level->nodes); -} - -// x509_policy_level_find returns the node in |level| corresponding to |policy|, -// or NULL if none exists. -static X509_POLICY_NODE *x509_policy_level_find(X509_POLICY_LEVEL *level, - const ASN1_OBJECT *policy) { - assert(sk_X509_POLICY_NODE_is_sorted(level->nodes)); - X509_POLICY_NODE node; - node.policy = (ASN1_OBJECT *)policy; - size_t idx; - if (!sk_X509_POLICY_NODE_find(level->nodes, &idx, &node)) { - return NULL; - } - return sk_X509_POLICY_NODE_value(level->nodes, idx); -} - -// x509_policy_level_add_nodes adds the nodes in |nodes| to |level|. It returns -// one on success and zero on error. No policy in |nodes| may already be present -// in |level|. This function modifies |nodes| to avoid making a copy, but the -// caller is still responsible for releasing |nodes| itself. -// -// This function is used to add nodes to |level| in bulk, and avoid resorting -// |level| after each addition. -static int x509_policy_level_add_nodes(X509_POLICY_LEVEL *level, - STACK_OF(X509_POLICY_NODE) *nodes) { - for (size_t i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) { - X509_POLICY_NODE *node = sk_X509_POLICY_NODE_value(nodes, i); - if (!sk_X509_POLICY_NODE_push(level->nodes, node)) { - return 0; - } - sk_X509_POLICY_NODE_set(nodes, i, NULL); - } - sk_X509_POLICY_NODE_sort(level->nodes); - -#if !defined(NDEBUG) - // There should be no duplicate nodes. - for (size_t i = 1; i < sk_X509_POLICY_NODE_num(level->nodes); i++) { - assert(OBJ_cmp(sk_X509_POLICY_NODE_value(level->nodes, i - 1)->policy, - sk_X509_POLICY_NODE_value(level->nodes, i)->policy) != 0); - } -#endif - return 1; -} - -static int policyinfo_cmp(const POLICYINFO *const *a, - const POLICYINFO *const *b) { +int policyinfo_cmp(const POLICYINFO *const *a, const POLICYINFO *const *b) { return OBJ_cmp((*a)->policyid, (*b)->policyid); } -static int delete_if_not_in_policies(X509_POLICY_NODE *node, void *data) { - const CERTIFICATEPOLICIES *policies = - reinterpret_cast(data); - assert(sk_POLICYINFO_is_sorted(policies)); - POLICYINFO info; - info.policyid = node->policy; - if (sk_POLICYINFO_find(policies, NULL, &info)) { - return 0; - } - x509_policy_node_free(node); - return 1; -} - -// process_certificate_policies updates |level| to incorporate |x509|'s +// process_certificate_policies updates `level` to incorporate `x509`'s // certificate policies extension. This implements steps (d) and (e) of RFC -// 5280, section 6.1.3. |level| must contain the previous level's +// 5280, section 6.1.3. `level` must contain the previous level's // "expected_policy_set" information. For all but the top-most level, this is -// the output of |process_policy_mappings|. |any_policy_allowed| specifies +// the output of `process_policy_mappings`. `any_policy_allowed` specifies // whether anyPolicy is allowed or inhibited, taking into account the exception // for self-issued certificates. -static int process_certificate_policies(const X509 *x509, - X509_POLICY_LEVEL *level, - int any_policy_allowed) { - int ret = 0; +bool process_certificate_policies(const X509 *x509, X509PolicyLevel *level, + int any_policy_allowed) { int critical; - STACK_OF(X509_POLICY_NODE) *new_nodes = NULL; - CERTIFICATEPOLICIES *policies = reinterpret_cast( - X509_get_ext_d2i(x509, NID_certificate_policies, &critical, NULL)); - - { - if (policies == NULL) { - if (critical != -1) { - return 0; // Syntax error in the extension. - } - - // RFC 5280, section 6.1.3, step (e). - x509_policy_level_clear(level); - return 1; + UniquePtr policies( + reinterpret_cast(X509_get_ext_d2i( + x509, NID_certificate_policies, &critical, nullptr))); + if (policies == nullptr) { + if (critical != -1) { + return false; // Syntax error in the extension. } - // certificatePolicies may not be empty. See RFC 5280, section 4.2.1.4. - // TODO(https://crbug.com/boringssl/443): Move this check into the parser. - if (sk_POLICYINFO_num(policies) == 0) { - OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION); - goto err; - } - - sk_POLICYINFO_set_cmp_func(policies, policyinfo_cmp); - sk_POLICYINFO_sort(policies); - int cert_has_any_policy = 0; - for (size_t i = 0; i < sk_POLICYINFO_num(policies); i++) { - const POLICYINFO *policy = sk_POLICYINFO_value(policies, i); - if (is_any_policy(policy->policyid)) { - cert_has_any_policy = 1; - } - if (i > 0 && OBJ_cmp(sk_POLICYINFO_value(policies, i - 1)->policyid, - policy->policyid) == 0) { - // Per RFC 5280, section 4.2.1.4, |policies| may not have duplicates. - OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION); - goto err; - } - } - - // This does the same thing as RFC 5280, section 6.1.3, step (d), though in - // a slighty different order. |level| currently contains - // "expected_policy_set" values of the previous level. See - // |process_policy_mappings| for details. - const int previous_level_has_any_policy = level->has_any_policy; - - // First, we handle steps (d.1.i) and (d.2). The net effect of these two - // steps is to intersect |level| with |policies|, ignoring anyPolicy if it - // is inhibited. - if (!cert_has_any_policy || !any_policy_allowed) { - sk_X509_POLICY_NODE_delete_if(level->nodes, delete_if_not_in_policies, - policies); - level->has_any_policy = 0; - } - - // Step (d.1.ii) may attach new nodes to the previous level's anyPolicy - // node. - if (previous_level_has_any_policy) { - new_nodes = sk_X509_POLICY_NODE_new_null(); - if (new_nodes == NULL) { - goto err; - } - for (size_t i = 0; i < sk_POLICYINFO_num(policies); i++) { - const POLICYINFO *policy = sk_POLICYINFO_value(policies, i); - // Though we've reordered the steps slightly, |policy| is in |level| if - // and only if it would have been a match in step (d.1.ii). - if (!is_any_policy(policy->policyid) && - x509_policy_level_find(level, policy->policyid) == NULL) { - X509_POLICY_NODE *node = x509_policy_node_new(policy->policyid); - if (node == NULL || // - !sk_X509_POLICY_NODE_push(new_nodes, node)) { - x509_policy_node_free(node); - goto err; - } - } - } - if (!x509_policy_level_add_nodes(level, new_nodes)) { - goto err; - } - } - - ret = 1; + // RFC 5280, section 6.1.3, step (e). + level->Clear(); + return true; } -err: - sk_X509_POLICY_NODE_pop_free(new_nodes, x509_policy_node_free); - CERTIFICATEPOLICIES_free(policies); - return ret; + // certificatePolicies may not be empty. See RFC 5280, section 4.2.1.4. + // TODO(https://crbug.com/boringssl/443): Move this check into the parser. + if (sk_POLICYINFO_num(policies.get()) == 0) { + OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION); + return false; + } + + sk_POLICYINFO_set_cmp_func(policies.get(), policyinfo_cmp); + sk_POLICYINFO_sort(policies.get()); + bool cert_has_any_policy = false; + for (size_t i = 0; i < sk_POLICYINFO_num(policies.get()); i++) { + const POLICYINFO *policy = sk_POLICYINFO_value(policies.get(), i); + if (is_any_policy(policy->policyid)) { + cert_has_any_policy = true; + } + if (i > 0 && OBJ_cmp(sk_POLICYINFO_value(policies.get(), i - 1)->policyid, + policy->policyid) == 0) { + // Per RFC 5280, section 4.2.1.4, `policies` may not have duplicates. + OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION); + return false; + } + } + + // This does the same thing as RFC 5280, section 6.1.3, step (d), though in + // a slightly different order. `level` currently contains + // "expected_policy_set" values of the previous level. See + // `process_policy_mappings` for details. + const bool previous_level_has_any_policy = level->has_any_policy(); + + // First, we handle steps (d.1.i) and (d.2). The net effect of these two + // steps is to intersect `level` with `policies`, ignoring anyPolicy if it + // is inhibited. + if (!cert_has_any_policy || !any_policy_allowed) { + level->EraseNodesIf([&](const X509PolicyNode &node) { + assert(sk_POLICYINFO_is_sorted(policies.get())); + // Erase the node if it not present in the current certificate. + POLICYINFO info; + info.policyid = node.policy.get(); + return !sk_POLICYINFO_find(policies.get(), nullptr, &info); + }); + level->set_has_any_policy(false); + } + + // Step (d.1.ii) may attach new nodes to the previous level's anyPolicy + // node. + if (previous_level_has_any_policy) { + Vector new_nodes; + for (const POLICYINFO *policy : policies.get()) { + // Though we've reordered the steps slightly, `policy` is in `level` if + // and only if it would have been a match in step (d.1.ii). + if (!is_any_policy(policy->policyid) && + level->Find(policy->policyid) == nullptr) { + auto node = X509PolicyNode::Create(policy->policyid); + if (!node.has_value() || !new_nodes.Push(*std::move(node))) { + return false; + } + } + } + if (!level->AddNodes(Span(new_nodes))) { + return false; + } + } + + return true; } -static int compare_issuer_policy(const POLICY_MAPPING *const *a, - const POLICY_MAPPING *const *b) { +int compare_issuer_policy(const POLICY_MAPPING *const *a, + const POLICY_MAPPING *const *b) { return OBJ_cmp((*a)->issuerDomainPolicy, (*b)->issuerDomainPolicy); } -static int compare_subject_policy(const POLICY_MAPPING *const *a, - const POLICY_MAPPING *const *b) { +int compare_subject_policy(const POLICY_MAPPING *const *a, + const POLICY_MAPPING *const *b) { return OBJ_cmp((*a)->subjectDomainPolicy, (*b)->subjectDomainPolicy); } -static int delete_if_mapped(X509_POLICY_NODE *node, void *data) { - const POLICY_MAPPINGS *mappings = reinterpret_cast(data); - // |mappings| must have been sorted by |compare_issuer_policy|. - assert(sk_POLICY_MAPPING_is_sorted(mappings)); - POLICY_MAPPING mapping; - mapping.issuerDomainPolicy = node->policy; - if (!sk_POLICY_MAPPING_find(mappings, /*out_index=*/NULL, &mapping)) { - return 0; - } - x509_policy_node_free(node); - return 1; -} - -// process_policy_mappings processes the policy mappings extension of |cert|, -// whose corresponding graph level is |level|. |mapping_allowed| specifies +// process_policy_mappings processes the policy mappings extension of `cert`, +// whose corresponding graph level is `level`. `mapping_allowed` specifies // whether policy mapping is inhibited at this point. On success, it returns an -// |X509_POLICY_LEVEL| containing the "expected_policy_set" for |level|. On -// error, it returns NULL. This implements steps (a) and (b) of RFC 5280, +// `X509PolicyLevel` containing the "expected_policy_set" for `level`. On error, +// it returns std::nullopt. This implements steps (a) and (b) of RFC 5280, // section 6.1.4. // -// We represent the "expected_policy_set" as an |X509_POLICY_LEVEL|. -// |has_any_policy| indicates whether there is an anyPolicy node with +// We represent the "expected_policy_set" as an `X509PolicyLevel`. +// `has_any_policy` indicates whether there is an anyPolicy node with // "expected_policy_set" of {anyPolicy}. If a node with policy oid P1 contains // P2 in its "expected_policy_set", the level will contain a node of policy P2 -// with P1 in |parent_policies|. +// with P1 in `parent_policies`. // -// This is equivalent to the |X509_POLICY_LEVEL| that would result if the next -// certificats contained anyPolicy. |process_certificate_policies| will filter +// This is equivalent to the `X509PolicyLevel` that would result if the next +// certificates contained anyPolicy. `process_certificate_policies` will filter // this result down to compute the actual level. -static X509_POLICY_LEVEL *process_policy_mappings(const X509 *cert, - X509_POLICY_LEVEL *level, - int mapping_allowed) { - int ok = 0; - STACK_OF(X509_POLICY_NODE) *new_nodes = NULL; - X509_POLICY_LEVEL *next = NULL; +std::optional process_policy_mappings(const X509 *cert, + X509PolicyLevel *level, + bool mapping_allowed) { int critical; - POLICY_MAPPINGS *mappings = reinterpret_cast( - X509_get_ext_d2i(cert, NID_policy_mappings, &critical, NULL)); + UniquePtr mappings(reinterpret_cast( + X509_get_ext_d2i(cert, NID_policy_mappings, &critical, nullptr))); + if (mappings == nullptr && critical != -1) { + // Syntax error in the policy mappings extension. + return std::nullopt; + } - { - if (mappings == NULL && critical != -1) { - // Syntax error in the policy mappings extension. - goto err; + if (mappings != nullptr) { + // PolicyMappings may not be empty. See RFC 5280, section 4.2.1.5. + // TODO(https://crbug.com/boringssl/443): Move this check into the parser. + if (sk_POLICY_MAPPING_num(mappings.get()) == 0) { + OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION); + return std::nullopt; } - if (mappings != NULL) { - // PolicyMappings may not be empty. See RFC 5280, section 4.2.1.5. - // TODO(https://crbug.com/boringssl/443): Move this check into the parser. - if (sk_POLICY_MAPPING_num(mappings) == 0) { - OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION); - goto err; + // RFC 5280, section 6.1.4, step (a). + for (const POLICY_MAPPING *mapping : mappings.get()) { + if (is_any_policy(mapping->issuerDomainPolicy) || + is_any_policy(mapping->subjectDomainPolicy)) { + return std::nullopt; } + } - // RFC 5280, section 6.1.4, step (a). - for (size_t i = 0; i < sk_POLICY_MAPPING_num(mappings); i++) { - POLICY_MAPPING *mapping = sk_POLICY_MAPPING_value(mappings, i); - if (is_any_policy(mapping->issuerDomainPolicy) || - is_any_policy(mapping->subjectDomainPolicy)) { - goto err; + // Sort to group by issuerDomainPolicy. + sk_POLICY_MAPPING_set_cmp_func(mappings.get(), compare_issuer_policy); + sk_POLICY_MAPPING_sort(mappings.get()); + + if (mapping_allowed) { + // Mark nodes as mapped, and add any nodes to `level` which may be + // needed as part of RFC 5280, section 6.1.4, step (b.1). + Vector new_nodes; + const ASN1_OBJECT *last_policy = nullptr; + for (const POLICY_MAPPING *mapping : mappings.get()) { + // There may be multiple mappings with the same `issuerDomainPolicy`. + if (last_policy != nullptr && + OBJ_cmp(mapping->issuerDomainPolicy, last_policy) == 0) { + continue; } - } + last_policy = mapping->issuerDomainPolicy; - // Sort to group by issuerDomainPolicy. - sk_POLICY_MAPPING_set_cmp_func(mappings, compare_issuer_policy); - sk_POLICY_MAPPING_sort(mappings); - - if (mapping_allowed) { - // Mark nodes as mapped, and add any nodes to |level| which may be - // needed as part of RFC 5280, section 6.1.4, step (b.1). - new_nodes = sk_X509_POLICY_NODE_new_null(); - if (new_nodes == NULL) { - goto err; - } - const ASN1_OBJECT *last_policy = NULL; - for (size_t i = 0; i < sk_POLICY_MAPPING_num(mappings); i++) { - const POLICY_MAPPING *mapping = sk_POLICY_MAPPING_value(mappings, i); - // There may be multiple mappings with the same |issuerDomainPolicy|. - if (last_policy != NULL && - OBJ_cmp(mapping->issuerDomainPolicy, last_policy) == 0) { + X509PolicyNode *node = level->Find(mapping->issuerDomainPolicy); + if (node != nullptr) { + node->mapped = true; + } else { + if (!level->has_any_policy()) { continue; } - last_policy = mapping->issuerDomainPolicy; - - X509_POLICY_NODE *node = - x509_policy_level_find(level, mapping->issuerDomainPolicy); - if (node == NULL) { - if (!level->has_any_policy) { - continue; - } - node = x509_policy_node_new(mapping->issuerDomainPolicy); - if (node == NULL || // - !sk_X509_POLICY_NODE_push(new_nodes, node)) { - x509_policy_node_free(node); - goto err; - } + auto new_node = X509PolicyNode::Create(mapping->issuerDomainPolicy); + if (!new_node.has_value()) { + return std::nullopt; + } + new_node->mapped = true; + if (!new_nodes.Push(*std::move(new_node))) { + return std::nullopt; } - node->mapped = 1; - } - if (!x509_policy_level_add_nodes(level, new_nodes)) { - goto err; - } - } else { - // RFC 5280, section 6.1.4, step (b.2). If mapping is inhibited, delete - // all mapped nodes. - sk_X509_POLICY_NODE_delete_if(level->nodes, delete_if_mapped, mappings); - sk_POLICY_MAPPING_pop_free(mappings, POLICY_MAPPING_free); - mappings = NULL; - } - } - - // If a node was not mapped, it retains the original "explicit_policy_set" - // value, itself. Add those to |mappings|. - if (mappings == NULL) { - mappings = sk_POLICY_MAPPING_new_null(); - if (mappings == NULL) { - goto err; - } - } - for (size_t i = 0; i < sk_X509_POLICY_NODE_num(level->nodes); i++) { - X509_POLICY_NODE *node = sk_X509_POLICY_NODE_value(level->nodes, i); - if (!node->mapped) { - POLICY_MAPPING *mapping = POLICY_MAPPING_new(); - if (mapping == NULL) { - goto err; - } - mapping->issuerDomainPolicy = OBJ_dup(node->policy); - mapping->subjectDomainPolicy = OBJ_dup(node->policy); - if (mapping->issuerDomainPolicy == NULL || - mapping->subjectDomainPolicy == NULL || - !sk_POLICY_MAPPING_push(mappings, mapping)) { - POLICY_MAPPING_free(mapping); - goto err; } } - } - - // Sort to group by subjectDomainPolicy. - sk_POLICY_MAPPING_set_cmp_func(mappings, compare_subject_policy); - sk_POLICY_MAPPING_sort(mappings); - - // Convert |mappings| to our "expected_policy_set" representation. - next = x509_policy_level_new(); - if (next == NULL) { - goto err; - } - next->has_any_policy = level->has_any_policy; - - X509_POLICY_NODE *last_node = NULL; - for (size_t i = 0; i < sk_POLICY_MAPPING_num(mappings); i++) { - POLICY_MAPPING *mapping = sk_POLICY_MAPPING_value(mappings, i); - // Skip mappings where |issuerDomainPolicy| does not appear in the graph. - if (!level->has_any_policy && - x509_policy_level_find(level, mapping->issuerDomainPolicy) == NULL) { - continue; + if (!level->AddNodes(Span(new_nodes))) { + return std::nullopt; } - - if (last_node == NULL || - OBJ_cmp(last_node->policy, mapping->subjectDomainPolicy) != 0) { - last_node = x509_policy_node_new(mapping->subjectDomainPolicy); - if (last_node == NULL || - !sk_X509_POLICY_NODE_push(next->nodes, last_node)) { - x509_policy_node_free(last_node); - goto err; - } - } - - if (!sk_ASN1_OBJECT_push(last_node->parent_policies, - mapping->issuerDomainPolicy)) { - goto err; - } - mapping->issuerDomainPolicy = NULL; + } else { + // RFC 5280, section 6.1.4, step (b.2). If mapping is inhibited, delete + // all mapped nodes. + level->EraseNodesIf([&](const X509PolicyNode &node) { + // `mappings` must have been sorted by `compare_issuer_policy`. + assert(sk_POLICY_MAPPING_is_sorted(mappings.get())); + // Check if the node was mapped. + POLICY_MAPPING mapping; + mapping.issuerDomainPolicy = node.policy.get(); + return sk_POLICY_MAPPING_find(mappings.get(), /*out_index=*/nullptr, + &mapping); + }); + // Dropping the mappings. + mappings = nullptr; } - - sk_X509_POLICY_NODE_sort(next->nodes); - ok = 1; } -err: - if (!ok) { - x509_policy_level_free(next); - next = NULL; + // If a node was not mapped, it retains the original "explicit_policy_set" + // value, itself. Add those to `mappings`. + if (mappings == nullptr) { + mappings.reset(sk_POLICY_MAPPING_new_null()); + if (mappings == nullptr) { + return std::nullopt; + } + } + for (const X509PolicyNode &node : level->nodes()) { + if (!node.mapped) { + UniquePtr mapping(POLICY_MAPPING_new()); + if (mapping == nullptr) { + return std::nullopt; + } + mapping->issuerDomainPolicy = OBJ_dup(node.policy.get()); + mapping->subjectDomainPolicy = OBJ_dup(node.policy.get()); + if (mapping->issuerDomainPolicy == nullptr || + mapping->subjectDomainPolicy == nullptr || + !PushToStack(mappings.get(), std::move(mapping))) { + return std::nullopt; + } + } } - sk_POLICY_MAPPING_pop_free(mappings, POLICY_MAPPING_free); - sk_X509_POLICY_NODE_pop_free(new_nodes, x509_policy_node_free); + // Sort to group by subjectDomainPolicy. + sk_POLICY_MAPPING_set_cmp_func(mappings.get(), compare_subject_policy); + sk_POLICY_MAPPING_sort(mappings.get()); + + // Convert `mappings` to our "expected_policy_set" representation. + Vector next_nodes; + for (POLICY_MAPPING *mapping : mappings.get()) { + // Skip mappings where `issuerDomainPolicy` does not appear in the graph. + if (!level->has_any_policy() && + level->Find(mapping->issuerDomainPolicy) == nullptr) { + continue; + } + + if (next_nodes.empty() || OBJ_cmp(next_nodes.back().policy.get(), + mapping->subjectDomainPolicy) != 0) { + auto new_node = X509PolicyNode::Create(mapping->subjectDomainPolicy); + if (!new_node.has_value() || !next_nodes.Push(*std::move(new_node))) { + return std::nullopt; + } + } + + // `mapping` is going to be destroyed, so steal its policy object. + UniquePtr policy( + std::exchange(mapping->issuerDomainPolicy, nullptr)); + if (!next_nodes.back().parent_policies.Push(std::move(policy))) { + return std::nullopt; + } + } + + X509PolicyLevel next; + next.set_has_any_policy(level->has_any_policy()); + if (!next.AddNodes(Span(next_nodes))) { + return std::nullopt; + } return next; } -// apply_skip_certs, if |skip_certs| is non-NULL, sets |*value| to the minimum -// of its current value and |skip_certs|. It returns one on success and zero if -// |skip_certs| is negative. -static int apply_skip_certs(const ASN1_INTEGER *skip_certs, size_t *value) { - if (skip_certs == NULL) { - return 1; +// apply_skip_certs, if `skip_certs` is non-NULL, sets `*value` to the minimum +// of its current value and `skip_certs`. It returns true on success and false +// if `skip_certs` is negative. +bool apply_skip_certs(const ASN1_INTEGER *skip_certs, size_t *value) { + if (skip_certs == nullptr) { + return true; } // TODO(https://crbug.com/boringssl/443): Move this check into the parser. if (skip_certs->type & V_ASN1_NEG) { OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION); - return 0; + return false; } - // If |skip_certs| does not fit in |uint64_t|, it must exceed |*value|. + // If `skip_certs` does not fit in `uint64_t`, it must exceed `*value`. uint64_t u64; if (ASN1_INTEGER_get_uint64(&u64, skip_certs) && u64 < *value) { *value = (size_t)u64; } ERR_clear_error(); - return 1; + return true; } -// process_policy_constraints updates |*explicit_policy|, |*policy_mapping|, and -// |*inhibit_any_policy| according to |x509|'s policy constraints and inhibit +// process_policy_constraints updates `*explicit_policy`, `*policy_mapping`, and +// `*inhibit_any_policy` according to `x509`'s policy constraints and inhibit // anyPolicy extensions. It returns one on success and zero on error. This // implements steps (i) and (j) of RFC 5280, section 6.1.4. -static int process_policy_constraints(const X509 *x509, size_t *explicit_policy, - size_t *policy_mapping, - size_t *inhibit_any_policy) { +bool process_policy_constraints(const X509 *x509, size_t *explicit_policy, + size_t *policy_mapping, + size_t *inhibit_any_policy) { int critical; - POLICY_CONSTRAINTS *constraints = reinterpret_cast( - X509_get_ext_d2i(x509, NID_policy_constraints, &critical, NULL)); - if (constraints == NULL && critical != -1) { - return 0; + UniquePtr constraints( + reinterpret_cast( + X509_get_ext_d2i(x509, NID_policy_constraints, &critical, nullptr))); + if (constraints == nullptr && critical != -1) { + return false; } - if (constraints != NULL) { - if (constraints->requireExplicitPolicy == NULL && - constraints->inhibitPolicyMapping == NULL) { + if (constraints != nullptr) { + if (constraints->requireExplicitPolicy == nullptr && + constraints->inhibitPolicyMapping == nullptr) { // Per RFC 5280, section 4.2.1.11, at least one of the fields must be // present. OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION); - POLICY_CONSTRAINTS_free(constraints); - return 0; + return false; } - int ok = - apply_skip_certs(constraints->requireExplicitPolicy, explicit_policy) && - apply_skip_certs(constraints->inhibitPolicyMapping, policy_mapping); - POLICY_CONSTRAINTS_free(constraints); - if (!ok) { - return 0; + if (!apply_skip_certs(constraints->requireExplicitPolicy, + explicit_policy) || + !apply_skip_certs(constraints->inhibitPolicyMapping, policy_mapping)) { + return false; } } - ASN1_INTEGER *inhibit_any_policy_ext = reinterpret_cast( - X509_get_ext_d2i(x509, NID_inhibit_any_policy, &critical, NULL)); - if (inhibit_any_policy_ext == NULL && critical != -1) { - return 0; + UniquePtr inhibit_any_policy_ext( + reinterpret_cast( + X509_get_ext_d2i(x509, NID_inhibit_any_policy, &critical, nullptr))); + if (inhibit_any_policy_ext == nullptr && critical != -1) { + return false; } - int ok = apply_skip_certs(inhibit_any_policy_ext, inhibit_any_policy); - ASN1_INTEGER_free(inhibit_any_policy_ext); - return ok; + return apply_skip_certs(inhibit_any_policy_ext.get(), inhibit_any_policy); } -// has_explicit_policy returns one if the set of authority-space policy OIDs -// |levels| has some non-empty intersection with |user_policies|, and zero +// has_explicit_policy returns true if the set of authority-space policy OIDs +// `levels` has some non-empty intersection with `user_policies`, and false // otherwise. This mirrors the logic in RFC 5280, section 6.1.5, step (g). This -// function modifies |levels| and should only be called at the end of policy +// function modifies `levels` and should only be called at the end of policy // evaluation. -static int has_explicit_policy(STACK_OF(X509_POLICY_LEVEL) *levels, - const STACK_OF(ASN1_OBJECT) *user_policies) { - assert(user_policies == NULL || sk_ASN1_OBJECT_is_sorted(user_policies)); +bool has_explicit_policy(Span levels, + const STACK_OF(ASN1_OBJECT) *user_policies) { + assert(user_policies == nullptr || sk_ASN1_OBJECT_is_sorted(user_policies)); // Step (g.i). If the policy graph is empty, the intersection is empty. - size_t num_levels = sk_X509_POLICY_LEVEL_num(levels); - X509_POLICY_LEVEL *level = sk_X509_POLICY_LEVEL_value(levels, num_levels - 1); - if (x509_policy_level_is_empty(level)) { - return 0; - } - - // If |user_policies| is empty, we interpret it as having a single anyPolicy - // value. The caller may also have supplied anyPolicy explicitly. - int user_has_any_policy = sk_ASN1_OBJECT_num(user_policies) == 0; - for (size_t i = 0; i < sk_ASN1_OBJECT_num(user_policies); i++) { - if (is_any_policy(sk_ASN1_OBJECT_value(user_policies, i))) { - user_has_any_policy = 1; - break; - } + if (levels.empty() || levels.back().is_empty()) { + return false; } // Step (g.ii). If the policy graph is not empty and the user set contains // anyPolicy, the intersection is the entire (non-empty) graph. - if (user_has_any_policy) { - return 1; + // + // If `user_policies` is empty, we interpret it as having a single anyPolicy + // value. The caller may also have supplied anyPolicy explicitly. + if (sk_ASN1_OBJECT_num(user_policies) == 0) { + return true; + } + for (const ASN1_OBJECT *user_policy : user_policies) { + if (is_any_policy(user_policy)) { + return true; + } } // Step (g.iii) does not delete anyPolicy nodes, so if the graph has // anyPolicy, some explicit policy will survive. The actual intersection may // synthesize some nodes in step (g.iii.3), but we do not return the policy // list itself, so we skip actually computing this. - if (level->has_any_policy) { - return 1; + if (levels.back().has_any_policy()) { + return true; } // We defer pruning the tree, so as we look for nodes with parent anyPolicy, // step (g.iii.1), we must limit to nodes reachable from the bottommost level. // Start by marking each of those nodes as reachable. - for (size_t i = 0; i < sk_X509_POLICY_NODE_num(level->nodes); i++) { - sk_X509_POLICY_NODE_value(level->nodes, i)->reachable = 1; + for (X509PolicyNode &node : levels.back().nodes()) { + node.reachable = true; } + const size_t num_levels = levels.size(); for (size_t i = num_levels - 1; i < num_levels; i--) { - level = sk_X509_POLICY_LEVEL_value(levels, i); - for (size_t j = 0; j < sk_X509_POLICY_NODE_num(level->nodes); j++) { - X509_POLICY_NODE *node = sk_X509_POLICY_NODE_value(level->nodes, j); - if (!node->reachable) { + X509PolicyLevel &level = levels[i]; + for (X509PolicyNode &node : level.nodes()) { + if (!node.reachable) { continue; } - if (sk_ASN1_OBJECT_num(node->parent_policies) == 0) { - // |node|'s parent is anyPolicy and is part of "valid_policy_node_set". - // If it exists in |user_policies|, the intersection is non-empty and we + if (node.parent_is_any_policy()) { + // `node`'s parent is anyPolicy and is part of "valid_policy_node_set". + // If it exists in `user_policies`, the intersection is non-empty and we // can return immediately. - if (sk_ASN1_OBJECT_find(user_policies, /*out_index=*/NULL, - node->policy)) { - return 1; + if (sk_ASN1_OBJECT_find(user_policies, /*out_index=*/nullptr, + node.policy.get())) { + return true; } } else if (i > 0) { - // |node|'s parents are concrete policies. Mark the parents reachable, + // `node`'s parents are concrete policies. Mark the parents reachable, // to be inspected by the next loop iteration. - X509_POLICY_LEVEL *prev = sk_X509_POLICY_LEVEL_value(levels, i - 1); - for (size_t k = 0; k < sk_ASN1_OBJECT_num(node->parent_policies); k++) { - X509_POLICY_NODE *parent = x509_policy_level_find( - prev, sk_ASN1_OBJECT_value(node->parent_policies, k)); - if (parent != NULL) { - parent->reachable = 1; + X509PolicyLevel &prev = levels[i - 1]; + for (const auto &parent_policy : node.parent_policies) { + X509PolicyNode *parent_node = prev.Find(parent_policy.get()); + if (parent_node != nullptr) { + parent_node->reachable = true; } } } } } - return 0; + return false; } -static int asn1_object_cmp(const ASN1_OBJECT *const *a, - const ASN1_OBJECT *const *b) { +int asn1_object_cmp(const ASN1_OBJECT *const *a, const ASN1_OBJECT *const *b) { return OBJ_cmp(*a, *b); } +} // namespace + 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 = NULL; - int ret = X509_V_ERR_OUT_OF_MEM; - X509_POLICY_LEVEL *level = NULL; - STACK_OF(X509_POLICY_LEVEL) *levels = NULL; - STACK_OF(ASN1_OBJECT) *user_policies_sorted = NULL; - size_t num_certs = sk_X509_num(certs); + *out_current_cert = nullptr; // Skip policy checking if the chain is just the trust anchor. + const size_t num_certs = sk_X509_num(certs); if (num_certs <= 1) { return X509_V_OK; } @@ -686,65 +587,58 @@ int X509_policy_check(const STACK_OF(X509) *certs, (flags & X509_V_FLAG_INHIBIT_ANY) ? 0 : num_certs + 1; size_t policy_mapping = (flags & X509_V_FLAG_INHIBIT_MAP) ? 0 : num_certs + 1; - levels = sk_X509_POLICY_LEVEL_new_null(); - if (levels == NULL) { - goto err; - } - + Vector levels; + std::optional level; for (size_t i = num_certs - 2; i < num_certs; i--) { X509 *cert = sk_X509_value(certs, i); - if (!x509v3_cache_extensions(cert)) { - goto err; + uint32_t ex_flags = X509_get_extension_flags(cert); + if (ex_flags & EXFLAG_INVALID) { + return X509_V_ERR_OUT_OF_MEM; } - const int is_self_issued = (cert->ex_flags & EXFLAG_SI) != 0; + const bool is_self_issued = (ex_flags & EXFLAG_SI) != 0; - if (level == NULL) { + // 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); - level = x509_policy_level_new(); - if (level == NULL) { - goto err; - } - level->has_any_policy = 1; + level.emplace(); + level->set_has_any_policy(true); } - // RFC 5280, section 6.1.3, steps (d) and (e). |any_policy_allowed| is + // 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 = inhibit_any_policy > 0 || (i > 0 && is_self_issued); - if (!process_certificate_policies(cert, level, any_policy_allowed)) { - ret = X509_V_ERR_INVALID_POLICY_EXTENSION; + if (!process_certificate_policies(cert, &*level, any_policy_allowed)) { *out_current_cert = cert; - goto err; + return X509_V_ERR_INVALID_POLICY_EXTENSION; } // RFC 5280, section 6.1.3, step (f). - if (explicit_policy == 0 && x509_policy_level_is_empty(level)) { - ret = X509_V_ERR_NO_EXPLICIT_POLICY; - goto err; + if (explicit_policy == 0 && level->is_empty()) { + return X509_V_ERR_NO_EXPLICIT_POLICY; } - // Insert into the list. - if (!sk_X509_POLICY_LEVEL_push(levels, level)) { - goto err; + // Insert the completed level into the list. + if (!levels.Push(*std::exchange(level, std::nullopt))) { + return X509_V_ERR_OUT_OF_MEM; } - X509_POLICY_LEVEL *current_level = level; - level = NULL; + level = std::nullopt; // If this is not the leaf certificate, we go to section 6.1.4. If it // is the leaf certificate, we go to section 6.1.5 instead. if (i != 0) { // RFC 5280, section 6.1.4, steps (a) and (b). - level = process_policy_mappings(cert, current_level, policy_mapping > 0); - if (level == NULL) { - ret = X509_V_ERR_INVALID_POLICY_EXTENSION; + level = process_policy_mappings(cert, &levels.back(), policy_mapping > 0); + if (!level.has_value()) { *out_current_cert = cert; - goto err; + return X509_V_ERR_INVALID_POLICY_EXTENSION; } } // RFC 5280, section 6.1.4, step (h-j) for non-leaves, and section 6.1.5, // step (a-b) for leaves. In the leaf case, RFC 5280 says only to update - // |explicit_policy|, but |policy_mapping| and |inhibit_any_policy| are no + // `explicit_policy`, but `policy_mapping` and `inhibit_any_policy` are no // longer read at this point, so we use the same process. if (i == 0 || !is_self_issued) { if (explicit_policy > 0) { @@ -759,38 +653,34 @@ int X509_policy_check(const STACK_OF(X509) *certs, } if (!process_policy_constraints(cert, &explicit_policy, &policy_mapping, &inhibit_any_policy)) { - ret = X509_V_ERR_INVALID_POLICY_EXTENSION; *out_current_cert = cert; - goto err; + return X509_V_ERR_INVALID_POLICY_EXTENSION; } } // RFC 5280, section 6.1.5, step (g). We do not output the policy set, so it // is only necessary to check if the user-constrained-policy-set is not empty. if (explicit_policy == 0) { - // Build a sorted copy of |user_policies| for more efficient lookup. - if (user_policies != NULL) { + // Build a sorted copy of `user_policies` for more efficient lookup. + STACK_OF(ASN1_OBJECT) *user_policies_sorted = nullptr; + // `user_policies_sorted`'s contents are owned by `user_policies`, so we do + // not use `sk_ASN1_OBJECT_pop_free`. + Cleanup cleanup = [&] { sk_ASN1_OBJECT_free(user_policies_sorted); }; + if (user_policies != nullptr) { user_policies_sorted = sk_ASN1_OBJECT_dup(user_policies); - if (user_policies_sorted == NULL) { - goto err; + if (user_policies_sorted == nullptr) { + return X509_V_ERR_OUT_OF_MEM; } sk_ASN1_OBJECT_set_cmp_func(user_policies_sorted, asn1_object_cmp); sk_ASN1_OBJECT_sort(user_policies_sorted); } - if (!has_explicit_policy(levels, user_policies_sorted)) { - ret = X509_V_ERR_NO_EXPLICIT_POLICY; - goto err; + if (!has_explicit_policy(Span(levels), user_policies_sorted)) { + return X509_V_ERR_NO_EXPLICIT_POLICY; } } - ret = X509_V_OK; - -err: - x509_policy_level_free(level); - // |user_policies_sorted|'s contents are owned by |user_policies|, so we do - // not use |sk_ASN1_OBJECT_pop_free|. - sk_ASN1_OBJECT_free(user_policies_sorted); - sk_X509_POLICY_LEVEL_pop_free(levels, x509_policy_level_free); - return ret; + return X509_V_OK; } + +BSSL_NAMESPACE_END diff --git a/Sources/CNIOBoringSSL/crypto/x509/rsa_pss.cc b/Sources/CNIOBoringSSL/crypto/x509/rsa_pss.cc index 9e0cf388..41a3f9f1 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/rsa_pss.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/rsa_pss.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,18 +19,23 @@ #include #include +#include #include #include #include #include +#include +#include "../rsa/internal.h" #include "internal.h" +using namespace bssl; + static 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 = (RSA_PSS_PARAMS *)*pval; + RSA_PSS_PARAMS *pss = asn1_load_ptr_as(pval); X509_ALGOR_free(pss->maskHash); } return 1; @@ -41,114 +51,21 @@ ASN1_SEQUENCE_cb(RSA_PSS_PARAMS, rsa_pss_cb) = { IMPLEMENT_ASN1_FUNCTIONS_const(RSA_PSS_PARAMS) -// Given an MGF1 Algorithm ID decode to an Algorithm Identifier -static X509_ALGOR *rsa_mgf1_decode(const X509_ALGOR *alg) { - if (OBJ_obj2nid(alg->algorithm) != NID_mgf1 || alg->parameter == NULL || - alg->parameter->type != V_ASN1_SEQUENCE) { - return NULL; - } - - const uint8_t *p = alg->parameter->value.sequence->data; - int plen = alg->parameter->value.sequence->length; - return d2i_X509_ALGOR(NULL, &p, plen); -} - -static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg) { - if (alg->parameter == NULL || alg->parameter->type != V_ASN1_SEQUENCE) { - return NULL; - } - - const uint8_t *p = alg->parameter->value.sequence->data; - int plen = alg->parameter->value.sequence->length; - return d2i_RSA_PSS_PARAMS(NULL, &p, plen); -} - -static int is_allowed_pss_md(const EVP_MD *md) { - int md_type = EVP_MD_type(md); - return md_type == NID_sha256 || md_type == NID_sha384 || - md_type == NID_sha512; -} - -// rsa_md_to_algor sets |*palg| to an |X509_ALGOR| describing the digest |md|, -// which must be an allowed PSS digest. -static int rsa_md_to_algor(X509_ALGOR **palg, const EVP_MD *md) { - // SHA-1 should be omitted (DEFAULT), but we do not allow SHA-1. - assert(is_allowed_pss_md(md)); - *palg = X509_ALGOR_new(); - if (*palg == NULL) { +static 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; } - if (!X509_ALGOR_set_md(*palg, md)) { - X509_ALGOR_free(*palg); - *palg = NULL; - return 0; - } - return 1; + + // Although a syntax error in DER, we tolerate an explicitly-encoded trailer. + // See the certificates in cl/362617931. + CBS cbs; + CBS_init(&cbs, alg->parameter->value.sequence->data, + alg->parameter->value.sequence->length); + return rsa_parse_pss_params(&cbs, out, /*allow_explicit_trailer=*/true) && + CBS_len(&cbs) == 0; } -// rsa_md_to_mgf1 sets |*palg| to an |X509_ALGOR| describing MGF-1 with the -// digest |mgf1md|, which must be an allowed PSS digest. -static int rsa_md_to_mgf1(X509_ALGOR **palg, const EVP_MD *mgf1md) { - // SHA-1 should be omitted (DEFAULT), but we do not allow SHA-1. - assert(is_allowed_pss_md(mgf1md)); - X509_ALGOR *algtmp = NULL; - ASN1_STRING *stmp = NULL; - // need to embed algorithm ID inside another - if (!rsa_md_to_algor(&algtmp, mgf1md) || - !ASN1_item_pack(algtmp, ASN1_ITEM_rptr(X509_ALGOR), &stmp)) { - goto err; - } - *palg = X509_ALGOR_new(); - if (!*palg) { - goto err; - } - if (!X509_ALGOR_set0(*palg, OBJ_nid2obj(NID_mgf1), V_ASN1_SEQUENCE, stmp)) { - goto err; - } - stmp = NULL; - -err: - ASN1_STRING_free(stmp); - X509_ALGOR_free(algtmp); - if (*palg) { - return 1; - } - - return 0; -} - -static const EVP_MD *rsa_algor_to_md(const X509_ALGOR *alg) { - if (!alg) { - // If omitted, PSS defaults to SHA-1, which we do not allow. - OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PSS_PARAMETERS); - return NULL; - } - const EVP_MD *md = EVP_get_digestbyobj(alg->algorithm); - if (md == NULL || !is_allowed_pss_md(md)) { - OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PSS_PARAMETERS); - return NULL; - } - return md; -} - -static const EVP_MD *rsa_mgf1_to_md(const X509_ALGOR *alg) { - if (!alg) { - // If omitted, PSS defaults to MGF-1 with SHA-1, which we do not allow. - OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PSS_PARAMETERS); - return NULL; - } - // Check mask and lookup mask hash algorithm. - X509_ALGOR *maskHash = rsa_mgf1_decode(alg); - if (maskHash == NULL) { - OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PSS_PARAMETERS); - return NULL; - } - const EVP_MD *ret = rsa_algor_to_md(maskHash); - X509_ALGOR_free(maskHash); - return ret; -} - -int x509_rsa_ctx_to_pss(EVP_MD_CTX *ctx, X509_ALGOR *algor) { +int bssl::x509_rsa_ctx_to_pss(EVP_MD_CTX *ctx, X509_ALGOR *algor) { const EVP_MD *sigmd, *mgf1md; int saltlen; if (!EVP_PKEY_CTX_get_signature_md(ctx->pctx, &sigmd) || @@ -157,203 +74,114 @@ int x509_rsa_ctx_to_pss(EVP_MD_CTX *ctx, X509_ALGOR *algor) { return 0; } - if (sigmd != mgf1md || !is_allowed_pss_md(sigmd)) { + if (sigmd != mgf1md) { OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PSS_PARAMETERS); return 0; } int md_len = (int)EVP_MD_size(sigmd); - if (saltlen == -1) { - saltlen = md_len; - } else if (saltlen != md_len) { + if (saltlen != RSA_PSS_SALTLEN_DIGEST && saltlen != md_len) { OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PSS_PARAMETERS); return 0; } - int ret = 0; - ASN1_STRING *os = NULL; - RSA_PSS_PARAMS *pss = RSA_PSS_PARAMS_new(); - if (!pss) { - goto err; + rsa_pss_params_t params; + switch (EVP_MD_type(sigmd)) { + case NID_sha256: + params = rsa_pss_sha256; + break; + case NID_sha384: + params = rsa_pss_sha384; + break; + case NID_sha512: + params = rsa_pss_sha512; + break; + default: + OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PSS_PARAMETERS); + return 0; } - // The DEFAULT value is 20, but this does not match any supported digest. - assert(saltlen != 20); - pss->saltLength = ASN1_INTEGER_new(); - if (!pss->saltLength || // - !ASN1_INTEGER_set_int64(pss->saltLength, saltlen)) { - goto err; + // Encode `params` to an `ASN1_STRING`. + uint8_t buf[128]; // The largest param fits comfortably in 128 bytes. + CBB cbb; + CBB_init_fixed(&cbb, buf, sizeof(buf)); + if (!rsa_marshal_pss_params(&cbb, params)) { + return 0; } - - if (!rsa_md_to_algor(&pss->hashAlgorithm, sigmd) || - !rsa_md_to_mgf1(&pss->maskGenAlgorithm, mgf1md)) { - goto err; - } - - // Finally create string with pss parameter encoding. - if (!ASN1_item_pack(pss, ASN1_ITEM_rptr(RSA_PSS_PARAMS), &os)) { - goto err; + UniquePtr params_str(ASN1_STRING_type_new(V_ASN1_SEQUENCE)); + if (params_str == nullptr || + !ASN1_STRING_set(params_str.get(), CBB_data(&cbb), CBB_len(&cbb))) { + return 0; } if (!X509_ALGOR_set0(algor, OBJ_nid2obj(NID_rsassaPss), V_ASN1_SEQUENCE, - os)) { - goto err; + params_str.get())) { + return 0; } - os = NULL; - ret = 1; - -err: - RSA_PSS_PARAMS_free(pss); - ASN1_STRING_free(os); - return ret; + params_str.release(); // `X509_ALGOR_set0` took ownership. + return 1; } -int x509_rsa_pss_to_ctx(EVP_MD_CTX *ctx, const X509_ALGOR *sigalg, - EVP_PKEY *pkey) { +int bssl::x509_rsa_pss_to_ctx(EVP_MD_CTX *ctx, const X509_ALGOR *sigalg, + EVP_PKEY *pkey) { assert(OBJ_obj2nid(sigalg->algorithm) == NID_rsassaPss); - - // Decode PSS parameters - int ret = 0; - RSA_PSS_PARAMS *pss = rsa_pss_decode(sigalg); - - { - if (pss == NULL) { - OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PSS_PARAMETERS); - goto err; - } - - const EVP_MD *mgf1md = rsa_mgf1_to_md(pss->maskGenAlgorithm); - const EVP_MD *md = rsa_algor_to_md(pss->hashAlgorithm); - if (mgf1md == NULL || md == NULL) { - goto err; - } - - // We require the MGF-1 and signing hashes to match. - if (mgf1md != md) { - OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PSS_PARAMETERS); - goto err; - } - - // We require the salt length be the hash length. The DEFAULT value is 20, - // but this does not match any supported salt length. - uint64_t salt_len = 0; - if (pss->saltLength == NULL || - !ASN1_INTEGER_get_uint64(&salt_len, pss->saltLength) || - salt_len != EVP_MD_size(md)) { - OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PSS_PARAMETERS); - goto err; - } - assert(salt_len <= INT_MAX); - - // The trailer field must be 1 (0xbc). This value is DEFAULT, so the - // structure is required to omit it in DER. Although a syntax error, we also - // tolerate an explicitly-encoded value. See the certificates in - // cl/362617931. - if (pss->trailerField != NULL && ASN1_INTEGER_get(pss->trailerField) != 1) { - OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PSS_PARAMETERS); - goto err; - } - - EVP_PKEY_CTX *pctx; - if (!EVP_DigestVerifyInit(ctx, &pctx, md, NULL, pkey) || - !EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) || - !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, (int)salt_len) || - !EVP_PKEY_CTX_set_rsa_mgf1_md(pctx, mgf1md)) { - goto err; - } - - ret = 1; + rsa_pss_params_t params; + if (!rsa_pss_decode(sigalg, ¶ms)) { + OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PSS_PARAMETERS); + return 0; } -err: - RSA_PSS_PARAMS_free(pss); - return ret; + const EVP_MD *md = rsa_pss_params_get_md(params); + EVP_PKEY_CTX *pctx; + if (!EVP_DigestVerifyInit(ctx, &pctx, md, nullptr, pkey) || + !EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) || + !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) || + !EVP_PKEY_CTX_set_rsa_mgf1_md(pctx, md)) { + return 0; + } + + return 1; } -int x509_print_rsa_pss_params(BIO *bp, const X509_ALGOR *sigalg, int indent, - ASN1_PCTX *pctx) { +int bssl::x509_print_rsa_pss_params(BIO *bp, const X509_ALGOR *sigalg, + int indent, ASN1_PCTX *pctx) { assert(OBJ_obj2nid(sigalg->algorithm) == NID_rsassaPss); + rsa_pss_params_t params; + if (!rsa_pss_decode(sigalg, ¶ms)) { + return BIO_puts(bp, " (INVALID PSS PARAMETERS)\n") > 0; + } - int rv = 0; - X509_ALGOR *maskHash = NULL; - RSA_PSS_PARAMS *pss = rsa_pss_decode(sigalg); - if (!pss) { - if (BIO_puts(bp, " (INVALID PSS PARAMETERS)\n") <= 0) { - goto err; - } - rv = 1; - goto err; + const char *hash_str = nullptr; + uint32_t salt_len = 0; + switch (params) { + case rsa_pss_none: + // `rsa_pss_decode` will never return this. + OPENSSL_PUT_ERROR(X509, ERR_R_INTERNAL_ERROR); + return 0; + case rsa_pss_sha256: + hash_str = "sha256"; + salt_len = 32; + break; + case rsa_pss_sha384: + hash_str = "sha384"; + salt_len = 48; + break; + case rsa_pss_sha512: + hash_str = "sha512"; + salt_len = 64; + break; } if (BIO_puts(bp, "\n") <= 0 || // !BIO_indent(bp, indent, 128) || // - BIO_puts(bp, "Hash Algorithm: ") <= 0) { - goto err; - } - - if (pss->hashAlgorithm) { - if (i2a_ASN1_OBJECT(bp, pss->hashAlgorithm->algorithm) <= 0) { - goto err; - } - } else if (BIO_puts(bp, "sha1 (default)") <= 0) { - goto err; - } - - if (BIO_puts(bp, "\n") <= 0 || // + BIO_printf(bp, "Hash Algorithm: %s\n", hash_str) <= 0 || !BIO_indent(bp, indent, 128) || // - BIO_puts(bp, "Mask Algorithm: ") <= 0) { - goto err; + BIO_printf(bp, "Mask Algorithm: mgf1 with %s\n", hash_str) <= 0 || + !BIO_indent(bp, indent, 128) || // + BIO_printf(bp, "Salt Length: 0x%x\n", salt_len) <= 0 || + !BIO_indent(bp, indent, 128) || // + BIO_puts(bp, "Trailer Field: 0xBC (default)\n") <= 0) { + return 0; } - if (pss->maskGenAlgorithm) { - maskHash = rsa_mgf1_decode(pss->maskGenAlgorithm); - if (maskHash == NULL) { - if (BIO_puts(bp, "INVALID") <= 0) { - goto err; - } - } else { - if (i2a_ASN1_OBJECT(bp, pss->maskGenAlgorithm->algorithm) <= 0 || - BIO_puts(bp, " with ") <= 0 || - i2a_ASN1_OBJECT(bp, maskHash->algorithm) <= 0) { - goto err; - } - } - } else if (BIO_puts(bp, "mgf1 with sha1 (default)") <= 0) { - goto err; - } - BIO_puts(bp, "\n"); - - if (!BIO_indent(bp, indent, 128) || // - BIO_puts(bp, "Salt Length: 0x") <= 0) { - goto err; - } - - if (pss->saltLength) { - if (i2a_ASN1_INTEGER(bp, pss->saltLength) <= 0) { - goto err; - } - } else if (BIO_puts(bp, "14 (default)") <= 0) { - goto err; - } - BIO_puts(bp, "\n"); - - if (!BIO_indent(bp, indent, 128) || // - BIO_puts(bp, "Trailer Field: 0x") <= 0) { - goto err; - } - - if (pss->trailerField) { - if (i2a_ASN1_INTEGER(bp, pss->trailerField) <= 0) { - goto err; - } - } else if (BIO_puts(bp, "BC (default)") <= 0) { - goto err; - } - BIO_puts(bp, "\n"); - - rv = 1; - -err: - RSA_PSS_PARAMS_free(pss); - X509_ALGOR_free(maskHash); - return rv; + return 1; } diff --git a/Sources/CNIOBoringSSL/crypto/x509/t_crl.cc b/Sources/CNIOBoringSSL/crypto/x509/t_crl.cc index 84e1f028..2f96a094 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/t_crl.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/t_crl.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,9 +21,9 @@ #include -int X509_CRL_print_fp(FILE *fp, X509_CRL *x) { +int X509_CRL_print_fp(FILE *fp, const X509_CRL *x) { BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); - if (b == NULL) { + if (b == nullptr) { OPENSSL_PUT_ERROR(X509, ERR_R_BUF_LIB); return 0; } @@ -27,7 +32,7 @@ int X509_CRL_print_fp(FILE *fp, X509_CRL *x) { return ret; } -int X509_CRL_print(BIO *out, X509_CRL *x) { +int X509_CRL_print(BIO *out, const X509_CRL *x) { long version = X509_CRL_get_version(x); assert(X509_CRL_VERSION_1 <= version && version <= X509_CRL_VERSION_2); const X509_ALGOR *sig_alg; @@ -36,15 +41,16 @@ int X509_CRL_print(BIO *out, X509_CRL *x) { if (BIO_printf(out, "Certificate Revocation List (CRL):\n") <= 0 || BIO_printf(out, "%8sVersion %ld (0x%lx)\n", "", version + 1, (unsigned long)version) <= 0 || - // Note this and the other |X509_signature_print| call both print the + // Note this and the other `X509_signature_print` call both print the // outer signature algorithm, rather than printing the inner and outer // ones separately. This matches OpenSSL, though it was probably a bug. - !X509_signature_print(out, sig_alg, NULL)) { + !X509_signature_print(out, sig_alg, nullptr)) { return 0; } - char *issuer = X509_NAME_oneline(X509_CRL_get_issuer(x), NULL, 0); - int ok = issuer != NULL && BIO_printf(out, "%8sIssuer: %s\n", "", issuer) > 0; + char *issuer = X509_NAME_oneline(X509_CRL_get_issuer(x), nullptr, 0); + int ok = + issuer != nullptr && BIO_printf(out, "%8sIssuer: %s\n", "", issuer) > 0; OPENSSL_free(issuer); if (!ok) { return 0; @@ -71,7 +77,9 @@ int X509_CRL_print(BIO *out, X509_CRL *x) { return 0; } - const STACK_OF(X509_REVOKED) *rev = X509_CRL_get_REVOKED(x); + // TODO(crbug.com/442860745): `X509_CRL_get_REVOKED` is not const-correct. + const STACK_OF(X509_REVOKED) *rev = + X509_CRL_get_REVOKED(const_cast(x)); if (sk_X509_REVOKED_num(rev) > 0) { if (BIO_printf(out, "Revoked Certificates:\n") <= 0) { return 0; diff --git a/Sources/CNIOBoringSSL/crypto/x509/t_req.cc b/Sources/CNIOBoringSSL/crypto/x509/t_req.cc index 83390e54..5829c032 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/t_req.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/t_req.cc @@ -1,15 +1,21 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -19,9 +25,11 @@ #include "internal.h" -int X509_REQ_print_fp(FILE *fp, X509_REQ *x) { +using namespace bssl; + +int X509_REQ_print_fp(FILE *fp, const X509_REQ *x) { BIO *bio = BIO_new_fp(fp, BIO_NOCLOSE); - if (bio == NULL) { + if (bio == nullptr) { OPENSSL_PUT_ERROR(X509, ERR_R_BUF_LIB); return 0; } @@ -30,7 +38,7 @@ int X509_REQ_print_fp(FILE *fp, X509_REQ *x) { return ret; } -int X509_REQ_print_ex(BIO *bio, X509_REQ *x, unsigned long nmflags, +int X509_REQ_print_ex(BIO *bio, const X509_REQ *x, unsigned long nmflags, unsigned long cflag) { long l; STACK_OF(X509_ATTRIBUTE) *sk; @@ -47,7 +55,7 @@ int X509_REQ_print_ex(BIO *bio, X509_REQ *x, unsigned long nmflags, nmindent = 16; } - X509_REQ_INFO *ri = x->req_info; + const X509_REQ_INFO *ri = x->req_info; if (!(cflag & X509_FLAG_NO_HEADER)) { if (BIO_write(bio, "Certificate Request:\n", 21) <= 0 || BIO_write(bio, " Data:\n", 10) <= 0) { @@ -56,7 +64,7 @@ int X509_REQ_print_ex(BIO *bio, X509_REQ *x, unsigned long nmflags, } if (!(cflag & X509_FLAG_NO_VERSION)) { l = X509_REQ_get_version(x); - // Only zero, |X509_REQ_VERSION_1|, is valid but our parser accepts some + // Only zero, `X509_REQ_VERSION_1`, is valid but our parser accepts some // invalid values for compatibility. assert(0 <= l && l <= 2); if (BIO_printf(bio, "%8sVersion: %ld (0x%lx)\n", "", l + 1, @@ -74,17 +82,17 @@ int X509_REQ_print_ex(BIO *bio, X509_REQ *x, unsigned long nmflags, if (!(cflag & X509_FLAG_NO_PUBKEY)) { if (BIO_write(bio, " Subject Public Key Info:\n", 33) <= 0 || BIO_printf(bio, "%12sPublic Key Algorithm: ", "") <= 0 || - i2a_ASN1_OBJECT(bio, ri->pubkey->algor->algorithm) <= 0 || + i2a_ASN1_OBJECT(bio, FromOpaque(ri->pubkey)->algor->algorithm) <= 0 || BIO_puts(bio, "\n") <= 0) { goto err; } const EVP_PKEY *pkey = X509_REQ_get0_pubkey(x); - if (pkey == NULL) { + if (pkey == nullptr) { BIO_printf(bio, "%12sUnable to load Public Key\n", ""); ERR_print_errors(bio); } else { - EVP_PKEY_print_public(bio, pkey, 16, NULL); + EVP_PKEY_print_public(bio, pkey, 16, nullptr); } } @@ -99,10 +107,11 @@ int X509_REQ_print_ex(BIO *bio, X509_REQ *x, unsigned long nmflags, goto err; } } else { - size_t i; - for (i = 0; i < sk_X509_ATTRIBUTE_num(sk); i++) { + for (size_t i = 0; i < sk_X509_ATTRIBUTE_num(sk); i++) { + // TODO(crbug.com/442860745): `X509_ATTRIBUTE` accessors are not + // const-correct. X509_ATTRIBUTE *a = sk_X509_ATTRIBUTE_value(sk, i); - ASN1_OBJECT *aobj = X509_ATTRIBUTE_get0_object(a); + const ASN1_OBJECT *aobj = X509_ATTRIBUTE_get0_object(a); if (X509_REQ_extension_nid(OBJ_obj2nid(aobj))) { continue; @@ -122,14 +131,8 @@ int X509_REQ_print_ex(BIO *bio, X509_REQ *x, unsigned long nmflags, } } - int j; - for (j = 0; j < num_attrs; j++) { - const ASN1_TYPE *at = X509_ATTRIBUTE_get0_type(a, j); - const int type = at->type; - ASN1_BIT_STRING *bs = at->value.asn1_string; - - int k; - for (k = 25 - obj_str_len; k > 0; k--) { + for (int j = 0; j < num_attrs; j++) { + for (int k = 25 - obj_str_len; k > 0; k--) { if (BIO_write(bio, " ", 1) != 1) { goto err; } @@ -139,9 +142,14 @@ int X509_REQ_print_ex(BIO *bio, X509_REQ *x, unsigned long nmflags, goto err; } - if (type == V_ASN1_PRINTABLESTRING || type == V_ASN1_UTF8STRING || - type == V_ASN1_IA5STRING || type == V_ASN1_T61STRING) { - if (BIO_write(bio, (char *)bs->data, bs->length) != bs->length) { + const ASN1_TYPE *at = X509_ATTRIBUTE_get0_type(a, j); + if (at->type == V_ASN1_PRINTABLESTRING || + at->type == V_ASN1_UTF8STRING || at->type == V_ASN1_IA5STRING || + at->type == V_ASN1_T61STRING) { + const ASN1_STRING *str = at->value.asn1_string; + int str_len = ASN1_STRING_length(str); + if (BIO_write(bio, ASN1_STRING_get0_data(str), str_len) != + str_len) { goto err; } BIO_puts(bio, "\n"); @@ -193,6 +201,6 @@ err: return 0; } -int X509_REQ_print(BIO *bio, X509_REQ *req) { +int X509_REQ_print(BIO *bio, const X509_REQ *req) { return X509_REQ_print_ex(bio, req, XN_FLAG_COMPAT, X509_FLAG_COMPAT); } diff --git a/Sources/CNIOBoringSSL/crypto/x509/t_x509.cc b/Sources/CNIOBoringSSL/crypto/x509/t_x509.cc index 1b8837bb..4500c1a5 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/t_x509.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/t_x509.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 // for PRIu64 and friends @@ -19,13 +24,16 @@ #include #include +#include "../internal.h" #include "internal.h" -int X509_print_ex_fp(FILE *fp, X509 *x, unsigned long nmflag, +using namespace bssl; + +int X509_print_ex_fp(FILE *fp, const X509 *x, unsigned long nmflag, unsigned long cflag) { BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); - if (b == NULL) { + if (b == nullptr) { OPENSSL_PUT_ERROR(X509, ERR_R_BUF_LIB); return 0; } @@ -34,16 +42,17 @@ int X509_print_ex_fp(FILE *fp, X509 *x, unsigned long nmflag, return ret; } -int X509_print_fp(FILE *fp, X509 *x) { +int X509_print_fp(FILE *fp, const X509 *x) { return X509_print_ex_fp(fp, x, XN_FLAG_COMPAT, X509_FLAG_COMPAT); } -int X509_print(BIO *bp, X509 *x) { +int X509_print(BIO *bp, const X509 *x) { return X509_print_ex(bp, x, XN_FLAG_COMPAT, X509_FLAG_COMPAT); } -int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags, +int X509_print_ex(BIO *bp, const X509 *x, unsigned long nmflags, unsigned long cflag) { + auto *impl = FromOpaque(x); char mlch = ' '; int nmindent = 0; if ((nmflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) { @@ -55,7 +64,6 @@ int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags, nmindent = 16; } - const X509_CINF *ci = x->cert_info; if (!(cflag & X509_FLAG_NO_HEADER)) { if (BIO_write(bp, "Certificate:\n", 13) <= 0) { return 0; @@ -86,7 +94,7 @@ int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags, return 0; } } else { - ERR_clear_error(); // Clear |ASN1_INTEGER_get_uint64|'s error. + ERR_clear_error(); // Clear `ASN1_INTEGER_get_uint64`'s error. const char *neg = (serial->type == V_ASN1_NEG_INTEGER) ? " (Negative)" : ""; if (BIO_printf(bp, "\n%12s%s", "", neg) <= 0) { @@ -103,7 +111,7 @@ int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags, } if (!(cflag & X509_FLAG_NO_SIGNAME)) { - if (X509_signature_print(bp, ci->signature, NULL) <= 0) { + if (X509_signature_print(bp, impl->tbs_sig_alg.get(), nullptr) <= 0) { return 0; } } @@ -127,13 +135,13 @@ int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags, if (BIO_write(bp, " Not Before: ", 24) <= 0) { return 0; } - if (!ASN1_TIME_print(bp, X509_get_notBefore(x))) { + if (!ASN1_TIME_print(bp, X509_get0_notBefore(x))) { return 0; } if (BIO_write(bp, "\n Not After : ", 25) <= 0) { return 0; } - if (!ASN1_TIME_print(bp, X509_get_notAfter(x))) { + if (!ASN1_TIME_print(bp, X509_get0_notAfter(x))) { return 0; } if (BIO_write(bp, "\n", 1) <= 0) { @@ -159,7 +167,7 @@ int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags, if (BIO_printf(bp, "%12sPublic Key Algorithm: ", "") <= 0) { return 0; } - if (i2a_ASN1_OBJECT(bp, ci->key->algor->algorithm) <= 0) { + if (i2a_ASN1_OBJECT(bp, impl->key.algor->algorithm) <= 0) { return 0; } if (BIO_puts(bp, "\n") <= 0) { @@ -167,44 +175,46 @@ int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags, } const EVP_PKEY *pkey = X509_get0_pubkey(x); - if (pkey == NULL) { + if (pkey == nullptr) { BIO_printf(bp, "%12sUnable to load Public Key\n", ""); ERR_print_errors(bp); } else { - EVP_PKEY_print_public(bp, pkey, 16, NULL); + EVP_PKEY_print_public(bp, pkey, 16, nullptr); } } if (!(cflag & X509_FLAG_NO_IDS)) { - if (ci->issuerUID) { + if (impl->issuerUID) { if (BIO_printf(bp, "%8sIssuer Unique ID: ", "") <= 0) { return 0; } - if (!X509_signature_dump(bp, ci->issuerUID, 12)) { + if (!X509_signature_dump(bp, impl->issuerUID.get(), 12)) { return 0; } } - if (ci->subjectUID) { + if (impl->subjectUID) { if (BIO_printf(bp, "%8sSubject Unique ID: ", "") <= 0) { return 0; } - if (!X509_signature_dump(bp, ci->subjectUID, 12)) { + if (!X509_signature_dump(bp, impl->subjectUID.get(), 12)) { return 0; } } } if (!(cflag & X509_FLAG_NO_EXTENSIONS)) { - X509V3_extensions_print(bp, "X509v3 extensions", ci->extensions, cflag, 8); + X509V3_extensions_print(bp, "X509v3 extensions", impl->extensions, cflag, + 8); } if (!(cflag & X509_FLAG_NO_SIGDUMP)) { - if (X509_signature_print(bp, x->sig_alg, x->signature) <= 0) { + if (X509_signature_print(bp, impl->sig_alg.get(), impl->signature.get()) <= + 0) { return 0; } } if (!(cflag & X509_FLAG_NO_AUX)) { - if (!X509_CERT_AUX_print(bp, x->aux, 0)) { + if (!X509_CERT_AUX_print(bp, impl->aux, 0)) { return 0; } } @@ -224,7 +234,7 @@ int X509_signature_print(BIO *bp, const X509_ALGOR *sigalg, // RSA-PSS signatures have parameters to print. int sig_nid = OBJ_obj2nid(sigalg->algorithm); if (sig_nid == NID_rsassaPss && - !x509_print_rsa_pss_params(bp, sigalg, 9, 0)) { + !x509_print_rsa_pss_params(bp, sigalg, 9, nullptr)) { return 0; } @@ -240,7 +250,7 @@ int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase) { char *s, *c, *b; int ret = 0, i; - b = X509_NAME_oneline(name, NULL, 0); + b = X509_NAME_oneline(name, nullptr, 0); if (!b) { return 0; } diff --git a/Sources/CNIOBoringSSL/crypto/x509/t_x509a.cc b/Sources/CNIOBoringSSL/crypto/x509/t_x509a.cc index 94d730e9..3c8033a8 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/t_x509a.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/t_x509a.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -16,9 +21,11 @@ #include "internal.h" +using namespace bssl; + // X509_CERT_AUX and string set routines -int X509_CERT_AUX_print(BIO *out, X509_CERT_AUX *aux, int indent) { +int bssl::X509_CERT_AUX_print(BIO *out, X509_CERT_AUX *aux, int indent) { char oidstr[80], first; size_t i; int j; diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_akey.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_akey.cc index 59b315da..40f52dff 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_akey.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_akey.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -18,41 +23,42 @@ #include #include -#include "ext_dat.h" #include "internal.h" +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); -const X509V3_EXT_METHOD v3_akey_id = { +const X509V3_EXT_METHOD bssl::v3_akey_id = { NID_authority_key_identifier, X509V3_EXT_MULTILINE, ASN1_ITEM_ref(AUTHORITY_KEYID), - 0, - 0, - 0, - 0, - 0, - 0, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, i2v_AUTHORITY_KEYID, v2i_AUTHORITY_KEYID, - 0, - 0, - NULL, + nullptr, + nullptr, + nullptr, }; static 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 == NULL; + int extlist_was_null = extlist == nullptr; if (akeyid->keyid) { char *tmp = x509v3_bytes_to_hex(akeyid->keyid->data, akeyid->keyid->length); - int ok = tmp != NULL && X509V3_add_value("keyid", tmp, &extlist); + int ok = tmp != nullptr && X509V3_add_value("keyid", tmp, &extlist); OPENSSL_free(tmp); if (!ok) { goto err; @@ -60,8 +66,8 @@ static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID( } if (akeyid->issuer) { STACK_OF(CONF_VALUE) *tmpextlist = - i2v_GENERAL_NAMES(NULL, akeyid->issuer, extlist); - if (tmpextlist == NULL) { + i2v_GENERAL_NAMES(nullptr, akeyid->issuer, extlist); + if (tmpextlist == nullptr) { goto err; } extlist = tmpextlist; @@ -77,44 +83,37 @@ err: if (extlist_was_null) { sk_CONF_VALUE_pop_free(extlist, X509V3_conf_free); } - return NULL; + return nullptr; } -// Currently two options: keyid: use the issuers subject keyid, the value -// 'always' means its is an error if the issuer certificate doesn't have a -// key id. issuer: use the issuers cert issuer and serial number. The default -// is to only use this if keyid is not present. With the option 'always' this -// is always included. - +// Currently two options: +// +// - keyid: Use the issuer's subject key ID. The value 'always' means it's an +// error if the issuer certificate doesn't have one. +// +// - 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) { - char keyid = 0, issuer = 0; - int j; - ASN1_OCTET_STRING *ikeyid = NULL; - X509_NAME *isname = NULL; - GENERAL_NAMES *gens = NULL; - GENERAL_NAME *gen = NULL; - ASN1_INTEGER *serial = NULL; - const X509 *cert; - AUTHORITY_KEYID *akeyid; - - for (size_t i = 0; i < sk_CONF_VALUE_num(values); i++) { - const CONF_VALUE *cnf = sk_CONF_VALUE_value(values, i); + enum Option { kOff = 0, kOn = 1, kAlways = 2 }; + Option use_key_id = kOff, use_issuer = kOff; + for (const CONF_VALUE *cnf : values) { if (!strcmp(cnf->name, "keyid")) { - keyid = 1; + use_key_id = kOn; if (cnf->value && !strcmp(cnf->value, "always")) { - keyid = 2; + use_key_id = kAlways; } } else if (!strcmp(cnf->name, "issuer")) { - issuer = 1; + use_issuer = kOn; if (cnf->value && !strcmp(cnf->value, "always")) { - issuer = 2; + use_issuer = kAlways; } } else { OPENSSL_PUT_ERROR(X509V3, X509V3_R_UNKNOWN_OPTION); ERR_add_error_data(2, "name=", cnf->name); - return NULL; + return nullptr; } } @@ -123,54 +122,53 @@ static void *v2i_AUTHORITY_KEYID(const X509V3_EXT_METHOD *method, return AUTHORITY_KEYID_new(); } OPENSSL_PUT_ERROR(X509V3, X509V3_R_NO_ISSUER_CERTIFICATE); - return NULL; + return nullptr; } - cert = ctx->issuer_cert; - - if (keyid) { - j = X509_get_ext_by_NID(cert, NID_subject_key_identifier, -1); - const X509_EXTENSION *ext; - if ((j >= 0) && (ext = X509_get_ext(cert, j))) { - ikeyid = reinterpret_cast(X509V3_EXT_d2i(ext)); + UniquePtr key_id; + if (use_key_id != kOff) { + int critical; + key_id.reset(static_cast(X509_get_ext_d2i( + ctx->issuer_cert, NID_subject_key_identifier, &critical, nullptr))); + if (key_id == nullptr && critical != -1) { + return nullptr; // Syntax error in the extension. } - if (keyid == 2 && !ikeyid) { + if (use_key_id == kAlways && key_id == nullptr) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_UNABLE_TO_GET_ISSUER_KEYID); - return NULL; + return nullptr; } } - if ((issuer && !ikeyid) || (issuer == 2)) { - isname = X509_NAME_dup(X509_get_issuer_name(cert)); - serial = ASN1_INTEGER_dup(X509_get0_serialNumber(cert)); - if (!isname || !serial) { + UniquePtr serial; + UniquePtr issuer_gens; + if ((use_issuer == kOn && key_id == nullptr) || use_issuer == kAlways) { + UniquePtr issuer_name( + X509_NAME_dup(X509_get_issuer_name(ctx->issuer_cert))); + serial.reset(ASN1_INTEGER_dup(X509_get0_serialNumber(ctx->issuer_cert))); + if (issuer_name == nullptr || serial == nullptr) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_UNABLE_TO_GET_ISSUER_DETAILS); - goto err; + return nullptr; } - } - - if (!(akeyid = AUTHORITY_KEYID_new())) { - goto err; - } - - if (isname) { - if (!(gens = sk_GENERAL_NAME_new_null()) || !(gen = GENERAL_NAME_new()) || - !sk_GENERAL_NAME_push(gens, gen)) { - goto err; + // AKID wraps the issuer name in a GeneralNames structure. + UniquePtr gen(GENERAL_NAME_new()); + if (gen == nullptr) { + return nullptr; } gen->type = GEN_DIRNAME; - gen->d.dirn = isname; + gen->d.directoryName = issuer_name.release(); + issuer_gens.reset(sk_GENERAL_NAME_new_null()); + if (issuer_gens == nullptr || + !PushToStack(issuer_gens.get(), std::move(gen))) { + return nullptr; + } } - akeyid->issuer = gens; - akeyid->serial = serial; - akeyid->keyid = ikeyid; - - return akeyid; - -err: - X509_NAME_free(isname); - ASN1_INTEGER_free(serial); - ASN1_OCTET_STRING_free(ikeyid); - return NULL; + UniquePtr akid(AUTHORITY_KEYID_new()); + if (akid == nullptr) { + return nullptr; + } + akid->issuer = issuer_gens.release(); + akid->serial = serial.release(); + akid->keyid = key_id.release(); + return akid.release(); } diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_akeya.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_akeya.cc index b4107ce2..2e794d94 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_akeya.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_akeya.cc @@ -1,11 +1,16 @@ -/* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -19,8 +24,8 @@ ASN1_SEQUENCE(AUTHORITY_KEYID) = { ASN1_IMP_OPT(AUTHORITY_KEYID, keyid, ASN1_OCTET_STRING, 0), - ASN1_IMP_SEQUENCE_OF_OPT(AUTHORITY_KEYID, issuer, GENERAL_NAME, 1), + ASN1_IMP_SEQUENCE_OF_OPT(AUTHORITY_KEYID, issuer, bssl::GENERAL_NAME, 1), ASN1_IMP_OPT(AUTHORITY_KEYID, serial, ASN1_INTEGER, 2), } ASN1_SEQUENCE_END(AUTHORITY_KEYID) -IMPLEMENT_ASN1_FUNCTIONS(AUTHORITY_KEYID) +IMPLEMENT_ASN1_FUNCTIONS_const(AUTHORITY_KEYID) diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_alt.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_alt.cc index 50f9b21b..ec2a09d3 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_alt.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_alt.cc @@ -1,25 +1,32 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "ext_dat.h" #include "internal.h" +using namespace bssl; + static void *v2i_subject_alt(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, const STACK_OF(CONF_VALUE) *nval); @@ -38,29 +45,69 @@ static STACK_OF(CONF_VALUE) *i2v_GENERAL_NAMES_cb( return i2v_GENERAL_NAMES(method, reinterpret_cast(ext), ret); } -const X509V3_EXT_METHOD v3_alt[] = { - {NID_subject_alt_name, 0, ASN1_ITEM_ref(GENERAL_NAMES), 0, 0, 0, 0, 0, 0, - i2v_GENERAL_NAMES_cb, v2i_subject_alt, NULL, NULL, NULL}, +const X509V3_EXT_METHOD bssl::v3_subject_alt_name = { + NID_subject_alt_name, + 0, + ASN1_ITEM_ref(GENERAL_NAMES), + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + i2v_GENERAL_NAMES_cb, + v2i_subject_alt, + nullptr, + nullptr, + nullptr, +}; - {NID_issuer_alt_name, 0, ASN1_ITEM_ref(GENERAL_NAMES), 0, 0, 0, 0, 0, 0, - i2v_GENERAL_NAMES_cb, v2i_issuer_alt, NULL, NULL, NULL}, +const X509V3_EXT_METHOD bssl::v3_issuer_alt_name = { + NID_issuer_alt_name, + 0, + ASN1_ITEM_ref(GENERAL_NAMES), + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + i2v_GENERAL_NAMES_cb, + v2i_issuer_alt, + nullptr, + nullptr, + nullptr, +}; - {NID_certificate_issuer, 0, ASN1_ITEM_ref(GENERAL_NAMES), 0, 0, 0, 0, 0, 0, - i2v_GENERAL_NAMES_cb, NULL, NULL, NULL, NULL}, +const X509V3_EXT_METHOD bssl::v3_certificate_issuer = { + NID_certificate_issuer, + 0, + ASN1_ITEM_ref(GENERAL_NAMES), + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + i2v_GENERAL_NAMES_cb, + nullptr, + nullptr, + nullptr, + nullptr, }; STACK_OF(CONF_VALUE) *i2v_GENERAL_NAMES(const X509V3_EXT_METHOD *method, const GENERAL_NAMES *gens, STACK_OF(CONF_VALUE) *ret) { - int ret_was_null = ret == NULL; + int ret_was_null = ret == nullptr; for (size_t i = 0; i < sk_GENERAL_NAME_num(gens); i++) { const GENERAL_NAME *gen = sk_GENERAL_NAME_value(gens, i); STACK_OF(CONF_VALUE) *tmp = i2v_GENERAL_NAME(method, gen, ret); - if (tmp == NULL) { + if (tmp == nullptr) { if (ret_was_null) { sk_CONF_VALUE_pop_free(ret, X509V3_conf_free); } - return NULL; + return nullptr; } ret = tmp; } @@ -74,7 +121,7 @@ STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(const X509V3_EXT_METHOD *method, const GENERAL_NAME *gen, STACK_OF(CONF_VALUE) *ret) { // Note the error-handling for this function relies on there being at most - // one |X509V3_add_value| call. If there were two and the second failed, we + // one `X509V3_add_value` call. If there were two and the second failed, we // would need to sometimes free the first call's result. unsigned char *p; char oline[256], htmp[5]; @@ -82,44 +129,44 @@ STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(const X509V3_EXT_METHOD *method, switch (gen->type) { case GEN_OTHERNAME: if (!X509V3_add_value("othername", "", &ret)) { - return NULL; + return nullptr; } break; case GEN_X400: if (!X509V3_add_value("X400Name", "", &ret)) { - return NULL; + return nullptr; } break; case GEN_EDIPARTY: if (!X509V3_add_value("EdiPartyName", "", &ret)) { - return NULL; + return nullptr; } break; case GEN_EMAIL: if (!x509V3_add_value_asn1_string("email", gen->d.ia5, &ret)) { - return NULL; + return nullptr; } break; case GEN_DNS: if (!x509V3_add_value_asn1_string("DNS", gen->d.ia5, &ret)) { - return NULL; + return nullptr; } break; case GEN_URI: if (!x509V3_add_value_asn1_string("URI", gen->d.ia5, &ret)) { - return NULL; + return nullptr; } break; case GEN_DIRNAME: - if (X509_NAME_oneline(gen->d.dirn, oline, 256) == NULL || + if (X509_NAME_oneline(gen->d.dirn, oline, 256) == nullptr || !X509V3_add_value("DirName", oline, &ret)) { - return NULL; + return nullptr; } break; @@ -140,19 +187,19 @@ STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(const X509V3_EXT_METHOD *method, } } else { if (!X509V3_add_value("IP Address", "", &ret)) { - return NULL; + return nullptr; } break; } if (!X509V3_add_value("IP Address", oline, &ret)) { - return NULL; + return nullptr; } break; case GEN_RID: i2t_ASN1_OBJECT(oline, 256, gen->d.rid); if (!X509V3_add_value("Registered ID", oline, &ret)) { - return NULL; + return nullptr; } break; } @@ -225,8 +272,8 @@ 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 == NULL) { - return 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); @@ -237,7 +284,7 @@ static void *v2i_issuer_alt(const X509V3_EXT_METHOD *method, } } else { GENERAL_NAME *gen = v2i_GENERAL_NAME(method, ctx, cnf); - if (gen == NULL || !sk_GENERAL_NAME_push(gens, gen)) { + if (gen == nullptr || !sk_GENERAL_NAME_push(gens, gen)) { GENERAL_NAME_free(gen); goto err; } @@ -246,7 +293,7 @@ static void *v2i_issuer_alt(const X509V3_EXT_METHOD *method, return gens; err: sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free); - return NULL; + return nullptr; } // Append subject altname of issuer to issuer alt name of subject @@ -265,7 +312,7 @@ static int copy_issuer(const X509V3_CTX *ctx, GENERAL_NAMES *gens) { } int ret = 0; - GENERAL_NAMES *ialt = NULL; + GENERAL_NAMES *ialt = nullptr; X509_EXTENSION *ext; if (!(ext = X509_get_ext(ctx->issuer_cert, i)) || !(ialt = reinterpret_cast(X509V3_EXT_d2i(ext)))) { @@ -278,8 +325,8 @@ static int copy_issuer(const X509V3_CTX *ctx, GENERAL_NAMES *gens) { if (!sk_GENERAL_NAME_push(gens, gen)) { goto err; } - // Ownership of |gen| has moved from |ialt| to |gens|. - sk_GENERAL_NAME_set(ialt, j, NULL); + // Ownership of `gen` has moved from `ialt` to `gens`. + sk_GENERAL_NAME_set(ialt, j, nullptr); } ret = 1; @@ -293,8 +340,8 @@ 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 == NULL) { - return 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); @@ -310,7 +357,7 @@ static void *v2i_subject_alt(const X509V3_EXT_METHOD *method, } } else { GENERAL_NAME *gen = v2i_GENERAL_NAME(method, ctx, cnf); - if (gen == NULL || !sk_GENERAL_NAME_push(gens, gen)) { + if (gen == nullptr || !sk_GENERAL_NAME_push(gens, gen)) { GENERAL_NAME_free(gen); goto err; } @@ -319,18 +366,18 @@ static void *v2i_subject_alt(const X509V3_EXT_METHOD *method, return gens; err: sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free); - return NULL; + return nullptr; } // Copy any email addresses in a certificate or request to GENERAL_NAMES static int copy_email(const X509V3_CTX *ctx, GENERAL_NAMES *gens, int move_p) { X509_NAME *nm; - ASN1_IA5STRING *email = NULL; + ASN1_IA5STRING *email = nullptr; X509_NAME_ENTRY *ne; - GENERAL_NAME *gen = NULL; + GENERAL_NAME *gen = nullptr; int i; - if (ctx != NULL && ctx->flags == X509V3_CTX_TEST) { + if (ctx != nullptr && ctx->flags == X509V3_CTX_TEST) { return 1; } if (!ctx || (!ctx->subject_cert && !ctx->subject_req)) { @@ -358,12 +405,12 @@ static int copy_email(const X509V3_CTX *ctx, GENERAL_NAMES *gens, int move_p) { goto err; } gen->d.ia5 = email; - email = NULL; + email = nullptr; gen->type = GEN_EMAIL; if (!sk_GENERAL_NAME_push(gens, gen)) { goto err; } - gen = NULL; + gen = nullptr; } return 1; @@ -374,17 +421,17 @@ err: return 0; } -GENERAL_NAMES *v2i_GENERAL_NAMES(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval) { +GENERAL_NAMES *bssl::v2i_GENERAL_NAMES(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 == NULL) { - return 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); GENERAL_NAME *gen = v2i_GENERAL_NAME(method, ctx, cnf); - if (gen == NULL || !sk_GENERAL_NAME_push(gens, gen)) { + if (gen == nullptr || !sk_GENERAL_NAME_push(gens, gen)) { GENERAL_NAME_free(gen); goto err; } @@ -392,12 +439,13 @@ GENERAL_NAMES *v2i_GENERAL_NAMES(const X509V3_EXT_METHOD *method, return gens; err: sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free); - return NULL; + return nullptr; } -GENERAL_NAME *v2i_GENERAL_NAME(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, const CONF_VALUE *cnf) { - return v2i_GENERAL_NAME_ex(NULL, method, ctx, cnf, 0); +GENERAL_NAME *bssl::v2i_GENERAL_NAME(const X509V3_EXT_METHOD *method, + const X509V3_CTX *ctx, + const CONF_VALUE *cnf) { + return v2i_GENERAL_NAME_ex(nullptr, method, ctx, cnf, 0); } static GENERAL_NAME *a2i_GENERAL_NAME(GENERAL_NAME *out, @@ -406,16 +454,16 @@ static GENERAL_NAME *a2i_GENERAL_NAME(GENERAL_NAME *out, const char *value, int is_nc) { if (!value) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_MISSING_VALUE); - return NULL; + return nullptr; } - GENERAL_NAME *gen = NULL; + GENERAL_NAME *gen = nullptr; if (out) { gen = out; } else { gen = GENERAL_NAME_new(); - if (gen == NULL) { - return NULL; + if (gen == nullptr) { + return nullptr; } } @@ -424,7 +472,7 @@ static GENERAL_NAME *a2i_GENERAL_NAME(GENERAL_NAME *out, case GEN_EMAIL: case GEN_DNS: { ASN1_IA5STRING *str = ASN1_IA5STRING_new(); - if (str == NULL || !ASN1_STRING_set(str, value, strlen(value))) { + if (str == nullptr || !ASN1_STRING_set(str, value, strlen(value))) { ASN1_STRING_free(str); goto err; } @@ -452,7 +500,7 @@ static GENERAL_NAME *a2i_GENERAL_NAME(GENERAL_NAME *out, } else { gen->d.ip = a2i_IPADDRESS(value); } - if (gen->d.ip == NULL) { + if (gen->d.ip == nullptr) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_BAD_IP_ADDRESS); ERR_add_error_data(2, "value=", value); goto err; @@ -483,18 +531,18 @@ err: if (!out) { GENERAL_NAME_free(gen); } - return NULL; + return nullptr; } -GENERAL_NAME *v2i_GENERAL_NAME_ex(GENERAL_NAME *out, - const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, const CONF_VALUE *cnf, - int is_nc) { +GENERAL_NAME *bssl::v2i_GENERAL_NAME_ex(GENERAL_NAME *out, + const X509V3_EXT_METHOD *method, + const X509V3_CTX *ctx, + const CONF_VALUE *cnf, int is_nc) { const char *name = cnf->name; const char *value = cnf->value; if (!value) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_MISSING_VALUE); - return NULL; + return nullptr; } int type; @@ -515,7 +563,7 @@ GENERAL_NAME *v2i_GENERAL_NAME_ex(GENERAL_NAME *out, } else { OPENSSL_PUT_ERROR(X509V3, X509V3_R_UNSUPPORTED_OPTION); ERR_add_error_data(2, "name=", name); - return NULL; + return nullptr; } return a2i_GENERAL_NAME(out, method, ctx, type, value, is_nc); @@ -524,29 +572,29 @@ GENERAL_NAME *v2i_GENERAL_NAME_ex(GENERAL_NAME *out, static int do_othername(GENERAL_NAME *gen, const char *value, const X509V3_CTX *ctx) { const char *semicolon = strchr(value, ';'); - if (semicolon == NULL) { + if (semicolon == nullptr) { return 0; } OTHERNAME *name = OTHERNAME_new(); - if (name == NULL) { + if (name == nullptr) { return 0; } char *objtmp = OPENSSL_strndup(value, semicolon - value); - if (objtmp == NULL) { + 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 == NULL) { + if (name->type_id == nullptr) { goto err; } ASN1_TYPE_free(name->value); name->value = ASN1_generate_v3(semicolon + 1, ctx); - if (name->value == NULL) { + if (name->value == nullptr) { goto err; } @@ -564,10 +612,10 @@ static int do_dirname(GENERAL_NAME *gen, const char *value, int ret = 0; const STACK_OF(CONF_VALUE) *sk = X509V3_get_section(ctx, value); X509_NAME *nm = X509_NAME_new(); - if (nm == NULL) { + if (nm == nullptr) { goto err; } - if (sk == NULL) { + if (sk == nullptr) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_SECTION_NOT_FOUND); ERR_add_error_data(2, "section=", value); goto err; diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_bcons.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_bcons.cc index c4b39268..fb72834d 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_bcons.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_bcons.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,31 +22,32 @@ #include #include -#include "ext_dat.h" #include "internal.h" +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 v3_bcons = { +const X509V3_EXT_METHOD bssl::v3_bcons = { NID_basic_constraints, 0, ASN1_ITEM_ref(BASIC_CONSTRAINTS), - 0, - 0, - 0, - 0, - 0, - 0, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, i2v_BASIC_CONSTRAINTS, v2i_BASIC_CONSTRAINTS, - NULL, - NULL, - NULL, + nullptr, + nullptr, + nullptr, }; ASN1_SEQUENCE(BASIC_CONSTRAINTS) = { @@ -63,9 +69,9 @@ static STACK_OF(CONF_VALUE) *i2v_BASIC_CONSTRAINTS( static void *v2i_BASIC_CONSTRAINTS(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, const STACK_OF(CONF_VALUE) *values) { - BASIC_CONSTRAINTS *bcons = NULL; + BASIC_CONSTRAINTS *bcons = nullptr; if (!(bcons = BASIC_CONSTRAINTS_new())) { - return NULL; + return nullptr; } for (size_t i = 0; i < sk_CONF_VALUE_num(values); i++) { const CONF_VALUE *val = sk_CONF_VALUE_value(values, i); @@ -86,5 +92,5 @@ static void *v2i_BASIC_CONSTRAINTS(const X509V3_EXT_METHOD *method, return bcons; err: BASIC_CONSTRAINTS_free(bcons); - return NULL; + return nullptr; } diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_bitst.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_bitst.cc index adc7ade0..1a233934 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_bitst.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_bitst.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -15,20 +20,17 @@ #include #include -#include "ext_dat.h" #include "internal.h" +using namespace bssl; + static 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, NULL, NULL}}; + {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[] = { {0, "Digital Signature", "digitalSignature"}, @@ -40,7 +42,7 @@ static const BIT_STRING_BITNAME key_usage_type_table[] = { {6, "CRL Sign", "cRLSign"}, {7, "Encipher Only", "encipherOnly"}, {8, "Decipher Only", "decipherOnly"}, - {-1, NULL, NULL}}; + {-1, nullptr, nullptr}}; static STACK_OF(CONF_VALUE) *i2v_ASN1_BIT_STRING( const X509V3_EXT_METHOD *method, void *ext, STACK_OF(CONF_VALUE) *ret) { @@ -49,7 +51,7 @@ static STACK_OF(CONF_VALUE) *i2v_ASN1_BIT_STRING( for (bnam = reinterpret_cast(method->usr_data); bnam->lname; bnam++) { if (ASN1_BIT_STRING_get_bit(bits, bnam->bitnum)) { - X509V3_add_value(bnam->lname, NULL, &ret); + X509V3_add_value(bnam->lname, nullptr, &ret); } } return ret; @@ -60,7 +62,7 @@ static void *v2i_ASN1_BIT_STRING(const X509V3_EXT_METHOD *method, const STACK_OF(CONF_VALUE) *nval) { ASN1_BIT_STRING *bs; if (!(bs = ASN1_BIT_STRING_new())) { - return NULL; + return nullptr; } for (size_t i = 0; i < sk_CONF_VALUE_num(nval); i++) { const CONF_VALUE *val = sk_CONF_VALUE_value(nval, i); @@ -70,7 +72,7 @@ static void *v2i_ASN1_BIT_STRING(const X509V3_EXT_METHOD *method, if (!strcmp(bnam->sname, val->name) || !strcmp(bnam->lname, val->name)) { if (!ASN1_BIT_STRING_set_bit(bs, bnam->bitnum, 1)) { ASN1_BIT_STRING_free(bs); - return NULL; + return nullptr; } break; } @@ -79,7 +81,7 @@ static void *v2i_ASN1_BIT_STRING(const X509V3_EXT_METHOD *method, OPENSSL_PUT_ERROR(X509V3, X509V3_R_UNKNOWN_BIT_STRING_ARGUMENT); X509V3_conf_err(val); ASN1_BIT_STRING_free(bs); - return NULL; + return nullptr; } } return bs; @@ -88,10 +90,11 @@ static void *v2i_ASN1_BIT_STRING(const X509V3_EXT_METHOD *method, #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, NULL, NULL, (void *)(table) \ + i2v_ASN1_BIT_STRING, v2i_ASN1_BIT_STRING, nullptr, nullptr, \ + (void *)(table) \ } -const X509V3_EXT_METHOD v3_nscert = +const X509V3_EXT_METHOD bssl::v3_nscert = EXT_BITSTRING(NID_netscape_cert_type, ns_cert_type_table); -const X509V3_EXT_METHOD v3_key_usage = +const X509V3_EXT_METHOD bssl::v3_key_usage = EXT_BITSTRING(NID_key_usage, key_usage_type_table); diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_conf.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_conf.cc index fbb81222..9f014b5f 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_conf.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_conf.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. // extension creation utilities @@ -23,6 +28,9 @@ #include "../internal.h" #include "internal.h" + +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, @@ -37,10 +45,10 @@ static unsigned char *generic_asn1(const char *value, const X509V3_CTX *ctx, 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|. + // If omitted, fill in an empty `X509V3_CTX`. X509V3_CTX ctx_tmp; - if (ctx == NULL) { - X509V3_set_ctx(&ctx_tmp, NULL, NULL, NULL, NULL, 0); + if (ctx == nullptr) { + X509V3_set_ctx(&ctx_tmp, nullptr, nullptr, nullptr, nullptr, 0); X509V3_set_nconf(&ctx_tmp, conf); ctx = &ctx_tmp; } @@ -60,10 +68,10 @@ X509_EXTENSION *X509V3_EXT_nconf(const CONF *conf, const X509V3_CTX *ctx, 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|. + // If omitted, fill in an empty `X509V3_CTX`. X509V3_CTX ctx_tmp; - if (ctx == NULL) { - X509V3_set_ctx(&ctx_tmp, NULL, NULL, NULL, NULL, 0); + if (ctx == nullptr) { + X509V3_set_ctx(&ctx_tmp, nullptr, nullptr, nullptr, nullptr, 0); X509V3_set_nconf(&ctx_tmp, conf); ctx = &ctx_tmp; } @@ -84,62 +92,62 @@ static X509_EXTENSION *do_ext_nconf(const CONF *conf, const X509V3_CTX *ctx, const X509V3_EXT_METHOD *method; X509_EXTENSION *ext; const STACK_OF(CONF_VALUE) *nval; - STACK_OF(CONF_VALUE) *nval_owned = NULL; + STACK_OF(CONF_VALUE) *nval_owned = nullptr; void *ext_struc; if (ext_nid == NID_undef) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_UNKNOWN_EXTENSION_NAME); - return NULL; + return nullptr; } if (!(method = X509V3_EXT_get_nid(ext_nid))) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_UNKNOWN_EXTENSION); - return NULL; + return nullptr; } // Now get internal extension representation based on type if (method->v2i) { if (*value == '@') { - // TODO(davidben): This is the only place where |X509V3_EXT_nconf|'s - // |conf| parameter is used. All other codepaths use the copy inside - // |ctx|. Should this be switched and then the parameter ignored? - if (conf == NULL) { + // TODO(davidben): This is the only place where `X509V3_EXT_nconf`'s + // `conf` parameter is used. All other codepaths use the copy inside + // `ctx`. Should this be switched and then the parameter ignored? + if (conf == nullptr) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_NO_CONFIG_DATABASE); - return NULL; + return nullptr; } nval = NCONF_get_section(conf, value + 1); } else { nval_owned = X509V3_parse_list(value); nval = nval_owned; } - if (nval == NULL || sk_CONF_VALUE_num(nval) <= 0) { + if (nval == nullptr || sk_CONF_VALUE_num(nval) <= 0) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_EXTENSION_STRING); ERR_add_error_data(4, "name=", OBJ_nid2sn(ext_nid), ",section=", value); sk_CONF_VALUE_pop_free(nval_owned, X509V3_conf_free); - return NULL; + return nullptr; } ext_struc = method->v2i(method, ctx, nval); sk_CONF_VALUE_pop_free(nval_owned, X509V3_conf_free); if (!ext_struc) { - return NULL; + return nullptr; } } else if (method->s2i) { if (!(ext_struc = method->s2i(method, ctx, value))) { - return NULL; + return nullptr; } } else if (method->r2i) { // TODO(davidben): Should this check be removed? This matches OpenSSL, but // r2i-based extensions do not necessarily require a config database. The // two built-in extensions only use it some of the time, and already handle - // |X509V3_get_section| returning NULL. + // `X509V3_get_section` returning NULL. if (!ctx->db) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_NO_CONFIG_DATABASE); - return NULL; + return nullptr; } if (!(ext_struc = method->r2i(method, ctx, value))) { - return NULL; + return nullptr; } } else { OPENSSL_PUT_ERROR(X509V3, X509V3_R_EXTENSION_SETTING_NOT_SUPPORTED); ERR_add_error_data(2, "name=", OBJ_nid2sn(ext_nid)); - return NULL; + return nullptr; } ext = do_ext_i2d(method, ext_nid, crit, ext_struc); @@ -151,22 +159,22 @@ static X509_EXTENSION *do_ext_nconf(const CONF *conf, const X509V3_CTX *ctx, 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 = NULL; + 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 NULL; + return nullptr; } ASN1_OCTET_STRING *ext_oct = ASN1_OCTET_STRING_new(); - if (ext_oct == NULL) { + if (ext_oct == nullptr) { OPENSSL_free(ext_der); - return NULL; + return nullptr; } ASN1_STRING_set0(ext_oct, ext_der, ext_len); X509_EXTENSION *ext = - X509_EXTENSION_create_by_NID(NULL, ext_nid, crit, ext_oct); + X509_EXTENSION_create_by_NID(nullptr, ext_nid, crit, ext_oct); ASN1_OCTET_STRING_free(ext_oct); return ext; } @@ -177,7 +185,7 @@ 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 NULL; + return nullptr; } return do_ext_i2d(method, ext_nid, crit, ext_struc); } @@ -221,62 +229,54 @@ static int v3_check_generic(const char **value) { static X509_EXTENSION *v3_generic_extension(const char *ext, const char *value, int crit, int gen_type, const X509V3_CTX *ctx) { - unsigned char *ext_der = NULL; - size_t ext_len = 0; - ASN1_OBJECT *obj = NULL; - ASN1_OCTET_STRING *oct = NULL; - X509_EXTENSION *extension = NULL; - if (!(obj = OBJ_txt2obj(ext, 0))) { + UniquePtr obj(OBJ_txt2obj(ext, 0)); + if (obj == nullptr) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_EXTENSION_NAME_ERROR); ERR_add_error_data(2, "name=", ext); - goto err; + return nullptr; } + UniquePtr ext_der; + size_t ext_len = 0; if (gen_type == 1) { - ext_der = x509v3_hex_to_bytes(value, &ext_len); + ext_der.reset(x509v3_hex_to_bytes(value, &ext_len)); } else if (gen_type == 2) { - ext_der = generic_asn1(value, ctx, &ext_len); + ext_der.reset(generic_asn1(value, ctx, &ext_len)); } - if (ext_der == NULL) { + if (ext_der == nullptr) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_EXTENSION_VALUE_ERROR); ERR_add_error_data(2, "value=", value); - goto err; + return nullptr; } if (ext_len > INT_MAX) { OPENSSL_PUT_ERROR(X509V3, ERR_R_OVERFLOW); - goto err; + return nullptr; } - oct = ASN1_OCTET_STRING_new(); - if (oct == NULL) { - goto err; + UniquePtr oct(ASN1_OCTET_STRING_new()); + if (oct == nullptr) { + return nullptr; } - ASN1_STRING_set0(oct, ext_der, (int)ext_len); - ext_der = NULL; + ASN1_STRING_set0(oct.get(), ext_der.get(), (int)ext_len); + ext_der.release(); // ASN1_STRING_set0 took ownership. - extension = X509_EXTENSION_create_by_OBJ(NULL, obj, crit, oct); - -err: - ASN1_OBJECT_free(obj); - ASN1_OCTET_STRING_free(oct); - OPENSSL_free(ext_der); - return extension; + 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 == NULL) { - return NULL; + if (typ == nullptr) { + return nullptr; } - unsigned char *ext_der = NULL; + unsigned char *ext_der = nullptr; int len = i2d_ASN1_TYPE(typ, &ext_der); ASN1_TYPE_free(typ); if (len < 0) { - return NULL; + return nullptr; } *ext_len = len; return ext_der; @@ -289,14 +289,14 @@ int X509V3_EXT_add_nconf_sk(const CONF *conf, const X509V3_CTX *ctx, const char *section, STACK_OF(X509_EXTENSION) **sk) { const STACK_OF(CONF_VALUE) *nval = NCONF_get_section(conf, section); - if (nval == NULL) { + if (nval == nullptr) { return 0; } for (size_t i = 0; i < sk_CONF_VALUE_num(nval); i++) { const CONF_VALUE *val = sk_CONF_VALUE_value(nval, i); X509_EXTENSION *ext = X509V3_EXT_nconf(conf, ctx, val->name, val->value); - int ok = ext != NULL && // - (sk == NULL || X509v3_add_ext(sk, ext, -1) != NULL); + int ok = ext != nullptr && // + (sk == nullptr || X509v3_add_ext(sk, ext, -1) != nullptr); X509_EXTENSION_free(ext); if (!ok) { return 0; @@ -309,9 +309,9 @@ int X509V3_EXT_add_nconf_sk(const CONF *conf, const X509V3_CTX *ctx, int X509V3_EXT_add_nconf(const CONF *conf, const X509V3_CTX *ctx, const char *section, X509 *cert) { - STACK_OF(X509_EXTENSION) **sk = NULL; + STACK_OF(X509_EXTENSION) **sk = nullptr; if (cert) { - sk = &cert->cert_info->extensions; + sk = &FromOpaque(cert)->extensions; } return X509V3_EXT_add_nconf_sk(conf, ctx, section, sk); } @@ -320,7 +320,7 @@ int X509V3_EXT_add_nconf(const CONF *conf, const X509V3_CTX *ctx, int X509V3_EXT_CRL_add_nconf(const CONF *conf, const X509V3_CTX *ctx, const char *section, X509_CRL *crl) { - STACK_OF(X509_EXTENSION) **sk = NULL; + STACK_OF(X509_EXTENSION) **sk = nullptr; if (crl) { sk = &crl->crl->extensions; } @@ -331,7 +331,7 @@ int X509V3_EXT_CRL_add_nconf(const CONF *conf, const X509V3_CTX *ctx, int X509V3_EXT_REQ_add_nconf(const CONF *conf, const X509V3_CTX *ctx, const char *section, X509_REQ *req) { - STACK_OF(X509_EXTENSION) *extlist = NULL, **sk = NULL; + STACK_OF(X509_EXTENSION) *extlist = nullptr, **sk = nullptr; int i; if (req) { sk = &extlist; @@ -347,11 +347,11 @@ int X509V3_EXT_REQ_add_nconf(const CONF *conf, const X509V3_CTX *ctx, // Config database functions -const STACK_OF(CONF_VALUE) *X509V3_get_section(const X509V3_CTX *ctx, - const char *section) { - if (ctx->db == NULL) { +const STACK_OF(CONF_VALUE) *bssl::X509V3_get_section(const X509V3_CTX *ctx, + const char *section) { + if (ctx->db == nullptr) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_OPERATION_NOT_DEFINED); - return NULL; + return nullptr; } return NCONF_get_section(ctx->db, section); } diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_cpols.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_cpols.cc index 153b98eb..a60333d6 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_cpols.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_cpols.cc @@ -1,15 +1,22 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -19,9 +26,11 @@ #include #include -#include "ext_dat.h" #include "internal.h" + +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, @@ -31,49 +40,44 @@ static void *r2i_certpol(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, 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 POLICYINFO *policy_section(const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *polstrs, - int ia5org); -static POLICYQUALINFO *notice_section(const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *unot, - int ia5org); +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 v3_cpols = { +const X509V3_EXT_METHOD bssl::v3_cpols = { NID_certificate_policies, 0, ASN1_ITEM_ref(CERTIFICATEPOLICIES), - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, i2r_certpol, r2i_certpol, - NULL, + nullptr, }; -DECLARE_ASN1_ITEM(POLICYINFO) -DECLARE_ASN1_ITEM(POLICYQUALINFO) -DECLARE_ASN1_ITEM(USERNOTICE) -DECLARE_ASN1_ITEM(NOTICEREF) +ASN1_SEQUENCE(NOTICEREF) = { + ASN1_SIMPLE(NOTICEREF, organization, DISPLAYTEXT), + ASN1_SEQUENCE_OF(NOTICEREF, noticenos, ASN1_INTEGER), +} ASN1_SEQUENCE_END(NOTICEREF) -ASN1_ITEM_TEMPLATE(CERTIFICATEPOLICIES) = ASN1_EX_TEMPLATE_TYPE( - ASN1_TFLG_SEQUENCE_OF, 0, CERTIFICATEPOLICIES, POLICYINFO) -ASN1_ITEM_TEMPLATE_END(CERTIFICATEPOLICIES) +IMPLEMENT_ASN1_ALLOC_FUNCTIONS(NOTICEREF) -IMPLEMENT_ASN1_FUNCTIONS_const(CERTIFICATEPOLICIES) +ASN1_SEQUENCE(USERNOTICE) = { + ASN1_OPT(USERNOTICE, noticeref, NOTICEREF), + ASN1_OPT(USERNOTICE, exptext, DISPLAYTEXT), +} ASN1_SEQUENCE_END(USERNOTICE) -ASN1_SEQUENCE(POLICYINFO) = { - ASN1_SIMPLE(POLICYINFO, policyid, ASN1_OBJECT), - ASN1_SEQUENCE_OF_OPT(POLICYINFO, qualifiers, POLICYQUALINFO), -} ASN1_SEQUENCE_END(POLICYINFO) - -IMPLEMENT_ASN1_ALLOC_FUNCTIONS(POLICYINFO) +IMPLEMENT_ASN1_ALLOC_FUNCTIONS(USERNOTICE) ASN1_ADB_TEMPLATE(policydefault) = ASN1_SIMPLE(POLICYQUALINFO, d.other, ASN1_ANY); @@ -92,202 +96,184 @@ ASN1_SEQUENCE(POLICYQUALINFO) = { IMPLEMENT_ASN1_ALLOC_FUNCTIONS(POLICYQUALINFO) -ASN1_SEQUENCE(USERNOTICE) = { - ASN1_OPT(USERNOTICE, noticeref, NOTICEREF), - ASN1_OPT(USERNOTICE, exptext, DISPLAYTEXT), -} ASN1_SEQUENCE_END(USERNOTICE) +ASN1_SEQUENCE(POLICYINFO) = { + ASN1_SIMPLE(POLICYINFO, policyid, ASN1_OBJECT), + ASN1_SEQUENCE_OF_OPT(POLICYINFO, qualifiers, POLICYQUALINFO), +} ASN1_SEQUENCE_END(POLICYINFO) -IMPLEMENT_ASN1_ALLOC_FUNCTIONS(USERNOTICE) +IMPLEMENT_ASN1_ALLOC_FUNCTIONS(POLICYINFO) -ASN1_SEQUENCE(NOTICEREF) = { - ASN1_SIMPLE(NOTICEREF, organization, DISPLAYTEXT), - ASN1_SEQUENCE_OF(NOTICEREF, noticenos, ASN1_INTEGER), -} ASN1_SEQUENCE_END(NOTICEREF) +ASN1_ITEM_TEMPLATE(CERTIFICATEPOLICIES) = ASN1_EX_TEMPLATE_TYPE( + ASN1_TFLG_SEQUENCE_OF, 0, CERTIFICATEPOLICIES, POLICYINFO) +ASN1_ITEM_TEMPLATE_END(CERTIFICATEPOLICIES) -IMPLEMENT_ASN1_ALLOC_FUNCTIONS(NOTICEREF) +IMPLEMENT_ASN1_FUNCTIONS_const(CERTIFICATEPOLICIES) static void *r2i_certpol(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, const char *value) { - STACK_OF(POLICYINFO) *pols = sk_POLICYINFO_new_null(); - if (pols == NULL) { - return NULL; + UniquePtr pols(sk_POLICYINFO_new_null()); + if (pols == nullptr) { + return nullptr; } - STACK_OF(CONF_VALUE) *vals = X509V3_parse_list(value); - - { - if (vals == NULL) { - OPENSSL_PUT_ERROR(X509V3, ERR_R_X509V3_LIB); - goto err; + UniquePtr vals(X509V3_parse_list(value)); + if (vals == nullptr) { + OPENSSL_PUT_ERROR(X509V3, ERR_R_X509V3_LIB); + 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; } - int ia5org = 0; - for (size_t i = 0; i < sk_CONF_VALUE_num(vals); i++) { - const CONF_VALUE *cnf = sk_CONF_VALUE_value(vals, i); - if (cnf->value || !cnf->name) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_POLICY_IDENTIFIER); + 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); - goto err; + return nullptr; } - POLICYINFO *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); - goto err; - } - pol = policy_section(ctx, polsect, ia5org); - if (!pol) { - goto err; - } - } else { - ASN1_OBJECT *pobj = OBJ_txt2obj(cnf->name, 0); - if (pobj == NULL) { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_OBJECT_IDENTIFIER); - X509V3_conf_err(cnf); - goto err; - } - pol = POLICYINFO_new(); - if (pol == NULL) { - ASN1_OBJECT_free(pobj); - goto err; - } - pol->policyid = pobj; + pol = policy_section(ctx, polsect, ia5org); + if (!pol) { + return nullptr; } - if (!sk_POLICYINFO_push(pols, pol)) { - POLICYINFO_free(pol); - goto err; + } 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; } + pol.reset(POLICYINFO_new()); + if (pol == nullptr) { + return nullptr; + } + pol->policyid = pobj.release(); + } + if (!PushToStack(pols.get(), std::move(pol))) { + return nullptr; } - sk_CONF_VALUE_pop_free(vals, X509V3_conf_free); - return pols; } - -err: - sk_CONF_VALUE_pop_free(vals, X509V3_conf_free); - sk_POLICYINFO_pop_free(pols, POLICYINFO_free); - return NULL; + return pols.release(); } -static POLICYINFO *policy_section(const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *polstrs, - int ia5org) { - POLICYINFO *pol; - POLICYQUALINFO *qual; - if (!(pol = POLICYINFO_new())) { - goto err; +static UniquePtr policy_section(const X509V3_CTX *ctx, + const STACK_OF(CONF_VALUE) *polstrs, + int ia5org) { + UniquePtr pol(POLICYINFO_new()); + if (pol == nullptr) { + return nullptr; } - for (size_t i = 0; i < sk_CONF_VALUE_num(polstrs); i++) { - const CONF_VALUE *cnf = sk_CONF_VALUE_value(polstrs, i); + for (const CONF_VALUE *cnf : polstrs) { if (!strcmp(cnf->name, "policyIdentifier")) { ASN1_OBJECT *pobj; if (!(pobj = OBJ_txt2obj(cnf->value, 0))) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_OBJECT_IDENTIFIER); X509V3_conf_err(cnf); - goto err; + return nullptr; } + ASN1_OBJECT_free(pol->policyid); pol->policyid = pobj; } else if (x509v3_conf_name_matches(cnf->name, "CPS")) { - if (!pol->qualifiers) { + if (pol->qualifiers == nullptr) { pol->qualifiers = sk_POLICYQUALINFO_new_null(); } - if (!(qual = POLICYQUALINFO_new())) { - goto err; - } - if (!sk_POLICYQUALINFO_push(pol->qualifiers, qual)) { - goto err; + UniquePtr qual(POLICYQUALINFO_new()); + if (qual == nullptr || pol->qualifiers == nullptr) { + return nullptr; } qual->pqualid = OBJ_nid2obj(NID_id_qt_cps); - if (qual->pqualid == NULL) { + if (qual->pqualid == nullptr) { OPENSSL_PUT_ERROR(X509V3, ERR_R_INTERNAL_ERROR); - goto err; + return nullptr; } qual->d.cpsuri = ASN1_IA5STRING_new(); - if (qual->d.cpsuri == NULL) { - goto err; + if (qual->d.cpsuri == nullptr) { + return nullptr; } if (!ASN1_STRING_set(qual->d.cpsuri, cnf->value, strlen(cnf->value))) { - goto err; + return nullptr; + } + if (!PushToStack(pol->qualifiers, std::move(qual))) { + return nullptr; } } else if (x509v3_conf_name_matches(cnf->name, "userNotice")) { if (*cnf->value != '@') { OPENSSL_PUT_ERROR(X509V3, X509V3_R_EXPECTED_A_SECTION_NAME); X509V3_conf_err(cnf); - goto err; + return nullptr; } const STACK_OF(CONF_VALUE) *unot = X509V3_get_section(ctx, cnf->value + 1); if (!unot) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_SECTION); X509V3_conf_err(cnf); - goto err; + return nullptr; } - qual = notice_section(ctx, unot, ia5org); - if (!qual) { - goto err; + UniquePtr qual = notice_section(ctx, unot, ia5org); + if (qual == nullptr) { + return nullptr; } - if (!pol->qualifiers) { + if (pol->qualifiers == nullptr) { pol->qualifiers = sk_POLICYQUALINFO_new_null(); } - if (!sk_POLICYQUALINFO_push(pol->qualifiers, qual)) { - goto err; + if (pol->qualifiers == nullptr || + !PushToStack(pol->qualifiers, std::move(qual))) { + return nullptr; } } else { OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_OPTION); X509V3_conf_err(cnf); - goto err; + return nullptr; } } if (!pol->policyid) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_NO_POLICY_IDENTIFIER); - goto err; + return nullptr; } return pol; - -err: - POLICYINFO_free(pol); - return NULL; } -static POLICYQUALINFO *notice_section(const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *unot, - int ia5org) { - USERNOTICE *notice; - POLICYQUALINFO *qual; - if (!(qual = POLICYQUALINFO_new())) { - goto err; +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 == NULL) { + if (qual->pqualid == nullptr) { OPENSSL_PUT_ERROR(X509V3, ERR_R_INTERNAL_ERROR); - goto err; + return nullptr; } - if (!(notice = USERNOTICE_new())) { - goto err; + USERNOTICE *notice = USERNOTICE_new(); + if (notice == nullptr) { + return nullptr; } qual->d.usernotice = notice; - for (size_t i = 0; i < sk_CONF_VALUE_num(unot); i++) { - const CONF_VALUE *cnf = sk_CONF_VALUE_value(unot, i); + for (const CONF_VALUE *cnf : unot) { if (!strcmp(cnf->name, "explicitText")) { notice->exptext = ASN1_VISIBLESTRING_new(); - if (notice->exptext == NULL) { - goto err; + if (notice->exptext == nullptr) { + return nullptr; } if (!ASN1_STRING_set(notice->exptext, cnf->value, strlen(cnf->value))) { - goto err; + return nullptr; } } else if (!strcmp(cnf->name, "organization")) { NOTICEREF *nref; if (!notice->noticeref) { if (!(nref = NOTICEREF_new())) { - goto err; + return nullptr; } notice->noticeref = nref; } else { @@ -300,57 +286,49 @@ static POLICYQUALINFO *notice_section(const X509V3_CTX *ctx, } if (!ASN1_STRING_set(nref->organization, cnf->value, strlen(cnf->value))) { - goto err; + return nullptr; } } else if (!strcmp(cnf->name, "noticeNumbers")) { NOTICEREF *nref; - STACK_OF(CONF_VALUE) *nos; if (!notice->noticeref) { if (!(nref = NOTICEREF_new())) { - goto err; + return nullptr; } notice->noticeref = nref; } else { nref = notice->noticeref; } - nos = X509V3_parse_list(cnf->value); - if (!nos || !sk_CONF_VALUE_num(nos)) { + 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); - sk_CONF_VALUE_pop_free(nos, X509V3_conf_free); - goto err; + return nullptr; } - int ret = nref_nos(nref->noticenos, nos); - sk_CONF_VALUE_pop_free(nos, X509V3_conf_free); - if (!ret) { - goto err; + if (!nref_nos(nref->noticenos, nos.get())) { + return nullptr; } } else { OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_OPTION); X509V3_conf_err(cnf); - goto err; + return nullptr; } } if (notice->noticeref && (!notice->noticeref->noticenos || !notice->noticeref->organization)) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_NEED_ORGANIZATION_AND_NUMBERS); - goto err; + return nullptr; } return qual; - -err: - POLICYQUALINFO_free(qual); - return NULL; } 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(NULL, cnf->name); - if (aint == NULL) { + ASN1_INTEGER *aint = s2i_ASN1_INTEGER(nullptr, cnf->name); + if (aint == nullptr) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NUMBER); return 0; } @@ -419,11 +397,11 @@ static void print_notice(BIO *out, const USERNOTICE *notice, int indent) { if (i) { BIO_puts(out, ", "); } - if (num == NULL) { + if (num == nullptr) { BIO_puts(out, "(null)"); } else { - tmp = i2s_ASN1_INTEGER(NULL, num); - if (tmp == NULL) { + tmp = i2s_ASN1_INTEGER(nullptr, num); + if (tmp == nullptr) { return; } BIO_puts(out, tmp); diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_crld.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_crld.cc index bf6f7946..008ae049 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_crld.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_crld.cc @@ -1,15 +1,23 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -18,91 +26,83 @@ #include #include -#include "ext_dat.h" +#include "../asn1/internal.h" +#include "../internal.h" #include "internal.h" +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); -const X509V3_EXT_METHOD v3_crld = { +const X509V3_EXT_METHOD bssl::v3_crld = { NID_crl_distribution_points, 0, ASN1_ITEM_ref(CRL_DIST_POINTS), - 0, - 0, - 0, - 0, - 0, - 0, - 0, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, v2i_crld, i2r_crldp, - 0, - NULL, + nullptr, + nullptr, }; -const X509V3_EXT_METHOD v3_freshest_crl = { - NID_freshest_crl, - 0, - ASN1_ITEM_ref(CRL_DIST_POINTS), - 0, - 0, - 0, - 0, - 0, - 0, - 0, - v2i_crld, - i2r_crldp, - 0, - NULL, +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, }; -static STACK_OF(GENERAL_NAME) *gnames_from_sectname(const X509V3_CTX *ctx, - char *sect) { +static UniquePtr gnames_from_sectname(const X509V3_CTX *ctx, + const char *sect) { const STACK_OF(CONF_VALUE) *gnsect; - STACK_OF(CONF_VALUE) *gnsect_owned = NULL; + UniquePtr gnsect_owned; if (*sect == '@') { gnsect = X509V3_get_section(ctx, sect + 1); } else { - gnsect_owned = X509V3_parse_list(sect); - gnsect = gnsect_owned; + gnsect_owned.reset(X509V3_parse_list(sect)); + gnsect = gnsect_owned.get(); } if (!gnsect) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_SECTION_NOT_FOUND); - return NULL; + return nullptr; } - STACK_OF(GENERAL_NAME) *gens = v2i_GENERAL_NAMES(NULL, ctx, gnsect); - sk_CONF_VALUE_pop_free(gnsect_owned, X509V3_conf_free); - return gens; + return UniquePtr(v2i_GENERAL_NAMES(nullptr, ctx, gnsect)); } -// set_dist_point_name decodes a DistributionPointName from |cnf| and writes the -// result in |*pdp|. It returns 1 on success, -1 on error, and 0 if |cnf| used +// set_dist_point_name decodes a DistributionPointName from `cnf` and writes the +// 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) { - STACK_OF(GENERAL_NAME) *fnm = NULL; - STACK_OF(X509_NAME_ENTRY) *rnm = NULL; - if (!strncmp(cnf->name, "fullname", 9)) { - // If |cnf| comes from |X509V3_parse_list|, which is possible for a v2i - // function, |cnf->value| may be NULL. - if (cnf->value == NULL) { + UniquePtr fnm; + UniquePtr rnm; + if (!strcmp(cnf->name, "fullname")) { + // If `cnf` comes from `X509V3_parse_list`, which is possible for a v2i + // function, `cnf->value` may be NULL. + if (cnf->value == nullptr) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_MISSING_VALUE); return -1; } fnm = gnames_from_sectname(ctx, cnf->value); if (!fnm) { - goto err; + return -1; } } else if (!strcmp(cnf->name, "relativename")) { - // If |cnf| comes from |X509V3_parse_list|, which is possible for a v2i - // function, |cnf->value| may be NULL. - if (cnf->value == NULL) { + // If `cnf` comes from `X509V3_parse_list`, which is possible for a v2i + // function, `cnf->value` may be NULL. + if (cnf->value == nullptr) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_MISSING_VALUE); return -1; } @@ -111,21 +111,20 @@ static int set_dist_point_name(DIST_POINT_NAME **pdp, const X509V3_CTX *ctx, OPENSSL_PUT_ERROR(X509V3, X509V3_R_SECTION_NOT_FOUND); return -1; } - X509_NAME *nm = X509_NAME_new(); + UniquePtr nm(X509_NAME_new()); if (!nm) { return -1; } - int ret = X509V3_NAME_from_section(nm, dnsect, MBSTRING_ASC); - rnm = nm->entries; - nm->entries = NULL; - X509_NAME_free(nm); - if (!ret || sk_X509_NAME_ENTRY_num(rnm) <= 0) { - goto err; + int ret = X509V3_NAME_from_section(nm.get(), dnsect, MBSTRING_ASC); + rnm = std::move(FromOpaque(nm.get())->entries); + if (!ret || sk_X509_NAME_ENTRY_num(rnm.get()) <= 0) { + return -1; } // There can only be one RDN in nameRelativeToCRLIssuer. - if (sk_X509_NAME_ENTRY_value(rnm, sk_X509_NAME_ENTRY_num(rnm) - 1)->set) { + if (X509_NAME_ENTRY_set(sk_X509_NAME_ENTRY_value( + rnm.get(), sk_X509_NAME_ENTRY_num(rnm.get()) - 1)) != 0) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_MULTIPLE_RDNS); - goto err; + return -1; } } else { return 0; @@ -133,27 +132,22 @@ static int set_dist_point_name(DIST_POINT_NAME **pdp, const X509V3_CTX *ctx, if (*pdp) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_DISTPOINT_ALREADY_SET); - goto err; + return -1; } *pdp = DIST_POINT_NAME_new(); if (!*pdp) { - goto err; + return -1; } if (fnm) { (*pdp)->type = 0; - (*pdp)->name.fullname = fnm; + (*pdp)->name.fullname = fnm.release(); } else { (*pdp)->type = 1; - (*pdp)->name.relativename = rnm; + (*pdp)->name.relativename = rnm.release(); } return 1; - -err: - sk_GENERAL_NAME_pop_free(fnm, GENERAL_NAME_free); - sk_X509_NAME_ENTRY_pop_free(rnm, X509_NAME_ENTRY_free); - return -1; } static const BIT_STRING_BITNAME reason_flags[] = { @@ -166,7 +160,7 @@ static const BIT_STRING_BITNAME reason_flags[] = { {6, "Certificate Hold", "certificateHold"}, {7, "Privilege Withdrawn", "privilegeWithdrawn"}, {8, "AA Compromise", "AACompromise"}, - {-1, NULL, NULL}}; +}; static int set_reasons(ASN1_BIT_STRING **preas, const char *value) { if (*preas) { @@ -174,52 +168,41 @@ static int set_reasons(ASN1_BIT_STRING **preas, const char *value) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_VALUE); return 0; } - int ret = 0; - STACK_OF(CONF_VALUE) *rsk = X509V3_parse_list(value); + UniquePtr rsk(X509V3_parse_list(value)); if (!rsk) { return 0; } - for (size_t i = 0; i < sk_CONF_VALUE_num(rsk); i++) { - const char *bnam = sk_CONF_VALUE_value(rsk, i)->name; + for (const CONF_VALUE *val : rsk.get()) { if (!*preas) { *preas = ASN1_BIT_STRING_new(); if (!*preas) { - goto err; + return 0; } } - const BIT_STRING_BITNAME *pbn; - for (pbn = reason_flags; pbn->lname; pbn++) { - if (!strcmp(pbn->sname, bnam)) { - if (!ASN1_BIT_STRING_set_bit(*preas, pbn->bitnum, 1)) { - goto err; - } - break; - } - } - if (!pbn->lname) { - goto err; + auto it = std::find_if(std::begin(reason_flags), std::end(reason_flags), + [&](const BIT_STRING_BITNAME &reason) { + return strcmp(reason.sname, val->name) == 0; + }); + if (it == std::end(reason_flags) || + !ASN1_BIT_STRING_set_bit(*preas, it->bitnum, 1)) { + return 0; } } - ret = 1; - -err: - sk_CONF_VALUE_pop_free(rsk, X509V3_conf_free); - return ret; + return 1; } static int print_reasons(BIO *out, const char *rname, ASN1_BIT_STRING *rflags, int indent) { - int first = 1; - const BIT_STRING_BITNAME *pbn; + bool first = true; BIO_printf(out, "%*s%s:\n%*s", indent, "", rname, indent + 2, ""); - for (pbn = reason_flags; pbn->lname; pbn++) { - if (ASN1_BIT_STRING_get_bit(rflags, pbn->bitnum)) { + for (const BIT_STRING_BITNAME &reason : reason_flags) { + if (ASN1_BIT_STRING_get_bit(rflags, reason.bitnum)) { if (first) { - first = 0; + first = false; } else { BIO_puts(out, ", "); } - BIO_puts(out, pbn->lname); + BIO_puts(out, reason.lname); } } if (first) { @@ -230,12 +213,11 @@ static int print_reasons(BIO *out, const char *rname, ASN1_BIT_STRING *rflags, return 1; } -static DIST_POINT *crldp_from_section(const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval) { - DIST_POINT *point = NULL; - point = DIST_POINT_new(); +static UniquePtr crldp_from_section( + const X509V3_CTX *ctx, const STACK_OF(CONF_VALUE) *nval) { + UniquePtr point(DIST_POINT_new()); if (!point) { - goto err; + return nullptr; } for (size_t i = 0; i < sk_CONF_VALUE_num(nval); i++) { const CONF_VALUE *cnf = sk_CONF_VALUE_value(nval, i); @@ -244,94 +226,73 @@ static DIST_POINT *crldp_from_section(const X509V3_CTX *ctx, continue; } if (ret < 0) { - goto err; + return nullptr; } if (!strcmp(cnf->name, "reasons")) { if (!set_reasons(&point->reasons, cnf->value)) { - goto err; + return nullptr; } } else if (!strcmp(cnf->name, "CRLissuer")) { GENERAL_NAMES_free(point->CRLissuer); - point->CRLissuer = gnames_from_sectname(ctx, cnf->value); + point->CRLissuer = gnames_from_sectname(ctx, cnf->value).release(); if (!point->CRLissuer) { - goto err; + return nullptr; } } } return point; - -err: - DIST_POINT_free(point); - return NULL; } static void *v2i_crld(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, const STACK_OF(CONF_VALUE) *nval) { - STACK_OF(DIST_POINT) *crld = NULL; - GENERAL_NAMES *gens = NULL; - GENERAL_NAME *gen = NULL; - if (!(crld = sk_DIST_POINT_new_null())) { - goto err; + UniquePtr crld(sk_DIST_POINT_new_null()); + if (crld == nullptr) { + return nullptr; } - for (size_t i = 0; i < sk_CONF_VALUE_num(nval); i++) { - DIST_POINT *point; - const CONF_VALUE *cnf = sk_CONF_VALUE_value(nval, i); + for (const CONF_VALUE *cnf : nval) { if (!cnf->value) { const STACK_OF(CONF_VALUE) *dpsect = X509V3_get_section(ctx, cnf->name); if (!dpsect) { - goto err; + return nullptr; } - point = crldp_from_section(ctx, dpsect); - if (!point) { - goto err; - } - if (!sk_DIST_POINT_push(crld, point)) { - DIST_POINT_free(point); - goto err; + UniquePtr point = crldp_from_section(ctx, dpsect); + if (!point || !PushToStack(crld.get(), std::move(point))) { + return nullptr; } } else { - if (!(gen = v2i_GENERAL_NAME(method, ctx, cnf))) { - goto err; + UniquePtr gen(v2i_GENERAL_NAME(method, ctx, cnf)); + if (gen == nullptr) { + return nullptr; } - if (!(gens = GENERAL_NAMES_new())) { - goto err; + UniquePtr gens(GENERAL_NAMES_new()); + if (gens == nullptr || !PushToStack(gens.get(), std::move(gen))) { + return nullptr; } - if (!sk_GENERAL_NAME_push(gens, gen)) { - goto err; - } - gen = NULL; - if (!(point = DIST_POINT_new())) { - goto err; - } - if (!sk_DIST_POINT_push(crld, point)) { - DIST_POINT_free(point); - goto err; + UniquePtr point(DIST_POINT_new()); + if (point == nullptr) { + return nullptr; } if (!(point->distpoint = DIST_POINT_NAME_new())) { - goto err; + return nullptr; } - point->distpoint->name.fullname = gens; + point->distpoint->name.fullname = gens.release(); point->distpoint->type = 0; - gens = NULL; + if (!PushToStack(crld.get(), std::move(point))) { + return nullptr; + } } } - return crld; - -err: - GENERAL_NAME_free(gen); - GENERAL_NAMES_free(gens); - sk_DIST_POINT_pop_free(crld, DIST_POINT_free); - return NULL; + return crld.release(); } static int dpn_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { - DIST_POINT_NAME *dpn = (DIST_POINT_NAME *)*pval; + DIST_POINT_NAME *dpn = asn1_load_ptr_as(pval); switch (operation) { case ASN1_OP_NEW_POST: - dpn->dpname = NULL; + dpn->dpname = nullptr; break; case ASN1_OP_FREE_POST: @@ -361,7 +322,7 @@ 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(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), @@ -372,28 +333,28 @@ ASN1_SEQUENCE(ISSUING_DIST_POINT) = { ASN1_IMP_OPT(ISSUING_DIST_POINT, onlyattr, ASN1_FBOOLEAN, 5), } ASN1_SEQUENCE_END(ISSUING_DIST_POINT) -IMPLEMENT_ASN1_FUNCTIONS(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 v3_idp = { +const X509V3_EXT_METHOD bssl::v3_idp = { NID_issuing_distribution_point, X509V3_EXT_MULTILINE, ASN1_ITEM_ref(ISSUING_DIST_POINT), - 0, - 0, - 0, - 0, - 0, - 0, - 0, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, v2i_idp, i2r_idp, - 0, - NULL, + nullptr, + nullptr, }; static void *v2i_idp(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, @@ -443,7 +404,7 @@ static void *v2i_idp(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, err: ISSUING_DIST_POINT_free(idp); - return NULL; + return nullptr; } static int print_gens(BIO *out, STACK_OF(GENERAL_NAME) *gens, int indent) { @@ -461,8 +422,12 @@ static int print_distpoint(BIO *out, DIST_POINT_NAME *dpn, int indent) { BIO_printf(out, "%*sFull Name:\n", indent, ""); print_gens(out, dpn->name.fullname, indent); } else { - X509_NAME ntmp; - ntmp.entries = dpn->name.relativename; + X509Name ntmp; + ntmp.entries.reset(sk_X509_NAME_ENTRY_deep_copy( + dpn->name.relativename, X509_NAME_ENTRY_dup, X509_NAME_ENTRY_free)); + if (ntmp.entries == nullptr) { + return 0; + } BIO_printf(out, "%*sRelative Name:\n%*s", indent, "", indent + 2, ""); X509_NAME_print_ex(out, &ntmp, 0, XN_FLAG_ONELINE); BIO_puts(out, "\n"); @@ -522,7 +487,7 @@ static int i2r_crldp(const X509V3_EXT_METHOD *method, void *pcrldp, BIO *out, return 1; } -int DIST_POINT_set_dpname(DIST_POINT_NAME *dpn, X509_NAME *iname) { +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; @@ -538,14 +503,14 @@ int DIST_POINT_set_dpname(DIST_POINT_NAME *dpn, X509_NAME *iname) { 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 = NULL; + dpn->dpname = nullptr; return 0; } } // generate cached encoding of name - if (i2d_X509_NAME(dpn->dpname, NULL) < 0) { + if (i2d_X509_NAME(dpn->dpname, nullptr) < 0) { X509_NAME_free(dpn->dpname); - dpn->dpname = NULL; + dpn->dpname = nullptr; return 0; } return 1; diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_enum.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_enum.cc index 0083558d..edd09f9c 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_enum.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_enum.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -14,10 +19,11 @@ #include #include -#include "ext_dat.h" #include "internal.h" +using namespace bssl; + typedef BIT_STRING_BITNAME ENUMERATED_NAMES; static const ENUMERATED_NAMES crl_reasons[] = { @@ -34,7 +40,7 @@ static const ENUMERATED_NAMES crl_reasons[] = { {CRL_REASON_PRIVILEGE_WITHDRAWN, "Privilege Withdrawn", "privilegeWithdrawn"}, {CRL_REASON_AA_COMPROMISE, "AA Compromise", "AACompromise"}, - {-1, NULL, NULL}}; + {-1, nullptr, nullptr}}; static char *i2s_ASN1_ENUMERATED_TABLE(const X509V3_EXT_METHOD *method, void *ext) { @@ -50,19 +56,19 @@ static char *i2s_ASN1_ENUMERATED_TABLE(const X509V3_EXT_METHOD *method, return i2s_ASN1_ENUMERATED(method, e); } -const X509V3_EXT_METHOD v3_crl_reason = { +const X509V3_EXT_METHOD bssl::v3_crl_reason = { NID_crl_reason, 0, ASN1_ITEM_ref(ASN1_ENUMERATED), - 0, - 0, - 0, - 0, + nullptr, + nullptr, + nullptr, + nullptr, i2s_ASN1_ENUMERATED_TABLE, - 0, - 0, - 0, - 0, - 0, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, (void *)crl_reasons, }; diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_extku.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_extku.cc index 562bf241..d086f273 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_extku.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_extku.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -15,49 +20,32 @@ #include #include -#include "ext_dat.h" #include "internal.h" +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 v3_ext_ku = { +const X509V3_EXT_METHOD bssl::v3_ext_ku = { NID_ext_key_usage, 0, ASN1_ITEM_ref(EXTENDED_KEY_USAGE), - 0, - 0, - 0, - 0, - 0, - 0, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, i2v_EXTENDED_KEY_USAGE, v2i_EXTENDED_KEY_USAGE, - 0, - 0, - NULL, -}; - -// NB OCSP acceptable responses also is a SEQUENCE OF OBJECT -const X509V3_EXT_METHOD v3_ocsp_accresp = { - NID_id_pkix_OCSP_acceptableResponses, - 0, - ASN1_ITEM_ref(EXTENDED_KEY_USAGE), - 0, - 0, - 0, - 0, - 0, - 0, - i2v_EXTENDED_KEY_USAGE, - v2i_EXTENDED_KEY_USAGE, - 0, - 0, - NULL, + nullptr, + nullptr, + nullptr, }; ASN1_ITEM_TEMPLATE(EXTENDED_KEY_USAGE) = ASN1_EX_TEMPLATE_TYPE( @@ -74,7 +62,7 @@ static STACK_OF(CONF_VALUE) *i2v_EXTENDED_KEY_USAGE( const ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(eku, i); char obj_tmp[80]; i2t_ASN1_OBJECT(obj_tmp, 80, obj); - X509V3_add_value(NULL, obj_tmp, &ext_list); + X509V3_add_value(nullptr, obj_tmp, &ext_list); } return ext_list; } @@ -83,8 +71,8 @@ static 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 == NULL) { - return NULL; + if (extku == nullptr) { + return nullptr; } for (size_t i = 0; i < sk_CONF_VALUE_num(nval); i++) { @@ -96,12 +84,12 @@ static void *v2i_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD *method, extval = val->name; } ASN1_OBJECT *obj = OBJ_txt2obj(extval, 0); - if (obj == NULL || !sk_ASN1_OBJECT_push(extku, obj)) { + if (obj == nullptr || !sk_ASN1_OBJECT_push(extku, obj)) { ASN1_OBJECT_free(obj); sk_ASN1_OBJECT_pop_free(extku, ASN1_OBJECT_free); OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_OBJECT_IDENTIFIER); X509V3_conf_err(val); - return NULL; + return nullptr; } } diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_genn.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_genn.cc index 010da023..25b49d28 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_genn.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_genn.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -17,6 +22,8 @@ #include "internal.h" +using namespace bssl; + ASN1_SEQUENCE(OTHERNAME) = { ASN1_SIMPLE(OTHERNAME, type_id, ASN1_OBJECT), // Maybe have a true ANY DEFINED BY later @@ -33,6 +40,8 @@ ASN1_SEQUENCE(EDIPARTYNAME) = { IMPLEMENT_ASN1_ALLOC_FUNCTIONS(EDIPARTYNAME) +BSSL_NAMESPACE_BEGIN + ASN1_CHOICE(GENERAL_NAME) = { ASN1_IMP(GENERAL_NAME, d.otherName, OTHERNAME, GEN_OTHERNAME), ASN1_IMP(GENERAL_NAME, d.rfc822Name, ASN1_IA5STRING, GEN_EMAIL), @@ -48,25 +57,31 @@ ASN1_CHOICE(GENERAL_NAME) = { ASN1_IMP(GENERAL_NAME, d.registeredID, ASN1_OBJECT, GEN_RID), } ASN1_CHOICE_END(GENERAL_NAME) -IMPLEMENT_ASN1_FUNCTIONS(GENERAL_NAME) +BSSL_NAMESPACE_END + +IMPLEMENT_ASN1_FUNCTIONS_const(GENERAL_NAME) + +BSSL_NAMESPACE_BEGIN ASN1_ITEM_TEMPLATE(GENERAL_NAMES) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, GeneralNames, GENERAL_NAME) ASN1_ITEM_TEMPLATE_END(GENERAL_NAMES) -IMPLEMENT_ASN1_FUNCTIONS(GENERAL_NAMES) +BSSL_NAMESPACE_END -IMPLEMENT_ASN1_DUP_FUNCTION(GENERAL_NAME) +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 == NULL) { - if (b->nameAssigner != NULL) { + if (a->nameAssigner == nullptr) { + if (b->nameAssigner != nullptr) { return -1; } } else { - if (b->nameAssigner == NULL || + if (b->nameAssigner == nullptr || ASN1_STRING_cmp(a->nameAssigner, b->nameAssigner) != 0) { return -1; } @@ -93,7 +108,7 @@ static int othername_cmp(const OTHERNAME *a, const OTHERNAME *b) { } // Returns 0 if they are equal, != 0 otherwise. -int GENERAL_NAME_cmp(const GENERAL_NAME *a, const GENERAL_NAME *b) { +int bssl::GENERAL_NAME_cmp(const GENERAL_NAME *a, const GENERAL_NAME *b) { if (!a || !b || a->type != b->type) { return -1; } @@ -190,7 +205,7 @@ void *GENERAL_NAME_get0_value(const GENERAL_NAME *a, int *out_type) { return a->d.rid; default: - return NULL; + return nullptr; } } @@ -213,10 +228,10 @@ int GENERAL_NAME_get0_otherName(const GENERAL_NAME *gen, ASN1_OBJECT **out_oid, if (gen->type != GEN_OTHERNAME) { return 0; } - if (out_oid != NULL) { + if (out_oid != nullptr) { *out_oid = gen->d.otherName->type_id; } - if (out_value != NULL) { + if (out_value != nullptr) { *out_value = gen->d.otherName->value; } return 1; diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_ia5.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_ia5.cc index 7bb61ec6..da89632b 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_ia5.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_ia5.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -18,17 +23,19 @@ #include #include "../internal.h" -#include "ext_dat.h" +#include "internal.h" +using namespace bssl; + static char *i2s_ASN1_IA5STRING(const X509V3_EXT_METHOD *method, void *ext) { const ASN1_IA5STRING *ia5 = reinterpret_cast(ext); char *tmp; if (!ia5 || !ia5->length) { - return NULL; + return nullptr; } if (!(tmp = reinterpret_cast(OPENSSL_malloc(ia5->length + 1)))) { - return NULL; + return nullptr; } OPENSSL_memcpy(tmp, ia5->data, ia5->length); tmp[ia5->length] = 0; @@ -40,7 +47,7 @@ static void *s2i_ASN1_IA5STRING(const X509V3_EXT_METHOD *method, ASN1_IA5STRING *ia5; if (!str) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_NULL_ARGUMENT); - return NULL; + return nullptr; } if (!(ia5 = ASN1_IA5STRING_new())) { goto err; @@ -51,24 +58,26 @@ static void *s2i_ASN1_IA5STRING(const X509V3_EXT_METHOD *method, } return ia5; err: - return NULL; + return nullptr; } #define EXT_IA5STRING(nid) \ { \ nid, 0, ASN1_ITEM_ref(ASN1_IA5STRING), 0, 0, 0, 0, i2s_ASN1_IA5STRING, \ - s2i_ASN1_IA5STRING, 0, 0, 0, 0, NULL \ + s2i_ASN1_IA5STRING, 0, 0, 0, 0, nullptr \ } -#define EXT_END \ - { -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } - -const X509V3_EXT_METHOD v3_ns_ia5_list[] = { - EXT_IA5STRING(NID_netscape_base_url), - EXT_IA5STRING(NID_netscape_revocation_url), - EXT_IA5STRING(NID_netscape_ca_revocation_url), - EXT_IA5STRING(NID_netscape_renewal_url), - EXT_IA5STRING(NID_netscape_ca_policy_url), - EXT_IA5STRING(NID_netscape_ssl_server_name), - EXT_IA5STRING(NID_netscape_comment), - EXT_END}; +const X509V3_EXT_METHOD bssl::v3_netscape_base_url = + EXT_IA5STRING(NID_netscape_base_url); +const X509V3_EXT_METHOD bssl::v3_netscape_revocation_url = + EXT_IA5STRING(NID_netscape_revocation_url); +const X509V3_EXT_METHOD bssl::v3_netscape_ca_revocation_url = + EXT_IA5STRING(NID_netscape_ca_revocation_url); +const X509V3_EXT_METHOD bssl::v3_netscape_renewal_url = + EXT_IA5STRING(NID_netscape_renewal_url); +const X509V3_EXT_METHOD bssl::v3_netscape_ca_policy_url = + EXT_IA5STRING(NID_netscape_ca_policy_url); +const X509V3_EXT_METHOD bssl::v3_netscape_ssl_server_name = + EXT_IA5STRING(NID_netscape_ssl_server_name); +const X509V3_EXT_METHOD bssl::v3_netscape_comment = + EXT_IA5STRING(NID_netscape_comment); diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_info.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_info.cc index 5bf292df..dea099ad 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_info.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_info.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 @@ -18,48 +23,49 @@ #include #include -#include "ext_dat.h" #include "internal.h" +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 v3_info = { +const X509V3_EXT_METHOD bssl::v3_info = { NID_info_access, X509V3_EXT_MULTILINE, ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS), - 0, - 0, - 0, - 0, - 0, - 0, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, i2v_AUTHORITY_INFO_ACCESS, v2i_AUTHORITY_INFO_ACCESS, - 0, - 0, - NULL, + nullptr, + nullptr, + nullptr, }; -const X509V3_EXT_METHOD v3_sinfo = { +const X509V3_EXT_METHOD bssl::v3_sinfo = { NID_sinfo_access, X509V3_EXT_MULTILINE, ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS), - 0, - 0, - 0, - 0, - 0, - 0, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, i2v_AUTHORITY_INFO_ACCESS, v2i_AUTHORITY_INFO_ACCESS, - 0, - 0, - NULL, + nullptr, + nullptr, + nullptr, }; ASN1_SEQUENCE(ACCESS_DESCRIPTION) = { @@ -73,7 +79,7 @@ ASN1_ITEM_TEMPLATE(AUTHORITY_INFO_ACCESS) = ASN1_EX_TEMPLATE_TYPE( ASN1_TFLG_SEQUENCE_OF, 0, GeneralNames, ACCESS_DESCRIPTION) ASN1_ITEM_TEMPLATE_END(AUTHORITY_INFO_ACCESS) -IMPLEMENT_ASN1_FUNCTIONS(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) { @@ -89,7 +95,7 @@ static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS( desc = sk_ACCESS_DESCRIPTION_value(ainfo, i); tmp = i2v_GENERAL_NAME(method, desc->location, tret); - if (tmp == NULL) { + if (tmp == nullptr) { goto err; } tret = tmp; @@ -102,58 +108,55 @@ static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS( OPENSSL_free(vtmp->name); vtmp->name = name; } - if (ret == NULL && tret == NULL) { + if (ret == nullptr && tret == nullptr) { return sk_CONF_VALUE_new_null(); } return tret; err: - if (ret == NULL && tret != NULL) { + if (ret == nullptr && tret != nullptr) { sk_CONF_VALUE_pop_free(tret, X509V3_conf_free); } - return NULL; + return nullptr; } static void *v2i_AUTHORITY_INFO_ACCESS(const X509V3_EXT_METHOD *method, const X509V3_CTX *ctx, const STACK_OF(CONF_VALUE) *nval) { - AUTHORITY_INFO_ACCESS *ainfo = NULL; - ACCESS_DESCRIPTION *acc; - if (!(ainfo = sk_ACCESS_DESCRIPTION_new_null())) { - return NULL; + UniquePtr ainfo(sk_ACCESS_DESCRIPTION_new_null()); + if (ainfo == 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 (!(acc = ACCESS_DESCRIPTION_new()) || - !sk_ACCESS_DESCRIPTION_push(ainfo, acc)) { - goto err; + UniquePtr acc(ACCESS_DESCRIPTION_new()); + if (acc == nullptr) { + return nullptr; } char *ptmp = strchr(cnf->name, ';'); if (!ptmp) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_SYNTAX); - goto err; + return nullptr; } CONF_VALUE ctmp; ctmp.name = ptmp + 1; ctmp.value = cnf->value; if (!v2i_GENERAL_NAME_ex(acc->location, method, ctx, &ctmp, 0)) { - goto err; + return nullptr; } - char *objtmp = OPENSSL_strndup(cnf->name, ptmp - cnf->name); - if (objtmp == NULL) { - goto err; + UniquePtr objtmp(OPENSSL_strndup(cnf->name, ptmp - cnf->name)); + if (objtmp == nullptr) { + return nullptr; } - acc->method = OBJ_txt2obj(objtmp, 0); + acc->method = OBJ_txt2obj(objtmp.get(), 0); if (!acc->method) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_BAD_OBJECT); - ERR_add_error_data(2, "value=", objtmp); - OPENSSL_free(objtmp); - goto err; + ERR_add_error_data(2, "value=", objtmp.get()); + return nullptr; + } + if (!PushToStack(ainfo.get(), std::move(acc))) { + return nullptr; } - OPENSSL_free(objtmp); } - return ainfo; -err: - sk_ACCESS_DESCRIPTION_pop_free(ainfo, ACCESS_DESCRIPTION_free); - return NULL; + return ainfo.release(); } diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_int.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_int.cc index 7be48a5a..437efe13 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_int.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_int.cc @@ -1,20 +1,27 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 "ext_dat.h" +#include "internal.h" +using namespace bssl; + static char *i2s_ASN1_INTEGER_cb(const X509V3_EXT_METHOD *method, void *ext) { return i2s_ASN1_INTEGER(method, reinterpret_cast(ext)); } @@ -24,53 +31,53 @@ static void *s2i_asn1_int(const X509V3_EXT_METHOD *meth, const X509V3_CTX *ctx, return s2i_ASN1_INTEGER(meth, value); } -const X509V3_EXT_METHOD v3_crl_num = { +const X509V3_EXT_METHOD bssl::v3_crl_num = { NID_crl_number, 0, ASN1_ITEM_ref(ASN1_INTEGER), - 0, - 0, - 0, - 0, + nullptr, + nullptr, + nullptr, + nullptr, i2s_ASN1_INTEGER_cb, - 0, - 0, - 0, - 0, - 0, - NULL, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, }; -const X509V3_EXT_METHOD v3_delta_crl = { +const X509V3_EXT_METHOD bssl::v3_delta_crl = { NID_delta_crl, 0, ASN1_ITEM_ref(ASN1_INTEGER), - 0, - 0, - 0, - 0, + nullptr, + nullptr, + nullptr, + nullptr, i2s_ASN1_INTEGER_cb, - 0, - 0, - 0, - 0, - 0, - NULL, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, }; -const X509V3_EXT_METHOD v3_inhibit_anyp = { +const X509V3_EXT_METHOD bssl::v3_inhibit_anyp = { NID_inhibit_any_policy, 0, ASN1_ITEM_ref(ASN1_INTEGER), - 0, - 0, - 0, - 0, + nullptr, + nullptr, + nullptr, + nullptr, i2s_ASN1_INTEGER_cb, s2i_asn1_int, - 0, - 0, - 0, - 0, - NULL, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, }; diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_lib.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_lib.cc index 23f9db8b..52c9eda0 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_lib.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_lib.cc @@ -1,11 +1,16 @@ -/* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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. /* X509 v3 extension utilities */ @@ -18,76 +23,124 @@ #include #include +#include "../mem_internal.h" #include "internal.h" -#include "ext_dat.h" -DEFINE_STACK_OF(X509V3_EXT_METHOD) +using namespace bssl; -static STACK_OF(X509V3_EXT_METHOD) *ext_list = NULL; - -static int ext_stack_cmp(const X509V3_EXT_METHOD *const *a, - const X509V3_EXT_METHOD *const *b) { - return ((*a)->ext_nid - (*b)->ext_nid); -} +// 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; int X509V3_EXT_add(X509V3_EXT_METHOD *ext) { - // We only support |ASN1_ITEM|-based extensions. - assert(ext->it != NULL); + // We only support `ASN1_ITEM`-based extensions. + assert(ext->it != nullptr); - // TODO(davidben): This should be locked. Also check for duplicates. - if (!ext_list && !(ext_list = sk_X509V3_EXT_METHOD_new(ext_stack_cmp))) { + // TODO(crbug.com/42290461): This API is not locked and doesn't check for + // duplicates. Remove it altogether as, even if those issues were fixed, it + // would not be possible to use safely anyway. + if (ext_list == nullptr) { + ext_list = bssl::New>(); + } + if (ext_list == nullptr || !ext_list->Push(ext)) { return 0; } - if (!sk_X509V3_EXT_METHOD_push(ext_list, ext)) { - return 0; - } - sk_X509V3_EXT_METHOD_sort(ext_list); return 1; } -static int ext_cmp(const void *void_a, const void *void_b) { - const X509V3_EXT_METHOD **a = (const X509V3_EXT_METHOD **)void_a; - const X509V3_EXT_METHOD **b = (const X509V3_EXT_METHOD **)void_b; - return ext_stack_cmp(a, b); -} - const X509V3_EXT_METHOD *X509V3_EXT_get_nid(int nid) { - X509V3_EXT_METHOD tmp; - const X509V3_EXT_METHOD *t = &tmp, *const * ret; - size_t idx; - if (nid < 0) { - return NULL; - } - tmp.ext_nid = nid; - ret = reinterpret_cast( - bsearch(&t, standard_exts, STANDARD_EXTENSION_COUNT, - sizeof(X509V3_EXT_METHOD *), ext_cmp)); - if (ret) { - return *ret; - } - if (!ext_list) { - return NULL; + return nullptr; } - if (!sk_X509V3_EXT_METHOD_find(ext_list, &idx, &tmp)) { - return NULL; + switch (nid) { + case NID_netscape_cert_type: + return &v3_nscert; + case NID_netscape_base_url: + return &v3_netscape_base_url; + case NID_netscape_revocation_url: + return &v3_netscape_revocation_url; + case NID_netscape_ca_revocation_url: + return &v3_netscape_ca_revocation_url; + case NID_netscape_renewal_url: + return &v3_netscape_renewal_url; + case NID_netscape_ca_policy_url: + return &v3_netscape_ca_policy_url; + case NID_netscape_ssl_server_name: + return &v3_netscape_ssl_server_name; + case NID_netscape_comment: + return &v3_netscape_comment; + case NID_subject_key_identifier: + return &v3_skey_id; + case NID_key_usage: + return &v3_key_usage; + case NID_subject_alt_name: + return &v3_subject_alt_name; + case NID_issuer_alt_name: + return &v3_issuer_alt_name; + case NID_certificate_issuer: + return &v3_certificate_issuer; + case NID_basic_constraints: + return &v3_bcons; + case NID_crl_number: + return &v3_crl_num; + case NID_certificate_policies: + return &v3_cpols; + case NID_authority_key_identifier: + return &v3_akey_id; + case NID_crl_distribution_points: + return &v3_crld; + case NID_ext_key_usage: + return &v3_ext_ku; + case NID_delta_crl: + return &v3_delta_crl; + case NID_crl_reason: + return &v3_crl_reason; + case NID_invalidity_date: + return &v3_crl_invdate; + case NID_info_access: + return &v3_info; + case NID_id_pkix_OCSP_noCheck: + return &v3_ocsp_nocheck; + case NID_sinfo_access: + return &v3_sinfo; + case NID_policy_constraints: + return &v3_policy_constraints; + case NID_name_constraints: + return &v3_name_constraints; + case NID_policy_mappings: + return &v3_policy_mappings; + case NID_inhibit_any_policy: + return &v3_inhibit_anyp; + case NID_issuing_distribution_point: + return &v3_idp; + case NID_freshest_crl: + return &v3_freshest_crl; } - return sk_X509V3_EXT_METHOD_value(ext_list, idx); + + if (ext_list != nullptr) { + for (const X509V3_EXT_METHOD *ext : *ext_list) { + if (ext->ext_nid == nid) { + return ext; + } + } + } + return nullptr; } const X509V3_EXT_METHOD *X509V3_EXT_get(const X509_EXTENSION *ext) { int nid; if ((nid = OBJ_obj2nid(ext->object)) == NID_undef) { - return NULL; + return nullptr; } return X509V3_EXT_get_nid(nid); } int X509V3_EXT_free(int nid, void *ext_data) { const X509V3_EXT_METHOD *ext_method = X509V3_EXT_get_nid(nid); - if (ext_method == NULL) { + if (ext_method == nullptr) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_CANNOT_FIND_FREE_FUNCTION); return 0; } @@ -106,24 +159,20 @@ int X509V3_EXT_add_alias(int nid_to, int nid_from) { OPENSSL_PUT_ERROR(X509V3, X509V3_R_EXTENSION_NOT_FOUND); return 0; } - if (!(tmpext = - (X509V3_EXT_METHOD *)OPENSSL_malloc(sizeof(X509V3_EXT_METHOD)))) { + if (!(tmpext = New())) { return 0; } *tmpext = *ext; tmpext->ext_nid = nid_to; if (!X509V3_EXT_add(tmpext)) { - OPENSSL_free(tmpext); + Delete(tmpext); return 0; } return 1; OPENSSL_END_ALLOW_DEPRECATED } -// Legacy function: we don't need to add standard extensions any more because -// they are now kept in ext_dat.h. - -int X509V3_add_standard_extensions(void) { return 1; } +int X509V3_add_standard_extensions() { return 1; } // Return an extension internal structure @@ -132,20 +181,20 @@ void *X509V3_EXT_d2i(const X509_EXTENSION *ext) { const unsigned char *p; if (!(method = X509V3_EXT_get(ext))) { - return NULL; + return nullptr; } p = ext->value->data; void *ret = - ASN1_item_d2i(NULL, &p, ext->value->length, ASN1_ITEM_ptr(method->it)); - if (ret == NULL) { - return NULL; + ASN1_item_d2i(nullptr, &p, ext->value->length, ASN1_ITEM_ptr(method->it)); + if (ret == nullptr) { + return nullptr; } // Check for trailing data. if (p != ext->value->data + ext->value->length) { ASN1_item_free(reinterpret_cast(ret), ASN1_ITEM_ptr(method->it)); OPENSSL_PUT_ERROR(X509V3, X509V3_R_TRAILING_DATA_IN_EXTENSION); - return NULL; + return nullptr; } return ret; } @@ -153,7 +202,7 @@ void *X509V3_EXT_d2i(const X509_EXTENSION *ext) { void *X509V3_get_d2i(const STACK_OF(X509_EXTENSION) *extensions, int nid, int *out_critical, int *out_idx) { int lastpos; - X509_EXTENSION *ex, *found_ex = NULL; + X509_EXTENSION *ex, *found_ex = nullptr; if (!extensions) { if (out_idx) { *out_idx = -1; @@ -161,7 +210,7 @@ void *X509V3_get_d2i(const STACK_OF(X509_EXTENSION) *extensions, int nid, if (out_critical) { *out_critical = -1; } - return NULL; + return nullptr; } if (out_idx) { lastpos = *out_idx + 1; @@ -185,7 +234,7 @@ void *X509V3_get_d2i(const STACK_OF(X509_EXTENSION) *extensions, int nid, if (out_critical) { *out_critical = -2; } - return NULL; + return nullptr; } found_ex = ex; } @@ -205,7 +254,7 @@ void *X509V3_get_d2i(const STACK_OF(X509_EXTENSION) *extensions, int nid, if (out_critical) { *out_critical = -1; } - return NULL; + return nullptr; } // This function is a general extension append, replace and delete utility. @@ -215,8 +264,8 @@ void *X509V3_get_d2i(const STACK_OF(X509_EXTENSION) *extensions, int nid, int X509V3_add1_i2d(STACK_OF(X509_EXTENSION) **x, int nid, void *value, int crit, unsigned long flags) { int errcode, extidx = -1; - X509_EXTENSION *ext = NULL, *extmp; - STACK_OF(X509_EXTENSION) *ret = NULL; + X509_EXTENSION *ext = nullptr, *extmp; + STACK_OF(X509_EXTENSION) *ret = nullptr; unsigned long ext_op = flags & X509V3_ADD_OP_MASK; // If appending we don't care if it exists, otherwise look for existing @@ -239,7 +288,7 @@ int X509V3_add1_i2d(STACK_OF(X509_EXTENSION) **x, int nid, void *value, // If delete, just delete it if (ext_op == X509V3_ADD_DELETE) { X509_EXTENSION *prev_ext = sk_X509_EXTENSION_delete(*x, extidx); - if (prev_ext == NULL) { + if (prev_ext == nullptr) { return -1; } X509_EXTENSION_free(prev_ext); @@ -274,7 +323,8 @@ int X509V3_add1_i2d(STACK_OF(X509_EXTENSION) **x, int nid, void *value, return 1; } - if ((ret = *x) == NULL && (ret = sk_X509_EXTENSION_new_null()) == NULL) { + if ((ret = *x) == nullptr && + (ret = sk_X509_EXTENSION_new_null()) == nullptr) { goto m_fail; } if (!sk_X509_EXTENSION_push(ret, ext)) { diff --git a/Sources/CNIOBoringSSL/crypto/x509/v3_ncons.cc b/Sources/CNIOBoringSSL/crypto/x509/v3_ncons.cc index 3dd6c691..4e4cf1c9 100644 --- a/Sources/CNIOBoringSSL/crypto/x509/v3_ncons.cc +++ b/Sources/CNIOBoringSSL/crypto/x509/v3_ncons.cc @@ -1,366 +1,62 @@ -/* - * Copyright 2003-2016 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ +// Copyright 2003-2016 The OpenSSL Project Authors. All Rights Reserved. +// +// 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 +#include +#include #include #include "../internal.h" -#include "ext_dat.h" #include "internal.h" -static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval); -static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a, - BIO *bp, int ind); -static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method, - STACK_OF(GENERAL_SUBTREE) *trees, BIO *bp, - int ind, const char *name); -static int print_nc_ipadd(BIO *bp, const ASN1_OCTET_STRING *ip); +BSSL_NAMESPACE_BEGIN +namespace { -static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc); -static int nc_match_single(GENERAL_NAME *sub, GENERAL_NAME *gen); -static int nc_dn(X509_NAME *sub, X509_NAME *nm); -static int nc_dns(const ASN1_IA5STRING *sub, const ASN1_IA5STRING *dns); -static int nc_email(const ASN1_IA5STRING *sub, const ASN1_IA5STRING *eml); -static int nc_uri(const ASN1_IA5STRING *uri, const ASN1_IA5STRING *base); - -const X509V3_EXT_METHOD v3_name_constraints = { - NID_name_constraints, - 0, - ASN1_ITEM_ref(NAME_CONSTRAINTS), - 0, - 0, - 0, - 0, - 0, - 0, - 0, - v2i_NAME_CONSTRAINTS, - i2r_NAME_CONSTRAINTS, - 0, - NULL, -}; - -ASN1_SEQUENCE(GENERAL_SUBTREE) = { - ASN1_SIMPLE(GENERAL_SUBTREE, base, GENERAL_NAME), - ASN1_IMP_OPT(GENERAL_SUBTREE, minimum, ASN1_INTEGER, 0), - ASN1_IMP_OPT(GENERAL_SUBTREE, maximum, ASN1_INTEGER, 1), -} ASN1_SEQUENCE_END(GENERAL_SUBTREE) - -ASN1_SEQUENCE(NAME_CONSTRAINTS) = { - ASN1_IMP_SEQUENCE_OF_OPT(NAME_CONSTRAINTS, permittedSubtrees, - GENERAL_SUBTREE, 0), - ASN1_IMP_SEQUENCE_OF_OPT(NAME_CONSTRAINTS, excludedSubtrees, - GENERAL_SUBTREE, 1), -} ASN1_SEQUENCE_END(NAME_CONSTRAINTS) - - -IMPLEMENT_ASN1_ALLOC_FUNCTIONS(GENERAL_SUBTREE) -IMPLEMENT_ASN1_ALLOC_FUNCTIONS(NAME_CONSTRAINTS) - -static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, - const X509V3_CTX *ctx, - const STACK_OF(CONF_VALUE) *nval) { - STACK_OF(GENERAL_SUBTREE) **ptree = NULL; - NAME_CONSTRAINTS *ncons = NULL; - GENERAL_SUBTREE *sub = NULL; - ncons = NAME_CONSTRAINTS_new(); - if (!ncons) { - goto err; - } - for (size_t i = 0; i < sk_CONF_VALUE_num(nval); i++) { - const CONF_VALUE *val = sk_CONF_VALUE_value(nval, i); - CONF_VALUE tval; - if (!strncmp(val->name, "permitted", 9) && val->name[9]) { - ptree = &ncons->permittedSubtrees; - tval.name = val->name + 10; - } else if (!strncmp(val->name, "excluded", 8) && val->name[8]) { - ptree = &ncons->excludedSubtrees; - tval.name = val->name + 9; - } else { - OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_SYNTAX); - goto err; - } - tval.value = val->value; - sub = GENERAL_SUBTREE_new(); - if (!v2i_GENERAL_NAME_ex(sub->base, method, ctx, &tval, 1)) { - goto err; - } - if (!*ptree) { - *ptree = sk_GENERAL_SUBTREE_new_null(); - } - if (!*ptree || !sk_GENERAL_SUBTREE_push(*ptree, sub)) { - goto err; - } - sub = NULL; - } - - return ncons; - -err: - NAME_CONSTRAINTS_free(ncons); - GENERAL_SUBTREE_free(sub); - return NULL; -} - -static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a, - BIO *bp, int ind) { - NAME_CONSTRAINTS *ncons = reinterpret_cast(a); - do_i2r_name_constraints(method, ncons->permittedSubtrees, bp, ind, - "Permitted"); - do_i2r_name_constraints(method, ncons->excludedSubtrees, bp, ind, "Excluded"); - return 1; -} - -static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method, - STACK_OF(GENERAL_SUBTREE) *trees, BIO *bp, - int ind, const char *name) { - GENERAL_SUBTREE *tree; - size_t i; - if (sk_GENERAL_SUBTREE_num(trees) > 0) { - BIO_printf(bp, "%*s%s:\n", ind, "", name); - } - for (i = 0; i < sk_GENERAL_SUBTREE_num(trees); i++) { - tree = sk_GENERAL_SUBTREE_value(trees, i); - BIO_printf(bp, "%*s", ind + 2, ""); - if (tree->base->type == GEN_IPADD) { - print_nc_ipadd(bp, tree->base->d.ip); - } else { - GENERAL_NAME_print(bp, tree->base); - } - BIO_puts(bp, "\n"); - } - return 1; -} - -static int print_nc_ipadd(BIO *bp, const ASN1_OCTET_STRING *ip) { - int i, len; - unsigned char *p; - p = ip->data; - len = ip->length; - BIO_puts(bp, "IP:"); - if (len == 8) { - BIO_printf(bp, "%d.%d.%d.%d/%d.%d.%d.%d", p[0], p[1], p[2], p[3], p[4], - p[5], p[6], p[7]); - } else if (len == 32) { - for (i = 0; i < 16; i++) { - uint16_t v = ((uint16_t)p[0] << 8) | p[1]; - BIO_printf(bp, "%X", v); - p += 2; - if (i == 7) { - BIO_puts(bp, "/"); - } else if (i != 15) { - BIO_puts(bp, ":"); - } - } - } else { - BIO_printf(bp, "IP Address:"); - } - return 1; -} - -//- -// Check a certificate conforms to a specified set of constraints. -// Return values: -// X509_V_OK: All constraints obeyed. -// X509_V_ERR_PERMITTED_VIOLATION: Permitted subtree violation. -// X509_V_ERR_EXCLUDED_VIOLATION: Excluded subtree violation. -// X509_V_ERR_SUBTREE_MINMAX: Min or max values present and matching type. -// X509_V_ERR_UNSPECIFIED: Unspecified error. -// X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE: Unsupported constraint type. -// X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: Bad or unsupported constraint -// syntax. -// X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: Bad or unsupported syntax of name. - -int NAME_CONSTRAINTS_check(X509 *x, NAME_CONSTRAINTS *nc) { - int r, i; - size_t j; - X509_NAME *nm; - - nm = X509_get_subject_name(x); - - // Guard against certificates with an excessive number of names or - // constraints causing a computationally expensive name constraints - // check. - size_t name_count = - X509_NAME_entry_count(nm) + sk_GENERAL_NAME_num(x->altname); - size_t constraint_count = sk_GENERAL_SUBTREE_num(nc->permittedSubtrees) + - sk_GENERAL_SUBTREE_num(nc->excludedSubtrees); - size_t check_count = constraint_count * name_count; - if (name_count < (size_t)X509_NAME_entry_count(nm) || - constraint_count < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees) || - (constraint_count && check_count / constraint_count != name_count) || - check_count > 1 << 20) { - return X509_V_ERR_UNSPECIFIED; - } - - if (X509_NAME_entry_count(nm) > 0) { - GENERAL_NAME gntmp; - gntmp.type = GEN_DIRNAME; - gntmp.d.directoryName = nm; - - r = nc_match(&gntmp, nc); - - if (r != X509_V_OK) { - return r; - } - - gntmp.type = GEN_EMAIL; - - // Process any email address attributes in subject name - - for (i = -1;;) { - i = X509_NAME_get_index_by_NID(nm, NID_pkcs9_emailAddress, i); - if (i == -1) { - break; - } - const X509_NAME_ENTRY *ne = X509_NAME_get_entry(nm, i); - gntmp.d.rfc822Name = X509_NAME_ENTRY_get_data(ne); - if (gntmp.d.rfc822Name->type != V_ASN1_IA5STRING) { - return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; - } - - r = nc_match(&gntmp, nc); - - if (r != X509_V_OK) { - return r; - } - } - } - - for (j = 0; j < sk_GENERAL_NAME_num(x->altname); j++) { - GENERAL_NAME *gen = sk_GENERAL_NAME_value(x->altname, j); - r = nc_match(gen, nc); - if (r != X509_V_OK) { - return r; - } - } - - return X509_V_OK; -} - -static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc) { - GENERAL_SUBTREE *sub; - int r, match = 0; - size_t i; - - // Permitted subtrees: if any subtrees exist of matching the type at - // least one subtree must match. - - for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees); i++) { - sub = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i); - if (gen->type != sub->base->type) { - continue; - } - if (sub->minimum || sub->maximum) { - return X509_V_ERR_SUBTREE_MINMAX; - } - // If we already have a match don't bother trying any more - if (match == 2) { - continue; - } - if (match == 0) { - match = 1; - } - r = nc_match_single(gen, sub->base); - if (r == X509_V_OK) { - match = 2; - } else if (r != X509_V_ERR_PERMITTED_VIOLATION) { - return r; - } - } - - if (match == 1) { - return X509_V_ERR_PERMITTED_VIOLATION; - } - - // Excluded subtrees: must not match any of these - - for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees); i++) { - sub = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i); - if (gen->type != sub->base->type) { - continue; - } - if (sub->minimum || sub->maximum) { - return X509_V_ERR_SUBTREE_MINMAX; - } - - r = nc_match_single(gen, sub->base); - if (r == X509_V_OK) { - return X509_V_ERR_EXCLUDED_VIOLATION; - } else if (r != X509_V_ERR_PERMITTED_VIOLATION) { - return r; - } - } - - return X509_V_OK; -} - -static int nc_match_single(GENERAL_NAME *gen, GENERAL_NAME *base) { - switch (base->type) { - case GEN_DIRNAME: - return nc_dn(gen->d.directoryName, base->d.directoryName); - - case GEN_DNS: - return nc_dns(gen->d.dNSName, base->d.dNSName); - - case GEN_EMAIL: - return nc_email(gen->d.rfc822Name, base->d.rfc822Name); - - case GEN_URI: - return nc_uri(gen->d.uniformResourceIdentifier, - base->d.uniformResourceIdentifier); - - default: - return X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE; - } -} - -// directoryName name constraint matching. The canonical encoding of -// X509_NAME makes this comparison easy. It is matched if the subtree is a -// subset of the name. - -static int nc_dn(X509_NAME *nm, X509_NAME *base) { - // Ensure canonical encodings are up to date. - if (nm->modified && i2d_X509_NAME(nm, NULL) < 0) { - return X509_V_ERR_OUT_OF_MEM; - } - if (base->modified && i2d_X509_NAME(base, NULL) < 0) { - return X509_V_ERR_OUT_OF_MEM; - } - if (base->canon_enclen > nm->canon_enclen) { - return X509_V_ERR_PERMITTED_VIOLATION; - } - if (OPENSSL_memcmp(base->canon_enc, nm->canon_enc, base->canon_enclen)) { - return X509_V_ERR_PERMITTED_VIOLATION; - } - return X509_V_OK; -} - -static int starts_with(const CBS *cbs, uint8_t c) { +int starts_with(const CBS *cbs, uint8_t c) { return CBS_len(cbs) > 0 && CBS_data(cbs)[0] == c; } -static int equal_case(const CBS *a, const CBS *b) { +int starts_with_str(const CBS *cbs, std::string_view str) { + return CBS_len(cbs) >= str.size() && + !OPENSSL_memcmp(CBS_data(cbs), str.data(), str.size()); +} + +int ends_with(const CBS *cbs, uint8_t c) { + return CBS_len(cbs) > 0 && CBS_data(cbs)[CBS_len(cbs) - 1] == c; +} + +int equal_case(const CBS *a, const CBS *b) { if (CBS_len(a) != CBS_len(b)) { return 0; } - // Note we cannot use |OPENSSL_strncasecmp| because that would stop + // Note we cannot use `OPENSSL_strncasecmp` because that would stop // iterating at NUL. const uint8_t *a_data = CBS_data(a), *b_data = CBS_data(b); for (size_t i = 0; i < CBS_len(a); i++) { @@ -371,7 +67,7 @@ static int equal_case(const CBS *a, const CBS *b) { return 1; } -static int has_suffix_case(const CBS *a, const CBS *b) { +int has_suffix_case(const CBS *a, const CBS *b) { if (CBS_len(a) < CBS_len(b)) { return 0; } @@ -380,7 +76,247 @@ static int has_suffix_case(const CBS *a, const CBS *b) { return equal_case(©, b); } -static int nc_dns(const ASN1_IA5STRING *dns, const ASN1_IA5STRING *base) { +bool is_allowed_rfc822_local_part(const CBS *cbs) { + if (CBS_len(cbs) == 0) { + return false; + } + for (size_t i = 0; i < CBS_len(cbs); i++) { + uint8_t c = CBS_data(cbs)[i]; + if (!(OPENSSL_isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' || + c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' || + c == '/' || c == '=' || c == '?' || c == '^' || c == '_' || + c == '`' || c == '{' || c == '|' || c == '}' || c == '~' || + c == '.')) { + return false; + } + } + return true; +} + +bool is_allowed_rfc822_domain(const CBS *cbs) { + if (CBS_len(cbs) == 0) { + return false; + } + for (size_t i = 0; i < CBS_len(cbs); i++) { + uint8_t c = CBS_data(cbs)[i]; + if (!(OPENSSL_isalnum(c) || c == '-' || c == '.')) { + return false; + } + } + return true; +} + +// Removes the port part of a URI authority string, if present, leaving the +// host. Returns true if the port was syntactically valid (contained only +// digits), or was not present (vacuously valid). +bool nc_uri_remove_port(CBS *in_out) { + CBS host, unused; + if (CBS_get_until_first(in_out, &host, ':')) { + if (!CBS_skip(in_out, 1) || + CBS_get_until_first_not_of(in_out, &unused, "0123456789")) { + return false; + } + *in_out = host; + return true; + } + // There was no port. + return true; +} + +// Strips a single trailing dot from `host` if present. +// Per RFC 9499, we allow names to be written relative to the root (e.g. +// "www.example.com" is allowed even though technically the FQDN is +// "www.example.com." with a trailing dot representing the common root), and +// normalize names into this relative form for consistency. +void nc_uri_remove_trailing_dot(CBS *host) { + if (ends_with(host, '.')) { + uint8_t unused_byte; + BSSL_CHECK(CBS_get_last_u8(host, &unused_byte)); + } +} + +// Returns whether the authority portion of a URI contains a syntactically valid +// fully qualified domain name (FQDN). +// +// RFC 3986, section 3.2: +// authority = [ userinfo "@" ] host [ ":" port ] +// +// RFC 5280, section 4.2.1.10: if a URI name constraint applies, applications +// MUST reject a certificate with a subjectAltName with a URI that "does not +// include an authority component with a host name specified as a fully +// qualified domain name". +// +// Therefore we reject IP addresses in this function, and reject authority +// components containing a userinfo component. The caller is responsible for +// having removed any colon and port component, and normalizing to DNS relative +// form by removing any trailing dot. +bool nc_uri_is_fqdn(const CBS *uri_authority) { + if (CBS_len(uri_authority) == 0) { + return false; + } + CBS host_to_parse = *uri_authority; + + // Reject userinfo, and IPv6 addresses delimited by square brackets. IPv4 + // addresses are rejected later. + CBS unused; + if (CBS_get_until_first_of(&host_to_parse, &unused, "@[]")) { + return false; + } + + // Validate that the host is identified by a registered name. Following RFC + // 3986, section 3.2.2: we refer to the preferred name syntax rules for DNS + // registered names found in RFC 1034, section 3.5, modified by RFC 1123: + // + // ::= | " " + // ::=