Compare commits

...
29 Commits
Author SHA1 Message Date
YOCKOW 9680b7251c Make memset_s consistent with Darwin. (#52)
Resolves [issue#51](https://github.com/apple/swift-crypto/issues/51).

In Swift 5.3, a warning is viewed on Linux because `memset_s` implemented in this module returns `Void`.
This commit let the function return the same type with Darwin.
2020-10-06 10:22:50 +01:00
Cory Benfield 3c632a678e Update BoringSSL to 67818bea6690a230e2f42e8a588e0f54949bbbf1 (#50) 2020-09-30 15:31:23 +01:00
Cory Benfield 7ba861aa8a We now use the main branch. (#49) 2020-09-24 18:03:00 +01:00
Cory Benfield afe4c9b5f6 Update BoringSSL to 54858b63c1d886f6c8d903d4a4f594f1485de189 (#47) 2020-08-03 15:57:04 +01:00
Cory Benfield d82f7d8ce8 Update to Developer Beta 3 build. (#46) 2020-07-31 19:50:26 +01:00
Tim Condon 6445f9fb06 Fix path to environment script (#44) 2020-07-03 18:01:46 +01:00
Tim Condon f8b6e4e17e Clarify the location of the line to comment out for macOS development (#42) 2020-07-03 09:59:19 +01:00
buttaface 68d56d2b3c DERTests: enable test function for Android (#41) 2020-06-27 21:01:37 +01:00
Cory Benfield 794901c991 Update Swift Crypto with API from CryptoKit @ WWDC20 (#40)
Motivation:

At WWDC 2020 Apple updated the CryptoKit APIs. This PR brings those new
APIs to Swift Crypto. This brings Swift Crypto up-to-date with the
latest CryptoKit API support, including PEM/DER key support and HKDF API
extensions.

Modifications:

- Bring forward the CryptoKit API files
- Update to have API match the WWDC seed.

Result:

Users will have access to the seed APIs.
2020-06-22 21:40:34 +01:00
Johannes Weiss 82503a48ce fix warnings in with newer Swift compilers (#37)
Motiviation:

One `let` was hiding as a `var` and a few `#file` parameters have been
forwarded to (now) `#filePath` ones.

Modification:

- make the `var` a `let`
- silence the `#file`/`#filePath` warning by adding `(#file)` because we
  can't forward them properly right now
  (https://bugs.swift.org/browse/SR-12934). That's okay because even on
  the Swift master branch, `#file` == `#filePath`.

Result:

No warnings in newer Swift compilers.
2020-06-15 13:52:24 +01:00
Cory Benfield 9b9d186860 Update BoringSSL to 53a17f55247101105ae35767d5c5a6c311843a8e (#36) 2020-06-02 09:39:37 +01:00
tomer doron 0a0b1d50e9 improve 5.3 docker setup (#35)
motivation: pin to 5.3 nighties 

changes: use swiftlang/swift:nightly-5.3-master-bionic instead of swiftlang/swift:nightly-master-bionic
2020-05-05 07:05:23 +01:00
tomer doron cce48362a4 update ci setup (#32)
motivation: 5.2 adoption, prepare for 5.3

changes:
* use 5.2 docker-compose setup
* add 5.3 docker-compose setup (placeholder)
* update format
2020-04-04 13:23:51 +01:00
Cory Benfield d67ac68d09 Update BoringSSL to 5298ef99bf2b2d77600b3bb74dd572027bf495be (#31) 2020-03-17 21:06:10 +00:00
tomer doronandCory Benfield 0473010f58 update docs generation script to work better with selinux (#30)
motivation: docs scripts is broken on selinux due to restriction on ssh-agent

changes:

* change the jazzy workspace to a directory accessible by the CI node so we can push from the agent instead of from the docker container
* dont remove older docs when pushing new ones
* add version inforamtion and source links

Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-03-04 15:24:29 +00:00
Cory Benfield 20053871fa Mitigate Folly/BoringSSL static linking issue. (#28)
Motivation:

BoringSSL and Folly both attempt to play silly buggers with the sdallocx
symbol defined in jemalloc. Unfortunately, they don't play nicely
together, and the end result if you have both present is that BoringSSL
will reliably SIGBUS or SIGSEGV on initialization. Naturally, this isn't
good.

See also apple/swift-nio-ssl#191.

Modifications:

- Resolve the issue by patching out BoringSSL's allocator optimisation.
- Update BoringSSL to 6432bb46ab44731567ec923e6c8fc182f13d0070.

Result:

Flow and BoringSSL will play better together.
2020-02-24 16:58:54 +00:00
Zev Eisenberg b6b60c3938 More idiomatic use of XCTest (#15) 2020-02-14 10:03:41 +00:00
Alexander Cyon 64a1a98e47 Search replace "CONTRIBUTORS.txt" -> "CONTRIBUTORS.md" (#24) 2020-02-06 11:28:29 +00:00
Alexander Cyon 3be1b8cbd4 [Github] Upgrading ISSUE_TEMPLATE to display 4 alternatives: Bug, Regression, Question or Feature Request (#21)
* Replaced ISSUE_TEMPLATE.md with directory containing four different issues types. Adding script for extraction of enviroment info, in order to make it easier for users to report issues.

* Updating year in sanity script
2020-02-06 10:48:55 +00:00
Alexander Cyon 77b30226ac Adding MARK delimiter for different curves within gyb generated files. (#19) 2020-02-06 10:22:29 +00:00
Alexander Cyon de232cbd67 Adding gyb discrepancy check to sanity script. (#13)
* 1) Adding gyb to scripts
2) Adding warning in gyb files about gyb overwritting manual edits to gyb generated swift files
3) Updated README with gyb instructions
4) Adding script for running all gyb generation
5) Adding CI check for discrepancies in gyb generated files

* Updating Dockerfile
2020-02-05 17:44:21 +00:00
Sindre Sorhus 36ea42cbb3 Hint to GitHub about vendored BoringSSL code (#17) 2020-02-04 21:43:43 +00:00
Alexander Cyon 5000bef967 Cyon fix typos (#16)
* Fixing several typos

* add math/code formatting of Weierstrass equation in docs.
2020-02-04 16:00:23 +00:00
Alexander Cyon d237bf149c Adding .mailmap (#14)
Renaming file `CONTRIBUTORS.txt` -> `CONTRIBUTORS.md`
Updating MARKDOWN format
Adding reference to mailmap docs.
2020-02-04 14:39:17 +00:00
Cory Benfield 94930a7edf Clean up rendering of project name in the README (#12) 2020-02-04 11:56:03 +00:00
Alexander Cyon 12e6f9ef3a Add '.xcodesamplecode.plist' file to achieve proper markdown rendering (#11) 2020-02-04 11:44:45 +00:00
Austin Conlon 132b8e5fd1 Give Feedback Assistant a relevant link (#10) 2020-02-04 07:37:37 +00:00
George Barnett fced1f801f Update GitHub issue template (#7)
Motivation:

The GitHub issue template asks for the SwiftLog version/commit hash.
This isn't the SwiftLog project.

Modifications:

Replace SwiftLog with SwiftCrypto in the issue template.

Result:

The GitHub issue template is more relevant to the project.
2020-02-03 19:33:58 +00:00
tomer doron bfb37dfb92 improve docker security (#6)
motivation: more secured ci setup

changes:
* enable :z selinux flag on bind mounts so we can enable selinux on ci
* drop potentially exploitable capabilities from docker-compose
2020-01-31 09:32:14 +00:00
295 changed files with 33567 additions and 18029 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
Sources/CCryptoBoringSSL/* linguist-vendored
-20
View File
@@ -1,20 +0,0 @@
### Expected behavior
_[what you expected to happen]_
### Actual behavior
_[what actually happened]_
### Steps to reproduce
1. ...
2. ...
### If possible, minimal yet complete reproducer code (or URL to code)
_[anything to help us reproducing the issue]_
### SwiftLog version/commit hash
_[the SwiftLog tag/commit hash]_
### Swift & OS version (output of `swift --version && uname -a`)
+40
View File
@@ -0,0 +1,40 @@
---
name: 🐛 Bug Report
about: If something isn't working as expected
---
<!-- 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] -->
### New Issue Checklist
- [ ] I'm using the latest version of Swift Crypto (master branch)
- [ ] I read the [Contribution Guidelines](https://github.com/apple/swift-crypto/blob/master/CONTRIBUTING.md)
- [ ] I searched for [existing GitHub issues](https://github.com/apple/swift-crypto/issues)
### Expected behavior
_[what you expected to happen]_
### Actual behavior
_[what actually happened]_
### Steps to reproduce
1. ...
2. ...
### If possible, minimal yet complete reproducer code (or URL to code)
_[anything to help us reproducing the issue]_
### Swift Crypto version/commit hash
_[the Swift Crypto tag/commit hash]_
### Environment
Stand in the root of the repo and run `./scripts/environment.sh` and paste the output below
<details>
<pre>PLEASE_REPLACE_THIS_STIRNG_WITH_OUTPUT_OF_script_environments_THAT_IS_IN_YOUR_PASTEBOARD</pre>
</details>
+15
View File
@@ -0,0 +1,15 @@
---
name: 💡 Feature Request
about: A suggestion for a new feature
---
### New API Proposal: <Feature Name>
#### Motivation:
<What use-case is this API proposal trying to serve? Are there any protocols in existence that require this API? If so, which? Please provide links to specifications where applicable, or peer implementations when attempting to perform interop work.>
#### Importance:
<Does this API unlock entirely new use-cases, or is it possible to achieve the same functionality with existing API, but in easier ways?>
+18
View File
@@ -0,0 +1,18 @@
---
name: ❓ Support Question
about: Not sure how something works or how to implement some functionality? Ask us here! (But please check the docs first)
---
### Question Checklist
- [ ] I'm using the latest version of Swift Crypto (master branch)
- [ ] I read the [Contribution Guidelines](https://github.com/apple/swift-crypto/blob/master/CONTRIBUTING.md)
- [ ] I searched for [existing GitHub issues](https://github.com/apple/swift-crypto/issues)
### Question Subject
<!-- What tool/action do you have a question about? -->
<!-- Is this a question about documentation? -->
#### Question Description
<!-- Please include expected behavior and any relevant code samples with your question if possible -->
+33
View File
@@ -0,0 +1,33 @@
---
name: 😱 Regression
about: If a recent release broke a feature (Please make sure you know the last known working release version)
---
<!-- 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] -->
### New Regression Checklist
- [ ] I'm using the latest version of Swift Crypto (master branch)
- [ ] I read the [Contribution Guidelines](https://github.com/apple/swift-crypto/blob/master/CONTRIBUTING.md)
- [ ] I searched for [existing GitHub issues](https://github.com/apple/swift-crypto/issues)
### Regression Information
<!-- Knowing the breaking versions and last working versions helps us track down the regression easier -->
- Breaking version: [e.g. `2.x.x`]
- Last working version: [e.g. `2.x.x`]
### Regression Description
<!-- Please include what's happening, expected behavior, and any relevant code samples -->
### Swift Crypto version/commit hash
_[the Swift Crypto tag/commit hash]_
### Environment
Stand in the root of the repo and run `./scripts/environment.sh` and paste the output below
<details>
<pre>PLEASE_REPLACE_THIS_STIRNG_WITH_OUTPUT_OF_script_environments_THAT_IS_IN_YOUR_PASTEBOARD</pre>
</details>
+12 -1
View File
@@ -1,5 +1,16 @@
_[One line description of your change]_
<!-- 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
- [ ] I've followed the code style of the rest of the project
- [ ] 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 `.script/generate_boilerplate_files_with_gyb` and included updated generated files in a commit of this pull request
### Motivation:
_[Explain here the context, and why you're making that change. What is the problem you're trying to solve.]_
@@ -10,4 +21,4 @@ _[Describe the modifications you've done.]_
### Result:
_[After your change, what will change.]_
_[After your change, what will change.]_
+1
View File
@@ -10,3 +10,4 @@ Package.resolved
.podspecs
DerivedData
.swiftpm
**/gyb.pyc
+2
View File
@@ -0,0 +1,2 @@
Alexander Cyon <alex.cyon@gmail.com> <Sajjon@users.noreply.github.com>
Tomer Doron <tomer@apple.com>
+1 -1
View File
@@ -1,5 +1,6 @@
# file options
--swiftversion 5.0
--exclude .build
# format options
@@ -7,7 +8,6 @@
--self insert
--patternlet inline
--stripunusedargs unnamed-only
--comments ignore
--ifdef no-indent
# rules
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array/>
</plist>
+7 -2
View File
@@ -11,8 +11,13 @@ needs to be listed here.
### Contributors
- Alexander Cyon <alex.cyon@gmail.com>
- Austin Conlon <austinconlon@icloud.com>
- Cory Benfield <lukasa@apple.com>
- George Barnett <gbrntt@gmail.com>
- Tomer Doron <tomer@apple.com>
**Updating this list**
## Updating this list
Please do not edit this file manually. It is generated using `./scripts/generate_contributors_list.sh`. If a name is misspelled or appearing multiple times: add an entry in `./.mailmap`
Please do not edit this file manually. It is generated using `./scripts/generate_contributors_list.sh`.
If a name is misspelled or appearing multiple times: add an entry in `./.mailmap` (see [docs](https://git-scm.com/docs/git-shortlog#_mapping_authors))
+2 -2
View File
@@ -7,7 +7,7 @@
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
@@ -20,7 +20,7 @@
// Sources/CCryptoBoringSSL directory. The source repository is at
// https://boringssl.googlesource.com/boringssl.
//
// BoringSSL Commit: 0416e8c3055c7fcfd6c3eab4c127a36df1e6097b
// BoringSSL Commit: 67818bea6690a230e2f42e8a588e0f54949bbbf1
import PackageDescription
+56 -28
View File
@@ -1,84 +1,112 @@
# SwiftCrypto
# Swift Crypto
SwiftCrypto is an open-source implementation of a substantial portion of the API of [Apple CryptoKit](https://developer.apple.com/documentation/cryptokit) suitable for use on Linux platforms. It enables cross-platform or server applications with the advantages of CryptoKit.
Swift Crypto is an open-source implementation of a substantial portion of the API of [Apple CryptoKit](https://developer.apple.com/documentation/cryptokit) suitable for use on Linux platforms. It enables cross-platform or server applications with the advantages of CryptoKit.
## Functionality
SwiftCrypto exposes the portions of the CryptoKit API that do not rely on specialised hardware to any Swift application. It provides safe APIs that abstract over the complexity of many cryptographic primitives that need to be used in modern applications. These APIs encourage safe usages of the underlying primitives, follow cryptographic best practices, and should be the first choice for building applications that need to use cryptography.
Swift Crypto exposes the portions of the CryptoKit API that do not rely on specialised hardware to any Swift application. It provides safe APIs that abstract over the complexity of many cryptographic primitives that need to be used in modern applications. These APIs encourage safe usages of the underlying primitives, follow cryptographic best practices, and should be the first choice for building applications that need to use cryptography.
The current features of SwiftCrypto cover key exchange, key derivation, encryption and decryption, hashing, message authentication, and more.
The current features of Swift Crypto cover key exchange, key derivation, encryption and decryption, hashing, message authentication, and more.
For specific API documentation, please see our documentation.
## Implementation
SwiftCrypto compiles in two distinct modes depending on the platform for which it is being built.
Swift Crypto compiles in two distinct modes depending on the platform for which it is being built.
When building SwiftCrypto for use on an Apple platform where CryptoKit is already available, SwiftCrypto compiles its entire API surface down to nothing and simply re-exports the API of CryptoKit. This means that when using Apple platforms SwiftCrypto simply delegates all work to the core implementation of CryptoKit, as though SwiftCrypto was not even there.
When building Swift Crypto for use on an Apple platform where CryptoKit is already available, Swift Crypto compiles its entire API surface down to nothing and simply re-exports the API of CryptoKit. This means that when using Apple platforms Swift Crypto simply delegates all work to the core implementation of CryptoKit, as though Swift Crypto was not even there.
When building SwiftCrypto for use on Linux, SwiftCrypto builds substantially more code. In particular, we build:
When building Swift Crypto for use on Linux, Swift Crypto builds substantially more code. In particular, we build:
1. A vendored copy of BoringSSL's libcrypto.
2. The common API of SwiftCrypto and CryptoKit.
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 SwiftCrypto. The backing BoringSSL-based implementation is unique to SwiftCrypto.
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.
## Evolution
The vast majority of the SwiftCrypto code is intended to remain in lockstep with the current version of Apple CryptoKit. For this reason, patches that extend the API of SwiftCrypto will be evaluated cautiously. For any such extension there are two possible outcomes for adding the API.
The vast majority of the Swift Crypto code is intended to remain in lockstep with the current version of Apple CryptoKit. For this reason, patches that extend the API of Swift Crypto will be evaluated cautiously. For any such extension there are two possible outcomes for adding the API.
Firstly, if the API is judged to be generally valuable and suitable for contribution to Apple CryptoKit, the API will be merged into a Staging namespace in SwiftCrypto. This Staging namespace is a temporary home for any API that is expected to become available in Apple CryptoKit but that is not available today. This enables users to use the API soon after merging. When the API is generally available in CryptoKit the API will be deprecated in the Staging namespace and made available in the main SwiftCrypto namespace.
Firstly, if the API is judged to be generally valuable and suitable for contribution to Apple CryptoKit, the API will be merged into a Staging namespace in Swift Crypto. This Staging namespace is a temporary home for any API that is expected to become available in Apple CryptoKit but that is not available today. This enables users to use the API soon after merging. When the API is generally available in CryptoKit the API will be deprecated in the Staging namespace and made available in the main Swift Crypto namespace.
Secondly, if the API is judged not to meet the criteria for acceptance in general CryptoKit but is sufficiently important to have available for server use-cases, it will be merged into a Server namespace. APIs are not expected to leave this namespace, as it indicates that they are not generally available but can only be accessed when using SwiftCrypto.
Secondly, if the API is judged not to meet the criteria for acceptance in general CryptoKit but is sufficiently important to have available for server use-cases, it will be merged into a Server namespace. APIs are not expected to leave this namespace, as it indicates that they are not generally available but can only be accessed when using Swift Crypto.
Note that SwiftCrypto does not intend to support all possible cryptographic primitives. SwiftCrypto will focus on safe, modern cryptographic primitives that are broadly useful and that do not easily lend themselves to misuse. This means that some cryptographic algorithms may never be supported: for example, 3DES is highly unlikely to ever be supported by SwiftCrypto due to the difficulty of safely deploying it and its legacy status. Please be aware when proposing the addition of new primitives to SwiftCrypto that the proposal may be refused for this reason.
Note that Swift Crypto does not intend to support all possible cryptographic primitives. Swift Crypto will focus on safe, modern cryptographic primitives that are broadly useful and that do not easily lend themselves to misuse. This means that some cryptographic algorithms may never be supported: for example, 3DES is highly unlikely to ever be supported by Swift Crypto due to the difficulty of safely deploying it and its legacy status. Please be aware when proposing the addition of new primitives to Swift Crypto that the proposal may be refused for this reason.
### Code Organisation
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring` or are in a `BoringSSL` directory, or if they are not.
Files that meet the above criteria are specific to the SwiftCrypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or access a BoringSSL API, it needs to be marked this way.
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or access a BoringSSL API, it needs to be marked this way.
Files that do not have the `_boring` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
### Contributing New Primitives
## Contributing
To contribute a new cryptographic primitive to SwiftCrypto, you should address the following questions:
Before contributing please read [CONTRIBUTING.md](CONTRIBUTING.md), also make sure to read the two following sections.
#### Contributing new primitives
To contribute a new cryptographic primitive to Swift Crypto, you should address the following questions:
1. What is the new primitive for?
2. How widely is it deployed?
3. Is it specified in any public specifications or used by any such specification?
4. How easy is it to misuse?
5. In what way does SwiftCrypto fail to satisfy that use-case today?
5. In what way does Swift Crypto fail to satisfy that use-case today?
In addition, new primitive implementations will only be accepted in cases where the implementation is thoroughly tested, including being tested with all currently available test vectors. If the [Wycheproof](https://github.com/google/wycheproof) project provides vectors for the algorithm those should be tested as well. It must be possible to ensure that we can appropriately regression test our implementations.
### Contributing bug fixes
#### Contributing bug fixes
If you discover a bug with SwiftCrypto, please report it via GitHub.
If you discover a bug with Swift Crypto, please report it via GitHub.
If you are interested in fixing a bug, feel free to open a pull request. Please also submit regression tests with bug fixes to ensure that they are not regressed in future.
If you have issues with CryptoKit, instead of Swift Crypto, please use Feedback Assistant to file those issues as you normally would.
If you have issues with CryptoKit, instead of Swift Crypto, please use [Feedback Assistant](https://feedbackassistant.apple.com) to file those issues as you normally would.
### Get started contributing
#### `gyb`
Some of the files in this project are autogenerated (metaprogramming) using the Swift Utils tools called [gyb](https://github.com/apple/swift/blob/main/utils/gyb.py) (_"generate your boilerplate"_). `gyb` is included in [`./scripts/gyb`](scripts/gyb).
`gyb` will generate some `Foobar.swift` Swift file from some `Foobar.swift.gyb` _template_ file. **You should not edit `Foobar.swift` directly**, since all manual edits in that generated file will be overwritten the next time `gyb` is run.
You run `gyb` for a single file like so:
```bash
./scripts/gyb --line-directive "" Sources/Foobar.swift.gyb -o Sources/Foobar.swift
```
More conveniently you can run the bash script `./scripts/generate_boilerplate_files_with_gyb.sh` to generate all Swift files from their corresponding gyb template.
**If you add a new `.gyb` file, you should append a `// MARK: - Generated file, do NOT edit` warning** inside it, e.g.
```swift
// MARK: - Generated file, do NOT edit
// any edits of this file WILL be overwritten and thus discarded
// see section `gyb` in `README` for details.
```
### Security
If you believe you have identified a vulnerability in swift-crypto, please [report that vulnerability to Apple through the usual channel](https://support.apple.com/en-us/HT201220).
If you believe you have identified a vulnerability in Swift Crypto, please [report that vulnerability to Apple through the usual channel](https://support.apple.com/en-us/HT201220).
### Swift versions
SwiftCrypto supports Swift 5.1 and later.
Swift Crypto supports Swift 5.1 and later.
### Compatibility
SwiftCrypto follows [SemVer 2.0.0](https://semver.org/#semantic-versioning-200). Our public API is the same as that of CryptoKit (except where we lack an implementation entirely), as well as everything in the Server and Staging namespaces. We do not maintain a stable ABI, as SwiftCrypto is a source-only distribution.
Swift Crypto follows [SemVer 2.0.0](https://semver.org/#semantic-versioning-200). Our public API is the same as that of CryptoKit (except where we lack an implementation entirely), as well as everything in the Server and Staging namespaces. We do not maintain a stable ABI, as Swift Crypto is a source-only distribution.
What this means for you is that you should depend on SwiftCrypto with a version range that covers everything from the minimum SwiftCrypto version you require up to the next major version.
In SwiftPM that can be easily done specifying for example `from: "1.0.0"` meaning that you support SwiftCrypto in every version starting from 1.0.0 up to (excluding) 2.0.0.
SemVer and SwiftCrypto's Public API guarantees should result in a working program without having to worry about testing every single version for compatibility.
What this means for you is that you should depend on Swift Crypto with a version range that covers everything from the minimum Swift Crypto version you require up to the next major version.
In SwiftPM that can be easily done specifying for example `from: "1.0.0"` meaning that you support Swift Crypto in every version starting from 1.0.0 up to (excluding) 2.0.0.
SemVer and Swift Crypto's Public API guarantees should result in a working program without having to worry about testing every single version for compatibility.
### Developing SwiftCrypto on macOS
### Developing Swift Crypto on macOS
SwiftCrypto normally defers to the OS implementation of CryptoKit on macOS. Naturally, this makes developing SwiftCrypto on macOS tricky. To get SwiftCrypto to build the open source implementation on macOS, uncomment the line that reads: `//.define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API")`, as this will force SwiftCrypto to build its public API.
Swift Crypto normally defers to the OS implementation of CryptoKit on macOS. Naturally, this makes developing Swift Crypto on macOS tricky. To get Swift Crypto to build the open source implementation on macOS, in `Package.swift`, uncomment the line that reads: `//.define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API")`, as this will force Swift Crypto to build its public API.
@@ -70,7 +70,7 @@ int ASN1_BIT_STRING_set(ASN1_BIT_STRING *x, unsigned char *d, int len)
return M_ASN1_BIT_STRING_set(x, d, len);
}
int i2c_ASN1_BIT_STRING(ASN1_BIT_STRING *a, unsigned char **pp)
int i2c_ASN1_BIT_STRING(const ASN1_BIT_STRING *a, unsigned char **pp)
{
int ret, j, bits, len;
unsigned char *p, *d;
@@ -233,7 +233,7 @@ int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value)
return (1);
}
int ASN1_BIT_STRING_get_bit(ASN1_BIT_STRING *a, int n)
int ASN1_BIT_STRING_get_bit(const ASN1_BIT_STRING *a, int n)
{
int w, v;
@@ -250,7 +250,7 @@ int ASN1_BIT_STRING_get_bit(ASN1_BIT_STRING *a, int n)
* which is not specified in 'flags', 1 otherwise.
* 'len' is the length of 'flags'.
*/
int ASN1_BIT_STRING_check(ASN1_BIT_STRING *a,
int ASN1_BIT_STRING_check(const ASN1_BIT_STRING *a,
unsigned char *flags, int flags_len)
{
int i, ok;
@@ -108,7 +108,7 @@ int ASN1_ENUMERATED_set(ASN1_ENUMERATED *a, long v)
return (1);
}
long ASN1_ENUMERATED_get(ASN1_ENUMERATED *a)
long ASN1_ENUMERATED_get(const ASN1_ENUMERATED *a)
{
int neg = 0, i;
@@ -147,7 +147,7 @@ long ASN1_ENUMERATED_get(ASN1_ENUMERATED *a)
return r;
}
ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(BIGNUM *bn, ASN1_ENUMERATED *ai)
ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(const BIGNUM *bn, ASN1_ENUMERATED *ai)
{
ASN1_ENUMERATED *ret;
int len, j;
@@ -183,7 +183,7 @@ ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(BIGNUM *bn, ASN1_ENUMERATED *ai)
return (NULL);
}
BIGNUM *ASN1_ENUMERATED_to_BN(ASN1_ENUMERATED *ai, BIGNUM *bn)
BIGNUM *ASN1_ENUMERATED_to_BN(const ASN1_ENUMERATED *ai, BIGNUM *bn)
{
BIGNUM *ret;
+1 -1
View File
@@ -115,7 +115,7 @@ int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y)
* followed by optional zeros isn't padded.
*/
int i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp)
int i2c_ASN1_INTEGER(const ASN1_INTEGER *a, unsigned char **pp)
{
int pad = 0, ret, i, neg;
unsigned char *p, *n, pb = 0;
@@ -66,7 +66,7 @@
#include "../internal.h"
int i2d_ASN1_OBJECT(ASN1_OBJECT *a, unsigned char **pp)
int i2d_ASN1_OBJECT(const ASN1_OBJECT *a, unsigned char **pp)
{
unsigned char *p, *allocated = NULL;
int objsize;
@@ -98,12 +98,12 @@ int i2d_ASN1_OBJECT(ASN1_OBJECT *a, unsigned char **pp)
return objsize;
}
int i2t_ASN1_OBJECT(char *buf, int buf_len, ASN1_OBJECT *a)
int i2t_ASN1_OBJECT(char *buf, int buf_len, const ASN1_OBJECT *a)
{
return OBJ_obj2txt(buf, buf_len, a, 0);
}
int i2a_ASN1_OBJECT(BIO *bp, ASN1_OBJECT *a)
int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a)
{
char buf[80], *p = buf;
int i;
@@ -100,7 +100,7 @@ ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, time_t t,
return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
}
int ASN1_TIME_check(ASN1_TIME *t)
int ASN1_TIME_check(const ASN1_TIME *t)
{
if (t->type == V_ASN1_GENERALIZEDTIME)
return ASN1_GENERALIZEDTIME_check(t);
@@ -110,7 +110,7 @@ int ASN1_TIME_check(ASN1_TIME *t)
}
/* Convert an ASN1_TIME structure to GeneralizedTime */
ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(ASN1_TIME *t,
ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *t,
ASN1_GENERALIZEDTIME **out)
{
ASN1_GENERALIZEDTIME *ret = NULL;
@@ -61,7 +61,7 @@
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_obj.h>
int ASN1_TYPE_get(ASN1_TYPE *a)
int ASN1_TYPE_get(const ASN1_TYPE *a)
{
if ((a->value.ptr != NULL) || (a->type == V_ASN1_NULL))
return (a->type);
@@ -424,13 +424,7 @@ int ASN1_STRING_length(const ASN1_STRING *x)
return M_ASN1_STRING_length(x);
}
void ASN1_STRING_length_set(ASN1_STRING *x, int len)
{
M_ASN1_STRING_length_set(x, len);
return;
}
int ASN1_STRING_type(ASN1_STRING *x)
int ASN1_STRING_type(const ASN1_STRING *x)
{
return M_ASN1_STRING_type(x);
}
@@ -93,7 +93,7 @@ ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, ASN1_STRING **oct)
/* Extract an ASN1 object from an ASN1_STRING */
void *ASN1_item_unpack(ASN1_STRING *oct, const ASN1_ITEM *it)
void *ASN1_item_unpack(const ASN1_STRING *oct, const ASN1_ITEM *it)
{
const unsigned char *p;
void *ret;
@@ -60,7 +60,7 @@
/* Based on a_int.c: equivalent ENUMERATED functions */
int i2a_ASN1_ENUMERATED(BIO *bp, ASN1_ENUMERATED *a)
int i2a_ASN1_ENUMERATED(BIO *bp, const ASN1_ENUMERATED *a)
{
int i, n = 0;
static const char *h = "0123456789ABCDEF";
+1 -1
View File
@@ -58,7 +58,7 @@
#include <CCryptoBoringSSL_bio.h>
int i2a_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *a)
int i2a_ASN1_INTEGER(BIO *bp, const ASN1_INTEGER *a)
{
int i, n = 0;
static const char *h = "0123456789ABCDEF";
@@ -58,7 +58,7 @@
#include <CCryptoBoringSSL_bio.h>
int i2a_ASN1_STRING(BIO *bp, ASN1_STRING *a, int type)
int i2a_ASN1_STRING(BIO *bp, const ASN1_STRING *a, int type)
{
int i, n = 0;
static const char *h = "0123456789ABCDEF";
@@ -447,6 +447,10 @@ int CBB_add_u16(CBB *cbb, uint16_t value) {
return cbb_buffer_add_u(cbb->base, value, 2);
}
int CBB_add_u16le(CBB *cbb, uint16_t value) {
return CBB_add_u16(cbb, CRYPTO_bswap2(value));
}
int CBB_add_u24(CBB *cbb, uint32_t value) {
if (!CBB_flush(cbb)) {
return 0;
@@ -463,6 +467,10 @@ int CBB_add_u32(CBB *cbb, uint32_t value) {
return cbb_buffer_add_u(cbb->base, value, 4);
}
int CBB_add_u32le(CBB *cbb, uint32_t value) {
return CBB_add_u32(cbb, CRYPTO_bswap4(value));
}
int CBB_add_u64(CBB *cbb, uint64_t value) {
if (!CBB_flush(cbb)) {
return 0;
@@ -470,6 +478,10 @@ int CBB_add_u64(CBB *cbb, uint64_t value) {
return cbb_buffer_add_u(cbb->base, value, 8);
}
int CBB_add_u64le(CBB *cbb, uint64_t value) {
return CBB_add_u64(cbb, CRYPTO_bswap8(value));
}
void CBB_discard_child(CBB *cbb) {
if (cbb->child == NULL) {
return;
@@ -120,6 +120,14 @@ int CBS_get_u16(CBS *cbs, uint16_t *out) {
return 1;
}
int CBS_get_u16le(CBS *cbs, uint16_t *out) {
if (!CBS_get_u16(cbs, out)) {
return 0;
}
*out = CRYPTO_bswap2(*out);
return 1;
}
int CBS_get_u24(CBS *cbs, uint32_t *out) {
uint64_t v;
if (!cbs_get_u(cbs, &v, 3)) {
@@ -138,10 +146,26 @@ int CBS_get_u32(CBS *cbs, uint32_t *out) {
return 1;
}
int CBS_get_u32le(CBS *cbs, uint32_t *out) {
if (!CBS_get_u32(cbs, out)) {
return 0;
}
*out = CRYPTO_bswap4(*out);
return 1;
}
int CBS_get_u64(CBS *cbs, uint64_t *out) {
return cbs_get_u(cbs, out, 8);
}
int CBS_get_u64le(CBS *cbs, uint64_t *out) {
if (!cbs_get_u(cbs, out, 8)) {
return 0;
}
*out = CRYPTO_bswap8(*out);
return 1;
}
int CBS_get_last_u8(CBS *cbs, uint8_t *out) {
if (cbs->len == 0) {
return 0;
@@ -35,6 +35,7 @@ Lone:
.align 5
_ChaCha20_ctr32:
AARCH64_VALID_CALL_TARGET
cbz x2,Labort
#if __has_feature(hwaddress_sanitizer) && __clang_major__ >= 10
adrp x5,:pg_hi21_nc:_OPENSSL_armcap_P
@@ -48,6 +49,7 @@ _ChaCha20_ctr32:
b.ne ChaCha20_neon
Lshort:
AARCH64_SIGN_LINK_REGISTER
stp x29,x30,[sp,#-96]!
add x29,sp,#0
@@ -260,6 +262,7 @@ Loop:
ldp x25,x26,[x29,#64]
ldp x27,x28,[x29,#80]
ldp x29,x30,[sp],#96
AARCH64_VALIDATE_LINK_REGISTER
Labort:
ret
@@ -316,12 +319,14 @@ Loop_tail:
ldp x25,x26,[x29,#64]
ldp x27,x28,[x29,#80]
ldp x29,x30,[sp],#96
AARCH64_VALIDATE_LINK_REGISTER
ret
.align 5
ChaCha20_neon:
AARCH64_SIGN_LINK_REGISTER
stp x29,x30,[sp,#-96]!
add x29,sp,#0
@@ -702,6 +707,7 @@ Loop_neon:
ldp x25,x26,[x29,#64]
ldp x27,x28,[x29,#80]
ldp x29,x30,[sp],#96
AARCH64_VALIDATE_LINK_REGISTER
ret
Ltail_neon:
@@ -811,11 +817,13 @@ Ldone_neon:
ldp x25,x26,[x29,#64]
ldp x27,x28,[x29,#80]
ldp x29,x30,[sp],#96
AARCH64_VALIDATE_LINK_REGISTER
ret
.align 5
ChaCha20_512_neon:
AARCH64_SIGN_LINK_REGISTER
stp x29,x30,[sp,#-96]!
add x29,sp,#0
@@ -1979,6 +1987,7 @@ Ldone_512_neon:
ldp x25,x26,[x29,#64]
ldp x27,x28,[x29,#80]
ldp x29,x30,[sp],#96
AARCH64_VALIDATE_LINK_REGISTER
ret
#endif // !OPENSSL_NO_ASM
@@ -36,6 +36,7 @@
.type ChaCha20_ctr32,%function
.align 5
ChaCha20_ctr32:
AARCH64_VALID_CALL_TARGET
cbz x2,.Labort
#if __has_feature(hwaddress_sanitizer) && __clang_major__ >= 10
adrp x5,:pg_hi21_nc:OPENSSL_armcap_P
@@ -49,6 +50,7 @@ ChaCha20_ctr32:
b.ne ChaCha20_neon
.Lshort:
AARCH64_SIGN_LINK_REGISTER
stp x29,x30,[sp,#-96]!
add x29,sp,#0
@@ -261,6 +263,7 @@ ChaCha20_ctr32:
ldp x25,x26,[x29,#64]
ldp x27,x28,[x29,#80]
ldp x29,x30,[sp],#96
AARCH64_VALIDATE_LINK_REGISTER
.Labort:
ret
@@ -317,12 +320,14 @@ ChaCha20_ctr32:
ldp x25,x26,[x29,#64]
ldp x27,x28,[x29,#80]
ldp x29,x30,[sp],#96
AARCH64_VALIDATE_LINK_REGISTER
ret
.size ChaCha20_ctr32,.-ChaCha20_ctr32
.type ChaCha20_neon,%function
.align 5
ChaCha20_neon:
AARCH64_SIGN_LINK_REGISTER
stp x29,x30,[sp,#-96]!
add x29,sp,#0
@@ -703,6 +708,7 @@ ChaCha20_neon:
ldp x25,x26,[x29,#64]
ldp x27,x28,[x29,#80]
ldp x29,x30,[sp],#96
AARCH64_VALIDATE_LINK_REGISTER
ret
.Ltail_neon:
@@ -812,11 +818,13 @@ ChaCha20_neon:
ldp x25,x26,[x29,#64]
ldp x27,x28,[x29,#80]
ldp x29,x30,[sp],#96
AARCH64_VALIDATE_LINK_REGISTER
ret
.size ChaCha20_neon,.-ChaCha20_neon
.type ChaCha20_512_neon,%function
.align 5
ChaCha20_512_neon:
AARCH64_SIGN_LINK_REGISTER
stp x29,x30,[sp,#-96]!
add x29,sp,#0
@@ -1980,6 +1988,7 @@ ChaCha20_512_neon:
ldp x25,x26,[x29,#64]
ldp x27,x28,[x29,#80]
ldp x29,x30,[sp],#96
AARCH64_VALIDATE_LINK_REGISTER
ret
.size ChaCha20_512_neon,.-ChaCha20_512_neon
#endif
@@ -3937,7 +3937,7 @@ do_length_block:
popq %rbp
.cfi_adjust_cfa_offset -8
.byte 0xf3,0xc3
.cfi_adjust_cfa_offset (8 * 6) + 288 + 32
.cfi_adjust_cfa_offset (8 * 7) + 288 + 32
seal_sse_128:
movdqu .chacha20_consts(%rip),%xmm0
@@ -86,7 +86,7 @@ int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md,
EVP_MD_CTX_init(&c);
for (;;) {
if (!EVP_DigestInit_ex(&c, md, NULL)) {
return 0;
goto err;
}
if (addmd++) {
if (!EVP_DigestUpdate(&c, md_buf, mds)) {
@@ -133,6 +133,7 @@ void EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in,
assert(orig_len >= in_len);
assert(in_len >= md_size);
assert(md_size <= EVP_MAX_MD_SIZE);
assert(md_size > 0);
// scan_start contains the number of bytes that we can ignore because
// the MAC's position can only vary by 255 bytes.
@@ -146,11 +146,13 @@ extern uint32_t OPENSSL_armcap_P;
static int g_has_broken_neon, g_needs_hwcap2_workaround;
void OPENSSL_cpuid_setup(void) {
char *cpuinfo_data;
size_t cpuinfo_len;
if (!read_file(&cpuinfo_data, &cpuinfo_len, "/proc/cpuinfo")) {
return;
}
// We ignore the return value of |read_file| and proceed with an empty
// /proc/cpuinfo on error. If |getauxval| works, we will still detect
// capabilities. There may be a false positive due to
// |crypto_cpuinfo_has_broken_neon|, but this is now rare.
char *cpuinfo_data = NULL;
size_t cpuinfo_len = 0;
read_file(&cpuinfo_data, &cpuinfo_len, "/proc/cpuinfo");
STRING_PIECE cpuinfo;
cpuinfo.data = cpuinfo_data;
cpuinfo.len = cpuinfo_len;
+13 -4
View File
@@ -123,7 +123,9 @@ static uint64_t OPENSSL_xgetbv(uint32_t xcr) {
// and |out[1]|. See the comment in |OPENSSL_cpuid_setup| about this.
static void handle_cpu_env(uint32_t *out, const char *in) {
const int invert = in[0] == '~';
const int hex = in[invert] == '0' && in[invert+1] == 'x';
const int or = in[0] == '|';
const int skip_first_byte = invert || or;
const int hex = in[skip_first_byte] == '0' && in[skip_first_byte+1] == 'x';
int sscanf_result;
uint64_t v;
@@ -140,6 +142,9 @@ static void handle_cpu_env(uint32_t *out, const char *in) {
if (invert) {
out[0] &= ~v;
out[1] &= ~(v >> 32);
} else if (or) {
out[0] |= v;
out[1] |= (v >> 32);
} else {
out[0] = v;
out[1] = v >> 32;
@@ -264,10 +269,14 @@ void OPENSSL_cpuid_setup(void) {
// OPENSSL_ia32cap can contain zero, one or two values, separated with a ':'.
// Each value is a 64-bit, unsigned value which may start with "0x" to
// indicate a hex value. Prior to the 64-bit value, a '~' may be given.
// indicate a hex value. Prior to the 64-bit value, a '~' or '|' may be given.
//
// If '~' isn't present, then the value is taken as the result of the CPUID.
// Otherwise the value is inverted and ANDed with the probed CPUID result.
// If the '~' prefix is present:
// the value is inverted and ANDed with the probed CPUID result
// If the '|' prefix is present:
// the value is ORed with the probed CPUID result
// Otherwise:
// the value is taken as the result of the CPUID
//
// The first value determines OPENSSL_ia32cap_P[0] and [1]. The second [2]
// and [3].
+11
View File
@@ -16,6 +16,8 @@
#include <CCryptoBoringSSL_cpu.h>
#include "fipsmodule/rand/fork_detect.h"
#include "fipsmodule/rand/internal.h"
#include "internal.h"
@@ -174,6 +176,15 @@ int CRYPTO_has_asm(void) {
#endif
}
void CRYPTO_pre_sandbox_init(void) {
// Read from /proc/cpuinfo if needed.
CRYPTO_library_init();
// Open /dev/urandom if needed.
CRYPTO_init_sysrand();
// Set up MADV_WIPEONFORK state if needed.
CRYPTO_get_fork_generation();
}
const char *SSLeay_version(int which) { return OpenSSL_version(which); }
const char *OpenSSL_version(int which) {
@@ -1,29 +1,21 @@
// The MIT License (MIT)
//
// Copyright (c) 2015-2016 the fiat-crypto authors (see the AUTHORS file).
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
/* Copyright (c) 2020, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
// Some of this code is taken from the ref10 version of Ed25519 in SUPERCOP
// 20141124 (http://bench.cr.yp.to/supercop.html). That code is released as
// public domain but parts have been replaced with code generated by Fiat
// (https://github.com/mit-plv/fiat-crypto), which is MIT licensed.
// public domain. Other parts have been replaced to call into code generated by
// Fiat (https://github.com/mit-plv/fiat-crypto) in //third_party/fiat.
//
// The field functions are shared by Ed25519 and X25519 where possible.
@@ -39,16 +31,16 @@
#include <CCryptoBoringSSL_type_check.h>
#include "internal.h"
#include "../../crypto/internal.h"
#include "../internal.h"
// Various pre-computed constants.
#include "./curve25519_tables.h"
#if defined(BORINGSSL_CURVE25519_64BIT)
#include "./curve25519_64.h"
#include "../../third_party/fiat/curve25519_64.h"
#else
#include "./curve25519_32.h"
#include "../../third_party/fiat/curve25519_32.h"
#endif // BORINGSSL_CURVE25519_64BIT
@@ -1,24 +1,16 @@
// The MIT License (MIT)
//
// Copyright (c) 2015-2016 the fiat-crypto authors (see the AUTHORS file).
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
/* Copyright (c) 2020, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
// This file is generated from
// ./make_curve25519_tables.py > curve25519_tables.h
@@ -1,24 +1,16 @@
// The MIT License (MIT)
//
// Copyright (c) 2015-2016 the fiat-crypto authors (see the AUTHORS file).
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
/* Copyright (c) 2020, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#ifndef OPENSSL_HEADER_CURVE25519_INTERNAL_H
#define OPENSSL_HEADER_CURVE25519_INTERNAL_H
@@ -29,7 +21,7 @@ extern "C" {
#include <CCryptoBoringSSL_base.h>
#include "../../crypto/internal.h"
#include "../internal.h"
#if defined(OPENSSL_ARM) && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_APPLE)
@@ -23,7 +23,7 @@
#include <CCryptoBoringSSL_sha.h>
#include "../internal.h"
#include "../../third_party/fiat/internal.h"
#include "./internal.h"
// The following precomputation tables are for the following
+15
View File
@@ -113,6 +113,16 @@ void DH_free(DH *dh) {
OPENSSL_free(dh);
}
const BIGNUM *DH_get0_pub_key(const DH *dh) { return dh->pub_key; }
const BIGNUM *DH_get0_priv_key(const DH *dh) { return dh->priv_key; }
const BIGNUM *DH_get0_p(const DH *dh) { return dh->p; }
const BIGNUM *DH_get0_q(const DH *dh) { return dh->q; }
const BIGNUM *DH_get0_g(const DH *dh) { return dh->g; }
void DH_get0_key(const DH *dh, const BIGNUM **out_pub_key,
const BIGNUM **out_priv_key) {
if (out_pub_key != NULL) {
@@ -174,6 +184,11 @@ int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g) {
return 1;
}
int DH_set_length(DH *dh, unsigned priv_length) {
dh->priv_length = priv_length;
return 1;
}
int DH_generate_parameters_ex(DH *dh, int prime_bits, int generator, BN_GENCB *cb) {
// We generate DH parameters as follows
// find a prime q which is prime_bits/2 bits long.
+19 -43
View File
@@ -72,12 +72,11 @@
#include <CCryptoBoringSSL_sha.h>
#include <CCryptoBoringSSL_thread.h>
#include "internal.h"
#include "../fipsmodule/bn/internal.h"
#include "../internal.h"
#define OPENSSL_DSA_MAX_MODULUS_BITS 10000
// Primality test according to FIPS PUB 186[-1], Appendix 2.1: 50 rounds of
// Miller-Rabin.
#define DSS_prime_checks 50
@@ -131,6 +130,16 @@ int DSA_up_ref(DSA *dsa) {
return 1;
}
const BIGNUM *DSA_get0_pub_key(const DSA *dsa) { return dsa->pub_key; }
const BIGNUM *DSA_get0_priv_key(const DSA *dsa) { return dsa->priv_key; }
const BIGNUM *DSA_get0_p(const DSA *dsa) { return dsa->p; }
const BIGNUM *DSA_get0_q(const DSA *dsa) { return dsa->q; }
const BIGNUM *DSA_get0_g(const DSA *dsa) { return dsa->g; }
void DSA_get0_key(const DSA *dsa, const BIGNUM **out_pub_key,
const BIGNUM **out_priv_key) {
if (out_pub_key != NULL) {
@@ -558,23 +567,7 @@ static int mod_mul_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
}
DSA_SIG *DSA_do_sign(const uint8_t *digest, size_t digest_len, const DSA *dsa) {
if (!dsa->p || !dsa->q || !dsa->g) {
OPENSSL_PUT_ERROR(DSA, DSA_R_MISSING_PARAMETERS);
return NULL;
}
// Reject invalid parameters. In particular, the algorithm will infinite loop
// if |g| is zero.
if (BN_is_zero(dsa->p) || BN_is_zero(dsa->q) || BN_is_zero(dsa->g)) {
OPENSSL_PUT_ERROR(DSA, DSA_R_INVALID_PARAMETERS);
return NULL;
}
// We only support DSA keys that are a multiple of 8 bits. (This is a weaker
// check than the one in |DSA_do_check_signature|, which only allows 160-,
// 224-, and 256-bit keys.
if (BN_num_bits(dsa->q) % 8 != 0) {
OPENSSL_PUT_ERROR(DSA, DSA_R_BAD_Q_VALUE);
if (!dsa_check_parameters(dsa)) {
return NULL;
}
@@ -668,35 +661,17 @@ int DSA_do_verify(const uint8_t *digest, size_t digest_len, DSA_SIG *sig,
int DSA_do_check_signature(int *out_valid, const uint8_t *digest,
size_t digest_len, DSA_SIG *sig, const DSA *dsa) {
BN_CTX *ctx;
BIGNUM u1, u2, t1;
int ret = 0;
unsigned i;
*out_valid = 0;
if (!dsa->p || !dsa->q || !dsa->g) {
OPENSSL_PUT_ERROR(DSA, DSA_R_MISSING_PARAMETERS);
return 0;
}
i = BN_num_bits(dsa->q);
// FIPS 186-3 allows only different sizes for q.
if (i != 160 && i != 224 && i != 256) {
OPENSSL_PUT_ERROR(DSA, DSA_R_BAD_Q_VALUE);
return 0;
}
if (BN_num_bits(dsa->p) > OPENSSL_DSA_MAX_MODULUS_BITS) {
OPENSSL_PUT_ERROR(DSA, DSA_R_MODULUS_TOO_LARGE);
if (!dsa_check_parameters(dsa)) {
return 0;
}
int ret = 0;
BIGNUM u1, u2, t1;
BN_init(&u1);
BN_init(&u2);
BN_init(&t1);
ctx = BN_CTX_new();
BN_CTX *ctx = BN_CTX_new();
if (ctx == NULL) {
goto err;
}
@@ -719,11 +694,12 @@ int DSA_do_check_signature(int *out_valid, const uint8_t *digest,
}
// save M in u1
if (digest_len > (i >> 3)) {
unsigned q_bits = BN_num_bits(dsa->q);
if (digest_len > (q_bits >> 3)) {
// if the digest length is greater than the size of q use the
// BN_num_bits(dsa->q) leftmost bits of the digest, see
// fips 186-3, 4.2
digest_len = (i >> 3);
digest_len = (q_bits >> 3);
}
if (BN_bin2bn(digest, digest_len, &u1) == NULL) {
+55 -4
View File
@@ -61,9 +61,45 @@
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include "internal.h"
#include "../bytestring/internal.h"
#define OPENSSL_DSA_MAX_MODULUS_BITS 10000
// This function is in dsa_asn1.c rather than dsa.c because it is reachable from
// |EVP_PKEY| parsers. This makes it easier for the static linker to drop most
// of the DSA implementation.
int dsa_check_parameters(const DSA *dsa) {
if (!dsa->p || !dsa->q || !dsa->g) {
OPENSSL_PUT_ERROR(DSA, DSA_R_MISSING_PARAMETERS);
return 0;
}
// Reject invalid parameters. In particular, signing will infinite loop if |g|
// is zero.
if (BN_is_zero(dsa->p) || BN_is_zero(dsa->q) || BN_is_zero(dsa->g)) {
OPENSSL_PUT_ERROR(DSA, DSA_R_INVALID_PARAMETERS);
return 0;
}
// FIPS 186-4 allows only three different sizes for q.
unsigned q_bits = BN_num_bits(dsa->q);
if (q_bits != 160 && q_bits != 224 && q_bits != 256) {
OPENSSL_PUT_ERROR(DSA, DSA_R_BAD_Q_VALUE);
return 0;
}
// Bound |dsa->p| to avoid a DoS vector. Note this limit is much larger than
// the one in FIPS 186-4, which only allows L = 1024, 2048, and 3072.
if (BN_num_bits(dsa->p) > OPENSSL_DSA_MAX_MODULUS_BITS) {
OPENSSL_PUT_ERROR(DSA, DSA_R_MODULUS_TOO_LARGE);
return 0;
}
return 1;
}
static int parse_integer(CBS *cbs, BIGNUM **out) {
assert(*out == NULL);
*out = BN_new();
@@ -124,10 +160,16 @@ DSA *DSA_parse_public_key(CBS *cbs) {
!parse_integer(&child, &ret->g) ||
CBS_len(&child) != 0) {
OPENSSL_PUT_ERROR(DSA, DSA_R_DECODE_ERROR);
DSA_free(ret);
return NULL;
goto err;
}
if (!dsa_check_parameters(ret)) {
goto err;
}
return ret;
err:
DSA_free(ret);
return NULL;
}
int DSA_marshal_public_key(CBB *cbb, const DSA *dsa) {
@@ -156,10 +198,16 @@ DSA *DSA_parse_parameters(CBS *cbs) {
!parse_integer(&child, &ret->g) ||
CBS_len(&child) != 0) {
OPENSSL_PUT_ERROR(DSA, DSA_R_DECODE_ERROR);
DSA_free(ret);
return NULL;
goto err;
}
if (!dsa_check_parameters(ret)) {
goto err;
}
return ret;
err:
DSA_free(ret);
return NULL;
}
int DSA_marshal_parameters(CBB *cbb, const DSA *dsa) {
@@ -203,6 +251,9 @@ DSA *DSA_parse_private_key(CBS *cbs) {
OPENSSL_PUT_ERROR(DSA, DSA_R_DECODE_ERROR);
goto err;
}
if (!dsa_check_parameters(ret)) {
goto err;
}
return ret;
err:
@@ -0,0 +1,34 @@
/* Copyright (c) 2020, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#ifndef OPENSSL_HEADER_DSA_INTERNAL_H
#define OPENSSL_HEADER_DSA_INTERNAL_H
#include <CCryptoBoringSSL_dsa.h>
#if defined(__cplusplus)
extern "C" {
#endif
// dsa_check_parameters checks that |dsa|'s group is within DoS bounds. It
// returns one on success and zero on error.
int dsa_check_parameters(const DSA *dsa);
#if defined(__cplusplus)
} // extern C
#endif
#endif // OPENSSL_HEADER_DSA_INTERNAL_H
@@ -0,0 +1,385 @@
/* Copyright (c) 2020, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#include <CCryptoBoringSSL_ec.h>
#include <CCryptoBoringSSL_digest.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_nid.h>
#include <CCryptoBoringSSL_type_check.h>
#include <assert.h>
#include "internal.h"
#include "../fipsmodule/bn/internal.h"
#include "../fipsmodule/ec/internal.h"
#include "../internal.h"
// This file implements hash-to-curve, as described in
// draft-irtf-cfrg-hash-to-curve-07.
//
// This hash-to-curve implementation is written generically with the
// expectation that we will eventually wish to support other curves. If it
// becomes a performance bottleneck, some possible optimizations by
// specializing it to the curve:
//
// - Rather than using a generic |felem_exp|, specialize the exponentation to
// c2 with a faster addition chain.
//
// - |felem_mul| and |felem_sqr| are indirect calls to generic Montgomery
// code. Given the few curves, we could specialize
// |map_to_curve_simple_swu|. But doing this reasonably without duplicating
// code in C is difficult. (C++ templates would be useful here.)
//
// - P-521's Z and c2 have small power-of-two absolute values. We could save
// two multiplications in SSWU. (Other curves have reasonable values of Z
// and inconvenient c2.) This is unlikely to be worthwhile without C++
// templates to make specializing more convenient.
// expand_message_xmd implements the operation described in section 5.3.1 of
// draft-irtf-cfrg-hash-to-curve-07. It returns one on success and zero on
// allocation failure or if |out_len| was too large.
static int expand_message_xmd(const EVP_MD *md, uint8_t *out, size_t out_len,
const uint8_t *msg, size_t msg_len,
const uint8_t *dst, size_t dst_len) {
int ret = 0;
const size_t block_size = EVP_MD_block_size(md);
const size_t md_size = EVP_MD_size(md);
EVP_MD_CTX ctx;
EVP_MD_CTX_init(&ctx);
// Long DSTs are hashed down to size. See section 5.3.3.
OPENSSL_STATIC_ASSERT(EVP_MAX_MD_SIZE < 256, "hashed DST still too large");
uint8_t dst_buf[EVP_MAX_MD_SIZE];
if (dst_len >= 256) {
static const char kPrefix[] = "H2C-OVERSIZE-DST-";
if (!EVP_DigestInit_ex(&ctx, md, NULL) ||
!EVP_DigestUpdate(&ctx, kPrefix, sizeof(kPrefix) - 1) ||
!EVP_DigestUpdate(&ctx, dst, dst_len) ||
!EVP_DigestFinal_ex(&ctx, dst_buf, NULL)) {
goto err;
}
dst = dst_buf;
dst_len = md_size;
}
uint8_t dst_len_u8 = (uint8_t)dst_len;
// Compute b_0.
static const uint8_t kZeros[EVP_MAX_MD_BLOCK_SIZE] = {0};
// If |out_len| exceeds 16 bits then |i| will wrap below causing an error to
// be returned. This depends on the static assert above.
uint8_t l_i_b_str_zero[3] = {out_len >> 8, out_len, 0};
uint8_t b_0[EVP_MAX_MD_SIZE];
if (!EVP_DigestInit_ex(&ctx, md, NULL) ||
!EVP_DigestUpdate(&ctx, kZeros, block_size) ||
!EVP_DigestUpdate(&ctx, msg, msg_len) ||
!EVP_DigestUpdate(&ctx, l_i_b_str_zero, sizeof(l_i_b_str_zero)) ||
!EVP_DigestUpdate(&ctx, dst, dst_len) ||
!EVP_DigestUpdate(&ctx, &dst_len_u8, 1) ||
!EVP_DigestFinal_ex(&ctx, b_0, NULL)) {
goto err;
}
uint8_t b_i[EVP_MAX_MD_SIZE];
uint8_t i = 1;
while (out_len > 0) {
if (i == 0) {
// Input was too large.
OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
goto err;
}
if (i > 1) {
for (size_t j = 0; j < md_size; j++) {
b_i[j] ^= b_0[j];
}
} else {
OPENSSL_memcpy(b_i, b_0, md_size);
}
if (!EVP_DigestInit_ex(&ctx, md, NULL) ||
!EVP_DigestUpdate(&ctx, b_i, md_size) ||
!EVP_DigestUpdate(&ctx, &i, 1) ||
!EVP_DigestUpdate(&ctx, dst, dst_len) ||
!EVP_DigestUpdate(&ctx, &dst_len_u8, 1) ||
!EVP_DigestFinal_ex(&ctx, b_i, NULL)) {
goto err;
}
size_t todo = out_len >= md_size ? md_size : out_len;
OPENSSL_memcpy(out, b_i, todo);
out += todo;
out_len -= todo;
i++;
}
ret = 1;
err:
EVP_MD_CTX_cleanup(&ctx);
return ret;
}
// num_bytes_to_derive determines the number of bytes to derive when hashing to
// a number modulo |modulus|. See the hash_to_field operation defined in
// section 5.2 of draft-irtf-cfrg-hash-to-curve-07.
static int num_bytes_to_derive(size_t *out, const BIGNUM *modulus, unsigned k) {
size_t bits = BN_num_bits(modulus);
size_t L = (bits + k + 7) / 8;
// We require 2^(8*L) < 2^(2*bits - 2) <= n^2 so to fit in bounds for
// |felem_reduce| and |ec_scalar_reduce|. All defined hash-to-curve suites
// define |k| to be well under this bound. (|k| is usually around half of
// |p_bits|.)
if (L * 8 >= 2 * bits - 2 ||
L > 2 * EC_MAX_BYTES) {
assert(0);
OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
return 0;
}
*out = L;
return 1;
}
// big_endian_to_words decodes |in| as a big-endian integer and writes the
// result to |out|. |num_words| must be large enough to contain the output.
static void big_endian_to_words(BN_ULONG *out, size_t num_words,
const uint8_t *in, size_t len) {
assert(len <= num_words * sizeof(BN_ULONG));
// Ensure any excess bytes are zeroed.
OPENSSL_memset(out, 0, num_words * sizeof(BN_ULONG));
uint8_t *out_u8 = (uint8_t *)out;
for (size_t i = 0; i < len; i++) {
out_u8[len - 1 - i] = in[i];
}
}
// hash_to_field implements the operation described in section 5.2
// of draft-irtf-cfrg-hash-to-curve-07, with count = 2. |k| is the security
// factor.
static int hash_to_field2(const EC_GROUP *group, const EVP_MD *md,
EC_FELEM *out1, EC_FELEM *out2, const uint8_t *dst,
size_t dst_len, unsigned k, const uint8_t *msg,
size_t msg_len) {
size_t L;
uint8_t buf[4 * EC_MAX_BYTES];
if (!num_bytes_to_derive(&L, &group->field, k) ||
!expand_message_xmd(md, buf, 2 * L, msg, msg_len, dst, dst_len)) {
return 0;
}
BN_ULONG words[2 * EC_MAX_WORDS];
size_t num_words = 2 * group->field.width;
big_endian_to_words(words, num_words, buf, L);
group->meth->felem_reduce(group, out1, words, num_words);
big_endian_to_words(words, num_words, buf + L, L);
group->meth->felem_reduce(group, out2, words, num_words);
return 1;
}
// hash_to_scalar behaves like |hash_to_field2| but returns a value modulo the
// group order rather than a field element. |k| is the security factor.
static int hash_to_scalar(const EC_GROUP *group, const EVP_MD *md,
EC_SCALAR *out, const uint8_t *dst, size_t dst_len,
unsigned k, const uint8_t *msg, size_t msg_len) {
size_t L;
uint8_t buf[EC_MAX_BYTES * 2];
if (!num_bytes_to_derive(&L, &group->order, k) ||
!expand_message_xmd(md, buf, L, msg, msg_len, dst, dst_len)) {
return 0;
}
BN_ULONG words[2 * EC_MAX_WORDS];
size_t num_words = 2 * group->order.width;
big_endian_to_words(words, num_words, buf, L);
ec_scalar_reduce(group, out, words, num_words);
return 1;
}
static inline void mul_A(const EC_GROUP *group, EC_FELEM *out,
const EC_FELEM *in) {
assert(group->a_is_minus3);
EC_FELEM tmp;
ec_felem_add(group, &tmp, in, in); // tmp = 2*in
ec_felem_add(group, &tmp, &tmp, &tmp); // tmp = 4*in
ec_felem_sub(group, out, in, &tmp); // out = -3*in
}
static inline void mul_minus_A(const EC_GROUP *group, EC_FELEM *out,
const EC_FELEM *in) {
assert(group->a_is_minus3);
EC_FELEM tmp;
ec_felem_add(group, &tmp, in, in); // tmp = 2*in
ec_felem_add(group, out, &tmp, in); // out = 3*in
}
// sgn0_le implements the operation described in section 4.1.2 of
// draft-irtf-cfrg-hash-to-curve-07.
static BN_ULONG sgn0_le(const EC_GROUP *group, const EC_FELEM *a) {
uint8_t buf[EC_MAX_BYTES];
size_t len;
ec_felem_to_bytes(group, buf, &len, a);
return buf[len - 1] & 1;
}
// map_to_curve_simple_swu implements the operation described in section 6.6.2
// of draft-irtf-cfrg-hash-to-curve-07, using the optimization in appendix
// D.2.1. It returns one on success and zero on error.
static int map_to_curve_simple_swu(const EC_GROUP *group, const EC_FELEM *Z,
const BN_ULONG *c1, size_t num_c1,
const EC_FELEM *c2, EC_RAW_POINT *out,
const EC_FELEM *u) {
void (*const felem_mul)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a,
const EC_FELEM *b) = group->meth->felem_mul;
void (*const felem_sqr)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a) =
group->meth->felem_sqr;
// This function requires the prime be 3 mod 4, and that A = -3.
if (group->field.width == 0 || (group->field.d[0] & 3) != 3 ||
!group->a_is_minus3) {
OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
return 0;
}
EC_FELEM tv1, tv2, tv3, tv4, xd, x1n, x2n, tmp, gxd, gx1, y1, y2;
felem_sqr(group, &tv1, u); // tv1 = u^2
felem_mul(group, &tv3, Z, &tv1); // tv3 = Z * tv1
felem_sqr(group, &tv2, &tv3); // tv2 = tv3^2
ec_felem_add(group, &xd, &tv2, &tv3); // xd = tv2 + tv3
ec_felem_add(group, &x1n, &xd, &group->one); // x1n = xd + 1
felem_mul(group, &x1n, &x1n, &group->b); // x1n = x1n * B
mul_minus_A(group, &xd, &xd); // xd = -A * xd
BN_ULONG e1 = ec_felem_non_zero_mask(group, &xd); // e1 = xd == 0 [flipped]
mul_A(group, &tmp, Z);
ec_felem_select(group, &xd, e1, &xd, &tmp); // xd = CMOV(xd, Z * A, e1)
felem_sqr(group, &tv2, &xd); // tv2 = xd^2
felem_mul(group, &gxd, &tv2, &xd); // gxd = tv2 * xd = xd^3
mul_A(group, &tv2, &tv2); // tv2 = A * tv2
felem_sqr(group, &gx1, &x1n); // gx1 = x1n^2
ec_felem_add(group, &gx1, &gx1, &tv2); // gx1 = gx1 + tv2
felem_mul(group, &gx1, &gx1, &x1n); // gx1 = gx1 * x1n
felem_mul(group, &tv2, &group->b, &gxd); // tv2 = B * gxd
ec_felem_add(group, &gx1, &gx1, &tv2); // gx1 = gx1 + tv2
felem_sqr(group, &tv4, &gxd); // tv4 = gxd^2
felem_mul(group, &tv2, &gx1, &gxd); // tv2 = gx1 * gxd
felem_mul(group, &tv4, &tv4, &tv2); // tv4 = tv4 * tv2
group->meth->felem_exp(group, &y1, &tv4, c1, num_c1); // y1 = tv4^c1
felem_mul(group, &y1, &y1, &tv2); // y1 = y1 * tv2
felem_mul(group, &x2n, &tv3, &x1n); // x2n = tv3 * x1n
felem_mul(group, &y2, &y1, c2); // y2 = y1 * c2
felem_mul(group, &y2, &y2, &tv1); // y2 = y2 * tv1
felem_mul(group, &y2, &y2, u); // y2 = y2 * u
felem_sqr(group, &tv2, &y1); // tv2 = y1^2
felem_mul(group, &tv2, &tv2, &gxd); // tv2 = tv2 * gxd
ec_felem_sub(group, &tv3, &tv2, &gx1);
BN_ULONG e2 =
ec_felem_non_zero_mask(group, &tv3); // e2 = tv2 == gx1 [flipped]
ec_felem_select(group, &x1n, e2, &x2n, &x1n); // xn = CMOV(x2n, x1n, e2)
ec_felem_select(group, &y1, e2, &y2, &y1); // y = CMOV(y2, y1, e2)
BN_ULONG sgn0_u = sgn0_le(group, u);
BN_ULONG sgn0_y = sgn0_le(group, &y1);
BN_ULONG e3 = sgn0_u ^ sgn0_y;
e3 = ((BN_ULONG)0) - e3; // e3 = sgn0(u) == sgn0(y) [flipped]
ec_felem_neg(group, &y2, &y1);
ec_felem_select(group, &y1, e3, &y2, &y1); // y = CMOV(-y, y, e3)
// Appendix D.1 describes how to convert (x1n, xd, y1, 1) to Jacobian
// coordinates. Note yd = 1. Also note that gxd computed above is xd^3.
felem_mul(group, &out->X, &x1n, &xd); // X = xn * xd
felem_mul(group, &out->Y, &y1, &gxd); // Y = yn * gxd = yn * xd^3
out->Z = xd; // Z = xd
return 1;
}
static int hash_to_curve(const EC_GROUP *group, const EVP_MD *md,
const EC_FELEM *Z, const EC_FELEM *c2, unsigned k,
EC_RAW_POINT *out, const uint8_t *dst, size_t dst_len,
const uint8_t *msg, size_t msg_len) {
EC_FELEM u0, u1;
if (!hash_to_field2(group, md, &u0, &u1, dst, dst_len, k, msg, msg_len)) {
return 0;
}
// Compute |c1| = (p - 3) / 4.
BN_ULONG c1[EC_MAX_WORDS];
size_t num_c1 = group->field.width;
if (!bn_copy_words(c1, num_c1, &group->field)) {
return 0;
}
bn_rshift_words(c1, c1, /*shift=*/2, /*num=*/num_c1);
EC_RAW_POINT Q0, Q1;
if (!map_to_curve_simple_swu(group, Z, c1, num_c1, c2, &Q0, &u0) ||
!map_to_curve_simple_swu(group, Z, c1, num_c1, c2, &Q1, &u1)) {
return 0;
}
group->meth->add(group, out, &Q0, &Q1); // R = Q0 + Q1
// All our curves have cofactor one, so |clear_cofactor| is a no-op.
return 1;
}
static int felem_from_u8(const EC_GROUP *group, EC_FELEM *out, uint8_t a) {
uint8_t bytes[EC_MAX_BYTES] = {0};
size_t len = BN_num_bytes(&group->field);
bytes[len - 1] = a;
return ec_felem_from_bytes(group, out, bytes, len);
}
int ec_hash_to_curve_p384_xmd_sha512_sswu_draft07(
const EC_GROUP *group, EC_RAW_POINT *out, const uint8_t *dst,
size_t dst_len, const uint8_t *msg, size_t msg_len) {
// See section 8.3 of draft-irtf-cfrg-hash-to-curve-07.
if (EC_GROUP_get_curve_name(group) != NID_secp384r1) {
OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH);
return 0;
}
// kSqrt1728 was computed as follows in python3:
//
// p = 2**384 - 2**128 - 2**96 + 2**32 - 1
// z3 = 12**3
// c2 = pow(z3, (p+1)//4, p)
// assert z3 == pow(c2, 2, p)
// ", ".join("0x%02x" % b for b in c2.to_bytes(384//8, 'big')
static const uint8_t kSqrt1728[] = {
0x01, 0x98, 0x77, 0xcc, 0x10, 0x41, 0xb7, 0x55, 0x57, 0x43, 0xc0, 0xae,
0x2e, 0x3a, 0x3e, 0x61, 0xfb, 0x2a, 0xaa, 0x2e, 0x0e, 0x87, 0xea, 0x55,
0x7a, 0x56, 0x3d, 0x8b, 0x59, 0x8a, 0x09, 0x40, 0xd0, 0xa6, 0x97, 0xa9,
0xe0, 0xb9, 0xe9, 0x2c, 0xfa, 0xa3, 0x14, 0xf5, 0x83, 0xc9, 0xd0, 0x66
};
// Z = -12, c2 = sqrt(1728)
EC_FELEM Z, c2;
if (!felem_from_u8(group, &Z, 12) ||
!ec_felem_from_bytes(group, &c2, kSqrt1728, sizeof(kSqrt1728))) {
return 0;
}
ec_felem_neg(group, &Z, &Z);
return hash_to_curve(group, EVP_sha512(), &Z, &c2, /*k=*/192, out, dst,
dst_len, msg, msg_len);
}
int ec_hash_to_scalar_p384_xmd_sha512_draft07(
const EC_GROUP *group, EC_SCALAR *out, const uint8_t *dst, size_t dst_len,
const uint8_t *msg, size_t msg_len) {
if (EC_GROUP_get_curve_name(group) != NID_secp384r1) {
OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH);
return 0;
}
return hash_to_scalar(group, EVP_sha512(), out, dst, dst_len, /*k=*/192, msg,
msg_len);
}
@@ -0,0 +1,56 @@
/* Copyright (c) 2020, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#ifndef OPENSSL_HEADER_EC_EXTRA_INTERNAL_H
#define OPENSSL_HEADER_EC_EXTRA_INTERNAL_H
#include <CCryptoBoringSSL_ec.h>
#include "../fipsmodule/ec/internal.h"
#if defined(__cplusplus)
extern "C" {
#endif
// Hash-to-curve.
//
// The following functions implement primitives from
// draft-irtf-cfrg-hash-to-curve. The |dst| parameter in each function is the
// domain separation tag and must be unique for each protocol and between the
// |hash_to_curve| and |hash_to_scalar| variants. See section 3.1 of the spec
// for additional guidance on this parameter.
// ec_hash_to_curve_p384_xmd_sha512_sswu_draft07 hashes |msg| to a point on
// |group| and writes the result to |out|, implementing the
// P384_XMD:SHA-512_SSWU_RO_ suite from draft-irtf-cfrg-hash-to-curve-07. It
// returns one on success and zero on error.
OPENSSL_EXPORT int ec_hash_to_curve_p384_xmd_sha512_sswu_draft07(
const EC_GROUP *group, EC_RAW_POINT *out, const uint8_t *dst,
size_t dst_len, const uint8_t *msg, size_t msg_len);
// ec_hash_to_scalar_p384_xmd_sha512_draft07 hashes |msg| to a scalar on |group|
// and writes the result to |out|, using the hash_to_field operation from the
// P384_XMD:SHA-512_SSWU_RO_ suite from draft-irtf-cfrg-hash-to-curve-07, but
// generating a value modulo the group order rather than a field element.
OPENSSL_EXPORT int ec_hash_to_scalar_p384_xmd_sha512_draft07(
const EC_GROUP *group, EC_SCALAR *out, const uint8_t *dst, size_t dst_len,
const uint8_t *msg, size_t msg_len);
#if defined(__cplusplus)
} // extern C
#endif
#endif // OPENSSL_HEADER_EC_EXTRA_INTERNAL_H
@@ -96,8 +96,8 @@ int ECDH_compute_key(void *out, size_t out_len, const EC_POINT *pub_key,
uint8_t buf[EC_MAX_BYTES];
size_t buf_len;
if (!ec_point_mul_scalar(group, &shared_point, &pub_key->raw, priv) ||
!ec_point_get_affine_coordinate_bytes(group, buf, NULL, &buf_len,
sizeof(buf), &shared_point)) {
!ec_get_x_coordinate_as_bytes(group, buf, &buf_len, sizeof(buf),
&shared_point)) {
OPENSSL_PUT_ERROR(ECDH, ECDH_R_POINT_ARITHMETIC_FAILURE);
return -1;
}
+33 -32
View File
@@ -495,38 +495,39 @@ static const char *err_string_lookup(uint32_t lib, uint32_t key,
static const char *const kLibraryNames[ERR_NUM_LIBS] = {
"invalid library (0)",
"unknown library", // ERR_LIB_NONE
"system library", // ERR_LIB_SYS
"bignum routines", // ERR_LIB_BN
"RSA routines", // ERR_LIB_RSA
"Diffie-Hellman routines", // ERR_LIB_DH
"public key routines", // ERR_LIB_EVP
"memory buffer routines", // ERR_LIB_BUF
"object identifier routines", // ERR_LIB_OBJ
"PEM routines", // ERR_LIB_PEM
"DSA routines", // ERR_LIB_DSA
"X.509 certificate routines", // ERR_LIB_X509
"ASN.1 encoding routines", // ERR_LIB_ASN1
"configuration file routines", // ERR_LIB_CONF
"common libcrypto routines", // ERR_LIB_CRYPTO
"elliptic curve routines", // ERR_LIB_EC
"SSL routines", // ERR_LIB_SSL
"BIO routines", // ERR_LIB_BIO
"PKCS7 routines", // ERR_LIB_PKCS7
"PKCS8 routines", // ERR_LIB_PKCS8
"X509 V3 routines", // ERR_LIB_X509V3
"random number generator", // ERR_LIB_RAND
"ENGINE routines", // ERR_LIB_ENGINE
"OCSP routines", // ERR_LIB_OCSP
"UI routines", // ERR_LIB_UI
"COMP routines", // ERR_LIB_COMP
"ECDSA routines", // ERR_LIB_ECDSA
"ECDH routines", // ERR_LIB_ECDH
"HMAC routines", // ERR_LIB_HMAC
"Digest functions", // ERR_LIB_DIGEST
"Cipher functions", // ERR_LIB_CIPHER
"HKDF functions", // ERR_LIB_HKDF
"User defined functions", // ERR_LIB_USER
"unknown library", // ERR_LIB_NONE
"system library", // ERR_LIB_SYS
"bignum routines", // ERR_LIB_BN
"RSA routines", // ERR_LIB_RSA
"Diffie-Hellman routines", // ERR_LIB_DH
"public key routines", // ERR_LIB_EVP
"memory buffer routines", // ERR_LIB_BUF
"object identifier routines", // ERR_LIB_OBJ
"PEM routines", // ERR_LIB_PEM
"DSA routines", // ERR_LIB_DSA
"X.509 certificate routines", // ERR_LIB_X509
"ASN.1 encoding routines", // ERR_LIB_ASN1
"configuration file routines", // ERR_LIB_CONF
"common libcrypto routines", // ERR_LIB_CRYPTO
"elliptic curve routines", // ERR_LIB_EC
"SSL routines", // ERR_LIB_SSL
"BIO routines", // ERR_LIB_BIO
"PKCS7 routines", // ERR_LIB_PKCS7
"PKCS8 routines", // ERR_LIB_PKCS8
"X509 V3 routines", // ERR_LIB_X509V3
"random number generator", // ERR_LIB_RAND
"ENGINE routines", // ERR_LIB_ENGINE
"OCSP routines", // ERR_LIB_OCSP
"UI routines", // ERR_LIB_UI
"COMP routines", // ERR_LIB_COMP
"ECDSA routines", // ERR_LIB_ECDSA
"ECDH routines", // ERR_LIB_ECDH
"HMAC routines", // ERR_LIB_HMAC
"Digest functions", // ERR_LIB_DIGEST
"Cipher functions", // ERR_LIB_CIPHER
"HKDF functions", // ERR_LIB_HKDF
"Trust Token functions", // ERR_LIB_TRUST_TOKEN
"User defined functions", // ERR_LIB_USER
};
const char *ERR_lib_error_string(uint32_t packed_error) {
File diff suppressed because it is too large. Load diff
@@ -76,6 +76,10 @@
// TODO(davidben): Fix Node to not touch the error queue itself and remove this.
OPENSSL_DECLARE_ERROR_REASON(EVP, NOT_XOF_OR_INVALID_LENGTH)
// The HPKE module uses the EVP error namespace, but it lives in another
// directory.
OPENSSL_DECLARE_ERROR_REASON(EVP, EMPTY_PSK)
EVP_PKEY *EVP_PKEY_new(void) {
EVP_PKEY *ret;
@@ -65,6 +65,7 @@
#include <CCryptoBoringSSL_rsa.h>
#include "internal.h"
#include "../bytestring/internal.h"
#include "../internal.h"
@@ -386,3 +387,161 @@ err:
EVP_PKEY_free(ret);
return NULL;
}
EVP_PKEY *d2i_PUBKEY(EVP_PKEY **out, const uint8_t **inp, long len) {
if (len < 0) {
return NULL;
}
CBS cbs;
CBS_init(&cbs, *inp, (size_t)len);
EVP_PKEY *ret = EVP_parse_public_key(&cbs);
if (ret == NULL) {
return NULL;
}
if (out != NULL) {
EVP_PKEY_free(*out);
*out = ret;
}
*inp = CBS_data(&cbs);
return ret;
}
int i2d_PUBKEY(const EVP_PKEY *pkey, uint8_t **outp) {
if (pkey == NULL) {
return 0;
}
CBB cbb;
if (!CBB_init(&cbb, 128) ||
!EVP_marshal_public_key(&cbb, pkey)) {
CBB_cleanup(&cbb);
return -1;
}
return CBB_finish_i2d(&cbb, outp);
}
RSA *d2i_RSA_PUBKEY(RSA **out, const uint8_t **inp, long len) {
if (len < 0) {
return NULL;
}
CBS cbs;
CBS_init(&cbs, *inp, (size_t)len);
EVP_PKEY *pkey = EVP_parse_public_key(&cbs);
if (pkey == NULL) {
return NULL;
}
RSA *rsa = EVP_PKEY_get1_RSA(pkey);
EVP_PKEY_free(pkey);
if (rsa == NULL) {
return NULL;
}
if (out != NULL) {
RSA_free(*out);
*out = rsa;
}
*inp = CBS_data(&cbs);
return rsa;
}
int i2d_RSA_PUBKEY(const RSA *rsa, uint8_t **outp) {
if (rsa == NULL) {
return 0;
}
int ret = -1;
EVP_PKEY *pkey = EVP_PKEY_new();
if (pkey == NULL ||
!EVP_PKEY_set1_RSA(pkey, (RSA *)rsa)) {
goto err;
}
ret = i2d_PUBKEY(pkey, outp);
err:
EVP_PKEY_free(pkey);
return ret;
}
DSA *d2i_DSA_PUBKEY(DSA **out, const uint8_t **inp, long len) {
if (len < 0) {
return NULL;
}
CBS cbs;
CBS_init(&cbs, *inp, (size_t)len);
EVP_PKEY *pkey = EVP_parse_public_key(&cbs);
if (pkey == NULL) {
return NULL;
}
DSA *dsa = EVP_PKEY_get1_DSA(pkey);
EVP_PKEY_free(pkey);
if (dsa == NULL) {
return NULL;
}
if (out != NULL) {
DSA_free(*out);
*out = dsa;
}
*inp = CBS_data(&cbs);
return dsa;
}
int i2d_DSA_PUBKEY(const DSA *dsa, uint8_t **outp) {
if (dsa == NULL) {
return 0;
}
int ret = -1;
EVP_PKEY *pkey = EVP_PKEY_new();
if (pkey == NULL ||
!EVP_PKEY_set1_DSA(pkey, (DSA *)dsa)) {
goto err;
}
ret = i2d_PUBKEY(pkey, outp);
err:
EVP_PKEY_free(pkey);
return ret;
}
EC_KEY *d2i_EC_PUBKEY(EC_KEY **out, const uint8_t **inp, long len) {
if (len < 0) {
return NULL;
}
CBS cbs;
CBS_init(&cbs, *inp, (size_t)len);
EVP_PKEY *pkey = EVP_parse_public_key(&cbs);
if (pkey == NULL) {
return NULL;
}
EC_KEY *ec_key = EVP_PKEY_get1_EC_KEY(pkey);
EVP_PKEY_free(pkey);
if (ec_key == NULL) {
return NULL;
}
if (out != NULL) {
EC_KEY_free(*out);
*out = ec_key;
}
*inp = CBS_data(&cbs);
return ec_key;
}
int i2d_EC_PUBKEY(const EC_KEY *ec_key, uint8_t **outp) {
if (ec_key == NULL) {
return 0;
}
int ret = -1;
EVP_PKEY *pkey = EVP_PKEY_new();
if (pkey == NULL ||
!EVP_PKEY_set1_EC_KEY(pkey, (EC_KEY *)ec_key)) {
goto err;
}
ret = i2d_PUBKEY(pkey, outp);
err:
EVP_PKEY_free(pkey);
return ret;
}
@@ -141,9 +141,13 @@ static int dsa_priv_decode(EVP_PKEY *out, CBS *params, CBS *key) {
goto err;
}
// Decode the key.
// Decode the key. To avoid DoS attacks when importing private keys, we bound
// |dsa->priv_key| against |dsa->q|, which itself bound by
// |DSA_parse_parameters|. (We cannot call |BN_num_bits| on |dsa->priv_key|.
// That would leak a secret bit width.)
if (!BN_parse_asn1_unsigned(key, dsa->priv_key) ||
CBS_len(key) != 0) {
CBS_len(key) != 0 ||
BN_cmp(dsa->priv_key, dsa->q) >= 0) {
OPENSSL_PUT_ERROR(EVP, EVP_R_DECODE_ERROR);
goto err;
}
@@ -472,7 +472,7 @@ static void aes_nohw_transpose(AES_NOHW_BATCH *batch) {
// |num_blocks| must be at most |AES_NOHW_BATCH|.
static void aes_nohw_to_batch(AES_NOHW_BATCH *out, const uint8_t *in,
size_t num_blocks) {
// Don't leave unused blocks unitialized.
// Don't leave unused blocks uninitialized.
memset(out, 0, sizeof(AES_NOHW_BATCH));
assert(num_blocks <= AES_NOHW_BATCH_SIZE);
for (size_t i = 0; i < num_blocks; i++) {
@@ -57,7 +57,23 @@
void AES_ctr128_encrypt(const uint8_t *in, uint8_t *out, size_t len,
const AES_KEY *key, uint8_t ivec[AES_BLOCK_SIZE],
uint8_t ecount_buf[AES_BLOCK_SIZE], unsigned int *num) {
CRYPTO_ctr128_encrypt(in, out, len, key, ivec, ecount_buf, num, AES_encrypt);
if (hwaes_capable()) {
CRYPTO_ctr128_encrypt_ctr32(in, out, len, key, ivec, ecount_buf, num,
aes_hw_ctr32_encrypt_blocks);
} else if (vpaes_capable()) {
#if defined(VPAES_CTR32)
// TODO(davidben): On ARM, where |BSAES| is additionally defined, this could
// use |vpaes_ctr32_encrypt_blocks_with_bsaes|.
CRYPTO_ctr128_encrypt_ctr32(in, out, len, key, ivec, ecount_buf, num,
vpaes_ctr32_encrypt_blocks);
#else
CRYPTO_ctr128_encrypt(in, out, len, key, ivec, ecount_buf, num,
vpaes_encrypt);
#endif
} else {
CRYPTO_ctr128_encrypt_ctr32(in, out, len, key, ivec, ecount_buf, num,
aes_nohw_ctr32_encrypt_blocks);
}
}
void AES_ecb_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key,
@@ -34,6 +34,8 @@ Lrcon:
.align 5
_aes_hw_set_encrypt_key:
Lenc_key:
// Armv8.3-A PAuth: even though x30 is pushed to stack it is not popped later.
AARCH64_VALID_CALL_TARGET
stp x29,x30,[sp,#-16]!
add x29,sp,#0
mov x3,#-1
@@ -202,6 +204,7 @@ Lenc_key_abort:
.align 5
_aes_hw_set_decrypt_key:
AARCH64_SIGN_LINK_REGISTER
stp x29,x30,[sp,#-16]!
add x29,sp,#0
bl Lenc_key
@@ -235,6 +238,7 @@ Loop_imc:
eor x0,x0,x0 // return value
Ldec_key_abort:
ldp x29,x30,[sp],#16
AARCH64_VALIDATE_LINK_REGISTER
ret
.globl _aes_hw_encrypt
@@ -242,6 +246,7 @@ Ldec_key_abort:
.align 5
_aes_hw_encrypt:
AARCH64_VALID_CALL_TARGET
ldr w3,[x2,#240]
ld1 {v0.4s},[x2],#16
ld1 {v2.16b},[x0]
@@ -272,6 +277,7 @@ Loop_enc:
.align 5
_aes_hw_decrypt:
AARCH64_VALID_CALL_TARGET
ldr w3,[x2,#240]
ld1 {v0.4s},[x2],#16
ld1 {v2.16b},[x0]
@@ -302,6 +308,8 @@ Loop_dec:
.align 5
_aes_hw_cbc_encrypt:
// Armv8.3-A PAuth: even though x30 is pushed to stack it is not popped later.
AARCH64_VALID_CALL_TARGET
stp x29,x30,[sp,#-16]!
add x29,sp,#0
subs x2,x2,#16
@@ -593,6 +601,8 @@ Lcbc_abort:
.align 5
_aes_hw_ctr32_encrypt_blocks:
// Armv8.3-A PAuth: even though x30 is pushed to stack it is not popped later.
AARCH64_VALID_CALL_TARGET
stp x29,x30,[sp,#-16]!
add x29,sp,#0
ldr w5,[x3,#240]
@@ -35,6 +35,8 @@
.align 5
aes_hw_set_encrypt_key:
.Lenc_key:
// Armv8.3-A PAuth: even though x30 is pushed to stack it is not popped later.
AARCH64_VALID_CALL_TARGET
stp x29,x30,[sp,#-16]!
add x29,sp,#0
mov x3,#-1
@@ -203,6 +205,7 @@ aes_hw_set_encrypt_key:
.type aes_hw_set_decrypt_key,%function
.align 5
aes_hw_set_decrypt_key:
AARCH64_SIGN_LINK_REGISTER
stp x29,x30,[sp,#-16]!
add x29,sp,#0
bl .Lenc_key
@@ -236,6 +239,7 @@ aes_hw_set_decrypt_key:
eor x0,x0,x0 // return value
.Ldec_key_abort:
ldp x29,x30,[sp],#16
AARCH64_VALIDATE_LINK_REGISTER
ret
.size aes_hw_set_decrypt_key,.-aes_hw_set_decrypt_key
.globl aes_hw_encrypt
@@ -243,6 +247,7 @@ aes_hw_set_decrypt_key:
.type aes_hw_encrypt,%function
.align 5
aes_hw_encrypt:
AARCH64_VALID_CALL_TARGET
ldr w3,[x2,#240]
ld1 {v0.4s},[x2],#16
ld1 {v2.16b},[x0]
@@ -273,6 +278,7 @@ aes_hw_encrypt:
.type aes_hw_decrypt,%function
.align 5
aes_hw_decrypt:
AARCH64_VALID_CALL_TARGET
ldr w3,[x2,#240]
ld1 {v0.4s},[x2],#16
ld1 {v2.16b},[x0]
@@ -303,6 +309,8 @@ aes_hw_decrypt:
.type aes_hw_cbc_encrypt,%function
.align 5
aes_hw_cbc_encrypt:
// Armv8.3-A PAuth: even though x30 is pushed to stack it is not popped later.
AARCH64_VALID_CALL_TARGET
stp x29,x30,[sp,#-16]!
add x29,sp,#0
subs x2,x2,#16
@@ -594,6 +602,8 @@ aes_hw_cbc_encrypt:
.type aes_hw_ctr32_encrypt_blocks,%function
.align 5
aes_hw_ctr32_encrypt_blocks:
// Armv8.3-A PAuth: even though x30 is pushed to stack it is not popped later.
AARCH64_VALID_CALL_TARGET
stp x29,x30,[sp,#-16]!
add x29,sp,#0
ldr w5,[x3,#240]
@@ -14,6 +14,8 @@
#if defined(BORINGSSL_PREFIX)
#include <CCryptoBoringSSL_boringssl_prefix_symbols_asm.h>
#endif
#include <CCryptoBoringSSL_arm_arch.h>
.text
.globl _bn_mul_mont
@@ -21,6 +23,7 @@
.align 5
_bn_mul_mont:
AARCH64_SIGN_LINK_REGISTER
tst x5,#7
b.eq __bn_sqr8x_mont
tst x5,#3
@@ -218,11 +221,14 @@ Lcond_copy:
mov x0,#1
ldp x23,x24,[x29,#48]
ldr x29,[sp],#64
AARCH64_VALIDATE_LINK_REGISTER
ret
.align 5
__bn_sqr8x_mont:
// Not adding AARCH64_SIGN_LINK_REGISTER here because __bn_sqr8x_mont is jumped to
// only from bn_mul_mont which has already signed the return address.
cmp x1,x2
b.ne __bn_mul4x_mont
Lsqr8x_mont:
@@ -976,11 +982,16 @@ Lsqr8x_done:
ldp x25,x26,[x29,#64]
ldp x27,x28,[x29,#80]
ldr x29,[sp],#128
// x30 is popped earlier
AARCH64_VALIDATE_LINK_REGISTER
ret
.align 5
__bn_mul4x_mont:
// Not adding AARCH64_SIGN_LINK_REGISTER here because __bn_mul4x_mont is jumped to
// only from bn_mul_mont or __bn_mul8x_mont which have already signed the
// return address.
stp x29,x30,[sp,#-128]!
add x29,sp,#0
stp x19,x20,[sp,#16]
@@ -1414,6 +1425,8 @@ Lmul4x_done:
ldp x25,x26,[x29,#64]
ldp x27,x28,[x29,#80]
ldr x29,[sp],#128
// x30 is popped earlier
AARCH64_VALIDATE_LINK_REGISTER
ret
.byte 77,111,110,116,103,111,109,101,114,121,32,77,117,108,116,105,112,108,105,99,97,116,105,111,110,32,102,111,114,32,65,82,77,118,56,44,32,67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97,112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103,62,0
@@ -15,6 +15,8 @@
#if defined(BORINGSSL_PREFIX)
#include <CCryptoBoringSSL_boringssl_prefix_symbols_asm.h>
#endif
#include <CCryptoBoringSSL_arm_arch.h>
.text
.globl bn_mul_mont
@@ -22,6 +24,7 @@
.type bn_mul_mont,%function
.align 5
bn_mul_mont:
AARCH64_SIGN_LINK_REGISTER
tst x5,#7
b.eq __bn_sqr8x_mont
tst x5,#3
@@ -219,11 +222,14 @@ bn_mul_mont:
mov x0,#1
ldp x23,x24,[x29,#48]
ldr x29,[sp],#64
AARCH64_VALIDATE_LINK_REGISTER
ret
.size bn_mul_mont,.-bn_mul_mont
.type __bn_sqr8x_mont,%function
.align 5
__bn_sqr8x_mont:
// Not adding AARCH64_SIGN_LINK_REGISTER here because __bn_sqr8x_mont is jumped to
// only from bn_mul_mont which has already signed the return address.
cmp x1,x2
b.ne __bn_mul4x_mont
.Lsqr8x_mont:
@@ -977,11 +983,16 @@ __bn_sqr8x_mont:
ldp x25,x26,[x29,#64]
ldp x27,x28,[x29,#80]
ldr x29,[sp],#128
// x30 is popped earlier
AARCH64_VALIDATE_LINK_REGISTER
ret
.size __bn_sqr8x_mont,.-__bn_sqr8x_mont
.type __bn_mul4x_mont,%function
.align 5
__bn_mul4x_mont:
// Not adding AARCH64_SIGN_LINK_REGISTER here because __bn_mul4x_mont is jumped to
// only from bn_mul_mont or __bn_mul8x_mont which have already signed the
// return address.
stp x29,x30,[sp,#-128]!
add x29,sp,#0
stp x19,x20,[sp,#16]
@@ -1415,6 +1426,8 @@ __bn_mul4x_mont:
ldp x25,x26,[x29,#64]
ldp x27,x28,[x29,#80]
ldr x29,[sp],#128
// x30 is popped earlier
AARCH64_VALIDATE_LINK_REGISTER
ret
.size __bn_mul4x_mont,.-__bn_mul4x_mont
.byte 77,111,110,116,103,111,109,101,114,121,32,77,117,108,116,105,112,108,105,99,97,116,105,111,110,32,102,111,114,32,65,82,77,118,56,44,32,67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97,112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103,62,0
@@ -995,553 +995,6 @@ bn_sub_words:
popl %ebp
ret
.size bn_sub_words,.-.L_bn_sub_words_begin
.globl bn_sub_part_words
.hidden bn_sub_part_words
.type bn_sub_part_words,@function
.align 16
bn_sub_part_words:
.L_bn_sub_part_words_begin:
pushl %ebp
pushl %ebx
pushl %esi
pushl %edi
movl 20(%esp),%ebx
movl 24(%esp),%esi
movl 28(%esp),%edi
movl 32(%esp),%ebp
xorl %eax,%eax
andl $4294967288,%ebp
jz .L029aw_finish
.L030aw_loop:
movl (%esi),%ecx
movl (%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,(%ebx)
movl 4(%esi),%ecx
movl 4(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,4(%ebx)
movl 8(%esi),%ecx
movl 8(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,8(%ebx)
movl 12(%esi),%ecx
movl 12(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,12(%ebx)
movl 16(%esi),%ecx
movl 16(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,16(%ebx)
movl 20(%esi),%ecx
movl 20(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,20(%ebx)
movl 24(%esi),%ecx
movl 24(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,24(%ebx)
movl 28(%esi),%ecx
movl 28(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,28(%ebx)
addl $32,%esi
addl $32,%edi
addl $32,%ebx
subl $8,%ebp
jnz .L030aw_loop
.L029aw_finish:
movl 32(%esp),%ebp
andl $7,%ebp
jz .L031aw_end
movl (%esi),%ecx
movl (%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,(%ebx)
addl $4,%esi
addl $4,%edi
addl $4,%ebx
decl %ebp
jz .L031aw_end
movl (%esi),%ecx
movl (%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,(%ebx)
addl $4,%esi
addl $4,%edi
addl $4,%ebx
decl %ebp
jz .L031aw_end
movl (%esi),%ecx
movl (%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,(%ebx)
addl $4,%esi
addl $4,%edi
addl $4,%ebx
decl %ebp
jz .L031aw_end
movl (%esi),%ecx
movl (%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,(%ebx)
addl $4,%esi
addl $4,%edi
addl $4,%ebx
decl %ebp
jz .L031aw_end
movl (%esi),%ecx
movl (%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,(%ebx)
addl $4,%esi
addl $4,%edi
addl $4,%ebx
decl %ebp
jz .L031aw_end
movl (%esi),%ecx
movl (%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,(%ebx)
addl $4,%esi
addl $4,%edi
addl $4,%ebx
decl %ebp
jz .L031aw_end
movl (%esi),%ecx
movl (%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,(%ebx)
addl $4,%esi
addl $4,%edi
addl $4,%ebx
.L031aw_end:
cmpl $0,36(%esp)
je .L032pw_end
movl 36(%esp),%ebp
cmpl $0,%ebp
je .L032pw_end
jge .L033pw_pos
movl $0,%edx
subl %ebp,%edx
movl %edx,%ebp
andl $4294967288,%ebp
jz .L034pw_neg_finish
.L035pw_neg_loop:
movl $0,%ecx
movl (%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,(%ebx)
movl $0,%ecx
movl 4(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,4(%ebx)
movl $0,%ecx
movl 8(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,8(%ebx)
movl $0,%ecx
movl 12(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,12(%ebx)
movl $0,%ecx
movl 16(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,16(%ebx)
movl $0,%ecx
movl 20(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,20(%ebx)
movl $0,%ecx
movl 24(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,24(%ebx)
movl $0,%ecx
movl 28(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,28(%ebx)
addl $32,%edi
addl $32,%ebx
subl $8,%ebp
jnz .L035pw_neg_loop
.L034pw_neg_finish:
movl 36(%esp),%edx
movl $0,%ebp
subl %edx,%ebp
andl $7,%ebp
jz .L032pw_end
movl $0,%ecx
movl (%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
decl %ebp
movl %ecx,(%ebx)
jz .L032pw_end
movl $0,%ecx
movl 4(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
decl %ebp
movl %ecx,4(%ebx)
jz .L032pw_end
movl $0,%ecx
movl 8(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
decl %ebp
movl %ecx,8(%ebx)
jz .L032pw_end
movl $0,%ecx
movl 12(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
decl %ebp
movl %ecx,12(%ebx)
jz .L032pw_end
movl $0,%ecx
movl 16(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
decl %ebp
movl %ecx,16(%ebx)
jz .L032pw_end
movl $0,%ecx
movl 20(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
decl %ebp
movl %ecx,20(%ebx)
jz .L032pw_end
movl $0,%ecx
movl 24(%edi),%edx
subl %eax,%ecx
movl $0,%eax
adcl %eax,%eax
subl %edx,%ecx
adcl $0,%eax
movl %ecx,24(%ebx)
jmp .L032pw_end
.L033pw_pos:
andl $4294967288,%ebp
jz .L036pw_pos_finish
.L037pw_pos_loop:
movl (%esi),%ecx
subl %eax,%ecx
movl %ecx,(%ebx)
jnc .L038pw_nc0
movl 4(%esi),%ecx
subl %eax,%ecx
movl %ecx,4(%ebx)
jnc .L039pw_nc1
movl 8(%esi),%ecx
subl %eax,%ecx
movl %ecx,8(%ebx)
jnc .L040pw_nc2
movl 12(%esi),%ecx
subl %eax,%ecx
movl %ecx,12(%ebx)
jnc .L041pw_nc3
movl 16(%esi),%ecx
subl %eax,%ecx
movl %ecx,16(%ebx)
jnc .L042pw_nc4
movl 20(%esi),%ecx
subl %eax,%ecx
movl %ecx,20(%ebx)
jnc .L043pw_nc5
movl 24(%esi),%ecx
subl %eax,%ecx
movl %ecx,24(%ebx)
jnc .L044pw_nc6
movl 28(%esi),%ecx
subl %eax,%ecx
movl %ecx,28(%ebx)
jnc .L045pw_nc7
addl $32,%esi
addl $32,%ebx
subl $8,%ebp
jnz .L037pw_pos_loop
.L036pw_pos_finish:
movl 36(%esp),%ebp
andl $7,%ebp
jz .L032pw_end
movl (%esi),%ecx
subl %eax,%ecx
movl %ecx,(%ebx)
jnc .L046pw_tail_nc0
decl %ebp
jz .L032pw_end
movl 4(%esi),%ecx
subl %eax,%ecx
movl %ecx,4(%ebx)
jnc .L047pw_tail_nc1
decl %ebp
jz .L032pw_end
movl 8(%esi),%ecx
subl %eax,%ecx
movl %ecx,8(%ebx)
jnc .L048pw_tail_nc2
decl %ebp
jz .L032pw_end
movl 12(%esi),%ecx
subl %eax,%ecx
movl %ecx,12(%ebx)
jnc .L049pw_tail_nc3
decl %ebp
jz .L032pw_end
movl 16(%esi),%ecx
subl %eax,%ecx
movl %ecx,16(%ebx)
jnc .L050pw_tail_nc4
decl %ebp
jz .L032pw_end
movl 20(%esi),%ecx
subl %eax,%ecx
movl %ecx,20(%ebx)
jnc .L051pw_tail_nc5
decl %ebp
jz .L032pw_end
movl 24(%esi),%ecx
subl %eax,%ecx
movl %ecx,24(%ebx)
jnc .L052pw_tail_nc6
movl $1,%eax
jmp .L032pw_end
.L053pw_nc_loop:
movl (%esi),%ecx
movl %ecx,(%ebx)
.L038pw_nc0:
movl 4(%esi),%ecx
movl %ecx,4(%ebx)
.L039pw_nc1:
movl 8(%esi),%ecx
movl %ecx,8(%ebx)
.L040pw_nc2:
movl 12(%esi),%ecx
movl %ecx,12(%ebx)
.L041pw_nc3:
movl 16(%esi),%ecx
movl %ecx,16(%ebx)
.L042pw_nc4:
movl 20(%esi),%ecx
movl %ecx,20(%ebx)
.L043pw_nc5:
movl 24(%esi),%ecx
movl %ecx,24(%ebx)
.L044pw_nc6:
movl 28(%esi),%ecx
movl %ecx,28(%ebx)
.L045pw_nc7:
addl $32,%esi
addl $32,%ebx
subl $8,%ebp
jnz .L053pw_nc_loop
movl 36(%esp),%ebp
andl $7,%ebp
jz .L054pw_nc_end
movl (%esi),%ecx
movl %ecx,(%ebx)
.L046pw_tail_nc0:
decl %ebp
jz .L054pw_nc_end
movl 4(%esi),%ecx
movl %ecx,4(%ebx)
.L047pw_tail_nc1:
decl %ebp
jz .L054pw_nc_end
movl 8(%esi),%ecx
movl %ecx,8(%ebx)
.L048pw_tail_nc2:
decl %ebp
jz .L054pw_nc_end
movl 12(%esi),%ecx
movl %ecx,12(%ebx)
.L049pw_tail_nc3:
decl %ebp
jz .L054pw_nc_end
movl 16(%esi),%ecx
movl %ecx,16(%ebx)
.L050pw_tail_nc4:
decl %ebp
jz .L054pw_nc_end
movl 20(%esi),%ecx
movl %ecx,20(%ebx)
.L051pw_tail_nc5:
decl %ebp
jz .L054pw_nc_end
movl 24(%esi),%ecx
movl %ecx,24(%ebx)
.L052pw_tail_nc6:
.L054pw_nc_end:
movl $0,%eax
.L032pw_end:
popl %edi
popl %esi
popl %ebx
popl %ebp
ret
.size bn_sub_part_words,.-.L_bn_sub_part_words_begin
#endif
.section .note.GNU-stack,"",@progbits
#endif // defined(__i386__) && defined(__linux__)
@@ -732,7 +732,7 @@ void bn_mod_exp_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num,
num_p--;
}
if (num_p == 0) {
bn_from_montgomery_small(r, mont->RR.d, num, mont);
bn_from_montgomery_small(r, num, mont->RR.d, num, mont);
return;
}
unsigned bits = BN_num_bits_word(p[num_p - 1]) + (num_p - 1) * BN_BITS2;
@@ -809,8 +809,8 @@ void bn_mod_exp_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num,
OPENSSL_cleanse(val, sizeof(val));
}
void bn_mod_inverse_prime_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num,
const BN_MONT_CTX *mont) {
void bn_mod_inverse0_prime_mont_small(BN_ULONG *r, const BN_ULONG *a,
size_t num, const BN_MONT_CTX *mont) {
if (num != (size_t)mont->N.width || num > BN_SMALL_MAX_WORDS) {
abort();
}
@@ -404,9 +404,19 @@ uint64_t bn_mont_n0(const BIGNUM *n);
int bn_mod_exp_base_2_consttime(BIGNUM *r, unsigned p, const BIGNUM *n,
BN_CTX *ctx);
#if defined(OPENSSL_X86_64) && defined(_MSC_VER)
#if defined(_MSC_VER)
#if defined(OPENSSL_X86_64)
#define BN_UMULT_LOHI(low, high, a, b) ((low) = _umul128((a), (b), &(high)))
#elif defined(OPENSSL_AARCH64)
#define BN_UMULT_LOHI(low, high, a, b) \
do { \
const BN_ULONG _a = (a); \
const BN_ULONG _b = (b); \
(low) = _a * _b; \
(high) = __umulh(_a, _b); \
} while (0)
#endif
#endif // _MSC_VER
#if !defined(BN_ULLONG) && !defined(BN_UMULT_LOHI)
#error "Either BN_ULLONG or BN_UMULT_LOHI must be defined on every platform."
@@ -647,10 +657,13 @@ void bn_to_montgomery_small(BN_ULONG *r, const BN_ULONG *a, size_t num,
const BN_MONT_CTX *mont);
// bn_from_montgomery_small sets |r| to |a| translated out of the Montgomery
// domain. |r| and |a| are |num| words long, which must be |mont->N.width|. |a|
// must be fully-reduced and may alias |r|.
void bn_from_montgomery_small(BN_ULONG *r, const BN_ULONG *a, size_t num,
const BN_MONT_CTX *mont);
// domain. |r| and |a| are |num_r| and |num_a| words long, respectively. |num_r|
// must be |mont->N.width|. |a| must be at most |mont->N|^2 and may alias |r|.
//
// Unlike most of these functions, only |num_r| is bounded by
// |BN_SMALL_MAX_WORDS|. |num_a| may exceed it, but must be at most 2 * |num_r|.
void bn_from_montgomery_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a,
size_t num_a, const BN_MONT_CTX *mont);
// bn_mod_mul_montgomery_small sets |r| to |a| * |b| mod |mont->N|. Both inputs
// and outputs are in the Montgomery domain. Each array is |num| words long,
@@ -675,13 +688,13 @@ void bn_mod_exp_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num,
const BN_ULONG *p, size_t num_p,
const BN_MONT_CTX *mont);
// bn_mod_inverse_prime_mont_small sets |r| to |a|^-1 mod |mont->N|. |mont->N|
// must be a prime. |r| and |a| are |num| words long, which must be
// |mont->N.width| and at most |BN_SMALL_MAX_WORDS|. |a| must be fully-reduced
// and may alias |r|. This function runs in time independent of |a|, but
// |mont->N| is a public value.
void bn_mod_inverse_prime_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num,
const BN_MONT_CTX *mont);
// bn_mod_inverse0_prime_mont_small sets |r| to |a|^-1 mod |mont->N|. If |a| is
// zero, |r| is set to zero. |mont->N| must be a prime. |r| and |a| are |num|
// words long, which must be |mont->N.width| and at most |BN_SMALL_MAX_WORDS|.
// |a| must be fully-reduced and may alias |r|. This function runs in time
// independent of |a|, but |mont->N| is a public value.
void bn_mod_inverse0_prime_mont_small(BN_ULONG *r, const BN_ULONG *a,
size_t num, const BN_MONT_CTX *mont);
#if defined(__cplusplus)
@@ -455,18 +455,18 @@ void bn_to_montgomery_small(BN_ULONG *r, const BN_ULONG *a, size_t num,
bn_mod_mul_montgomery_small(r, a, mont->RR.d, num, mont);
}
void bn_from_montgomery_small(BN_ULONG *r, const BN_ULONG *a, size_t num,
const BN_MONT_CTX *mont) {
if (num != (size_t)mont->N.width || num > BN_SMALL_MAX_WORDS) {
void bn_from_montgomery_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a,
size_t num_a, const BN_MONT_CTX *mont) {
if (num_r != (size_t)mont->N.width || num_r > BN_SMALL_MAX_WORDS ||
num_a > 2 * num_r) {
abort();
}
BN_ULONG tmp[BN_SMALL_MAX_WORDS * 2];
OPENSSL_memcpy(tmp, a, num * sizeof(BN_ULONG));
OPENSSL_memset(tmp + num, 0, num * sizeof(BN_ULONG));
if (!bn_from_montgomery_in_place(r, num, tmp, 2 * num, mont)) {
BN_ULONG tmp[BN_SMALL_MAX_WORDS * 2] = {0};
OPENSSL_memcpy(tmp, a, num_a * sizeof(BN_ULONG));
if (!bn_from_montgomery_in_place(r, num_r, tmp, 2 * num_r, mont)) {
abort();
}
OPENSSL_cleanse(tmp, 2 * num * sizeof(BN_ULONG));
OPENSSL_cleanse(tmp, 2 * num_r * sizeof(BN_ULONG));
}
void bn_mod_mul_montgomery_small(BN_ULONG *r, const BN_ULONG *a,
@@ -119,26 +119,20 @@ static void bn_mul_normal(BN_ULONG *r, const BN_ULONG *a, size_t na,
}
}
#if !defined(OPENSSL_X86) || defined(OPENSSL_NO_ASM)
// Here follows specialised variants of bn_add_words() and bn_sub_words(). They
// have the property performing operations on arrays of different sizes. The
// sizes of those arrays is expressed through cl, which is the common length (
// basicall, min(len(a),len(b)) ), and dl, which is the delta between the two
// lengths, calculated as len(a)-len(b). All lengths are the number of
// BN_ULONGs... For the operations that require a result array as parameter,
// it must have the length cl+abs(dl). These functions should probably end up
// in bn_asm.c as soon as there are assembler counterparts for the systems that
// use assembler files.
// bn_sub_part_words sets |r| to |a| - |b|. It returns the borrow bit, which is
// one if the operation underflowed and zero otherwise. |cl| is the common
// length, that is, the shorter of len(a) or len(b). |dl| is the delta length,
// that is, len(a) - len(b). |r|'s length matches the larger of |a| and |b|, or
// cl + abs(dl).
//
// TODO(davidben): Make this take |size_t|. The |cl| + |dl| calling convention
// is confusing.
static BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a,
const BN_ULONG *b, int cl, int dl) {
BN_ULONG c, t;
assert(cl >= 0);
c = bn_sub_words(r, a, b, cl);
BN_ULONG borrow = bn_sub_words(r, a, b, cl);
if (dl == 0) {
return c;
return borrow;
}
r += cl;
@@ -146,147 +140,26 @@ static BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a,
b += cl;
if (dl < 0) {
for (;;) {
t = b[0];
r[0] = 0 - t - c;
if (t != 0) {
c = 1;
}
if (++dl >= 0) {
break;
}
t = b[1];
r[1] = 0 - t - c;
if (t != 0) {
c = 1;
}
if (++dl >= 0) {
break;
}
t = b[2];
r[2] = 0 - t - c;
if (t != 0) {
c = 1;
}
if (++dl >= 0) {
break;
}
t = b[3];
r[3] = 0 - t - c;
if (t != 0) {
c = 1;
}
if (++dl >= 0) {
break;
}
b += 4;
r += 4;
// |a| is shorter than |b|. Complete the subtraction as if the excess words
// in |a| were zeros.
dl = -dl;
for (int i = 0; i < dl; i++) {
r[i] = 0u - b[i] - borrow;
borrow |= r[i] != 0;
}
} else {
int save_dl = dl;
while (c) {
t = a[0];
r[0] = t - c;
if (t != 0) {
c = 0;
}
if (--dl <= 0) {
break;
}
t = a[1];
r[1] = t - c;
if (t != 0) {
c = 0;
}
if (--dl <= 0) {
break;
}
t = a[2];
r[2] = t - c;
if (t != 0) {
c = 0;
}
if (--dl <= 0) {
break;
}
t = a[3];
r[3] = t - c;
if (t != 0) {
c = 0;
}
if (--dl <= 0) {
break;
}
save_dl = dl;
a += 4;
r += 4;
}
if (dl > 0) {
if (save_dl > dl) {
switch (save_dl - dl) {
case 1:
r[1] = a[1];
if (--dl <= 0) {
break;
}
OPENSSL_FALLTHROUGH;
case 2:
r[2] = a[2];
if (--dl <= 0) {
break;
}
OPENSSL_FALLTHROUGH;
case 3:
r[3] = a[3];
if (--dl <= 0) {
break;
}
}
a += 4;
r += 4;
}
}
if (dl > 0) {
for (;;) {
r[0] = a[0];
if (--dl <= 0) {
break;
}
r[1] = a[1];
if (--dl <= 0) {
break;
}
r[2] = a[2];
if (--dl <= 0) {
break;
}
r[3] = a[3];
if (--dl <= 0) {
break;
}
a += 4;
r += 4;
}
// |b| is shorter than |a|. Complete the subtraction as if the excess words
// in |b| were zeros.
for (int i = 0; i < dl; i++) {
// |r| and |a| may alias, so use a temporary.
BN_ULONG tmp = a[i];
r[i] = a[i] - borrow;
borrow = tmp < r[i];
}
}
return c;
return borrow;
}
#else
// On other platforms the function is defined in asm.
BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b,
int cl, int dl);
#endif
// bn_abs_sub_part_words computes |r| = |a| - |b|, storing the absolute value
// and returning a mask of all ones if the result was negative and all zeros if
@@ -294,8 +167,7 @@ BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b,
// convention.
//
// TODO(davidben): Make this take |size_t|. The |cl| + |dl| calling convention
// is confusing. The trouble is 32-bit x86 implements |bn_sub_part_words| in
// assembly, but we can probably just delete it?
// is confusing.
static BN_ULONG bn_abs_sub_part_words(BN_ULONG *r, const BN_ULONG *a,
const BN_ULONG *b, int cl, int dl,
BN_ULONG *tmp) {
@@ -583,7 +455,7 @@ static int bn_mul_impl(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
static const int kMulNormalSize = 16;
if (al >= kMulNormalSize && bl >= kMulNormalSize) {
if (-1 <= i && i <= 1) {
// Find the larger power of two less than or equal to the larger length.
// Find the largest power of two less than or equal to the larger length.
int j;
if (i >= 0) {
j = BN_num_bits_word((BN_ULONG)al);
@@ -599,6 +471,10 @@ static int bn_mul_impl(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
if (al > j || bl > j) {
// We know |al| and |bl| are at most one from each other, so if al > j,
// bl >= j, and vice versa. Thus we can use |bn_mul_part_recursive|.
//
// TODO(davidben): This codepath is almost unused in standard
// algorithms. Is this optimization necessary? See notes in
// https://boringssl-review.googlesource.com/q/I0bd604e2cd6a75c266f64476c23a730ca1721ea6
assert(al >= j && bl >= j);
if (!bn_wexpand(t, j * 8) ||
!bn_wexpand(rr, j * 4)) {
@@ -122,6 +122,8 @@ int EVP_DigestFinalXOF(EVP_MD_CTX *ctx, uint8_t *out, size_t len) {
uint32_t EVP_MD_meth_get_flags(const EVP_MD *md) { return EVP_MD_flags(md); }
void EVP_MD_CTX_set_flags(EVP_MD_CTX *ctx, int flags) {}
int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in) {
// |in->digest| may be NULL if this is a signing |EVP_MD_CTX| for, e.g.,
// Ed25519 which does not hash with |EVP_MD_CTX|.
@@ -243,6 +243,22 @@ DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha512) {
}
static void sha512_256_init(EVP_MD_CTX *ctx) {
CHECK(SHA512_256_Init(ctx->md_data));
}
DEFINE_METHOD_FUNCTION(EVP_MD, EVP_sha512_256) {
out->type = NID_sha512_256;
out->md_size = SHA512_256_DIGEST_LENGTH;
out->flags = 0;
out->init = sha512_256_init;
out->update = sha512_update;
out->final = sha512_final;
out->block_size = 128;
out->ctx_size = sizeof(SHA512_CTX);
}
typedef struct {
MD5_CTX md5;
SHA_CTX sha1;
+289 -117
View File
@@ -84,7 +84,7 @@
static void ec_point_free(EC_POINT *point, int free_group);
static const uint8_t kP224Params[6 * 28] = {
// p
// p = 2^224 - 2^96 + 1
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01,
@@ -111,7 +111,7 @@ static const uint8_t kP224Params[6 * 28] = {
};
static const uint8_t kP256Params[6 * 32] = {
// p
// p = 2^256 - 2^224 + 2^192 + 2^96 - 1
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
@@ -138,7 +138,7 @@ static const uint8_t kP256Params[6 * 32] = {
};
static const uint8_t kP384Params[6 * 48] = {
// p
// p = 2^384 - 2^128 - 2^96 + 2^32 - 1
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF,
@@ -171,7 +171,7 @@ static const uint8_t kP384Params[6 * 48] = {
};
static const uint8_t kP521Params[6 * 66] = {
// p
// p = 2^521 - 1
0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
@@ -301,17 +301,49 @@ EC_GROUP *ec_group_new(const EC_METHOD *meth) {
return ret;
}
static void ec_group_set0_generator(EC_GROUP *group, EC_POINT *generator) {
static int ec_group_set_generator(EC_GROUP *group, const EC_AFFINE *generator,
const BIGNUM *order) {
assert(group->generator == NULL);
assert(group == generator->group);
if (!BN_copy(&group->order, order)) {
return 0;
}
// Store the order in minimal form, so it can be used with |BN_ULONG| arrays.
bn_set_minimal_width(&group->order);
BN_MONT_CTX_free(group->order_mont);
group->order_mont = BN_MONT_CTX_new_for_modulus(&group->order, NULL);
if (group->order_mont == NULL) {
return 0;
}
group->field_greater_than_order = BN_cmp(&group->field, order) > 0;
if (group->field_greater_than_order) {
BIGNUM tmp;
BN_init(&tmp);
int ok =
BN_sub(&tmp, &group->field, order) &&
bn_copy_words(group->field_minus_order.words, group->field.width, &tmp);
BN_free(&tmp);
if (!ok) {
return 0;
}
}
group->generator = EC_POINT_new(group);
if (group->generator == NULL) {
return 0;
}
ec_affine_to_jacobian(group, &group->generator->raw, generator);
assert(ec_felem_equal(group, &group->one, &group->generator->raw.Z));
// Avoid a reference cycle. |group->generator| does not maintain an owning
// pointer to |group|.
group->generator = generator;
int is_zero = CRYPTO_refcount_dec_and_test_zero(&group->references);
assert(!is_zero);
(void)is_zero;
return 1;
}
EC_GROUP *EC_GROUP_new_curve_GFp(const BIGNUM *p, const BIGNUM *a,
@@ -321,20 +353,37 @@ EC_GROUP *EC_GROUP_new_curve_GFp(const BIGNUM *p, const BIGNUM *a,
return NULL;
}
EC_GROUP *ret = ec_group_new(EC_GFp_mont_method());
if (ret == NULL) {
return NULL;
BN_CTX *new_ctx = NULL;
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL) {
return NULL;
}
}
if (ret->meth->group_set_curve == NULL) {
OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
EC_GROUP_free(ret);
return NULL;
// Historically, |a| and |b| were not required to be fully reduced.
// TODO(davidben): Can this be removed?
EC_GROUP *ret = NULL;
BN_CTX_start(ctx);
BIGNUM *a_reduced = BN_CTX_get(ctx);
BIGNUM *b_reduced = BN_CTX_get(ctx);
if (a_reduced == NULL || b_reduced == NULL ||
!BN_nnmod(a_reduced, a, p, ctx) ||
!BN_nnmod(b_reduced, b, p, ctx)) {
goto err;
}
if (!ret->meth->group_set_curve(ret, p, a, b, ctx)) {
ret = ec_group_new(EC_GFp_mont_method());
if (ret == NULL ||
!ret->meth->group_set_curve(ret, p, a_reduced, b_reduced, ctx)) {
EC_GROUP_free(ret);
return NULL;
ret = NULL;
goto err;
}
err:
BN_CTX_end(ctx);
BN_CTX_free(new_ctx);
return ret;
}
@@ -367,7 +416,6 @@ int EC_GROUP_set_generator(EC_GROUP *group, const EC_POINT *generator,
// tiny prime (less than 17). See the proof in |field_element_to_scalar| in
// the ECDSA implementation.
int ret = 0;
EC_POINT *copy = NULL;
BIGNUM *tmp = BN_new();
if (tmp == NULL ||
!BN_lshift1(tmp, order)) {
@@ -378,44 +426,22 @@ int EC_GROUP_set_generator(EC_GROUP *group, const EC_POINT *generator,
goto err;
}
copy = EC_POINT_new(group);
if (copy == NULL ||
!EC_POINT_copy(copy, generator) ||
!BN_copy(&group->order, order)) {
goto err;
}
// Store the order in minimal form, so it can be used with |BN_ULONG| arrays.
bn_set_minimal_width(&group->order);
BN_MONT_CTX_free(group->order_mont);
group->order_mont = BN_MONT_CTX_new_for_modulus(&group->order, NULL);
if (group->order_mont == NULL) {
EC_AFFINE affine;
if (!ec_jacobian_to_affine(group, &affine, &generator->raw) ||
!ec_group_set_generator(group, &affine, order)) {
goto err;
}
group->field_greater_than_order = BN_cmp(&group->field, &group->order) > 0;
if (group->field_greater_than_order) {
if (!BN_sub(tmp, &group->field, &group->order) ||
!bn_copy_words(group->field_minus_order.words, group->field.width,
tmp)) {
goto err;
}
}
ec_group_set0_generator(group, copy);
copy = NULL;
ret = 1;
err:
EC_POINT_free(copy);
BN_free(tmp);
return ret;
}
static EC_GROUP *ec_group_new_from_data(const struct built_in_curve *curve) {
EC_GROUP *group = NULL;
EC_POINT *P = NULL;
BIGNUM *p = NULL, *a = NULL, *b = NULL, *x = NULL, *y = NULL;
BIGNUM *p = NULL, *a = NULL, *b = NULL, *order = NULL;
int ok = 0;
BN_CTX *ctx = BN_CTX_new();
@@ -429,7 +455,8 @@ static EC_GROUP *ec_group_new_from_data(const struct built_in_curve *curve) {
if (!(p = BN_bin2bn(params + 0 * param_len, param_len, NULL)) ||
!(a = BN_bin2bn(params + 1 * param_len, param_len, NULL)) ||
!(b = BN_bin2bn(params + 2 * param_len, param_len, NULL))) {
!(b = BN_bin2bn(params + 2 * param_len, param_len, NULL)) ||
!(order = BN_bin2bn(params + 5 * param_len, param_len, NULL))) {
OPENSSL_PUT_ERROR(EC, ERR_R_BN_LIB);
goto err;
}
@@ -441,42 +468,18 @@ static EC_GROUP *ec_group_new_from_data(const struct built_in_curve *curve) {
goto err;
}
if ((P = EC_POINT_new(group)) == NULL) {
OPENSSL_PUT_ERROR(EC, ERR_R_EC_LIB);
EC_AFFINE G;
EC_FELEM x, y;
if (!ec_felem_from_bytes(group, &x, params + 3 * param_len, param_len) ||
!ec_felem_from_bytes(group, &y, params + 4 * param_len, param_len) ||
!ec_point_set_affine_coordinates(group, &G, &x, &y)) {
goto err;
}
if (!(x = BN_bin2bn(params + 3 * param_len, param_len, NULL)) ||
!(y = BN_bin2bn(params + 4 * param_len, param_len, NULL))) {
OPENSSL_PUT_ERROR(EC, ERR_R_BN_LIB);
if (!ec_group_set_generator(group, &G, order)) {
goto err;
}
if (!EC_POINT_set_affine_coordinates_GFp(group, P, x, y, ctx)) {
OPENSSL_PUT_ERROR(EC, ERR_R_EC_LIB);
goto err;
}
if (!BN_bin2bn(params + 5 * param_len, param_len, &group->order)) {
OPENSSL_PUT_ERROR(EC, ERR_R_BN_LIB);
goto err;
}
group->field_greater_than_order = BN_cmp(&group->field, &group->order) > 0;
if (group->field_greater_than_order) {
if (!BN_sub(p, &group->field, &group->order) ||
!bn_copy_words(group->field_minus_order.words, group->field.width, p)) {
goto err;
}
}
group->order_mont = BN_MONT_CTX_new_for_modulus(&group->order, ctx);
if (group->order_mont == NULL) {
OPENSSL_PUT_ERROR(EC, ERR_R_BN_LIB);
goto err;
}
ec_group_set0_generator(group, P);
P = NULL;
ok = 1;
err:
@@ -484,13 +487,11 @@ err:
EC_GROUP_free(group);
group = NULL;
}
EC_POINT_free(P);
BN_CTX_free(ctx);
BN_free(p);
BN_free(a);
BN_free(b);
BN_free(x);
BN_free(y);
BN_free(order);
return group;
}
@@ -606,7 +607,7 @@ int EC_GROUP_cmp(const EC_GROUP *a, const EC_GROUP *b, BN_CTX *ignored) {
BN_cmp(&a->field, &b->field) != 0 ||
!ec_felem_equal(a, &a->a, &b->a) ||
!ec_felem_equal(a, &a->b, &b->b) ||
ec_GFp_simple_cmp(a, &a->generator->raw, &b->generator->raw) != 0;
!ec_GFp_simple_points_equal(a, &a->generator->raw, &b->generator->raw);
}
const EC_POINT *EC_GROUP_get0_generator(const EC_GROUP *group) {
@@ -769,7 +770,9 @@ int EC_POINT_cmp(const EC_GROUP *group, const EC_POINT *a, const EC_POINT *b,
OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS);
return -1;
}
return ec_GFp_simple_cmp(group, &a->raw, &b->raw);
// Note |EC_POINT_cmp| returns zero for equality and non-zero for inequality.
return ec_GFp_simple_points_equal(group, &a->raw, &b->raw) ? 0 : 1;
}
int EC_POINT_get_affine_coordinates_GFp(const EC_GROUP *group,
@@ -787,13 +790,67 @@ int EC_POINT_get_affine_coordinates_GFp(const EC_GROUP *group,
if (!group->meth->point_get_affine_coordinates(group, &point->raw,
x == NULL ? NULL : &x_felem,
y == NULL ? NULL : &y_felem) ||
(x != NULL && !bn_set_words(x, x_felem.words, group->field.width)) ||
(y != NULL && !bn_set_words(y, y_felem.words, group->field.width))) {
(x != NULL && !ec_felem_to_bignum(group, x, &x_felem)) ||
(y != NULL && !ec_felem_to_bignum(group, y, &y_felem))) {
return 0;
}
return 1;
}
void ec_affine_to_jacobian(const EC_GROUP *group, EC_RAW_POINT *out,
const EC_AFFINE *p) {
out->X = p->X;
out->Y = p->Y;
out->Z = group->one;
}
int ec_jacobian_to_affine(const EC_GROUP *group, EC_AFFINE *out,
const EC_RAW_POINT *p) {
return group->meth->point_get_affine_coordinates(group, p, &out->X, &out->Y);
}
int ec_jacobian_to_affine_batch(const EC_GROUP *group, EC_AFFINE *out,
const EC_RAW_POINT *in, size_t num) {
if (group->meth->jacobian_to_affine_batch == NULL) {
OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
return group->meth->jacobian_to_affine_batch(group, out, in, num);
}
int ec_point_set_affine_coordinates(const EC_GROUP *group, EC_AFFINE *out,
const EC_FELEM *x, const EC_FELEM *y) {
void (*const felem_mul)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a,
const EC_FELEM *b) = group->meth->felem_mul;
void (*const felem_sqr)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a) =
group->meth->felem_sqr;
// Check if the point is on the curve.
EC_FELEM lhs, rhs;
felem_sqr(group, &lhs, y); // lhs = y^2
felem_sqr(group, &rhs, x); // rhs = x^2
ec_felem_add(group, &rhs, &rhs, &group->a); // rhs = x^2 + a
felem_mul(group, &rhs, &rhs, x); // rhs = x^3 + ax
ec_felem_add(group, &rhs, &rhs, &group->b); // rhs = x^3 + ax + b
if (!ec_felem_equal(group, &lhs, &rhs)) {
OPENSSL_PUT_ERROR(EC, EC_R_POINT_IS_NOT_ON_CURVE);
// In the event of an error, defend against the caller not checking the
// return value by setting a known safe value. Note this may not be possible
// if the caller is in the process of constructing an arbitrary group and
// the generator is missing.
if (group->generator != NULL) {
assert(ec_felem_equal(group, &group->one, &group->generator->raw.Z));
out->X = group->generator->raw.X;
out->Y = group->generator->raw.Y;
}
return 0;
}
out->X = *x;
out->Y = *y;
return 1;
}
int EC_POINT_set_affine_coordinates_GFp(const EC_GROUP *group, EC_POINT *point,
const BIGNUM *x, const BIGNUM *y,
BN_CTX *ctx) {
@@ -801,24 +858,24 @@ int EC_POINT_set_affine_coordinates_GFp(const EC_GROUP *group, EC_POINT *point,
OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
if (!ec_GFp_simple_point_set_affine_coordinates(group, &point->raw, x, y)) {
if (x == NULL || y == NULL) {
OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (!EC_POINT_is_on_curve(group, point, ctx)) {
EC_FELEM x_felem, y_felem;
EC_AFFINE affine;
if (!ec_bignum_to_felem(group, &x_felem, x) ||
!ec_bignum_to_felem(group, &y_felem, y) ||
!ec_point_set_affine_coordinates(group, &affine, &x_felem, &y_felem)) {
// In the event of an error, defend against the caller not checking the
// return value by setting a known safe value: the base point.
const EC_POINT *generator = EC_GROUP_get0_generator(group);
// The generator can be missing if the caller is in the process of
// constructing an arbitrary group. In this, we give up and hope they're
// checking the return value.
if (generator) {
ec_GFp_simple_point_copy(&point->raw, &generator->raw);
}
OPENSSL_PUT_ERROR(EC, EC_R_POINT_IS_NOT_ON_CURVE);
// return value by setting a known safe value.
ec_set_to_safe_point(group, &point->raw);
return 0;
}
ec_affine_to_jacobian(group, &point->raw, &affine);
return 1;
}
@@ -949,10 +1006,27 @@ int ec_point_mul_scalar_public(const EC_GROUP *group, EC_RAW_POINT *r,
return 0;
}
if (group->meth->mul_public == NULL) {
return group->meth->mul_public_batch(group, r, g_scalar, p, p_scalar, 1);
}
group->meth->mul_public(group, r, g_scalar, p, p_scalar);
return 1;
}
int ec_point_mul_scalar_public_batch(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_SCALAR *g_scalar,
const EC_RAW_POINT *points,
const EC_SCALAR *scalars, size_t num) {
if (group->meth->mul_public_batch == NULL) {
OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
return group->meth->mul_public_batch(group, r, g_scalar, points, scalars,
num);
}
int ec_point_mul_scalar(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_RAW_POINT *p, const EC_SCALAR *scalar) {
if (p == NULL || scalar == NULL) {
@@ -961,6 +1035,14 @@ int ec_point_mul_scalar(const EC_GROUP *group, EC_RAW_POINT *r,
}
group->meth->mul(group, r, p, scalar);
// Check the result is on the curve to defend against fault attacks or bugs.
// This has negligible cost compared to the multiplication.
if (!ec_GFp_simple_is_on_curve(group, r)) {
OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
@@ -972,9 +1054,93 @@ int ec_point_mul_scalar_base(const EC_GROUP *group, EC_RAW_POINT *r,
}
group->meth->mul_base(group, r, scalar);
// Check the result is on the curve to defend against fault attacks or bugs.
// This has negligible cost compared to the multiplication.
if (!ec_GFp_simple_is_on_curve(group, r)) {
OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
int ec_point_mul_scalar_batch(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_RAW_POINT *p0, const EC_SCALAR *scalar0,
const EC_RAW_POINT *p1, const EC_SCALAR *scalar1,
const EC_RAW_POINT *p2,
const EC_SCALAR *scalar2) {
if (group->meth->mul_batch == NULL) {
OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
group->meth->mul_batch(group, r, p0, scalar0, p1, scalar1, p2, scalar2);
// Check the result is on the curve to defend against fault attacks or bugs.
// This has negligible cost compared to the multiplication.
if (!ec_GFp_simple_is_on_curve(group, r)) {
OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
int ec_init_precomp(const EC_GROUP *group, EC_PRECOMP *out,
const EC_RAW_POINT *p) {
if (group->meth->init_precomp == NULL) {
OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
return group->meth->init_precomp(group, out, p);
}
int ec_point_mul_scalar_precomp(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_PRECOMP *p0, const EC_SCALAR *scalar0,
const EC_PRECOMP *p1, const EC_SCALAR *scalar1,
const EC_PRECOMP *p2,
const EC_SCALAR *scalar2) {
if (group->meth->mul_precomp == NULL) {
OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
group->meth->mul_precomp(group, r, p0, scalar0, p1, scalar1, p2, scalar2);
// Check the result is on the curve to defend against fault attacks or bugs.
// This has negligible cost compared to the multiplication.
if (!ec_GFp_simple_is_on_curve(group, r)) {
OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
void ec_point_select(const EC_GROUP *group, EC_RAW_POINT *out, BN_ULONG mask,
const EC_RAW_POINT *a, const EC_RAW_POINT *b) {
ec_felem_select(group, &out->X, mask, &a->X, &b->X);
ec_felem_select(group, &out->Y, mask, &a->Y, &b->Y);
ec_felem_select(group, &out->Z, mask, &a->Z, &b->Z);
}
void ec_affine_select(const EC_GROUP *group, EC_AFFINE *out, BN_ULONG mask,
const EC_AFFINE *a, const EC_AFFINE *b) {
ec_felem_select(group, &out->X, mask, &a->X, &b->X);
ec_felem_select(group, &out->Y, mask, &a->Y, &b->Y);
}
void ec_precomp_select(const EC_GROUP *group, EC_PRECOMP *out, BN_ULONG mask,
const EC_PRECOMP *a, const EC_PRECOMP *b) {
OPENSSL_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++) {
ec_affine_select(group, &out->comb[i], mask, &a->comb[i], &b->comb[i]);
}
}
int ec_cmp_x_coordinate(const EC_GROUP *group, const EC_RAW_POINT *p,
const EC_SCALAR *r) {
return group->meth->cmp_x_coordinate(group, p, r);
@@ -982,14 +1148,19 @@ int ec_cmp_x_coordinate(const EC_GROUP *group, const EC_RAW_POINT *p,
int ec_get_x_coordinate_as_scalar(const EC_GROUP *group, EC_SCALAR *out,
const EC_RAW_POINT *p) {
EC_FELEM x;
// For simplicity, in case of width mismatches between |group->field| and
// |group->order|, zero any untouched words in |x|.
OPENSSL_memset(&x, 0, sizeof(x));
if (!group->meth->point_get_affine_coordinates(group, p, &x, NULL)) {
uint8_t bytes[EC_MAX_BYTES];
size_t len;
if (!ec_get_x_coordinate_as_bytes(group, bytes, &len, sizeof(bytes), p)) {
return 0;
}
// For simplicity, in case of width mismatches between |group->field| and
// |group->order|, zero any untouched words in |out|.
OPENSSL_memset(out, 0, sizeof(EC_SCALAR));
for (size_t i = 0; i < len; i++) {
out->bytes[len - i - 1] = bytes[i];
}
// We must have p < 2×order, assuming p is not tiny (p >= 17). Thus rather we
// can reduce by performing at most one subtraction.
//
@@ -1008,17 +1179,17 @@ int ec_get_x_coordinate_as_scalar(const EC_GROUP *group, EC_SCALAR *out,
// The above does not guarantee |group->field| is not one word larger than
// |group->order|, so read one extra carry word.
BN_ULONG tmp[EC_MAX_WORDS];
BN_ULONG carry =
group->order.width < EC_MAX_WORDS ? x.words[group->order.width] : 0;
bn_reduce_once(out->words, x.words, carry, group->order.d,
group->order.width);
group->order.width < EC_MAX_WORDS ? out->words[group->order.width] : 0;
bn_reduce_once_in_place(out->words, carry, group->order.d, tmp,
group->order.width);
return 1;
}
int ec_point_get_affine_coordinate_bytes(const EC_GROUP *group, uint8_t *out_x,
uint8_t *out_y, size_t *out_len,
size_t max_out,
const EC_RAW_POINT *p) {
int ec_get_x_coordinate_as_bytes(const EC_GROUP *group, uint8_t *out,
size_t *out_len, size_t max_out,
const EC_RAW_POINT *p) {
size_t len = BN_num_bytes(&group->field);
assert(len <= EC_MAX_BYTES);
if (max_out < len) {
@@ -1026,26 +1197,27 @@ int ec_point_get_affine_coordinate_bytes(const EC_GROUP *group, uint8_t *out_x,
return 0;
}
EC_FELEM x, y;
if (!group->meth->point_get_affine_coordinates(
group, p, out_x == NULL ? NULL : &x, out_y == NULL ? NULL : &y)) {
EC_FELEM x;
if (!group->meth->point_get_affine_coordinates(group, p, &x, NULL)) {
return 0;
}
if (out_x != NULL) {
for (size_t i = 0; i < len; i++) {
out_x[i] = x.bytes[len - i - 1];
}
}
if (out_y != NULL) {
for (size_t i = 0; i < len; i++) {
out_y[i] = y.bytes[len - i - 1];
}
}
ec_felem_to_bytes(group, out, out_len, &x);
*out_len = len;
return 1;
}
void ec_set_to_safe_point(const EC_GROUP *group, EC_RAW_POINT *out) {
if (group->generator != NULL) {
ec_GFp_simple_point_copy(out, &group->generator->raw);
} else {
// The generator can be missing if the caller is in the process of
// constructing an arbitrary group. In this case, we give up and use the
// point at infinity.
ec_GFp_simple_point_set_to_infinity(group, out);
}
}
void EC_GROUP_set_asn1_flag(EC_GROUP *group, int flag) {}
const EC_METHOD *EC_GROUP_method_of(const EC_GROUP *group) {
@@ -292,10 +292,6 @@ void EC_KEY_set_conv_form(EC_KEY *key, point_conversion_form_t cform) {
}
int EC_KEY_check_key(const EC_KEY *eckey) {
int ok = 0;
BN_CTX *ctx = NULL;
EC_POINT *point = NULL;
if (!eckey || !eckey->group || !eckey->pub_key) {
OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
return 0;
@@ -303,41 +299,31 @@ int EC_KEY_check_key(const EC_KEY *eckey) {
if (EC_POINT_is_at_infinity(eckey->group, eckey->pub_key)) {
OPENSSL_PUT_ERROR(EC, EC_R_POINT_AT_INFINITY);
goto err;
return 0;
}
ctx = BN_CTX_new();
if (ctx == NULL) {
goto err;
}
// testing whether the pub_key is on the elliptic curve
if (!EC_POINT_is_on_curve(eckey->group, eckey->pub_key, ctx)) {
// Test whether the public key is on the elliptic curve.
if (!EC_POINT_is_on_curve(eckey->group, eckey->pub_key, NULL)) {
OPENSSL_PUT_ERROR(EC, EC_R_POINT_IS_NOT_ON_CURVE);
goto err;
return 0;
}
// in case the priv_key is present :
// check if generator * priv_key == pub_key
// Check the public and private keys match.
if (eckey->priv_key != NULL) {
point = EC_POINT_new(eckey->group);
if (point == NULL ||
!ec_point_mul_scalar_base(eckey->group, &point->raw,
EC_RAW_POINT point;
if (!ec_point_mul_scalar_base(eckey->group, &point,
&eckey->priv_key->scalar)) {
OPENSSL_PUT_ERROR(EC, ERR_R_EC_LIB);
goto err;
return 0;
}
if (EC_POINT_cmp(eckey->group, point, eckey->pub_key, ctx) != 0) {
if (!ec_GFp_simple_points_equal(eckey->group, &point,
&eckey->pub_key->raw)) {
OPENSSL_PUT_ERROR(EC, EC_R_INVALID_PRIVATE_KEY);
goto err;
return 0;
}
}
ok = 1;
err:
BN_CTX_free(ctx);
EC_POINT_free(point);
return ok;
return 1;
}
int EC_KEY_check_fips(const EC_KEY *key) {
@@ -92,35 +92,20 @@ void ec_GFp_mont_group_finish(EC_GROUP *group) {
int ec_GFp_mont_group_set_curve(EC_GROUP *group, const BIGNUM *p,
const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) {
BN_CTX *new_ctx = NULL;
int ret = 0;
BN_MONT_CTX_free(group->mont);
group->mont = NULL;
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL) {
return 0;
}
}
group->mont = BN_MONT_CTX_new_for_modulus(p, ctx);
if (group->mont == NULL) {
OPENSSL_PUT_ERROR(EC, ERR_R_BN_LIB);
goto err;
return 0;
}
ret = ec_GFp_simple_group_set_curve(group, p, a, b, ctx);
if (!ret) {
if (!ec_GFp_simple_group_set_curve(group, p, a, b, ctx)) {
BN_MONT_CTX_free(group->mont);
group->mont = NULL;
return 0;
}
err:
BN_CTX_free(new_ctx);
return ret;
return 1;
}
static void ec_GFp_mont_felem_to_montgomery(const EC_GROUP *group,
@@ -132,14 +117,14 @@ static void ec_GFp_mont_felem_to_montgomery(const EC_GROUP *group,
static void ec_GFp_mont_felem_from_montgomery(const EC_GROUP *group,
EC_FELEM *out,
const EC_FELEM *in) {
bn_from_montgomery_small(out->words, in->words, group->field.width,
group->mont);
bn_from_montgomery_small(out->words, group->field.width, in->words,
group->field.width, group->mont);
}
static void ec_GFp_mont_felem_inv(const EC_GROUP *group, EC_FELEM *out,
const EC_FELEM *a) {
bn_mod_inverse_prime_mont_small(out->words, a->words, group->field.width,
group->mont);
static void ec_GFp_mont_felem_inv0(const EC_GROUP *group, EC_FELEM *out,
const EC_FELEM *a) {
bn_mod_inverse0_prime_mont_small(out->words, a->words, group->field.width,
group->mont);
}
void ec_GFp_mont_felem_mul(const EC_GROUP *group, EC_FELEM *r,
@@ -154,30 +139,39 @@ void ec_GFp_mont_felem_sqr(const EC_GROUP *group, EC_FELEM *r,
group->mont);
}
int ec_GFp_mont_bignum_to_felem(const EC_GROUP *group, EC_FELEM *out,
const BIGNUM *in) {
if (group->mont == NULL) {
OPENSSL_PUT_ERROR(EC, EC_R_NOT_INITIALIZED);
void ec_GFp_mont_felem_to_bytes(const EC_GROUP *group, uint8_t *out,
size_t *out_len, const EC_FELEM *in) {
EC_FELEM tmp;
ec_GFp_mont_felem_from_montgomery(group, &tmp, in);
ec_GFp_simple_felem_to_bytes(group, out, out_len, &tmp);
}
int ec_GFp_mont_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out,
const uint8_t *in, size_t len) {
if (!ec_GFp_simple_felem_from_bytes(group, out, in, len)) {
return 0;
}
if (!bn_copy_words(out->words, group->field.width, in)) {
return 0;
}
ec_GFp_mont_felem_to_montgomery(group, out, out);
return 1;
}
int ec_GFp_mont_felem_to_bignum(const EC_GROUP *group, BIGNUM *out,
const EC_FELEM *in) {
if (group->mont == NULL) {
OPENSSL_PUT_ERROR(EC, EC_R_NOT_INITIALIZED);
return 0;
}
static void ec_GFp_mont_felem_reduce(const EC_GROUP *group, EC_FELEM *out,
const BN_ULONG *words, size_t num) {
// Convert "from" Montgomery form so the value is reduced mod p.
bn_from_montgomery_small(out->words, group->field.width, words, num,
group->mont);
// Convert "to" Montgomery form to remove the R^-1 factor added.
ec_GFp_mont_felem_to_montgomery(group, out, out);
// Convert to Montgomery form to match this implementation's representation.
ec_GFp_mont_felem_to_montgomery(group, out, out);
}
EC_FELEM tmp;
ec_GFp_mont_felem_from_montgomery(group, &tmp, in);
return bn_set_words(out, tmp.words, group->field.width);
static void ec_GFp_mont_felem_exp(const EC_GROUP *group, EC_FELEM *out,
const EC_FELEM *a, const BN_ULONG *exp,
size_t num_exp) {
bn_mod_exp_mont_small(out->words, a->words, group->field.width, exp, num_exp,
group->mont);
}
static int ec_GFp_mont_point_get_affine_coordinates(const EC_GROUP *group,
@@ -188,18 +182,12 @@ static int ec_GFp_mont_point_get_affine_coordinates(const EC_GROUP *group,
return 0;
}
// Transform (X, Y, Z) into (x, y) := (X/Z^2, Y/Z^3).
// Transform (X, Y, Z) into (x, y) := (X/Z^2, Y/Z^3). Note the check above
// ensures |point->Z| is non-zero, so the inverse always exists.
EC_FELEM z1, z2;
ec_GFp_mont_felem_inv(group, &z2, &point->Z);
ec_GFp_mont_felem_inv0(group, &z2, &point->Z);
ec_GFp_mont_felem_sqr(group, &z1, &z2);
// Instead of using |ec_GFp_mont_felem_from_montgomery| to convert the |x|
// coordinate and then calling |ec_GFp_mont_felem_from_montgomery| again to
// convert the |y| coordinate below, convert the common factor |z1| once now,
// saving one reduction.
ec_GFp_mont_felem_from_montgomery(group, &z1, &z1);
if (x != NULL) {
ec_GFp_mont_felem_mul(group, x, &point->X, &z1);
}
@@ -212,6 +200,52 @@ static int ec_GFp_mont_point_get_affine_coordinates(const EC_GROUP *group,
return 1;
}
static int ec_GFp_mont_jacobian_to_affine_batch(const EC_GROUP *group,
EC_AFFINE *out,
const EC_RAW_POINT *in,
size_t num) {
if (num == 0) {
return 1;
}
// Compute prefix products of all Zs. Use |out[i].X| as scratch space
// to store these values.
out[0].X = in[0].Z;
for (size_t i = 1; i < num; i++) {
ec_GFp_mont_felem_mul(group, &out[i].X, &out[i - 1].X, &in[i].Z);
}
// Some input was infinity iff the product of all Zs is zero.
if (ec_felem_non_zero_mask(group, &out[num - 1].X) == 0) {
OPENSSL_PUT_ERROR(EC, EC_R_POINT_AT_INFINITY);
return 0;
}
// Invert the product of all Zs.
EC_FELEM zinvprod;
ec_GFp_mont_felem_inv0(group, &zinvprod, &out[num - 1].X);
for (size_t i = num - 1; i < num; i--) {
// Our loop invariant is that |zinvprod| is Z0^-1 * Z1^-1 * ... * Zi^-1.
// Recover Zi^-1 by multiplying by the previous product.
EC_FELEM zinv, zinv2;
if (i == 0) {
zinv = zinvprod;
} else {
ec_GFp_mont_felem_mul(group, &zinv, &zinvprod, &out[i - 1].X);
// Maintain the loop invariant for the next iteration.
ec_GFp_mont_felem_mul(group, &zinvprod, &zinvprod, &in[i].Z);
}
// Compute affine coordinates: x = X * Z^-2 and y = Y * Z^-3.
ec_GFp_mont_felem_sqr(group, &zinv2, &zinv);
ec_GFp_mont_felem_mul(group, &out[i].X, &in[i].X, &zinv2);
ec_GFp_mont_felem_mul(group, &out[i].Y, &in[i].Y, &zinv2);
ec_GFp_mont_felem_mul(group, &out[i].Y, &out[i].Y, &zinv);
}
return 1;
}
void ec_GFp_mont_add(const EC_GROUP *group, EC_RAW_POINT *out,
const EC_RAW_POINT *a, const EC_RAW_POINT *b) {
if (a == b) {
@@ -468,16 +502,23 @@ DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_mont_method) {
out->group_finish = ec_GFp_mont_group_finish;
out->group_set_curve = ec_GFp_mont_group_set_curve;
out->point_get_affine_coordinates = ec_GFp_mont_point_get_affine_coordinates;
out->jacobian_to_affine_batch = ec_GFp_mont_jacobian_to_affine_batch;
out->add = ec_GFp_mont_add;
out->dbl = ec_GFp_mont_dbl;
out->mul = ec_GFp_mont_mul;
out->mul_base = ec_GFp_mont_mul_base;
out->mul_public = ec_GFp_mont_mul_public;
out->mul_batch = ec_GFp_mont_mul_batch;
out->mul_public_batch = ec_GFp_mont_mul_public_batch;
out->init_precomp = ec_GFp_mont_init_precomp;
out->mul_precomp = ec_GFp_mont_mul_precomp;
out->felem_mul = ec_GFp_mont_felem_mul;
out->felem_sqr = ec_GFp_mont_felem_sqr;
out->bignum_to_felem = ec_GFp_mont_bignum_to_felem;
out->felem_to_bignum = ec_GFp_mont_felem_to_bignum;
out->scalar_inv_montgomery = ec_simple_scalar_inv_montgomery;
out->scalar_inv_montgomery_vartime = ec_GFp_simple_mont_inv_mod_ord_vartime;
out->felem_to_bytes = ec_GFp_mont_felem_to_bytes;
out->felem_from_bytes = ec_GFp_mont_felem_from_bytes;
out->felem_reduce = ec_GFp_mont_felem_reduce;
out->felem_exp = ec_GFp_mont_felem_exp;
out->scalar_inv0_montgomery = ec_simple_scalar_inv0_montgomery;
out->scalar_to_montgomery_inv_vartime =
ec_simple_scalar_to_montgomery_inv_vartime;
out->cmp_x_coordinate = ec_GFp_mont_cmp_x_coordinate;
}
@@ -14,6 +14,7 @@
#include <CCryptoBoringSSL_ec.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <assert.h>
@@ -23,15 +24,34 @@
int ec_bignum_to_felem(const EC_GROUP *group, EC_FELEM *out, const BIGNUM *in) {
if (BN_is_negative(in) || BN_cmp(in, &group->field) >= 0) {
uint8_t bytes[EC_MAX_BYTES];
size_t len = BN_num_bytes(&group->field);
assert(sizeof(bytes) >= len);
if (BN_is_negative(in) ||
BN_cmp(in, &group->field) >= 0 ||
!BN_bn2bin_padded(bytes, len, in)) {
OPENSSL_PUT_ERROR(EC, EC_R_COORDINATES_OUT_OF_RANGE);
return 0;
}
return group->meth->bignum_to_felem(group, out, in);
return ec_felem_from_bytes(group, out, bytes, len);
}
int ec_felem_to_bignum(const EC_GROUP *group, BIGNUM *out, const EC_FELEM *in) {
return group->meth->felem_to_bignum(group, out, in);
uint8_t bytes[EC_MAX_BYTES];
size_t len;
ec_felem_to_bytes(group, bytes, &len, in);
return BN_bin2bn(bytes, len, out) != NULL;
}
void ec_felem_to_bytes(const EC_GROUP *group, uint8_t *out, size_t *out_len,
const EC_FELEM *in) {
group->meth->felem_to_bytes(group, out, out_len, in);
}
int ec_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out, const uint8_t *in,
size_t len) {
return group->meth->felem_from_bytes(group, out, in, len);
}
void ec_felem_neg(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a) {
@@ -75,8 +95,6 @@ void ec_felem_select(const EC_GROUP *group, EC_FELEM *out, BN_ULONG mask,
int ec_felem_equal(const EC_GROUP *group, const EC_FELEM *a,
const EC_FELEM *b) {
// Note this function is variable-time. Constant-time operations should use
// |ec_felem_non_zero_mask|.
return OPENSSL_memcmp(a->words, b->words,
group->field.width * sizeof(BN_ULONG)) == 0;
return CRYPTO_memcmp(a->words, b->words,
group->field.width * sizeof(BN_ULONG)) == 0;
}
@@ -71,8 +71,8 @@
#include <CCryptoBoringSSL_base.h>
#include <CCryptoBoringSSL_bn.h>
#include <CCryptoBoringSSL_ec.h>
#include <CCryptoBoringSSL_ex_data.h>
#include <CCryptoBoringSSL_thread.h>
#include <CCryptoBoringSSL_type_check.h>
#include "../bn/internal.h"
@@ -82,6 +82,9 @@ extern "C" {
#endif
// EC internals.
// Cap the size of all field elements and scalars, including custom curves, to
// 66 bytes, large enough to fit secp521r1 and brainpoolP512r1, which appear to
// be the largest fields anyone plausibly uses.
@@ -91,6 +94,9 @@ extern "C" {
OPENSSL_STATIC_ASSERT(EC_MAX_WORDS <= BN_SMALL_MAX_WORDS,
"bn_*_small functions not usable");
// Scalars.
// An EC_SCALAR is an integer fully reduced modulo the order. Only the first
// |order->width| words are used. An |EC_SCALAR| is specific to an |EC_GROUP|
// and must not be mixed between groups.
@@ -100,6 +106,88 @@ typedef union {
BN_ULONG words[EC_MAX_WORDS];
} EC_SCALAR;
// ec_bignum_to_scalar converts |in| to an |EC_SCALAR| and writes it to
// |*out|. It returns one on success and zero if |in| is out of range.
OPENSSL_EXPORT int ec_bignum_to_scalar(const EC_GROUP *group, EC_SCALAR *out,
const BIGNUM *in);
// ec_scalar_to_bytes serializes |in| as a big-endian bytestring to |out| and
// sets |*out_len| to the number of bytes written. The number of bytes written
// is |BN_num_bytes(&group->order)|, which is at most |EC_MAX_BYTES|.
OPENSSL_EXPORT void ec_scalar_to_bytes(const EC_GROUP *group, uint8_t *out,
size_t *out_len, const EC_SCALAR *in);
// ec_scalar_from_bytes deserializes |in| and stores the resulting scalar over
// group |group| to |out|. It returns one on success and zero if |in| is
// invalid.
int ec_scalar_from_bytes(const EC_GROUP *group, EC_SCALAR *out,
const uint8_t *in, size_t len);
// ec_scalar_reduce sets |out| to |words|, reduced modulo the group order.
// |words| must be less than order^2. |num| must be at most twice the width of
// group order. This function treats |words| as secret.
void ec_scalar_reduce(const EC_GROUP *group, EC_SCALAR *out,
const BN_ULONG *words, size_t num);
// ec_random_nonzero_scalar sets |out| to a uniformly selected random value from
// 1 to |group->order| - 1. It returns one on success and zero on error.
int ec_random_nonzero_scalar(const EC_GROUP *group, EC_SCALAR *out,
const uint8_t additional_data[32]);
// ec_scalar_equal_vartime returns one if |a| and |b| are equal and zero
// otherwise. Both values are treated as public.
int ec_scalar_equal_vartime(const EC_GROUP *group, const EC_SCALAR *a,
const EC_SCALAR *b);
// ec_scalar_is_zero returns one if |a| is zero and zero otherwise.
int ec_scalar_is_zero(const EC_GROUP *group, const EC_SCALAR *a);
// ec_scalar_add sets |r| to |a| + |b|.
void ec_scalar_add(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a,
const EC_SCALAR *b);
// ec_scalar_sub sets |r| to |a| - |b|.
void ec_scalar_sub(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a,
const EC_SCALAR *b);
// ec_scalar_neg sets |r| to -|a|.
void ec_scalar_neg(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a);
// ec_scalar_to_montgomery sets |r| to |a| in Montgomery form.
void ec_scalar_to_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a);
// ec_scalar_to_montgomery sets |r| to |a| converted from Montgomery form.
void ec_scalar_from_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a);
// ec_scalar_mul_montgomery sets |r| to |a| * |b| where inputs and outputs are
// in Montgomery form.
void ec_scalar_mul_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a, const EC_SCALAR *b);
// ec_scalar_inv0_montgomery sets |r| to |a|^-1 where inputs and outputs are in
// Montgomery form. If |a| is zero, |r| is set to zero.
void ec_scalar_inv0_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a);
// ec_scalar_to_montgomery_inv_vartime sets |r| to |a|^-1 R. That is, it takes
// in |a| not in Montgomery form and computes the inverse in Montgomery form. It
// returns one on success and zero if |a| has no inverse. This function assumes
// |a| is public and may leak information about it via timing.
//
// Note this is not the same operation as |ec_scalar_inv0_montgomery|.
int ec_scalar_to_montgomery_inv_vartime(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a);
// ec_scalar_select, in constant time, sets |out| to |a| if |mask| is all ones
// and |b| if |mask| is all zeros.
void ec_scalar_select(const EC_GROUP *group, EC_SCALAR *out, BN_ULONG mask,
const EC_SCALAR *a, const EC_SCALAR *b);
// Field elements.
// An EC_FELEM represents a field element. Only the first |field->width| words
// are used. An |EC_FELEM| is specific to an |EC_GROUP| and must not be mixed
// between groups. Additionally, the representation (whether or not elements are
@@ -110,15 +198,268 @@ typedef union {
BN_ULONG words[EC_MAX_WORDS];
} EC_FELEM;
// An EC_RAW_POINT represents an elliptic curve point. Unlike |EC_POINT|, it is
// a plain struct which can be stack-allocated and needs no cleanup. It is
// specific to an |EC_GROUP| and must not be mixed between groups.
// ec_bignum_to_felem converts |in| to an |EC_FELEM|. It returns one on success
// and zero if |in| is out of range.
int ec_bignum_to_felem(const EC_GROUP *group, EC_FELEM *out, const BIGNUM *in);
// ec_felem_to_bignum converts |in| to a |BIGNUM|. It returns one on success and
// zero on allocation failure.
int ec_felem_to_bignum(const EC_GROUP *group, BIGNUM *out, const EC_FELEM *in);
// ec_felem_to_bytes serializes |in| as a big-endian bytestring to |out| and
// sets |*out_len| to the number of bytes written. The number of bytes written
// is |BN_num_bytes(&group->order)|, which is at most |EC_MAX_BYTES|.
void ec_felem_to_bytes(const EC_GROUP *group, uint8_t *out, size_t *out_len,
const EC_FELEM *in);
// ec_felem_from_bytes deserializes |in| and stores the resulting field element
// to |out|. It returns one on success and zero if |in| is invalid.
int ec_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out, const uint8_t *in,
size_t len);
// ec_felem_neg sets |out| to -|a|.
void ec_felem_neg(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a);
// ec_felem_add sets |out| to |a| + |b|.
void ec_felem_add(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a,
const EC_FELEM *b);
// ec_felem_add sets |out| to |a| - |b|.
void ec_felem_sub(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a,
const EC_FELEM *b);
// ec_felem_non_zero_mask returns all ones if |a| is non-zero and all zeros
// otherwise.
BN_ULONG ec_felem_non_zero_mask(const EC_GROUP *group, const EC_FELEM *a);
// ec_felem_select, in constant time, sets |out| to |a| if |mask| is all ones
// and |b| if |mask| is all zeros.
void ec_felem_select(const EC_GROUP *group, EC_FELEM *out, BN_ULONG mask,
const EC_FELEM *a, const EC_FELEM *b);
// ec_felem_equal returns one if |a| and |b| are equal and zero otherwise.
int ec_felem_equal(const EC_GROUP *group, const EC_FELEM *a, const EC_FELEM *b);
// Points.
//
// Points may represented in affine coordinates as |EC_AFFINE| or Jacobian
// coordinates as |EC_RAW_POINT|. Affine coordinates directly represent a
// point on the curve, but point addition over affine coordinates requires
// costly field inversions, so arithmetic is done in Jacobian coordinates.
// Converting from affine to Jacobian is cheap, while converting from Jacobian
// to affine costs a field inversion. (Jacobian coordinates amortize the field
// inversions needed in a sequence of point operations.)
//
// TODO(davidben): Rename |EC_RAW_POINT| to |EC_JACOBIAN|.
// An EC_RAW_POINT represents an elliptic curve point in Jacobian coordinates.
// Unlike |EC_POINT|, it is a plain struct which can be stack-allocated and
// needs no cleanup. It is specific to an |EC_GROUP| and must not be mixed
// between groups.
typedef struct {
EC_FELEM X, Y, Z;
// X, Y, and Z are Jacobian projective coordinates. They represent
// (X/Z^2, Y/Z^3) if Z != 0 and the point at infinity otherwise.
EC_FELEM X, Y, Z;
} EC_RAW_POINT;
// An EC_AFFINE represents an elliptic curve point in affine coordinates.
// coordinates. Note the point at infinity cannot be represented in affine
// coordinates.
typedef struct {
EC_FELEM X, Y;
} EC_AFFINE;
// ec_affine_to_jacobian converts |p| to Jacobian form and writes the result to
// |*out|. This operation is very cheap and only costs a few copies.
void ec_affine_to_jacobian(const EC_GROUP *group, EC_RAW_POINT *out,
const EC_AFFINE *p);
// ec_jacobian_to_affine converts |p| to affine form and writes the result to
// |*out|. It returns one on success and zero if |p| was the point at infinity.
// This operation performs a field inversion and should only be done once per
// point.
//
// If only extracting the x-coordinate, use |ec_get_x_coordinate_*| which is
// slightly faster.
int ec_jacobian_to_affine(const EC_GROUP *group, EC_AFFINE *out,
const EC_RAW_POINT *p);
// ec_jacobian_to_affine_batch converts |num| points in |in| from Jacobian
// coordinates to affine coordinates and writes the results to |out|. It returns
// one on success and zero if any of the input points were infinity.
//
// This function is not implemented for all curves. Add implementations as
// needed.
int ec_jacobian_to_affine_batch(const EC_GROUP *group, EC_AFFINE *out,
const EC_RAW_POINT *in, size_t num);
// ec_point_set_affine_coordinates sets |out|'s to a point with affine
// coordinates |x| and |y|. It returns one if the point is on the curve and
// zero otherwise. If the point is not on the curve, the value of |out| is
// undefined.
int ec_point_set_affine_coordinates(const EC_GROUP *group, EC_AFFINE *out,
const EC_FELEM *x, const EC_FELEM *y);
// ec_point_mul_scalar sets |r| to |p| * |scalar|. Both inputs are considered
// secret.
int ec_point_mul_scalar(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_RAW_POINT *p, const EC_SCALAR *scalar);
// ec_point_mul_scalar_base sets |r| to generator * |scalar|. |scalar| is
// treated as secret.
int ec_point_mul_scalar_base(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_SCALAR *scalar);
// ec_point_mul_scalar_batch sets |r| to |p0| * |scalar0| + |p1| * |scalar1| +
// |p2| * |scalar2|. |p2| may be NULL to skip that term.
//
// The inputs are treated as secret, however, this function leaks information
// about whether intermediate computations add a point to itself. Callers must
// ensure that discrete logs between |p0|, |p1|, and |p2| are uniformly
// distributed and independent of the scalars, which should be uniformly
// selected and not under the attackers control. This ensures the doubling case
// will occur with negligible probability.
//
// This function is not implemented for all curves. Add implementations as
// needed.
//
// TODO(davidben): This function does not use base point tables. For now, it is
// only used with the generic |EC_GFp_mont_method| implementation which has
// none. If generalizing to tuned curves, this may be useful. However, we still
// must double up to the least efficient input, so precomputed tables can only
// save table setup and allow a wider window size.
int ec_point_mul_scalar_batch(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_RAW_POINT *p0, const EC_SCALAR *scalar0,
const EC_RAW_POINT *p1, const EC_SCALAR *scalar1,
const EC_RAW_POINT *p2, const EC_SCALAR *scalar2);
#define EC_MONT_PRECOMP_COMB_SIZE 5
// An |EC_PRECOMP| stores precomputed information about a point, to optimize
// repeated multiplications involving it. It is a union so different
// |EC_METHOD|s can store different information in it.
typedef union {
EC_AFFINE comb[(1 << EC_MONT_PRECOMP_COMB_SIZE) - 1];
} EC_PRECOMP;
// ec_init_precomp precomputes multiples of |p| and writes the result to |out|.
// It returns one on success and zero on error. The resulting table may be used
// with |ec_point_mul_scalar_precomp|. This function will fail if |p| is the
// point at infinity.
//
// This function is not implemented for all curves. Add implementations as
// needed.
int ec_init_precomp(const EC_GROUP *group, EC_PRECOMP *out,
const EC_RAW_POINT *p);
// ec_point_mul_scalar_precomp sets |r| to |p0| * |scalar0| + |p1| * |scalar1| +
// |p2| * |scalar2|. |p1| or |p2| may be NULL to skip the corresponding term.
// The points are represented as |EC_PRECOMP| and must be initialized with
// |ec_init_precomp|. This function runs faster than |ec_point_mul_scalar_batch|
// but requires setup work per input point, so it is only appropriate for points
// which are used frequently.
//
// The inputs are treated as secret, however, this function leaks information
// about whether intermediate computations add a point to itself. Callers must
// ensure that discrete logs between |p0|, |p1|, and |p2| are uniformly
// distributed and independent of the scalars, which should be uniformly
// selected and not under the attackers control. This ensures the doubling case
// will occur with negligible probability.
//
// This function is not implemented for all curves. Add implementations as
// needed.
//
// TODO(davidben): This function does not use base point tables. For now, it is
// only used with the generic |EC_GFp_mont_method| implementation which has
// none. If generalizing to tuned curves, we should add a parameter for the base
// point and arrange for the generic implementation to have base point tables
// available.
int ec_point_mul_scalar_precomp(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_PRECOMP *p0, const EC_SCALAR *scalar0,
const EC_PRECOMP *p1, const EC_SCALAR *scalar1,
const EC_PRECOMP *p2, const EC_SCALAR *scalar2);
// ec_point_mul_scalar_public sets |r| to
// generator * |g_scalar| + |p| * |p_scalar|. It assumes that the inputs are
// public so there is no concern about leaking their values through timing.
OPENSSL_EXPORT int ec_point_mul_scalar_public(const EC_GROUP *group,
EC_RAW_POINT *r,
const EC_SCALAR *g_scalar,
const EC_RAW_POINT *p,
const EC_SCALAR *p_scalar);
// ec_point_mul_scalar_public_batch sets |r| to the sum of generator *
// |g_scalar| and |points[i]| * |scalars[i]| where |points| and |scalars| have
// |num| elements. It assumes that the inputs are public so there is no concern
// about leaking their values through timing. |g_scalar| may be NULL to skip
// that term.
//
// This function is not implemented for all curves. Add implementations as
// needed.
int ec_point_mul_scalar_public_batch(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_SCALAR *g_scalar,
const EC_RAW_POINT *points,
const EC_SCALAR *scalars, size_t num);
// ec_point_select, in constant time, sets |out| to |a| if |mask| is all ones
// and |b| if |mask| is all zeros.
void ec_point_select(const EC_GROUP *group, EC_RAW_POINT *out, BN_ULONG mask,
const EC_RAW_POINT *a, const EC_RAW_POINT *b);
// ec_affine_select behaves like |ec_point_select| but acts on affine points.
void ec_affine_select(const EC_GROUP *group, EC_AFFINE *out, BN_ULONG mask,
const EC_AFFINE *a, const EC_AFFINE *b);
// ec_precomp_select behaves like |ec_point_select| but acts on |EC_PRECOMP|.
void ec_precomp_select(const EC_GROUP *group, EC_PRECOMP *out, BN_ULONG mask,
const EC_PRECOMP *a, const EC_PRECOMP *b);
// ec_cmp_x_coordinate compares the x (affine) coordinate of |p|, mod the group
// order, with |r|. It returns one if the values match and zero if |p| is the
// point at infinity of the values do not match.
int ec_cmp_x_coordinate(const EC_GROUP *group, const EC_RAW_POINT *p,
const EC_SCALAR *r);
// ec_get_x_coordinate_as_scalar sets |*out| to |p|'s x-coordinate, modulo
// |group->order|. It returns one on success and zero if |p| is the point at
// infinity.
int ec_get_x_coordinate_as_scalar(const EC_GROUP *group, EC_SCALAR *out,
const EC_RAW_POINT *p);
// ec_get_x_coordinate_as_bytes writes |p|'s affine x-coordinate to |out|, which
// must have at must |max_out| bytes. It sets |*out_len| to the number of bytes
// written. The value is written big-endian and zero-padded to the size of the
// field. This function returns one on success and zero on failure.
int ec_get_x_coordinate_as_bytes(const EC_GROUP *group, uint8_t *out,
size_t *out_len, size_t max_out,
const EC_RAW_POINT *p);
// ec_point_to_bytes behaves like |EC_POINT_point2oct| but takes an
// |EC_AFFINE|.
size_t ec_point_to_bytes(const EC_GROUP *group, const EC_AFFINE *point,
point_conversion_form_t form, uint8_t *buf,
size_t len);
// ec_point_from_uncompressed parses |in| as a point in uncompressed form and
// sets the result to |out|. It returns one on success and zero if the input was
// invalid.
int ec_point_from_uncompressed(const EC_GROUP *group, EC_AFFINE *out,
const uint8_t *in, size_t len);
// ec_set_to_safe_point sets |out| to an arbitrary point on |group|, either the
// generator or the point at infinity. This is used to guard against callers of
// external APIs not checking the return value.
void ec_set_to_safe_point(const EC_GROUP *group, EC_RAW_POINT *out);
// ec_affine_jacobian_equal returns one if |a| and |b| represent the same point
// and zero otherwise. It treats both inputs as secret.
int ec_affine_jacobian_equal(const EC_GROUP *group, const EC_AFFINE *a,
const EC_RAW_POINT *b);
// Implementation details.
struct ec_method_st {
int (*group_init)(EC_GROUP *);
void (*group_finish)(EC_GROUP *);
@@ -128,12 +469,13 @@ struct ec_method_st {
// point_get_affine_coordinates sets |*x| and |*y| to the affine coordinates
// of |p|. Either |x| or |y| may be NULL to omit it. It returns one on success
// and zero if |p| is the point at infinity.
//
// Note: unlike |EC_FELEM|s used as intermediate values internal to the
// |EC_METHOD|, |*x| and |*y| are not encoded in Montgomery form.
int (*point_get_affine_coordinates)(const EC_GROUP *, const EC_RAW_POINT *p,
EC_FELEM *x, EC_FELEM *y);
// jacobian_to_affine_batch implements |ec_jacobian_to_affine_batch|.
int (*jacobian_to_affine_batch)(const EC_GROUP *group, EC_AFFINE *out,
const EC_RAW_POINT *in, size_t num);
// add sets |r| to |a| + |b|.
void (*add)(const EC_GROUP *group, EC_RAW_POINT *r, const EC_RAW_POINT *a,
const EC_RAW_POINT *b);
@@ -146,12 +488,32 @@ struct ec_method_st {
// mul_base sets |r| to |scalar|*generator.
void (*mul_base)(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_SCALAR *scalar);
// mul_batch implements |ec_mul_scalar_batch|.
void (*mul_batch)(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_RAW_POINT *p0, const EC_SCALAR *scalar0,
const EC_RAW_POINT *p1, const EC_SCALAR *scalar1,
const EC_RAW_POINT *p2, const EC_SCALAR *scalar2);
// mul_public sets |r| to |g_scalar|*generator + |p_scalar|*|p|. It assumes
// that the inputs are public so there is no concern about leaking their
// values through timing.
//
// This function may be omitted if |mul_public_batch| is provided.
void (*mul_public)(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_SCALAR *g_scalar, const EC_RAW_POINT *p,
const EC_SCALAR *p_scalar);
// mul_public_batch implements |ec_point_mul_scalar_public_batch|.
int (*mul_public_batch)(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_SCALAR *g_scalar, const EC_RAW_POINT *points,
const EC_SCALAR *scalars, size_t num);
// init_precomp implements |ec_init_precomp|.
int (*init_precomp)(const EC_GROUP *group, EC_PRECOMP *out,
const EC_RAW_POINT *p);
// mul_precomp implements |ec_point_mul_scalar_precomp|.
void (*mul_precomp)(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_PRECOMP *p0, const EC_SCALAR *scalar0,
const EC_PRECOMP *p1, const EC_SCALAR *scalar1,
const EC_PRECOMP *p2, const EC_SCALAR *scalar2);
// felem_mul and felem_sqr implement multiplication and squaring,
// respectively, so that the generic |EC_POINT_add| and |EC_POINT_dbl|
@@ -168,21 +530,36 @@ struct ec_method_st {
const EC_FELEM *b);
void (*felem_sqr)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a);
int (*bignum_to_felem)(const EC_GROUP *group, EC_FELEM *out,
const BIGNUM *in);
int (*felem_to_bignum)(const EC_GROUP *group, BIGNUM *out,
void (*felem_to_bytes)(const EC_GROUP *group, uint8_t *out, size_t *out_len,
const EC_FELEM *in);
int (*felem_from_bytes)(const EC_GROUP *group, EC_FELEM *out,
const uint8_t *in, size_t len);
// scalar_inv_montgomery sets |out| to |in|^-1, where both input and output
// are in Montgomery form.
void (*scalar_inv_montgomery)(const EC_GROUP *group, EC_SCALAR *out,
const EC_SCALAR *in);
// felem_reduce sets |out| to |words|, reduced modulo the field size, p.
// |words| must be less than p^2. |num| must be at most twice the width of p.
// This function treats |words| as secret.
//
// This function is only used in hash-to-curve and may be omitted in curves
// that do not support it.
void (*felem_reduce)(const EC_GROUP *group, EC_FELEM *out,
const BN_ULONG *words, size_t num);
// scalar_inv_montgomery_vartime performs the same computation as
// |scalar_inv_montgomery|. It further assumes that the inputs are public so
// there is no concern about leaking their values through timing.
int (*scalar_inv_montgomery_vartime)(const EC_GROUP *group, EC_SCALAR *out,
const EC_SCALAR *in);
// felem_exp sets |out| to |a|^|exp|. It treats |a| is secret but |exp| as
// public.
//
// This function is used in hash-to-curve and may be NULL in curves not used
// with hash-to-curve.
void (*felem_exp)(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a,
const BN_ULONG *exp, size_t num_exp);
// scalar_inv0_montgomery implements |ec_scalar_inv0_montgomery|.
void (*scalar_inv0_montgomery)(const EC_GROUP *group, EC_SCALAR *out,
const EC_SCALAR *in);
// scalar_to_montgomery_inv_vartime implements
// |ec_scalar_to_montgomery_inv_vartime|.
int (*scalar_to_montgomery_inv_vartime)(const EC_GROUP *group, EC_SCALAR *out,
const EC_SCALAR *in);
// cmp_x_coordinate compares the x (affine) coordinate of |p|, mod the group
// order, with |r|. It returns one if the values match and zero if |p| is the
@@ -197,7 +574,8 @@ struct ec_group_st {
const EC_METHOD *meth;
// Unlike all other |EC_POINT|s, |generator| does not own |generator->group|
// to avoid a reference cycle.
// to avoid a reference cycle. Additionally, Z is guaranteed to be one, so X
// and Y are suitable for use as an |EC_AFFINE|.
EC_POINT *generator;
BIGNUM order;
@@ -247,133 +625,20 @@ struct ec_point_st {
EC_GROUP *ec_group_new(const EC_METHOD *meth);
// ec_bignum_to_felem converts |in| to an |EC_FELEM|. It returns one on success
// and zero if |in| is out of range.
int ec_bignum_to_felem(const EC_GROUP *group, EC_FELEM *out, const BIGNUM *in);
// ec_felem_to_bignum converts |in| to a |BIGNUM|. It returns one on success and
// zero on allocation failure.
int ec_felem_to_bignum(const EC_GROUP *group, BIGNUM *out, const EC_FELEM *in);
// ec_felem_neg sets |out| to -|a|.
void ec_felem_neg(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a);
// ec_felem_add sets |out| to |a| + |b|.
void ec_felem_add(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a,
const EC_FELEM *b);
// ec_felem_add sets |out| to |a| - |b|.
void ec_felem_sub(const EC_GROUP *group, EC_FELEM *out, const EC_FELEM *a,
const EC_FELEM *b);
// ec_felem_non_zero_mask returns all ones if |a| is non-zero and all zeros
// otherwise.
BN_ULONG ec_felem_non_zero_mask(const EC_GROUP *group, const EC_FELEM *a);
// ec_felem_select, in constant time, sets |out| to |a| if |mask| is all ones
// and |b| if |mask| is all zeros.
void ec_felem_select(const EC_GROUP *group, EC_FELEM *out, BN_ULONG mask,
const EC_FELEM *a, const EC_FELEM *b);
// ec_felem_equal returns one if |a| and |b| are equal and zero otherwise. It
// treats |a| and |b| as public and does *not* run in constant time.
int ec_felem_equal(const EC_GROUP *group, const EC_FELEM *a, const EC_FELEM *b);
// ec_bignum_to_scalar converts |in| to an |EC_SCALAR| and writes it to
// |*out|. It returns one on success and zero if |in| is out of range.
OPENSSL_EXPORT int ec_bignum_to_scalar(const EC_GROUP *group, EC_SCALAR *out,
const BIGNUM *in);
// ec_random_nonzero_scalar sets |out| to a uniformly selected random value from
// 1 to |group->order| - 1. It returns one on success and zero on error.
int ec_random_nonzero_scalar(const EC_GROUP *group, EC_SCALAR *out,
const uint8_t additional_data[32]);
// ec_scalar_equal_vartime returns one if |a| and |b| are equal and zero
// otherwise. Both values are treated as public.
int ec_scalar_equal_vartime(const EC_GROUP *group, const EC_SCALAR *a,
const EC_SCALAR *b);
// ec_scalar_is_zero returns one if |a| is zero and zero otherwise.
int ec_scalar_is_zero(const EC_GROUP *group, const EC_SCALAR *a);
// ec_scalar_add sets |r| to |a| + |b|.
void ec_scalar_add(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a,
const EC_SCALAR *b);
// ec_scalar_to_montgomery sets |r| to |a| in Montgomery form.
void ec_scalar_to_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a);
// ec_scalar_to_montgomery sets |r| to |a| converted from Montgomery form.
void ec_scalar_from_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a);
// ec_scalar_mul_montgomery sets |r| to |a| * |b| where inputs and outputs are
// in Montgomery form.
void ec_scalar_mul_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a, const EC_SCALAR *b);
// ec_scalar_mul_montgomery sets |r| to |a|^-1 where inputs and outputs are in
// Montgomery form.
void ec_scalar_inv_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a);
// ec_scalar_inv_montgomery_vartime performs the same actions as
// |ec_scalar_inv_montgomery|, but in variable time.
int ec_scalar_inv_montgomery_vartime(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a);
// ec_point_mul_scalar sets |r| to |p| * |scalar|. Both inputs are considered
// secret.
int ec_point_mul_scalar(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_RAW_POINT *p, const EC_SCALAR *scalar);
// ec_point_mul_scalar_base sets |r| to generator * |scalar|. |scalar| is
// treated as secret.
int ec_point_mul_scalar_base(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_SCALAR *scalar);
// ec_point_mul_scalar_public performs the same computation as
// ec_point_mul_scalar. It further assumes that the inputs are public so
// there is no concern about leaking their values through timing.
OPENSSL_EXPORT int ec_point_mul_scalar_public(const EC_GROUP *group,
EC_RAW_POINT *r,
const EC_SCALAR *g_scalar,
const EC_RAW_POINT *p,
const EC_SCALAR *p_scalar);
// ec_cmp_x_coordinate compares the x (affine) coordinate of |p|, mod the group
// order, with |r|. It returns one if the values match and zero if |p| is the
// point at infinity of the values do not match.
int ec_cmp_x_coordinate(const EC_GROUP *group, const EC_RAW_POINT *p,
const EC_SCALAR *r);
// ec_get_x_coordinate_as_scalar sets |*out| to |p|'s x-coordinate, modulo
// |group->order|. It returns one on success and zero if |p| is the point at
// infinity.
int ec_get_x_coordinate_as_scalar(const EC_GROUP *group, EC_SCALAR *out,
const EC_RAW_POINT *p);
// ec_point_get_affine_coordinate_bytes writes |p|'s affine coordinates to
// |out_x| and |out_y|, each of which must have at must |max_out| bytes. It sets
// |*out_len| to the number of bytes written in each buffer. Coordinates are
// written big-endian and zero-padded to the size of the field.
//
// Either of |out_x| or |out_y| may be NULL to omit that coordinate. This
// function returns one on success and zero on failure.
int ec_point_get_affine_coordinate_bytes(const EC_GROUP *group, uint8_t *out_x,
uint8_t *out_y, size_t *out_len,
size_t max_out, const EC_RAW_POINT *p);
// ec_field_element_to_scalar reduces |r| modulo |group->order|. |r| must
// previously have been reduced modulo |group->field|.
int ec_field_element_to_scalar(const EC_GROUP *group, BIGNUM *r);
void ec_GFp_mont_mul(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_RAW_POINT *p, const EC_SCALAR *scalar);
void ec_GFp_mont_mul_base(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_SCALAR *scalar);
void ec_GFp_mont_mul_batch(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_RAW_POINT *p0, const EC_SCALAR *scalar0,
const EC_RAW_POINT *p1, const EC_SCALAR *scalar1,
const EC_RAW_POINT *p2, const EC_SCALAR *scalar2);
int ec_GFp_mont_init_precomp(const EC_GROUP *group, EC_PRECOMP *out,
const EC_RAW_POINT *p);
void ec_GFp_mont_mul_precomp(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_PRECOMP *p0, const EC_SCALAR *scalar0,
const EC_PRECOMP *p1, const EC_SCALAR *scalar1,
const EC_PRECOMP *p2, const EC_SCALAR *scalar2);
// ec_compute_wNAF writes the modified width-(w+1) Non-Adjacent Form (wNAF) of
// |scalar| to |out|. |out| must have room for |bits| + 1 elements, each of
@@ -386,9 +651,10 @@ void ec_GFp_mont_mul_base(const EC_GROUP *group, EC_RAW_POINT *r,
void ec_compute_wNAF(const EC_GROUP *group, int8_t *out,
const EC_SCALAR *scalar, size_t bits, int w);
void ec_GFp_mont_mul_public(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_SCALAR *g_scalar, const EC_RAW_POINT *p,
const EC_SCALAR *p_scalar);
int ec_GFp_mont_mul_public_batch(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_SCALAR *g_scalar,
const EC_RAW_POINT *points,
const EC_SCALAR *scalars, size_t num);
// method functions in simple.c
int ec_GFp_simple_group_init(EC_GROUP *);
@@ -400,26 +666,29 @@ int ec_GFp_simple_group_get_curve(const EC_GROUP *, BIGNUM *p, BIGNUM *a,
void ec_GFp_simple_point_init(EC_RAW_POINT *);
void ec_GFp_simple_point_copy(EC_RAW_POINT *, const EC_RAW_POINT *);
void ec_GFp_simple_point_set_to_infinity(const EC_GROUP *, EC_RAW_POINT *);
int ec_GFp_simple_point_set_affine_coordinates(const EC_GROUP *, EC_RAW_POINT *,
const BIGNUM *x,
const BIGNUM *y);
void ec_GFp_mont_add(const EC_GROUP *, EC_RAW_POINT *r, const EC_RAW_POINT *a,
const EC_RAW_POINT *b);
void ec_GFp_mont_dbl(const EC_GROUP *, EC_RAW_POINT *r, const EC_RAW_POINT *a);
void ec_GFp_simple_invert(const EC_GROUP *, EC_RAW_POINT *);
int ec_GFp_simple_is_at_infinity(const EC_GROUP *, const EC_RAW_POINT *);
int ec_GFp_simple_is_on_curve(const EC_GROUP *, const EC_RAW_POINT *);
int ec_GFp_simple_cmp(const EC_GROUP *, const EC_RAW_POINT *a,
const EC_RAW_POINT *b);
void ec_simple_scalar_inv_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a);
int ec_GFp_simple_points_equal(const EC_GROUP *, const EC_RAW_POINT *a,
const EC_RAW_POINT *b);
void ec_simple_scalar_inv0_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a);
int ec_GFp_simple_mont_inv_mod_ord_vartime(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a);
int ec_simple_scalar_to_montgomery_inv_vartime(const EC_GROUP *group,
EC_SCALAR *r,
const EC_SCALAR *a);
int ec_GFp_simple_cmp_x_coordinate(const EC_GROUP *group, const EC_RAW_POINT *p,
const EC_SCALAR *r);
void ec_GFp_simple_felem_to_bytes(const EC_GROUP *group, uint8_t *out,
size_t *out_len, const EC_FELEM *in);
int ec_GFp_simple_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out,
const uint8_t *in, size_t len);
// method functions in montgomery.c
int ec_GFp_mont_group_init(EC_GROUP *);
int ec_GFp_mont_group_set_curve(EC_GROUP *, const BIGNUM *p, const BIGNUM *a,
@@ -429,12 +698,13 @@ void ec_GFp_mont_felem_mul(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a,
const EC_FELEM *b);
void ec_GFp_mont_felem_sqr(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a);
int ec_GFp_mont_bignum_to_felem(const EC_GROUP *group, EC_FELEM *out,
const BIGNUM *in);
int ec_GFp_mont_felem_to_bignum(const EC_GROUP *group, BIGNUM *out,
const EC_FELEM *in);
void ec_GFp_mont_felem_to_bytes(const EC_GROUP *group, uint8_t *out,
size_t *out_len, const EC_FELEM *in);
int ec_GFp_mont_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out,
const uint8_t *in, size_t len);
void ec_GFp_nistp_recode_scalar_bits(uint8_t *sign, uint8_t *digit, uint8_t in);
void ec_GFp_nistp_recode_scalar_bits(crypto_word_t *sign, crypto_word_t *digit,
crypto_word_t in);
const EC_METHOD *EC_GFp_nistp224_method(void);
const EC_METHOD *EC_GFp_nistp256_method(void);
@@ -453,6 +723,9 @@ typedef struct {
struct ec_key_st {
EC_GROUP *group;
// Ideally |pub_key| would be an |EC_AFFINE| so serializing it does not pay an
// inversion each time, but the |EC_KEY_get0_public_key| API implies public
// keys are stored in an |EC_POINT|-compatible form.
EC_POINT *pub_key;
EC_WRAPPED_SCALAR *priv_key;
@@ -73,21 +73,15 @@
#include "internal.h"
static size_t ec_GFp_simple_point2oct(const EC_GROUP *group,
const EC_RAW_POINT *point,
point_conversion_form_t form,
uint8_t *buf, size_t len) {
size_t ec_point_to_bytes(const EC_GROUP *group, const EC_AFFINE *point,
point_conversion_form_t form, uint8_t *buf,
size_t len) {
if (form != POINT_CONVERSION_COMPRESSED &&
form != POINT_CONVERSION_UNCOMPRESSED) {
OPENSSL_PUT_ERROR(EC, EC_R_INVALID_FORM);
return 0;
}
if (ec_GFp_simple_is_at_infinity(group, point)) {
OPENSSL_PUT_ERROR(EC, EC_R_POINT_AT_INFINITY);
return 0;
}
const size_t field_len = BN_num_bytes(&group->field);
size_t output_len = 1 /* type byte */ + field_len;
if (form == POINT_CONVERSION_UNCOMPRESSED) {
@@ -102,79 +96,89 @@ static size_t ec_GFp_simple_point2oct(const EC_GROUP *group,
return 0;
}
uint8_t y_buf[EC_MAX_BYTES];
size_t field_len_out;
if (!ec_point_get_affine_coordinate_bytes(
group, buf + 1 /* x */,
form == POINT_CONVERSION_COMPRESSED ? y_buf : buf + 1 + field_len,
&field_len_out, field_len, point)) {
return 0;
}
ec_felem_to_bytes(group, buf + 1, &field_len_out, &point->X);
assert(field_len_out == field_len);
if (field_len_out != field_len) {
OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
return 0;
}
if (form == POINT_CONVERSION_COMPRESSED) {
buf[0] = form + (y_buf[field_len - 1] & 1);
} else {
if (form == POINT_CONVERSION_UNCOMPRESSED) {
ec_felem_to_bytes(group, buf + 1 + field_len, &field_len_out, &point->Y);
assert(field_len_out == field_len);
buf[0] = form;
} else {
uint8_t y_buf[EC_MAX_BYTES];
ec_felem_to_bytes(group, y_buf, &field_len_out, &point->Y);
buf[0] = form + (y_buf[field_len_out - 1] & 1);
}
}
return output_len;
}
int ec_point_from_uncompressed(const EC_GROUP *group, EC_AFFINE *out,
const uint8_t *in, size_t len) {
const size_t field_len = BN_num_bytes(&group->field);
if (len != 1 + 2 * field_len || in[0] != POINT_CONVERSION_UNCOMPRESSED) {
OPENSSL_PUT_ERROR(EC, EC_R_INVALID_ENCODING);
return 0;
}
EC_FELEM x, y;
if (!ec_felem_from_bytes(group, &x, in + 1, field_len) ||
!ec_felem_from_bytes(group, &y, in + 1 + field_len, field_len) ||
!ec_point_set_affine_coordinates(group, out, &x, &y)) {
return 0;
}
return 1;
}
static int ec_GFp_simple_oct2point(const EC_GROUP *group, EC_POINT *point,
const uint8_t *buf, size_t len,
BN_CTX *ctx) {
BN_CTX *new_ctx = NULL;
int ret = 0, used_ctx = 0;
if (len == 0) {
OPENSSL_PUT_ERROR(EC, EC_R_BUFFER_TOO_SMALL);
goto err;
return 0;
}
point_conversion_form_t form = buf[0];
const int y_bit = form & 1;
form = form & ~1U;
if ((form != POINT_CONVERSION_COMPRESSED &&
form != POINT_CONVERSION_UNCOMPRESSED) ||
(form == POINT_CONVERSION_UNCOMPRESSED && y_bit)) {
OPENSSL_PUT_ERROR(EC, EC_R_INVALID_ENCODING);
goto err;
}
const size_t field_len = BN_num_bytes(&group->field);
size_t enc_len = 1 /* type byte */ + field_len;
if (form == POINT_CONVERSION_UNCOMPRESSED) {
// Uncompressed points have a second coordinate.
enc_len += field_len;
EC_AFFINE affine;
if (!ec_point_from_uncompressed(group, &affine, buf, len)) {
// In the event of an error, defend against the caller not checking the
// return value by setting a known safe value.
ec_set_to_safe_point(group, &point->raw);
return 0;
}
ec_affine_to_jacobian(group, &point->raw, &affine);
return 1;
}
if (len != enc_len) {
const int y_bit = form & 1;
const size_t field_len = BN_num_bytes(&group->field);
form = form & ~1u;
if (form != POINT_CONVERSION_COMPRESSED ||
len != 1 /* type byte */ + field_len) {
OPENSSL_PUT_ERROR(EC, EC_R_INVALID_ENCODING);
goto err;
return 0;
}
// TODO(davidben): Integrate compressed coordinates with the lower-level EC
// abstractions. This requires a way to compute square roots, which is tricky
// for primes which are not 3 (mod 4), namely P-224 and custom curves. P-224's
// prime is particularly inconvenient for compressed coordinates. See
// https://cr.yp.to/papers/sqroot.pdf
BN_CTX *new_ctx = NULL;
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL) {
goto err;
return 0;
}
}
int ret = 0;
BN_CTX_start(ctx);
used_ctx = 1;
BIGNUM *x = BN_CTX_get(ctx);
BIGNUM *y = BN_CTX_get(ctx);
if (x == NULL || y == NULL) {
goto err;
}
if (!BN_bin2bn(buf + 1, field_len, x)) {
if (x == NULL || !BN_bin2bn(buf + 1, field_len, x)) {
goto err;
}
if (BN_ucmp(x, &group->field) >= 0) {
@@ -182,30 +186,14 @@ static int ec_GFp_simple_oct2point(const EC_GROUP *group, EC_POINT *point,
goto err;
}
if (form == POINT_CONVERSION_COMPRESSED) {
if (!EC_POINT_set_compressed_coordinates_GFp(group, point, x, y_bit, ctx)) {
goto err;
}
} else {
if (!BN_bin2bn(buf + 1 + field_len, field_len, y)) {
goto err;
}
if (BN_ucmp(y, &group->field) >= 0) {
OPENSSL_PUT_ERROR(EC, EC_R_INVALID_ENCODING);
goto err;
}
if (!EC_POINT_set_affine_coordinates_GFp(group, point, x, y, ctx)) {
goto err;
}
if (!EC_POINT_set_compressed_coordinates_GFp(group, point, x, y_bit, ctx)) {
goto err;
}
ret = 1;
err:
if (used_ctx) {
BN_CTX_end(ctx);
}
BN_CTX_end(ctx);
BN_CTX_free(new_ctx);
return ret;
}
@@ -226,7 +214,11 @@ size_t EC_POINT_point2oct(const EC_GROUP *group, const EC_POINT *point,
OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS);
return 0;
}
return ec_GFp_simple_point2oct(group, &point->raw, form, buf, len);
EC_AFFINE affine;
if (!ec_jacobian_to_affine(group, &affine, &point->raw)) {
return 0;
}
return ec_point_to_bytes(group, &affine, form, buf, len);
}
int EC_POINT_set_compressed_coordinates_GFp(const EC_GROUP *group,
@@ -866,7 +866,7 @@ static void p224_select_point(const uint64_t idx, size_t size,
}
// p224_get_bit returns the |i|th bit in |in|
static char p224_get_bit(const p224_felem_bytearray in, size_t i) {
static crypto_word_t p224_get_bit(const p224_felem_bytearray in, size_t i) {
if (i >= 224) {
return 0;
}
@@ -977,13 +977,13 @@ static void ec_GFp_nistp224_point_mul(const EC_GROUP *group, EC_RAW_POINT *r,
// Add every 5 doublings.
if (i % 5 == 0) {
uint64_t bits = p224_get_bit(scalar->bytes, i + 4) << 5;
crypto_word_t bits = p224_get_bit(scalar->bytes, i + 4) << 5;
bits |= p224_get_bit(scalar->bytes, i + 3) << 4;
bits |= p224_get_bit(scalar->bytes, i + 2) << 3;
bits |= p224_get_bit(scalar->bytes, i + 1) << 2;
bits |= p224_get_bit(scalar->bytes, i) << 1;
bits |= p224_get_bit(scalar->bytes, i - 1);
uint8_t sign, digit;
crypto_word_t sign, digit;
ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits);
// Select the point to add or subtract.
@@ -1022,7 +1022,7 @@ static void ec_GFp_nistp224_point_mul_base(const EC_GROUP *group,
}
// First, look 28 bits upwards.
uint64_t bits = p224_get_bit(scalar->bytes, i + 196) << 3;
crypto_word_t bits = p224_get_bit(scalar->bytes, i + 196) << 3;
bits |= p224_get_bit(scalar->bytes, i + 140) << 2;
bits |= p224_get_bit(scalar->bytes, i + 84) << 1;
bits |= p224_get_bit(scalar->bytes, i + 28);
@@ -1080,14 +1080,15 @@ static void ec_GFp_nistp224_point_mul_public(const EC_GROUP *group,
// Add multiples of the generator.
if (i <= 27) {
// First, look 28 bits upwards.
uint64_t bits = p224_get_bit(g_scalar->bytes, i + 196) << 3;
crypto_word_t bits = p224_get_bit(g_scalar->bytes, i + 196) << 3;
bits |= p224_get_bit(g_scalar->bytes, i + 140) << 2;
bits |= p224_get_bit(g_scalar->bytes, i + 84) << 1;
bits |= p224_get_bit(g_scalar->bytes, i + 28);
size_t index = (size_t)bits;
p224_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */,
g_p224_pre_comp[1][bits][0], g_p224_pre_comp[1][bits][1],
g_p224_pre_comp[1][bits][2]);
g_p224_pre_comp[1][index][0], g_p224_pre_comp[1][index][1],
g_p224_pre_comp[1][index][2]);
assert(!skip);
// Second, look at the current position.
@@ -1095,20 +1096,21 @@ static void ec_GFp_nistp224_point_mul_public(const EC_GROUP *group,
bits |= p224_get_bit(g_scalar->bytes, i + 112) << 2;
bits |= p224_get_bit(g_scalar->bytes, i + 56) << 1;
bits |= p224_get_bit(g_scalar->bytes, i);
index = (size_t)bits;
p224_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */,
g_p224_pre_comp[0][bits][0], g_p224_pre_comp[0][bits][1],
g_p224_pre_comp[0][bits][2]);
g_p224_pre_comp[0][index][0], g_p224_pre_comp[0][index][1],
g_p224_pre_comp[0][index][2]);
}
// Incorporate |p_scalar| every 5 doublings.
if (i % 5 == 0) {
uint64_t bits = p224_get_bit(p_scalar->bytes, i + 4) << 5;
crypto_word_t bits = p224_get_bit(p_scalar->bytes, i + 4) << 5;
bits |= p224_get_bit(p_scalar->bytes, i + 3) << 4;
bits |= p224_get_bit(p_scalar->bytes, i + 2) << 3;
bits |= p224_get_bit(p_scalar->bytes, i + 1) << 2;
bits |= p224_get_bit(p_scalar->bytes, i) << 1;
bits |= p224_get_bit(p_scalar->bytes, i - 1);
uint8_t sign, digit;
crypto_word_t sign, digit;
ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits);
// Select the point to add or subtract.
@@ -1154,16 +1156,6 @@ static void ec_GFp_nistp224_felem_sqr(const EC_GROUP *group, EC_FELEM *r,
p224_felem_to_generic(r, felem);
}
static int ec_GFp_nistp224_bignum_to_felem(const EC_GROUP *group, EC_FELEM *out,
const BIGNUM *in) {
return bn_copy_words(out->words, group->field.width, in);
}
static int ec_GFp_nistp224_felem_to_bignum(const EC_GROUP *group, BIGNUM *out,
const EC_FELEM *in) {
return bn_set_words(out, in->words, group->field.width);
}
DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistp224_method) {
out->group_init = ec_GFp_simple_group_init;
out->group_finish = ec_GFp_simple_group_finish;
@@ -1177,10 +1169,11 @@ DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistp224_method) {
out->mul_public = ec_GFp_nistp224_point_mul_public;
out->felem_mul = ec_GFp_nistp224_felem_mul;
out->felem_sqr = ec_GFp_nistp224_felem_sqr;
out->bignum_to_felem = ec_GFp_nistp224_bignum_to_felem;
out->felem_to_bignum = ec_GFp_nistp224_felem_to_bignum;
out->scalar_inv_montgomery = ec_simple_scalar_inv_montgomery;
out->scalar_inv_montgomery_vartime = ec_GFp_simple_mont_inv_mod_ord_vartime;
out->felem_to_bytes = ec_GFp_simple_felem_to_bytes;
out->felem_from_bytes = ec_GFp_simple_felem_from_bytes;
out->scalar_inv0_montgomery = ec_simple_scalar_inv0_montgomery;
out->scalar_to_montgomery_inv_vartime =
ec_simple_scalar_to_montgomery_inv_vartime;
out->cmp_x_coordinate = ec_GFp_simple_cmp_x_coordinate;
}
File diff suppressed because it is too large. Load diff
@@ -52,8 +52,8 @@ static const BN_ULONG ONE[P256_LIMBS] = {
// Recode window to a signed digit, see |ec_GFp_nistp_recode_scalar_bits| in
// util.c for details
static unsigned booth_recode_w5(unsigned in) {
unsigned s, d;
static crypto_word_t booth_recode_w5(crypto_word_t in) {
crypto_word_t s, d;
s = ~((in >> 5) - 1);
d = (1 << 6) - in - 1;
@@ -63,8 +63,8 @@ static unsigned booth_recode_w5(unsigned in) {
return (d << 1) + (s & 1);
}
static unsigned booth_recode_w7(unsigned in) {
unsigned s, d;
static crypto_word_t booth_recode_w7(crypto_word_t in) {
crypto_word_t s, d;
s = ~((in >> 7) - 1);
d = (1 << 8) - in - 1;
@@ -119,86 +119,73 @@ static BN_ULONG is_not_zero(BN_ULONG in) {
return in;
}
// ecp_nistz256_mod_inverse_mont sets |r| to (|in| * 2^-256)^-1 * 2^256 mod p.
// That is, |r| is the modular inverse of |in| for input and output in the
// Montgomery domain.
static void ecp_nistz256_mod_inverse_mont(BN_ULONG r[P256_LIMBS],
const BN_ULONG in[P256_LIMBS]) {
/* The poly is ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff
ffffffff
We use FLT and used poly-2 as exponent */
BN_ULONG p2[P256_LIMBS];
BN_ULONG p4[P256_LIMBS];
BN_ULONG p8[P256_LIMBS];
BN_ULONG p16[P256_LIMBS];
BN_ULONG p32[P256_LIMBS];
BN_ULONG res[P256_LIMBS];
int i;
// ecp_nistz256_mod_inverse_sqr_mont sets |r| to (|in| * 2^-256)^-2 * 2^256 mod
// p. That is, |r| is the modular inverse square of |in| for input and output in
// the Montgomery domain.
static void ecp_nistz256_mod_inverse_sqr_mont(BN_ULONG r[P256_LIMBS],
const BN_ULONG in[P256_LIMBS]) {
// This implements the addition chain described in
// https://briansmith.org/ecc-inversion-addition-chains-01#p256_field_inversion
BN_ULONG x2[P256_LIMBS], x3[P256_LIMBS], x6[P256_LIMBS], x12[P256_LIMBS],
x15[P256_LIMBS], x30[P256_LIMBS], x32[P256_LIMBS];
ecp_nistz256_sqr_mont(x2, in); // 2^2 - 2^1
ecp_nistz256_mul_mont(x2, x2, in); // 2^2 - 2^0
ecp_nistz256_sqr_mont(res, in);
ecp_nistz256_mul_mont(p2, res, in); // 3*p
ecp_nistz256_sqr_mont(x3, x2); // 2^3 - 2^1
ecp_nistz256_mul_mont(x3, x3, in); // 2^3 - 2^0
ecp_nistz256_sqr_mont(res, p2);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(p4, res, p2); // f*p
ecp_nistz256_sqr_mont(x6, x3);
for (int i = 1; i < 3; i++) {
ecp_nistz256_sqr_mont(x6, x6);
} // 2^6 - 2^3
ecp_nistz256_mul_mont(x6, x6, x3); // 2^6 - 2^0
ecp_nistz256_sqr_mont(res, p4);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(p8, res, p4); // ff*p
ecp_nistz256_sqr_mont(x12, x6);
for (int i = 1; i < 6; i++) {
ecp_nistz256_sqr_mont(x12, x12);
} // 2^12 - 2^6
ecp_nistz256_mul_mont(x12, x12, x6); // 2^12 - 2^0
ecp_nistz256_sqr_mont(res, p8);
for (i = 0; i < 7; i++) {
ecp_nistz256_sqr_mont(res, res);
}
ecp_nistz256_mul_mont(p16, res, p8); // ffff*p
ecp_nistz256_sqr_mont(x15, x12);
for (int i = 1; i < 3; i++) {
ecp_nistz256_sqr_mont(x15, x15);
} // 2^15 - 2^3
ecp_nistz256_mul_mont(x15, x15, x3); // 2^15 - 2^0
ecp_nistz256_sqr_mont(res, p16);
for (i = 0; i < 15; i++) {
ecp_nistz256_sqr_mont(res, res);
}
ecp_nistz256_mul_mont(p32, res, p16); // ffffffff*p
ecp_nistz256_sqr_mont(x30, x15);
for (int i = 1; i < 15; i++) {
ecp_nistz256_sqr_mont(x30, x30);
} // 2^30 - 2^15
ecp_nistz256_mul_mont(x30, x30, x15); // 2^30 - 2^0
ecp_nistz256_sqr_mont(res, p32);
for (i = 0; i < 31; i++) {
ecp_nistz256_sqr_mont(res, res);
}
ecp_nistz256_mul_mont(res, res, in);
ecp_nistz256_sqr_mont(x32, x30);
ecp_nistz256_sqr_mont(x32, x32); // 2^32 - 2^2
ecp_nistz256_mul_mont(x32, x32, x2); // 2^32 - 2^0
for (i = 0; i < 32 * 4; i++) {
ecp_nistz256_sqr_mont(res, res);
}
ecp_nistz256_mul_mont(res, res, p32);
BN_ULONG ret[P256_LIMBS];
ecp_nistz256_sqr_mont(ret, x32);
for (int i = 1; i < 31 + 1; i++) {
ecp_nistz256_sqr_mont(ret, ret);
} // 2^64 - 2^32
ecp_nistz256_mul_mont(ret, ret, in); // 2^64 - 2^32 + 2^0
for (i = 0; i < 32; i++) {
ecp_nistz256_sqr_mont(res, res);
}
ecp_nistz256_mul_mont(res, res, p32);
for (int i = 0; i < 96 + 32; i++) {
ecp_nistz256_sqr_mont(ret, ret);
} // 2^192 - 2^160 + 2^128
ecp_nistz256_mul_mont(ret, ret, x32); // 2^192 - 2^160 + 2^128 + 2^32 - 2^0
for (i = 0; i < 16; i++) {
ecp_nistz256_sqr_mont(res, res);
}
ecp_nistz256_mul_mont(res, res, p16);
for (int i = 0; i < 32; i++) {
ecp_nistz256_sqr_mont(ret, ret);
} // 2^224 - 2^192 + 2^160 + 2^64 - 2^32
ecp_nistz256_mul_mont(ret, ret, x32); // 2^224 - 2^192 + 2^160 + 2^64 - 2^0
for (i = 0; i < 8; i++) {
ecp_nistz256_sqr_mont(res, res);
}
ecp_nistz256_mul_mont(res, res, p8);
for (int i = 0; i < 30; i++) {
ecp_nistz256_sqr_mont(ret, ret);
} // 2^254 - 2^222 + 2^190 + 2^94 - 2^30
ecp_nistz256_mul_mont(ret, ret, x30); // 2^254 - 2^222 + 2^190 + 2^94 - 2^0
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(res, res, p4);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(res, res, p2);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_sqr_mont(res, res);
ecp_nistz256_mul_mont(r, res, in);
ecp_nistz256_sqr_mont(ret, ret);
ecp_nistz256_sqr_mont(r, ret); // 2^256 - 2^224 + 2^192 + 2^96 - 2^2
}
// r = p * p_scalar
@@ -209,8 +196,8 @@ static void ecp_nistz256_windowed_mul(const EC_GROUP *group, P256_POINT *r,
assert(p_scalar != NULL);
assert(group->field.width == P256_LIMBS);
static const unsigned kWindowSize = 5;
static const unsigned kMask = (1 << (5 /* kWindowSize */ + 1)) - 1;
static const size_t kWindowSize = 5;
static const crypto_word_t kMask = (1 << (5 /* kWindowSize */ + 1)) - 1;
// A |P256_POINT| is (3 * 32) = 96 bytes, and the 64-byte alignment should
// add no more than 63 bytes of overhead. Thus, |table| should require
@@ -247,17 +234,17 @@ static void ecp_nistz256_windowed_mul(const EC_GROUP *group, P256_POINT *r,
BN_ULONG tmp[P256_LIMBS];
alignas(32) P256_POINT h;
unsigned index = 255;
unsigned wvalue = p_str[(index - 1) / 8];
size_t index = 255;
crypto_word_t wvalue = p_str[(index - 1) / 8];
wvalue = (wvalue >> ((index - 1) % 8)) & kMask;
ecp_nistz256_select_w5(r, table, booth_recode_w5(wvalue) >> 1);
while (index >= 5) {
if (index != 255) {
unsigned off = (index - 1) / 8;
size_t off = (index - 1) / 8;
wvalue = p_str[off] | p_str[off + 1] << 8;
wvalue = (crypto_word_t)p_str[off] | (crypto_word_t)p_str[off + 1] << 8;
wvalue = (wvalue >> ((index - 1) % 8)) & kMask;
wvalue = booth_recode_w5(wvalue);
@@ -298,21 +285,22 @@ typedef union {
P256_POINT_AFFINE a;
} p256_point_union_t;
static unsigned calc_first_wvalue(unsigned *index, const uint8_t p_str[33]) {
static const unsigned kWindowSize = 7;
static const unsigned kMask = (1 << (7 /* kWindowSize */ + 1)) - 1;
static crypto_word_t calc_first_wvalue(size_t *index, const uint8_t p_str[33]) {
static const size_t kWindowSize = 7;
static const crypto_word_t kMask = (1 << (7 /* kWindowSize */ + 1)) - 1;
*index = kWindowSize;
unsigned wvalue = (p_str[0] << 1) & kMask;
crypto_word_t wvalue = (p_str[0] << 1) & kMask;
return booth_recode_w7(wvalue);
}
static unsigned calc_wvalue(unsigned *index, const uint8_t p_str[33]) {
static const unsigned kWindowSize = 7;
static const unsigned kMask = (1 << (7 /* kWindowSize */ + 1)) - 1;
static crypto_word_t calc_wvalue(size_t *index, const uint8_t p_str[33]) {
static const size_t kWindowSize = 7;
static const crypto_word_t kMask = (1 << (7 /* kWindowSize */ + 1)) - 1;
const unsigned off = (*index - 1) / 8;
unsigned wvalue = p_str[off] | p_str[off + 1] << 8;
const size_t off = (*index - 1) / 8;
crypto_word_t wvalue =
(crypto_word_t)p_str[off] | (crypto_word_t)p_str[off + 1] << 8;
wvalue = (wvalue >> ((*index - 1) % 8)) & kMask;
*index += kWindowSize;
@@ -340,8 +328,8 @@ static void ecp_nistz256_point_mul_base(const EC_GROUP *group, EC_RAW_POINT *r,
p_str[32] = 0;
// First window
unsigned index = 0;
unsigned wvalue = calc_first_wvalue(&index, p_str);
size_t index = 0;
crypto_word_t wvalue = calc_first_wvalue(&index, p_str);
ecp_nistz256_select_w7(&p.a, ecp_nistz256_precomputed[0], wvalue >> 1);
ecp_nistz256_neg(p.p.Z, p.p.Y);
@@ -385,8 +373,8 @@ static void ecp_nistz256_points_mul_public(const EC_GROUP *group,
p_str[32] = 0;
// First window
unsigned index = 0;
unsigned wvalue = calc_first_wvalue(&index, p_str);
size_t index = 0;
size_t wvalue = calc_first_wvalue(&index, p_str);
// Convert |p| from affine to Jacobian coordinates. We set Z to zero if |p|
// is infinity and |ONE| otherwise. |p| was computed from the table, so it
@@ -442,24 +430,17 @@ static int ecp_nistz256_get_affine(const EC_GROUP *group,
}
BN_ULONG z_inv2[P256_LIMBS];
BN_ULONG z_inv3[P256_LIMBS];
assert(group->field.width == P256_LIMBS);
ecp_nistz256_mod_inverse_mont(z_inv3, point->Z.words);
ecp_nistz256_sqr_mont(z_inv2, z_inv3);
// Instead of using |ecp_nistz256_from_mont| to convert the |x| coordinate
// and then calling |ecp_nistz256_from_mont| again to convert the |y|
// coordinate below, convert the common factor |z_inv2| once now, saving one
// reduction.
ecp_nistz256_from_mont(z_inv2, z_inv2);
ecp_nistz256_mod_inverse_sqr_mont(z_inv2, point->Z.words);
if (x != NULL) {
ecp_nistz256_mul_mont(x->words, z_inv2, point->X.words);
}
if (y != NULL) {
ecp_nistz256_mul_mont(z_inv3, z_inv3, z_inv2);
ecp_nistz256_mul_mont(y->words, z_inv3, point->Y.words);
ecp_nistz256_sqr_mont(z_inv2, z_inv2); // z^-4
ecp_nistz256_mul_mont(y->words, point->Y.words, point->Z.words); // y * z
ecp_nistz256_mul_mont(y->words, y->words, z_inv2); // y * z^-3
}
return 1;
@@ -492,8 +473,8 @@ static void ecp_nistz256_dbl(const EC_GROUP *group, EC_RAW_POINT *r,
OPENSSL_memcpy(r->Z.words, a.Z, P256_LIMBS * sizeof(BN_ULONG));
}
static void ecp_nistz256_inv_mod_ord(const EC_GROUP *group, EC_SCALAR *out,
const EC_SCALAR *in) {
static void ecp_nistz256_inv0_mod_ord(const EC_GROUP *group, EC_SCALAR *out,
const EC_SCALAR *in) {
// table[i] stores a power of |in| corresponding to the matching enum value.
enum {
// The following indices specify the power in binary.
@@ -573,12 +554,12 @@ static void ecp_nistz256_inv_mod_ord(const EC_GROUP *group, EC_SCALAR *out,
}
}
static int ecp_nistz256_mont_inv_mod_ord_vartime(const EC_GROUP *group,
static int ecp_nistz256_scalar_to_montgomery_inv_vartime(const EC_GROUP *group,
EC_SCALAR *out,
const EC_SCALAR *in) {
if ((OPENSSL_ia32cap_get()[1] & (1 << 28)) == 0) {
// No AVX support; fallback to generic code.
return ec_GFp_simple_mont_inv_mod_ord_vartime(group, out, in);
return ec_simple_scalar_to_montgomery_inv_vartime(group, out, in);
}
assert(group->order.width == P256_LIMBS);
@@ -642,10 +623,11 @@ DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistz256_method) {
out->mul_public = ecp_nistz256_points_mul_public;
out->felem_mul = ec_GFp_mont_felem_mul;
out->felem_sqr = ec_GFp_mont_felem_sqr;
out->bignum_to_felem = ec_GFp_mont_bignum_to_felem;
out->felem_to_bignum = ec_GFp_mont_felem_to_bignum;
out->scalar_inv_montgomery = ecp_nistz256_inv_mod_ord;
out->scalar_inv_montgomery_vartime = ecp_nistz256_mont_inv_mod_ord_vartime;
out->felem_to_bytes = ec_GFp_mont_felem_to_bytes;
out->felem_from_bytes = ec_GFp_mont_felem_from_bytes;
out->scalar_inv0_montgomery = ecp_nistz256_inv0_mod_ord;
out->scalar_to_montgomery_inv_vartime =
ecp_nistz256_scalar_to_montgomery_inv_vartime;
out->cmp_x_coordinate = ecp_nistz256_cmp_x_coordinate;
}
@@ -0,0 +1,740 @@
/* Copyright (c) 2020, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
// An implementation of the NIST P-256 elliptic curve point multiplication.
// 256-bit Montgomery form for 64 and 32-bit. Field operations are generated by
// Fiat, which lives in //third_party/fiat.
#include <CCryptoBoringSSL_base.h>
#include <CCryptoBoringSSL_bn.h>
#include <CCryptoBoringSSL_ec.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_type_check.h>
#include <assert.h>
#include <string.h>
#include "../../internal.h"
#include "../delocate.h"
#include "./internal.h"
// MSVC does not implement uint128_t, and crashes with intrinsics
#if defined(BORINGSSL_HAS_UINT128)
#define BORINGSSL_NISTP256_64BIT 1
#include "../../../third_party/fiat/p256_64.h"
#else
#include "../../../third_party/fiat/p256_32.h"
#endif
// utility functions, handwritten
#if defined(BORINGSSL_NISTP256_64BIT)
#define FIAT_P256_NLIMBS 4
typedef uint64_t fiat_p256_limb_t;
typedef uint64_t fiat_p256_felem[FIAT_P256_NLIMBS];
static const fiat_p256_felem fiat_p256_one = {0x1, 0xffffffff00000000,
0xffffffffffffffff, 0xfffffffe};
#else // 64BIT; else 32BIT
#define FIAT_P256_NLIMBS 8
typedef uint32_t fiat_p256_limb_t;
typedef uint32_t fiat_p256_felem[FIAT_P256_NLIMBS];
static const fiat_p256_felem fiat_p256_one = {
0x1, 0x0, 0x0, 0xffffffff, 0xffffffff, 0xffffffff, 0xfffffffe, 0x0};
#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++) {
out[i] = in1[i];
}
}
static void fiat_p256_cmovznz(fiat_p256_limb_t out[FIAT_P256_NLIMBS],
fiat_p256_limb_t t,
const fiat_p256_limb_t z[FIAT_P256_NLIMBS],
const fiat_p256_limb_t nz[FIAT_P256_NLIMBS]) {
fiat_p256_selectznz(out, !!t, z, nz);
}
static void fiat_p256_from_generic(fiat_p256_felem out, const EC_FELEM *in) {
fiat_p256_from_bytes(out, in->bytes);
}
static void fiat_p256_to_generic(EC_FELEM *out, const fiat_p256_felem in) {
// This works because 256 is a multiple of 64, so there are no excess bytes to
// zero when rounding up to |BN_ULONG|s.
OPENSSL_STATIC_ASSERT(
256 / 8 == sizeof(BN_ULONG) * ((256 + BN_BITS2 - 1) / BN_BITS2),
"fiat_p256_to_bytes leaves bytes uninitialized");
fiat_p256_to_bytes(out->bytes, in);
}
// fiat_p256_inv_square calculates |out| = |in|^{-2}
//
// Based on Fermat's Little Theorem:
// a^p = a (mod p)
// a^{p-1} = 1 (mod p)
// a^{p-3} = a^{-2} (mod p)
static void fiat_p256_inv_square(fiat_p256_felem out,
const fiat_p256_felem in) {
// This implements the addition chain described in
// https://briansmith.org/ecc-inversion-addition-chains-01#p256_field_inversion
fiat_p256_felem x2, x3, x6, x12, x15, x30, x32;
fiat_p256_square(x2, in); // 2^2 - 2^1
fiat_p256_mul(x2, x2, in); // 2^2 - 2^0
fiat_p256_square(x3, x2); // 2^3 - 2^1
fiat_p256_mul(x3, x3, in); // 2^3 - 2^0
fiat_p256_square(x6, x3);
for (int i = 1; i < 3; i++) {
fiat_p256_square(x6, x6);
} // 2^6 - 2^3
fiat_p256_mul(x6, x6, x3); // 2^6 - 2^0
fiat_p256_square(x12, x6);
for (int i = 1; i < 6; i++) {
fiat_p256_square(x12, x12);
} // 2^12 - 2^6
fiat_p256_mul(x12, x12, x6); // 2^12 - 2^0
fiat_p256_square(x15, x12);
for (int i = 1; i < 3; i++) {
fiat_p256_square(x15, x15);
} // 2^15 - 2^3
fiat_p256_mul(x15, x15, x3); // 2^15 - 2^0
fiat_p256_square(x30, x15);
for (int i = 1; i < 15; i++) {
fiat_p256_square(x30, x30);
} // 2^30 - 2^15
fiat_p256_mul(x30, x30, x15); // 2^30 - 2^0
fiat_p256_square(x32, x30);
fiat_p256_square(x32, x32); // 2^32 - 2^2
fiat_p256_mul(x32, x32, x2); // 2^32 - 2^0
fiat_p256_felem ret;
fiat_p256_square(ret, x32);
for (int i = 1; i < 31 + 1; i++) {
fiat_p256_square(ret, ret);
} // 2^64 - 2^32
fiat_p256_mul(ret, ret, in); // 2^64 - 2^32 + 2^0
for (int i = 0; i < 96 + 32; i++) {
fiat_p256_square(ret, ret);
} // 2^192 - 2^160 + 2^128
fiat_p256_mul(ret, ret, x32); // 2^192 - 2^160 + 2^128 + 2^32 - 2^0
for (int i = 0; i < 32; i++) {
fiat_p256_square(ret, ret);
} // 2^224 - 2^192 + 2^160 + 2^64 - 2^32
fiat_p256_mul(ret, ret, x32); // 2^224 - 2^192 + 2^160 + 2^64 - 2^0
for (int i = 0; i < 30; i++) {
fiat_p256_square(ret, ret);
} // 2^254 - 2^222 + 2^190 + 2^94 - 2^30
fiat_p256_mul(ret, ret, x30); // 2^254 - 2^222 + 2^190 + 2^94 - 2^0
fiat_p256_square(ret, ret);
fiat_p256_square(out, ret); // 2^256 - 2^224 + 2^192 + 2^96 - 2^2
}
// Group operations
// ----------------
//
// 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);
}
// 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 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 (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);
}
#include "./p256_table.h"
// fiat_p256_select_point_affine selects the |idx-1|th point from a
// precomputation table and copies it to out. If |idx| is zero, the output is
// the point at infinity.
static void fiat_p256_select_point_affine(
const fiat_p256_limb_t idx, size_t size,
const fiat_p256_felem pre_comp[/*size*/][2], fiat_p256_felem out[3]) {
OPENSSL_memset(out, 0, sizeof(fiat_p256_felem) * 3);
for (size_t i = 0; i < size; i++) {
fiat_p256_limb_t mismatch = i ^ (idx - 1);
fiat_p256_cmovznz(out[0], mismatch, pre_comp[i][0], out[0]);
fiat_p256_cmovznz(out[1], mismatch, pre_comp[i][1], out[1]);
}
fiat_p256_cmovznz(out[2], idx, out[2], fiat_p256_one);
}
// fiat_p256_select_point selects the |idx|th point from a precomputation table
// and copies it to out.
static void fiat_p256_select_point(const fiat_p256_limb_t idx, size_t size,
const fiat_p256_felem pre_comp[/*size*/][3],
fiat_p256_felem out[3]) {
OPENSSL_memset(out, 0, sizeof(fiat_p256_felem) * 3);
for (size_t i = 0; i < size; i++) {
fiat_p256_limb_t mismatch = i ^ idx;
fiat_p256_cmovznz(out[0], mismatch, pre_comp[i][0], out[0]);
fiat_p256_cmovznz(out[1], mismatch, pre_comp[i][1], out[1]);
fiat_p256_cmovznz(out[2], mismatch, pre_comp[i][2], out[2]);
}
}
// fiat_p256_get_bit returns the |i|th bit in |in|
static crypto_word_t fiat_p256_get_bit(const uint8_t *in, int i) {
if (i < 0 || i >= 256) {
return 0;
}
return (in[i >> 3] >> (i & 7)) & 1;
}
// OPENSSL EC_METHOD FUNCTIONS
// Takes the Jacobian coordinates (X, Y, Z) of a point and returns (X', Y') =
// (X/Z^2, Y/Z^3).
static int ec_GFp_nistp256_point_get_affine_coordinates(
const EC_GROUP *group, const EC_RAW_POINT *point, EC_FELEM *x_out,
EC_FELEM *y_out) {
if (ec_GFp_simple_is_at_infinity(group, point)) {
OPENSSL_PUT_ERROR(EC, EC_R_POINT_AT_INFINITY);
return 0;
}
fiat_p256_felem z1, z2;
fiat_p256_from_generic(z1, &point->Z);
fiat_p256_inv_square(z2, z1);
if (x_out != NULL) {
fiat_p256_felem x;
fiat_p256_from_generic(x, &point->X);
fiat_p256_mul(x, x, z2);
fiat_p256_to_generic(x_out, x);
}
if (y_out != NULL) {
fiat_p256_felem y;
fiat_p256_from_generic(y, &point->Y);
fiat_p256_square(z2, z2); // z^-4
fiat_p256_mul(y, y, z1); // y * z
fiat_p256_mul(y, y, z2); // y * z^-3
fiat_p256_to_generic(y_out, y);
}
return 1;
}
static void ec_GFp_nistp256_add(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_RAW_POINT *a, const EC_RAW_POINT *b) {
fiat_p256_felem x1, y1, z1, x2, y2, z2;
fiat_p256_from_generic(x1, &a->X);
fiat_p256_from_generic(y1, &a->Y);
fiat_p256_from_generic(z1, &a->Z);
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_to_generic(&r->X, x1);
fiat_p256_to_generic(&r->Y, y1);
fiat_p256_to_generic(&r->Z, z1);
}
static void ec_GFp_nistp256_dbl(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_RAW_POINT *a) {
fiat_p256_felem x, y, z;
fiat_p256_from_generic(x, &a->X);
fiat_p256_from_generic(y, &a->Y);
fiat_p256_from_generic(z, &a->Z);
fiat_p256_point_double(x, y, z, x, y, z);
fiat_p256_to_generic(&r->X, x);
fiat_p256_to_generic(&r->Y, y);
fiat_p256_to_generic(&r->Z, z);
}
static void ec_GFp_nistp256_point_mul(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_RAW_POINT *p,
const EC_SCALAR *scalar) {
fiat_p256_felem p_pre_comp[17][3];
OPENSSL_memset(&p_pre_comp, 0, sizeof(p_pre_comp));
// Precompute multiples.
fiat_p256_from_generic(p_pre_comp[1][0], &p->X);
fiat_p256_from_generic(p_pre_comp[1][1], &p->Y);
fiat_p256_from_generic(p_pre_comp[1][2], &p->Z);
for (size_t j = 2; j <= 16; ++j) {
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][2]);
} else {
fiat_p256_point_double(p_pre_comp[j][0], p_pre_comp[j][1],
p_pre_comp[j][2], p_pre_comp[j / 2][0],
p_pre_comp[j / 2][1], p_pre_comp[j / 2][2]);
}
}
// Set nq to the point at infinity.
fiat_p256_felem nq[3] = {{0}, {0}, {0}}, ftmp, tmp[3];
// Loop over |scalar| msb-to-lsb, incorporating |p_pre_comp| every 5th round.
int skip = 1; // Save two point operations in the first round.
for (size_t i = 255; i < 256; i--) {
// double
if (!skip) {
fiat_p256_point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]);
}
// do other additions every 5 doublings
if (i % 5 == 0) {
crypto_word_t bits = fiat_p256_get_bit(scalar->bytes, i + 4) << 5;
bits |= fiat_p256_get_bit(scalar->bytes, i + 3) << 4;
bits |= fiat_p256_get_bit(scalar->bytes, i + 2) << 3;
bits |= fiat_p256_get_bit(scalar->bytes, i + 1) << 2;
bits |= fiat_p256_get_bit(scalar->bytes, i) << 1;
bits |= fiat_p256_get_bit(scalar->bytes, i - 1);
crypto_word_t sign, digit;
ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits);
// select the point to add or subtract, in constant time.
fiat_p256_select_point((fiat_p256_limb_t)digit, 17,
(const fiat_p256_felem(*)[3])p_pre_comp, tmp);
fiat_p256_opp(ftmp, tmp[1]); // (X, -Y, Z) is the negative point.
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]);
} else {
fiat_p256_copy(nq[0], tmp[0]);
fiat_p256_copy(nq[1], tmp[1]);
fiat_p256_copy(nq[2], tmp[2]);
skip = 0;
}
}
}
fiat_p256_to_generic(&r->X, nq[0]);
fiat_p256_to_generic(&r->Y, nq[1]);
fiat_p256_to_generic(&r->Z, nq[2]);
}
static void ec_GFp_nistp256_point_mul_base(const EC_GROUP *group,
EC_RAW_POINT *r,
const EC_SCALAR *scalar) {
// Set nq to the point at infinity.
fiat_p256_felem nq[3] = {{0}, {0}, {0}}, tmp[3];
int skip = 1; // Save two point operations in the first round.
for (size_t i = 31; i < 32; i--) {
if (!skip) {
fiat_p256_point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]);
}
// First, look 32 bits upwards.
crypto_word_t bits = fiat_p256_get_bit(scalar->bytes, i + 224) << 3;
bits |= fiat_p256_get_bit(scalar->bytes, i + 160) << 2;
bits |= fiat_p256_get_bit(scalar->bytes, i + 96) << 1;
bits |= fiat_p256_get_bit(scalar->bytes, i + 32);
// Select the point to add, in constant time.
fiat_p256_select_point_affine((fiat_p256_limb_t)bits, 15,
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]);
} else {
fiat_p256_copy(nq[0], tmp[0]);
fiat_p256_copy(nq[1], tmp[1]);
fiat_p256_copy(nq[2], tmp[2]);
skip = 0;
}
// Second, look at the current position.
bits = fiat_p256_get_bit(scalar->bytes, i + 192) << 3;
bits |= fiat_p256_get_bit(scalar->bytes, i + 128) << 2;
bits |= fiat_p256_get_bit(scalar->bytes, i + 64) << 1;
bits |= fiat_p256_get_bit(scalar->bytes, i);
// 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_to_generic(&r->X, nq[0]);
fiat_p256_to_generic(&r->Y, nq[1]);
fiat_p256_to_generic(&r->Z, nq[2]);
}
static void ec_GFp_nistp256_point_mul_public(const EC_GROUP *group,
EC_RAW_POINT *r,
const EC_SCALAR *g_scalar,
const EC_RAW_POINT *p,
const EC_SCALAR *p_scalar) {
#define P256_WSIZE_PUBLIC 4
// Precompute multiples of |p|. p_pre_comp[i] is (2*i+1) * |p|.
fiat_p256_felem p_pre_comp[1 << (P256_WSIZE_PUBLIC - 1)][3];
fiat_p256_from_generic(p_pre_comp[0][0], &p->X);
fiat_p256_from_generic(p_pre_comp[0][1], &p->Y);
fiat_p256_from_generic(p_pre_comp[0][2], &p->Z);
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++) {
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]);
}
// Set up the coefficients for |p_scalar|.
int8_t p_wNAF[257];
ec_compute_wNAF(group, p_wNAF, p_scalar, 256, P256_WSIZE_PUBLIC);
// Set |ret| to the point at infinity.
int skip = 1; // Save some point operations.
fiat_p256_felem ret[3] = {{0}, {0}, {0}};
for (int i = 256; i >= 0; i--) {
if (!skip) {
fiat_p256_point_double(ret[0], ret[1], ret[2], ret[0], ret[1], ret[2]);
}
// For the |g_scalar|, we use the precomputed table without the
// constant-time lookup.
if (i <= 31) {
// First, look 32 bits upwards.
crypto_word_t bits = fiat_p256_get_bit(g_scalar->bytes, i + 224) << 3;
bits |= fiat_p256_get_bit(g_scalar->bytes, i + 160) << 2;
bits |= fiat_p256_get_bit(g_scalar->bytes, i + 96) << 1;
bits |= fiat_p256_get_bit(g_scalar->bytes, i + 32);
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);
skip = 0;
}
// Second, look at the current position.
bits = fiat_p256_get_bit(g_scalar->bytes, i + 192) << 3;
bits |= fiat_p256_get_bit(g_scalar->bytes, i + 128) << 2;
bits |= fiat_p256_get_bit(g_scalar->bytes, i + 64) << 1;
bits |= fiat_p256_get_bit(g_scalar->bytes, i);
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);
skip = 0;
}
}
int digit = p_wNAF[i];
if (digit != 0) {
assert(digit & 1);
size_t idx = (size_t)(digit < 0 ? (-digit) >> 1 : digit >> 1);
fiat_p256_felem *y = &p_pre_comp[idx][1], tmp;
if (digit < 0) {
fiat_p256_opp(tmp, p_pre_comp[idx][1]);
y = &tmp;
}
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]);
} else {
fiat_p256_copy(ret[0], p_pre_comp[idx][0]);
fiat_p256_copy(ret[1], *y);
fiat_p256_copy(ret[2], p_pre_comp[idx][2]);
skip = 0;
}
}
}
fiat_p256_to_generic(&r->X, ret[0]);
fiat_p256_to_generic(&r->Y, ret[1]);
fiat_p256_to_generic(&r->Z, ret[2]);
}
static int ec_GFp_nistp256_cmp_x_coordinate(const EC_GROUP *group,
const EC_RAW_POINT *p,
const EC_SCALAR *r) {
if (ec_GFp_simple_is_at_infinity(group, p)) {
return 0;
}
// We wish to compare X/Z^2 with r. This is equivalent to comparing X with
// r*Z^2. Note that X and Z are represented in Montgomery form, while r is
// not.
fiat_p256_felem Z2_mont;
fiat_p256_from_generic(Z2_mont, &p->Z);
fiat_p256_mul(Z2_mont, Z2_mont, Z2_mont);
fiat_p256_felem r_Z2;
fiat_p256_from_bytes(r_Z2, r->bytes); // r < order < p, so this is valid.
fiat_p256_mul(r_Z2, r_Z2, Z2_mont);
fiat_p256_felem X;
fiat_p256_from_generic(X, &p->X);
fiat_p256_from_montgomery(X, X);
if (OPENSSL_memcmp(&r_Z2, &X, sizeof(r_Z2)) == 0) {
return 1;
}
// During signing the x coefficient is reduced modulo the group order.
// Therefore there is a small possibility, less than 1/2^128, that group_order
// < p.x < P. in that case we need not only to compare against |r| but also to
// compare against r+group_order.
assert(group->field.width == group->order.width);
if (bn_less_than_words(r->words, group->field_minus_order.words,
group->field.width)) {
// We can ignore the carry because: r + group_order < p < 2^256.
EC_FELEM tmp;
bn_add_words(tmp.words, r->words, group->order.d, group->order.width);
fiat_p256_from_generic(r_Z2, &tmp);
fiat_p256_mul(r_Z2, r_Z2, Z2_mont);
if (OPENSSL_memcmp(&r_Z2, &X, sizeof(r_Z2)) == 0) {
return 1;
}
}
return 0;
}
DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistp256_method) {
out->group_init = ec_GFp_mont_group_init;
out->group_finish = ec_GFp_mont_group_finish;
out->group_set_curve = ec_GFp_mont_group_set_curve;
out->point_get_affine_coordinates =
ec_GFp_nistp256_point_get_affine_coordinates;
out->add = ec_GFp_nistp256_add;
out->dbl = ec_GFp_nistp256_dbl;
out->mul = ec_GFp_nistp256_point_mul;
out->mul_base = ec_GFp_nistp256_point_mul_base;
out->mul_public = ec_GFp_nistp256_point_mul_public;
out->felem_mul = ec_GFp_mont_felem_mul;
out->felem_sqr = ec_GFp_mont_felem_sqr;
out->felem_to_bytes = ec_GFp_mont_felem_to_bytes;
out->felem_from_bytes = ec_GFp_mont_felem_from_bytes;
out->scalar_inv0_montgomery = ec_simple_scalar_inv0_montgomery;
out->scalar_to_montgomery_inv_vartime =
ec_simple_scalar_to_montgomery_inv_vartime;
out->cmp_x_coordinate = ec_GFp_nistp256_cmp_x_coordinate;
}
#undef BORINGSSL_NISTP256_64BIT
@@ -0,0 +1,297 @@
/* Copyright (c) 2020, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
// This file is generated by make_tables.go.
// Base point pre computation
// --------------------------
//
// Two different sorts of precomputed tables are used in the following code.
// Each contain various points on the curve, where each point is three field
// elements (x, y, z).
//
// For the base point table, z is usually 1 (0 for the point at infinity).
// This table has 2 * 16 elements, starting with the following:
// index | bits | point
// ------+---------+------------------------------
// 0 | 0 0 0 0 | 0G
// 1 | 0 0 0 1 | 1G
// 2 | 0 0 1 0 | 2^64G
// 3 | 0 0 1 1 | (2^64 + 1)G
// 4 | 0 1 0 0 | 2^128G
// 5 | 0 1 0 1 | (2^128 + 1)G
// 6 | 0 1 1 0 | (2^128 + 2^64)G
// 7 | 0 1 1 1 | (2^128 + 2^64 + 1)G
// 8 | 1 0 0 0 | 2^192G
// 9 | 1 0 0 1 | (2^192 + 1)G
// 10 | 1 0 1 0 | (2^192 + 2^64)G
// 11 | 1 0 1 1 | (2^192 + 2^64 + 1)G
// 12 | 1 1 0 0 | (2^192 + 2^128)G
// 13 | 1 1 0 1 | (2^192 + 2^128 + 1)G
// 14 | 1 1 1 0 | (2^192 + 2^128 + 2^64)G
// 15 | 1 1 1 1 | (2^192 + 2^128 + 2^64 + 1)G
// followed by a copy of this with each element multiplied by 2^32.
//
// The reason for this is so that we can clock bits into four different
// locations when doing simple scalar multiplies against the base point,
// and then another four locations using the second 16 elements.
//
// Tables for other points have table[i] = iG for i in 0 .. 16.
// fiat_p256_g_pre_comp is the table of precomputed base points
#if defined(BORINGSSL_NISTP256_64BIT)
static const fiat_p256_felem fiat_p256_g_pre_comp[2][15][2] = {
{{{0x79e730d418a9143c, 0x75ba95fc5fedb601, 0x79fb732b77622510,
0x18905f76a53755c6},
{0xddf25357ce95560a, 0x8b4ab8e4ba19e45c, 0xd2e88688dd21f325,
0x8571ff1825885d85}},
{{0x4f922fc516a0d2bb, 0x0d5cc16c1a623499, 0x9241cf3a57c62c8b,
0x2f5e6961fd1b667f},
{0x5c15c70bf5a01797, 0x3d20b44d60956192, 0x04911b37071fdb52,
0xf648f9168d6f0f7b}},
{{0x9e566847e137bbbc, 0xe434469e8a6a0bec, 0xb1c4276179d73463,
0x5abe0285133d0015},
{0x92aa837cc04c7dab, 0x573d9f4c43260c07, 0x0c93156278e6cc37,
0x94bb725b6b6f7383}},
{{0x62a8c244bfe20925, 0x91c19ac38fdce867, 0x5a96a5d5dd387063,
0x61d587d421d324f6},
{0xe87673a2a37173ea, 0x2384800853778b65, 0x10f8441e05bab43e,
0xfa11fe124621efbe}},
{{0x1c891f2b2cb19ffd, 0x01ba8d5bb1923c23, 0xb6d03d678ac5ca8e,
0x586eb04c1f13bedc},
{0x0c35c6e527e8ed09, 0x1e81a33c1819ede2, 0x278fd6c056c652fa,
0x19d5ac0870864f11}},
{{0x62577734d2b533d5, 0x673b8af6a1bdddc0, 0x577e7c9aa79ec293,
0xbb6de651c3b266b1},
{0xe7e9303ab65259b3, 0xd6a0afd3d03a7480, 0xc5ac83d19b3cfc27,
0x60b4619a5d18b99b}},
{{0xbd6a38e11ae5aa1c, 0xb8b7652b49e73658, 0x0b130014ee5f87ed,
0x9d0f27b2aeebffcd},
{0xca9246317a730a55, 0x9c955b2fddbbc83a, 0x07c1dfe0ac019a71,
0x244a566d356ec48d}},
{{0x56f8410ef4f8b16a, 0x97241afec47b266a, 0x0a406b8e6d9c87c1,
0x803f3e02cd42ab1b},
{0x7f0309a804dbec69, 0xa83b85f73bbad05f, 0xc6097273ad8e197f,
0xc097440e5067adc1}},
{{0x846a56f2c379ab34, 0xa8ee068b841df8d1, 0x20314459176c68ef,
0xf1af32d5915f1f30},
{0x99c375315d75bd50, 0x837cffbaf72f67bc, 0x0613a41848d7723f,
0x23d0f130e2d41c8b}},
{{0xed93e225d5be5a2b, 0x6fe799835934f3c6, 0x4314092622626ffc,
0x50bbb4d97990216a},
{0x378191c6e57ec63e, 0x65422c40181dcdb2, 0x41a8099b0236e0f6,
0x2b10011801fe49c3}},
{{0xfc68b5c59b391593, 0xc385f5a2598270fc, 0x7144f3aad19adcbb,
0xdd55899983fbae0c},
{0x93b88b8e74b82ff4, 0xd2e03c4071e734c9, 0x9a7a9eaf43c0322a,
0xe6e4c551149d6041}},
{{0x5fe14bfe80ec21fe, 0xf6ce116ac255be82, 0x98bc5a072f4a5d67,
0xfad27148db7e63af},
{0x90c0b6ac29ab05b3, 0x37a9a83c4e251ae6, 0x0a7dc875c2aade7d,
0x77387de39f0e1a84}},
{{0x1e9ecc49a56c0dd7, 0xa5cffcd846086c74, 0x8f7a1408f505aece,
0xb37b85c0bef0c47e},
{0x3596b6e4cc0e6a8f, 0xfd6d4bbf6b388f23, 0xaba453fac39cef4e,
0x9c135ac8f9f628d5}},
{{0x0a1c729495c8f8be, 0x2961c4803bf362bf, 0x9e418403df63d4ac,
0xc109f9cb91ece900},
{0xc2d095d058945705, 0xb9083d96ddeb85c0, 0x84692b8d7a40449b,
0x9bc3344f2eee1ee1}},
{{0x0d5ae35642913074, 0x55491b2748a542b1, 0x469ca665b310732a,
0x29591d525f1a4cc1},
{0xe76f5b6bb84f983f, 0xbe7eef419f5f84e1, 0x1200d49680baa189,
0x6376551f18ef332c}}},
{{{0x202886024147519a, 0xd0981eac26b372f0, 0xa9d4a7caa785ebc8,
0xd953c50ddbdf58e9},
{0x9d6361ccfd590f8f, 0x72e9626b44e6c917, 0x7fd9611022eb64cf,
0x863ebb7e9eb288f3}},
{{0x4fe7ee31b0e63d34, 0xf4600572a9e54fab, 0xc0493334d5e7b5a4,
0x8589fb9206d54831},
{0xaa70f5cc6583553a, 0x0879094ae25649e5, 0xcc90450710044652,
0xebb0696d02541c4f}},
{{0xabbaa0c03b89da99, 0xa6f2d79eb8284022, 0x27847862b81c05e8,
0x337a4b5905e54d63},
{0x3c67500d21f7794a, 0x207005b77d6d7f61, 0x0a5a378104cfd6e8,
0x0d65e0d5f4c2fbd6}},
{{0xd433e50f6d3549cf, 0x6f33696ffacd665e, 0x695bfdacce11fcb4,
0x810ee252af7c9860},
{0x65450fe17159bb2c, 0xf7dfbebe758b357b, 0x2b057e74d69fea72,
0xd485717a92731745}},
{{0xce1f69bbe83f7669, 0x09f8ae8272877d6b, 0x9548ae543244278d,
0x207755dee3c2c19c},
{0x87bd61d96fef1945, 0x18813cefb12d28c3, 0x9fbcd1d672df64aa,
0x48dc5ee57154b00d}},
{{0xef0f469ef49a3154, 0x3e85a5956e2b2e9a, 0x45aaec1eaa924a9c,
0xaa12dfc8a09e4719},
{0x26f272274df69f1d, 0xe0e4c82ca2ff5e73, 0xb9d8ce73b7a9dd44,
0x6c036e73e48ca901}},
{{0xe1e421e1a47153f0, 0xb86c3b79920418c9, 0x93bdce87705d7672,
0xf25ae793cab79a77},
{0x1f3194a36d869d0c, 0x9d55c8824986c264, 0x49fb5ea3096e945e,
0x39b8e65313db0a3e}},
{{0xe3417bc035d0b34a, 0x440b386b8327c0a7, 0x8fb7262dac0362d1,
0x2c41114ce0cdf943},
{0x2ba5cef1ad95a0b1, 0xc09b37a867d54362, 0x26d6cdd201e486c9,
0x20477abf42ff9297}},
{{0x0f121b41bc0a67d2, 0x62d4760a444d248a, 0x0e044f1d659b4737,
0x08fde365250bb4a8},
{0xaceec3da848bf287, 0xc2a62182d3369d6e, 0x3582dfdc92449482,
0x2f7e2fd2565d6cd7}},
{{0x0a0122b5178a876b, 0x51ff96ff085104b4, 0x050b31ab14f29f76,
0x84abb28b5f87d4e6},
{0xd5ed439f8270790a, 0x2d6cb59d85e3f46b, 0x75f55c1b6c1e2212,
0xe5436f6717655640}},
{{0xc2965ecc9aeb596d, 0x01ea03e7023c92b4, 0x4704b4b62e013961,
0x0ca8fd3f905ea367},
{0x92523a42551b2b61, 0x1eb7a89c390fcd06, 0xe7f1d2be0392a63e,
0x96dca2644ddb0c33}},
{{0x231c210e15339848, 0xe87a28e870778c8d, 0x9d1de6616956e170,
0x4ac3c9382bb09c0b},
{0x19be05516998987d, 0x8b2376c4ae09f4d6, 0x1de0b7651a3f933d,
0x380d94c7e39705f4}},
{{0x3685954b8c31c31d, 0x68533d005bf21a0c, 0x0bd7626e75c79ec9,
0xca17754742c69d54},
{0xcc6edafff6d2dbb2, 0xfd0d8cbd174a9d18, 0x875e8793aa4578e8,
0xa976a7139cab2ce6}},
{{0xce37ab11b43ea1db, 0x0a7ff1a95259d292, 0x851b02218f84f186,
0xa7222beadefaad13},
{0xa2ac78ec2b0a9144, 0x5a024051f2fa59c5, 0x91d1eca56147ce38,
0xbe94d523bc2ac690}},
{{0x2d8daefd79ec1a0f, 0x3bbcd6fdceb39c97, 0xf5575ffc58f61a95,
0xdbd986c4adf7b420},
{0x81aa881415f39eb7, 0x6ee2fcf5b98d976c, 0x5465475dcf2f717d,
0x8e24d3c46860bbd0}}}};
#else
static const fiat_p256_felem fiat_p256_g_pre_comp[2][15][2] = {
{{{0x18a9143c, 0x79e730d4, 0x5fedb601, 0x75ba95fc, 0x77622510, 0x79fb732b,
0xa53755c6, 0x18905f76},
{0xce95560a, 0xddf25357, 0xba19e45c, 0x8b4ab8e4, 0xdd21f325, 0xd2e88688,
0x25885d85, 0x8571ff18}},
{{0x16a0d2bb, 0x4f922fc5, 0x1a623499, 0x0d5cc16c, 0x57c62c8b, 0x9241cf3a,
0xfd1b667f, 0x2f5e6961},
{0xf5a01797, 0x5c15c70b, 0x60956192, 0x3d20b44d, 0x071fdb52, 0x04911b37,
0x8d6f0f7b, 0xf648f916}},
{{0xe137bbbc, 0x9e566847, 0x8a6a0bec, 0xe434469e, 0x79d73463, 0xb1c42761,
0x133d0015, 0x5abe0285},
{0xc04c7dab, 0x92aa837c, 0x43260c07, 0x573d9f4c, 0x78e6cc37, 0x0c931562,
0x6b6f7383, 0x94bb725b}},
{{0xbfe20925, 0x62a8c244, 0x8fdce867, 0x91c19ac3, 0xdd387063, 0x5a96a5d5,
0x21d324f6, 0x61d587d4},
{0xa37173ea, 0xe87673a2, 0x53778b65, 0x23848008, 0x05bab43e, 0x10f8441e,
0x4621efbe, 0xfa11fe12}},
{{0x2cb19ffd, 0x1c891f2b, 0xb1923c23, 0x01ba8d5b, 0x8ac5ca8e, 0xb6d03d67,
0x1f13bedc, 0x586eb04c},
{0x27e8ed09, 0x0c35c6e5, 0x1819ede2, 0x1e81a33c, 0x56c652fa, 0x278fd6c0,
0x70864f11, 0x19d5ac08}},
{{0xd2b533d5, 0x62577734, 0xa1bdddc0, 0x673b8af6, 0xa79ec293, 0x577e7c9a,
0xc3b266b1, 0xbb6de651},
{0xb65259b3, 0xe7e9303a, 0xd03a7480, 0xd6a0afd3, 0x9b3cfc27, 0xc5ac83d1,
0x5d18b99b, 0x60b4619a}},
{{0x1ae5aa1c, 0xbd6a38e1, 0x49e73658, 0xb8b7652b, 0xee5f87ed, 0x0b130014,
0xaeebffcd, 0x9d0f27b2},
{0x7a730a55, 0xca924631, 0xddbbc83a, 0x9c955b2f, 0xac019a71, 0x07c1dfe0,
0x356ec48d, 0x244a566d}},
{{0xf4f8b16a, 0x56f8410e, 0xc47b266a, 0x97241afe, 0x6d9c87c1, 0x0a406b8e,
0xcd42ab1b, 0x803f3e02},
{0x04dbec69, 0x7f0309a8, 0x3bbad05f, 0xa83b85f7, 0xad8e197f, 0xc6097273,
0x5067adc1, 0xc097440e}},
{{0xc379ab34, 0x846a56f2, 0x841df8d1, 0xa8ee068b, 0x176c68ef, 0x20314459,
0x915f1f30, 0xf1af32d5},
{0x5d75bd50, 0x99c37531, 0xf72f67bc, 0x837cffba, 0x48d7723f, 0x0613a418,
0xe2d41c8b, 0x23d0f130}},
{{0xd5be5a2b, 0xed93e225, 0x5934f3c6, 0x6fe79983, 0x22626ffc, 0x43140926,
0x7990216a, 0x50bbb4d9},
{0xe57ec63e, 0x378191c6, 0x181dcdb2, 0x65422c40, 0x0236e0f6, 0x41a8099b,
0x01fe49c3, 0x2b100118}},
{{0x9b391593, 0xfc68b5c5, 0x598270fc, 0xc385f5a2, 0xd19adcbb, 0x7144f3aa,
0x83fbae0c, 0xdd558999},
{0x74b82ff4, 0x93b88b8e, 0x71e734c9, 0xd2e03c40, 0x43c0322a, 0x9a7a9eaf,
0x149d6041, 0xe6e4c551}},
{{0x80ec21fe, 0x5fe14bfe, 0xc255be82, 0xf6ce116a, 0x2f4a5d67, 0x98bc5a07,
0xdb7e63af, 0xfad27148},
{0x29ab05b3, 0x90c0b6ac, 0x4e251ae6, 0x37a9a83c, 0xc2aade7d, 0x0a7dc875,
0x9f0e1a84, 0x77387de3}},
{{0xa56c0dd7, 0x1e9ecc49, 0x46086c74, 0xa5cffcd8, 0xf505aece, 0x8f7a1408,
0xbef0c47e, 0xb37b85c0},
{0xcc0e6a8f, 0x3596b6e4, 0x6b388f23, 0xfd6d4bbf, 0xc39cef4e, 0xaba453fa,
0xf9f628d5, 0x9c135ac8}},
{{0x95c8f8be, 0x0a1c7294, 0x3bf362bf, 0x2961c480, 0xdf63d4ac, 0x9e418403,
0x91ece900, 0xc109f9cb},
{0x58945705, 0xc2d095d0, 0xddeb85c0, 0xb9083d96, 0x7a40449b, 0x84692b8d,
0x2eee1ee1, 0x9bc3344f}},
{{0x42913074, 0x0d5ae356, 0x48a542b1, 0x55491b27, 0xb310732a, 0x469ca665,
0x5f1a4cc1, 0x29591d52},
{0xb84f983f, 0xe76f5b6b, 0x9f5f84e1, 0xbe7eef41, 0x80baa189, 0x1200d496,
0x18ef332c, 0x6376551f}}},
{{{0x4147519a, 0x20288602, 0x26b372f0, 0xd0981eac, 0xa785ebc8, 0xa9d4a7ca,
0xdbdf58e9, 0xd953c50d},
{0xfd590f8f, 0x9d6361cc, 0x44e6c917, 0x72e9626b, 0x22eb64cf, 0x7fd96110,
0x9eb288f3, 0x863ebb7e}},
{{0xb0e63d34, 0x4fe7ee31, 0xa9e54fab, 0xf4600572, 0xd5e7b5a4, 0xc0493334,
0x06d54831, 0x8589fb92},
{0x6583553a, 0xaa70f5cc, 0xe25649e5, 0x0879094a, 0x10044652, 0xcc904507,
0x02541c4f, 0xebb0696d}},
{{0x3b89da99, 0xabbaa0c0, 0xb8284022, 0xa6f2d79e, 0xb81c05e8, 0x27847862,
0x05e54d63, 0x337a4b59},
{0x21f7794a, 0x3c67500d, 0x7d6d7f61, 0x207005b7, 0x04cfd6e8, 0x0a5a3781,
0xf4c2fbd6, 0x0d65e0d5}},
{{0x6d3549cf, 0xd433e50f, 0xfacd665e, 0x6f33696f, 0xce11fcb4, 0x695bfdac,
0xaf7c9860, 0x810ee252},
{0x7159bb2c, 0x65450fe1, 0x758b357b, 0xf7dfbebe, 0xd69fea72, 0x2b057e74,
0x92731745, 0xd485717a}},
{{0xe83f7669, 0xce1f69bb, 0x72877d6b, 0x09f8ae82, 0x3244278d, 0x9548ae54,
0xe3c2c19c, 0x207755de},
{0x6fef1945, 0x87bd61d9, 0xb12d28c3, 0x18813cef, 0x72df64aa, 0x9fbcd1d6,
0x7154b00d, 0x48dc5ee5}},
{{0xf49a3154, 0xef0f469e, 0x6e2b2e9a, 0x3e85a595, 0xaa924a9c, 0x45aaec1e,
0xa09e4719, 0xaa12dfc8},
{0x4df69f1d, 0x26f27227, 0xa2ff5e73, 0xe0e4c82c, 0xb7a9dd44, 0xb9d8ce73,
0xe48ca901, 0x6c036e73}},
{{0xa47153f0, 0xe1e421e1, 0x920418c9, 0xb86c3b79, 0x705d7672, 0x93bdce87,
0xcab79a77, 0xf25ae793},
{0x6d869d0c, 0x1f3194a3, 0x4986c264, 0x9d55c882, 0x096e945e, 0x49fb5ea3,
0x13db0a3e, 0x39b8e653}},
{{0x35d0b34a, 0xe3417bc0, 0x8327c0a7, 0x440b386b, 0xac0362d1, 0x8fb7262d,
0xe0cdf943, 0x2c41114c},
{0xad95a0b1, 0x2ba5cef1, 0x67d54362, 0xc09b37a8, 0x01e486c9, 0x26d6cdd2,
0x42ff9297, 0x20477abf}},
{{0xbc0a67d2, 0x0f121b41, 0x444d248a, 0x62d4760a, 0x659b4737, 0x0e044f1d,
0x250bb4a8, 0x08fde365},
{0x848bf287, 0xaceec3da, 0xd3369d6e, 0xc2a62182, 0x92449482, 0x3582dfdc,
0x565d6cd7, 0x2f7e2fd2}},
{{0x178a876b, 0x0a0122b5, 0x085104b4, 0x51ff96ff, 0x14f29f76, 0x050b31ab,
0x5f87d4e6, 0x84abb28b},
{0x8270790a, 0xd5ed439f, 0x85e3f46b, 0x2d6cb59d, 0x6c1e2212, 0x75f55c1b,
0x17655640, 0xe5436f67}},
{{0x9aeb596d, 0xc2965ecc, 0x023c92b4, 0x01ea03e7, 0x2e013961, 0x4704b4b6,
0x905ea367, 0x0ca8fd3f},
{0x551b2b61, 0x92523a42, 0x390fcd06, 0x1eb7a89c, 0x0392a63e, 0xe7f1d2be,
0x4ddb0c33, 0x96dca264}},
{{0x15339848, 0x231c210e, 0x70778c8d, 0xe87a28e8, 0x6956e170, 0x9d1de661,
0x2bb09c0b, 0x4ac3c938},
{0x6998987d, 0x19be0551, 0xae09f4d6, 0x8b2376c4, 0x1a3f933d, 0x1de0b765,
0xe39705f4, 0x380d94c7}},
{{0x8c31c31d, 0x3685954b, 0x5bf21a0c, 0x68533d00, 0x75c79ec9, 0x0bd7626e,
0x42c69d54, 0xca177547},
{0xf6d2dbb2, 0xcc6edaff, 0x174a9d18, 0xfd0d8cbd, 0xaa4578e8, 0x875e8793,
0x9cab2ce6, 0xa976a713}},
{{0xb43ea1db, 0xce37ab11, 0x5259d292, 0x0a7ff1a9, 0x8f84f186, 0x851b0221,
0xdefaad13, 0xa7222bea},
{0x2b0a9144, 0xa2ac78ec, 0xf2fa59c5, 0x5a024051, 0x6147ce38, 0x91d1eca5,
0xbc2ac690, 0xbe94d523}},
{{0x79ec1a0f, 0x2d8daefd, 0xceb39c97, 0x3bbcd6fd, 0x58f61a95, 0xf5575ffc,
0xadf7b420, 0xdbd986c4},
{0x15f39eb7, 0x81aa8814, 0xb98d976c, 0x6ee2fcf5, 0xcf2f717d, 0x5465475d,
0x6860bbd0, 0x8e24d3c4}}}};
#endif
@@ -51,6 +51,45 @@ int ec_random_nonzero_scalar(const EC_GROUP *group, EC_SCALAR *out,
additional_data);
}
void ec_scalar_to_bytes(const EC_GROUP *group, uint8_t *out, size_t *out_len,
const EC_SCALAR *in) {
size_t len = BN_num_bytes(&group->order);
for (size_t i = 0; i < len; i++) {
out[len - i - 1] = in->bytes[i];
}
*out_len = len;
}
int ec_scalar_from_bytes(const EC_GROUP *group, EC_SCALAR *out,
const uint8_t *in, size_t len) {
if (len != BN_num_bytes(&group->order)) {
OPENSSL_PUT_ERROR(EC, EC_R_INVALID_SCALAR);
return 0;
}
OPENSSL_memset(out, 0, sizeof(EC_SCALAR));
for (size_t i = 0; i < len; i++) {
out->bytes[i] = in[len - i - 1];
}
if (!bn_less_than_words(out->words, group->order.d, group->order.width)) {
OPENSSL_PUT_ERROR(EC, EC_R_INVALID_SCALAR);
return 0;
}
return 1;
}
void ec_scalar_reduce(const EC_GROUP *group, EC_SCALAR *out,
const BN_ULONG *words, size_t num) {
// Convert "from" Montgomery form so the value is reduced modulo the order.
bn_from_montgomery_small(out->words, group->order.width, words, num,
group->order_mont);
// Convert "to" Montgomery form to remove the R^-1 factor added.
ec_scalar_to_montgomery(group, out, out);
}
void ec_scalar_add(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a,
const EC_SCALAR *b) {
const BIGNUM *order = &group->order;
@@ -59,6 +98,26 @@ void ec_scalar_add(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a,
OPENSSL_cleanse(tmp, sizeof(tmp));
}
void ec_scalar_sub(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a,
const EC_SCALAR *b) {
const BIGNUM *order = &group->order;
BN_ULONG tmp[EC_MAX_WORDS];
bn_mod_sub_words(r->words, a->words, b->words, order->d, tmp, order->width);
OPENSSL_cleanse(tmp, sizeof(tmp));
}
void ec_scalar_neg(const EC_GROUP *group, EC_SCALAR *r, const EC_SCALAR *a) {
EC_SCALAR zero;
OPENSSL_memset(&zero, 0, sizeof(EC_SCALAR));
ec_scalar_sub(group, r, &zero, a);
}
void ec_scalar_select(const EC_GROUP *group, EC_SCALAR *out, BN_ULONG mask,
const EC_SCALAR *a, const EC_SCALAR *b) {
const BIGNUM *order = &group->order;
bn_select_words(out->words, mask, a->words, b->words, order->width);
}
void ec_scalar_to_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a) {
const BIGNUM *order = &group->order;
@@ -68,7 +127,8 @@ void ec_scalar_to_montgomery(const EC_GROUP *group, EC_SCALAR *r,
void ec_scalar_from_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a) {
const BIGNUM *order = &group->order;
bn_from_montgomery_small(r->words, a->words, order->width, group->order_mont);
bn_from_montgomery_small(r->words, order->width, a->words, order->width,
group->order_mont);
}
void ec_scalar_mul_montgomery(const EC_GROUP *group, EC_SCALAR *r,
@@ -78,19 +138,38 @@ void ec_scalar_mul_montgomery(const EC_GROUP *group, EC_SCALAR *r,
group->order_mont);
}
void ec_simple_scalar_inv_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a) {
void ec_simple_scalar_inv0_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a) {
const BIGNUM *order = &group->order;
bn_mod_inverse_prime_mont_small(r->words, a->words, order->width,
group->order_mont);
bn_mod_inverse0_prime_mont_small(r->words, a->words, order->width,
group->order_mont);
}
void ec_scalar_inv_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a) {
group->meth->scalar_inv_montgomery(group, r, a);
int ec_simple_scalar_to_montgomery_inv_vartime(const EC_GROUP *group,
EC_SCALAR *r,
const EC_SCALAR *a) {
if (ec_scalar_is_zero(group, a)) {
return 0;
}
// This implementation (in fact) runs in constant time,
// even though for this interface it is not mandatory.
// r = a^-1 in the Montgomery domain. This is
// |ec_scalar_to_montgomery| followed by |ec_scalar_inv0_montgomery|, but
// |ec_scalar_inv0_montgomery| followed by |ec_scalar_from_montgomery| is
// equivalent and slightly more efficient.
ec_scalar_inv0_montgomery(group, r, a);
ec_scalar_from_montgomery(group, r, r);
return 1;
}
int ec_scalar_inv_montgomery_vartime(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a) {
return group->meth->scalar_inv_montgomery_vartime(group, r, a);
void ec_scalar_inv0_montgomery(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a) {
group->meth->scalar_inv0_montgomery(group, r, a);
}
int ec_scalar_to_montgomery_inv_vartime(const EC_GROUP *group, EC_SCALAR *r,
const EC_SCALAR *a) {
return group->meth->scalar_to_montgomery_inv_vartime(group, r, a);
}
@@ -101,22 +101,13 @@ void ec_GFp_simple_group_finish(EC_GROUP *group) {
int ec_GFp_simple_group_set_curve(EC_GROUP *group, const BIGNUM *p,
const BIGNUM *a, const BIGNUM *b,
BN_CTX *ctx) {
int ret = 0;
BN_CTX *new_ctx = NULL;
// p must be a prime > 3
if (BN_num_bits(p) <= 2 || !BN_is_odd(p)) {
OPENSSL_PUT_ERROR(EC, EC_R_INVALID_FIELD);
return 0;
}
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL) {
return 0;
}
}
int ret = 0;
BN_CTX_start(ctx);
BIGNUM *tmp = BN_CTX_get(ctx);
if (tmp == NULL) {
@@ -131,33 +122,23 @@ int ec_GFp_simple_group_set_curve(EC_GROUP *group, const BIGNUM *p,
// Store the field in minimal form, so it can be used with |BN_ULONG| arrays.
bn_set_minimal_width(&group->field);
// group->a
if (!BN_nnmod(tmp, a, &group->field, ctx) ||
!ec_bignum_to_felem(group, &group->a, tmp)) {
if (!ec_bignum_to_felem(group, &group->a, a) ||
!ec_bignum_to_felem(group, &group->b, b) ||
!ec_bignum_to_felem(group, &group->one, BN_value_one())) {
goto err;
}
// group->a_is_minus3
if (!BN_add_word(tmp, 3)) {
if (!BN_copy(tmp, a) ||
!BN_add_word(tmp, 3)) {
goto err;
}
group->a_is_minus3 = (0 == BN_cmp(tmp, &group->field));
// group->b
if (!BN_nnmod(tmp, b, &group->field, ctx) ||
!ec_bignum_to_felem(group, &group->b, tmp)) {
goto err;
}
if (!ec_bignum_to_felem(group, &group->one, BN_value_one())) {
goto err;
}
ret = 1;
err:
BN_CTX_end(ctx);
BN_CTX_free(new_ctx);
return ret;
}
@@ -190,24 +171,6 @@ void ec_GFp_simple_point_set_to_infinity(const EC_GROUP *group,
ec_GFp_simple_point_init(point);
}
int ec_GFp_simple_point_set_affine_coordinates(const EC_GROUP *group,
EC_RAW_POINT *point,
const BIGNUM *x,
const BIGNUM *y) {
if (x == NULL || y == NULL) {
OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (!ec_bignum_to_felem(group, &point->X, x) ||
!ec_bignum_to_felem(group, &point->Y, y)) {
return 0;
}
OPENSSL_memcpy(&point->Z, &group->one, sizeof(EC_FELEM));
return 1;
}
void ec_GFp_simple_invert(const EC_GROUP *group, EC_RAW_POINT *point) {
ec_felem_neg(group, &point->Y, &point->Y);
}
@@ -219,10 +182,6 @@ int ec_GFp_simple_is_at_infinity(const EC_GROUP *group,
int ec_GFp_simple_is_on_curve(const EC_GROUP *group,
const EC_RAW_POINT *point) {
if (ec_GFp_simple_is_at_infinity(group, point)) {
return 1;
}
// We have a curve defined by a Weierstrass equation
// y^2 = x^3 + a*x + b.
// The point to consider is given in Jacobian projective coordinates
@@ -231,6 +190,9 @@ int ec_GFp_simple_is_on_curve(const EC_GROUP *group,
// into
// Y^2 = X^3 + a*X*Z^4 + b*Z^6.
// To test this, we add up the right-hand side in 'rh'.
//
// This function may be used when double-checking the secret result of a point
// multiplication, so we proceed in constant-time.
void (*const felem_mul)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a,
const EC_FELEM *b) = group->meth->felem_mul;
@@ -242,128 +204,114 @@ int ec_GFp_simple_is_on_curve(const EC_GROUP *group,
felem_sqr(group, &rh, &point->X);
EC_FELEM tmp, Z4, Z6;
if (!ec_felem_equal(group, &point->Z, &group->one)) {
felem_sqr(group, &tmp, &point->Z);
felem_sqr(group, &Z4, &tmp);
felem_mul(group, &Z6, &Z4, &tmp);
felem_sqr(group, &tmp, &point->Z);
felem_sqr(group, &Z4, &tmp);
felem_mul(group, &Z6, &Z4, &tmp);
// rh := (rh + a*Z^4)*X
if (group->a_is_minus3) {
ec_felem_add(group, &tmp, &Z4, &Z4);
ec_felem_add(group, &tmp, &tmp, &Z4);
ec_felem_sub(group, &rh, &rh, &tmp);
felem_mul(group, &rh, &rh, &point->X);
} else {
felem_mul(group, &tmp, &Z4, &group->a);
ec_felem_add(group, &rh, &rh, &tmp);
felem_mul(group, &rh, &rh, &point->X);
}
// rh := rh + b*Z^6
felem_mul(group, &tmp, &group->b, &Z6);
ec_felem_add(group, &rh, &rh, &tmp);
// rh := rh + a*Z^4
if (group->a_is_minus3) {
ec_felem_add(group, &tmp, &Z4, &Z4);
ec_felem_add(group, &tmp, &tmp, &Z4);
ec_felem_sub(group, &rh, &rh, &tmp);
} else {
// rh := (rh + a)*X
ec_felem_add(group, &rh, &rh, &group->a);
felem_mul(group, &rh, &rh, &point->X);
// rh := rh + b
ec_felem_add(group, &rh, &rh, &group->b);
felem_mul(group, &tmp, &Z4, &group->a);
ec_felem_add(group, &rh, &rh, &tmp);
}
// rh := (rh + a*Z^4)*X
felem_mul(group, &rh, &rh, &point->X);
// rh := rh + b*Z^6
felem_mul(group, &tmp, &group->b, &Z6);
ec_felem_add(group, &rh, &rh, &tmp);
// 'lh' := Y^2
felem_sqr(group, &tmp, &point->Y);
return ec_felem_equal(group, &tmp, &rh);
ec_felem_sub(group, &tmp, &tmp, &rh);
BN_ULONG not_equal = ec_felem_non_zero_mask(group, &tmp);
// If Z = 0, the point is infinity, which is always on the curve.
BN_ULONG not_infinity = ec_felem_non_zero_mask(group, &point->Z);
return 1 & ~(not_infinity & not_equal);
}
int ec_GFp_simple_cmp(const EC_GROUP *group, const EC_RAW_POINT *a,
const EC_RAW_POINT *b) {
// Note this function returns zero if |a| and |b| are equal and 1 if they are
// not equal.
if (ec_GFp_simple_is_at_infinity(group, a)) {
return ec_GFp_simple_is_at_infinity(group, b) ? 0 : 1;
}
int ec_GFp_simple_points_equal(const EC_GROUP *group, const EC_RAW_POINT *a,
const EC_RAW_POINT *b) {
// This function is implemented in constant-time for two reasons. First,
// although EC points are usually public, their Jacobian Z coordinates may be
// secret, or at least are not obviously public. Second, more complex
// protocols will sometimes manipulate secret points.
//
// This does mean that we pay a 6M+2S Jacobian comparison when comparing two
// publicly affine points costs no field operations at all. If needed, we can
// restore this optimization by keeping better track of affine vs. Jacobian
// forms. See https://crbug.com/boringssl/326.
if (ec_GFp_simple_is_at_infinity(group, b)) {
return 1;
}
int a_Z_is_one = ec_felem_equal(group, &a->Z, &group->one);
int b_Z_is_one = ec_felem_equal(group, &b->Z, &group->one);
if (a_Z_is_one && b_Z_is_one) {
return !ec_felem_equal(group, &a->X, &b->X) ||
!ec_felem_equal(group, &a->Y, &b->Y);
}
// If neither |a| or |b| is infinity, we have to decide whether
// (X_a/Z_a^2, Y_a/Z_a^3) = (X_b/Z_b^2, Y_b/Z_b^3),
// or equivalently, whether
// (X_a*Z_b^2, Y_a*Z_b^3) = (X_b*Z_a^2, Y_b*Z_a^3).
void (*const felem_mul)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a,
const EC_FELEM *b) = group->meth->felem_mul;
void (*const felem_sqr)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a) =
group->meth->felem_sqr;
// We have to decide whether
// (X_a/Z_a^2, Y_a/Z_a^3) = (X_b/Z_b^2, Y_b/Z_b^3),
// or equivalently, whether
// (X_a*Z_b^2, Y_a*Z_b^3) = (X_b*Z_a^2, Y_b*Z_a^3).
EC_FELEM tmp1, tmp2, Za23, Zb23;
const EC_FELEM *tmp1_, *tmp2_;
if (!b_Z_is_one) {
felem_sqr(group, &Zb23, &b->Z);
felem_mul(group, &tmp1, &a->X, &Zb23);
tmp1_ = &tmp1;
} else {
tmp1_ = &a->X;
}
if (!a_Z_is_one) {
felem_sqr(group, &Za23, &a->Z);
felem_mul(group, &tmp2, &b->X, &Za23);
tmp2_ = &tmp2;
} else {
tmp2_ = &b->X;
}
felem_sqr(group, &Zb23, &b->Z); // Zb23 = Z_b^2
felem_mul(group, &tmp1, &a->X, &Zb23); // tmp1 = X_a * Z_b^2
felem_sqr(group, &Za23, &a->Z); // Za23 = Z_a^2
felem_mul(group, &tmp2, &b->X, &Za23); // tmp2 = X_b * Z_a^2
ec_felem_sub(group, &tmp1, &tmp1, &tmp2);
const BN_ULONG x_not_equal = ec_felem_non_zero_mask(group, &tmp1);
// Compare X_a*Z_b^2 with X_b*Z_a^2.
if (!ec_felem_equal(group, tmp1_, tmp2_)) {
return 1; // The points differ.
}
felem_mul(group, &Zb23, &Zb23, &b->Z); // Zb23 = Z_b^3
felem_mul(group, &tmp1, &a->Y, &Zb23); // tmp1 = Y_a * Z_b^3
felem_mul(group, &Za23, &Za23, &a->Z); // Za23 = Z_a^3
felem_mul(group, &tmp2, &b->Y, &Za23); // tmp2 = Y_b * Z_a^3
ec_felem_sub(group, &tmp1, &tmp1, &tmp2);
const BN_ULONG y_not_equal = ec_felem_non_zero_mask(group, &tmp1);
const BN_ULONG x_and_y_equal = ~(x_not_equal | y_not_equal);
if (!b_Z_is_one) {
felem_mul(group, &Zb23, &Zb23, &b->Z);
felem_mul(group, &tmp1, &a->Y, &Zb23);
// tmp1_ = &tmp1
} else {
tmp1_ = &a->Y;
}
if (!a_Z_is_one) {
felem_mul(group, &Za23, &Za23, &a->Z);
felem_mul(group, &tmp2, &b->Y, &Za23);
// tmp2_ = &tmp2
} else {
tmp2_ = &b->Y;
}
const BN_ULONG a_not_infinity = ec_felem_non_zero_mask(group, &a->Z);
const BN_ULONG b_not_infinity = ec_felem_non_zero_mask(group, &b->Z);
const BN_ULONG a_and_b_infinity = ~(a_not_infinity | b_not_infinity);
// Compare Y_a*Z_b^3 with Y_b*Z_a^3.
if (!ec_felem_equal(group, tmp1_, tmp2_)) {
return 1; // The points differ.
}
// The points are equal.
return 0;
const BN_ULONG equal =
a_and_b_infinity | (a_not_infinity & b_not_infinity & x_and_y_equal);
return equal & 1;
}
int ec_GFp_simple_mont_inv_mod_ord_vartime(const EC_GROUP *group,
EC_SCALAR *out,
const EC_SCALAR *in) {
// This implementation (in fact) runs in constant time,
// even though for this interface it is not mandatory.
int ec_affine_jacobian_equal(const EC_GROUP *group, const EC_AFFINE *a,
const EC_RAW_POINT *b) {
// If |b| is not infinity, we have to decide whether
// (X_a, Y_a) = (X_b/Z_b^2, Y_b/Z_b^3),
// or equivalently, whether
// (X_a*Z_b^2, Y_a*Z_b^3) = (X_b, Y_b).
// out = in^-1 in the Montgomery domain. This is
// |ec_scalar_to_montgomery| followed by |ec_scalar_inv_montgomery|, but
// |ec_scalar_inv_montgomery| followed by |ec_scalar_from_montgomery| is
// equivalent and slightly more efficient.
ec_scalar_inv_montgomery(group, out, in);
ec_scalar_from_montgomery(group, out, out);
return 1;
void (*const felem_mul)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a,
const EC_FELEM *b) = group->meth->felem_mul;
void (*const felem_sqr)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a) =
group->meth->felem_sqr;
EC_FELEM tmp, Zb2;
felem_sqr(group, &Zb2, &b->Z); // Zb2 = Z_b^2
felem_mul(group, &tmp, &a->X, &Zb2); // tmp = X_a * Z_b^2
ec_felem_sub(group, &tmp, &tmp, &b->X);
const BN_ULONG x_not_equal = ec_felem_non_zero_mask(group, &tmp);
felem_mul(group, &tmp, &a->Y, &Zb2); // tmp = Y_a * Z_b^2
felem_mul(group, &tmp, &tmp, &b->Z); // tmp = Y_a * Z_b^3
ec_felem_sub(group, &tmp, &tmp, &b->Y);
const BN_ULONG y_not_equal = ec_felem_non_zero_mask(group, &tmp);
const BN_ULONG x_and_y_equal = ~(x_not_equal | y_not_equal);
const BN_ULONG b_not_infinity = ec_felem_non_zero_mask(group, &b->Z);
const BN_ULONG equal = b_not_infinity & x_and_y_equal;
return equal & 1;
}
int ec_GFp_simple_cmp_x_coordinate(const EC_GROUP *group, const EC_RAW_POINT *p,
@@ -378,3 +326,32 @@ int ec_GFp_simple_cmp_x_coordinate(const EC_GROUP *group, const EC_RAW_POINT *p,
return ec_get_x_coordinate_as_scalar(group, &x, p) &&
ec_scalar_equal_vartime(group, &x, r);
}
void ec_GFp_simple_felem_to_bytes(const EC_GROUP *group, uint8_t *out,
size_t *out_len, const EC_FELEM *in) {
size_t len = BN_num_bytes(&group->field);
for (size_t i = 0; i < len; i++) {
out[i] = in->bytes[len - 1 - i];
}
*out_len = len;
}
int ec_GFp_simple_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out,
const uint8_t *in, size_t len) {
if (len != BN_num_bytes(&group->field)) {
OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR);
return 0;
}
OPENSSL_memset(out, 0, sizeof(EC_FELEM));
for (size_t i = 0; i < len; i++) {
out->bytes[i] = in[len - 1 - i];
}
if (!bn_less_than_words(out->words, group->field.d, group->field.width)) {
OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR);
return 0;
}
return 1;
}
@@ -60,9 +60,7 @@ void ec_GFp_mont_mul(const EC_GROUP *group, EC_RAW_POINT *r,
OPENSSL_memset(&tmp, 0, sizeof(EC_RAW_POINT));
for (size_t j = 0; j < OPENSSL_ARRAY_SIZE(precomp); j++) {
BN_ULONG mask = constant_time_eq_w(j, window);
ec_felem_select(group, &tmp.X, mask, &precomp[j].X, &tmp.X);
ec_felem_select(group, &tmp.Y, mask, &precomp[j].Y, &tmp.Y);
ec_felem_select(group, &tmp.Z, mask, &precomp[j].Z, &tmp.Z);
ec_point_select(group, &tmp, mask, &precomp[j], &tmp);
}
if (r_is_at_infinity) {
@@ -82,3 +80,191 @@ void ec_GFp_mont_mul_base(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_SCALAR *scalar) {
ec_GFp_mont_mul(group, r, &group->generator->raw, scalar);
}
static void ec_GFp_mont_batch_precomp(const EC_GROUP *group, EC_RAW_POINT *out,
size_t num, const EC_RAW_POINT *p) {
assert(num > 1);
ec_GFp_simple_point_set_to_infinity(group, &out[0]);
ec_GFp_simple_point_copy(&out[1], p);
for (size_t j = 2; j < num; j++) {
if (j & 1) {
ec_GFp_mont_add(group, &out[j], &out[1], &out[j - 1]);
} else {
ec_GFp_mont_dbl(group, &out[j], &out[j / 2]);
}
}
}
static void ec_GFp_mont_batch_get_window(const EC_GROUP *group,
EC_RAW_POINT *out,
const EC_RAW_POINT precomp[17],
const EC_SCALAR *scalar, unsigned i) {
const size_t width = group->order.width;
uint8_t window = bn_is_bit_set_words(scalar->words, width, i + 4) << 5;
window |= bn_is_bit_set_words(scalar->words, width, i + 3) << 4;
window |= bn_is_bit_set_words(scalar->words, width, i + 2) << 3;
window |= bn_is_bit_set_words(scalar->words, width, i + 1) << 2;
window |= bn_is_bit_set_words(scalar->words, width, i) << 1;
if (i > 0) {
window |= bn_is_bit_set_words(scalar->words, width, i - 1);
}
crypto_word_t sign, digit;
ec_GFp_nistp_recode_scalar_bits(&sign, &digit, window);
// Select the entry in constant-time.
OPENSSL_memset(out, 0, sizeof(EC_RAW_POINT));
for (size_t j = 0; j < 17; j++) {
BN_ULONG mask = constant_time_eq_w(j, digit);
ec_point_select(group, out, mask, &precomp[j], out);
}
// Negate if necessary.
EC_FELEM neg_Y;
ec_felem_neg(group, &neg_Y, &out->Y);
crypto_word_t sign_mask = sign;
sign_mask = 0u - sign_mask;
ec_felem_select(group, &out->Y, sign_mask, &neg_Y, &out->Y);
}
void ec_GFp_mont_mul_batch(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_RAW_POINT *p0, const EC_SCALAR *scalar0,
const EC_RAW_POINT *p1, const EC_SCALAR *scalar1,
const EC_RAW_POINT *p2, const EC_SCALAR *scalar2) {
EC_RAW_POINT precomp[3][17];
ec_GFp_mont_batch_precomp(group, precomp[0], 17, p0);
ec_GFp_mont_batch_precomp(group, precomp[1], 17, p1);
if (p2 != NULL) {
ec_GFp_mont_batch_precomp(group, precomp[2], 17, p2);
}
// Divide bits in |scalar| into windows.
unsigned bits = BN_num_bits(&group->order);
int r_is_at_infinity = 1;
for (unsigned i = bits; i <= bits; i--) {
if (!r_is_at_infinity) {
ec_GFp_mont_dbl(group, r, r);
}
if (i % 5 == 0) {
EC_RAW_POINT tmp;
ec_GFp_mont_batch_get_window(group, &tmp, precomp[0], scalar0, i);
if (r_is_at_infinity) {
ec_GFp_simple_point_copy(r, &tmp);
r_is_at_infinity = 0;
} else {
ec_GFp_mont_add(group, r, r, &tmp);
}
ec_GFp_mont_batch_get_window(group, &tmp, precomp[1], scalar1, i);
ec_GFp_mont_add(group, r, r, &tmp);
if (p2 != NULL) {
ec_GFp_mont_batch_get_window(group, &tmp, precomp[2], scalar2, i);
ec_GFp_mont_add(group, r, r, &tmp);
}
}
}
if (r_is_at_infinity) {
ec_GFp_simple_point_set_to_infinity(group, r);
}
}
static unsigned ec_GFp_mont_comb_stride(const EC_GROUP *group) {
return (BN_num_bits(&group->field) + EC_MONT_PRECOMP_COMB_SIZE - 1) /
EC_MONT_PRECOMP_COMB_SIZE;
}
int ec_GFp_mont_init_precomp(const EC_GROUP *group, EC_PRECOMP *out,
const EC_RAW_POINT *p) {
// comb[i - 1] stores the ith element of the comb. That is, if i is
// b4 * 2^4 + b3 * 2^3 + ... + b0 * 2^0, it stores k * |p|, where k is
// b4 * 2^(4*stride) + b3 * 2^(3*stride) + ... + b0 * 2^(0*stride). stride
// here is |ec_GFp_mont_comb_stride|. We store at index i - 1 because the 0th
// comb entry is always infinity.
EC_RAW_POINT comb[(1 << EC_MONT_PRECOMP_COMB_SIZE) - 1];
unsigned stride = ec_GFp_mont_comb_stride(group);
// We compute the comb sequentially by the highest set bit. Initially, all
// entries up to 2^0 are filled.
comb[(1 << 0) - 1] = *p;
for (unsigned i = 1; i < EC_MONT_PRECOMP_COMB_SIZE; i++) {
// Compute entry 2^i by doubling the entry for 2^(i-1) |stride| times.
unsigned bit = 1 << i;
ec_GFp_mont_dbl(group, &comb[bit - 1], &comb[bit / 2 - 1]);
for (unsigned j = 1; j < stride; j++) {
ec_GFp_mont_dbl(group, &comb[bit - 1], &comb[bit - 1]);
}
// Compute entries from 2^i + 1 to 2^i + (2^i - 1) by adding entry 2^i to
// a previous entry.
for (unsigned j = 1; j < bit; j++) {
ec_GFp_mont_add(group, &comb[bit + j - 1], &comb[bit - 1], &comb[j - 1]);
}
}
// Store the comb in affine coordinates to shrink the table. (This reduces
// cache pressure and makes the constant-time selects faster.)
OPENSSL_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 void ec_GFp_mont_get_comb_window(const EC_GROUP *group,
EC_RAW_POINT *out,
const EC_PRECOMP *precomp,
const EC_SCALAR *scalar, unsigned i) {
const size_t width = group->order.width;
unsigned stride = ec_GFp_mont_comb_stride(group);
// Select the bits corresponding to the comb shifted up by |i|.
unsigned window = 0;
for (unsigned j = 0; j < EC_MONT_PRECOMP_COMB_SIZE; j++) {
window |= bn_is_bit_set_words(scalar->words, width, j * stride + i)
<< j;
}
// Select precomp->comb[window - 1]. If |window| is zero, |match| will always
// be zero, which will leave |out| at infinity.
OPENSSL_memset(out, 0, sizeof(EC_RAW_POINT));
for (unsigned j = 0; j < OPENSSL_ARRAY_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);
}
BN_ULONG is_infinity = constant_time_is_zero_w(window);
ec_felem_select(group, &out->Z, is_infinity, &out->Z, &group->one);
}
void ec_GFp_mont_mul_precomp(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_PRECOMP *p0, const EC_SCALAR *scalar0,
const EC_PRECOMP *p1, const EC_SCALAR *scalar1,
const EC_PRECOMP *p2, const EC_SCALAR *scalar2) {
unsigned stride = ec_GFp_mont_comb_stride(group);
int r_is_at_infinity = 1;
for (unsigned i = stride - 1; i < stride; i--) {
if (!r_is_at_infinity) {
ec_GFp_mont_dbl(group, r, r);
}
EC_RAW_POINT tmp;
ec_GFp_mont_get_comb_window(group, &tmp, p0, scalar0, i);
if (r_is_at_infinity) {
ec_GFp_simple_point_copy(r, &tmp);
r_is_at_infinity = 0;
} else {
ec_GFp_mont_add(group, r, r, &tmp);
}
if (p1 != NULL) {
ec_GFp_mont_get_comb_window(group, &tmp, p1, scalar1, i);
ec_GFp_mont_add(group, r, r, &tmp);
}
if (p2 != NULL) {
ec_GFp_mont_get_comb_window(group, &tmp, p2, scalar2, i);
ec_GFp_mont_add(group, r, r, &tmp);
}
}
if (r_is_at_infinity) {
ec_GFp_simple_point_set_to_infinity(group, r);
}
}
@@ -240,9 +240,9 @@
// P-384: ...01110011; w = 2, 5, 6, 7 are okay
// P-256: ...01010001; w = 5, 7 are okay
// P-224: ...00111101; w = 3, 4, 5, 6 are okay
void ec_GFp_nistp_recode_scalar_bits(uint8_t *sign, uint8_t *digit,
uint8_t in) {
uint8_t s, d;
void ec_GFp_nistp_recode_scalar_bits(crypto_word_t *sign, crypto_word_t *digit,
crypto_word_t in) {
crypto_word_t s, d;
s = ~((in >> 5) - 1); /* sets all bits to MSB(in), 'in' seen as
* 6-bit value */
@@ -72,6 +72,7 @@
#include <CCryptoBoringSSL_bn.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_thread.h>
#include "internal.h"
@@ -174,24 +175,57 @@ static void lookup_precomp(const EC_GROUP *group, EC_RAW_POINT *out,
// EC_WNAF_TABLE_SIZE is the table size to use for |ec_GFp_mont_mul_public|.
#define EC_WNAF_TABLE_SIZE (1 << (EC_WNAF_WINDOW_BITS - 1))
void ec_GFp_mont_mul_public(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_SCALAR *g_scalar, const EC_RAW_POINT *p,
const EC_SCALAR *p_scalar) {
// EC_WNAF_STACK is the number of points worth of data to stack-allocate and
// avoid a malloc.
#define EC_WNAF_STACK 3
int ec_GFp_mont_mul_public_batch(const EC_GROUP *group, EC_RAW_POINT *r,
const EC_SCALAR *g_scalar,
const EC_RAW_POINT *points,
const EC_SCALAR *scalars, size_t num) {
size_t bits = BN_num_bits(&group->order);
size_t wNAF_len = bits + 1;
int ret = 0;
int8_t wNAF_stack[EC_WNAF_STACK][EC_MAX_BYTES * 8 + 1];
int8_t (*wNAF_alloc)[EC_MAX_BYTES * 8 + 1] = NULL;
int8_t (*wNAF)[EC_MAX_BYTES * 8 + 1];
EC_RAW_POINT precomp_stack[EC_WNAF_STACK][EC_WNAF_TABLE_SIZE];
EC_RAW_POINT (*precomp_alloc)[EC_WNAF_TABLE_SIZE] = NULL;
EC_RAW_POINT (*precomp)[EC_WNAF_TABLE_SIZE];
if (num <= EC_WNAF_STACK) {
wNAF = wNAF_stack;
precomp = precomp_stack;
} else {
if (num >= ((size_t)-1) / sizeof(wNAF_alloc[0]) ||
num >= ((size_t)-1) / sizeof(precomp_alloc[0])) {
OPENSSL_PUT_ERROR(EC, ERR_R_OVERFLOW);
goto err;
}
wNAF_alloc = OPENSSL_malloc(num * sizeof(wNAF_alloc[0]));
precomp_alloc = OPENSSL_malloc(num * sizeof(precomp_alloc[0]));
if (wNAF_alloc == NULL || precomp_alloc == NULL) {
OPENSSL_PUT_ERROR(EC, ERR_R_MALLOC_FAILURE);
goto err;
}
wNAF = wNAF_alloc;
precomp = precomp_alloc;
}
int8_t g_wNAF[EC_MAX_BYTES * 8 + 1];
EC_RAW_POINT g_precomp[EC_WNAF_TABLE_SIZE];
assert(wNAF_len <= OPENSSL_ARRAY_SIZE(g_wNAF));
const EC_RAW_POINT *g = &group->generator->raw;
ec_compute_wNAF(group, g_wNAF, g_scalar, bits, EC_WNAF_WINDOW_BITS);
compute_precomp(group, g_precomp, g, EC_WNAF_TABLE_SIZE);
if (g_scalar != NULL) {
ec_compute_wNAF(group, g_wNAF, g_scalar, bits, EC_WNAF_WINDOW_BITS);
compute_precomp(group, g_precomp, g, EC_WNAF_TABLE_SIZE);
}
int8_t p_wNAF[EC_MAX_BYTES * 8 + 1];
EC_RAW_POINT p_precomp[EC_WNAF_TABLE_SIZE];
assert(wNAF_len <= OPENSSL_ARRAY_SIZE(p_wNAF));
ec_compute_wNAF(group, p_wNAF, p_scalar, bits, EC_WNAF_WINDOW_BITS);
compute_precomp(group, p_precomp, p, EC_WNAF_TABLE_SIZE);
for (size_t i = 0; i < num; i++) {
assert(wNAF_len <= OPENSSL_ARRAY_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);
}
EC_RAW_POINT tmp;
int r_is_at_infinity = 1;
@@ -200,7 +234,7 @@ void ec_GFp_mont_mul_public(const EC_GROUP *group, EC_RAW_POINT *r,
ec_GFp_mont_dbl(group, r, r);
}
if (g_wNAF[k] != 0) {
if (g_scalar != NULL && g_wNAF[k] != 0) {
lookup_precomp(group, &tmp, g_precomp, g_wNAF[k]);
if (r_is_at_infinity) {
ec_GFp_simple_point_copy(r, &tmp);
@@ -210,13 +244,15 @@ void ec_GFp_mont_mul_public(const EC_GROUP *group, EC_RAW_POINT *r,
}
}
if (p_wNAF[k] != 0) {
lookup_precomp(group, &tmp, p_precomp, p_wNAF[k]);
if (r_is_at_infinity) {
ec_GFp_simple_point_copy(r, &tmp);
r_is_at_infinity = 0;
} else {
ec_GFp_mont_add(group, r, r, &tmp);
for (size_t i = 0; i < num; i++) {
if (wNAF[i][k] != 0) {
lookup_precomp(group, &tmp, precomp[i], wNAF[i][k]);
if (r_is_at_infinity) {
ec_GFp_simple_point_copy(r, &tmp);
r_is_at_infinity = 0;
} else {
ec_GFp_mont_add(group, r, r, &tmp);
}
}
}
}
@@ -224,4 +260,11 @@ void ec_GFp_mont_mul_public(const EC_GROUP *group, EC_RAW_POINT *r,
if (r_is_at_infinity) {
ec_GFp_simple_point_set_to_infinity(group, r);
}
ret = 1;
err:
OPENSSL_free(wNAF_alloc);
OPENSSL_free(precomp_alloc);
return ret;
}
@@ -94,8 +94,8 @@ int ECDH_compute_key_fips(uint8_t *out, size_t out_len, const EC_POINT *pub_key,
uint8_t buf[EC_MAX_BYTES];
size_t buflen;
if (!ec_point_mul_scalar(group, &shared_point, &pub_key->raw, priv) ||
!ec_point_get_affine_coordinate_bytes(group, buf, NULL, &buflen,
sizeof(buf), &shared_point)) {
!ec_get_x_coordinate_as_bytes(group, buf, &buflen, sizeof(buf),
&shared_point)) {
OPENSSL_PUT_ERROR(ECDH, ECDH_R_POINT_ARITHMETIC_FAILURE);
return 0;
}
@@ -122,6 +122,14 @@ void ECDSA_SIG_free(ECDSA_SIG *sig) {
OPENSSL_free(sig);
}
const BIGNUM *ECDSA_SIG_get0_r(const ECDSA_SIG *sig) {
return sig->r;
}
const BIGNUM *ECDSA_SIG_get0_s(const ECDSA_SIG *sig) {
return sig->s;
}
void ECDSA_SIG_get0(const ECDSA_SIG *sig, const BIGNUM **out_r,
const BIGNUM **out_s) {
if (out_r != NULL) {
@@ -161,8 +169,11 @@ int ECDSA_do_verify(const uint8_t *digest, size_t digest_len,
return 0;
}
// s_inv_mont = s^-1 in the Montgomery domain. This is
ec_scalar_inv_montgomery_vartime(group, &s_inv_mont, &s);
// s_inv_mont = s^-1 in the Montgomery domain.
if (!ec_scalar_to_montgomery_inv_vartime(group, &s_inv_mont, &s)) {
OPENSSL_PUT_ERROR(ECDSA, ERR_R_INTERNAL_ERROR);
return 0;
}
// u1 = m * s^-1 mod order
// u2 = r * s^-1 mod order
@@ -208,6 +219,10 @@ static int ecdsa_sign_setup(const EC_KEY *eckey, EC_SCALAR *out_kinv_mont,
if (!ec_bignum_to_scalar(group, &k, eckey->fixed_k)) {
goto err;
}
if (ec_scalar_is_zero(group, &k)) {
OPENSSL_PUT_ERROR(ECDSA, ERR_R_INTERNAL_ERROR);
goto err;
}
} else {
// Pass a SHA512 hash of the private key and digest as additional data
// into the RBG. This is a hardening measure against entropy failure.
@@ -225,10 +240,10 @@ static int ecdsa_sign_setup(const EC_KEY *eckey, EC_SCALAR *out_kinv_mont,
}
// Compute k^-1 in the Montgomery domain. This is |ec_scalar_to_montgomery|
// followed by |ec_scalar_inv_montgomery|, but |ec_scalar_inv_montgomery|
// followed by |ec_scalar_inv0_montgomery|, but |ec_scalar_inv0_montgomery|
// followed by |ec_scalar_from_montgomery| is equivalent and slightly more
// efficient.
ec_scalar_inv_montgomery(group, out_kinv_mont, &k);
// efficient. Note k is non-zero, so the inverse must exist.
ec_scalar_inv0_montgomery(group, out_kinv_mont, &k);
ec_scalar_from_montgomery(group, out_kinv_mont, out_kinv_mont);
// Compute r, the x-coordinate of generator * k.
@@ -14,6 +14,8 @@
#if defined(BORINGSSL_PREFIX)
#include <CCryptoBoringSSL_boringssl_prefix_symbols_asm.h>
#endif
#include <CCryptoBoringSSL_arm_arch.h>
.text
.globl _gcm_init_neon
@@ -21,6 +23,7 @@
.align 4
_gcm_init_neon:
AARCH64_VALID_CALL_TARGET
// This function is adapted from gcm_init_v8. xC2 is t3.
ld1 {v17.2d}, [x1] // load H
movi v19.16b, #0xe1
@@ -46,6 +49,7 @@ _gcm_init_neon:
.align 4
_gcm_gmult_neon:
AARCH64_VALID_CALL_TARGET
ld1 {v3.16b}, [x0] // load Xi
ld1 {v5.1d}, [x1], #8 // load twisted H
ld1 {v6.1d}, [x1]
@@ -65,6 +69,7 @@ _gcm_gmult_neon:
.align 4
_gcm_ghash_neon:
AARCH64_VALID_CALL_TARGET
ld1 {v0.16b}, [x0] // load Xi
ld1 {v5.1d}, [x1], #8 // load twisted H
ld1 {v6.1d}, [x1]
@@ -15,6 +15,8 @@
#if defined(BORINGSSL_PREFIX)
#include <CCryptoBoringSSL_boringssl_prefix_symbols_asm.h>
#endif
#include <CCryptoBoringSSL_arm_arch.h>
.text
.globl gcm_init_neon
@@ -22,6 +24,7 @@
.type gcm_init_neon,%function
.align 4
gcm_init_neon:
AARCH64_VALID_CALL_TARGET
// This function is adapted from gcm_init_v8. xC2 is t3.
ld1 {v17.2d}, [x1] // load H
movi v19.16b, #0xe1
@@ -47,6 +50,7 @@ gcm_init_neon:
.type gcm_gmult_neon,%function
.align 4
gcm_gmult_neon:
AARCH64_VALID_CALL_TARGET
ld1 {v3.16b}, [x0] // load Xi
ld1 {v5.1d}, [x1], #8 // load twisted H
ld1 {v6.1d}, [x1]
@@ -66,6 +70,7 @@ gcm_gmult_neon:
.type gcm_ghash_neon,%function
.align 4
gcm_ghash_neon:
AARCH64_VALID_CALL_TARGET
ld1 {v0.16b}, [x0] // load Xi
ld1 {v5.1d}, [x1], #8 // load twisted H
ld1 {v6.1d}, [x1]
@@ -1121,8 +1121,6 @@ gcm_ghash_avx:
.byte 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0xc2
.L7_mask:
.long 7,0,7,0
.L7_mask_poly:
.long 7,0,450,0
.align 64
.byte 71,72,65,83,72,32,102,111,114,32,120,56,54,95,54,52,44,32,67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97,112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103,62,0
@@ -1120,8 +1120,6 @@ L$0x1c2_polynomial:
.byte 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0xc2
L$7_mask:
.long 7,0,7,0
L$7_mask_poly:
.long 7,0,450,0
.p2align 6
.byte 71,72,65,83,72,32,102,111,114,32,120,56,54,95,54,52,44,32,67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97,112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103,62,0
@@ -23,6 +23,7 @@
.align 4
_gcm_init_v8:
AARCH64_VALID_CALL_TARGET
ld1 {v17.2d},[x1] //load input H
movi v19.16b,#0xe1
shl v19.2d,v19.2d,#57 //0xc2.0
@@ -74,6 +75,7 @@ _gcm_init_v8:
.align 4
_gcm_gmult_v8:
AARCH64_VALID_CALL_TARGET
ld1 {v17.2d},[x0] //load Xi
movi v19.16b,#0xe1
ld1 {v20.2d,v21.2d},[x1] //load twisted H, ...
@@ -116,6 +118,7 @@ _gcm_gmult_v8:
.align 4
_gcm_ghash_v8:
AARCH64_VALID_CALL_TARGET
ld1 {v0.2d},[x0] //load [rotated] Xi
//"[rotated]" means that
//loaded value would have
@@ -24,6 +24,7 @@
.type gcm_init_v8,%function
.align 4
gcm_init_v8:
AARCH64_VALID_CALL_TARGET
ld1 {v17.2d},[x1] //load input H
movi v19.16b,#0xe1
shl v19.2d,v19.2d,#57 //0xc2.0
@@ -75,6 +76,7 @@ gcm_init_v8:
.type gcm_gmult_v8,%function
.align 4
gcm_gmult_v8:
AARCH64_VALID_CALL_TARGET
ld1 {v17.2d},[x0] //load Xi
movi v19.16b,#0xe1
ld1 {v20.2d,v21.2d},[x1] //load twisted H, ...
@@ -117,6 +119,7 @@ gcm_gmult_v8:
.type gcm_ghash_v8,%function
.align 4
gcm_ghash_v8:
AARCH64_VALID_CALL_TARGET
ld1 {v0.2d},[x0] //load [rotated] Xi
//"[rotated]" means that
//loaded value would have
@@ -0,0 +1,137 @@
/* Copyright (c) 2020, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#if !defined(_GNU_SOURCE)
#define _GNU_SOURCE // needed for madvise() and MAP_ANONYMOUS on Linux.
#endif
#include <CCryptoBoringSSL_base.h>
#include "fork_detect.h"
#if defined(OPENSSL_LINUX)
#include <sys/mman.h>
#include <unistd.h>
#include <stdlib.h>
#include <CCryptoBoringSSL_type_check.h>
#include "../delocate.h"
#include "../../internal.h"
#if defined(MADV_WIPEONFORK)
OPENSSL_STATIC_ASSERT(MADV_WIPEONFORK == 18, "MADV_WIPEONFORK is not 18");
#else
#define MADV_WIPEONFORK 18
#endif
DEFINE_STATIC_ONCE(g_fork_detect_once);
DEFINE_STATIC_MUTEX(g_fork_detect_lock);
DEFINE_BSS_GET(volatile char *, g_fork_detect_addr);
DEFINE_BSS_GET(uint64_t, g_fork_generation);
DEFINE_BSS_GET(int, g_ignore_madv_wipeonfork);
static void init_fork_detect(void) {
if (*g_ignore_madv_wipeonfork_bss_get()) {
return;
}
long page_size = sysconf(_SC_PAGESIZE);
if (page_size <= 0) {
return;
}
void *addr = mmap(NULL, (size_t)page_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (addr == MAP_FAILED) {
return;
}
// Some versions of qemu (up to at least 5.0.0-rc4, see linux-user/syscall.c)
// ignore |madvise| calls and just return zero (i.e. success). But we need to
// know whether MADV_WIPEONFORK actually took effect. Therefore try an invalid
// call to check that the implementation of |madvise| is actually rejecting
// unknown |advice| values.
if (madvise(addr, (size_t)page_size, -1) == 0 ||
madvise(addr, (size_t)page_size, MADV_WIPEONFORK) != 0) {
munmap(addr, (size_t)page_size);
return;
}
*((volatile char *) addr) = 1;
*g_fork_detect_addr_bss_get() = addr;
*g_fork_generation_bss_get() = 1;
}
uint64_t CRYPTO_get_fork_generation(void) {
// In a single-threaded process, there are obviously no races because there's
// only a single mutator in the address space.
//
// In a multi-threaded environment, |CRYPTO_once| ensures that the flag byte
// is initialised atomically, even if multiple threads enter this function
// concurrently.
//
// In the limit, the kernel may clear WIPEONFORK pages while a multi-threaded
// process is running. (For example, because a VM was cloned.) Therefore a
// lock is used below to synchronise the potentially multiple threads that may
// concurrently observe the cleared flag.
CRYPTO_once(g_fork_detect_once_bss_get(), init_fork_detect);
// This pointer is |volatile| because the value pointed to may be changed by
// external forces (i.e. the kernel wiping the page) thus the compiler must
// not assume that it has exclusive access to it.
volatile char *const flag_ptr = *g_fork_detect_addr_bss_get();
if (flag_ptr == NULL) {
// Our kernel is too old to support |MADV_WIPEONFORK|.
return 0;
}
struct CRYPTO_STATIC_MUTEX *const lock = g_fork_detect_lock_bss_get();
uint64_t *const generation_ptr = g_fork_generation_bss_get();
CRYPTO_STATIC_MUTEX_lock_read(lock);
uint64_t current_generation = *generation_ptr;
if (*flag_ptr) {
CRYPTO_STATIC_MUTEX_unlock_read(lock);
return current_generation;
}
CRYPTO_STATIC_MUTEX_unlock_read(lock);
CRYPTO_STATIC_MUTEX_lock_write(lock);
current_generation = *generation_ptr;
if (*flag_ptr == 0) {
// A fork has occurred.
*flag_ptr = 1;
current_generation++;
if (current_generation == 0) {
current_generation = 1;
}
*generation_ptr = current_generation;
}
CRYPTO_STATIC_MUTEX_unlock_write(lock);
return current_generation;
}
void CRYPTO_fork_detect_ignore_madv_wipeonfork_for_testing(void) {
*g_ignore_madv_wipeonfork_bss_get() = 1;
}
#else // !OPENSSL_LINUX
uint64_t CRYPTO_get_fork_generation(void) { return 0; }
#endif // OPENSSL_LINUX
@@ -0,0 +1,49 @@
/* Copyright (c) 2020, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#ifndef OPENSSL_HEADER_CRYPTO_FORK_DETECT_H
#define OPENSSL_HEADER_CRYPTO_FORK_DETECT_H
#include <CCryptoBoringSSL_base.h>
#if defined(__cplusplus)
extern "C" {
#endif
// crypto_get_fork_generation returns the fork generation number for the current
// process, or zero if not supported on the platform. The fork generation number
// is a non-zero, strictly-monotonic counter with the property that, if queried
// in an address space and then again in a subsequently forked copy, the forked
// address space will observe a greater value.
//
// This function may be used to clear cached values across a fork. When
// initializing a cache, record the fork generation. Before using the cache,
// check if the fork generation has changed. If so, drop the cache and update
// the save fork generation. Note this logic transparently handles platforms
// which always return zero.
//
// This is not reliably supported on all platforms which implement |fork|, so it
// should only be used as a hardening measure.
OPENSSL_EXPORT uint64_t CRYPTO_get_fork_generation(void);
// CRYPTO_fork_detect_ignore_madv_wipeonfork_for_testing is an internal detail
// used for testing purposes.
OPENSSL_EXPORT void CRYPTO_fork_detect_ignore_madv_wipeonfork_for_testing(void);
#if defined(__cplusplus)
} // extern C
#endif
#endif // OPENSSL_HEADER_CRYPTO_FORK_DETECT_H
@@ -0,0 +1,64 @@
/* Copyright (c) 2020, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#ifndef OPENSSL_HEADER_CRYPTO_RAND_GETRANDOM_FILLIN_H
#define OPENSSL_HEADER_CRYPTO_RAND_GETRANDOM_FILLIN_H
#include <CCryptoBoringSSL_base.h>
#if defined(OPENSSL_LINUX)
#include <sys/syscall.h>
#if defined(OPENSSL_X86_64)
#define EXPECTED_NR_getrandom 318
#elif defined(OPENSSL_X86)
#define EXPECTED_NR_getrandom 355
#elif defined(OPENSSL_AARCH64)
#define EXPECTED_NR_getrandom 278
#elif defined(OPENSSL_ARM)
#define EXPECTED_NR_getrandom 384
#elif defined(OPENSSL_PPC64LE)
#define EXPECTED_NR_getrandom 359
#endif
#if defined(EXPECTED_NR_getrandom)
#define USE_NR_getrandom
#if defined(__NR_getrandom)
#if __NR_getrandom != EXPECTED_NR_getrandom
#error "system call number for getrandom is not the expected value"
#endif
#else // __NR_getrandom
#define __NR_getrandom EXPECTED_NR_getrandom
#endif // __NR_getrandom
#endif // EXPECTED_NR_getrandom
#if !defined(GRND_NONBLOCK)
#define GRND_NONBLOCK 1
#endif
#if !defined(GRND_RANDOM)
#define GRND_RANDOM 2
#endif
#endif // OPENSSL_LINUX
#endif // OPENSSL_HEADER_CRYPTO_RAND_GETRANDOM_FILLIN_H
@@ -40,17 +40,33 @@ void RAND_bytes_with_additional_data(uint8_t *out, size_t out_len,
// system.
void CRYPTO_sysrand(uint8_t *buf, size_t len);
#if defined(OPENSSL_URANDOM) || defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE)
#if defined(OPENSSL_URANDOM)
// CRYPTO_init_sysrand initializes long-lived resources needed to draw entropy
// from the operating system.
void CRYPTO_init_sysrand(void);
// CRYPTO_sysrand_for_seed fills |len| bytes at |buf| with entropy from the
// operating system. It may draw from the |GRND_RANDOM| pool on Android,
// depending on the vendor's configuration.
void CRYPTO_sysrand_for_seed(uint8_t *buf, size_t len);
// CRYPTO_sysrand_if_available fills |len| bytes at |buf| with entropy from the
// operating system, if the entropy pool is initialized. If it is uninitialized,
// it will not block and will instead fill |buf| with all zeros or early
// /dev/urandom output.
void CRYPTO_sysrand_if_available(uint8_t *buf, size_t len);
// operating system, or early /dev/urandom data, and returns 1, _if_ the entropy
// pool is initialized or if getrandom() is not available and not in FIPS mode.
// Otherwise it will not block and will instead fill |buf| with all zeros and
// return 0.
int CRYPTO_sysrand_if_available(uint8_t *buf, size_t len);
#else
OPENSSL_INLINE void CRYPTO_init_sysrand(void) {}
OPENSSL_INLINE void CRYPTO_sysrand_for_seed(uint8_t *buf, size_t len) {
CRYPTO_sysrand(buf, len);
}
OPENSSL_INLINE int CRYPTO_sysrand_if_available(uint8_t *buf, size_t len) {
CRYPTO_sysrand(buf, len);
return 1;
}
#endif
// rand_fork_unsafe_buffering_enabled returns whether fork-unsafe buffering has
@@ -105,10 +121,19 @@ OPENSSL_EXPORT void CTR_DRBG_clear(CTR_DRBG_STATE *drbg);
#if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM)
OPENSSL_INLINE int have_rdrand(void) {
return (OPENSSL_ia32cap_get()[1] & (1u << 30)) != 0;
}
// have_fast_rdrand returns true if RDRAND is supported and it's reasonably
// fast. Concretely the latter is defined by whether the chip is Intel (fast) or
// not (assumed slow).
OPENSSL_INLINE int have_fast_rdrand(void) {
const uint32_t *const ia32cap = OPENSSL_ia32cap_get();
return (ia32cap[1] & (1u << 30)) && (ia32cap[0] & (1u << 30));
}
// CRYPTO_rdrand writes eight bytes of random data from the hardware RNG to
// |out|. It returns one on success or zero on hardware failure.
int CRYPTO_rdrand(uint8_t out[8]);
@@ -117,6 +142,17 @@ int CRYPTO_rdrand(uint8_t out[8]);
// the hardware RNG. The |len| argument must be a multiple of eight. It returns
// one on success and zero on hardware failure.
int CRYPTO_rdrand_multiple8_buf(uint8_t *buf, size_t len);
#else // OPENSSL_X86_64 && !OPENSSL_NO_ASM
OPENSSL_INLINE int have_rdrand(void) {
return 0;
}
OPENSSL_INLINE int have_fast_rdrand(void) {
return 0;
}
#endif // OPENSSL_X86_64 && !OPENSSL_NO_ASM
@@ -27,6 +27,7 @@
#include <CCryptoBoringSSL_mem.h>
#include "internal.h"
#include "fork_detect.h"
#include "../../internal.h"
#include "../delocate.h"
@@ -57,6 +58,7 @@ static const unsigned kReseedInterval = 4096;
// rand_thread_state contains the per-thread state for the RNG.
struct rand_thread_state {
CTR_DRBG_STATE drbg;
uint64_t fork_generation;
// calls is the number of generate calls made on |drbg| since it was last
// (re)seeded. This is bound by |kReseedInterval|.
unsigned calls;
@@ -125,11 +127,9 @@ static void rand_thread_state_free(void *state_in) {
#if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM) && \
!defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE)
static int hwrand(uint8_t *buf, const size_t len) {
if (!have_rdrand()) {
return 0;
}
// rdrand should only be called if either |have_rdrand| or |have_fast_rdrand|
// returned true.
static int rdrand(uint8_t *buf, const size_t len) {
const size_t len_multiple8 = len & ~7;
if (!CRYPTO_rdrand_multiple8_buf(buf, len_multiple8)) {
return 0;
@@ -157,7 +157,7 @@ static int hwrand(uint8_t *buf, const size_t len) {
#else
static int hwrand(uint8_t *buf, size_t len) {
static int rdrand(uint8_t *buf, size_t len) {
return 0;
}
@@ -168,7 +168,8 @@ static int hwrand(uint8_t *buf, size_t len) {
static void rand_get_seed(struct rand_thread_state *state,
uint8_t seed[CTR_DRBG_ENTROPY_LEN]) {
if (!state->last_block_valid) {
if (!hwrand(state->last_block, sizeof(state->last_block))) {
if (!have_rdrand() ||
!rdrand(state->last_block, sizeof(state->last_block))) {
CRYPTO_sysrand_for_seed(state->last_block, sizeof(state->last_block));
}
state->last_block_valid = 1;
@@ -179,8 +180,8 @@ static void rand_get_seed(struct rand_thread_state *state,
#define FIPS_OVERREAD 10
uint8_t entropy[CTR_DRBG_ENTROPY_LEN * FIPS_OVERREAD];
int used_hwrand = hwrand(entropy, sizeof(entropy));
if (!used_hwrand) {
int used_rdrand = have_rdrand() && rdrand(entropy, sizeof(entropy));
if (!used_rdrand) {
CRYPTO_sysrand_for_seed(entropy, sizeof(entropy));
}
@@ -215,7 +216,7 @@ static void rand_get_seed(struct rand_thread_state *state,
#if defined(OPENSSL_URANDOM)
// If we used RDRAND, also opportunistically read from the system. This avoids
// solely relying on the hardware once the entropy pool has been initialized.
if (used_hwrand) {
if (used_rdrand) {
CRYPTO_sysrand_if_available(entropy, CTR_DRBG_ENTROPY_LEN);
for (size_t i = 0; i < CTR_DRBG_ENTROPY_LEN; i++) {
seed[i] ^= entropy[i];
@@ -241,20 +242,31 @@ void RAND_bytes_with_additional_data(uint8_t *out, size_t out_len,
return;
}
const uint64_t fork_generation = CRYPTO_get_fork_generation();
// Additional data is mixed into every CTR-DRBG call to protect, as best we
// can, against forks & VM clones. We do not over-read this information and
// don't reseed with it so, from the point of view of FIPS, this doesn't
// provide “prediction resistance”. But, in practice, it does.
uint8_t additional_data[32];
if (!hwrand(additional_data, sizeof(additional_data))) {
// Intel chips have fast RDRAND instructions while, in other cases, RDRAND can
// be _slower_ than a system call.
if (!have_fast_rdrand() ||
!rdrand(additional_data, sizeof(additional_data))) {
// Without a hardware RNG to save us from address-space duplication, the OS
// entropy is used. This can be expensive (one read per |RAND_bytes| call)
// and so can be disabled by applications that we have ensured don't fork
// and aren't at risk of VM cloning.
if (!rand_fork_unsafe_buffering_enabled()) {
CRYPTO_sysrand(additional_data, sizeof(additional_data));
} else {
// and so is disabled when we have fork detection, or if the application has
// promised not to fork.
if (fork_generation != 0 || rand_fork_unsafe_buffering_enabled()) {
OPENSSL_memset(additional_data, 0, sizeof(additional_data));
} else if (!have_rdrand()) {
// No alternative so block for OS entropy.
CRYPTO_sysrand(additional_data, sizeof(additional_data));
} else if (!CRYPTO_sysrand_if_available(additional_data,
sizeof(additional_data)) &&
!rdrand(additional_data, sizeof(additional_data))) {
// RDRAND failed: block for OS entropy.
CRYPTO_sysrand(additional_data, sizeof(additional_data));
}
}
@@ -283,6 +295,7 @@ void RAND_bytes_with_additional_data(uint8_t *out, size_t out_len,
abort();
}
state->calls = 0;
state->fork_generation = fork_generation;
#if defined(BORINGSSL_FIPS)
if (state != &stack_state) {
@@ -299,7 +312,8 @@ void RAND_bytes_with_additional_data(uint8_t *out, size_t out_len,
#endif
}
if (state->calls >= kReseedInterval) {
if (state->calls >= kReseedInterval ||
state->fork_generation != fork_generation) {
uint8_t seed[CTR_DRBG_ENTROPY_LEN];
rand_get_seed(state, seed);
#if defined(BORINGSSL_FIPS)
@@ -317,6 +331,7 @@ void RAND_bytes_with_additional_data(uint8_t *out, size_t out_len,
abort();
}
state->calls = 0;
state->fork_generation = fork_generation;
} else {
#if defined(BORINGSSL_FIPS)
CRYPTO_STATIC_MUTEX_lock_read(thread_states_list_lock_bss_get());
@@ -65,38 +65,12 @@
#include <CCryptoBoringSSL_thread.h>
#include <CCryptoBoringSSL_mem.h>
#include "getrandom_fillin.h"
#include "../delocate.h"
#include "../../internal.h"
#if defined(OPENSSL_LINUX)
#if defined(OPENSSL_X86_64)
#define EXPECTED_NR_getrandom 318
#elif defined(OPENSSL_X86)
#define EXPECTED_NR_getrandom 355
#elif defined(OPENSSL_AARCH64)
#define EXPECTED_NR_getrandom 278
#elif defined(OPENSSL_ARM)
#define EXPECTED_NR_getrandom 384
#elif defined(OPENSSL_PPC64LE)
#define EXPECTED_NR_getrandom 359
#endif
#if defined(EXPECTED_NR_getrandom)
#define USE_NR_getrandom
#if defined(__NR_getrandom)
#if __NR_getrandom != EXPECTED_NR_getrandom
#error "system call number for getrandom is not the expected value"
#endif
#else // __NR_getrandom
#define __NR_getrandom EXPECTED_NR_getrandom
#endif // __NR_getrandom
#if defined(USE_NR_getrandom)
#if defined(OPENSSL_MSAN)
void __msan_unpoison(void *, size_t);
@@ -119,28 +93,12 @@ static ssize_t boringssl_getrandom(void *buf, size_t buf_len, unsigned flags) {
return ret;
}
#endif // EXPECTED_NR_getrandom
#endif // USE_NR_getrandom
#if !defined(GRND_NONBLOCK)
#define GRND_NONBLOCK 1
#endif
#if !defined(GRND_RANDOM)
#define GRND_RANDOM 2
#endif
#endif // OPENSSL_LINUX
// rand_lock is used to protect the |*_requested| variables.
DEFINE_STATIC_MUTEX(rand_lock)
// The following constants are magic values of |urandom_fd|.
static const int kUnset = 0;
// kHaveGetrandom in |urandom_fd| signals that |getrandom| or |getentropy| is
// available and should be used instead.
static const int kHaveGetrandom = -3;
// urandom_fd_requested is set by |RAND_set_urandom_fd|. It's protected by
// |rand_lock|.
DEFINE_BSS_GET(int, urandom_fd_requested)
// urandom_fd is a file descriptor to /dev/urandom. It's protected by |once|.
DEFINE_BSS_GET(int, urandom_fd)
@@ -179,14 +137,9 @@ static void maybe_set_extra_getrandom_flags(void) {
DEFINE_STATIC_ONCE(rand_once)
// init_once initializes the state of this module to values previously
// requested. This is the only function that modifies |urandom_fd| and
// |urandom_buffering|, whose values may be read safely after calling the
// once.
// requested. This is the only function that modifies |urandom_fd|, which may be
// read safely after calling the once.
static void init_once(void) {
CRYPTO_STATIC_MUTEX_lock_read(rand_lock_bss_get());
int fd = *urandom_fd_requested_bss_get();
CRYPTO_STATIC_MUTEX_unlock_read(rand_lock_bss_get());
#if defined(USE_NR_getrandom)
int have_getrandom;
uint8_t dummy;
@@ -229,31 +182,16 @@ static void init_once(void) {
abort();
#endif
if (fd == kUnset) {
do {
fd = open("/dev/urandom", O_RDONLY);
} while (fd == -1 && errno == EINTR);
}
int fd;
do {
fd = open("/dev/urandom", O_RDONLY);
} while (fd == -1 && errno == EINTR);
if (fd < 0) {
perror("failed to open /dev/urandom");
abort();
}
assert(kUnset == 0);
if (fd == kUnset) {
// Because we want to keep |urandom_fd| in the BSS, we have to initialise
// it to zero. But zero is a valid file descriptor too. Thus if open
// returns zero for /dev/urandom, we dup it to get a non-zero number.
fd = dup(fd);
close(kUnset);
if (fd <= 0) {
perror("failed to dup /dev/urandom fd");
abort();
}
}
int flags = fcntl(fd, F_GETFD);
if (flags == -1) {
// Native Client doesn't implement |fcntl|.
@@ -342,40 +280,6 @@ static void wait_for_entropy(void) {
#endif // BORINGSSL_FIPS
}
void RAND_set_urandom_fd(int fd) {
fd = dup(fd);
if (fd < 0) {
perror("failed to dup supplied urandom fd");
abort();
}
assert(kUnset == 0);
if (fd == kUnset) {
// Because we want to keep |urandom_fd| in the BSS, we have to initialise
// it to zero. But zero is a valid file descriptor too. Thus if dup
// returned zero we dup it again to get a non-zero number.
fd = dup(fd);
close(kUnset);
if (fd <= 0) {
perror("failed to dup supplied urandom fd");
abort();
}
}
CRYPTO_STATIC_MUTEX_lock_write(rand_lock_bss_get());
*urandom_fd_requested_bss_get() = fd;
CRYPTO_STATIC_MUTEX_unlock_write(rand_lock_bss_get());
CRYPTO_once(rand_once_bss_get(), init_once);
if (*urandom_fd_bss_get() == kHaveGetrandom) {
close(fd);
} else if (*urandom_fd_bss_get() != fd) {
fprintf(stderr, "RAND_set_urandom_fd called after initialisation.\n");
abort();
}
}
// fill_with_entropy writes |len| bytes of entropy into |out|. It returns one
// on success and zero on error. If |block| is one, this function will block
// until the entropy pool is initialized. Otherwise, this function may fail,
@@ -397,7 +301,7 @@ static int fill_with_entropy(uint8_t *out, size_t len, int block, int seed) {
}
#endif
CRYPTO_once(rand_once_bss_get(), init_once);
CRYPTO_init_sysrand();
if (block) {
CRYPTO_once(wait_for_entropy_once_bss_get(), wait_for_entropy);
}
@@ -452,6 +356,10 @@ void CRYPTO_sysrand(uint8_t *out, size_t requested) {
}
}
void CRYPTO_init_sysrand(void) {
CRYPTO_once(rand_once_bss_get(), init_once);
}
#if defined(BORINGSSL_FIPS)
void CRYPTO_sysrand_for_seed(uint8_t *out, size_t requested) {
if (!fill_with_entropy(out, requested, /*block=*/1, /*seed=*/1)) {
@@ -466,16 +374,18 @@ void CRYPTO_sysrand_for_seed(uint8_t *out, size_t requested) {
#endif
}
void CRYPTO_sysrand_if_available(uint8_t *out, size_t requested) {
// Return all zeros if |fill_with_entropy| fails.
OPENSSL_memset(out, 0, requested);
#endif // BORINGSSL_FIPS
if (!fill_with_entropy(out, requested, /*block=*/0, /*seed=*/0) &&
errno != EAGAIN) {
int CRYPTO_sysrand_if_available(uint8_t *out, size_t requested) {
if (fill_with_entropy(out, requested, /*block=*/0, /*seed=*/0)) {
return 1;
} else if (errno == EAGAIN) {
OPENSSL_memset(out, 0, requested);
return 0;
} else {
perror("opportunistic entropy fill failed");
abort();
}
}
#endif // BORINGSSL_FIPS
#endif // OPENSSL_URANDOM
@@ -167,6 +167,10 @@ void BN_BLINDING_free(BN_BLINDING *r) {
OPENSSL_free(r);
}
void BN_BLINDING_invalidate(BN_BLINDING *b) {
b->counter = BN_BLINDING_COUNTER - 1;
}
static int bn_blinding_update(BN_BLINDING *b, const BIGNUM *e,
const BN_MONT_CTX *mont, BN_CTX *ctx) {
if (++b->counter == BN_BLINDING_COUNTER) {
@@ -83,6 +83,7 @@ int rsa_default_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in,
BN_BLINDING *BN_BLINDING_new(void);
void BN_BLINDING_free(BN_BLINDING *b);
void BN_BLINDING_invalidate(BN_BLINDING *b);
int BN_BLINDING_convert(BIGNUM *n, BN_BLINDING *b, const BIGNUM *e,
const BN_MONT_CTX *mont_ctx, BN_CTX *ctx);
int BN_BLINDING_invert(BIGNUM *n, const BN_BLINDING *b, BN_MONT_CTX *mont_ctx,
@@ -107,6 +108,10 @@ int RSA_padding_check_PKCS1_OAEP_mgf1(uint8_t *out, size_t *out_len,
int RSA_padding_add_none(uint8_t *to, size_t to_len, const uint8_t *from,
size_t from_len);
// rsa_check_public_key checks that |rsa|'s public modulus and exponent are
// within DoS bounds.
int rsa_check_public_key(const RSA *rsa);
// RSA_private_transform calls either the method-specific |private_transform|
// function (if given) or the generic one. See the comment for
// |private_transform| in |rsa_meth_st|.
@@ -167,6 +167,22 @@ int RSA_up_ref(RSA *rsa) {
unsigned RSA_bits(const RSA *rsa) { return BN_num_bits(rsa->n); }
const BIGNUM *RSA_get0_n(const RSA *rsa) { return rsa->n; }
const BIGNUM *RSA_get0_e(const RSA *rsa) { return rsa->e; }
const BIGNUM *RSA_get0_d(const RSA *rsa) { return rsa->d; }
const BIGNUM *RSA_get0_p(const RSA *rsa) { return rsa->p; }
const BIGNUM *RSA_get0_q(const RSA *rsa) { return rsa->q; }
const BIGNUM *RSA_get0_dmp1(const RSA *rsa) { return rsa->dmp1; }
const BIGNUM *RSA_get0_dmq1(const RSA *rsa) { return rsa->dmq1; }
const BIGNUM *RSA_get0_iqmp(const RSA *rsa) { return rsa->iqmp; }
void RSA_get0_key(const RSA *rsa, const BIGNUM **out_n, const BIGNUM **out_e,
const BIGNUM **out_d) {
if (out_n != NULL) {
@@ -639,7 +655,15 @@ err:
}
static int check_mod_inverse(int *out_ok, const BIGNUM *a, const BIGNUM *ainv,
const BIGNUM *m, int check_reduced, BN_CTX *ctx) {
const BIGNUM *m, BN_CTX *ctx) {
if (BN_is_negative(ainv) || BN_cmp(ainv, m) >= 0) {
*out_ok = 0;
return 1;
}
// Note |bn_mul_consttime| and |bn_div_consttime| do not scale linearly, but
// checking |ainv| is in range bounds the running time, assuming |m|'s bounds
// were checked by the caller.
BN_CTX_start(ctx);
BIGNUM *tmp = BN_CTX_get(ctx);
int ret = tmp != NULL &&
@@ -647,84 +671,97 @@ static int check_mod_inverse(int *out_ok, const BIGNUM *a, const BIGNUM *ainv,
bn_div_consttime(NULL, tmp, tmp, m, ctx);
if (ret) {
*out_ok = BN_is_one(tmp);
if (check_reduced && (BN_is_negative(ainv) || BN_cmp(ainv, m) >= 0)) {
*out_ok = 0;
}
}
BN_CTX_end(ctx);
return ret;
}
int RSA_check_key(const RSA *key) {
BIGNUM n, pm1, qm1, lcm, dmp1, dmq1, iqmp_times_q;
BN_CTX *ctx;
int ok = 0, has_crt_values;
// TODO(davidben): RSA key initialization is spread across
// |rsa_check_public_key|, |RSA_check_key|, |freeze_private_key|, and
// |BN_MONT_CTX_set_locked| as a result of API issues. See
// https://crbug.com/boringssl/316. As a result, we inconsistently check RSA
// invariants. We should fix this and integrate that logic.
if (RSA_is_opaque(key)) {
// Opaque keys can't be checked.
return 1;
}
if (!rsa_check_public_key(key)) {
return 0;
}
if ((key->p != NULL) != (key->q != NULL)) {
OPENSSL_PUT_ERROR(RSA, RSA_R_ONLY_ONE_OF_P_Q_GIVEN);
return 0;
}
if (!key->n || !key->e) {
OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
// |key->d| must be bounded by |key->n|. This ensures bounds on |RSA_bits|
// translate to bounds on the running time of private key operations.
if (key->d != NULL &&
(BN_is_negative(key->d) || BN_cmp(key->d, key->n) >= 0)) {
OPENSSL_PUT_ERROR(RSA, RSA_R_D_OUT_OF_RANGE);
return 0;
}
if (!key->d || !key->p) {
if (key->d == NULL || key->p == NULL) {
// For a public key, or without p and q, there's nothing that can be
// checked.
return 1;
}
ctx = BN_CTX_new();
BN_CTX *ctx = BN_CTX_new();
if (ctx == NULL) {
OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
return 0;
}
BN_init(&n);
BIGNUM tmp, de, pm1, qm1, dmp1, dmq1;
int ok = 0;
BN_init(&tmp);
BN_init(&de);
BN_init(&pm1);
BN_init(&qm1);
BN_init(&lcm);
BN_init(&dmp1);
BN_init(&dmq1);
BN_init(&iqmp_times_q);
int d_ok;
if (!bn_mul_consttime(&n, key->p, key->q, ctx) ||
// lcm = lcm(p, q)
!bn_usub_consttime(&pm1, key->p, BN_value_one()) ||
!bn_usub_consttime(&qm1, key->q, BN_value_one()) ||
!bn_lcm_consttime(&lcm, &pm1, &qm1, ctx) ||
// Other implementations use the Euler totient rather than the Carmichael
// totient, so allow unreduced |key->d|.
!check_mod_inverse(&d_ok, key->e, key->d, &lcm,
0 /* don't require reduced */, ctx)) {
// Check that p * q == n. Before we multiply, we check that p and q are in
// bounds, to avoid a DoS vector in |bn_mul_consttime| below. Note that
// n was bound by |rsa_check_public_key|.
if (BN_is_negative(key->p) || BN_cmp(key->p, key->n) >= 0 ||
BN_is_negative(key->q) || BN_cmp(key->q, key->n) >= 0) {
OPENSSL_PUT_ERROR(RSA, RSA_R_N_NOT_EQUAL_P_Q);
goto out;
}
if (!bn_mul_consttime(&tmp, key->p, key->q, ctx)) {
OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
goto out;
}
if (BN_cmp(&n, key->n) != 0) {
if (BN_cmp(&tmp, key->n) != 0) {
OPENSSL_PUT_ERROR(RSA, RSA_R_N_NOT_EQUAL_P_Q);
goto out;
}
if (!d_ok) {
// d must be an inverse of e mod the Carmichael totient, lcm(p-1, q-1), but it
// may be unreduced because other implementations use the Euler totient. We
// simply check that d * e is one mod p-1 and mod q-1. Note d and e were bound
// by earlier checks in this function.
if (!bn_usub_consttime(&pm1, key->p, BN_value_one()) ||
!bn_usub_consttime(&qm1, key->q, BN_value_one()) ||
!bn_mul_consttime(&de, key->d, key->e, ctx) ||
!bn_div_consttime(NULL, &tmp, &de, &pm1, ctx) ||
!bn_div_consttime(NULL, &de, &de, &qm1, ctx)) {
OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
goto out;
}
if (!BN_is_one(&tmp) || !BN_is_one(&de)) {
OPENSSL_PUT_ERROR(RSA, RSA_R_D_E_NOT_CONGRUENT_TO_1);
goto out;
}
if (BN_is_negative(key->d) || BN_cmp(key->d, key->n) >= 0) {
OPENSSL_PUT_ERROR(RSA, RSA_R_D_OUT_OF_RANGE);
goto out;
}
has_crt_values = key->dmp1 != NULL;
int has_crt_values = key->dmp1 != NULL;
if (has_crt_values != (key->dmq1 != NULL) ||
has_crt_values != (key->iqmp != NULL)) {
OPENSSL_PUT_ERROR(RSA, RSA_R_INCONSISTENT_SET_OF_CRT_VALUES);
@@ -733,12 +770,9 @@ int RSA_check_key(const RSA *key) {
if (has_crt_values) {
int dmp1_ok, dmq1_ok, iqmp_ok;
if (!check_mod_inverse(&dmp1_ok, key->e, key->dmp1, &pm1,
1 /* check reduced */, ctx) ||
!check_mod_inverse(&dmq1_ok, key->e, key->dmq1, &qm1,
1 /* check reduced */, ctx) ||
!check_mod_inverse(&iqmp_ok, key->q, key->iqmp, key->p,
1 /* check reduced */, ctx)) {
if (!check_mod_inverse(&dmp1_ok, key->e, key->dmp1, &pm1, ctx) ||
!check_mod_inverse(&dmq1_ok, key->e, key->dmq1, &qm1, ctx) ||
!check_mod_inverse(&iqmp_ok, key->q, key->iqmp, key->p, ctx)) {
OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
goto out;
}
@@ -752,13 +786,12 @@ int RSA_check_key(const RSA *key) {
ok = 1;
out:
BN_free(&n);
BN_free(&tmp);
BN_free(&de);
BN_free(&pm1);
BN_free(&qm1);
BN_free(&lcm);
BN_free(&dmp1);
BN_free(&dmq1);
BN_free(&iqmp_times_q);
BN_CTX_free(ctx);
return ok;
@@ -70,9 +70,15 @@
#include "../bn/internal.h"
#include "../../internal.h"
#include "../delocate.h"
#include "../rand/fork_detect.h"
static int check_modulus_and_exponent_sizes(const RSA *rsa) {
int rsa_check_public_key(const RSA *rsa) {
if (rsa->n == NULL || rsa->e == NULL) {
OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
return 0;
}
unsigned rsa_bits = BN_num_bits(rsa->n);
if (rsa_bits > 16 * 1024) {
@@ -252,8 +258,7 @@ size_t rsa_default_size(const RSA *rsa) {
int RSA_encrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
const uint8_t *in, size_t in_len, int padding) {
if (rsa->n == NULL || rsa->e == NULL) {
OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
if (!rsa_check_public_key(rsa)) {
return 0;
}
@@ -268,10 +273,6 @@ int RSA_encrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
return 0;
}
if (!check_modulus_and_exponent_sizes(rsa)) {
return 0;
}
ctx = BN_CTX_new();
if (ctx == NULL) {
goto err;
@@ -345,7 +346,7 @@ err:
// MAX_BLINDINGS_PER_RSA defines the maximum number of cached BN_BLINDINGs per
// RSA*. Then this limit is exceeded, BN_BLINDING objects will be created and
// destroyed as needed.
#if defined(OPNESSL_TSAN)
#if defined(OPENSSL_TSAN)
// Smaller under TSAN so that the edge case can be hit with fewer threads.
#define MAX_BLINDINGS_PER_RSA 2
#else
@@ -365,10 +366,23 @@ static BN_BLINDING *rsa_blinding_get(RSA *rsa, unsigned *index_used,
assert(rsa->mont_n != NULL);
BN_BLINDING *ret = NULL;
const uint64_t fork_generation = CRYPTO_get_fork_generation();
CRYPTO_MUTEX_lock_write(&rsa->lock);
// Wipe the blinding cache on |fork|.
if (rsa->blinding_fork_generation != fork_generation) {
for (unsigned i = 0; i < rsa->num_blindings; i++) {
// The inuse flag must be zero unless we were forked from a
// multi-threaded process, in which case calling back into BoringSSL is
// forbidden.
assert(rsa->blindings_inuse[i] == 0);
BN_BLINDING_invalidate(rsa->blindings[i]);
}
rsa->blinding_fork_generation = fork_generation;
}
uint8_t *const free_inuse_flag =
memchr(rsa->blindings_inuse, 0, rsa->num_blindings);
OPENSSL_memchr(rsa->blindings_inuse, 0, rsa->num_blindings);
if (free_inuse_flag != NULL) {
*free_inuse_flag = 1;
*index_used = free_inuse_flag - rsa->blindings_inuse;
@@ -578,8 +592,7 @@ static int mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx);
int RSA_verify_raw(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
const uint8_t *in, size_t in_len, int padding) {
if (rsa->n == NULL || rsa->e == NULL) {
OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
if (!rsa_check_public_key(rsa)) {
return 0;
}
@@ -596,10 +609,6 @@ int RSA_verify_raw(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
return 0;
}
if (!check_modulus_and_exponent_sizes(rsa)) {
return 0;
}
BN_CTX *ctx = BN_CTX_new();
if (ctx == NULL) {
return 0;
@@ -1107,8 +1116,8 @@ static int rsa_generate_key_impl(RSA *rsa, int bits, const BIGNUM *e_value,
// Reject excessively large public exponents. Windows CryptoAPI and Go don't
// support values larger than 32 bits, so match their limits for generating
// keys. (|check_modulus_and_exponent_sizes| uses a slightly more conservative
// value, but we don't need to support generating such keys.)
// keys. (|rsa_check_public_key| uses a slightly more conservative value, but
// we don't need to support generating such keys.)
// https://github.com/golang/go/issues/3161
// https://msdn.microsoft.com/en-us/library/aa387685(VS.85).aspx
if (BN_num_bits(e_value) > 32) {
@@ -21,6 +21,7 @@
#include <CCryptoBoringSSL_aes.h>
#include <CCryptoBoringSSL_bn.h>
#include <CCryptoBoringSSL_des.h>
#include <CCryptoBoringSSL_ec.h>
#include <CCryptoBoringSSL_ecdsa.h>
#include <CCryptoBoringSSL_ec_key.h>
#include <CCryptoBoringSSL_nid.h>
@@ -430,11 +431,44 @@ int boringssl_fips_self_test(
0xba, 0x4d, 0xd9, 0x86, 0x77, 0xda, 0x7d, 0x8f, 0xef, 0xc4, 0x1a,
0xf0, 0xcc, 0x81, 0xe5, 0xea, 0x3f, 0xc2, 0x41, 0x7f, 0xd8,
};
// kP256Point is SHA256("Primitive Z Computation KAT")×G within P-256.
const uint8_t kP256Point[65] = {
0x04, 0x4e, 0xc1, 0x94, 0x8c, 0x5c, 0xf4, 0x37, 0x35, 0x0d, 0xa3,
0xf9, 0x55, 0xf9, 0x8b, 0x26, 0x23, 0x5c, 0x43, 0xe0, 0x83, 0x51,
0x2b, 0x0d, 0x4b, 0x56, 0x24, 0xc3, 0xe4, 0xa5, 0xa8, 0xe2, 0xe9,
0x95, 0xf2, 0xc4, 0xb9, 0xb7, 0x48, 0x7d, 0x2a, 0xae, 0xc5, 0xc0,
0x0a, 0xcc, 0x1b, 0xd0, 0xec, 0xb8, 0xdc, 0xbe, 0x0c, 0xbe, 0x52,
0x79, 0x93, 0x7c, 0x0b, 0x92, 0x2b, 0x7f, 0x17, 0xa5, 0x80,
};
// kP256Scalar is SHA256("Primitive Z Computation KAT scalar").
const uint8_t kP256Scalar[32] = {
0xe7, 0x60, 0x44, 0x91, 0x26, 0x9a, 0xfb, 0x5b, 0x10, 0x2d, 0x6e,
0xa5, 0x2c, 0xb5, 0x9f, 0xeb, 0x70, 0xae, 0xde, 0x6c, 0xe3, 0xbf,
0xb3, 0xe0, 0x10, 0x54, 0x85, 0xab, 0xd8, 0x61, 0xd7, 0x7b,
};
// kP256PointResult is |kP256Scalar|×|kP256Point|.
const uint8_t kP256PointResult[65] = {
0x04, 0xf1, 0x63, 0x00, 0x88, 0xc5, 0xd5, 0xe9, 0x05, 0x52, 0xac,
0xb6, 0xec, 0x68, 0x76, 0xb8, 0x73, 0x7f, 0x0f, 0x72, 0x34, 0xe6,
0xbb, 0x30, 0x32, 0x22, 0x37, 0xb6, 0x2a, 0x80, 0xe8, 0x9e, 0x6e,
0x6f, 0x36, 0x02, 0xe7, 0x21, 0xd2, 0x31, 0xdb, 0x94, 0x63, 0xb7,
0xd8, 0x19, 0x0e, 0xc2, 0xc0, 0xa7, 0x2f, 0x15, 0x49, 0x1a, 0xa2,
0x7c, 0x41, 0x8f, 0xaf, 0x9c, 0x40, 0xaf, 0x2e, 0x4a,
#if !defined(BORINGSSL_FIPS_BREAK_Z_COMPUTATION)
0x0c,
#else
0x00,
#endif
};
EVP_AEAD_CTX aead_ctx;
EVP_AEAD_CTX_zero(&aead_ctx);
RSA *rsa_key = NULL;
EC_KEY *ec_key = NULL;
EC_GROUP *ec_group = NULL;
EC_POINT *ec_point_in = NULL;
EC_POINT *ec_point_out = NULL;
BIGNUM *ec_scalar = NULL;
ECDSA_SIG *sig = NULL;
int ret = 0;
@@ -602,6 +636,30 @@ int boringssl_fips_self_test(
goto err;
}
// Primitive Z Computation KAT (IG 9.6).
ec_group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
if (ec_group == NULL) {
fprintf(stderr, "Failed to create P-256 group.\n");
goto err;
}
ec_point_in = EC_POINT_new(ec_group);
ec_point_out = EC_POINT_new(ec_group);
ec_scalar = BN_new();
uint8_t z_comp_result[65];
if (ec_point_in == NULL || ec_point_out == NULL || ec_scalar == NULL ||
!EC_POINT_oct2point(ec_group, ec_point_in, kP256Point, sizeof(kP256Point),
NULL) ||
!BN_bin2bn(kP256Scalar, sizeof(kP256Scalar), ec_scalar) ||
!EC_POINT_mul(ec_group, ec_point_out, NULL, ec_point_in, ec_scalar,
NULL) ||
!EC_POINT_point2oct(ec_group, ec_point_out, POINT_CONVERSION_UNCOMPRESSED,
z_comp_result, sizeof(z_comp_result), NULL) ||
!check_test(kP256PointResult, z_comp_result, sizeof(z_comp_result),
"Z Computation Result")) {
fprintf(stderr, "Z Computation KAT failed.\n");
goto err;
}
// DBRG KAT
CTR_DRBG_STATE drbg;
if (!CTR_DRBG_init(&drbg, kDRBGEntropy, kDRBGPersonalization,
@@ -642,6 +700,10 @@ err:
EVP_AEAD_CTX_cleanup(&aead_ctx);
RSA_free(rsa_key);
EC_KEY_free(ec_key);
EC_POINT_free(ec_point_in);
EC_POINT_free(ec_point_out);
EC_GROUP_free(ec_group);
BN_free(ec_scalar);
ECDSA_SIG_free(sig);
return ret;
@@ -105,6 +105,23 @@ int SHA512_Init(SHA512_CTX *sha) {
return 1;
}
int SHA512_256_Init(SHA512_CTX *sha) {
sha->h[0] = UINT64_C(0x22312194fc2bf72c);
sha->h[1] = UINT64_C(0x9f555fa3c84c64c2);
sha->h[2] = UINT64_C(0x2393b86b6f53b151);
sha->h[3] = UINT64_C(0x963877195940eabd);
sha->h[4] = UINT64_C(0x96283ee2a88effe3);
sha->h[5] = UINT64_C(0xbe5e1e2553863992);
sha->h[6] = UINT64_C(0x2b0199fc2c85b8aa);
sha->h[7] = UINT64_C(0x0eb72ddc81c52ca2);
sha->Nl = 0;
sha->Nh = 0;
sha->num = 0;
sha->md_len = SHA512_256_DIGEST_LENGTH;
return 1;
}
uint8_t *SHA384(const uint8_t *data, size_t len,
uint8_t out[SHA384_DIGEST_LENGTH]) {
SHA512_CTX ctx;
@@ -125,6 +142,16 @@ uint8_t *SHA512(const uint8_t *data, size_t len,
return out;
}
uint8_t *SHA512_256(const uint8_t *data, size_t len,
uint8_t out[SHA512_256_DIGEST_LENGTH]) {
SHA512_CTX ctx;
SHA512_256_Init(&ctx);
SHA512_Update(&ctx, data, len);
SHA512_Final(out, &ctx);
OPENSSL_cleanse(&ctx, sizeof(ctx));
return out;
}
#if !defined(SHA512_ASM)
static void sha512_block_data_order(uint64_t *state, const uint8_t *in,
size_t num_blocks);
@@ -141,6 +168,17 @@ int SHA384_Update(SHA512_CTX *sha, const void *data, size_t len) {
return SHA512_Update(sha, data, len);
}
int SHA512_256_Update(SHA512_CTX *sha, const void *data, size_t len) {
return SHA512_Update(sha, data, len);
}
int SHA512_256_Final(uint8_t out[SHA512_256_DIGEST_LENGTH],
SHA512_CTX *sha) {
// |SHA512_256_Init| sets |sha->md_len| to |SHA512_256_DIGEST_LENGTH|, so this
// has a |smaller output.
return SHA512_Final(out, sha);
}
void SHA512_Transform(SHA512_CTX *c, const uint8_t block[SHA512_CBLOCK]) {
sha512_block_data_order(c->h, block, 1);
}
@@ -231,41 +269,12 @@ int SHA512_Final(uint8_t out[SHA512_DIGEST_LENGTH], SHA512_CTX *sha) {
return 0;
}
switch (sha->md_len) {
// Let compiler decide if it's appropriate to unroll...
case SHA384_DIGEST_LENGTH:
for (n = 0; n < SHA384_DIGEST_LENGTH / 8; n++) {
uint64_t t = sha->h[n];
*(out++) = (uint8_t)(t >> 56);
*(out++) = (uint8_t)(t >> 48);
*(out++) = (uint8_t)(t >> 40);
*(out++) = (uint8_t)(t >> 32);
*(out++) = (uint8_t)(t >> 24);
*(out++) = (uint8_t)(t >> 16);
*(out++) = (uint8_t)(t >> 8);
*(out++) = (uint8_t)(t);
}
break;
case SHA512_DIGEST_LENGTH:
for (n = 0; n < SHA512_DIGEST_LENGTH / 8; n++) {
uint64_t t = sha->h[n];
*(out++) = (uint8_t)(t >> 56);
*(out++) = (uint8_t)(t >> 48);
*(out++) = (uint8_t)(t >> 40);
*(out++) = (uint8_t)(t >> 32);
*(out++) = (uint8_t)(t >> 24);
*(out++) = (uint8_t)(t >> 16);
*(out++) = (uint8_t)(t >> 8);
*(out++) = (uint8_t)(t);
}
break;
// ... as well as make sure md_len is not abused.
default:
// TODO(davidben): This bad |md_len| case is one of the few places a
// low-level hash 'final' function can fail. This should never happen.
return 0;
assert(sha->md_len % 8 == 0);
const size_t out_words = sha->md_len / 8;
for (size_t i = 0; i < out_words; i++) {
const uint64_t t = CRYPTO_bswap8(sha->h[i]);
memcpy(out, &t, sizeof(t));
out += sizeof(t);
}
return 1;
Loaded 100 of 295 files, more files were not shown because too many files have changed in this diff. Show more