Compare commits

..
31 Commits
Author SHA1 Message Date
1b6b2e274e Add module anchor to fix empty dynamic framework on Xcode 26 (#436)
## Summary

Fixes #435.

On Apple platforms every source file in the `Crypto` target compiles to
just `@_exported import CryptoKit` (because `CRYPTO_IN_SWIFTPM` is
defined but `CRYPTO_IN_SWIFTPM_FORCE_BUILD_API` is not), producing
**zero exported symbols**.

Xcode 26 changed how SPM packages are built for test-target
dependencies: each package product is built as a separate dynamic
framework. A module with no symbols generates a `.framework` directory
but no Mach-O binary, causing a linker error:

```
clang: error: no such file or directory:
  '.../PackageFrameworks/Crypto_17A3B1FFC41E47_PackageProduct.framework/Crypto_17A3B1FFC41E47_PackageProduct'
```

## Fix

Added a minimal `_CryptoModuleAnchor` public enum (outside the
conditional compilation guard) so the module always produces at least
one exported symbol, regardless of how it is linked. The type is
prefixed with `_` to signal it is not intended for public use.

## Test plan

- [ ] Build a project with a test target that has `swift-crypto` (or a
transitive dependency like `swift-certificates`) as a
`packageProductDependency` on Xcode 26 targeting iOS Simulator — should
now succeed
- [ ] Verify existing tests still pass (`swift test`)

---------

Co-authored-by: Niccolò Calamai <niccolo.calamai@esselunga.it>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-04-20 09:37:39 +01:00
2d37b1192f Adopt FoundationEssentials instead of Foundation where available (#317)
Use `FoundationEssentials` if available.

<!-- Thanks for contributing to Swift Crypto! Before you submit your
issue, please make sure you followed our checklist and check the
appropriate boxes by putting an x in the [ ]: [x] -->

### Checklist
- [x] I've run tests to see all new and existing tests pass (macOS and
linux)
- [x] I've followed the code style of the rest of the project
- [x] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [x] I've updated the documentation if necessary

#### If you've made changes to `gyb` files
- [ ] I've run `.script/generate_boilerplate_files_with_gyb` and
included updated generated files in a commit of this pull request
```
bash .script/generate_boilerplate_files_with_gyb
bash: .script/generate_boilerplate_files_with_gyb: No such file or directory
```

### Motivation:

Would be great that packages that depend on `swift-crypto` can be built
without linking full `Foundation`.

### Modifications:

This patch simply replaces `import Foundation` with a conditional
`import FoundationEssentials`.

In some files this also required to explicitly import the C standard
lib.

Maybe we could follow the same approach as in
https://github.com/swiftlang/swift-tools-support-core/blob/main/Sources/TSCLibc/libc.swift
and add an internal module that abstracts this import dance in a single
place.

### Result:

After this change the package should only depend on
`FoundationEssentials`.

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-04-17 15:06:53 +00:00
Andreas BauerandCory Benfield c5b1d7f0cb Add support for SHA-512/256 (#432)
Add SHA-512/256 digest implementation via BoringSSL

### Checklist
- [x] I've run tests to see all new and existing tests pass
- [x] I've followed the code style of the rest of the project
- [x] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [x] I've updated the documentation if necessary

#### If you've made changes to `gyb` files
- [N/A] I've run `.script/generate_boilerplate_files_with_gyb` and
included updated generated files in a commit of this pull request

### Motivation:

Neither CryptoKit nor swift-crypto currently explore the SHA-512/256
hashing function. SHA-512/256 provides the same 256-bit security level
as SHA-256 but can be significantly faster on 64-bit platforms because
it uses the SHA-512 internal structure, which operates on 64-bit words.

### Modifications:

We modified CryptoExtras to include support using the BoringSSL
implementation.

### Result:

Swift ecosystem supports SHA-512/256.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-04-17 14:02:55 +00:00
Rick Newton-Rogers 476538ccb8 Drop Swift 6.0 (#434)
Motivation:

Swift 6.0 is no longer supported, we should bump the tools version and
remove it from our CI.

Modifications:

* Bump the Swift tools version to Swift 6.1
* Remove Swift 6.0 jobs where appropriate in main.yml, pull_request.yml

Result:

Code reflects our support window.
2026-04-08 15:04:09 +01:00
Rick Newton-Rogers 5ef6059b2b Enable Swift 6.3 jobs in CI (#433)
Motivation:

Swift 6.3 has been released, we should add it to our CI coverage.

Modifications:

Add additional Swift 6.3 jobs where appropriate in main.yml,
pull_request.yml

Result:

Improved test coverage.
2026-04-01 14:20:59 +01:00
Raphael bb4ba815da Merge commit from fork
* Reproduce memory-safty issue in HPKE decapsulation

* Validate ciphertext len before calling decapsulate
2026-04-01 10:08:47 +01:00
Rick Newton-Rogers fa308c07a6 update actions/checkout from v4 to v6 (#431)
Motivation

* Following [GitHub's
announcement](https://github.blog/changelog/2025-09-19-deprecation-of-node-20-on-github-actions-runners/),
Node 20 is being deprecated and runners will begin using Node 24 by
default starting March 4th, 2026. Node 20 will reach end-of-life in
April 2026.

Modifications

* Upgrade GitHub Actions to their latest versions to ensure
compatibility with Node 24.
* Replace `actions/checkout@v4` with `actions/checkout@v6` in all
workflow files.

Result

* Workflow files reference `actions/checkout@v6`.
2026-03-02 13:29:52 +00:00
Francesco Paolo Severino a5a71cfcbc Add support for encrypted PEM keys via BoringSSL (#428)
Add support for creating RSA private keys from encrypted PEM files.

### Checklist
- [X] I've run tests to see all new and existing tests pass
- [X] I've followed the code style of the rest of the project
- [X] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [X] I've updated the documentation if necessary

#### If you've made changes to `gyb` files
- [ ] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and
included updated generated files in a commit of this pull request

### Motivation:

Resolves #264

### Modifications:

Adds an initializer to `_RSA.Signing.PrivateKey` that takes the
encrypted PEM representation and the encryption password and calls the
high-level BoringSSL function to parse the encrypted key format.

Tests were copied from #318 by @ptoffy.

### Result:

RSA private keys can be created from encrypted PEM files.
2026-02-23 13:29:41 +00:00
Rick Newton-Rogers 31611736b0 switch from main to 0.0.7 for swiftlang workflows (#430)
Motivation

* `@main` references to `swiftlang/github-workflows` are deprecated.

Modifications

* Replace `@main` with `@0.0.7` in all workflow files.

Result

* Workflow files reference a pinned version of
`swiftlang/github-workflows`.
2026-02-20 13:34:31 +00:00
Mike SchragandMike Schrag 6f70fa9eab Add RSA PKCSv1.5 padding support for legacy compat (#425)
Add RSA PKCSv1.5 padding support for legacy compat

### Checklist
- [X] I've run tests to see all new and existing tests pass
- [X] I've followed the code style of the rest of the project
- [X] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [X] I've updated the documentation if necessary

#### If you've made changes to `gyb` files
- [n/a] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and
included updated generated files in a commit of this pull request

### Motivation:
I have a scenario that requires me to be able to encrypt and decrypt
values that use RSA PKCSv1.5 padding. This is known to be a weak
algorithm, so we explicitly want to discourage its use, but there are
scenarios where you need the algorithm for legacy compatibility, so we
want to provide the capability, even if we strongly discourage its use.

### Modifications:
Added a new enum + constant + passthrough to allow users to specify RSA
PKCSv1.5. From the internal review, we thought it would be best to
explicitly name the constants in a way that discouraged use without very
intentional needs, hence the "weak" and "insecure" references in all of
the naming.

### Result:
You can now specify PKCSv1.5 padding for use in encryption and
decryption. This is only adding constants, and the enums are not public,
so there should not be any impact on compatibility (source or binary).

Co-authored-by: Mike Schrag <schrag@apple.com>
2025-11-19 20:31:42 +00:00
Mike SchragandMike Schrag e8ed8867ec Incorrect maximum encryption size for RSA OAEP (#423)
Incorrect maximum encryption size for RSA OAEP

### Checklist
- [X] I've run tests to see all new and existing tests pass
- [X] I've followed the code style of the rest of the project
- [X] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [X] I've updated the documentation if necessary

#### If you've made changes to `gyb` files
- [n/a] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and
included updated generated files in a commit of this pull request

### Motivation:
The `maximumEncryptSize` function is hardcoded to use 42 as the hash
offset, but the RFC actually says it's "2*hLen-2" so 42 is only valid
for SHA1. SHA256 should be 62 (2*32-2). This adds a hash length onto the
Digest enum, which can then be used in the length calculation.

In writing the tests for this, I also stumbled on the unsafe PEM
representation for RSA Public Keys don't allow 1024-bit keys as
documented, so this also fixes that.

### Modifications:
* Added a `hashBitLength` to the RSA Digest which is then used in the
`maximumEncryptSize` to properly compute the maximum length
* Corrected the minimum key size for RSA unsafe PEM public keys to 1024
from 2048

### Result:
* The `maximumEncryptSize` function will return the expected value for
RSA OAEP SHA256 keys. I don't believe anything calls this internally, so
this would be for external consumers.
* Unsafe construction of RSA public keys now allow 1024 bit keys. It was
documented as supporting them, but the check was still 2048 (probably
copy-paste error from the safe variant). This only expands the potential
uses, so it shouldn't introduce any new failures.

Co-authored-by: Mike Schrag <schrag@apple.com>
2025-10-29 10:58:46 +00:00
Paul Toffoloni 87a9e066d9 Add PEM/DER APIs for Curve25519 (#419)
Add PEM/DER APIs for Curve25519

### Checklist
- [x] I've run tests to see all new and existing tests pass
- [x] I've followed the code style of the rest of the project
- [x] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [x] I've updated the documentation if necessary

#### If you've made changes to `gyb` files
- [ ] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and
included updated generated files in a commit of this pull request

### Motivation:

Closes #82 
Creating Ed25519/X25519 keys using PEM/DER and also generating their
PEM/DER representations can be handy

### Modifications:

Added 
- `init(pemRepresentation:)` and the `pemRepresentation` computed
property
- `init(derRepresentation:)` and the `derRepresentation` computed
property

to `Curve25519.{Signing,KeyAgreement}.{Private,Public}Key`

### Result:

Curve25519 can now be created with and can produce PEM/DER
representations
2025-10-23 12:35:45 +01:00
Melissa Kilby 781478b4e0 chore: restrict GitHub workflow permissions - future-proof (#421)
See https://github.com/swiftlang/github-workflows/issues/167 for
additional context

This approach aligns with security best practices, as detailed in the
following documentation:

-
https://github.com/ossf/scorecard/blob/main/docs/checks.md#token-permissions
-
https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#defining-access-for-the-github_token-scopes
-
https://openssf.org/blog/2024/08/12/mitigating-attack-vectors-in-github-workflows/


The default GITHUB_TOKEN permissions are defined at the repository
level. This PR modifies the workflow-level overrides to conform to
OpenSSF best practices -> defense in depth.

Allow me to quote OpenSSF:

https://github.com/ossf/scorecard/blob/main/docs/checks.md#token-permissions

> The highest score is awarded when the permissions definitions in each
workflow's yaml file are set as read-only at the top level and the
required write permissions are declared at the run-level.”

> Remediation steps
> - Set top-level permissions as read-all or contents: read as described
in GitHub's documentation.
> - Set any required write permissions at the job-level. Only set the
permissions required for that job; do not set permissions: write-all at
the job level.


Compare to the LLVM project:

Top-level: contents read, e.g.
https://github.com/swiftlang/llvm-project/blob/next/.github/workflows/build-ci-container-windows.yml#L3-L4
-> this makes it future-proof

Job-level: Allow write permissions as needed, e.g.
https://github.com/swiftlang/llvm-project/blob/next/.github/workflows/build-ci-container-windows.yml#L53-L58

Signed-off-by: Melissa Kilby <mkilby@apple.com>
2025-10-20 08:49:09 +01:00
Cory Benfield bcd2b89f2a Update README for 4.0 release (#418) 2025-10-06 15:02:13 +01:00
+6 431013afaf Update to WWDC25 release (#417)
This change updates Crypto to WWDC25 equivalent code.

Each of these changes were individually merged to the WWDC25 branch.
This includes:

- #359
- #363
- #365
- #367
- #368
- #397
- #403
- #410
- #407
- #401
- #415

---------

Co-authored-by: YourMJK <37852512+YourMJK@users.noreply.github.com>
Co-authored-by: Si Beaumont <beaumont@apple.com>
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
Co-authored-by: Raphael <josephnoir@users.noreply.github.com>
Co-authored-by: Evan Wilde <ewilde@apple.com>
Co-authored-by: Tim Condon <0xTim@users.noreply.github.com>
Co-authored-by: Gus Cairo <gus.cairo@apple.com>
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Fabrice de Gans <Steelskin@users.noreply.github.com>
Co-authored-by: Wojciech Nagrodzki <278594+wnagrodzki@users.noreply.github.com>
Co-authored-by: Jesse L. Zamora <xtremekforever@gmail.com>
Co-authored-by: aryan-25 <aryan_shah@apple.com>
Co-authored-by: Gwynne Raskind <gwynne@vapor.codes>
Co-authored-by: 3405691582 <dsk@google.com>
Co-authored-by: Paul Toffoloni <69189821+ptoffy@users.noreply.github.com>
2025-09-26 11:55:11 +01:00
Rick Newton-Rogers 95ba0316a9 Enable Swift 6.2 jobs in CI (#414)
Motivation:

Swift 6.2 has been released, we should add it to our CI coverage.

Modifications:

Add additional Swift 6.2 jobs where appropriate in main.yml,
pull_request.yml

Result:

Improved test coverage.
2025-09-22 13:22:05 +01:00
Paul Toffoloni 527fef6228 Remove useless try to fix warnings (#412)
`getKeyPrimitives` is marked as throws but is not actually throwing
errors and this is yielding warnings. This fixes the warnings.

### Checklist
- [x] I've run tests to see all new and existing tests pass
- [x] I've followed the code style of the rest of the project
- [x] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [x] I've updated the documentation if necessary

#### If you've made changes to `gyb` files
- [N/A] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and
included updated generated files in a commit of this pull request

### Motivation:

Currently there's a warning
```
/swift-crypto/Sources/_CryptoExtras/RSA/RSA_boring.swift:67:9: warning: no calls to throwing functions occur within 'try' expression
```
because we're using `try` on a non throwing function. This escalates to
all of the functions that use it.
I'm not sure if removing `throws` from a non-actually-throwing public
function is breaking, as using `try` on a non throwing function only
yields a warning (if not in warnings-as-errors mode) but it actively is
a signature change so it might still be breaking. In case we don't want
to merge this as is, the warning can be removed by simply removing
useless `try`s and we can wait for the next major version to remove the
false-throwers.

### Modifications:

Remove the useless `try` and `throws` where they're not needed.

### Result:

The warning is gone.
2025-09-22 11:02:42 +00:00
3405691582 b1f7679f29 Buildfix OpenBSD. (#411)
The threading changes missed an `os(OpenBSD)`, causing the Swift
toolchain build to fail.

### Checklist
- [ ] I've run tests to see all new and existing tests pass
- [X] I've followed the code style of the rest of the project
- [X] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [ ] I've updated the documentation if necessary 

#### If you've made changes to `gyb` files
- [ ] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and
included updated generated files in a commit of this pull request

### Motivation:

Buildfix the upstream Swift toolchain on OpenBSD.

### Modifications:

Added an `os(OpenBSD)` conditional, much like FreeBSD.

### Result:

The Swift toolchain will build successfully again.
2025-09-16 15:08:43 +00:00
Gwynne Raskind c661debfc2 Update BoringSSL to 0226f30467f540a3f62ef48d453f93927da199b6 (#406)
Fix multiple issues in the BoringSSL vendoring script and update
BoringSSL to 0226f30467f540a3f62ef48d453f93927da199b6

### Checklist
- [x] I've run tests to see all new and existing tests pass
- [x] I've followed the code style of the rest of the project
- [x] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [x] I've updated the documentation if necessary

### Motivation:

The `vendor-boringssl.sh` script is currently broken in a number of
ways, both in general and relative to the latest BoringSSL version:

- `--enable-test-discovery` is still in use
- The Linux Swift SDKs being generated are out of date (5.10-jammy)
- The script does not prefix exported C++ symbols
- Invoking the script without a `BORINGSSL_REVISION` results in an
unconditional error
- The `PATTERNS` list is out of date for the latest BoringSSL
- The latest BoringSSL contains a bug which fails to apply `extern "C"`
to two exported symbols, allowing for collisions.

In addition, the latest BoringSSL has made `BN_MONT_CTX` opaque,
necessitating that it be referenced with `OpaquePointer` rather than
`UnsafePointer<>`.

### Modifications:

The following changes are included:

- `--enable-test-discovery` has been removed
- `vendor-boringssl.sh` and `generate-linux-sdks.sh` have been updated
to use Swift 6.1.2 SDKs built for Ubuntu Noble
- The `mangle_cpp_structures` function from `swift-nio-ssl`'s version
of `vendor-boringssl.sh` has been copied over (thanks @Lukasa!)
- `BORINGSSL_REVISION` is now allowed to be an empty string
- The `PATTERNS` array has been updated
- A patch has been added which applies `extern "C"` to the functions
which should have it
- `s/UnsafePointer<BN_MONT_CTX>/OpaquePointer/g`
- Updated `CMakeLists.txt` per `update-cmake-lists.sh`
- Update BoringSSL to
`0226f30467f540a3f62ef48d453f93927da199b6`

### Result:

Vendoring the latest BoringSSL will work again.
The latest BoringSSL is vendored.
2025-09-15 15:21:20 +01:00
Cory Benfield 141f5b4e17 Make the tests Swift 6 ready. (#409)
This little box type allows us to easily audit the correctness of the
locking.
2025-09-09 09:04:31 +01:00
Tim Condon 9552067c74 Fix script path in PR template (#408)
Fix PR template to point to correct script
2025-09-09 06:53:45 +00:00
Cory Benfield c46250209e Move away from Foundation.Thread (#404)
Motivation

In preparation for adopting FoundationEssentials where available, we
need to avoid using Thread as that isn't available. To that end, let's
bring over NIO's ThreadSpecificVariable wrapper.

Modifications

Bring over NIO's ThreadSpecificVariable wrapper and supporting code.

Result

No need for Thread anymore.
2025-09-09 07:31:53 +01:00
aryan-25 d1c6b70f7c Avoid TSAN issue in _CryptoExtras/AES/CMAC (#402)
### Motivation:
swift-crypto currently fails to compile with TSAN enabled in 5.10 and
6.0 due to a TSAN error stemming from the use of `consuming` in the
`finalize()` method of `_CryptoExtras/AES/CMAC`.

### Modifications:
Like #384, the `consuming finalize()` method in `_CryptoExtras/AES/CMAC`
is now wrapped inside a `#if compiler(>=6.1)` condition. A non-consuming
variant is used otherwise.

### Result:
`swift-crypto` can successfully compile with TSAN enabled in 5.10 and
6.0.
2025-08-27 13:18:16 +01:00
Jesse L. Zamora b7c303d97b Use Swift SDKs to generate symbols for Linux targets and armv7 (using swift-sdk-generator) (#399)
Swift SDK solution for adding armv7 symbols for swift-crypto using the
[swift-sdk-generator](https://github.com/swiftlang/swift-sdk-generator).

### Motivation:

As outlined in #223, the necessary symbols for armv7 are missing from
swift-crypto, and we'd like to add them in some way that could be
accepted by the team. It was discussed that using Swift SDKs generated
from the swift-sdk-generator could be a solution that could be easily
vetted, since the swift-sdk-generator is a component maintained by Apple
and the swiftlang organization.

### Modifications:

- Added a new `./scripts/generate-linux-sdks.sh` script to clone & build
the swift-sdk-generator, and create Swift SDKs for x86_64, aarch64, and
armv7.
- Modified the `./scripts/vendor-boringssl.sh` script to use these
installed Swift SDKs to cross-compile for Linux architectures in the
script.
- Ran the scripts against the exact revision of BoringSSL to avoid
source updates, which adds the missing symbols for armv7.

### Result:

Swift SDKs are used to generate symbols for Linux architectures instead
of Docker, and missing symbols for armv7 are added as well.

I have a few pros and cons for this solution:

- Pros
- Swift SDKs are used to cross-compile for Linux instead of Docker,
which performs better than Rosetta 2 emulation. Docker does not have to
be used at all for this solution.
- Switching to using Swift SDKs is the more "correct" way to
cross-compile for Linux targets, and much of the ecosystem for
cross-compilation of Swift packages is moving to using Swift SDKs.
 - Cons
- Lots of downloads need to happen since the swift-sdk-generator needs
to download the host macOS toolchain for Swift 5.10, plus Ubuntu
packages and target toolchains for each architecture (x86_64, aarch64,
armv7). This results in ~15GB of artifacts in the /tmp directory for
just the generator artifacts. However, this only needs to be run once
before running the vendoring script.

Let me know what you think @Lukasa.
2025-08-15 14:46:01 +01:00
Jesse L. Zamora c066b057ed Improve vendor-boringssl.sh script to make it work better (#396)
Updates for the `scripts/vendor-boringssl.h` script that make it a bit
easier to use and ensure you don't accidentally get an update of
BoringSSL you don't want.

### Motivation:

I was working on investigating building a Swift SDK for #223 and ran
into a couple of things that I saw could be improved. Not all need to be
done, but at the very least I feel the boringssl revision lock should be
considered. @Lukasa

### Modifications:

- Add missing invocation of `$sed` in the script- `gsed` was being
invoked instead, although everywhere else `$sed` was used (typo).
- Support locking `BORINGSSL_REVISION` to a specific revision number
through an argument to the script. This way the script can be re-run
without unintentionally upgrading boringssl.
- Remove the non-existent `boringssl_prefix_symbols_nasm.inc` exclude
from the `CCryptoBoringSSL` target. I'm guessing it was there for an
older version of boringssl, but no longer there with the current
revision?

### Result:

The `scripts/vendor_boringssl.sh` script behaves a bit better and can be
run without upgrading the boringssl version unless explicitly desired.
2025-08-11 17:09:16 +01:00
Si Beaumont 2347f20e24 Use Thread.threadDictionary instead of TaskLocal for thread-local (#395)
## Motivation

We were using a `@TaskLocal static var` to hold the
`FiniteFieldArithmeticContext` (FFAC) on each of the curve types. The
intention here was this would operate as a thread-local value, since
task-locals behave like thread locals when the caller is not part of a
task context. However, they still require binding, (i.e. the use of e.g.
`P256.$__ffac.withValue { ... }`[^1], otherwise they just return the
_default_ value, which is globally shared. We were not doing that, nor
do we have a sensible place where we could.

This causes crashes when using these values in a multithreaded
environment since the same value will be used across threads.

## Modifications

- Use an explicit thread-local API from Foundation to store and read the
per-curve FFAC.
- Add a test that shows each thread gets the same value on each read,
but distinct from all other threads.

## Result

Fixes crash when using ECToolbox-based APIs in multithreaded code.

[^1]:
https://developer.apple.com/documentation/swift/tasklocal#Using-task-local-values-outside-of-tasks
2025-08-08 17:54:24 +01:00
Cory Benfield 334e682869 Add AES CMAC support (#394)
Motivation

AES CMAC is a standardised albeit somewhat uncommon MAC built on top of
the AES block cipher. CMAC pops up in a few places, mostly where it is
convenient to assume that you have access to AES, but not to a hash
function. For example, AES-SIV is built on CMAC.

Modifications

Add CMAC support
Add tests and test vectors

Result

CMAC is supported
2025-08-05 10:16:29 +00:00
Wojciech NagrodzkiandCory Benfield c68a7a7c7f Add Sequence conformance to AES._CBC.IV (#389) (#392)
Add Sequence conformance to `AES._CBC.IV` where `Element` is `UInt8`.

<!-- Thanks for contributing to Swift Crypto! Before you submit your
issue, please make sure you followed our checklist and check the
appropriate boxes by putting an x in the [ ]: [x] -->

### Checklist
- [ ] I've run tests to see all new and existing tests pass
> PKCS8DERRepresentationTests do not compile on master branch with Error
`'pkcs8DERRepresentation' is only available in iOS 14.0 or newer`. All
the other tests pass after my changes.
- [x] I've followed the code style of the rest of the project
- [x] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [x] I've updated the documentation if necessary

#### If you've made changes to `gyb` files
- [ ] I've run `.script/generate_boilerplate_files_with_gyb` and
included updated generated files in a commit of this pull request

### Motivation:

No convenient API for converting `AES._CBC.IV` into `Data`.

### Modifications:

Added `Sequence` conformance to `AES._CBC.IV` similarly how it is done
for `AES.GCM._SIV.Nonce`.

### Result:

It will be possible to create `Data` instance with `AES._CBC.IV` passed
as init argument.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-07-31 13:06:20 +01:00
RaphaelandGeorge Barnett 8c9d27a339 Enable release mode builds in CI (#388)
Enable release mode build tests in CI

### Motivation:

Some errors do not show up in debug builds. Enabling release mode builds
improves the CI coverage.

### Modifications:

Add a new workflow for release mode builds and enable it in the pull
requests workflow.

### Result:

The CI performs release mode builds to test pull requests.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-07-30 15:13:18 +01:00
Cory Benfield 176abc28e0 Cache curves to avoid repeatedly reallocating state (#391)
Motivation

We shouldn't repeatedly reconstruct static data

Modifications

- Turn the groups into static lets instead of computed properties

Result

Fewer allocations
2025-07-30 11:53:08 +00:00
Cory Benfield 64a4de00fb Add some benchmarks for EC key agreement (#390)
We should have some benchmarks for EC key agreement.
2025-07-30 12:45:10 +01:00
518 changed files with 30850 additions and 6284 deletions

No files matched your search

+2 -2
View File
@@ -9,7 +9,7 @@ _[One line description of your change]_
- [ ] I've updated the documentation if necessary
#### If you've made changes to `gyb` files
- [ ] I've run `.script/generate_boilerplate_files_with_gyb` and included updated generated files in a commit of this pull request
- [ ] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and included updated generated files in a commit of this pull request
### Motivation:
@@ -21,4 +21,4 @@ _[Describe the modifications you've done.]_
### Result:
_[After your change, what will change.]_
_[After your change, what will change.]_
+19 -3
View File
@@ -1,5 +1,8 @@
name: Main
permissions:
contents: read
on:
push:
branches: [main]
@@ -12,19 +15,32 @@ jobs:
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
with:
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_0_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_1_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_2_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_3_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_0_enabled: true
windows_6_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
windows_6_0_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_1_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_2_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_3_arguments_override: "--explicit-target-dependency-import-check error"
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
release-builds:
name: Release builds
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
with:
windows_6_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
cxx-interop:
name: Cxx interop
uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main
+23 -5
View File
@@ -1,5 +1,8 @@
name: PR
permissions:
contents: read
on:
pull_request:
types: [opened, reopened, synchronize]
@@ -7,7 +10,7 @@ on:
jobs:
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.7
with:
license_header_check_project_name: "SwiftCrypto"
docs_check_enabled: false
@@ -17,19 +20,32 @@ jobs:
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
with:
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_0_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_1_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_2_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_3_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_0_enabled: true
windows_6_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
windows_6_0_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_1_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_2_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_3_arguments_override: "--explicit-target-dependency-import-check error"
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
release-builds:
name: Release builds
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
with:
windows_6_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
cxx-interop:
name: Cxx interop
uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main
@@ -44,8 +60,10 @@ jobs:
{ "name": "CCryptoBoringSSL", "type": "source", "exceptions": [] },
{ "name": "CCryptoBoringSSLShims", "type": "source", "exceptions": [] },
{ "name": "CryptoBoringWrapper", "type": "source", "exceptions": [] },
{ "name": "CXKCP", "type": "source", "exceptions": [] },
{ "name": "CXKCPShims", "type": "source", "exceptions": [] },
{ "name": "Crypto", "type": "source", "exceptions": [] },
{ "name": "_CryptoExtras", "type": "source", "exceptions": [] },
{ "name": "CryptoExtras", "type": "source", "exceptions": [] },
{ "name": "CCryptoBoringSSL", "type": "assembly", "exceptions": [ "*/AES/*.swift" ] }
]
}
+4 -1
View File
@@ -1,5 +1,8 @@
name: PR label
permissions:
contents: read
on:
pull_request:
types: [labeled, unlabeled, opened, reopened, synchronize]
@@ -11,7 +14,7 @@ jobs:
timeout-minutes: 1
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
persist-credentials: false
- name: Check for Semantic Version label
+2 -1
View File
@@ -1,5 +1,5 @@
.DS_Store
/.build
.build
/out
/Packages
/*.xcodeproj
@@ -12,6 +12,7 @@ Package.resolved
DerivedData
.swiftpm
**/gyb.pyc
scripts/__pycache__/
.*.sw[nop]
+1
View File
@@ -43,6 +43,7 @@ dev/update-benchmark-thresholds
**/*.der
.swiftformat
Sources/CCryptoBoringSSL/*
Sources/CXKCP/*
**/*.swift.gyb
scripts/*.patch
scripts/gyb
+1 -1
View File
@@ -1,5 +1,5 @@
version: 1
builder:
configs:
- documentation_targets: [Crypto, _CryptoExtras]
- documentation_targets: [Crypto, CryptoExtras]
platform: linux
+79 -68
View File
@@ -25,6 +25,7 @@ Sources/Crypto/Digests/Digest.swift
Sources/Crypto/Digests/Digests.swift
Sources/Crypto/Digests/HashFunctions.swift
Sources/Crypto/Digests/HashFunctions_SHA2.swift
Sources/Crypto/Digests/HashFunctions_SHA3.swift
Sources/Crypto/HPKE/Ciphersuite/HPKE-AEAD.swift
Sources/Crypto/HPKE/Ciphersuite/HPKE-Ciphersuite.swift
Sources/Crypto/HPKE/Ciphersuite/HPKE-KDF.swift
@@ -43,8 +44,12 @@ Sources/Crypto/HPKE/Modes/HPKE-Modes.swift
Sources/Crypto/Insecure/Insecure.swift
Sources/Crypto/Insecure/Insecure_HashFunctions.swift
Sources/Crypto/KEM/KEM.swift
Sources/Crypto/KEM/KEM-Errors.swift
Sources/Crypto/KEM/MLKEM.swift
Sources/Crypto/KEM/XWing.swift
Sources/Crypto/Key Agreement/DH.swift
Sources/Crypto/Key Agreement/ECDH.swift
Sources/Crypto/Key Derivation/ANSIx963.swift
Sources/Crypto/Key Derivation/HKDF.swift
Sources/Crypto/Key Wrapping/AESWrap.swift
Sources/Crypto/Keys/EC/Curve25519.swift
@@ -58,51 +63,52 @@ Sources/Crypto/Message Authentication Codes/MessageAuthenticationCode.swift
Sources/Crypto/PRF/AES.swift
Sources/Crypto/Signatures/ECDSA.swift
Sources/Crypto/Signatures/Ed25519.swift
Sources/Crypto/Signatures/MLDSA.swift
Sources/Crypto/Signatures/Signature.swift
Sources/Crypto/Util/PrettyBytes.swift
Sources/Crypto/Util/SafeCompare.swift
Sources/Crypto/Util/SecureBytes.swift
Sources/Crypto/Util/Zeroization.swift
Sources/_CryptoExtras/AES/AES_CBC.swift
Sources/_CryptoExtras/AES/AES_CFB.swift
Sources/_CryptoExtras/AES/AES_CTR.swift
Sources/_CryptoExtras/AES/AES_GCM_SIV.swift
Sources/_CryptoExtras/AES/Block Function.swift
Sources/_CryptoExtras/ARC/ARC+API.swift
Sources/_CryptoExtras/ARC/ARC.swift
Sources/_CryptoExtras/ARC/ARCCredential.swift
Sources/_CryptoExtras/ARC/ARCEncoding.swift
Sources/_CryptoExtras/ARC/ARCPrecredential.swift
Sources/_CryptoExtras/ARC/ARCPresentation.swift
Sources/_CryptoExtras/ARC/ARCRequest.swift
Sources/_CryptoExtras/ARC/ARCResponse.swift
Sources/_CryptoExtras/ARC/ARCServer.swift
Sources/_CryptoExtras/ZKPs/Prover.swift
Sources/_CryptoExtras/ZKPs/Verifier.swift
Sources/_CryptoExtras/ZKPs/ZKPToolbox.swift
Sources/_CryptoExtras/ChaCha20CTR/ChaCha20CTR.swift
Sources/_CryptoExtras/ECToolbox/ECToolbox.swift
Sources/_CryptoExtras/H2G/HashToField.swift
Sources/_CryptoExtras/Key Derivation/KDF.swift
Sources/_CryptoExtras/Key Derivation/PBKDF2/PBKDF2.swift
Sources/_CryptoExtras/Key Derivation/Scrypt/Scrypt.swift
Sources/_CryptoExtras/OPRFs/OPRF.swift
Sources/_CryptoExtras/OPRFs/OPRFClient.swift
Sources/_CryptoExtras/OPRFs/OPRFServer.swift
Sources/_CryptoExtras/OPRFs/VOPRF+API.swift
Sources/_CryptoExtras/OPRFs/VOPRFClient.swift
Sources/_CryptoExtras/OPRFs/VOPRFServer.swift
Sources/_CryptoExtras/RSA/RSA+BlindSigning.swift
Sources/_CryptoExtras/RSA/RSA.swift
Sources/_CryptoExtras/Util/BoringSSLHelpers.swift
Sources/_CryptoExtras/Util/DigestType.swift
Sources/_CryptoExtras/Util/Error.swift
Sources/_CryptoExtras/Util/I2OSP.swift
Sources/_CryptoExtras/Util/IntegerEncoding.swift
Sources/_CryptoExtras/Util/PEMDocument.swift
Sources/_CryptoExtras/Util/PrettyBytes.swift
Sources/_CryptoExtras/Util/SubjectPublicKeyInfo.swift
Sources/_CryptoExtras/ZKPs/DLEQ.swift
Sources/CryptoExtras/AES/AES_CBC.swift
Sources/CryptoExtras/AES/AES_CFB.swift
Sources/CryptoExtras/AES/AES_CTR.swift
Sources/CryptoExtras/AES/AES_GCM_SIV.swift
Sources/CryptoExtras/AES/Block Function.swift
Sources/CryptoExtras/ARC/ARC+API.swift
Sources/CryptoExtras/ARC/ARC.swift
Sources/CryptoExtras/ARC/ARCCredential.swift
Sources/CryptoExtras/ARC/ARCEncoding.swift
Sources/CryptoExtras/ARC/ARCPrecredential.swift
Sources/CryptoExtras/ARC/ARCPresentation.swift
Sources/CryptoExtras/ARC/ARCRequest.swift
Sources/CryptoExtras/ARC/ARCResponse.swift
Sources/CryptoExtras/ARC/ARCServer.swift
Sources/CryptoExtras/ZKPs/Prover.swift
Sources/CryptoExtras/ZKPs/Verifier.swift
Sources/CryptoExtras/ZKPs/ZKPToolbox.swift
Sources/CryptoExtras/ChaCha20CTR/ChaCha20CTR.swift
Sources/CryptoExtras/ECToolbox/ECToolbox.swift
Sources/CryptoExtras/H2G/HashToField.swift
Sources/CryptoExtras/Key Derivation/KDF.swift
Sources/CryptoExtras/Key Derivation/PBKDF2/PBKDF2.swift
Sources/CryptoExtras/Key Derivation/Scrypt/Scrypt.swift
Sources/CryptoExtras/OPRFs/OPRF.swift
Sources/CryptoExtras/OPRFs/OPRFClient.swift
Sources/CryptoExtras/OPRFs/OPRFServer.swift
Sources/CryptoExtras/OPRFs/VOPRF+API.swift
Sources/CryptoExtras/OPRFs/VOPRFClient.swift
Sources/CryptoExtras/OPRFs/VOPRFServer.swift
Sources/CryptoExtras/RSA/RSA+BlindSigning.swift
Sources/CryptoExtras/RSA/RSA.swift
Sources/CryptoExtras/Util/BoringSSLHelpers.swift
Sources/CryptoExtras/Util/DigestType.swift
Sources/CryptoExtras/Util/Error.swift
Sources/CryptoExtras/Util/I2OSP.swift
Sources/CryptoExtras/Util/IntegerEncoding.swift
Sources/CryptoExtras/Util/PEMDocument.swift
Sources/CryptoExtras/Util/PrettyBytes.swift
Sources/CryptoExtras/Util/SubjectPublicKeyInfo.swift
Sources/CryptoExtras/ZKPs/DLEQ.swift
Sources/crypto-shasum/main.swift
Tests/CryptoTests/ASN1/ASN1Tests.swift
Tests/CryptoTests/ASN1/GeneralizedTimeTests.swift
@@ -115,6 +121,9 @@ Tests/CryptoTests/Encodings/DERTests.swift
Tests/CryptoTests/Encodings/ECKeyEncodingsTests.swift
Tests/CryptoTests/HPKE/HPKETests-TestVectors.swift
Tests/CryptoTests/HPKE/HPKETests.swift
Tests/CryptoTests/KEM/MLKEMKeyGenTests.swift
Tests/CryptoTests/KEM/MLKEMTests.swift
Tests/CryptoTests/KEM/XWingTests.swift
Tests/CryptoTests/Key Derivation/ECprivateKeysFromSeeds.swift
Tests/CryptoTests/Key Derivation/HKDFTests.swift
Tests/CryptoTests/Key Derivation/SharedSecretTests.swift
@@ -125,36 +134,38 @@ Tests/CryptoTests/SecureBytes/SecureBytesTests.swift
Tests/CryptoTests/Signatures/ECDSA/ECDSASignatureTests.swift
Tests/CryptoTests/Signatures/ECDSA/RawECDSASignaturesTests.swift
Tests/CryptoTests/Signatures/EdDSA/Ed25519-Runner.swift
Tests/CryptoTests/Signatures/MLDSA/MLDSAKeyGenTests.swift
Tests/CryptoTests/Signatures/MLDSA/MLDSATests.swift
Tests/CryptoTests/Utils/PrettyBytes.swift
Tests/CryptoTests/Utils/RFCVector.swift
Tests/CryptoTests/Utils/SplitData.swift
Tests/CryptoTests/Utils/Wycheproof.swift
Tests/CryptoTests/Utils/XCTestUtils.swift
Tests/_CryptoExtrasTests/AES Block Function Tests.swift
Tests/_CryptoExtrasTests/AES-GCM-SIV-Runner.swift
Tests/_CryptoExtrasTests/AES_CBCTests.swift
Tests/_CryptoExtrasTests/AES_CFBTests.swift
Tests/_CryptoExtrasTests/AES_CTRTests.swift
Tests/_CryptoExtrasTests/ARC/ARCAPITests.swift
Tests/_CryptoExtrasTests/ARC/ARCEncodingTests.swift
Tests/_CryptoExtrasTests/ARC/ARCPublicAPITests.swift
Tests/_CryptoExtrasTests/ARC/ARCTestVectors.swift
Tests/_CryptoExtrasTests/ARC/ARCTests.swift
Tests/_CryptoExtrasTests/ChaCha20CTRTests.swift
Tests/_CryptoExtrasTests/ECToolbox/HashToCurveTests.swift
Tests/_CryptoExtrasTests/OPRFs/ECVOPRFTests.swift
Tests/_CryptoExtrasTests/OPRFs/VOPRFAPITests.swift
Tests/_CryptoExtrasTests/OPRFs/VOPRFPublicAPITests.swift
Tests/_CryptoExtrasTests/PBKDF2Tests.swift
Tests/_CryptoExtrasTests/ScryptTests.swift
Tests/_CryptoExtrasTests/TestRSABlindSigning.swift
Tests/_CryptoExtrasTests/TestRSABlindSigningAPI.swift
Tests/_CryptoExtrasTests/TestRSAEncryption.swift
Tests/_CryptoExtrasTests/TestRSASigning.swift
Tests/_CryptoExtrasTests/Util/IntegerEncodingTests.swift
Tests/_CryptoExtrasTests/Utils/BytesUtil.swift
Tests/_CryptoExtrasTests/Utils/RFCVector.swift
Tests/_CryptoExtrasTests/Utils/SplitData.swift
Tests/_CryptoExtrasTests/Utils/Wycheproof.swift
Tests/_CryptoExtrasTests/Utils/XCTestUtils.swift
Tests/_CryptoExtrasTests/ZKPs/ZKPToolbox.swift
Tests/CryptoExtrasTests/AES Block Function Tests.swift
Tests/CryptoExtrasTests/AES-GCM-SIV-Runner.swift
Tests/CryptoExtrasTests/AES_CBCTests.swift
Tests/CryptoExtrasTests/AES_CFBTests.swift
Tests/CryptoExtrasTests/AES_CTRTests.swift
Tests/CryptoExtrasTests/ARC/ARCAPITests.swift
Tests/CryptoExtrasTests/ARC/ARCEncodingTests.swift
Tests/CryptoExtrasTests/ARC/ARCPublicAPITests.swift
Tests/CryptoExtrasTests/ARC/ARCTestVectors.swift
Tests/CryptoExtrasTests/ARC/ARCTests.swift
Tests/CryptoExtrasTests/ChaCha20CTRTests.swift
Tests/CryptoExtrasTests/ECToolbox/HashToCurveTests.swift
Tests/CryptoExtrasTests/OPRFs/ECVOPRFTests.swift
Tests/CryptoExtrasTests/OPRFs/VOPRFAPITests.swift
Tests/CryptoExtrasTests/OPRFs/VOPRFPublicAPITests.swift
Tests/CryptoExtrasTests/PBKDF2Tests.swift
Tests/CryptoExtrasTests/ScryptTests.swift
Tests/CryptoExtrasTests/TestRSABlindSigning.swift
Tests/CryptoExtrasTests/TestRSABlindSigningAPI.swift
Tests/CryptoExtrasTests/TestRSAEncryption.swift
Tests/CryptoExtrasTests/TestRSASigning.swift
Tests/CryptoExtrasTests/Util/IntegerEncodingTests.swift
Tests/CryptoExtrasTests/Utils/BytesUtil.swift
Tests/CryptoExtrasTests/Utils/RFCVector.swift
Tests/CryptoExtrasTests/Utils/SplitData.swift
Tests/CryptoExtrasTests/Utils/Wycheproof.swift
Tests/CryptoExtrasTests/Utils/XCTestUtils.swift
Tests/CryptoExtrasTests/ZKPs/ZKPToolbox.swift
+2 -1
View File
@@ -1 +1,2 @@
Sources/CCryptoBoringSSL/*
Sources/CCryptoBoringSSL/*
Sources/CXKCP/*
+51 -1
View File
@@ -13,8 +13,13 @@
//===----------------------------------------------------------------------===//
import Benchmark
import Crypto
import CryptoExtras
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
import _CryptoExtras
#endif
let benchmarks = {
let defaultMetrics: [BenchmarkMetric] = [.mallocCountTotal, .cpuTotal]
@@ -158,4 +163,49 @@ let benchmarks = {
blackHole(try privateKey.evaluate(blindedElement))
}
}
Benchmark(
"key-exchange-p256",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 10
)
) { benchmark in
for _ in benchmark.scaledIterations {
let (key1, key2) = (P256.KeyAgreement.PrivateKey(), P256.KeyAgreement.PrivateKey())
blackHole(try key1.sharedSecretFromKeyAgreement(with: key2.publicKey))
}
}
Benchmark(
"key-exchange-p384",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 10
)
) { benchmark in
for _ in benchmark.scaledIterations {
let (key1, key2) = (P384.KeyAgreement.PrivateKey(), P384.KeyAgreement.PrivateKey())
blackHole(try key1.sharedSecretFromKeyAgreement(with: key2.publicKey))
}
}
Benchmark(
"key-exchange-p521",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 10
)
) { benchmark in
for _ in benchmark.scaledIterations {
let (key1, key2) = (P521.KeyAgreement.PrivateKey(), P521.KeyAgreement.PrivateKey())
blackHole(try key1.sharedSecretFromKeyAgreement(with: key2.publicKey))
}
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.10
// swift-tools-version:6.1
import PackageDescription
let package = Package(
@@ -14,7 +14,7 @@ let package = Package(
dependencies: [
.product(name: "Benchmark", package: "package-benchmark"),
.product(name: "Crypto", package: "swift-crypto"),
.product(name: "_CryptoExtras", package: "swift-crypto"),
.product(name: "CryptoExtras", package: "swift-crypto"),
],
path: "Benchmarks/",
plugins: [
+1 -1
View File
@@ -69,7 +69,7 @@ act --container-architecture linux/amd64 pull_request -j cmake-lists -W ./.githu
You can find the underlying script at https://github.com/apple/swift-nio/blob/main/scripts/update-cmake-lists.sh . Using the script directly is less straightforwards because it requires you to pass the JSON config from the `pull_request.yml` file into the script, such as:
```
curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/update-cmake-lists.sh | CONFIG_JSON='{"targets":[{"name":"CCryptoBoringSSL","type":"source","exceptions":[]},{"name":"CCryptoBoringSSLShims","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"_CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash
curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/update-cmake-lists.sh | CONFIG_JSON='{"targets":[{"name":"CCryptoBoringSSL","type":"source","exceptions":[]},{"name":"CCryptoBoringSSLShims","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash
```
## API Evolution
+1 -1
View File
@@ -34,7 +34,7 @@ This product contains test vectors from Google's wycheproof project.
---
This product contains a derivation of various scripts from SwiftNIO.
This product contains a derivation of various files from SwiftNIO.
* LICENSE (Apache License 2.0):
* https://www.apache.org/licenses/LICENSE-2.0
+54 -7
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.10
// swift-tools-version:6.1
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
@@ -20,7 +20,7 @@
// Sources/CCryptoBoringSSL directory. The source repository is at
// https://boringssl.googlesource.com/boringssl.
//
// BoringSSL Commit: 035e720641f385e82c72b7b0a9e1d89e58cb5ed5
// BoringSSL Commit: 0226f30467f540a3f62ef48d453f93927da199b6
import PackageDescription
@@ -49,6 +49,8 @@ if development || isFreeBSD {
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
"CryptoBoringWrapper",
"CXKCP",
"CXKCPShims",
]
} else {
let platforms: [Platform] = [
@@ -66,6 +68,8 @@ if development || isFreeBSD {
.target(name: "CCryptoBoringSSL", condition: .when(platforms: platforms)),
.target(name: "CCryptoBoringSSLShims", condition: .when(platforms: platforms)),
.target(name: "CryptoBoringWrapper", condition: .when(platforms: platforms)),
.target(name: "CXKCP", condition: .when(platforms: platforms)),
.target(name: "CXKCPShims", condition: .when(platforms: platforms)),
]
}
@@ -85,7 +89,9 @@ let package = Package(
name: "swift-crypto",
products: [
.library(name: "Crypto", targets: ["Crypto"]),
// Kept for backward compatibility
.library(name: "_CryptoExtras", targets: ["_CryptoExtras"]),
.library(name: "CryptoExtras", targets: ["CryptoExtras"]),
/* This target is used only for symbol mangling. It's added and removed automatically because it emits build warnings. MANGLE_START
.library(name: "CCryptoBoringSSL", type: .static, targets: ["CCryptoBoringSSL"]),
MANGLE_END */
@@ -98,7 +104,6 @@ let package = Package(
name: "CCryptoBoringSSL",
exclude: privacyManifestExclude + [
"hash.txt",
"include/boringssl_prefix_symbols_nasm.inc",
"CMakeLists.txt",
/*
* These files are excluded to support WASI libc which doesn't provide <netdb.h>.
@@ -125,6 +130,21 @@ let package = Package(
.define("OPENSSL_NO_ASM", .when(platforms: [Platform.wasi])),
]
),
.target(
name: "CXKCP",
exclude: [
"CMakeLists.txt"
],
cSettings: [
.define("XKCP_has_KeccakP1600"),
.headerSearchPath("include"),
.headerSearchPath("high"),
.headerSearchPath("low"),
.headerSearchPath("low/KeccakP-1600"),
.headerSearchPath("low/common"),
.headerSearchPath("common"),
]
),
.target(
name: "CCryptoBoringSSLShims",
dependencies: ["CCryptoBoringSSL"],
@@ -133,6 +153,14 @@ let package = Package(
],
resources: privacyManifestResource
),
.target(
name: "CXKCPShims",
dependencies: ["CXKCP"],
exclude: privacyManifestExclude + [
"CMakeLists.txt"
],
resources: privacyManifestResource
),
.target(
name: "Crypto",
dependencies: dependencies,
@@ -142,12 +170,16 @@ let package = Package(
"Digests/Digests.swift.gyb",
"Key Agreement/ECDH.swift.gyb",
"Signatures/ECDSA.swift.gyb",
"Signatures/MLDSA.swift.gyb",
"Signatures/BoringSSL/MLDSA_boring.swift.gyb",
"KEM/MLKEM.swift.gyb",
"KEM/BoringSSL/MLKEM_boring.swift.gyb",
],
resources: privacyManifestResource,
swiftSettings: swiftSettings
),
.target(
name: "_CryptoExtras",
name: "CryptoExtras",
dependencies: [
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
@@ -161,6 +193,13 @@ let package = Package(
resources: privacyManifestResource,
swiftSettings: swiftSettings
),
.target(
name: "_CryptoExtras",
dependencies: [
"CryptoExtras",
],
swiftSettings: swiftSettings
),
.target(
name: "CryptoBoringWrapper",
dependencies: [
@@ -177,13 +216,20 @@ let package = Package(
name: "CryptoTests",
dependencies: ["Crypto"],
resources: [
.copy("HPKE/hpke-test-vectors.json")
.copy("HPKE/hpke-test-vectors.json"),
.copy("KEM/MLKEM768_BSSLKAT.json"),
.copy("KEM/MLKEM768KAT.json"),
.copy("KEM/MLKEM1024_BSSLKAT.json"),
.copy("KEM/MLKEM1024KAT.json"),
.copy("KEM/test-vectors.json"),
.copy("Signatures/MLDSA/MLDSA65_KeyGen_KAT.json"),
.copy("Signatures/MLDSA/MLDSA87_KeyGen_KAT.json"),
],
swiftSettings: swiftSettings
),
.testTarget(
name: "_CryptoExtrasTests",
dependencies: ["_CryptoExtras"],
name: "CryptoExtrasTests",
dependencies: ["CryptoExtras"],
resources: [
.copy("ECToolbox/H2CVectors/P256_XMD-SHA-256_SSWU_RO_.json"),
.copy("ECToolbox/H2CVectors/P384_XMD-SHA-384_SSWU_RO_.json"),
@@ -194,6 +240,7 @@ let package = Package(
swiftSettings: swiftSettings
),
.testTarget(name: "CryptoBoringWrapperTests", dependencies: ["CryptoBoringWrapper"]),
.testTarget(name: "CXKCPTests", dependencies: ["CXKCP"]),
],
cxxLanguageStandard: .cxx17
)
+11 -6
View File
@@ -7,9 +7,9 @@ Swift Crypto is an open-source implementation of a substantial portion of the AP
Swift Crypto is available as a Swift Package Manager package. To use it, add the following dependency in your `Package.swift`:
```swift
// swift-crypto 1.x, 2.x and 3.x are almost API compatible, so most clients
// swift-crypto 1.x, 2.x, 3.x, and 4.x are almost API compatible, so most clients
// should allow any of them
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "4.0.0"),
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "5.0.0"),
```
and to your target, add `Crypto` to your dependencies. You can then `import Crypto` to get access to Swift Crypto's functionality.
@@ -34,7 +34,7 @@ When building Swift Crypto for use on Linux or Windows, Swift Crypto builds subs
2. The common API of Swift Crypto and CryptoKit.
3. The backing implementation of this common API, which calls into BoringSSL.
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The backing BoringSSL-based implementation is unique to Swift Crypto.
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The backing BoringSSL-based implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIS predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL implementation of the library in your application, no matter the platform.
## Evolution
@@ -108,7 +108,7 @@ If you believe you have identified a vulnerability in Swift Crypto, please [repo
### Swift versions
The most recent versions of Swift Crypto support Swift 5.7 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
The most recent versions of Swift Crypto support Swift 6 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
Swift Crypto | Minimum Swift Version
--------------------|----------------------
@@ -119,7 +119,8 @@ Swift Crypto | Minimum Swift Version
`3.1.0 ..< 3.3.0` | 5.7
`3.3.0 ..< 3.8.0` | 5.8
`3.9.0 ..< 3.13.0` | 5.9
`3.13.0 ...` | 5.10
`3.13.0 ..< 4.0.0` | 5.10
`4.0.0 ...` | 6.0
### Compatibility
@@ -131,10 +132,14 @@ SemVer and Swift Crypto's Public API guarantees should result in a working progr
Swift Crypto 2.0.0 was released in September 2021. The only breaking change between Swift Crypto 2.0.0 and 1.0.0 was the addition of new cases in the `CryptoError` enumeration. For most users, then, it's safe to depend on either the 1.0.0 _or_ 2.0.0 series of releases.
Swift Crypto 3.0.0 was released in September 2023. Again the only breaking change was the addition of new cases in the `CryptoError` enumeration, so most users can safely depend on the 1.0.0, 2.0.0, or 3.0.0 series of releases.
Swift Crypto 4.0.0 was released in September 2025. Again the only breaking change was the addition of new cases in the `CryptoError` enumeration, so most users can safely depend on the 1.0.0, 2.0.0, 3.0.0, or 4.0.0 series of releases. Note that in this release `_CryptoExtras` was renamed to `CryptoExtras`. The old products and targets have been kept around for compatibility reasons, but users depending only on new code should use `CryptoExtras` not `_CryptoExtras`.
To do so, please use the following dependency in your `Package.swift`:
```swift
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "3.0.0"),
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "5.0.0"),
```
### Developing Swift Crypto on macOS
-1
View File
@@ -255,7 +255,6 @@ add_library(CCryptoBoringSSL STATIC
"crypto/x509/x_req.cc"
"crypto/x509/x_sig.cc"
"crypto/x509/x_spki.cc"
"crypto/x509/x_val.cc"
"crypto/x509/x_x509.cc"
"crypto/x509/x_x509a.cc"
"crypto/xwing/xwing.cc"
@@ -20,6 +20,7 @@
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_span.h>
#include "../internal.h"
#include "internal.h"
@@ -110,76 +111,96 @@ int asn1_marshal_bit_string(CBB *out, const ASN1_BIT_STRING *in,
CBB_flush(out);
}
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;
if (len < 1) {
static int asn1_parse_bit_string_contents(bssl::Span<const uint8_t> 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<uint8_t *>(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(&copy, &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;
if (!ASN1_STRING_set(out, CBS_data(&cbs), CBS_len(&cbs))) {
return 0;
}
*pp = p;
out->type = V_ASN1_BIT_STRING;
// |ASN1_STRING_FLAG_BITS_LEFT| and the bottom 3 bits encode |padding|.
out->flags &= ~0x07;
out->flags |= ASN1_STRING_FLAG_BITS_LEFT | padding;
return 1;
}
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;
}
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(bssl::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 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 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);
}
// These next 2 functions from Goetz Babin-Ebell <babinebell@trustcenter.de>
@@ -21,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,
@@ -36,6 +36,23 @@ int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d) {
return 1;
}
int 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);
}
+60 -36
View File
@@ -21,6 +21,7 @@
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_span.h>
#include "../internal.h"
#include "internal.h"
@@ -146,32 +147,13 @@ 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(bssl::Span<const uint8_t> 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;
}
ASN1_INTEGER *ret = NULL;
if (out == NULL || *out == NULL) {
ret = ASN1_INTEGER_new();
if (ret == NULL) {
return NULL;
}
} else {
ret = *out;
return 0;
}
// Convert to |ASN1_INTEGER|'s sign-and-magnitude representation. First,
@@ -192,33 +174,75 @@ 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 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 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(bssl::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) {
@@ -27,26 +27,27 @@
#include "internal.h"
int i2d_ASN1_OBJECT(const ASN1_OBJECT *in, unsigned char **outp) {
int asn1_marshal_object(CBB *out, const ASN1_OBJECT *in, CBS_ASN1_TAG tag) {
if (in == NULL) {
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 bssl::I2DFromCBB(
/*initial_capacity=*/static_cast<size_t>(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) {
@@ -90,53 +91,48 @@ 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 bssl::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) {
return bssl::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_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 NULL;
return nullptr;
}
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 ASN1_OBJECT_create(NID_undef, CBS_data(&child), CBS_len(&child),
/*sn=*/nullptr, /*ln=*/nullptr);
}
ASN1_OBJECT *ASN1_OBJECT_new(void) {
@@ -18,6 +18,8 @@
#include <stdlib.h>
#include <string.h>
#include <iterator>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_obj.h>
@@ -129,7 +131,7 @@ 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<ASN1_STRING_TABLE *>(
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) {
return tbl;
@@ -202,5 +204,5 @@ void ASN1_STRING_TABLE_cleanup(void) {}
void 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);
}
@@ -222,3 +222,19 @@ int ASN1_TIME_to_posix(const ASN1_TIME *t, int64_t *out_time) {
}
return OPENSSL_tm_to_posix(&tm, out_time);
}
int 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 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<CBS_ASN1_TAG>(in->type));
}
@@ -16,6 +16,7 @@
#include <assert.h>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_obj.h>
@@ -170,3 +171,220 @@ int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b) {
return result;
}
int 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) {
bssl::UniquePtr<ASN1_OBJECT> 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.
bssl::UniquePtr<ASN1_STRING> 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 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:
case CBS_ASN1_T61STRING:
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:
// T61String is parsed as Latin-1, so all byte strings are valid. The
// others we currently do not enforce.
//
// TODO(crbug.com/42290290): Enforce the encoding of the other string
// types.
if (!asn1_parse_octet_string(&elem, out, tag)) {
return 0;
}
out->type = static_cast<int>(tag);
return 1;
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;
}
}
int 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:
return asn1_marshal_integer(out, in->value.integer,
static_cast<CBS_ASN1_TAG>(in->type));
case V_ASN1_BIT_STRING:
return asn1_marshal_bit_string(out, in->value.bit_string, /*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->value.asn1_string,
static_cast<CBS_ASN1_TAG>(in->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->value.asn1_string),
ASN1_STRING_length(in->value.asn1_string));
default:
// |ASN1_TYPE|s can have type -1 when default-constructed.
OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE);
return 0;
}
}
@@ -37,6 +37,22 @@ int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d,
return 1;
}
int 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);
}
@@ -295,11 +295,21 @@ ASN1_STRING *ASN1_STRING_type_new(int type) {
return ret;
}
void asn1_string_init(ASN1_STRING *str, int type) {
OPENSSL_memset(str, 0, sizeof(ASN1_STRING));
str->type = type;
}
void asn1_string_cleanup(ASN1_STRING *str) {
OPENSSL_free(str->data);
str->data = nullptr;
}
void ASN1_STRING_free(ASN1_STRING *str) {
if (str == NULL) {
return;
}
OPENSSL_free(str->data);
asn1_string_cleanup(str);
OPENSSL_free(str);
}
@@ -353,3 +363,70 @@ 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 asn1_parse_octet_string(CBS *cbs, ASN1_STRING *out, CBS_ASN1_TAG tag) {
tag = tag == 0 ? CBS_ASN1_OCTETSTRING : tag;
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 = V_ASN1_OCTET_STRING;
return 1;
}
int 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(&copy) != 0) {
uint32_t c;
if (!get_char(&copy, &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 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 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 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);
}
+189 -53
View File
@@ -48,7 +48,8 @@ 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
@@ -72,6 +73,130 @@ struct asn1_object_st {
ASN1_OBJECT *ASN1_OBJECT_new(void);
// 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);
// asn1_bit_string_length returns the number of bytes in |str| and sets
// |*out_padding_bits| to the number of padding bits.
//
// 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 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_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_type_cleanup releases memory associated with |a|'s value, without
// freeing |a| itself.
void asn1_type_cleanup(ASN1_TYPE *a);
// 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 zeron on error.
int asn1_marshal_any(CBB *out, const ASN1_TYPE *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 {
@@ -79,16 +204,8 @@ typedef struct ASN1_ENCODING_st {
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;
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_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it);
void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
@@ -97,14 +214,12 @@ 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|.
// non-zero, the value is optional.
//
// 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);
const ASN1_ITEM *it, int tag, int aclass, char opt);
// 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
@@ -150,47 +265,11 @@ int asn1_enc_restore(int *len, unsigned char **out, ASN1_VALUE **pval,
// 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|.
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.
//
// 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);
// 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|.
int asn1_marshal_integer(CBB *out, const ASN1_INTEGER *in, CBS_ASN1_TAG tag);
typedef struct {
int nid;
long minsize;
@@ -210,8 +289,18 @@ 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);
typedef int ASN1_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it);
@@ -221,10 +310,57 @@ 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_parse *asn1_ex_parse;
ASN1_ex_i2d *asn1_ex_i2d;
} ASN1_EXTERN_FUNCS;
#define IMPLEMENT_EXTERN_ASN1_SIMPLE(name, new_func, free_func, parse_func, \
i2d_func) \
static int name##_new_cb(ASN1_VALUE **pval, const ASN1_ITEM *it) { \
*pval = (ASN1_VALUE *)new_func(); \
return *pval != nullptr; \
} \
\
static void name##_free_cb(ASN1_VALUE **pval, const ASN1_ITEM *it) { \
free_func((name *)*pval); \
*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, CBS_ASN1_SEQUENCE)) { \
return 1; \
} \
\
if ((*pval == nullptr && !name##_new_cb(pval, it)) || \
!parse_func(cbs, (name *)*pval)) { \
return 0; \
} \
return 1; \
} \
\
static int name##_i2d_cb(ASN1_VALUE **pval, unsigned char **out, \
const ASN1_ITEM *it) { \
return i2d_func((name *)*pval, out); \
} \
\
static const ASN1_EXTERN_FUNCS name##_extern_funcs = { \
name##_new_cb, name##_free_cb, name##_parse_cb, name##_i2d_cb}; \
\
IMPLEMENT_EXTERN_ASN1(name, name##_extern_funcs)
// 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)
// ASN1_ANY_AS_STRING is an |ASN1_ITEM| with ASN.1 type ANY and C type
// |ASN1_STRING*|. Types which are not represented with |ASN1_STRING|, such as
// |ASN1_OBJECT|, are represented with type |V_ASN1_OTHER|.
+183 -292
View File
@@ -39,18 +39,16 @@ static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
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);
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);
int depth);
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);
char opt, int depth);
unsigned long ASN1_tag2bit(int tag) {
switch (tag) {
@@ -91,25 +89,6 @@ unsigned long ASN1_tag2bit(int 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
@@ -119,7 +98,7 @@ ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **pval, const unsigned char **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) {
/*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
@@ -149,7 +128,7 @@ ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
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) {
char opt, int depth) {
const ASN1_TEMPLATE *tt, *errtt = NULL;
const unsigned char *p = NULL, *q;
unsigned char oclass;
@@ -161,10 +140,9 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
if (!pval) {
return 0;
}
if (buf != NULL) {
assert(CRYPTO_BUFFER_data(buf) <= *in &&
*in + len <= CRYPTO_BUFFER_data(buf) + CRYPTO_BUFFER_len(buf));
if (len < 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BUFFER_TOO_SMALL);
goto err;
}
// Bound |len| to comfortably fit in an int. Lengths in this module often
@@ -189,11 +167,9 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
goto err;
}
return asn1_template_ex_d2i(pval, in, len, it->templates, opt, buf,
depth);
return asn1_template_ex_d2i(pval, in, len, it->templates, opt, depth);
}
return asn1_d2i_ex_primitive(pval, in, len, it, tag, aclass, opt);
break;
case ASN1_ITYPE_MSTRING:
// It never makes sense for multi-strings to have implicit tagging, so
@@ -239,7 +215,18 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
}
const ASN1_EXTERN_FUNCS *ef =
reinterpret_cast<const ASN1_EXTERN_FUNCS *>(it->funcs);
return ef->asn1_ex_d2i(pval, in, len, it, opt, NULL);
CBS cbs;
CBS_init(&cbs, *in, len);
CBS copy = cbs;
if (!ef->asn1_ex_parse(pval, &cbs, it, opt)) {
goto err;
}
*in = CBS_data(&cbs);
// Check whether the function skipped an optional element.
//
// TODO(crbug.com/42290418): Switch the rest of this function to
// |asn1_ex_parse|'s calling convention.
return CBS_len(&cbs) == CBS_len(&copy) ? -1 : 1;
}
case ASN1_ITYPE_CHOICE: {
@@ -274,7 +261,7 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **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);
ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, depth);
// If field not present, try the next one
if (ret == -1) {
continue;
@@ -380,7 +367,7 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
}
// attempt to read in field, allowing each to be OPTIONAL
ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, buf, depth);
ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, depth);
if (!ret) {
errtt = seqtt;
goto err;
@@ -419,7 +406,7 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
}
}
// Save encoding
if (!asn1_enc_save(pval, *in, p - *in, it, buf)) {
if (!asn1_enc_save(pval, *in, p - *in, it)) {
goto auxerr;
}
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) {
@@ -445,10 +432,8 @@ err:
}
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);
const ASN1_ITEM *it, int tag, int aclass, char opt) {
return asn1_item_ex_d2i(pval, in, len, it, tag, aclass, opt, /*depth=*/0);
}
// Templates are handled with two separate functions. One handles any
@@ -456,7 +441,7 @@ int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
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 depth) {
int aclass;
int ret;
long len;
@@ -488,7 +473,7 @@ static int asn1_template_ex_d2i(ASN1_VALUE **val, const unsigned char **in,
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);
ret = asn1_template_noexp_d2i(val, &p, len, tt, /*opt=*/0, depth);
if (!ret) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
return 0;
@@ -501,7 +486,7 @@ static int asn1_template_ex_d2i(ASN1_VALUE **val, const unsigned char **in,
goto err;
}
} else {
return asn1_template_noexp_d2i(val, in, inlen, tt, opt, buf, depth);
return asn1_template_noexp_d2i(val, in, inlen, tt, opt, depth);
}
*in = p;
@@ -514,7 +499,7 @@ err:
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 depth) {
int aclass;
int ret;
const unsigned char *p;
@@ -572,7 +557,8 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in,
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)) {
/*tag=*/-1, /*aclass=*/0, /*opt=*/0, depth)) {
ASN1_item_ex_free(&skfield, ASN1_ITEM_ptr(tt->item));
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
goto err;
}
@@ -585,7 +571,7 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in,
} 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);
aclass, opt, depth);
if (!ret) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
goto err;
@@ -595,7 +581,7 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in,
} else {
// Nothing special
ret = asn1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), /*tag=*/-1,
/*aclass=*/0, opt, buf, depth);
/*aclass=*/0, opt, depth);
if (!ret) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
goto err;
@@ -612,306 +598,211 @@ err:
return 0;
}
// TODO(crbug.com/42290418): Switch the whole file to use a CBS-based calling
// convention.
static int asn1_d2i_ex_primitive_cbs(ASN1_VALUE **pval, CBS *cbs,
const ASN1_ITEM *it, int tag, int aclass,
char opt);
// asn1_d2i_ex_primitive returns one on success, zero on error, and -1 if an
// optional value was skipped.
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
CBS cbs;
CBS_init(&cbs, *in, inlen);
int ret = asn1_d2i_ex_primitive_cbs(pval, &cbs, it, tag, aclass, opt);
if (ret <= 0) {
return ret;
}
*in = CBS_data(&cbs);
return 1;
}
static ASN1_STRING *ensure_string(ASN1_VALUE **pval) {
if (*pval) {
return (ASN1_STRING *)*pval;
}
ASN1_STRING *str = ASN1_STRING_new();
if (str == nullptr) {
return nullptr;
}
*pval = (ASN1_VALUE *)str;
return str;
}
static int asn1_d2i_ex_primitive_cbs(ASN1_VALUE **pval, CBS *cbs,
const ASN1_ITEM *it, int tag, int aclass,
char opt) {
// Historically, |it->funcs| for primitive types contained an
// |ASN1_PRIMITIVE_FUNCS| table of callbacks.
assert(it->funcs == NULL);
int utype;
assert(it->itype == ASN1_ITYPE_PRIMITIVE || it->itype == ASN1_ITYPE_MSTRING);
if (it->itype == ASN1_ITYPE_MSTRING) {
// MSTRING passes utype in |tag|, normally used for implicit tagging.
utype = tag;
tag = -1;
} else {
utype = it->utype;
}
// Handle ANY types.
if (utype == V_ASN1_ANY || utype == V_ASN1_ANY_AS_STRING) {
// If type is ANY need to figure out type from tag
unsigned char oclass;
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);
return 0;
}
const int is_string = utype == V_ASN1_ANY_AS_STRING;
p = *in;
ret = asn1_check_tlen(&plen, &utype, &oclass, &cst, &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;
}
// These three types are not represented as |ASN1_STRING|, so they must be
// parsed separately and then treated as an opaque |V_ASN1_OTHER|.
if (is_string && (utype == V_ASN1_OBJECT || utype == V_ASN1_NULL ||
utype == V_ASN1_BOOLEAN)) {
if (cst) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_PRIMITIVE);
return 0;
}
CBS cbs;
CBS_init(&cbs, p, plen);
if (utype == V_ASN1_OBJECT && !CBS_is_valid_asn1_oid(&cbs)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_OBJECT_ENCODING);
return 0;
}
if (utype == V_ASN1_NULL && CBS_len(&cbs) != 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NULL_IS_WRONG_LENGTH);
return 0;
}
if (utype == V_ASN1_BOOLEAN) {
if (CBS_len(&cbs) != 1) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
return 0;
}
uint8_t v = CBS_data(&cbs)[0];
if (v != 0 && v != 0xff) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
}
utype = V_ASN1_OTHER;
if (opt && CBS_len(cbs) == 0) {
return -1; // Omitted OPTIONAL value.
}
}
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;
}
// We now have content length and type: translate into a structure
if (!asn1_ex_c2i(pval, cont, len, utype, it)) {
goto err;
}
*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 (utype == V_ASN1_ANY) {
ASN1_TYPE *typ;
if (!*pval) {
typ = ASN1_TYPE_new();
if (typ == NULL) {
goto err;
return 0;
}
*pval = (ASN1_VALUE *)typ;
} else {
typ = (ASN1_TYPE *)*pval;
}
if (utype != typ->type) {
ASN1_TYPE_set(typ, utype, NULL);
return asn1_parse_any(cbs, typ);
}
if (utype == V_ASN1_ANY_AS_STRING) {
ASN1_STRING *str = ensure_string(pval);
if (str == nullptr) {
return 0;
}
opval = pval;
pval = &typ->value.asn1_value;
return asn1_parse_any_as_string(cbs, str);
}
// If implementing a type that is not represented in |ASN1_STRING|, the
// |V_ASN1_ANY_AS_STRING| logic must be modified to redirect it to
// |V_ASN1_OTHER|.
switch (utype) {
case V_ASN1_OBJECT:
if (!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len)) {
goto err;
}
break;
// Convert the crypto/asn1 tag into a CBS one.
if (tag == -1) {
tag = utype;
aclass = V_ASN1_UNIVERSAL;
}
case V_ASN1_NULL:
if (len) {
// All edge cases of |utype| should have been handled already. |utype| is now
// either a primitive |ASN1_ITEM|, handled by |DECLARE_ASN1_ITEM|, or a
// multistring option with a corresponding |B_ASN1_*| constant.
assert(utype >= 0 && utype <= V_ASN1_MAX_UNIVERSAL);
CBS_ASN1_TAG cbs_tag =
(static_cast<CBS_ASN1_TAG>(aclass) << CBS_ASN1_TAG_SHIFT) |
static_cast<CBS_ASN1_TAG>(tag);
if (utype == V_ASN1_SEQUENCE || utype == V_ASN1_SET) {
cbs_tag |= CBS_ASN1_CONSTRUCTED;
}
if (opt && !CBS_peek_asn1_tag(cbs, cbs_tag)) {
return -1; // Omitted OPTIONAL value.
}
// Handle non-|ASN1_STRING| types.
switch (utype) {
case V_ASN1_OBJECT: {
bssl::UniquePtr<ASN1_OBJECT> obj(asn1_parse_object(cbs, cbs_tag));
if (obj == nullptr) {
return 0;
}
ASN1_OBJECT_free((ASN1_OBJECT *)*pval);
*pval = (ASN1_VALUE *)obj.release();
return 1;
}
case V_ASN1_NULL: {
CBS null;
if (!CBS_get_asn1(cbs, &null, cbs_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) {
return 1;
}
case V_ASN1_BOOLEAN: {
CBS child;
if (!CBS_get_asn1(cbs, &child, cbs_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;
ASN1_BOOLEAN *tbool;
tbool = (ASN1_BOOLEAN *)pval;
*tbool = CBS_data(&child)[0];
return 1;
}
}
// All other types as an |ASN1_STRING| representation.
ASN1_STRING *str = ensure_string(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, cbs_tag);
case V_ASN1_INTEGER:
return asn1_parse_integer(cbs, str, cbs_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, cbs_tag);
case V_ASN1_UNIVERSALSTRING:
return asn1_parse_universal_string(cbs, str, cbs_tag);
case V_ASN1_BMPSTRING:
return asn1_parse_bmp_string(cbs, str, cbs_tag);
case V_ASN1_UTF8STRING:
return asn1_parse_utf8_string(cbs, str, cbs_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, cbs_tag,
/*allow_timezone_offset=*/1);
case V_ASN1_GENERALIZEDTIME:
return asn1_parse_generalized_time(cbs, str, cbs_tag);
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_OTHER:
case V_ASN1_SET:
// T61String is parsed as Latin-1, so all byte strings are valid. The
// others we currently do not enforce.
//
// TODO(crbug.com/42290290): Enforce the encoding of the other string
// types.
if (!asn1_parse_octet_string(cbs, str, cbs_tag)) {
return 0;
}
str->type = utype;
return 1;
case V_ASN1_SEQUENCE: {
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;
}
}
// Save the entire element in the string.
CBS elem;
if (!CBS_get_asn1_element(cbs, &elem, cbs_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));
}
default:
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
goto err;
}
// 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 0;
}
}
return ret;
}
// Check an ASN1 tag and length: a bit like ASN1_get_object but it
@@ -19,6 +19,9 @@
#include "internal.h"
// 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) \
@@ -94,7 +94,6 @@ void asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it) {
if (enc) {
enc->enc = NULL;
enc->len = 0;
enc->buf = NULL;
}
}
@@ -106,7 +105,7 @@ void asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
}
int asn1_enc_save(ASN1_VALUE **pval, const uint8_t *in, size_t in_len,
const ASN1_ITEM *it, CRYPTO_BUFFER *buf) {
const ASN1_ITEM *it) {
ASN1_ENCODING *enc;
enc = asn1_get_enc_ptr(pval, it);
if (!enc) {
@@ -114,17 +113,9 @@ 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<uint8_t *>(OPENSSL_memdup(in, in_len));
if (!enc->enc) {
return 0;
}
enc->enc = reinterpret_cast<uint8_t *>(OPENSSL_memdup(in, in_len));
if (!enc->enc) {
return 0;
}
enc->len = in_len;
@@ -132,14 +123,9 @@ int asn1_enc_save(ASN1_VALUE **pval, const uint8_t *in, size_t in_len,
}
void asn1_encoding_clear(ASN1_ENCODING *enc) {
if (enc->buf != NULL) {
CRYPTO_BUFFER_free(enc->buf);
} else {
OPENSSL_free(enc->enc);
}
OPENSSL_free(enc->enc);
enc->enc = NULL;
enc->len = 0;
enc->buf = NULL;
}
int asn1_enc_restore(int *len, unsigned char **out, ASN1_VALUE **pval,
@@ -16,6 +16,8 @@
#include <assert.h>
#include <iterator>
#include "../internal.h"
// https://tools.ietf.org/html/rfc7693#section-2.6
@@ -99,7 +101,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];
}
@@ -15,12 +15,14 @@
#ifndef OPENSSL_HEADER_CRYPTO_BYTESTRING_INTERNAL_H
#define OPENSSL_HEADER_CRYPTO_BYTESTRING_INTERNAL_H
#include <CCryptoBoringSSL_base.h>
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_err.h>
#include <type_traits>
#if defined(__cplusplus)
extern "C" {
#endif
// 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
@@ -66,9 +68,53 @@ OPENSSL_EXPORT int CBS_get_asn1_implicit_string(CBS *in, CBS *out,
// This function may be used to help implement legacy i2d ASN.1 functions.
int CBB_finish_i2d(CBB *cbb, uint8_t **outp);
#if defined(__cplusplus)
} // extern C
#endif
BSSL_NAMESPACE_BEGIN
// D2IFromCBS takes a functor of type |Unique<T>(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 <typename T, typename CBSFunc>
inline T *D2IFromCBS(T **out, const uint8_t **inp, long len, CBSFunc func) {
static_assert(std::is_invocable_v<CBSFunc, CBS *>);
static_assert(
std::is_same_v<std::invoke_result_t<CBSFunc, CBS *>, UniquePtr<T>> ||
std::is_same_v<std::invoke_result_t<CBSFunc, CBS *>, T *>);
if (len < 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BUFFER_TOO_SMALL);
return nullptr;
}
CBS cbs;
CBS_init(&cbs, *inp, len);
UniquePtr<T> ret(func(&cbs));
if (ret == nullptr) {
return nullptr;
}
if (out != nullptr) {
UniquePtr<T> 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 <typename CBBFunc>
inline int I2DFromCBB(size_t initial_capacity, uint8_t **outp, CBBFunc func) {
static_assert(std::is_invocable_v<CBBFunc, CBB *>);
static_assert(std::is_same_v<std::invoke_result_t<CBBFunc, CBB *>, bool>);
ScopedCBB cbb;
if (!CBB_init(cbb.get(), initial_capacity) || !func(cbb.get())) {
return -1;
}
return CBB_finish_i2d(cbb.get(), outp);
}
BSSL_NAMESPACE_END
#endif // OPENSSL_HEADER_CRYPTO_BYTESTRING_INTERNAL_H
@@ -19,7 +19,7 @@
#include <CCryptoBoringSSL_cipher.h>
#include <CCryptoBoringSSL_crypto.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_sha.h>
#include <CCryptoBoringSSL_sha2.h>
#include "../fipsmodule/aes/internal.h"
#include "../fipsmodule/cipher/internal.h"
+30 -26
View File
@@ -31,7 +31,7 @@
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];
@@ -51,15 +51,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,11 +71,15 @@ 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;
@@ -85,7 +88,7 @@ static int aead_tls_init(EVP_AEAD_CTX *ctx, const uint8_t *key, size_t key_len,
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)) {
!HMAC_Init_ex(tls_ctx->hmac_ctx, key, mac_key_len, md, NULL)) {
aead_tls_cleanup(ctx);
return 0;
}
@@ -99,7 +102,7 @@ static size_t aead_tls_tag_len(const EVP_AEAD_CTX *ctx, const size_t in_len,
assert(extra_in_len == 0);
const AEAD_TLS_CTX *tls_ctx = (AEAD_TLS_CTX *)&ctx->state;
const size_t hmac_len = HMAC_size(&tls_ctx->hmac_ctx);
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;
@@ -160,11 +163,11 @@ static int aead_tls_seal_scatter(const EVP_AEAD_CTX *ctx, uint8_t *out,
// in-place.
uint8_t mac[EVP_MAX_MD_SIZE];
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_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)) {
return 0;
}
@@ -187,7 +190,8 @@ static int aead_tls_seal_scatter(const EVP_AEAD_CTX *ctx, uint8_t *out,
// 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;
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];
@@ -245,7 +249,7 @@ 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)) {
if (in_len < HMAC_size(tls_ctx->hmac_ctx)) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
@@ -303,7 +307,7 @@ static int aead_tls_open(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len,
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))) {
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;
@@ -313,9 +317,9 @@ static int aead_tls_open(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len,
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));
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);
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
@@ -335,14 +339,14 @@ static int aead_tls_open(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_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,
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));
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);
@@ -352,15 +356,15 @@ static int aead_tls_open(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len,
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)) {
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));
assert(mac_len == HMAC_size(tls_ctx->hmac_ctx));
record_mac = &out[data_len];
}
@@ -55,17 +55,17 @@ 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
@@ -75,11 +75,11 @@ const EVP_CIPHER *EVP_get_cipherbyname(const char *name) {
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;
}
@@ -19,6 +19,7 @@
#include <stdlib.h>
#include <CCryptoBoringSSL_base.h>
#include <CCryptoBoringSSL_sha.h>
#include "../internal.h"
@@ -129,7 +130,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,
@@ -623,6 +623,8 @@ int CONF_modules_load_file(const char *filename, const char *appname,
return 1;
}
void CONF_modules_unload(int all) {}
void CONF_modules_free(void) {}
void OPENSSL_config(const char *config_name) {}
@@ -137,6 +137,8 @@ void ENGINE_load_builtin_engines(void) {}
int ENGINE_register_all_complete(void) { return 1; }
void ENGINE_cleanup(void) {}
void OPENSSL_load_builtin_modules(void) {}
int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings) {
@@ -24,7 +24,7 @@
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_rand.h>
#include <CCryptoBoringSSL_sha.h>
#include <CCryptoBoringSSL_sha2.h>
#include "../internal.h"
#include "internal.h"
@@ -17,10 +17,12 @@
#include <assert.h>
#include <string.h>
#include <iterator>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_rand.h>
#include <CCryptoBoringSSL_sha.h>
#include <CCryptoBoringSSL_sha2.h>
#include "../fipsmodule/bn/internal.h"
#include "../internal.h"
@@ -333,18 +335,17 @@ static const scalar kOrder = {
// 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|.
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|.
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,
+4 -22
View File
@@ -95,29 +95,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 bssl::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 bssl::I2DFromCBB(
/*initial_capacity=*/256, outp,
[&](CBB *cbb) -> bool { return DH_marshal_parameters(cbb, in); });
}
+9 -9
View File
@@ -17,13 +17,13 @@
#include <CCryptoBoringSSL_bn.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_span.h>
#include "../fipsmodule/bn/internal.h"
#include "../fipsmodule/dh/internal.h"
static BIGNUM *get_params(BIGNUM *ret, const BN_ULONG *words,
size_t num_words) {
static BIGNUM *get_params(BIGNUM *ret, bssl::Span<const BN_ULONG> words) {
BIGNUM *alloc = NULL;
if (ret == NULL) {
alloc = BN_new();
@@ -33,7 +33,7 @@ static BIGNUM *get_params(BIGNUM *ret, const BN_ULONG *words,
ret = alloc;
}
if (!bn_set_words(ret, words, num_words)) {
if (!bn_set_words(ret, words.data(), words.size())) {
BN_free(alloc);
return NULL;
}
@@ -56,7 +56,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) {
@@ -78,7 +78,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) {
@@ -108,7 +108,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) {
@@ -146,7 +146,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) {
@@ -200,7 +200,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) {
@@ -270,7 +270,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,
@@ -22,6 +22,8 @@
#include <CCryptoBoringSSL_md5.h>
#include <CCryptoBoringSSL_nid.h>
#include <CCryptoBoringSSL_obj.h>
#include <CCryptoBoringSSL_sha.h>
#include <CCryptoBoringSSL_span.h>
#include "../asn1/internal.h"
#include "../fipsmodule/digest/internal.h"
@@ -71,9 +73,9 @@ const EVP_MD *EVP_get_digestbynid(int nid) {
return NULL;
}
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();
}
}
@@ -101,42 +103,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<const uint8_t>(*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
@@ -149,13 +150,21 @@ const EVP_MD *EVP_parse_digest_algorithm(CBS *cbs) {
CBS_len(&param) != 0 || //
CBS_len(&algorithm) != 0) {
OPENSSL_PUT_ERROR(DIGEST, DIGEST_R_DECODE_ERROR);
return NULL;
return NID_undef;
}
}
return ret;
}
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;
@@ -198,16 +207,16 @@ int EVP_marshal_digest_algorithm_no_params(CBB *cbb, const EVP_MD *md) {
}
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;
}
static void blake2b256_init(EVP_MD_CTX *ctx) {
@@ -230,6 +239,8 @@ static const EVP_MD evp_md_blake2b256 = {
const EVP_MD *EVP_blake2b256(void) { return &evp_md_blake2b256; }
static_assert(sizeof(BLAKE2B_CTX) <= EVP_MAX_MD_DATA_SIZE);
static void md4_init(EVP_MD_CTX *ctx) {
BSSL_CHECK(MD4_Init(reinterpret_cast<MD4_CTX *>(ctx->md_data)));
@@ -257,6 +268,9 @@ static const EVP_MD evp_md_md4 = {
const EVP_MD *EVP_md4(void) { 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<MD5_CTX *>(ctx->md_data)));
}
@@ -277,6 +291,9 @@ static const EVP_MD evp_md_md5 = {
const EVP_MD *EVP_md5(void) { return &evp_md_md5; }
static_assert(sizeof(MD5_CTX) <= EVP_MAX_MD_DATA_SIZE);
typedef struct {
MD5_CTX md5;
SHA_CTX sha1;
@@ -312,3 +329,5 @@ const EVP_MD evp_md_md5_sha1 = {
};
const EVP_MD *EVP_md5_sha1(void) { return &evp_md_md5_sha1; }
static_assert(sizeof(MD5_SHA1_CTX) <= EVP_MAX_MD_DATA_SIZE);
+1 -1
View File
@@ -24,7 +24,7 @@
#include <CCryptoBoringSSL_ex_data.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_rand.h>
#include <CCryptoBoringSSL_sha.h>
#include <CCryptoBoringSSL_sha2.h>
#include "../fipsmodule/bn/internal.h"
#include "../fipsmodule/dh/internal.h"
+16 -88
View File
@@ -255,113 +255,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 bssl::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 bssl::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 bssl::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 bssl::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 bssl::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 bssl::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 bssl::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 bssl::I2DFromCBB(
/*initial_capacity=*/256, outp,
[&](CBB *cbb) -> bool { return DSA_marshal_parameters(cbb, in); });
}
+102 -122
View File
@@ -17,6 +17,9 @@
#include <limits.h>
#include <string.h>
#include <algorithm>
#include <array>
#include <CCryptoBoringSSL_bn.h>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_ec_key.h>
@@ -27,6 +30,7 @@
#include "../bytestring/internal.h"
#include "../fipsmodule/ec/internal.h"
#include "../internal.h"
#include "internal.h"
static const CBS_ASN1_TAG kParametersTag =
@@ -34,17 +38,23 @@ static const CBS_ASN1_TAG kParametersTag =
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 *ec_key_parse_private_key(
CBS *cbs, const EC_GROUP *group,
bssl::Span<const EC_GROUP *const> allowed_groups) {
// If a group was supplied externally, no other groups can be parsed.
if (group != nullptr) {
allowed_groups = bssl::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) ||
@@ -66,23 +76,31 @@ EC_KEY *EC_KEY_parse_private_key(CBS *cbs, const EC_GROUP *group) {
OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR);
return nullptr;
}
const EC_GROUP *inner_group = EC_KEY_parse_parameters(&child);
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;
}
if (group == nullptr) {
group = inner_group;
} else if (EC_GROUP_cmp(group, inner_group, nullptr) != 0) {
// If a group was supplied externally, it must match.
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);
return nullptr;
}
}
// The group must have been specified either externally, or explicitly in the
// structure.
if (group == nullptr) {
OPENSSL_PUT_ERROR(EC, EC_R_MISSING_PARAMETERS);
return nullptr;
@@ -151,6 +169,10 @@ EC_KEY *EC_KEY_parse_private_key(CBS *cbs, const EC_GROUP *group) {
return ret.release();
}
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) {
@@ -296,23 +318,29 @@ static int integers_equal(const CBS *bytes, const BIGNUM *bn) {
return CBS_mem_equal(&copy, buf, CBS_len(&copy));
}
EC_GROUP *EC_KEY_parse_curve_name(CBS *cbs) {
const EC_GROUP *ec_key_parse_curve_name(
CBS *cbs, bssl::Span<const EC_GROUP *const> 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 == bssl::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_GROUP *>(ec_key_parse_curve_name(cbs, get_all_groups()));
}
int EC_KEY_marshal_curve_name(CBB *cbb, const EC_GROUP *group) {
@@ -324,9 +352,10 @@ int EC_KEY_marshal_curve_name(CBB *cbb, const EC_GROUP *group) {
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 *ec_key_parse_parameters(
CBS *cbs, bssl::Span<const EC_GROUP *const> 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
@@ -348,8 +377,7 @@ EC_GROUP *EC_KEY_parse_parameters(CBS *cbs) {
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;
}
@@ -372,13 +400,19 @@ EC_GROUP *EC_KEY_parse_parameters(CBS *cbs) {
!integers_equal(&curve.base_y, y.get())) {
break;
}
return const_cast<EC_GROUP *>(group);
return group;
}
OPENSSL_PUT_ERROR(EC, EC_R_UNKNOWN_GROUP);
return nullptr;
}
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_GROUP *>(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);
@@ -398,52 +432,20 @@ EC_KEY *d2i_ECPrivateKey(EC_KEY **out, const uint8_t **inp, long len) {
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 bssl::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 bssl::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 bssl::D2IFromCBS(out, inp, len, EC_KEY_parse_parameters);
}
int i2d_ECPKParameters(const EC_GROUP *group, uint8_t **outp) {
@@ -451,40 +453,24 @@ int i2d_ECPKParameters(const EC_GROUP *group, uint8_t **outp) {
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 bssl::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 bssl::D2IFromCBS(
out_key, inp, len, [](CBS *cbs) -> bssl::UniquePtr<EC_KEY> {
const EC_GROUP *group = EC_KEY_parse_parameters(cbs);
if (group == nullptr) {
return nullptr;
}
bssl::UniquePtr<EC_KEY> 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) {
@@ -492,14 +478,10 @@ int i2d_ECParameters(const EC_KEY *key, uint8_t **outp) {
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 bssl::I2DFromCBB(
/*initial_capacity=*/16, outp, [&](CBB *cbb) -> bool {
return EC_KEY_marshal_curve_name(cbb, key->group);
});
}
EC_KEY *o2i_ECPublicKey(EC_KEY **keyp, const uint8_t **inp, long len) {
@@ -529,27 +511,25 @@ int i2o_ECPublicKey(const EC_KEY *key, uint8_t **outp) {
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);
// 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 = bssl::I2DFromCBB(
/*initial_capacity=*/0, outp, [&](CBB *cbb) -> bool {
return EC_POINT_point2cbb(cbb, key->group, key->pub_key, key->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();
}
@@ -17,6 +17,8 @@
#include <CCryptoBoringSSL_ec.h>
#include <CCryptoBoringSSL_span.h>
#include "../fipsmodule/ec/internal.h"
#if defined(__cplusplus)
@@ -24,6 +26,31 @@ extern "C" {
#endif
// 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<const EC_GROUP *const> 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<const EC_GROUP *const> 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<const EC_GROUP *const> allowed_groups);
// Hash-to-curve.
//
// Internal |EC_JACOBIAN| versions of the corresponding public APIs.
@@ -324,28 +324,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 bssl::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 bssl::I2DFromCBB(
/*initial_capacity=*/64, outp,
[&](CBB *cbb) -> bool { return ECDSA_SIG_marshal(cbb, sig); });
}
+63 -81
View File
@@ -41,19 +41,10 @@ EVP_PKEY *EVP_PKEY_new(void) {
return NULL;
}
ret->type = EVP_PKEY_NONE;
ret->references = 1;
return ret;
}
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;
}
}
void EVP_PKEY_free(EVP_PKEY *pkey) {
if (pkey == NULL) {
return;
@@ -63,7 +54,7 @@ void EVP_PKEY_free(EVP_PKEY *pkey) {
return;
}
free_it(pkey);
evp_pkey_set0(pkey, nullptr, nullptr);
OPENSSL_free(pkey);
}
@@ -80,7 +71,7 @@ int EVP_PKEY_is_opaque(const EVP_PKEY *pkey) {
}
int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *b) {
if (a->type != b->type) {
if (EVP_PKEY_id(a) != EVP_PKEY_id(b)) {
return -1;
}
@@ -103,9 +94,13 @@ int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *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) {
if (EVP_PKEY_id(to) == 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, from->ameth, nullptr);
} else if (EVP_PKEY_id(to) != EVP_PKEY_id(from)) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DIFFERENT_KEY_TYPES);
return 0;
}
@@ -128,8 +123,9 @@ int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from) {
return from->ameth->param_copy(to, from);
}
// 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;
}
@@ -154,32 +150,17 @@ int EVP_PKEY_bits(const EVP_PKEY *pkey) {
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) {
return pkey->ameth != nullptr ? pkey->ameth->pkey_id : EVP_PKEY_NONE;
}
void evp_pkey_set_method(EVP_PKEY *pkey, const EVP_PKEY_ASN1_METHOD *method) {
free_it(pkey);
void evp_pkey_set0(EVP_PKEY *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) {
@@ -210,84 +191,85 @@ 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);
// Some callers rely on |pkey| getting cleared even if |type| is
// unsupported, usually setting |type| to |EVP_PKEY_NONE|.
evp_pkey_set0(pkey, 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_ASN1_METHOD *ameth;
if (type == EVP_PKEY_X25519) {
ameth = &x25519_asn1_meth;
} 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);
evp_pkey_set0(pkey, ameth, 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;
}
bssl::UniquePtr<EVP_PKEY> ret(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_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;
}
bssl::UniquePtr<EVP_PKEY> ret(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;
return EVP_PKEY_from_raw_private_key(EVP_pkey_x25519(), in, len);
case EVP_PKEY_ED25519:
method = &ed25519_asn1_meth;
break;
return EVP_PKEY_from_raw_private_key(EVP_pkey_ed25519(), in, len);
default:
OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM);
return nullptr;
}
bssl::UniquePtr<EVP_PKEY> 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();
}
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;
return EVP_PKEY_from_raw_public_key(EVP_pkey_x25519(), in, len);
case EVP_PKEY_ED25519:
method = &ed25519_asn1_meth;
break;
return EVP_PKEY_from_raw_public_key(EVP_pkey_ed25519(), in, len);
default:
OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM);
return nullptr;
}
bssl::UniquePtr<EVP_PKEY> 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();
}
int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, uint8_t *out,
@@ -311,7 +293,7 @@ int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, uint8_t *out,
}
int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b) {
if (a->type != b->type) {
if (EVP_PKEY_id(a) != EVP_PKEY_id(b)) {
return -1;
}
if (a->ameth && a->ameth->param_cmp) {
+179 -219
View File
@@ -16,84 +16,68 @@
#include <string.h>
#include <array>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_dsa.h>
#include <CCryptoBoringSSL_ec_key.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_rsa.h>
#include <CCryptoBoringSSL_span.h>
#include "internal.h"
#include "../bytestring/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,
};
static const EVP_PKEY_ASN1_METHOD *parse_key_type(CBS *cbs) {
CBS oid;
if (!CBS_get_asn1(cbs, &oid, CBS_ASN1_OBJECT)) {
return NULL;
}
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;
}
}
return NULL;
}
EVP_PKEY *EVP_parse_public_key(CBS *cbs) {
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 spki, algorithm, key;
uint8_t padding;
if (!CBS_get_asn1(cbs, &spki, CBS_ASN1_SEQUENCE) ||
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) {
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) {
CBS_len(&spki) != 0 || //
CBS_len(&cbs) != 0) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR);
return nullptr;
}
// Set up an |EVP_PKEY| of the appropriate type.
bssl::UniquePtr<EVP_PKEY> 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;
for (const EVP_PKEY_ALG *alg : bssl::Span(algs, num_algs)) {
if (alg->method->pub_decode == nullptr ||
bssl::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(), &params, &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 ret.release();
OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM);
return nullptr;
}
int EVP_marshal_public_key(CBB *cbb, const EVP_PKEY *key) {
@@ -105,43 +89,47 @@ int EVP_marshal_public_key(CBB *cbb, const EVP_PKEY *key) {
return key->ameth->pub_encode(cbb, key);
}
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<EVP_PKEY> ret(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 : bssl::Span(algs, num_algs)) {
if (alg->method->priv_decode == nullptr ||
bssl::Span(alg->method->oid, alg->method->oid_len) != oid) {
continue;
}
CBS params = algorithm, key_copy = key;
switch (alg->method->priv_decode(alg, ret.get(), &params, &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) {
@@ -153,6 +141,30 @@ int EVP_marshal_private_key(CBB *cbb, const EVP_PKEY *key) {
return key->ameth->priv_encode(cbb, key);
}
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 = bssl::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 = bssl::GetDefaultEVPAlgorithms();
return EVP_PKEY_from_private_key_info(CBS_data(&elem), CBS_len(&elem),
algs.data(), algs.size());
}
static bssl::UniquePtr<EVP_PKEY> old_priv_decode(CBS *cbs, int type) {
bssl::UniquePtr<EVP_PKEY> ret(EVP_PKEY_new());
if (ret == nullptr) {
@@ -192,35 +204,26 @@ static bssl::UniquePtr<EVP_PKEY> 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<EVP_PKEY> 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));
if (ret == nullptr) {
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 bssl::D2IFromCBS(
out, inp, len, [&](CBS *cbs) -> bssl::UniquePtr<EVP_PKEY> {
// Parse with the legacy format.
CBS copy = *cbs;
bssl::UniquePtr<EVP_PKEY> ret = old_priv_decode(cbs, type);
if (ret == 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;
}
}
return ret;
});
}
// num_elements parses one SEQUENCE from |in| and returns the number of elements
@@ -279,7 +282,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:
@@ -294,93 +297,70 @@ 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<EVP_PKEY> ret(EVP_PKEY_new());
if (ret == nullptr) {
return nullptr;
}
return bssl::D2IFromCBS(
out, inp, len, [&](CBS *cbs) -> bssl::UniquePtr<EVP_PKEY> {
bssl::UniquePtr<EVP_PKEY> ret(EVP_PKEY_new());
if (ret == nullptr) {
return nullptr;
}
switch (type) {
case EVP_PKEY_RSA: {
bssl::UniquePtr<RSA> rsa(RSA_parse_public_key(cbs));
if (rsa == nullptr) {
return nullptr;
}
EVP_PKEY_assign_RSA(ret.get(), rsa.release());
return ret;
}
CBS cbs;
CBS_init(&cbs, *inp, len < 0 ? 0 : (size_t)len);
switch (type) {
case EVP_PKEY_RSA: {
bssl::UniquePtr<RSA> 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 nullptr;
}
*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<EVP_PKEY> 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 bssl::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 bssl::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<EVP_PKEY> parse_spki(
CBS *cbs, bssl::Span<const EVP_PKEY_ALG *const> 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 bssl::UniquePtr<EVP_PKEY>(EVP_PKEY_from_subject_public_key_info(
CBS_data(&spki), CBS_len(&spki), algs.data(), algs.size()));
}
static bssl::UniquePtr<EVP_PKEY> parse_spki(CBS *cbs, const EVP_PKEY_ALG *alg) {
return parse_spki(cbs, bssl::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<EVP_PKEY> pkey(EVP_parse_public_key(&cbs));
if (pkey == nullptr) {
return nullptr;
}
bssl::UniquePtr<RSA> 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 bssl::D2IFromCBS(out, inp, len, [](CBS *cbs) -> bssl::UniquePtr<RSA> {
bssl::UniquePtr<EVP_PKEY> pkey = parse_spki(cbs, EVP_pkey_rsa());
if (pkey == nullptr) {
return nullptr;
}
return bssl::UniquePtr<RSA>(EVP_PKEY_get1_RSA(pkey.get()));
});
}
int i2d_RSA_PUBKEY(const RSA *rsa, uint8_t **outp) {
@@ -398,25 +378,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<EVP_PKEY> pkey(EVP_parse_public_key(&cbs));
if (pkey == nullptr) {
return nullptr;
}
bssl::UniquePtr<DSA> 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 bssl::D2IFromCBS(out, inp, len, [](CBS *cbs) -> bssl::UniquePtr<DSA> {
bssl::UniquePtr<EVP_PKEY> pkey = parse_spki(cbs, EVP_pkey_dsa());
if (pkey == nullptr) {
return nullptr;
}
return bssl::UniquePtr<DSA>(EVP_PKEY_get1_DSA(pkey.get()));
});
}
int i2d_DSA_PUBKEY(const DSA *dsa, uint8_t **outp) {
@@ -434,25 +402,17 @@ 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 nullptr;
}
CBS cbs;
CBS_init(&cbs, *inp, (size_t)len);
bssl::UniquePtr<EVP_PKEY> pkey(EVP_parse_public_key(&cbs));
if (pkey == nullptr) {
return nullptr;
}
bssl::UniquePtr<EC_KEY> ec_key(EVP_PKEY_get1_EC_KEY(pkey.get()));
if (ec_key == nullptr) {
return nullptr;
}
if (out != nullptr) {
EC_KEY_free(*out);
*out = ec_key.get();
}
*inp = CBS_data(&cbs);
return ec_key.release();
return bssl::D2IFromCBS(
out, inp, len, [](CBS *cbs) -> bssl::UniquePtr<EC_KEY> {
const EVP_PKEY_ALG *const algs[] = {
EVP_pkey_ec_p224(), EVP_pkey_ec_p256(), EVP_pkey_ec_p384(),
EVP_pkey_ec_p521()};
bssl::UniquePtr<EVP_PKEY> pkey = parse_spki(cbs, algs);
if (pkey == nullptr) {
return nullptr;
}
return bssl::UniquePtr<EC_KEY>(EVP_PKEY_get1_EC_KEY(pkey.get()));
});
}
int i2d_EC_PUBKEY(const EC_KEY *ec_key, uint8_t **outp) {
+16 -15
View File
@@ -25,29 +25,31 @@
#include "internal.h"
static const EVP_PKEY_METHOD *const evp_methods[] = {
// |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.
static const EVP_PKEY_CTX_METHOD *const evp_methods[] = {
&rsa_pkey_meth, &ec_pkey_meth, &ed25519_pkey_meth,
&x25519_pkey_meth, &hkdf_pkey_meth,
};
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];
static const EVP_PKEY_CTX_METHOD *evp_pkey_meth_find(int type) {
for (auto method : evp_methods) {
if (method->pkey_id == type) {
return method;
}
}
return NULL;
return nullptr;
}
static EVP_PKEY_CTX *evp_pkey_ctx_new(EVP_PKEY *pkey, ENGINE *e,
const EVP_PKEY_METHOD *pmeth) {
static EVP_PKEY_CTX *evp_pkey_ctx_new(EVP_PKEY *pkey,
const EVP_PKEY_CTX_METHOD *pmeth) {
bssl::UniquePtr<EVP_PKEY_CTX> ret = bssl::MakeUnique<EVP_PKEY_CTX>();
if (!ret) {
return nullptr;
}
ret->engine = e;
ret->pmeth = pmeth;
ret->operation = EVP_PKEY_OP_UNDEFINED;
ret->pkey = bssl::UpRef(pkey);
@@ -66,25 +68,25 @@ EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e) {
return NULL;
}
const EVP_PKEY_METHOD *pkey_method = pkey->ameth->pkey_method;
const EVP_PKEY_CTX_METHOD *pkey_method = pkey->ameth->pkey_method;
if (pkey_method == NULL) {
OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM);
ERR_add_error_dataf("algorithm %d", pkey->ameth->pkey_id);
return NULL;
}
return evp_pkey_ctx_new(pkey, e, pkey_method);
return evp_pkey_ctx_new(pkey, pkey_method);
}
EVP_PKEY_CTX *EVP_PKEY_CTX_new_id(int id, ENGINE *e) {
const EVP_PKEY_METHOD *pkey_method = evp_pkey_meth_find(id);
const EVP_PKEY_CTX_METHOD *pkey_method = evp_pkey_meth_find(id);
if (pkey_method == NULL) {
OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_ALGORITHM);
ERR_add_error_dataf("algorithm %d", id);
return NULL;
}
return evp_pkey_ctx_new(NULL, e, pkey_method);
return evp_pkey_ctx_new(NULL, pkey_method);
}
evp_pkey_ctx_st::~evp_pkey_ctx_st() {
@@ -106,7 +108,6 @@ EVP_PKEY_CTX *EVP_PKEY_CTX_dup(EVP_PKEY_CTX *ctx) {
}
ret->pmeth = ctx->pmeth;
ret->engine = ctx->engine;
ret->operation = ctx->operation;
ret->pkey = bssl::UpRef(ctx->pkey);
ret->peerkey = bssl::UpRef(ctx->peerkey);
@@ -297,7 +298,7 @@ int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer) {
return 0;
}
if (ctx->pkey->type != peer->type) {
if (EVP_PKEY_id(ctx->pkey.get()) != EVP_PKEY_id(peer)) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DIFFERENT_KEY_TYPES);
return 0;
}
+89 -38
View File
@@ -15,9 +15,11 @@
#ifndef OPENSSL_HEADER_CRYPTO_EVP_INTERNAL_H
#define OPENSSL_HEADER_CRYPTO_EVP_INTERNAL_H
#include <CCryptoBoringSSL_base.h>
#include <CCryptoBoringSSL_evp.h>
#include <CCryptoBoringSSL_rsa.h>
#include <array>
#include <CCryptoBoringSSL_span.h>
#include "../internal.h"
@@ -27,23 +29,46 @@ extern "C" {
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;
struct evp_pkey_alg_st {
// method implements operations for this |EVP_PKEY_ALG|.
const EVP_PKEY_ASN1_METHOD *method;
// ec_group returns the |EC_GROUP| for this algorithm, if |method| is for
// |EVP_PKEY_EC|.
const EC_GROUP *(*ec_group)();
};
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);
// 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, EVP_PKEY *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.
@@ -52,10 +77,16 @@ struct evp_pkey_asn1_method_st {
int (*pub_cmp)(const EVP_PKEY *a, const EVP_PKEY *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);
// 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, EVP_PKEY *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.
@@ -94,15 +125,11 @@ struct evp_pkey_asn1_method_st {
struct evp_pkey_st {
CRYPTO_refcount_t references;
// 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 |type|.
// pkey contains a pointer to a structure dependent on |ameth|.
void *pkey;
// ameth contains a pointer to a method table that contains many ASN.1
// methods for the key type.
// ameth contains a pointer to a method table that determines the key type, or
// nullptr if the key is empty.
const EVP_PKEY_ASN1_METHOD *ameth;
} /* EVP_PKEY */;
@@ -167,7 +194,7 @@ 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)
@@ -179,20 +206,21 @@ struct evp_pkey_ctx_st {
~evp_pkey_ctx_st();
// Method associated with this operation
const EVP_PKEY_METHOD *pmeth = nullptr;
// Engine that implements this method or nullptr if builtin
ENGINE *engine = nullptr;
const EVP_PKEY_CTX_METHOD *pmeth = nullptr;
// Key: may be nullptr
bssl::UniquePtr<EVP_PKEY> pkey;
// Peer key for key agreement, may be nullptr
bssl::UniquePtr<EVP_PKEY> peerkey;
// operation contains one of the |EVP_PKEY_OP_*| values.
int operation = EVP_PKEY_OP_UNDEFINED;
// Algorithm specific data
// Algorithm specific data.
// TODO(davidben): 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;
} /* EVP_PKEY_CTX */;
struct evp_pkey_method_st {
struct evp_pkey_ctx_method_st {
int pkey_id;
int (*init)(EVP_PKEY_CTX *ctx);
@@ -227,7 +255,7 @@ struct evp_pkey_method_st {
int (*paramgen)(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey);
int (*ctrl)(EVP_PKEY_CTX *ctx, int type, int p1, void *p2);
} /* EVP_PKEY_METHOD */;
} /* EVP_PKEY_CTX_METHOD */;
typedef struct {
// key is the concatenation of the private seed and public key. It is stored
@@ -249,24 +277,47 @@ typedef struct {
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 rsa_pss_sha256_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;
extern const EVP_PKEY_CTX_METHOD rsa_pkey_meth;
extern const EVP_PKEY_CTX_METHOD rsa_pss_sha256_pkey_meth;
extern const EVP_PKEY_CTX_METHOD ec_pkey_meth;
extern const EVP_PKEY_CTX_METHOD ed25519_pkey_meth;
extern const EVP_PKEY_CTX_METHOD x25519_pkey_meth;
extern const EVP_PKEY_CTX_METHOD hkdf_pkey_meth;
extern const EVP_PKEY_CTX_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);
// 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(EVP_PKEY *pkey, const EVP_PKEY_ASN1_METHOD *method,
void *pkey_data);
#if defined(__cplusplus)
} // extern C
#endif
BSSL_NAMESPACE_BEGIN
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(),
// 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
+1 -1
View File
@@ -129,7 +129,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,
@@ -120,13 +120,15 @@ int EVP_PKEY_set1_DH(EVP_PKEY *pkey, DH *key) {
}
int EVP_PKEY_assign_DH(EVP_PKEY *pkey, DH *key) {
evp_pkey_set_method(pkey, &dh_asn1_meth);
pkey->pkey = key;
return key != NULL;
if (key == nullptr) {
return 0;
}
evp_pkey_set0(pkey, &dh_asn1_meth, key);
return 1;
}
DH *EVP_PKEY_get0_DH(const EVP_PKEY *pkey) {
if (pkey->type != EVP_PKEY_DH) {
if (EVP_PKEY_id(pkey) != EVP_PKEY_DH) {
OPENSSL_PUT_ERROR(EVP, EVP_R_EXPECTING_A_DH_KEY);
return NULL;
}
@@ -24,36 +24,32 @@
#include "internal.h"
static int dsa_pub_decode(EVP_PKEY *out, CBS *params, CBS *key) {
static evp_decode_result_t dsa_pub_decode(const EVP_PKEY_ALG *alg,
EVP_PKEY *out, CBS *params,
CBS *key) {
// See RFC 3279, section 2.3.2.
// Parameters may or may not be present.
bssl::UniquePtr<DSA> 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;
}
// 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.
bssl::UniquePtr<DSA> dsa(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 = BN_new();
if (dsa->pub_key == nullptr) {
return 0;
return evp_decode_error;
}
if (!BN_parse_asn1_unsigned(key, dsa->pub_key) || CBS_len(key) != 0) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR);
return 0;
return evp_decode_error;
}
EVP_PKEY_assign_DSA(out, dsa.release());
return 1;
return evp_decode_ok;
}
static int dsa_pub_encode(CBB *out, const EVP_PKEY *key) {
@@ -78,23 +74,25 @@ static int dsa_pub_encode(CBB *out, const EVP_PKEY *key) {
return 1;
}
static int dsa_priv_decode(EVP_PKEY *out, CBS *params, CBS *key) {
static evp_decode_result_t dsa_priv_decode(const EVP_PKEY_ALG *alg,
EVP_PKEY *out, CBS *params,
CBS *key) {
// See PKCS#11, v2.40, section 2.5.
// Decode parameters.
bssl::UniquePtr<DSA> dsa(DSA_parse_parameters(params));
if (dsa == nullptr || CBS_len(params) != 0) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR);
return 0;
return evp_decode_error;
}
dsa->priv_key = BN_new();
if (dsa->priv_key == nullptr) {
return 0;
return evp_decode_error;
}
if (!BN_parse_asn1_unsigned(key, dsa->priv_key) || CBS_len(key) != 0) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR);
return 0;
return evp_decode_error;
}
// To avoid DoS attacks when importing private keys, check bounds on |dsa|.
@@ -102,7 +100,7 @@ static int dsa_priv_decode(EVP_PKEY *out, CBS *params, CBS *key) {
// width.
if (!dsa_check_key(dsa.get())) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR);
return 0;
return evp_decode_error;
}
// Calculate the public key.
@@ -111,11 +109,11 @@ static int dsa_priv_decode(EVP_PKEY *out, CBS *params, CBS *key) {
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;
return evp_decode_error;
}
EVP_PKEY_assign_DSA(out, dsa.release());
return 1;
return evp_decode_ok;
}
static int dsa_priv_encode(CBB *out, const EVP_PKEY *key) {
@@ -236,6 +234,14 @@ const EVP_PKEY_ASN1_METHOD dsa_asn1_meth = {
int_dsa_free,
};
const EVP_PKEY_ALG *EVP_pkey_dsa(void) {
static const EVP_PKEY_ALG kAlg = {
/*method=*/&dsa_asn1_meth,
/*ec_group=*/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);
@@ -257,13 +263,15 @@ int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, DSA *key) {
}
int EVP_PKEY_assign_DSA(EVP_PKEY *pkey, DSA *key) {
evp_pkey_set_method(pkey, &dsa_asn1_meth);
pkey->pkey = key;
return key != nullptr;
if (key == nullptr) {
return 0;
}
evp_pkey_set0(pkey, &dsa_asn1_meth, key);
return 1;
}
DSA *EVP_PKEY_get0_DSA(const EVP_PKEY *pkey) {
if (pkey->type != EVP_PKEY_DSA) {
if (EVP_PKEY_id(pkey) != EVP_PKEY_DSA) {
OPENSSL_PUT_ERROR(EVP, EVP_R_EXPECTING_A_DSA_KEY);
return nullptr;
}
+9 -8
View File
@@ -148,12 +148,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<const EC_GROUP *>(p2);
return 1;
}
@@ -197,7 +193,7 @@ 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,
@@ -216,8 +212,13 @@ const EVP_PKEY_METHOD ec_pkey_meth = {
};
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<EC_GROUP *>(group));
}
int EVP_PKEY_CTX_set_ec_param_enc(EVP_PKEY_CTX *ctx, int encoding) {
@@ -20,7 +20,10 @@
#include <CCryptoBoringSSL_ec_key.h>
#include <CCryptoBoringSSL_ecdsa.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_nid.h>
#include <CCryptoBoringSSL_span.h>
#include "../ec/internal.h"
#include "internal.h"
@@ -48,25 +51,35 @@ static int eckey_pub_encode(CBB *out, const EVP_PKEY *key) {
return 1;
}
static int eckey_pub_decode(EVP_PKEY *out, CBS *params, CBS *key) {
static evp_decode_result_t eckey_pub_decode(const EVP_PKEY_ALG *alg,
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) {
// Check that |params| matches |alg|. Only the namedCurve form is allowed.
const EC_GROUP *group = alg->ec_group();
if (ec_key_parse_curve_name(params, bssl::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 0;
return evp_decode_error;
}
if (CBS_len(params) != 0) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR);
return evp_decode_error;
}
bssl::UniquePtr<EC_KEY> 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;
return evp_decode_error;
}
EVP_PKEY_assign_EC_KEY(out, eckey.release());
return 1;
return evp_decode_ok;
}
static int eckey_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) {
@@ -85,23 +98,32 @@ static int eckey_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) {
}
}
static int eckey_priv_decode(EVP_PKEY *out, CBS *params, CBS *key) {
static evp_decode_result_t eckey_priv_decode(const EVP_PKEY_ALG *alg,
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) {
const EC_GROUP *group = alg->ec_group();
if (ec_key_parse_parameters(params, bssl::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 0;
return evp_decode_error;
}
if (CBS_len(params) != 0) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR);
return evp_decode_error;
}
EC_KEY *ec_key = EC_KEY_parse_private_key(key, group);
if (ec_key == NULL || CBS_len(key) != 0) {
bssl::UniquePtr<EC_KEY> 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);
EC_KEY_free(ec_key);
return 0;
return evp_decode_error;
}
EVP_PKEY_assign_EC_KEY(out, ec_key);
return 1;
EVP_PKEY_assign_EC_KEY(out, ec_key.release());
return evp_decode_ok;
}
static int eckey_priv_encode(CBB *out, const EVP_PKEY *key) {
@@ -255,6 +277,39 @@ const EVP_PKEY_ASN1_METHOD ec_asn1_meth = {
int_ec_free,
};
const EVP_PKEY_ALG *EVP_pkey_ec_p224(void) {
static const EVP_PKEY_ALG kAlg = {
/*method=*/&ec_asn1_meth,
/*ec_group=*/&EC_group_p224,
};
return &kAlg;
}
const EVP_PKEY_ALG *EVP_pkey_ec_p256(void) {
static const EVP_PKEY_ALG kAlg = {
/*method=*/&ec_asn1_meth,
/*ec_group=*/&EC_group_p256,
};
return &kAlg;
}
const EVP_PKEY_ALG *EVP_pkey_ec_p384(void) {
static const EVP_PKEY_ALG kAlg = {
/*method=*/&ec_asn1_meth,
/*ec_group=*/&EC_group_p384,
};
return &kAlg;
}
const EVP_PKEY_ALG *EVP_pkey_ec_p521(void) {
static const EVP_PKEY_ALG kAlg = {
/*method=*/&ec_asn1_meth,
/*ec_group=*/&EC_group_p521,
};
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);
@@ -264,14 +319,16 @@ int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, EC_KEY *key) {
}
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;
if (key == nullptr) {
return 0;
}
evp_pkey_set0(pkey, &ec_asn1_meth, key);
return 1;
}
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);
if (EVP_PKEY_id(pkey) != EVP_PKEY_EC) {
OPENSSL_PUT_ERROR(EVP, EVP_R_EXPECTING_A_EC_KEY);
return NULL;
}
return reinterpret_cast<EC_KEY *>(pkey->pkey);
@@ -284,3 +341,23 @@ EC_KEY *EVP_PKEY_get1_EC_KEY(const EVP_PKEY *pkey) {
}
return ec_key;
}
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);
}
@@ -31,14 +31,11 @@ static int pkey_ed25519_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) {
return 0;
}
evp_pkey_set_method(pkey, &ed25519_asn1_meth);
uint8_t pubkey_unused[32];
ED25519_keypair(pubkey_unused, key->key);
key->has_private = 1;
OPENSSL_free(pkey->pkey);
pkey->pkey = key;
evp_pkey_set0(pkey, &ed25519_asn1_meth, key);
return 1;
}
@@ -84,7 +81,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,
@@ -45,9 +45,7 @@ static int ed25519_set_priv_raw(EVP_PKEY *pkey, const uint8_t *in, size_t len) {
uint8_t pubkey_unused[32];
ED25519_keypair_from_seed(pubkey_unused, key->key, in);
key->has_private = 1;
ed25519_free(pkey);
pkey->pkey = key;
evp_pkey_set0(pkey, &ed25519_asn1_meth, key);
return 1;
}
@@ -65,9 +63,7 @@ static int ed25519_set_pub_raw(EVP_PKEY *pkey, const uint8_t *in, size_t len) {
OPENSSL_memcpy(key->key + ED25519_PUBLIC_KEY_OFFSET, in, 32);
key->has_private = 0;
ed25519_free(pkey);
pkey->pkey = key;
evp_pkey_set0(pkey, &ed25519_asn1_meth, key);
return 1;
}
@@ -113,16 +109,20 @@ static int ed25519_get_pub_raw(const EVP_PKEY *pkey, uint8_t *out,
return 1;
}
static int ed25519_pub_decode(EVP_PKEY *out, CBS *params, CBS *key) {
static evp_decode_result_t ed25519_pub_decode(const EVP_PKEY_ALG *alg,
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 evp_decode_error;
}
return ed25519_set_pub_raw(out, CBS_data(key), CBS_len(key));
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 EVP_PKEY *pkey) {
@@ -153,7 +153,9 @@ static int ed25519_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) {
b_key->key + ED25519_PUBLIC_KEY_OFFSET, 32) == 0;
}
static int ed25519_priv_decode(EVP_PKEY *out, CBS *params, CBS *key) {
static evp_decode_result_t ed25519_priv_decode(const EVP_PKEY_ALG *alg,
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
@@ -162,10 +164,12 @@ static int ed25519_priv_decode(EVP_PKEY *out, CBS *params, CBS *key) {
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 evp_decode_error;
}
return ed25519_set_priv_raw(out, CBS_data(&inner), CBS_len(&inner));
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 EVP_PKEY *pkey) {
@@ -223,3 +227,11 @@ const EVP_PKEY_ASN1_METHOD ed25519_asn1_meth = {
/*param_cmp=*/NULL,
ed25519_free,
};
const EVP_PKEY_ALG *EVP_pkey_ed25519(void) {
static const EVP_PKEY_ALG kAlg = {
/*method=*/&ed25519_asn1_meth,
/*ec_group=*/nullptr,
};
return &kAlg;
}
@@ -183,7 +183,7 @@ static int pkey_hkdf_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) {
}
}
const EVP_PKEY_METHOD hkdf_pkey_meth = {
const EVP_PKEY_CTX_METHOD hkdf_pkey_meth = {
/*pkey_id=*/EVP_PKEY_HKDF,
pkey_hkdf_init,
pkey_hkdf_copy,
+186 -137
View File
@@ -24,50 +24,59 @@
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_nid.h>
#include <CCryptoBoringSSL_rsa.h>
#include <CCryptoBoringSSL_span.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;
namespace {
typedef struct {
uint8_t *data;
size_t len;
} RSA_OAEP_LABEL_PARAMS;
struct RSA_PKEY_CTX {
// Key gen parameters
int nbits = 2048;
bssl::UniquePtr<BIGNUM> 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;
bssl::Array<uint8_t> oaep_label;
};
static bool is_pss_only(const EVP_PKEY_CTX *ctx) {
return ctx->pmeth->pkey_id == EVP_PKEY_RSA_PSS;
}
static int pkey_rsa_init(EVP_PKEY_CTX *ctx) {
RSA_PKEY_CTX *rctx =
reinterpret_cast<RSA_PKEY_CTX *>(OPENSSL_zalloc(sizeof(RSA_PKEY_CTX)));
RSA_PKEY_CTX *rctx = bssl::New<RSA_PKEY_CTX>();
if (!rctx) {
return 0;
}
rctx->nbits = 2048;
rctx->pad_mode = RSA_PKCS1_PADDING;
rctx->saltlen = -2;
if (is_pss_only(ctx)) {
rctx->pad_mode = RSA_PKCS1_PSS_PADDING;
// Pick up PSS parameters from the key. For now, we only support the SHA-256
// parameter set, so every key is necessarily SHA-256. If we ever support
// other parameters, we will need more state in |EVP_PKEY| and to translate
// that state into defaults here.
if (ctx->pkey != nullptr) {
rctx->md = rctx->mgf1md = EVP_sha256();
rctx->saltlen = EVP_MD_size(rctx->md);
rctx->restrict_pss_params = true;
}
}
ctx->data = rctx;
return 1;
}
@@ -80,7 +89,7 @@ static int pkey_rsa_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) {
dctx = reinterpret_cast<RSA_PKEY_CTX *>(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;
}
@@ -90,42 +99,16 @@ 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<uint8_t *>(
OPENSSL_memdup(sctx->oaep_label, sctx->oaep_labellen));
if (!dctx->oaep_label) {
return 0;
}
dctx->oaep_labellen = sctx->oaep_labellen;
dctx->restrict_pss_params = sctx->restrict_pss_params;
if (!dctx->oaep_label.CopyFrom(sctx->oaep_label)) {
return 0;
}
return 1;
}
static void pkey_rsa_cleanup(EVP_PKEY_CTX *ctx) {
RSA_PKEY_CTX *rctx = reinterpret_cast<RSA_PKEY_CTX *>(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<uint8_t *>(
OPENSSL_malloc(EVP_PKEY_size(pk->pkey.get())));
if (!ctx->tbuf) {
return 0;
}
return 1;
bssl::Delete(reinterpret_cast<RSA_PKEY_CTX *>(ctx->data));
}
static int pkey_rsa_sign(EVP_PKEY_CTX *ctx, uint8_t *sig, size_t *siglen,
@@ -187,12 +170,13 @@ 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.get());
if (!setup_tbuf(rctx, ctx) ||
!RSA_verify_raw(rsa, &rslen, rctx->tbuf, key_len, sig, siglen,
bssl::Array<uint8_t> 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;
}
@@ -232,33 +216,28 @@ 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;
}
bssl::UniquePtr<uint8_t> free_asn1_prefix(asn1_prefix_allocated ? asn1_prefix
: nullptr);
bssl::Array<uint8_t> 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);
OPENSSL_memcpy(out, tbuf.data() + rslen - hash_len, hash_len);
}
*out_len = hash_len;
@@ -282,11 +261,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,
bssl::Array<uint8_t> 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;
}
@@ -313,13 +293,15 @@ static int pkey_rsa_decrypt(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *outlen,
}
if (rctx->pad_mode == RSA_PKCS1_OAEP_PADDING) {
bssl::Array<uint8_t> 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;
@@ -357,6 +339,11 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) {
RSA_PKEY_CTX *rctx = reinterpret_cast<RSA_PKEY_CTX *>(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))) ||
@@ -365,8 +352,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 == NULL) {
rctx->md = EVP_sha1();
}
rctx->pad_mode = p1;
@@ -385,7 +371,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<size_t>(p1) < EVP_MD_size(rctx->md)) {
OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PSS_SALTLEN);
return 0;
}
rctx->saltlen = p1;
@@ -404,8 +404,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<BIGNUM *>(p2);
rctx->pub_exp.reset(reinterpret_cast<BIGNUM *>(p2));
return 1;
case EVP_PKEY_CTRL_RSA_OAEP_MD:
@@ -421,12 +420,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<EVP_MD *>(p2), rctx->pad_mode)) {
case EVP_PKEY_CTRL_MD: {
const EVP_MD *md = reinterpret_cast<EVP_MD *>(p2);
if (!check_padding_md(md, rctx->pad_mode)) {
return 0;
}
rctx->md = reinterpret_cast<EVP_MD *>(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;
@@ -446,7 +452,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<EVP_MD *>(p2);
const EVP_MD *md = reinterpret_cast<EVP_MD *>(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;
@@ -455,11 +467,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<RSA_OAEP_LABEL_PARAMS *>(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<bssl::Span<uint8_t> *>(p2);
rctx->oaep_label.Reset(label->data(), label->size());
return 1;
}
@@ -468,7 +479,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<CBS *>(p2) = CBS(rctx->oaep_label);
return 1;
default:
@@ -478,90 +489,130 @@ 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;
RSA_PKEY_CTX *rctx = reinterpret_cast<RSA_PKEY_CTX *>(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();
bssl::UniquePtr<RSA> 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 = {
} // namespace
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,
pkey_rsa_ctrl,
};
const EVP_PKEY_CTX_METHOD rsa_pss_sha256_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,
pkey_rsa_ctrl,
};
static int rsa_or_rsa_pss_ctrl(EVP_PKEY_CTX *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(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(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(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(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(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(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) {
@@ -575,22 +626,20 @@ int EVP_PKEY_CTX_get_rsa_oaep_md(EVP_PKEY_CTX *ctx, const EVP_MD **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(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(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};
bssl::Span span(label, label_len);
return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT,
EVP_PKEY_CTRL_RSA_OAEP_LABEL, 0, &params);
EVP_PKEY_CTRL_RSA_OAEP_LABEL, 0, &span);
}
int EVP_PKEY_CTX_get0_rsa_oaep_label(EVP_PKEY_CTX *ctx,
+186 -28
View File
@@ -20,8 +20,10 @@
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_rsa.h>
#include <CCryptoBoringSSL_span.h>
#include "../fipsmodule/rsa/internal.h"
#include "../rsa/internal.h"
#include "internal.h"
@@ -45,7 +47,9 @@ static int rsa_pub_encode(CBB *out, const EVP_PKEY *key) {
return 1;
}
static int rsa_pub_decode(EVP_PKEY *out, CBS *params, CBS *key) {
static evp_decode_result_t rsa_pub_decode(const EVP_PKEY_ALG *alg,
EVP_PKEY *out, CBS *params,
CBS *key) {
// See RFC 3279, section 2.3.1.
// The parameters must be NULL.
@@ -53,21 +57,25 @@ static int rsa_pub_decode(EVP_PKEY *out, CBS *params, CBS *key) {
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;
return evp_decode_error;
}
RSA *rsa = RSA_parse_public_key(key);
if (rsa == NULL || CBS_len(key) != 0) {
bssl::UniquePtr<RSA> rsa(
RSA_public_key_from_bytes(CBS_data(key), CBS_len(key)));
if (rsa == nullptr) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR);
RSA_free(rsa);
return 0;
return evp_decode_error;
}
EVP_PKEY_assign_RSA(out, rsa);
return 1;
EVP_PKEY_assign_RSA(out, rsa.release());
return evp_decode_ok;
}
static int rsa_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *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<const RSA *>(a->pkey);
const RSA *b_rsa = reinterpret_cast<const RSA *>(b->pkey);
return BN_cmp(RSA_get0_n(b_rsa), RSA_get0_n(a_rsa)) == 0 &&
@@ -93,26 +101,122 @@ static int rsa_priv_encode(CBB *out, const EVP_PKEY *key) {
return 1;
}
static int rsa_priv_decode(EVP_PKEY *out, CBS *params, CBS *key) {
// Per RFC 3447, A.1, the parameters have type NULL.
static evp_decode_result_t rsa_priv_decode(const EVP_PKEY_ALG *alg,
EVP_PKEY *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 0;
return evp_decode_error;
}
RSA *rsa = RSA_parse_private_key(key);
if (rsa == NULL || CBS_len(key) != 0) {
bssl::UniquePtr<RSA> rsa(
RSA_private_key_from_bytes(CBS_data(key), CBS_len(key)));
if (rsa == nullptr) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR);
RSA_free(rsa);
return evp_decode_error;
}
EVP_PKEY_assign_RSA(out, rsa.release());
return evp_decode_ok;
}
static evp_decode_result_t rsa_decode_pss_params_sha256(CBS *params) {
// For now, we only support the SHA-256 parameter set. If we want to support
// more, we'll need to record a little more state in the |EVP_PKEY|.
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 == rsa_pss_sha256 ? evp_decode_ok : evp_decode_unsupported;
}
static int rsa_pub_encode_pss_sha256(CBB *out, const EVP_PKEY *key) {
const RSA *rsa = reinterpret_cast<const RSA *>(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_sha256_asn1_meth.oid,
rsa_pss_sha256_asn1_meth.oid_len) ||
!rsa_marshal_pss_params(&algorithm, rsa_pss_sha256) ||
!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;
}
EVP_PKEY_assign_RSA(out, rsa);
return 1;
}
static evp_decode_result_t rsa_pub_decode_pss_sha256(const EVP_PKEY_ALG *alg,
EVP_PKEY *out, CBS *params,
CBS *key) {
evp_decode_result_t ret = rsa_decode_pss_params_sha256(params);
if (ret != evp_decode_ok) {
return ret;
}
bssl::UniquePtr<RSA> 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(out, &rsa_pss_sha256_asn1_meth, rsa.release());
return evp_decode_ok;
}
static int rsa_priv_encode_pss_sha256(CBB *out, const EVP_PKEY *key) {
const RSA *rsa = reinterpret_cast<const RSA *>(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_sha256_asn1_meth.oid,
rsa_pss_sha256_asn1_meth.oid_len) ||
!rsa_marshal_pss_params(&algorithm, rsa_pss_sha256) ||
!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 evp_decode_result_t rsa_priv_decode_pss_sha256(const EVP_PKEY_ALG *alg,
EVP_PKEY *out,
CBS *params, CBS *key) {
evp_decode_result_t ret = rsa_decode_pss_params_sha256(params);
if (ret != evp_decode_ok) {
return ret;
}
bssl::UniquePtr<RSA> 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(out, &rsa_pss_sha256_asn1_meth, rsa.release());
return evp_decode_ok;
}
static int rsa_opaque(const EVP_PKEY *pkey) {
const RSA *rsa = reinterpret_cast<const RSA *>(pkey->pkey);
return RSA_is_opaque(rsa);
@@ -148,25 +252,76 @@ const EVP_PKEY_ASN1_METHOD rsa_asn1_meth = {
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,
/*set_priv_raw=*/nullptr,
/*set_pub_raw=*/nullptr,
/*get_priv_raw=*/nullptr,
/*get_pub_raw=*/nullptr,
/*set1_tls_encodedpoint=*/nullptr,
/*get1_tls_encodedpoint=*/nullptr,
rsa_opaque,
int_rsa_size,
rsa_bits,
0,
0,
0,
/*param_missing=*/nullptr,
/*param_copy=*/nullptr,
/*param_cmp=*/nullptr,
int_rsa_free,
};
const EVP_PKEY_ASN1_METHOD rsa_pss_sha256_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_sha256_pkey_meth,
rsa_pub_decode_pss_sha256,
rsa_pub_encode_pss_sha256,
rsa_pub_cmp,
rsa_priv_decode_pss_sha256,
rsa_priv_encode_pss_sha256,
/*set_priv_raw=*/nullptr,
/*set_pub_raw=*/nullptr,
/*get_priv_raw=*/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_cmp=*/nullptr,
int_rsa_free,
};
const EVP_PKEY_ALG *EVP_pkey_rsa(void) {
static const EVP_PKEY_ALG kAlg = {
/*method=*/&rsa_asn1_meth,
/*ec_group=*/nullptr,
};
return &kAlg;
}
const EVP_PKEY_ALG *EVP_pkey_rsa_pss_sha256(void) {
static const EVP_PKEY_ALG kAlg = {
/*method=*/&rsa_pss_sha256_asn1_meth,
/*ec_group=*/nullptr,
};
return &kAlg;
}
int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, RSA *key) {
if (EVP_PKEY_assign_RSA(pkey, key)) {
RSA_up_ref(key);
@@ -176,13 +331,16 @@ int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, RSA *key) {
}
int EVP_PKEY_assign_RSA(EVP_PKEY *pkey, RSA *key) {
evp_pkey_set_method(pkey, &rsa_asn1_meth);
pkey->pkey = key;
return key != NULL;
if (key == nullptr) {
return 0;
}
evp_pkey_set0(pkey, &rsa_asn1_meth, key);
return 1;
}
RSA *EVP_PKEY_get0_RSA(const EVP_PKEY *pkey) {
if (pkey->type != EVP_PKEY_RSA) {
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 NULL;
}
@@ -31,13 +31,9 @@ static int pkey_x25519_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) {
return 0;
}
evp_pkey_set_method(pkey, &x25519_asn1_meth);
X25519_keypair(key->pub, key->priv);
key->has_private = 1;
OPENSSL_free(pkey->pkey);
pkey->pkey = key;
evp_pkey_set0(pkey, &x25519_asn1_meth, key);
return 1;
}
@@ -90,7 +86,7 @@ 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,
/*copy=*/pkey_x25519_copy,
@@ -44,8 +44,7 @@ static int x25519_set_priv_raw(EVP_PKEY *pkey, const uint8_t *in, size_t len) {
X25519_public_from_private(key->pub, key->priv);
key->has_private = 1;
x25519_free(pkey);
pkey->pkey = key;
evp_pkey_set0(pkey, &x25519_asn1_meth, key);
return 1;
}
@@ -64,8 +63,7 @@ static int x25519_set_pub_raw(EVP_PKEY *pkey, const uint8_t *in, size_t len) {
OPENSSL_memcpy(key->pub, in, 32);
key->has_private = 0;
x25519_free(pkey);
pkey->pkey = key;
evp_pkey_set0(pkey, &x25519_asn1_meth, key);
return 1;
}
@@ -127,16 +125,20 @@ static size_t x25519_get1_tls_encodedpoint(const EVP_PKEY *pkey,
return *out_ptr == NULL ? 0 : 32;
}
static int x25519_pub_decode(EVP_PKEY *out, CBS *params, CBS *key) {
static evp_decode_result_t x25519_pub_decode(const EVP_PKEY_ALG *alg,
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 evp_decode_error;
}
return x25519_set_pub_raw(out, CBS_data(key), CBS_len(key));
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 EVP_PKEY *pkey) {
@@ -165,7 +167,9 @@ static int x25519_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) {
return OPENSSL_memcmp(a_key->pub, b_key->pub, 32) == 0;
}
static int x25519_priv_decode(EVP_PKEY *out, CBS *params, CBS *key) {
static evp_decode_result_t x25519_priv_decode(const EVP_PKEY_ALG *alg,
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
@@ -174,10 +178,12 @@ static int x25519_priv_decode(EVP_PKEY *out, CBS *params, CBS *key) {
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 evp_decode_error;
}
return x25519_set_priv_raw(out, CBS_data(&inner), CBS_len(&inner));
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 EVP_PKEY *pkey) {
@@ -235,3 +241,11 @@ const EVP_PKEY_ASN1_METHOD x25519_asn1_meth = {
/*param_cmp=*/NULL,
x25519_free,
};
const EVP_PKEY_ALG *EVP_pkey_x25519(void) {
static const EVP_PKEY_ALG kAlg = {
/*method=*/&x25519_asn1_meth,
/*ec_group=*/nullptr,
};
return &kAlg;
}
+10 -67
View File
@@ -152,55 +152,6 @@ 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) {
@@ -277,18 +228,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,
@@ -298,15 +243,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,
@@ -318,7 +261,7 @@ 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));
const EVP_PKEY_PRINT_METHOD *method = find_method(EVP_PKEY_id(pkey));
if (method != NULL && method->pub_print != NULL) {
return method->pub_print(out, pkey, indent);
}
@@ -327,7 +270,7 @@ 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));
const EVP_PKEY_PRINT_METHOD *method = find_method(EVP_PKEY_id(pkey));
if (method != NULL && method->priv_print != NULL) {
return method->priv_print(out, pkey, indent);
}
@@ -336,7 +279,7 @@ 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));
const EVP_PKEY_PRINT_METHOD *method = find_method(EVP_PKEY_id(pkey));
if (method != NULL && method->param_print != NULL) {
return method->param_print(out, pkey, indent);
}
@@ -26,7 +26,7 @@
#include <CCryptoBoringSSL_digest.h>
#include <CCryptoBoringSSL_hmac.h>
#include <CCryptoBoringSSL_sha.h>
#include <CCryptoBoringSSL_sha2.h>
#include "../bcm_support.h"
#include "../internal.h"
@@ -90,6 +90,7 @@
#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"
@@ -172,8 +173,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.
@@ -529,6 +529,140 @@ OPENSSL_EXPORT bcm_status BCM_mldsa87_verify_internal(
OPENSSL_EXPORT bcm_status BCM_mldsa87_marshal_private_key(
CBB *out, const struct BCM_mldsa87_private_key *private_key);
// 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
// BCM_MLDSA44_PUBLIC_KEY_BYTES is the number of bytes in an encoded ML-DSA-44
// public key.
#define BCM_MLDSA44_PUBLIC_KEY_BYTES 1312
// BCM_MLDSA44_SIGNATURE_BYTES is the number of bytes in an encoded ML-DSA-44
// signature.
#define BCM_MLDSA44_SIGNATURE_BYTES 2420
struct BCM_mldsa44_private_key {
union {
uint8_t bytes[32 + 32 + 64 + 256 * 4 * (4 + 4 + 4)];
uint32_t alignment;
} opaque;
};
struct BCM_mldsa44_public_key {
union {
uint8_t bytes[32 + 64 + 256 * 4 * 4];
uint32_t alignment;
} opaque;
};
struct BCM_mldsa44_prehash {
union {
uint8_t bytes[200 + 4 + 4 + 4 * sizeof(size_t)];
uint64_t alignment;
} opaque;
};
OPENSSL_EXPORT bcm_status BCM_mldsa44_generate_key(
uint8_t out_encoded_public_key[BCM_MLDSA44_PUBLIC_KEY_BYTES],
uint8_t out_seed[BCM_MLDSA_SEED_BYTES],
struct BCM_mldsa44_private_key *out_private_key);
OPENSSL_EXPORT bcm_status BCM_mldsa44_private_key_from_seed(
struct BCM_mldsa44_private_key *out_private_key,
const uint8_t seed[BCM_MLDSA_SEED_BYTES]);
OPENSSL_EXPORT bcm_status BCM_mldsa44_public_from_private(
struct BCM_mldsa44_public_key *out_public_key,
const struct BCM_mldsa44_private_key *private_key);
OPENSSL_EXPORT bcm_status
BCM_mldsa44_check_key_fips(struct BCM_mldsa44_private_key *private_key);
OPENSSL_EXPORT bcm_status BCM_mldsa44_generate_key_fips(
uint8_t out_encoded_public_key[BCM_MLDSA44_PUBLIC_KEY_BYTES],
uint8_t out_seed[BCM_MLDSA_SEED_BYTES],
struct BCM_mldsa44_private_key *out_private_key);
OPENSSL_EXPORT bcm_status BCM_mldsa44_private_key_from_seed_fips(
struct BCM_mldsa44_private_key *out_private_key,
const uint8_t seed[BCM_MLDSA_SEED_BYTES]);
OPENSSL_EXPORT bcm_status BCM_mldsa44_sign(
uint8_t out_encoded_signature[BCM_MLDSA44_SIGNATURE_BYTES],
const struct BCM_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 struct BCM_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(
struct BCM_mldsa44_prehash *out_prehash_ctx,
const struct BCM_mldsa44_public_key *public_key, const uint8_t *context,
size_t context_len);
OPENSSL_EXPORT void BCM_mldsa44_prehash_update(
struct BCM_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[BCM_MLDSA_MU_BYTES],
struct BCM_mldsa44_prehash *inout_prehash_ctx);
OPENSSL_EXPORT bcm_status BCM_mldsa44_sign_message_representative(
uint8_t out_encoded_signature[BCM_MLDSA44_SIGNATURE_BYTES],
const struct BCM_mldsa44_private_key *private_key,
const uint8_t msg_rep[BCM_MLDSA_MU_BYTES]);
OPENSSL_EXPORT bcm_status BCM_mldsa44_marshal_public_key(
CBB *out, const struct BCM_mldsa44_public_key *public_key);
OPENSSL_EXPORT bcm_status BCM_mldsa44_parse_public_key(
struct BCM_mldsa44_public_key *public_key, CBS *in);
OPENSSL_EXPORT bcm_status BCM_mldsa44_parse_private_key(
struct BCM_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[BCM_MLDSA44_PUBLIC_KEY_BYTES],
struct BCM_mldsa44_private_key *out_private_key,
const uint8_t entropy[BCM_MLDSA_SEED_BYTES]);
OPENSSL_EXPORT bcm_status BCM_mldsa44_generate_key_external_entropy_fips(
uint8_t out_encoded_public_key[BCM_MLDSA44_PUBLIC_KEY_BYTES],
struct BCM_mldsa44_private_key *out_private_key,
const uint8_t entropy[BCM_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[BCM_MLDSA44_SIGNATURE_BYTES],
const struct BCM_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]);
// 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 struct BCM_mldsa44_public_key *public_key,
const uint8_t encoded_signature[BCM_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 struct BCM_mldsa44_private_key *private_key);
// ML-KEM
//
@@ -560,9 +560,9 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
// |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.
// "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
@@ -578,12 +578,12 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
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|.
@@ -591,7 +591,7 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
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);
}
}
@@ -614,11 +614,11 @@ 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 {
@@ -44,24 +44,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
@@ -198,8 +198,8 @@ void bn_sqr_add_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)
@@ -209,13 +209,13 @@ void bn_sqr_add_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)
@@ -225,8 +225,8 @@ void bn_sqr_add_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)
@@ -105,11 +105,6 @@ 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|.
int bn_minimal_width(const BIGNUM *bn);
@@ -268,16 +263,27 @@ int bn_rand_secret_range(BIGNUM *r, int *out_is_uniform, BN_ULONG min_inclusive,
// |BIGNUM|s, in |bn_wexpand|, but the exactfloat library needs to create 8 MiB
// values for other operations.
//
// TODO(crbug.com/402677800): This is not quite tight enough to limit the
// |bn_mul_mont| allocation to under a page. Lower the maximum RSA key and then
// lower this to match.
#define BN_MONTGOMERY_MAX_WORDS (16384 / BN_BITS2)
// This limit is set so that one number fits within 1 KiB, giving room to
// allocate a few of them on the stack in |bn_mul_mont_words| without exceeding
// a page (4 KiB). It is also set to limit the DoS impact of large RSA, DH, and
// DSA keys, which scale cubically.
#define BN_MONTGOMERY_MAX_WORDS (8192 / BN_BITS2)
struct bn_mont_ctx_st {
// RR is R^2, 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
};
#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
// 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|.
//
@@ -295,8 +301,9 @@ int bn_rand_secret_range(BIGNUM *r, int *out_is_uniform, BN_ULONG min_inclusive,
//
// See also discussion in |ToWord| in abi_test.h for notes on smaller-than-word
// inputs.
void 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 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) {
@@ -304,30 +311,36 @@ inline int bn_mulx_adx_capable(void) {
return CRYPTO_is_BMI2_capable() && CRYPTO_is_ADX_capable();
}
void 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);
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;
}
void 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);
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();
}
void 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);
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;
}
void 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);
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();
}
void 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);
const BN_ULONG *np,
const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], size_t num);
void 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);
const BN_ULONG *np,
const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], size_t num);
#endif
#endif // OPENSSL_BN_ASM_MONT
@@ -340,7 +353,8 @@ void bn_mul_mont_nohw(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp,
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);
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() &&
@@ -348,11 +362,13 @@ inline int bn_mulx4x_mont_gather5_capable(int num) {
}
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);
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);
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
@@ -368,7 +384,8 @@ 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);
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; }
@@ -377,7 +394,8 @@ inline int bn_powerx5_capable(int num) {
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);
const BN_ULONG *np, const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS],
int num, int power);
#endif // !OPENSSL_NO_ASM && OPENSSL_X86_64
@@ -64,8 +64,9 @@ 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;
}
to->n0[0] = from->n0[0];
to->n0[1] = from->n0[1];
for (size_t i = 0; i < BN_MONT_CTX_N0_LIMBS; i++) {
to->n0[i] = from->n0[i];
}
return to;
}
@@ -111,8 +112,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;
}
@@ -309,16 +308,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.
// |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|
// 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);
bn_mul_mont(r->d, a->d, b->d, mont->N.d, mont->n0, num);
bn_mul_mont_words(r->d, a->d, b->d, mont->N.d, mont->n0, num);
r->neg = 0;
r->width = num;
return 1;
@@ -359,9 +358,9 @@ void bn_mod_mul_montgomery_small(BN_ULONG *r, const BN_ULONG *a,
}
#if defined(OPENSSL_BN_ASM_MONT)
// |bn_mul_mont| requires at least 128 bits of limbs.
// |bn_mul_mont_words| requires at least 128 bits of limbs.
if (num >= (128 / BN_BITS2)) {
bn_mul_mont(r, a, b, mont->N.d, mont->n0, num);
bn_mul_mont_words(r, a, b, mont->N.d, mont->n0, num);
return;
}
#endif
@@ -382,8 +381,8 @@ void bn_mod_mul_montgomery_small(BN_ULONG *r, const BN_ULONG *a,
}
#if defined(OPENSSL_BN_ASM_MONT) && defined(OPENSSL_X86_64)
void 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 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)) {
bn_sqr8x_mont(rp, ap, bn_mulx_adx_capable(), np, n0, num);
} else if (bn_mulx4x_mont_capable(num)) {
@@ -397,8 +396,8 @@ void bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp,
#endif
#if defined(OPENSSL_BN_ASM_MONT) && defined(OPENSSL_ARM)
void 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 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)) {
bn_mul8x_mont_neon(rp, ap, bp, np, n0, num);
} else {
@@ -14,6 +14,8 @@
#include <CCryptoBoringSSL_bn.h>
#include <iterator>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
@@ -193,9 +195,9 @@ 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
@@ -16,6 +16,8 @@
#include <string.h>
#include <iterator>
#include <CCryptoBoringSSL_bn.h>
#include <CCryptoBoringSSL_digest.h>
#include <CCryptoBoringSSL_err.h>
@@ -406,7 +408,7 @@ DH *DH_get_rfc7919_2048(void) {
}
bn_set_static_words(ffdhe2048_p.get(), kFFDHE2048Data,
OPENSSL_ARRAY_SIZE(kFFDHE2048Data));
std::size(kFFDHE2048Data));
if (!BN_rshift1(ffdhe2048_q.get(), ffdhe2048_p.get()) ||
!BN_set_word(ffdhe2048_g.get(), 2) ||
@@ -36,7 +36,9 @@ 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) {
@@ -53,8 +55,6 @@ EVP_MD_CTX *EVP_MD_CTX_new(void) {
EVP_MD_CTX *EVP_MD_CTX_create(void) { 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);
if (ctx->pctx_ops) {
ctx->pctx_ops->free(ctx->pctx);
@@ -66,7 +66,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);
}
@@ -97,6 +97,10 @@ int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in) {
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);
@@ -107,31 +111,9 @@ 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<uint8_t *>(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<uint8_t *>(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) {
OPENSSL_memcpy(out->md_data, in->md_data, in->digest->ctx_size);
}
@@ -167,14 +149,7 @@ 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<uint8_t *>(OPENSSL_malloc(type->ctx_size));
if (md_data == NULL) {
return 0;
}
OPENSSL_free(ctx->md_data);
ctx->md_data = md_data;
assert(type->ctx_size <= sizeof(ctx->md_data));
ctx->digest = type;
}
@@ -54,6 +54,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<SHA256_CTX *>(ctx->md_data));
@@ -78,6 +80,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<SHA256_CTX *>(ctx->md_data));
@@ -126,6 +129,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<SHA512_CTX *>(ctx->md_data));
@@ -18,6 +18,8 @@
#include <assert.h>
#include <string.h>
#include <iterator>
#include <CCryptoBoringSSL_bn.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
@@ -64,10 +66,10 @@ DEFINE_METHOD_FUNCTION(EC_GROUP, EC_group_p224) {
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();
@@ -98,10 +100,10 @@ DEFINE_METHOD_FUNCTION(EC_GROUP, EC_group_p256) {
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)) && \
@@ -129,10 +131,10 @@ DEFINE_METHOD_FUNCTION(EC_GROUP, EC_group_p384) {
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;
@@ -154,10 +156,10 @@ DEFINE_METHOD_FUNCTION(EC_GROUP, EC_group_p521) {
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;
@@ -870,7 +872,7 @@ void 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]);
}
}
@@ -262,9 +262,7 @@ int EC_POINT_set_compressed_coordinates_GFp(const EC_GROUP *group,
}
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) {
if (ERR_equals(ERR_peek_last_error(), ERR_LIB_BN, BN_R_NOT_A_SQUARE)) {
ERR_clear_error();
OPENSSL_PUT_ERROR(EC, EC_R_INVALID_COMPRESSED_POINT);
} else {
@@ -651,9 +651,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]);
}
}
@@ -26,18 +26,14 @@
#include <assert.h>
#include <string.h>
#include <iterator>
#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"
// utility functions, handwritten
@@ -56,13 +52,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++) {
@@ -172,198 +161,44 @@ 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:
// <https://github.com/mit-plv/fiat-crypto/blob/79f8b5f39ed609339f0233098dee1a3c4e6b3080/src/Spec/WeierstrassCurve.v#L28>
// As a sanity check, a proof that these points form a commutative group:
// <https://github.com/mit-plv/fiat-crypto/blob/79f8b5f39ed609339f0233098dee1a3c4e6b3080/src/Curves/Weierstrass/AffineProofs.v#L33>
// 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:
// <https://github.com/mit-plv/fiat-crypto/blob/79f8b5f39ed609339f0233098dee1a3c4e6b3080/src/Curves/Weierstrass/Jacobian.v#L93>
// <https://github.com/mit-plv/fiat-crypto/blob/79f8b5f39ed609339f0233098dee1a3c4e6b3080/src/Curves/Weierstrass/Jacobian.v#L201>
//
// 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:
// <https://github.com/mit-plv/fiat-crypto/blob/79f8b5f39ed609339f0233098dee1a3c4e6b3080/src/Curves/Weierstrass/Jacobian.v#L135>
// <https://github.com/mit-plv/fiat-crypto/blob/79f8b5f39ed609339f0233098dee1a3c4e6b3080/src/Curves/Weierstrass/Jacobian.v#L205>
//
// 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
@@ -454,8 +289,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 +320,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],
@@ -524,8 +358,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 +396,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 +413,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]);
@@ -602,11 +436,10 @@ 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|.
@@ -632,9 +465,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 +478,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 +495,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);
@@ -16,6 +16,9 @@
#include <assert.h>
#include <iterator>
#include <type_traits>
#include "internal.h"
#include "../bn/internal.h"
#include "../../internal.h"
@@ -31,7 +34,7 @@ void ec_GFp_mont_mul(const EC_GROUP *group, EC_JACOBIAN *r,
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 {
@@ -58,7 +61,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);
}
@@ -202,10 +205,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<decltype(comb)> == std::extent_v<decltype(out->comb)>,
"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,
@@ -224,7 +227,7 @@ static void ec_GFp_mont_get_comb_window(const EC_GROUP *group,
// 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);
@@ -18,6 +18,8 @@
#include <assert.h>
#include <string.h>
#include <iterator>
#include <CCryptoBoringSSL_bn.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
@@ -167,7 +169,7 @@ 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) {
ec_compute_wNAF(group, g_wNAF, g_scalar, bits, EC_WNAF_WINDOW_BITS);
@@ -175,7 +177,7 @@ int ec_GFp_mont_mul_public_batch(const EC_GROUP *group, EC_JACOBIAN *r,
}
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);
}
@@ -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 <CCryptoBoringSSL_base.h>
#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
@@ -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 <CCryptoBoringSSL_base.h>
#if defined(OPENSSL_LINUX) || defined(OPENSSL_MACOS)
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <array>
#include <type_traits>
#include <utility>
#include <CCryptoBoringSSL_mem.h>
#include "internal.h"
#include "sha512.cc.inc"
#if defined(__x86_64__)
#include <x86intrin.h>
#endif
BSSL_NAMESPACE_BEGIN
namespace entropy {
namespace {
#if defined(__x86_64__)
static inline uint64_t GetTimestamp() { return _rdtsc(); }
#elif defined(__aarch64__)
static inline uint64_t GetTimestamp() {
// Ideally this would use __arm_rsr64 from <arm_acle.h>. 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 inline 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<uint8_t *>(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<uint8_t *>(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 <typename T>
class DeltaSampler {
public:
explicit DeltaSampler(T &&sub_sampler)
: sub_sampler_(std::forward<T>(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_;
};
template <typename U>
DeltaSampler(U &&sub_sampler) -> DeltaSampler<std::decay_t<U>>;
template <typename T>
class MaskSampler {
public:
explicit MaskSampler(uint8_t mask, T &&sub_sampler)
: mask_(mask), sub_sampler_(std::forward<T>(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 <typename U>
MaskSampler(uint8_t mask, U &&sub_sampler) -> MaskSampler<std::decay_t<U>>;
// 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<unsigned>(-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<unsigned>(val);
if (val == static_cast<float>(truncated)) {
return truncated;
}
if (val > 0) {
return truncated + 1;
}
__builtin_unreachable();
}
template <typename T>
class RepetitionCountTest {
public:
static constexpr unsigned kThreshold = 1 + Ceil(-kAlphaLog2 / kH);
static_assert(kThreshold == 26);
explicit RepetitionCountTest(T &&sub_sampler)
: sub_sampler_(std::forward<T>(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 <typename U>
RepetitionCountTest(U &&sub_sampler) -> RepetitionCountTest<std::decay_t<U>>;
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^x using the Taylor series: e^x = 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 <typename T>
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<T>(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<uint8_t, kWindowSize> buffer_{};
// An array to store the frequency counts of each possible byte value (0-255)
// within the current window.
std::array<uint16_t, 256> 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 <typename U>
AdaptiveProportionTest(U &&sub_sampler)
-> AdaptiveProportionTest<std::decay_t<U>>;
template <typename T>
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<T>(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 <typename U>
SeedSampler(U &&sub_sampler) -> SeedSampler<std::decay_t<U>>;
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
@@ -0,0 +1,324 @@
// 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 <stdint.h>
#include <string.h>
// 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.
namespace bssl::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<const uint8_t *>(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 bssl::entropy
@@ -50,7 +50,6 @@ 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;
@@ -65,6 +64,8 @@ constexpr size_t public_key_bytes() {
return BCM_MLDSA65_PUBLIC_KEY_BYTES;
} else if constexpr (K == 8) {
return BCM_MLDSA87_PUBLIC_KEY_BYTES;
} else if constexpr (K == 4) {
return BCM_MLDSA44_PUBLIC_KEY_BYTES;
}
}
@@ -74,6 +75,8 @@ constexpr size_t signature_bytes() {
return BCM_MLDSA65_SIGNATURE_BYTES;
} else if constexpr (K == 8) {
return BCM_MLDSA87_SIGNATURE_BYTES;
} else if constexpr (K == 4) {
return BCM_MLDSA44_SIGNATURE_BYTES;
}
}
@@ -83,6 +86,8 @@ constexpr int tau() {
return 49;
} else if constexpr (K == 8) {
return 60;
} else if constexpr (K == 4) {
return 39;
}
}
@@ -92,22 +97,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 <int K>
constexpr int gamma1_bits() {
if constexpr (K == 6 || K == 8) {
return 19;
} else if constexpr (K == 4) {
return 17;
}
}
template <int K>
constexpr int gamma1() {
return 1 << gamma1_bits<K>();
}
template <int K>
constexpr int scalar_le_gamma1_bytes() {
return ((gamma1_bits<K>() + 1) * kDegree) / 8;
}
template <int K>
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 <int K>
constexpr uint32_t w1_scalar_bytes() {
return (w1_coeffs_bits<K>() * kDegree) / 8;
}
template <int K>
constexpr uint32_t w1_bytes() {
return w1_scalar_bytes<K>() * K;
}
template <int K>
constexpr uint32_t prime_minus_one_over_gamma2() {
if constexpr (K == 6 || K == 8) {
return 32;
} else if constexpr (K == 4) {
return 88;
}
}
template <int K>
constexpr uint32_t gamma2() {
return (kPrime - 1) / prime_minus_one_over_gamma2<K>();
}
template <int K>
constexpr int beta() {
if constexpr (K == 6) {
return 196;
} else if constexpr (K == 8) {
return 120;
} else if constexpr (K == 4) {
return 78;
}
}
@@ -117,6 +171,8 @@ constexpr int omega() {
return 55;
} else if constexpr (K == 8) {
return 75;
} else if constexpr (K == 4) {
return 80;
}
}
@@ -124,7 +180,7 @@ template <int K>
constexpr int eta() {
if constexpr (K == 6) {
return 4;
} else if constexpr (K == 8) {
} else if constexpr (K == 8 || K == 4) {
return 2;
}
}
@@ -133,7 +189,7 @@ template <int K>
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;
}
}
@@ -433,42 +489,54 @@ void scale_power2_round(uint32_t *out, uint32_t r1) {
}
// FIPS 204, Algorithm 37 (`HighBits`).
template <int K>
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<K>() == 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<K>() == 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`).
template <int K>
void decompose(uint32_t *r1, int32_t *r0, uint32_t r) {
*r1 = high_bits(r);
*r1 = high_bits<K>(r);
*r0 = r;
*r0 -= *r1 * 2 * (int32_t)kGamma2;
*r0 -= *r1 * 2 * (int32_t)gamma2<K>();
*r0 -= (((int32_t)kHalfPrime - *r0) >> 31) & (int32_t)kPrime;
}
// FIPS 204, Algorithm 38 (`LowBits`).
template <int K>
int32_t low_bits(uint32_t x) {
uint32_t r1;
int32_t r0;
decompose(&r1, &r0, x);
decompose<K>(&r1, &r0, x);
return r0;
}
@@ -480,24 +548,45 @@ 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.
template <int K>
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<K>(r) != high_bits<K>(r_plus_z);
}
// FIPS 204, Algorithm 40 (`UseHint`).
template <int K>
uint32_t use_hint_vartime(uint32_t h, uint32_t r) {
uint32_t r1;
int32_t r0;
decompose(&r1, &r0, r);
decompose<K>(&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<K>() == 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<K>() == 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;
@@ -515,15 +604,17 @@ void scalar_scale_power2_round(scalar *out, const scalar *in) {
}
}
template <int K>
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<K>(in->c[i]);
}
}
template <int K>
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<K>(in->c[i]);
}
}
@@ -541,16 +632,18 @@ void scalar_max_signed(uint32_t *max, const scalar *s) {
}
}
template <int K>
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<K>(ct0->c[i], cs2->c[i], w->c[i]);
}
}
template <int K>
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<K>(h->c[i], r->c[i]);
}
}
@@ -568,17 +661,17 @@ void vector_scale_power2_round(vector<X> *out, const vector<X> *in) {
}
}
template <int X>
void vector_high_bits(vector<X> *out, const vector<X> *in) {
for (int i = 0; i < X; i++) {
scalar_high_bits(&out->v[i], &in->v[i]);
template <int K>
void vector_high_bits(vector<K> *out, const vector<K> *in) {
for (int i = 0; i < K; i++) {
scalar_high_bits<K>(&out->v[i], &in->v[i]);
}
}
template <int X>
void vector_low_bits(vector<X> *out, const vector<X> *in) {
for (int i = 0; i < X; i++) {
scalar_low_bits(&out->v[i], &in->v[i]);
template <int K>
void vector_low_bits(vector<K> *out, const vector<K> *in) {
for (int i = 0; i < K; i++) {
scalar_low_bits<K>(&out->v[i], &in->v[i]);
}
}
@@ -612,19 +705,19 @@ size_t vector_count_ones(const vector<X> *a) {
return count;
}
template <int X>
void vector_make_hint(vector<X> *out, const vector<X> *ct0,
const vector<X> *cs2, const vector<X> *w) {
for (int i = 0; i < X; i++) {
scalar_make_hint(&out->v[i], &ct0->v[i], &cs2->v[i], &w->v[i]);
template <int K>
void vector_make_hint(vector<K> *out, const vector<K> *ct0,
const vector<K> *cs2, const vector<K> *w) {
for (int i = 0; i < K; i++) {
scalar_make_hint<K>(&out->v[i], &ct0->v[i], &cs2->v[i], &w->v[i]);
}
}
template <int X>
void vector_use_hint_vartime(vector<X> *out, const vector<X> *h,
const vector<X> *r) {
for (int i = 0; i < X; i++) {
scalar_use_hint_vartime(&out->v[i], &h->v[i], &r->v[i]);
template <int K>
void vector_use_hint_vartime(vector<K> *out, const vector<K> *h,
const vector<K> *r) {
for (int i = 0; i < K; i++) {
scalar_use_hint_vartime<K>(&out->v[i], &h->v[i], &r->v[i]);
}
}
@@ -643,6 +736,25 @@ static void scalar_encode_4(uint8_t out[128], const scalar *s) {
}
}
// FIPS 204, Algorithm 16 (`SimpleBitPack`). Specialized to bitlen(b) = 6.
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) {
// Every four elements lands on a byte boundary.
@@ -730,10 +842,10 @@ 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<uint8_t>(h);
}
}
@@ -757,9 +869,35 @@ 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<uint16_t>(d));
}
}
// FIPS 204, Algorithm 17 (`BitPack`). Specialized to bitlen(a+b) = 18 and b =
// 2^17.
void scalar_encode_signed_18_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++) {
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);
}
}
@@ -775,6 +913,9 @@ void scalar_encode_signed(uint8_t *out, const scalar *s, int bits,
} else if (bits == 20) {
assert(max == 1u << 19);
scalar_encode_signed_20_19(out, s);
} else if (bits == 18) {
assert(max == 1u << 17);
scalar_encode_signed_18_17(out, s);
} else {
assert(bits == 13);
assert(max == 1u << 12);
@@ -784,10 +925,9 @@ void scalar_encode_signed(uint8_t *out, const scalar *s, int bits,
// FIPS 204, Algorithm 18 (`SimpleBitUnpack`). Specialized for bitlen(b) == 10.
void scalar_decode_10(scalar *out, const uint8_t in[320]) {
uint32_t v;
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 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;
@@ -798,10 +938,9 @@ void scalar_decode_10(scalar *out, const uint8_t in[320]) {
// 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;
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;
@@ -865,14 +1004,12 @@ void scalar_decode_signed_13_12(scalar *out, const uint8_t in[416]) {
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.
@@ -887,19 +1024,43 @@ void scalar_decode_signed_13_12(scalar *out, const uint8_t in[416]) {
}
}
// FIPS 204, Algorithm 19 (`BitUnpack`). Specialized to bitlen(a+b) = 18 and b =
// 2^17.
void scalar_decode_signed_18_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);
}
}
// 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]) {
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.
@@ -923,6 +1084,10 @@ int scalar_decode_signed(scalar *out, const uint8_t *in, int bits,
assert(max == (1u << 12));
scalar_decode_signed_13_12(out, in);
return 1;
} else if (bits == 18) {
assert(max == (1u << 17));
scalar_decode_signed_18_17(out, in);
return 1;
} else if (bits == 20) {
assert(max == (1u << 19));
scalar_decode_signed_20_19(out, in);
@@ -1016,13 +1181,14 @@ void scalar_uniform(scalar *out, const uint8_t derived_seed[kSigmaBytes + 2]) {
}
// FIPS 204, Algorithm 34 (`ExpandMask`), but just a single step.
template <int K>
void scalar_sample_mask(scalar *out,
const uint8_t derived_seed[kRhoPrimeBytes + 2]) {
uint8_t buf[640];
uint8_t buf[scalar_le_gamma1_bytes<K>()];
BORINGSSL_keccak(buf, sizeof(buf), derived_seed, kRhoPrimeBytes + 2,
boringssl_shake256);
scalar_decode_signed_20_19(out, buf);
scalar_decode_signed(out, buf, gamma1_bits<K>() + 1, gamma1<K>());
}
// FIPS 204, Algorithm 29 (`SampleInBall`).
@@ -1108,7 +1274,7 @@ void vector_expand_short(vector<L> *s1, vector<K> *s2,
}
// FIPS 204, Algorithm 34 (`ExpandMask`).
template <int L>
template <int K, int L>
void vector_expand_mask(vector<L> *out, const uint8_t seed[kRhoPrimeBytes],
size_t kappa) {
assert(kappa + L <= 0x10000);
@@ -1119,7 +1285,7 @@ void vector_expand_mask(vector<L> *out, const uint8_t seed[kRhoPrimeBytes],
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<K>(&out->v[i], derived_seed);
}
}
@@ -1136,6 +1302,10 @@ void vector_encode(uint8_t *out, const vector<K> *a, int bits) {
for (int i = 0; i < K; i++) {
scalar_encode_4(out + i * bits * kDegree / 8, &a->v[i]);
}
} else if (bits == 6) {
for (int i = 0; i < K; i++) {
scalar_encode_6(out + i * bits * kDegree / 8, &a->v[i]);
}
} else {
assert(bits == 10);
for (int i = 0; i < K; i++) {
@@ -1179,8 +1349,8 @@ int vector_decode_signed(vector<X> *out, const uint8_t *in, int bits,
// FIPS 204, Algorithm 28 (`w1Encode`).
template <int K>
void w1_encode(uint8_t out[128 * K], const vector<K> *w1) {
vector_encode(out, w1, 4);
void w1_encode(uint8_t out[w1_bytes<K>()], const vector<K> *w1) {
vector_encode(out, w1, w1_coeffs_bits<K>());
}
// FIPS 204, Algorithm 20 (`HintBitPack`).
@@ -1364,10 +1534,11 @@ int mldsa_marshal_signature(CBB *out, const struct signature<K, L> *sign) {
}
uint8_t *vectorl_output;
if (!CBB_add_space(out, &vectorl_output, 640 * L)) {
if (!CBB_add_space(out, &vectorl_output, scalar_le_gamma1_bytes<K>() * L)) {
return 0;
}
vector_encode_signed(vectorl_output, &sign->z, 20, 1 << 19);
vector_encode_signed(vectorl_output, &sign->z, gamma1_bits<K>() + 1,
gamma1<K>());
uint8_t *hint_output;
if (!CBB_add_space(out, &hint_output, omega<K>() + K)) {
@@ -1384,9 +1555,10 @@ int mldsa_parse_signature(struct signature<K, L> *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<K>() * L) ||
// Note: Decoding b+1 bits into (-2^b, 2^b] cannot fail.
!vector_decode_signed(&sign->z, CBS_data(&z_bytes), gamma1_bits<K>() + 1,
gamma1<K>()) ||
!CBS_get_bytes(in, &hint_bytes, omega<K>() + K) ||
!hint_bit_unpack(&sign->h, CBS_data(&hint_bytes))) {
return 0;
@@ -1561,7 +1733,7 @@ int mldsa_sign_mu(
// 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<K, L>(&values->y, rho_prime, kappa);
vector<L> *y_ntt = &values->cs1;
OPENSSL_memcpy(y_ntt, &values->y, sizeof(*y_ntt));
@@ -1571,12 +1743,12 @@ int mldsa_sign_mu(
vector_inverse_ntt(&values->w);
vector_high_bits(&values->w1, &values->w);
uint8_t w1_encoded[128 * K];
uint8_t w1_encoded[w1_bytes<K>()];
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<K>());
BORINGSSL_keccak_squeeze(&keccak_ctx, values->sign.c_tilde,
2 * lambda_bytes<K>());
@@ -1609,7 +1781,7 @@ int mldsa_sign_mu(
uint32_t r0_max = vector_max_signed(r0);
if (constant_time_declassify_w(
constant_time_ge_w(z_max, gamma1<K>() - beta<K>()) |
constant_time_ge_w(r0_max, kGamma2 - beta<K>()))) {
constant_time_ge_w(r0_max, gamma2<K>() - beta<K>()))) {
#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.
@@ -1626,7 +1798,7 @@ int mldsa_sign_mu(
// 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<K>()) |
constant_time_lt_w(omega<K>(), h_ones))) {
#if defined(BORINGSSL_FIPS_BREAK_TESTS)
// In order to show that our self-tests trigger both restart cases in
@@ -1778,13 +1950,13 @@ int mldsa_verify_internal_no_self_test(
vector_inverse_ntt(w1);
vector_use_hint_vartime(w1, &values->sign.h, w1);
uint8_t w1_encoded[128 * K];
uint8_t w1_encoded[w1_bytes<K>()];
w1_encode(w1_encoded, w1);
uint8_t c_tilde[2 * lambda_bytes<K>()];
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<K>());
BORINGSSL_keccak_squeeze(&keccak_ctx, c_tilde, 2 * lambda_bytes<K>());
uint32_t z_max = vector_max(&values->sign.z);
@@ -1871,6 +2043,39 @@ struct prehash_context *prehash_context_from_external_87(
return reinterpret_cast<prehash_context *>(external);
}
struct private_key<4, 4> *private_key_from_external_44(
const struct BCM_mldsa44_private_key *external) {
static_assert(sizeof(struct BCM_mldsa44_private_key) ==
sizeof(struct private_key<4, 4>),
"MLDSA44 private key size incorrect");
static_assert(alignof(struct BCM_mldsa44_private_key) ==
alignof(struct private_key<4, 4>),
"MLDSA44 private key alignment incorrect");
return (struct private_key<4, 4> *)external;
}
struct public_key<4> *public_key_from_external_44(
const struct BCM_mldsa44_public_key *external) {
static_assert(
sizeof(struct BCM_mldsa44_public_key) == sizeof(struct public_key<4>),
"MLDSA44 public key size incorrect");
static_assert(
alignof(struct BCM_mldsa44_public_key) == alignof(struct public_key<4>),
"MLDSA44 public key alignment incorrect");
return (struct public_key<4> *)external;
}
struct prehash_context *prehash_context_from_external_44(
struct BCM_mldsa44_prehash *external) {
static_assert(
sizeof(struct BCM_mldsa44_prehash) == sizeof(struct prehash_context),
"MLDSA pre-hash context size incorrect");
static_assert(
alignof(struct BCM_mldsa44_prehash) == alignof(struct prehash_context),
"MLDSA pre-hash context alignment incorrect");
return reinterpret_cast<prehash_context *>(external);
}
namespace fips {
#include "fips_known_values.inc"
@@ -2442,6 +2647,209 @@ bcm_status BCM_mldsa87_marshal_public_key(
out, mldsa::public_key_from_external_87(public_key)));
}
// ML-DSA-44 specific wrappers.
bcm_status BCM_mldsa44_parse_public_key(
struct BCM_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 BCM_mldsa44_marshal_private_key(
CBB *out, const struct BCM_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 BCM_mldsa44_parse_private_key(
struct BCM_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 BCM_mldsa44_check_key_fips(
struct BCM_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 BCM_mldsa44_generate_key(
uint8_t out_encoded_public_key[BCM_MLDSA44_PUBLIC_KEY_BYTES],
uint8_t out_seed[BCM_MLDSA_SEED_BYTES],
struct BCM_mldsa44_private_key *out_private_key) {
BCM_rand_bytes(out_seed, BCM_MLDSA_SEED_BYTES);
return BCM_mldsa44_generate_key_external_entropy(out_encoded_public_key,
out_private_key, out_seed);
}
bcm_status BCM_mldsa44_private_key_from_seed(
struct BCM_mldsa44_private_key *out_private_key,
const uint8_t seed[BCM_MLDSA_SEED_BYTES]) {
uint8_t public_key[BCM_MLDSA44_PUBLIC_KEY_BYTES];
return BCM_mldsa44_generate_key_external_entropy(public_key, out_private_key,
seed);
}
bcm_status BCM_mldsa44_generate_key_external_entropy(
uint8_t out_encoded_public_key[BCM_MLDSA44_PUBLIC_KEY_BYTES],
struct BCM_mldsa44_private_key *out_private_key,
const uint8_t entropy[BCM_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 BCM_mldsa44_generate_key_fips(
uint8_t out_encoded_public_key[BCM_MLDSA44_PUBLIC_KEY_BYTES],
uint8_t out_seed[BCM_MLDSA_SEED_BYTES],
struct BCM_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 BCM_mldsa44_generate_key_external_entropy_fips(
uint8_t out_encoded_public_key[BCM_MLDSA44_PUBLIC_KEY_BYTES],
struct BCM_mldsa44_private_key *out_private_key,
const uint8_t entropy[BCM_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 BCM_mldsa44_private_key_from_seed_fips(
struct BCM_mldsa44_private_key *out_private_key,
const uint8_t seed[BCM_MLDSA_SEED_BYTES]) {
uint8_t public_key[BCM_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 BCM_mldsa44_public_from_private(
struct BCM_mldsa44_public_key *out_public_key,
const struct BCM_mldsa44_private_key *private_key) {
return bcm_as_approved_status(mldsa_public_from_private(
mldsa::public_key_from_external_44(out_public_key),
mldsa::private_key_from_external_44(private_key)));
}
bcm_status BCM_mldsa44_sign_internal(
uint8_t out_encoded_signature[BCM_MLDSA44_SIGNATURE_BYTES],
const struct BCM_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));
}
// ML-DSA signature in randomized mode, filling the random bytes with
// |BCM_rand_bytes|.
bcm_status BCM_mldsa44_sign(
uint8_t out_encoded_signature[BCM_MLDSA44_SIGNATURE_BYTES],
const struct BCM_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));
const uint8_t context_prefix[2] = {0, static_cast<uint8_t>(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 BCM_mldsa44_prehash_init(struct BCM_mldsa44_prehash *out_prehash_ctx,
const struct BCM_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<uint8_t>(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 BCM_mldsa44_prehash_update(struct BCM_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 BCM_mldsa44_prehash_finalize(
uint8_t out_msg_rep[BCM_MLDSA_MU_BYTES],
struct BCM_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 BCM_mldsa44_sign_message_representative(
uint8_t out_encoded_signature[BCM_MLDSA44_SIGNATURE_BYTES],
const struct BCM_mldsa44_private_key *private_key,
const uint8_t msg_rep[BCM_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));
}
// FIPS 204, Algorithm 3 (`ML-DSA.Verify`).
bcm_status BCM_mldsa44_verify(const struct BCM_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<uint8_t>(context_len)};
return BCM_mldsa44_verify_internal(public_key, signature, msg, msg_len,
context_prefix, sizeof(context_prefix),
context, context_len);
}
bcm_status BCM_mldsa44_verify_internal(
const struct BCM_mldsa44_public_key *public_key,
const uint8_t encoded_signature[BCM_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 BCM_mldsa44_marshal_public_key(
CBB *out, const struct BCM_mldsa44_public_key *public_key) {
return bcm_as_approved_status(mldsa_marshal_public_key(
out, mldsa::public_key_from_external_44(public_key)));
}
int boringssl_self_test_mldsa() {
return mldsa::fips::keygen_self_test() && mldsa::fips::sign_self_test() &&
mldsa::fips::verify_self_test();
@@ -17,6 +17,7 @@
#include <assert.h>
#include <CCryptoBoringSSL_mem.h>
#include <algorithm>
#include "../aes/internal.h"
#include "../service_indicator/internal.h"
@@ -26,8 +27,122 @@
// 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,
@@ -35,7 +150,24 @@ CTR_DRBG_STATE *CTR_DRBG_new(const uint8_t entropy[CTR_DRBG_ENTROPY_LEN],
CTR_DRBG_STATE *drbg = reinterpret_cast<CTR_DRBG_STATE *>(
OPENSSL_malloc(sizeof(CTR_DRBG_STATE)));
if (drbg == NULL ||
!CTR_DRBG_init(drbg, entropy, personalization, personalization_len)) {
!CTR_DRBG_init(drbg, /*df=*/false, entropy, CTR_DRBG_ENTROPY_LEN,
/*nonce=*/nullptr, personalization, personalization_len)) {
CTR_DRBG_free(drbg);
return NULL;
}
return drbg;
}
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 = reinterpret_cast<CTR_DRBG_STATE *>(
OPENSSL_malloc(sizeof(CTR_DRBG_STATE)));
if (drbg == NULL ||
!CTR_DRBG_init(drbg, /*df=*/true, entropy, entropy_len, nonce,
personalization, personalization_len)) {
CTR_DRBG_free(drbg);
return NULL;
}
@@ -45,26 +177,45 @@ CTR_DRBG_STATE *CTR_DRBG_new(const uint8_t entropy[CTR_DRBG_ENTROPY_LEN],
void CTR_DRBG_free(CTR_DRBG_STATE *state) { OPENSSL_free(state); }
int CTR_DRBG_init(CTR_DRBG_STATE *drbg,
const uint8_t entropy[CTR_DRBG_ENTROPY_LEN],
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) {
// Section 10.2.1.3.1
if (personalization_len > CTR_DRBG_ENTROPY_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,6 +226,7 @@ int CTR_DRBG_init(CTR_DRBG_STATE *drbg,
seed_material[i] ^= kInitMask[i];
}
drbg->df = df;
drbg->ctr = aes_ctr_set_key(&drbg->ks, NULL, &drbg->block, seed_material, 32);
OPENSSL_memcpy(drbg->counter, seed_material + 32, 16);
drbg->reseed_counter = 1;
@@ -82,7 +234,7 @@ int CTR_DRBG_init(CTR_DRBG_STATE *drbg,
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
@@ -92,22 +244,15 @@ static void ctr32_add(CTR_DRBG_STATE *drbg, uint32_t n) {
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];
}
@@ -121,23 +266,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 +327,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 +355,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 +383,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;
}
@@ -37,14 +37,19 @@ struct ctr_drbg_state_st {
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],
// 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);
@@ -187,8 +187,7 @@ bcm_status BCM_rand_bytes_hwrng(uint8_t *buf, const size_t len) {
struct entropy_buffer {
// bytes contains entropy suitable for seeding a DRBG.
uint8_t
bytes[CRNGT_BLOCK_SIZE + CTR_DRBG_ENTROPY_LEN * BORINGSSL_FIPS_OVERREAD];
uint8_t bytes[CRNGT_BLOCK_SIZE + CTR_DRBG_SEED_LEN * BORINGSSL_FIPS_OVERREAD];
// bytes_valid indicates the number of bytes of |bytes| that contain valid
// data.
size_t bytes_valid;
@@ -250,11 +249,11 @@ static void get_seed_entropy(uint8_t *out_entropy, size_t out_entropy_len,
// fill |additional_input| with entropy to supplement |seed|. It sets
// |*out_additional_input_len| to the number of extra bytes.
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 seed[CTR_DRBG_SEED_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];
CTR_DRBG_SEED_LEN * BORINGSSL_FIPS_OVERREAD];
uint8_t *entropy = entropy_bytes;
size_t entropy_len = sizeof(entropy_bytes);
@@ -293,12 +292,12 @@ static void rand_get_seed(struct rand_thread_state *state,
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);
assert(entropy_len == BORINGSSL_FIPS_OVERREAD * CTR_DRBG_SEED_LEN);
OPENSSL_memcpy(seed, entropy, CTR_DRBG_SEED_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];
for (size_t j = 0; j < CTR_DRBG_SEED_LEN; j++) {
seed[j] ^= entropy[CTR_DRBG_SEED_LEN * i + j];
}
}
@@ -307,8 +306,8 @@ static void rand_get_seed(struct rand_thread_state *state,
// 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;
CRYPTO_sysrand_if_available(additional_input, CTR_DRBG_SEED_LEN)) {
*out_additional_input_len = CTR_DRBG_SEED_LEN;
}
}
@@ -318,12 +317,12 @@ static void rand_get_seed(struct rand_thread_state *state,
// fill |additional_input| with entropy to supplement |seed|. It sets
// |*out_additional_input_len| to the number of extra bytes.
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 seed[CTR_DRBG_SEED_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_for_seed(seed, CTR_DRBG_SEED_LEN);
*out_additional_input_len = 0;
}
@@ -384,13 +383,13 @@ bcm_infallible BCM_rand_bytes_with_additional_data(
}
state->last_block_valid = 0;
uint8_t seed[CTR_DRBG_ENTROPY_LEN];
uint8_t personalization[CTR_DRBG_ENTROPY_LEN] = {0};
uint8_t seed[CTR_DRBG_SEED_LEN];
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, 32u, seed + 32,
personalization, personalization_len)) {
abort();
}
state->calls = 0;
@@ -422,8 +421,8 @@ bcm_infallible BCM_rand_bytes_with_additional_data(
// 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 seed[CTR_DRBG_SEED_LEN];
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);
@@ -433,8 +432,9 @@ bcm_infallible BCM_rand_bytes_with_additional_data(
// |rand_thread_state_clear_all|.
CRYPTO_MUTEX_lock_read(&state->clear_drbg_lock);
#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;
@@ -178,16 +178,14 @@ int RSA_verify_PKCS1_PSS_mgf1(const RSA *rsa, const uint8_t *mHash,
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;
}
@@ -202,7 +200,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;
@@ -299,16 +297,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 {
@@ -18,6 +18,8 @@
#include <limits.h>
#include <string.h>
#include <iterator>
#include <CCryptoBoringSSL_bn.h>
#include <CCryptoBoringSSL_digest.h>
#include <CCryptoBoringSSL_engine.h>
@@ -276,12 +278,6 @@ void RSA_get0_factors(const RSA *rsa, const BIGNUM **out_p,
}
}
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) {
@@ -875,8 +871,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<BN_ULONG *>(kSmallFactorsLimbs);
out->width = std::size(kSmallFactorsLimbs);
out->dmax = out->width;
out->neg = 0;
out->flags = BN_FLG_STATIC_DATA;
@@ -18,6 +18,8 @@
#include <limits.h>
#include <string.h>
#include <iterator>
#include <CCryptoBoringSSL_bn.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
@@ -840,7 +842,7 @@ const BN_ULONG kBoringSSLRSASqrtTwo[] = {
TOBN(0xed17ac85, 0x83339915), TOBN(0x1d6f60ba, 0x893ba84c),
TOBN(0x597d89b3, 0x754abe9f), TOBN(0xb504f333, 0xf9de6484),
};
const size_t kBoringSSLRSASqrtTwoLen = OPENSSL_ARRAY_SIZE(kBoringSSLRSASqrtTwo);
const size_t kBoringSSLRSASqrtTwoLen = std::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
@@ -1183,9 +1185,7 @@ static int RSA_generate_key_ex_maybe_fips(RSA *rsa, int bits,
return 0;
}
RSA *tmp = NULL;
uint32_t err;
int ret = 0;
bssl::UniquePtr<RSA> tmp;
// |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
@@ -1195,27 +1195,25 @@ static int RSA_generate_key_ex_maybe_fips(RSA *rsa, int bits,
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(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);
} 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);
@@ -1235,11 +1233,7 @@ static int RSA_generate_key_ex_maybe_fips(RSA *rsa, int bits,
replace_bignum(&rsa->dmq1_fixed, &tmp->dmq1_fixed);
replace_bignum(&rsa->iqmp_mont, &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,
@@ -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;
}
}
@@ -17,6 +17,8 @@
#include <stdio.h>
#include <stdlib.h>
#include <iterator>
#include <CCryptoBoringSSL_aead.h>
#include <CCryptoBoringSSL_aes.h>
#include <CCryptoBoringSSL_bn.h>
@@ -269,7 +271,7 @@ 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)) {
goto err;
@@ -569,7 +571,7 @@ 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();
@@ -840,11 +842,14 @@ static int boringssl_self_test_fast(void) {
}
// 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 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',
@@ -852,12 +857,12 @@ static int boringssl_self_test_fast(void) {
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,
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,
@@ -866,21 +871,23 @@ static int boringssl_self_test_fast(void) {
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,
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;
if (!CTR_DRBG_init(&drbg, kDRBGEntropy, kDRBGPersonalization,
if (!CTR_DRBG_init(&drbg, /*df=*/true, kDRBGEntropy, sizeof(kDRBGEntropy),
kDRBGNonce, kDRBGPersonalization,
sizeof(kDRBGPersonalization)) ||
!CTR_DRBG_generate(&drbg, output, sizeof(kDRBGOutput), kDRBGAD,
sizeof(kDRBGAD)) ||
!BORINGSSL_check_test(kDRBGOutput, output, sizeof(kDRBGOutput),
"DRBG Generate KAT") ||
!CTR_DRBG_reseed(&drbg, kDRBGEntropy2, kDRBGAD, sizeof(kDRBGAD)) ||
!CTR_DRBG_reseed_ex(&drbg, kDRBGEntropy2, sizeof(kDRBGEntropy2), kDRBGAD,
sizeof(kDRBGAD)) ||
!CTR_DRBG_generate(&drbg, output, sizeof(kDRBGReseedOutput), kDRBGAD,
sizeof(kDRBGAD)) ||
!BORINGSSL_check_test(kDRBGReseedOutput, output,
@@ -17,6 +17,9 @@
#include <CCryptoBoringSSL_base.h>
#if defined(__cplusplus)
extern "C" {
#endif
// FIPS_service_indicator_before_call and |FIPS_service_indicator_after_call|
// both currently return the same local thread counter which is slowly
@@ -37,6 +40,10 @@
OPENSSL_EXPORT uint64_t FIPS_service_indicator_before_call(void);
OPENSSL_EXPORT uint64_t FIPS_service_indicator_after_call(void);
#if defined(__cplusplus)
}
#endif
#if defined(BORINGSSL_FIPS)
// FIPS_service_indicator_update_state records that an approved service has been
@@ -217,7 +217,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.
@@ -40,8 +40,8 @@ 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;
return bcm_infallible::approved;
@@ -58,8 +58,8 @@ 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;
return bcm_infallible::approved;
@@ -75,8 +75,8 @@ 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;
return bcm_infallible::approved;
@@ -124,7 +124,6 @@ bcm_infallible BCM_sha512_transform(SHA512_CTX *c,
bcm_infallible BCM_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<const uint8_t *>(in_data);
@@ -132,14 +131,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;
@@ -195,8 +190,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);
@@ -17,7 +17,7 @@
#include <assert.h>
#include <string.h>
#include <CCryptoBoringSSL_sha.h>
#include <CCryptoBoringSSL_sha2.h>
#include "../../internal.h"
#include "./params.h"
+119 -2
View File
@@ -27,7 +27,8 @@
#include <CCryptoBoringSSL_hkdf.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_rand.h>
#include <CCryptoBoringSSL_sha.h>
#include <CCryptoBoringSSL_sha2.h>
#include <CCryptoBoringSSL_xwing.h>
#include "../fipsmodule/ec/internal.h"
#include "../internal.h"
@@ -35,7 +36,7 @@
// 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 {
@@ -601,6 +602,122 @@ const EVP_HPKE_KEM *EVP_hpke_p256_hkdf_sha256(void) {
return &kKEM;
}
#define XWING_PRIVATE_KEY_LEN 32
#define XWING_PUBLIC_KEY_LEN 1216
#define XWING_PUBLIC_VALUE_LEN 1120
#define XWING_SEED_LEN 64
#define XWING_SHARED_KEY_LEN 32
static int xwing_init_key(EVP_HPKE_KEY *key, const uint8_t *priv_key,
size_t priv_key_len) {
CBS cbs;
CBS_init(&cbs, priv_key, priv_key_len);
XWING_private_key private_key;
if (!XWING_parse_private_key(&private_key, &cbs) || CBS_len(&cbs) != 0) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR);
return 0;
}
if (!XWING_public_from_private(key->public_key, &private_key)) {
return 0;
}
if (priv_key_len > sizeof(key->private_key)) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR);
return 0;
}
OPENSSL_memcpy(key->private_key, priv_key, priv_key_len);
return 1;
}
static int xwing_generate_key(EVP_HPKE_KEY *key) {
XWING_private_key private_key;
if (!XWING_generate_key(key->public_key, &private_key)) {
return 0;
}
CBB cbb;
CBB_init_fixed(&cbb, key->private_key, XWING_PRIVATE_KEY_LEN);
if (!XWING_marshal_private_key(&cbb, &private_key) ||
CBB_len(&cbb) != XWING_PRIVATE_KEY_LEN) {
return 0;
}
return 1;
}
static int xwing_encap_with_seed(const EVP_HPKE_KEM *kem,
uint8_t *out_shared_secret,
size_t *out_shared_secret_len,
uint8_t *out_enc, size_t *out_enc_len,
size_t max_enc, const uint8_t *peer_public_key,
size_t peer_public_key_len,
const uint8_t *seed, size_t seed_len) {
if (max_enc < XWING_PUBLIC_VALUE_LEN) {
OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE);
return 0;
}
if (peer_public_key_len != XWING_PUBLIC_KEY_LEN ||
seed_len != XWING_SEED_LEN) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR);
return 0;
}
if (!XWING_encap_external_entropy(out_enc, out_shared_secret, peer_public_key,
seed)) {
OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR);
return 0;
}
*out_enc_len = XWING_PUBLIC_VALUE_LEN;
*out_shared_secret_len = XWING_SHARED_KEY_LEN;
return 1;
}
static int xwing_decap(const EVP_HPKE_KEY *key, uint8_t *out_shared_secret,
size_t *out_shared_secret_len, const uint8_t *enc,
size_t enc_len) {
if (enc_len != XWING_PUBLIC_VALUE_LEN) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR);
return 0;
}
CBS cbs;
CBS_init(&cbs, key->private_key, XWING_PRIVATE_KEY_LEN);
XWING_private_key private_key;
if (!XWING_parse_private_key(&private_key, &cbs)) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR);
return 0;
}
if (!XWING_decap(out_shared_secret, enc, &private_key)) {
OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR);
return 0;
}
*out_shared_secret_len = XWING_SHARED_KEY_LEN;
return 1;
}
const EVP_HPKE_KEM *EVP_hpke_xwing(void) {
static const EVP_HPKE_KEM kKEM = {
/*id=*/EVP_HPKE_XWING,
/*public_key_len=*/XWING_PUBLIC_KEY_LEN,
/*private_key_len=*/XWING_PRIVATE_KEY_LEN,
/*seed_len=*/XWING_SEED_LEN,
/*enc_len=*/XWING_PUBLIC_VALUE_LEN,
xwing_init_key,
xwing_generate_key,
xwing_encap_with_seed,
xwing_decap,
// 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,
};
return &kKEM;
}
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) {
+4 -2
View File
@@ -17,13 +17,15 @@
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <iterator>
#include <type_traits>
#include <CCryptoBoringSSL_bn.h>
#include <CCryptoBoringSSL_hmac.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_rand.h>
#include <CCryptoBoringSSL_sha.h>
#include <CCryptoBoringSSL_sha2.h>
#include "../internal.h"
#include "internal.h"
@@ -309,7 +311,7 @@ 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));
}
+66 -11
View File
@@ -23,6 +23,8 @@
#include <stdlib.h>
#include <string.h>
#include <type_traits>
#if defined(BORINGSSL_CONSTANT_TIME_VALIDATION)
#include <valgrind/memcheck.h>
#endif
@@ -50,6 +52,10 @@
#include <windows.h>
#endif
#if defined(_M_X64) || defined(_M_IX86)
#include "intrin.h"
#endif
#if defined(__cplusplus)
extern "C" {
#endif
@@ -100,8 +106,6 @@ typedef __uint128_t uint128_t;
#endif
#endif
#define OPENSSL_ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
// 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
@@ -527,8 +531,6 @@ OPENSSL_EXPORT void CRYPTO_once(CRYPTO_once_t *once, void (*init)(void));
using CRYPTO_atomic_u32 = std::atomic<uint32_t>;
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);
}
@@ -567,12 +569,6 @@ inline void CRYPTO_atomic_store_u32(CRYPTO_atomic_u32 *val, uint32_t desired) {
#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.
@@ -886,6 +882,16 @@ static inline void *OPENSSL_memset(void *dst, int c, size_t n) {
// 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_le(const void *in) {
uint16_t v;
OPENSSL_memcpy(&v, in, sizeof(v));
return v;
}
static inline void CRYPTO_store_u16_le(void *out, uint16_t v) {
OPENSSL_memcpy(out, &v, sizeof(v));
}
static inline uint16_t CRYPTO_load_u16_be(const void *in) {
uint16_t v;
OPENSSL_memcpy(&v, in, sizeof(v));
@@ -1444,6 +1450,9 @@ inline int CRYPTO_fuzzer_mode_enabled(void) { return 0; }
// 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,
@@ -1480,16 +1489,26 @@ inline uint64_t CRYPTO_addc_u64(uint64_t x, uint64_t y, uint64_t carry,
static 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) {
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);
@@ -1544,17 +1563,29 @@ inline uint64_t CRYPTO_subc_u64(uint64_t x, uint64_t y, uint64_t borrow,
static 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) {
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
@@ -1567,4 +1598,28 @@ static inline uint64_t CRYPTO_subc_u64(uint64_t x, uint64_t y, uint64_t borrow,
#endif
BSSL_NAMESPACE_BEGIN
// Cleanup implements a custom scope guard, when the cleanup logic does not fit
// in a destructor. Usage:
//
// bssl::Cleanup cleanup = [&] { SomeCleanupWork(local_var); };
template <typename F>
class Cleanup {
public:
static_assert(std::is_invocable_v<F>);
static_assert(std::is_same_v<std::invoke_result_t<F>, void>);
Cleanup(F func) : func_(func) {}
Cleanup(const Cleanup &) = delete;
Cleanup &operator=(const Cleanup &) = delete;
~Cleanup() { func_(); }
private:
F func_;
};
template <typename F>
Cleanup(F func) -> Cleanup<F>;
BSSL_NAMESPACE_END
#endif // OPENSSL_HEADER_CRYPTO_INTERNAL_H
Loaded 100 of 518 files, more files were not shown because too many files have changed in this diff. Show more