Compare commits

...
64 Commits
Author SHA1 Message Date
Cory Benfield 9c53b7a758 Update BoringSSL to 2042972e8458833714bce23386931b1c79978439 (#97) 2021-12-09 11:12:34 +00:00
Cory Benfield bd5abc2a12 Update BoringSSL to 3a667d10e94186fd503966f5638e134fe9fb4080 (#96) 2021-11-25 17:00:52 +00:00
Cory Benfield 9b5ef28601 Update BoringSSL to a9670a8b476470e6f874fef3554e8059683e1413 (#95) 2021-11-10 09:06:17 +00:00
Cory Benfield f47c1950ae Update the README to cover a wider version range (#93)
* Update the README to cover a wider version range

* Code review
2021-09-23 08:10:42 +01:00
Cory Benfield ab6b6fc81b Update to Swift 5.5 release in CI (#92) 2021-09-23 08:03:04 +01:00
Cory Benfield 127d3745c3 Update BoringSSL to 25773430c07075a368416c3646fa4b07daf4968a (#91) 2021-09-08 16:17:47 +01:00
Benedek Kozma d89b2ef9ed fix possible overindexing (#90) 2021-09-02 10:43:04 +01:00
Cory Benfield 684952cafa Update BoringSSL to 2e68a05c9943a8dec1758d4a393b2ae906fd3295 (#88)
Also update the vendor script to pass an explicit destination
2021-08-17 09:37:33 +01:00
Cory Benfield 8273610176 Only install Jazzy on focal (#89) 2021-08-17 09:31:47 +01:00
Cory Benfield 53da7b3706 Support compressed keys. (#87)
Motivation:

CryptoKit supports the compressed key format: we should as well.

Modifications:

Extend the constructors of public keys to tolerate the compressed
representation.

Result:

Users holding compressed keys can use them.
2021-07-30 07:20:33 +01:00
Cory Benfield 22fd389195 Update to CryptoKit 2021 API (#86)
This patch adds Crypto support for new API added in CryptoKit during the
summer releases of 2021.
2021-06-09 09:51:01 +01:00
buttafaceandCory Benfield 01c3fdfb85 Fix build for 32-bit platforms (#85)
Motivation:

I couldn't build for Android armv7 on the CI I set up without this.

Modifications:

Initialize with the right size of UInt to BoringSSL.

Result:

I can build for armv7 again.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2021-06-01 10:30:49 +01:00
Cory Benfield eefb07cc59 Futz around with Swift versions. (#84)
Motivation:

The various Apple SoS projects are currently dropping Swift 5.1 support.
Swift Crypto should do the same. While we're here, let's add CI for 5.4,
5.5 nightlies, and main nightlies.

Modifications:

- Remove 5.1 dockerfile.
- Stop claiming we support 5.1.
- Add 5.4, 5.5, and main dockerfiles.
- Updated Swift Format to 5.2.
- Associated formatting changes.

Result:

Better test matrix and support matrix.
2021-06-01 10:27:50 +01:00
Cory Benfield 158e2b140c Add SECURITY.md for swift-crypto (#83) 2021-05-27 14:27:10 +01:00
buttaface 8b7b68753f build: add amd64 and aarch64 assembly files to CMake build for Android (#81) 2021-05-19 14:55:27 +01:00
Cory Benfield 6c245a7f7f Provide initial proposal for RSA signing (#80)
Motivation:

Some critical use-cases require RSA signing support. This is most
commonly required when interacting with legacy systems. While RSA is an
older and less efficient cryptosystem than the elliptic-curve algorithms
supported by Swift Crypto already, those interop use-cases are
unavoidable.

This version of the patch does not promote RSA to supported API at this
time, as we'd like to let the API bake somewhat. Users are free to use
it, but these APIs are not covered by semantic versioning at this time
and may break in future.

Modifications:

- Defined new RSA API
- Implemented on top of `Security` when available
- Implemented on top of BoringSSL when `Security` is unavailable

Result:

Users can do RSA if needed.
2021-04-23 15:01:56 +01:00
Cory Benfield 3bea268b22 Update BoringSSL to 04b3213d43492b6c9e0434d8e2a4530a9938f958 (#79) 2021-03-10 14:25:25 +00:00
Yim LeeandCory Benfield 0141f53dd5 Add ARM64 assembly files to cmake build (#78)
Motivation:
See https://github.com/apple/swift-crypto/issues/74

Modifications:
- Add ARM64 assembly files to cmake build
- Update script to handle ARM64 assembly files

Result:
Resolves https://github.com/apple/swift-crypto/issues/74

Co-authored-by: Cory Benfield <lukasa@apple.com>
2021-03-03 09:52:54 +00:00
Max Desiatov b985ba6482 Stop referring to the missing master branch in BUG_REPORT.md (#75) 2021-03-03 08:36:39 +00:00
Yim Lee 296d3308b4 Fix typo in license header (#72) 2021-02-09 07:51:02 +00:00
Saleem Abdulrasool 8ff3d9dc83 build: explicitly include include in interface directories (#71)
The `include` directory is required for the interface include
directories for using `CCryptoBoringSSL` as a module from an external
package (i.e. SPM).  This allows SPM to include `CCryptoBoringSSL`
and find the module map.
2021-02-05 18:55:23 -08:00
Yim Lee 5c066af98c Update vendor-boringssl to save modulemap (#69)
* Update vendor-boringssl to save modulemap

Motivation:
The vendor-boringssl script rewrites `include`, which leads to deletion of `module.modulemap`.

Modification:
Save a copy of modulemap to tmp dir and copy it back at the end.

Result:
`module.modulemap` remains after running the script.

* Recreate modulemap each time instead of copying
2021-02-05 09:53:10 +00:00
Saleem Abdulrasoolandtomer doron 26d3f525eb build: allow using a build tree of dispatch, Foundation (#67)
When building swift-crypto from source for a toolchain build, it is
convenient to build it without building up a toolchain image.  This
additional knob allows for building swift-crypto with the build
artifacts of previous builds, allowing building up a toolchain image
while chaining multiple builds together.

Co-authored-by: tomer doron <tomer@apple.com>
2021-02-05 08:44:03 +00:00
Yim Lee 03581fe6ef Setup docker for cmake build (#70)
* Setup docker for cmake build

Motivation:
Be able to run cmake build in CI

Modifications:
- Add "cmake" service to `docker-compose.yaml`
- Update `Dockerfile` to install `cmake` and `ninja`. Remove unneeded dependencies.
- Add `docker-compose.2004.53.yaml`. `cmake` on previous Ubuntu versions are too old and it would be a pain to upgrade, so using Ubuntu 20.04 to simplify things.
- Add back modulemap to ensure cmake build is successful

Result:
Can run cmake in CI
2021-02-04 13:45:56 -08:00
Cory Benfield f9e47ba809 Update BoringSSL to bb43a45d6de7375f3310511d37f040d1055f8a10 (#66) 2021-02-04 12:31:56 +00:00
Yim Lee 42f5ffecd4 Update/Fix CMake build (#65)
Motivation:
SwiftPM's CMake build
(https://github.com/apple/swift-package-manager/pull/3202) unsuccessful
even with https://github.com/apple/swift-crypto/pull/60.

Modifications:
- Use consistent `SWIFT_CRYPTO_EXPORTS` naming. In some places `CRYPTO_EXPORTS` was used instead.
- Install `CCryptoBoringSSL` so we can import it in code (see https://github.com/apple/swift-package-manager/pull/3202)
- Always set `BUILD_SHARED_LIBS`

Result:
Successful CMake build.
2021-01-29 14:09:36 +00:00
47640ada33 Add CMake build files (#60)
Motivation:
This is to support https://github.com/apple/swift-package-manager/pull/3202, which adds swift-crypto as a dependency to SwiftPM.

Modifications:
Add CMake files.

Result:
Can build swift-crypto with cmake.

Co-authored-by: Saleem Abdulrasool <compnerd@compnerd.org>
Co-authored-by: Saleem Abdulrasool <abdulras@google.com>
2021-01-27 20:21:59 +00:00
Colin TremblayandCory Benfield 73dc51e2b2 fix a typo in documentation (#64)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2021-01-26 18:15:55 +00:00
Fabian Fett f8034c8319 Use welcoming language (#63) 2021-01-26 07:54:17 +00:00
Saleem Abdulrasool 85d00fea15 Tests: add Windows into the RNG path (#61)
This adds Windows to the SystemNumberGenerator condition as well, which
is needed to get the tests to build on Windows.
2021-01-22 09:28:25 +00:00
Saleem AbdulrasoolandCory Benfield 8f4bfa5bc1 scripts: update scripts for Windows support (#57)
Add support for Windows for vending BoringSSL.  This is required in
order to build SwiftCrypto for Windows.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-12-02 15:51:18 +00:00
Cory Benfield 0effb70b52 Update BoringSSL to 9dae0ac4f0ae18ebed988d36bfb4c4e4023fc574. (#54) 2020-12-02 15:44:56 +00:00
Saleem AbdulrasoolandCory Benfield 6eee6ab1d9 CCryptoBoringSSL: add Windows generated assembly (#56)
This adds the generated assembly files for Windows.  Unfortunately, the
x64 generated assembly appears to be ELF-esque and SYSV ABI rather than
Win64.  Additionally, the ARM targets do not seem to generate valid
Windows ARM code either (quick perusal shows at least invalid SP
handling on ARMv7 NT and non-conforming prologues on AArch64).  Add x86
Windows assembly only for the time being.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-12-02 15:43:03 +00:00
Saleem AbdulrasoolandCory Benfield 8b1daa33f6 build: allow building on Windows (#53)
This allows us to build on Windows, though not entirely.  The assembly
routines need to be generated for the Windows targets, but this is
required to get to that point.  With this set of changes, we are able to
get to the point where we can start linking the `crypto-shasum` target,
which exposes the missing symbols.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-12-02 11:09:40 +00:00
Saleem Abdulrasool ef6f94da02 gitignore: ignore vim swapfiles (#55) 2020-12-01 21:41:40 +00:00
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
555 changed files with 92733 additions and 32450 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 (`main` 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.]_
+5
View File
@@ -1,5 +1,6 @@
.DS_Store
/.build
/out
/Packages
/*.xcodeproj
Package.pins
@@ -10,3 +11,7 @@ Package.resolved
.podspecs
DerivedData
.swiftpm
**/gyb.pyc
.*.sw[nop]
+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.2
--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>
+46
View File
@@ -0,0 +1,46 @@
##===----------------------------------------------------------------------===##
##
## This source file is part of the SwiftCrypto open source project
##
## Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors
## Licensed under Apache License v2.0
##
## See LICENSE.txt for license information
## See CONTRIBUTORS.md for the list of SwiftCrypto project authors
##
## SPDX-License-Identifier: Apache-2.0
##
##===----------------------------------------------------------------------===##
cmake_minimum_required(VERSION 3.15.1)
project(SwiftCrypto
LANGUAGES ASM C Swift)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules)
include(SwiftSupport)
if(CMAKE_VERSION VERSION_LESS 3.16 AND CMAKE_SYSTEM_NAME STREQUAL Windows)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
else()
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
endif()
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift)
option(BUILD_SHARED_LIBS "Build shared libraries by default" YES)
if(BUILD_SHARED_LIBS)
set(CMAKE_POSITION_INDEPENDENT_CODE YES)
endif()
if(NOT CMAKE_SYSTEM_NAME STREQUAL Darwin)
find_package(dispatch CONFIG)
find_package(Foundation CONFIG)
endif()
add_subdirectory(Sources)
add_subdirectory(cmake/modules)
+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))
+17 -4
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.1
// swift-tools-version:5.2
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
@@ -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: 2042972e8458833714bce23386931b1c79978439
import PackageDescription
@@ -40,17 +40,30 @@ let package = Package(
],
products: [
.library(name: "Crypto", targets: ["Crypto"]),
.library(name: "_CryptoExtras", targets: ["_CryptoExtras"]),
/* This target is used only for symbol mangling. It's added and removed automatically because it emits build warnings. MANGLE_START
.library(name: "CCryptoBoringSSL", type: .static, targets: ["CCryptoBoringSSL"]),
MANGLE_END */
],
dependencies: [],
targets: [
.target(name: "CCryptoBoringSSL"),
.target(
name: "CCryptoBoringSSL",
cSettings: [
/*
* This define is required on Windows, but because we need older
* versions of SPM, we cannot conditionally define this on Windows
* only. Unconditionally define it instead.
*/
.define("WIN32_LEAN_AND_MEAN"),
]
),
.target(name: "CCryptoBoringSSLShims", dependencies: ["CCryptoBoringSSL"]),
.target(name: "Crypto", dependencies: ["CCryptoBoringSSL", "CCryptoBoringSSLShims"], swiftSettings: swiftSettings),
.target(name: "_CryptoExtras", dependencies: ["CCryptoBoringSSL", "CCryptoBoringSSLShims", "Crypto"]),
.target(name: "crypto-shasum", dependencies: ["Crypto"]),
.testTarget(name: "CryptoTests", dependencies: ["Crypto"], swiftSettings: swiftSettings),
.testTarget(name: "_CryptoExtrasTests", dependencies: ["_CryptoExtras"]),
],
cxxLanguageStandard: .cxx11
)
+76 -28
View File
@@ -1,84 +1,132 @@
# 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.
## Using Swift Crypto
Swift Crypto is available as a Swift Package Manager package. To use it, add the following dependency in your `Package.swift`:
```swift
// swift-crypto 1.x and 2.x are almost API compatible, so most clients should
// allow either
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "3.0.0"),
```
and to your target, add `Crypto` to your dependencies. You can then `import Crypto` to get access to Swift Crypto's functionality.
## 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.2 and later. Swift Crypto supported Swift 5.1 until version 1.2.
### 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. Any symbol beginning with an underscore, and any product beginning with an underscore, is not subject to semantic versioning: these APIs may change without warning. 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
Swift Crypto 2.0.0 was released in September 2021. The only breaking change between Swift Crypto 2.0.0 and 1.0.0 was the addition of new cases in the `CryptoKitError` enumeration. For most users, then, it's safe to depend on either the 1.0.0 _or_ 2.0.0 series of releases.
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.
To do so, please use the following dependency in your `Package.swift`:
```swift
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "3.0.0"),
```
### Developing Swift Crypto on macOS
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.
+12
View File
@@ -0,0 +1,12 @@
# Security
This document specifies the security process for Swift Crypto.
## Disclosures
To report a known or suspected vulnerability in Swift Crypto, [please report that vulnerability to Apple through the usual channel](https://support.apple.com/en-us/HT201220).
**Do not file a public issue.**
Fixes to Swift Crypto will be released simultaneously with any changes that need to be made in CryptoKit, to avoid the risk of having only partially fixed projects.
+392
View File
@@ -0,0 +1,392 @@
##===----------------------------------------------------------------------===##
##
## This source file is part of the SwiftCrypto open source project
##
## Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors
## Licensed under Apache License v2.0
##
## See LICENSE.txt for license information
## See CONTRIBUTORS.md for the list of SwiftCrypto project authors
##
## SPDX-License-Identifier: Apache-2.0
##
##===----------------------------------------------------------------------===##
add_library(CCryptoBoringSSL STATIC
"crypto/asn1/a_bitstr.c"
"crypto/asn1/a_bool.c"
"crypto/asn1/a_d2i_fp.c"
"crypto/asn1/a_dup.c"
"crypto/asn1/a_enum.c"
"crypto/asn1/a_gentm.c"
"crypto/asn1/a_i2d_fp.c"
"crypto/asn1/a_int.c"
"crypto/asn1/a_mbstr.c"
"crypto/asn1/a_object.c"
"crypto/asn1/a_octet.c"
"crypto/asn1/a_print.c"
"crypto/asn1/a_strex.c"
"crypto/asn1/a_strnid.c"
"crypto/asn1/a_time.c"
"crypto/asn1/a_type.c"
"crypto/asn1/a_utctm.c"
"crypto/asn1/a_utf8.c"
"crypto/asn1/asn1_lib.c"
"crypto/asn1/asn1_par.c"
"crypto/asn1/asn_pack.c"
"crypto/asn1/f_int.c"
"crypto/asn1/f_string.c"
"crypto/asn1/tasn_dec.c"
"crypto/asn1/tasn_enc.c"
"crypto/asn1/tasn_fre.c"
"crypto/asn1/tasn_new.c"
"crypto/asn1/tasn_typ.c"
"crypto/asn1/tasn_utl.c"
"crypto/asn1/time_support.c"
"crypto/base64/base64.c"
"crypto/bio/bio.c"
"crypto/bio/bio_mem.c"
"crypto/bio/connect.c"
"crypto/bio/fd.c"
"crypto/bio/file.c"
"crypto/bio/hexdump.c"
"crypto/bio/pair.c"
"crypto/bio/printf.c"
"crypto/bio/socket.c"
"crypto/bio/socket_helper.c"
"crypto/blake2/blake2.c"
"crypto/bn_extra/bn_asn1.c"
"crypto/bn_extra/convert.c"
"crypto/buf/buf.c"
"crypto/bytestring/asn1_compat.c"
"crypto/bytestring/ber.c"
"crypto/bytestring/cbb.c"
"crypto/bytestring/cbs.c"
"crypto/bytestring/unicode.c"
"crypto/chacha/chacha.c"
"crypto/cipher_extra/cipher_extra.c"
"crypto/cipher_extra/derive_key.c"
"crypto/cipher_extra/e_aesccm.c"
"crypto/cipher_extra/e_aesctrhmac.c"
"crypto/cipher_extra/e_aesgcmsiv.c"
"crypto/cipher_extra/e_chacha20poly1305.c"
"crypto/cipher_extra/e_null.c"
"crypto/cipher_extra/e_rc2.c"
"crypto/cipher_extra/e_rc4.c"
"crypto/cipher_extra/e_tls.c"
"crypto/cipher_extra/tls_cbc.c"
"crypto/cmac/cmac.c"
"crypto/conf/conf.c"
"crypto/cpu-aarch64-fuchsia.c"
"crypto/cpu-aarch64-linux.c"
"crypto/cpu-aarch64-win.c"
"crypto/cpu-arm-linux.c"
"crypto/cpu-arm.c"
"crypto/cpu-intel.c"
"crypto/cpu-ppc64le.c"
"crypto/crypto.c"
"crypto/curve25519/curve25519.c"
"crypto/curve25519/spake25519.c"
"crypto/dh_extra/dh_asn1.c"
"crypto/dh_extra/params.c"
"crypto/digest_extra/digest_extra.c"
"crypto/dsa/dsa.c"
"crypto/dsa/dsa_asn1.c"
"crypto/ec_extra/ec_asn1.c"
"crypto/ec_extra/ec_derive.c"
"crypto/ec_extra/hash_to_curve.c"
"crypto/ecdh_extra/ecdh_extra.c"
"crypto/ecdsa_extra/ecdsa_asn1.c"
"crypto/engine/engine.c"
"crypto/err/err.c"
"crypto/err/err_data.c"
"crypto/evp/digestsign.c"
"crypto/evp/evp.c"
"crypto/evp/evp_asn1.c"
"crypto/evp/evp_ctx.c"
"crypto/evp/p_dsa_asn1.c"
"crypto/evp/p_ec.c"
"crypto/evp/p_ec_asn1.c"
"crypto/evp/p_ed25519.c"
"crypto/evp/p_ed25519_asn1.c"
"crypto/evp/p_rsa.c"
"crypto/evp/p_rsa_asn1.c"
"crypto/evp/p_x25519.c"
"crypto/evp/p_x25519_asn1.c"
"crypto/evp/pbkdf.c"
"crypto/evp/print.c"
"crypto/evp/scrypt.c"
"crypto/evp/sign.c"
"crypto/ex_data.c"
"crypto/fipsmodule/aes/aes.c"
"crypto/fipsmodule/aes/aes_nohw.c"
"crypto/fipsmodule/aes/key_wrap.c"
"crypto/fipsmodule/aes/mode_wrappers.c"
"crypto/fipsmodule/bn/add.c"
"crypto/fipsmodule/bn/asm/x86_64-gcc.c"
"crypto/fipsmodule/bn/bn.c"
"crypto/fipsmodule/bn/bytes.c"
"crypto/fipsmodule/bn/cmp.c"
"crypto/fipsmodule/bn/ctx.c"
"crypto/fipsmodule/bn/div.c"
"crypto/fipsmodule/bn/div_extra.c"
"crypto/fipsmodule/bn/exponentiation.c"
"crypto/fipsmodule/bn/gcd.c"
"crypto/fipsmodule/bn/gcd_extra.c"
"crypto/fipsmodule/bn/generic.c"
"crypto/fipsmodule/bn/jacobi.c"
"crypto/fipsmodule/bn/montgomery.c"
"crypto/fipsmodule/bn/montgomery_inv.c"
"crypto/fipsmodule/bn/mul.c"
"crypto/fipsmodule/bn/prime.c"
"crypto/fipsmodule/bn/random.c"
"crypto/fipsmodule/bn/rsaz_exp.c"
"crypto/fipsmodule/bn/shift.c"
"crypto/fipsmodule/bn/sqrt.c"
"crypto/fipsmodule/cipher/aead.c"
"crypto/fipsmodule/cipher/cipher.c"
"crypto/fipsmodule/cipher/e_aes.c"
"crypto/fipsmodule/cipher/e_des.c"
"crypto/fipsmodule/des/des.c"
"crypto/fipsmodule/dh/check.c"
"crypto/fipsmodule/dh/dh.c"
"crypto/fipsmodule/digest/digest.c"
"crypto/fipsmodule/digest/digests.c"
"crypto/fipsmodule/ec/ec.c"
"crypto/fipsmodule/ec/ec_key.c"
"crypto/fipsmodule/ec/ec_montgomery.c"
"crypto/fipsmodule/ec/felem.c"
"crypto/fipsmodule/ec/oct.c"
"crypto/fipsmodule/ec/p224-64.c"
"crypto/fipsmodule/ec/p256-x86_64.c"
"crypto/fipsmodule/ec/p256.c"
"crypto/fipsmodule/ec/scalar.c"
"crypto/fipsmodule/ec/simple.c"
"crypto/fipsmodule/ec/simple_mul.c"
"crypto/fipsmodule/ec/util.c"
"crypto/fipsmodule/ec/wnaf.c"
"crypto/fipsmodule/ecdh/ecdh.c"
"crypto/fipsmodule/ecdsa/ecdsa.c"
"crypto/fipsmodule/fips_shared_support.c"
"crypto/fipsmodule/hmac/hmac.c"
"crypto/fipsmodule/md4/md4.c"
"crypto/fipsmodule/md5/md5.c"
"crypto/fipsmodule/modes/cbc.c"
"crypto/fipsmodule/modes/cfb.c"
"crypto/fipsmodule/modes/ctr.c"
"crypto/fipsmodule/modes/gcm.c"
"crypto/fipsmodule/modes/gcm_nohw.c"
"crypto/fipsmodule/modes/ofb.c"
"crypto/fipsmodule/modes/polyval.c"
"crypto/fipsmodule/rand/ctrdrbg.c"
"crypto/fipsmodule/rand/fork_detect.c"
"crypto/fipsmodule/rand/rand.c"
"crypto/fipsmodule/rand/urandom.c"
"crypto/fipsmodule/rsa/blinding.c"
"crypto/fipsmodule/rsa/padding.c"
"crypto/fipsmodule/rsa/rsa.c"
"crypto/fipsmodule/rsa/rsa_impl.c"
"crypto/fipsmodule/self_check/fips.c"
"crypto/fipsmodule/self_check/self_check.c"
"crypto/fipsmodule/sha/sha1-altivec.c"
"crypto/fipsmodule/sha/sha1.c"
"crypto/fipsmodule/sha/sha256.c"
"crypto/fipsmodule/sha/sha512.c"
"crypto/fipsmodule/tls/kdf.c"
"crypto/hkdf/hkdf.c"
"crypto/hpke/hpke.c"
"crypto/hrss/hrss.c"
"crypto/lhash/lhash.c"
"crypto/mem.c"
"crypto/obj/obj.c"
"crypto/obj/obj_xref.c"
"crypto/pem/pem_all.c"
"crypto/pem/pem_info.c"
"crypto/pem/pem_lib.c"
"crypto/pem/pem_oth.c"
"crypto/pem/pem_pk8.c"
"crypto/pem/pem_pkey.c"
"crypto/pem/pem_x509.c"
"crypto/pem/pem_xaux.c"
"crypto/pkcs7/pkcs7.c"
"crypto/pkcs7/pkcs7_x509.c"
"crypto/pkcs8/p5_pbev2.c"
"crypto/pkcs8/pkcs8.c"
"crypto/pkcs8/pkcs8_x509.c"
"crypto/poly1305/poly1305.c"
"crypto/poly1305/poly1305_arm.c"
"crypto/poly1305/poly1305_vec.c"
"crypto/pool/pool.c"
"crypto/rand_extra/deterministic.c"
"crypto/rand_extra/forkunsafe.c"
"crypto/rand_extra/fuchsia.c"
"crypto/rand_extra/passive.c"
"crypto/rand_extra/rand_extra.c"
"crypto/rand_extra/windows.c"
"crypto/rc4/rc4.c"
"crypto/refcount_c11.c"
"crypto/refcount_lock.c"
"crypto/rsa_extra/rsa_asn1.c"
"crypto/rsa_extra/rsa_print.c"
"crypto/siphash/siphash.c"
"crypto/stack/stack.c"
"crypto/thread.c"
"crypto/thread_none.c"
"crypto/thread_pthread.c"
"crypto/thread_win.c"
"crypto/trust_token/pmbtoken.c"
"crypto/trust_token/trust_token.c"
"crypto/trust_token/voprf.c"
"crypto/x509/a_digest.c"
"crypto/x509/a_sign.c"
"crypto/x509/a_verify.c"
"crypto/x509/algorithm.c"
"crypto/x509/asn1_gen.c"
"crypto/x509/by_dir.c"
"crypto/x509/by_file.c"
"crypto/x509/i2d_pr.c"
"crypto/x509/name_print.c"
"crypto/x509/rsa_pss.c"
"crypto/x509/t_crl.c"
"crypto/x509/t_req.c"
"crypto/x509/t_x509.c"
"crypto/x509/t_x509a.c"
"crypto/x509/x509.c"
"crypto/x509/x509_att.c"
"crypto/x509/x509_cmp.c"
"crypto/x509/x509_d2.c"
"crypto/x509/x509_def.c"
"crypto/x509/x509_ext.c"
"crypto/x509/x509_lu.c"
"crypto/x509/x509_obj.c"
"crypto/x509/x509_req.c"
"crypto/x509/x509_set.c"
"crypto/x509/x509_trs.c"
"crypto/x509/x509_txt.c"
"crypto/x509/x509_v3.c"
"crypto/x509/x509_vfy.c"
"crypto/x509/x509_vpm.c"
"crypto/x509/x509cset.c"
"crypto/x509/x509name.c"
"crypto/x509/x509rset.c"
"crypto/x509/x509spki.c"
"crypto/x509/x_algor.c"
"crypto/x509/x_all.c"
"crypto/x509/x_attrib.c"
"crypto/x509/x_crl.c"
"crypto/x509/x_exten.c"
"crypto/x509/x_info.c"
"crypto/x509/x_name.c"
"crypto/x509/x_pkey.c"
"crypto/x509/x_pubkey.c"
"crypto/x509/x_req.c"
"crypto/x509/x_sig.c"
"crypto/x509/x_spki.c"
"crypto/x509/x_val.c"
"crypto/x509/x_x509.c"
"crypto/x509/x_x509a.c"
"crypto/x509v3/pcy_cache.c"
"crypto/x509v3/pcy_data.c"
"crypto/x509v3/pcy_lib.c"
"crypto/x509v3/pcy_map.c"
"crypto/x509v3/pcy_node.c"
"crypto/x509v3/pcy_tree.c"
"crypto/x509v3/v3_akey.c"
"crypto/x509v3/v3_akeya.c"
"crypto/x509v3/v3_alt.c"
"crypto/x509v3/v3_bcons.c"
"crypto/x509v3/v3_bitst.c"
"crypto/x509v3/v3_conf.c"
"crypto/x509v3/v3_cpols.c"
"crypto/x509v3/v3_crld.c"
"crypto/x509v3/v3_enum.c"
"crypto/x509v3/v3_extku.c"
"crypto/x509v3/v3_genn.c"
"crypto/x509v3/v3_ia5.c"
"crypto/x509v3/v3_info.c"
"crypto/x509v3/v3_int.c"
"crypto/x509v3/v3_lib.c"
"crypto/x509v3/v3_ncons.c"
"crypto/x509v3/v3_ocsp.c"
"crypto/x509v3/v3_pci.c"
"crypto/x509v3/v3_pcia.c"
"crypto/x509v3/v3_pcons.c"
"crypto/x509v3/v3_pmaps.c"
"crypto/x509v3/v3_prn.c"
"crypto/x509v3/v3_purp.c"
"crypto/x509v3/v3_skey.c"
"crypto/x509v3/v3_utl.c")
if(CMAKE_SYSTEM_NAME STREQUAL Darwin AND CMAKE_SYSTEM_PROCESSOR MATCHES "amd64|x86_64")
target_sources(CCryptoBoringSSL PRIVATE
crypto/chacha/chacha-x86_64.mac.x86_64.S
crypto/cipher_extra/aes128gcmsiv-x86_64.mac.x86_64.S
crypto/cipher_extra/chacha20_poly1305_x86_64.mac.x86_64.S
crypto/fipsmodule/aesni-gcm-x86_64.mac.x86_64.S
crypto/fipsmodule/aesni-x86_64.mac.x86_64.S
crypto/fipsmodule/ghash-ssse3-x86_64.mac.x86_64.S
crypto/fipsmodule/ghash-x86_64.mac.x86_64.S
crypto/fipsmodule/md5-x86_64.mac.x86_64.S
crypto/fipsmodule/p256-x86_64-asm.mac.x86_64.S
crypto/fipsmodule/p256_beeu-x86_64-asm.mac.x86_64.S
crypto/fipsmodule/rdrand-x86_64.mac.x86_64.S
crypto/fipsmodule/rsaz-avx2.mac.x86_64.S
crypto/fipsmodule/sha1-x86_64.mac.x86_64.S
crypto/fipsmodule/sha256-x86_64.mac.x86_64.S
crypto/fipsmodule/sha512-x86_64.mac.x86_64.S
crypto/fipsmodule/vpaes-x86_64.mac.x86_64.S
crypto/fipsmodule/x86_64-mont.mac.x86_64.S
crypto/fipsmodule/x86_64-mont5.mac.x86_64.S)
elseif(CMAKE_SYSTEM_NAME MATCHES "Linux|Android" AND CMAKE_SYSTEM_PROCESSOR MATCHES "amd64|x86_64")
target_sources(CCryptoBoringSSL PRIVATE
crypto/chacha/chacha-x86_64.linux.x86_64.S
crypto/cipher_extra/aes128gcmsiv-x86_64.linux.x86_64.S
crypto/cipher_extra/chacha20_poly1305_x86_64.linux.x86_64.S
crypto/fipsmodule/aesni-gcm-x86_64.linux.x86_64.S
crypto/fipsmodule/aesni-x86_64.linux.x86_64.S
crypto/fipsmodule/ghash-ssse3-x86_64.linux.x86_64.S
crypto/fipsmodule/ghash-x86_64.linux.x86_64.S
crypto/fipsmodule/md5-x86_64.linux.x86_64.S
crypto/fipsmodule/p256-x86_64-asm.linux.x86_64.S
crypto/fipsmodule/p256_beeu-x86_64-asm.linux.x86_64.S
crypto/fipsmodule/rdrand-x86_64.linux.x86_64.S
crypto/fipsmodule/rsaz-avx2.linux.x86_64.S
crypto/fipsmodule/sha1-x86_64.linux.x86_64.S
crypto/fipsmodule/sha256-x86_64.linux.x86_64.S
crypto/fipsmodule/sha512-x86_64.linux.x86_64.S
crypto/fipsmodule/vpaes-x86_64.linux.x86_64.S
crypto/fipsmodule/x86_64-mont.linux.x86_64.S
crypto/fipsmodule/x86_64-mont5.linux.x86_64.S)
elseif(CMAKE_SYSTEM_NAME STREQUAL Darwin AND CMAKE_SYSTEM_PROCESSOR MATCHES "arm64|aarch64")
target_sources(CCryptoBoringSSL PRIVATE
crypto/chacha/chacha-armv8.ios.aarch64.S
crypto/fipsmodule/aesv8-armx64.ios.aarch64.S
crypto/fipsmodule/armv8-mont.ios.aarch64.S
crypto/fipsmodule/ghash-neon-armv8.ios.aarch64.S
crypto/fipsmodule/ghashv8-armx64.ios.aarch64.S
crypto/fipsmodule/sha1-armv8.ios.aarch64.S
crypto/fipsmodule/sha256-armv8.ios.aarch64.S
crypto/fipsmodule/sha512-armv8.ios.aarch64.S
crypto/fipsmodule/vpaes-armv8.ios.aarch64.S)
elseif(CMAKE_SYSTEM_NAME MATCHES "Linux|Android" AND CMAKE_SYSTEM_PROCESSOR MATCHES "arm64|aarch64")
target_sources(CCryptoBoringSSL PRIVATE
crypto/chacha/chacha-armv8.linux.aarch64.S
crypto/fipsmodule/aesv8-armx64.linux.aarch64.S
crypto/fipsmodule/armv8-mont.linux.aarch64.S
crypto/fipsmodule/ghash-neon-armv8.linux.aarch64.S
crypto/fipsmodule/ghashv8-armx64.linux.aarch64.S
crypto/fipsmodule/sha1-armv8.linux.aarch64.S
crypto/fipsmodule/sha256-armv8.linux.aarch64.S
crypto/fipsmodule/sha512-armv8.linux.aarch64.S
crypto/fipsmodule/vpaes-armv8.linux.aarch64.S)
endif()
target_include_directories(CCryptoBoringSSL PUBLIC
include)
target_compile_definitions(CCryptoBoringSSL PRIVATE
$<$<PLATFORM_ID:Windows>:WIN32_LEAN_AND_MEAN>)
set_target_properties(CCryptoBoringSSL PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/include;${CMAKE_Swift_MODULE_DIRECTORY}")
set_property(GLOBAL APPEND PROPERTY SWIFT_CRYPTO_EXPORTS CCryptoBoringSSL)
+72 -59
View File
@@ -63,66 +63,72 @@
#include <CCryptoBoringSSL_mem.h>
#include "../internal.h"
#include "internal.h"
int ASN1_BIT_STRING_set(ASN1_BIT_STRING *x, unsigned char *d, int len)
int ASN1_BIT_STRING_set(ASN1_BIT_STRING *x, const unsigned char *d, int len)
{
return M_ASN1_BIT_STRING_set(x, d, len);
return ASN1_STRING_set(x, d, len);
}
int i2c_ASN1_BIT_STRING(ASN1_BIT_STRING *a, unsigned char **pp)
{
int ret, j, bits, len;
unsigned char *p, *d;
if (a == NULL)
return (0);
len = a->length;
int asn1_bit_string_length(const ASN1_BIT_STRING *str,
uint8_t *out_padding_bits) {
int len = str->length;
if (str->flags & ASN1_STRING_FLAG_BITS_LEFT) {
// If the string is already empty, it cannot have padding bits.
*out_padding_bits = len == 0 ? 0 : str->flags & 0x07;
return len;
}
// TODO(https://crbug.com/boringssl/447): If we move this logic to
// |ASN1_BIT_STRING_set_bit|, can we remove this representation?
while (len > 0 && str->data[len - 1] == 0) {
len--;
}
uint8_t padding_bits = 0;
if (len > 0) {
if (a->flags & ASN1_STRING_FLAG_BITS_LEFT) {
bits = (int)a->flags & 0x07;
} else {
for (; len > 0; len--) {
if (a->data[len - 1])
break;
uint8_t last = str->data[len - 1];
assert(last != 0);
for (; padding_bits < 7; padding_bits++) {
if (last & (1 << padding_bits)) {
break;
}
j = a->data[len - 1];
if (j & 0x01)
bits = 0;
else if (j & 0x02)
bits = 1;
else if (j & 0x04)
bits = 2;
else if (j & 0x08)
bits = 3;
else if (j & 0x10)
bits = 4;
else if (j & 0x20)
bits = 5;
else if (j & 0x40)
bits = 6;
else if (j & 0x80)
bits = 7;
else
bits = 0; /* should not happen */
}
} else
bits = 0;
}
*out_padding_bits = padding_bits;
return len;
}
ret = 1 + len;
if (pp == NULL)
return (ret);
int ASN1_BIT_STRING_num_bytes(const ASN1_BIT_STRING *str, size_t *out) {
uint8_t padding_bits;
int len = asn1_bit_string_length(str, &padding_bits);
if (padding_bits != 0) {
return 0;
}
*out = len;
return 1;
}
p = *pp;
int i2c_ASN1_BIT_STRING(const ASN1_BIT_STRING *a, unsigned char **pp)
{
if (a == NULL) {
return 0;
}
*(p++) = (unsigned char)bits;
d = a->data;
OPENSSL_memcpy(p, d, len);
uint8_t bits;
int len = asn1_bit_string_length(a, &bits);
int ret = 1 + len;
if (pp == NULL) {
return ret;
}
uint8_t *p = *pp;
*(p++) = bits;
OPENSSL_memcpy(p, a->data, len);
if (len > 0) {
p[len - 1] &= (0xff << bits);
}
p += len;
if (len > 0)
p[-1] &= (0xff << bits);
*pp = p;
return (ret);
}
@@ -146,18 +152,27 @@ ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a,
}
if ((a == NULL) || ((*a) == NULL)) {
if ((ret = M_ASN1_BIT_STRING_new()) == NULL)
if ((ret = ASN1_BIT_STRING_new()) == NULL)
return (NULL);
} else
ret = (*a);
p = *pp;
padding = *(p++);
len--;
if (padding > 7) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);
goto err;
}
/* Unused bits in a BIT STRING must be zero. */
uint8_t padding_mask = (1 << padding) - 1;
if (padding != 0 &&
(len < 1 || (p[len - 1] & padding_mask) != 0)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BIT_STRING_PADDING);
goto err;
}
/*
* We do this to preserve the settings. If we modify the settings, via
* the _set_bit function, we will recalculate on output
@@ -165,21 +180,19 @@ ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a,
ret->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); /* clear */
ret->flags |= (ASN1_STRING_FLAG_BITS_LEFT | padding); /* set */
if (len-- > 1) { /* using one because of the bits left byte */
s = (unsigned char *)OPENSSL_malloc((int)len);
if (len > 0) {
s = OPENSSL_memdup(p, len);
if (s == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
OPENSSL_memcpy(s, p, (int)len);
s[len - 1] &= (0xff << padding);
p += len;
} else
} else {
s = NULL;
}
ret->length = (int)len;
if (ret->data != NULL)
OPENSSL_free(ret->data);
OPENSSL_free(ret->data);
ret->data = s;
ret->type = V_ASN1_BIT_STRING;
if (a != NULL)
@@ -188,7 +201,7 @@ ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a,
return (ret);
err:
if ((ret != NULL) && ((a == NULL) || (*a != ret)))
M_ASN1_BIT_STRING_free(ret);
ASN1_BIT_STRING_free(ret);
return (NULL);
}
@@ -233,7 +246,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,8 +263,8 @@ 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,
unsigned char *flags, int flags_len)
int ASN1_BIT_STRING_check(const ASN1_BIT_STRING *a,
const unsigned char *flags, int flags_len)
{
int i, ok;
/* Check if there is one bit set at all. */
+22 -23
View File
@@ -59,7 +59,7 @@
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
int i2d_ASN1_BOOLEAN(int a, unsigned char **pp)
int i2d_ASN1_BOOLEAN(ASN1_BOOLEAN a, unsigned char **pp)
{
int r;
unsigned char *p, *allocated = NULL;
@@ -71,14 +71,14 @@ int i2d_ASN1_BOOLEAN(int a, unsigned char **pp)
if (*pp == NULL) {
if ((p = allocated = OPENSSL_malloc(r)) == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return 0;
return -1;
}
} else {
p = *pp;
}
ASN1_put_object(&p, 0, 1, V_ASN1_BOOLEAN, V_ASN1_UNIVERSAL);
*p = (unsigned char)a;
*p = a ? 0xff : 0x00;
/*
* If a new buffer was allocated, just return it back.
@@ -88,36 +88,35 @@ int i2d_ASN1_BOOLEAN(int a, unsigned char **pp)
return r;
}
int d2i_ASN1_BOOLEAN(int *a, const unsigned char **pp, long length)
{
int ret = -1;
const unsigned char *p;
ASN1_BOOLEAN d2i_ASN1_BOOLEAN(ASN1_BOOLEAN *a, const unsigned char **pp,
long length) {
const unsigned char *p = *pp;
long len;
int inf, tag, xclass;
int i = 0;
p = *pp;
inf = ASN1_get_object(&p, &len, &tag, &xclass, length);
if (inf & 0x80) {
i = ASN1_R_BAD_OBJECT_HEADER;
goto err;
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_OBJECT_HEADER);
return -1;
}
if (tag != V_ASN1_BOOLEAN) {
i = ASN1_R_EXPECTING_A_BOOLEAN;
goto err;
if (inf & V_ASN1_CONSTRUCTED) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_PRIMITIVE);
return -1;
}
if (tag != V_ASN1_BOOLEAN || xclass != V_ASN1_UNIVERSAL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_EXPECTING_A_BOOLEAN);
return -1;
}
if (len != 1) {
i = ASN1_R_BOOLEAN_IS_WRONG_LENGTH;
goto err;
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
return -1;
}
ret = (int)*(p++);
if (a != NULL)
ASN1_BOOLEAN ret = (ASN1_BOOLEAN)*(p++);
if (a != NULL) {
(*a) = ret;
}
*pp = p;
return (ret);
err:
OPENSSL_PUT_ERROR(ASN1, i);
return (ret);
return ret;
}
@@ -78,7 +78,6 @@ void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *x)
return ret;
}
#ifndef OPENSSL_NO_FP_API
void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x)
{
BIO *b = BIO_new_fp(in, BIO_NOCLOSE);
@@ -90,4 +89,3 @@ void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x)
BIO_free(b);
return ret;
}
#endif
@@ -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,13 +147,13 @@ 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;
if (ai == NULL)
ret = M_ASN1_ENUMERATED_new();
ret = ASN1_ENUMERATED_new();
else
ret = ai;
if (ret == NULL) {
@@ -179,11 +179,11 @@ ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(BIGNUM *bn, ASN1_ENUMERATED *ai)
return (ret);
err:
if (ret != ai)
M_ASN1_ENUMERATED_free(ret);
ASN1_ENUMERATED_free(ret);
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;
@@ -62,7 +62,7 @@
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include "asn1_locl.h"
#include "internal.h"
int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d)
{
@@ -237,6 +237,11 @@ ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s,
goto err;
}
if (ts->tm_year < 0 - 1900 || ts->tm_year > 9999 - 1900) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_TIME_VALUE);
goto err;
}
p = (char *)tmps->data;
if ((p == NULL) || ((size_t)tmps->length < len)) {
p = OPENSSL_malloc(len);
+6 -6
View File
@@ -67,7 +67,7 @@
ASN1_INTEGER *ASN1_INTEGER_dup(const ASN1_INTEGER *x)
{
return M_ASN1_INTEGER_dup(x);
return ASN1_STRING_dup(x);
}
int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y)
@@ -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;
@@ -206,7 +206,7 @@ ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp,
}
if ((a == NULL) || ((*a) == NULL)) {
if ((ret = M_ASN1_INTEGER_new()) == NULL)
if ((ret = ASN1_INTEGER_new()) == NULL)
return (NULL);
ret->type = V_ASN1_INTEGER;
} else
@@ -282,7 +282,7 @@ ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp,
err:
OPENSSL_PUT_ERROR(ASN1, i);
if ((ret != NULL) && ((a == NULL) || (*a != ret)))
M_ASN1_INTEGER_free(ret);
ASN1_INTEGER_free(ret);
return (NULL);
}
@@ -374,7 +374,7 @@ ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai)
int len, j;
if (ai == NULL)
ret = M_ASN1_INTEGER_new();
ret = ASN1_INTEGER_new();
else
ret = ai;
if (ret == NULL) {
@@ -404,7 +404,7 @@ ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai)
return (ret);
err:
if (ret != ai)
M_ASN1_INTEGER_free(ret);
ASN1_INTEGER_free(ret);
return (NULL);
}
+16 -23
View File
@@ -63,11 +63,9 @@
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include "asn1_locl.h"
#include "internal.h"
#include "../bytestring/internal.h"
static int is_printable(uint32_t value);
/*
* These functions take a string in UTF8, ASCII or multibyte form and a mask
* of permissible ASN1 string types. It then works out the minimal type
@@ -153,7 +151,7 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
}
/* Update which output formats are still possible. */
if ((mask & B_ASN1_PRINTABLESTRING) && !is_printable(c)) {
if ((mask & B_ASN1_PRINTABLESTRING) && !asn1_is_printable(c)) {
mask &= ~B_ASN1_PRINTABLESTRING;
}
if ((mask & B_ASN1_IA5STRING) && (c > 127)) {
@@ -208,11 +206,14 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
encode_func = cbb_add_utf32_be;
size_estimate = 4 * nchar;
outform = MBSTRING_UNIV;
} else {
} else if (mask & B_ASN1_UTF8STRING) {
str_type = V_ASN1_UTF8STRING;
outform = MBSTRING_UTF8;
encode_func = cbb_add_utf8;
size_estimate = utf8_len;
} else {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_CHARACTERS);
return -1;
}
if (!out)
@@ -282,24 +283,16 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
return -1;
}
/* Return 1 if the character is permitted in a PrintableString */
static int is_printable(uint32_t value)
int asn1_is_printable(uint32_t value)
{
int ch;
if (value > 0x7f)
if (value > 0x7f) {
return 0;
ch = (int)value;
/*
* Note: we can't use 'isalnum' because certain accented characters may
* count as alphanumeric in some environments.
*/
if ((ch >= 'a') && (ch <= 'z'))
return 1;
if ((ch >= 'A') && (ch <= 'Z'))
return 1;
if ((ch >= '0') && (ch <= '9'))
return 1;
if ((ch == ' ') || strchr("'()+,-./:=?", ch))
return 1;
return 0;
}
/* Note we cannot use |isalnum| because it is locale-dependent. */
return ('a' <= value && value <= 'z') || //
('A' <= value && value <= 'Z') || //
('0' <= value && value <= '9') || //
value == ' ' || value == '\'' || value == '(' || value == ')' ||
value == '+' || value == ',' || value == '-' || value == '.' ||
value == '/' || value == ':' || value == '=' || value == '?';
}
+71 -58
View File
@@ -64,24 +64,31 @@
#include <CCryptoBoringSSL_obj.h>
#include "../internal.h"
#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;
if (a == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
if ((a == NULL) || (a->data == NULL))
return (0);
if (a->length == 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OBJECT);
return -1;
}
objsize = ASN1_object_size(0, a->length, V_ASN1_OBJECT);
if (pp == NULL || objsize == -1)
int objsize = ASN1_object_size(0, a->length, V_ASN1_OBJECT);
if (pp == NULL || objsize == -1) {
return objsize;
}
unsigned char *p, *allocated = NULL;
if (*pp == NULL) {
if ((p = allocated = OPENSSL_malloc(objsize)) == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return 0;
return -1;
}
} else {
p = *pp;
@@ -98,59 +105,70 @@ 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)
static int write_str(BIO *bp, const char *str)
{
char buf[80], *p = buf;
int i;
int len = strlen(str);
return BIO_write(bp, str, len) == len ? len : -1;
}
if ((a == NULL) || (a->data == NULL))
return (BIO_write(bp, "NULL", 4));
i = i2t_ASN1_OBJECT(buf, sizeof buf, a);
if (i > (int)(sizeof(buf) - 1)) {
p = OPENSSL_malloc(i + 1);
if (!p)
return -1;
i2t_ASN1_OBJECT(p, i + 1, a);
int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a)
{
if (a == NULL || a->data == NULL) {
return write_str(bp, "NULL");
}
if (i <= 0)
return BIO_write(bp, "<INVALID>", 9);
BIO_write(bp, p, i);
if (p != buf)
OPENSSL_free(p);
return (i);
char buf[80], *allocated = NULL;
const char *str = buf;
int len = i2t_ASN1_OBJECT(buf, sizeof(buf), a);
if (len > (int)sizeof(buf) - 1) {
/* The input was truncated. Allocate a buffer that fits. */
allocated = OPENSSL_malloc(len + 1);
if (allocated == NULL) {
return -1;
}
len = i2t_ASN1_OBJECT(allocated, len + 1, a);
str = allocated;
}
if (len <= 0) {
str = "<INVALID>";
}
int ret = write_str(bp, str);
OPENSSL_free(allocated);
return ret;
}
ASN1_OBJECT *d2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp,
long length)
{
const unsigned char *p;
long len;
int tag, xclass;
int inf, i;
ASN1_OBJECT *ret = NULL;
p = *pp;
inf = ASN1_get_object(&p, &len, &tag, &xclass, length);
const unsigned char *p = *pp;
int inf = ASN1_get_object(&p, &len, &tag, &xclass, length);
if (inf & 0x80) {
i = ASN1_R_BAD_OBJECT_HEADER;
goto err;
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_OBJECT_HEADER);
return NULL;
}
if (tag != V_ASN1_OBJECT) {
i = ASN1_R_EXPECTING_AN_OBJECT;
goto err;
if (inf & V_ASN1_CONSTRUCTED) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_PRIMITIVE);
return NULL;
}
ret = c2i_ASN1_OBJECT(a, &p, len);
if (ret)
if (tag != V_ASN1_OBJECT || xclass != V_ASN1_UNIVERSAL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_EXPECTING_AN_OBJECT);
return NULL;
}
ASN1_OBJECT *ret = c2i_ASN1_OBJECT(a, &p, len);
if (ret) {
*pp = p;
}
return ret;
err:
OPENSSL_PUT_ERROR(ASN1, i);
return (NULL);
}
ASN1_OBJECT *c2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp,
@@ -180,16 +198,13 @@ ASN1_OBJECT *c2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp,
}
}
/*
* only the ASN1_OBJECTs from the 'table' will have values for ->sn or
* ->ln
*/
if ((a == NULL) || ((*a) == NULL) ||
!((*a)->flags & ASN1_OBJECT_FLAG_DYNAMIC)) {
if ((ret = ASN1_OBJECT_new()) == NULL)
return (NULL);
} else
} else {
ret = (*a);
}
p = *pp;
/* detach data from object */
@@ -208,12 +223,17 @@ ASN1_OBJECT *c2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp,
ret->flags |= ASN1_OBJECT_FLAG_DYNAMIC_DATA;
}
OPENSSL_memcpy(data, p, length);
/* If there are dynamic strings, free them here, and clear the flag */
if ((ret->flags & ASN1_OBJECT_FLAG_DYNAMIC_STRINGS) != 0) {
OPENSSL_free((char *)ret->sn);
OPENSSL_free((char *)ret->ln);
ret->flags &= ~ASN1_OBJECT_FLAG_DYNAMIC_STRINGS;
}
/* reattach data to object, after which it remains const */
ret->data = data;
ret->length = length;
ret->sn = NULL;
ret->ln = NULL;
/* ret->flags=ASN1_OBJECT_FLAG_DYNAMIC; we know it is dynamic */
p += length;
if (a != NULL)
@@ -250,19 +270,12 @@ void ASN1_OBJECT_free(ASN1_OBJECT *a)
if (a == NULL)
return;
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC_STRINGS) {
#ifndef CONST_STRICT /* disable purely for compile-time strict
* const checking. Doing this on a "real"
* compile will cause memory leaks */
if (a->sn != NULL)
OPENSSL_free((void *)a->sn);
if (a->ln != NULL)
OPENSSL_free((void *)a->ln);
#endif
OPENSSL_free((void *)a->sn);
OPENSSL_free((void *)a->ln);
a->sn = a->ln = NULL;
}
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC_DATA) {
if (a->data != NULL)
OPENSSL_free((void *)a->data);
OPENSSL_free((void *)a->data);
a->data = NULL;
a->length = 0;
}
@@ -270,7 +283,7 @@ void ASN1_OBJECT_free(ASN1_OBJECT *a)
OPENSSL_free(a);
}
ASN1_OBJECT *ASN1_OBJECT_create(int nid, unsigned char *data, int len,
ASN1_OBJECT *ASN1_OBJECT_create(int nid, const unsigned char *data, int len,
const char *sn, const char *ln)
{
ASN1_OBJECT o;
@@ -61,17 +61,17 @@
ASN1_OCTET_STRING *ASN1_OCTET_STRING_dup(const ASN1_OCTET_STRING *x)
{
return M_ASN1_OCTET_STRING_dup(x);
return ASN1_STRING_dup(x);
}
int ASN1_OCTET_STRING_cmp(const ASN1_OCTET_STRING *a,
const ASN1_OCTET_STRING *b)
{
return M_ASN1_OCTET_STRING_cmp(a, b);
return ASN1_STRING_cmp(a, b);
}
int ASN1_OCTET_STRING_set(ASN1_OCTET_STRING *x, const unsigned char *d,
int len)
{
return M_ASN1_OCTET_STRING_set(x, d, len);
return ASN1_STRING_set(x, d, len);
}
+20 -30
View File
@@ -56,38 +56,28 @@
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <string.h>
#include "internal.h"
int ASN1_PRINTABLE_type(const unsigned char *s, int len)
{
int c;
int ia5 = 0;
int t61 = 0;
if (len <= 0)
len = -1;
if (s == NULL)
return (V_ASN1_PRINTABLESTRING);
while ((*s) && (len-- != 0)) {
c = *(s++);
if (!(((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
(c == ' ') ||
((c >= '0') && (c <= '9')) ||
(c == ' ') || (c == '\'') ||
(c == '(') || (c == ')') ||
(c == '+') || (c == ',') ||
(c == '-') || (c == '.') ||
(c == '/') || (c == ':') || (c == '=') || (c == '?')))
ia5 = 1;
if (c & 0x80)
t61 = 1;
if (len < 0) {
len = strlen((const char *)s);
}
if (t61)
return (V_ASN1_T61STRING);
if (ia5)
return (V_ASN1_IA5STRING);
return (V_ASN1_PRINTABLESTRING);
int printable = 1;
for (int i = 0; i < len; i++) {
unsigned char c = s[i];
if (c & 0x80) {
/* No need to continue iterating. */
return V_ASN1_T61STRING;
}
if (!asn1_is_printable(c)) {
printable = 0;
}
}
return printable ? V_ASN1_PRINTABLESTRING : V_ASN1_IA5STRING;
}
@@ -54,23 +54,27 @@
* copied and put under another distribution licence
* [including the GNU Public Licence.] */
#include <CCryptoBoringSSL_x509.h>
#include <CCryptoBoringSSL_asn1.h>
#include <ctype.h>
#include <inttypes.h>
#include <string.h>
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_bio.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_obj.h>
#include "charmap.h"
#include "../asn1/asn1_locl.h"
#include "internal.h"
/*
* ASN1_STRING_print_ex() and X509_NAME_print_ex(). Enhanced string and name
* printing routines handling multibyte characters, RFC2253 and a host of
* other options.
*/
// These flags must be distinct from |ESC_FLAGS| and fit in a byte.
// Character is a valid PrintableString character
#define CHARTYPE_PRINTABLESTRING 0x10
// Character needs escaping if it is the first character
#define CHARTYPE_FIRST_ESC_2253 0x20
// Character needs escaping if it is the last character
#define CHARTYPE_LAST_ESC_2253 0x40
#define CHARTYPE_BS_ESC (ASN1_STRFLGS_ESC_2253 | CHARTYPE_FIRST_ESC_2253 | CHARTYPE_LAST_ESC_2253)
@@ -79,26 +83,12 @@
ASN1_STRFLGS_ESC_CTRL | \
ASN1_STRFLGS_ESC_MSB)
static int send_bio_chars(void *arg, const void *buf, int len)
static int maybe_write(BIO *out, const void *buf, int len)
{
if (!arg)
return 1;
if (BIO_write(arg, buf, len) != len)
return 0;
return 1;
/* If |out| is NULL, ignore the output but report the length. */
return out == NULL || BIO_write(out, buf, len) == len;
}
static int send_fp_chars(void *arg, const void *buf, int len)
{
if (!arg)
return 1;
if (fwrite(buf, 1, len, arg) != (unsigned int)len)
return 0;
return 1;
}
typedef int char_io (void *arg, const void *buf, int len);
/*
* This function handles display of strings, one character at a time. It is
* passed an unsigned long for each character because it could come from 2 or
@@ -108,20 +98,20 @@ typedef int char_io (void *arg, const void *buf, int len);
#define HEX_SIZE(type) (sizeof(type)*2)
static int do_esc_char(uint32_t c, unsigned char flags, char *do_quotes,
char_io *io_ch, void *arg)
BIO *out)
{
unsigned char chflgs, chtmp;
char tmphex[HEX_SIZE(uint32_t) + 3];
if (c > 0xffff) {
BIO_snprintf(tmphex, sizeof tmphex, "\\W%08" PRIX32, c);
if (!io_ch(arg, tmphex, 10))
if (!maybe_write(out, tmphex, 10))
return -1;
return 10;
}
if (c > 0xff) {
BIO_snprintf(tmphex, sizeof tmphex, "\\U%04" PRIX32, c);
if (!io_ch(arg, tmphex, 6))
if (!maybe_write(out, tmphex, 6))
return -1;
return 6;
}
@@ -135,19 +125,19 @@ static int do_esc_char(uint32_t c, unsigned char flags, char *do_quotes,
if (chflgs & ASN1_STRFLGS_ESC_QUOTE) {
if (do_quotes)
*do_quotes = 1;
if (!io_ch(arg, &chtmp, 1))
if (!maybe_write(out, &chtmp, 1))
return -1;
return 1;
}
if (!io_ch(arg, "\\", 1))
if (!maybe_write(out, "\\", 1))
return -1;
if (!io_ch(arg, &chtmp, 1))
if (!maybe_write(out, &chtmp, 1))
return -1;
return 2;
}
if (chflgs & (ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB)) {
BIO_snprintf(tmphex, 11, "\\%02X", chtmp);
if (!io_ch(arg, tmphex, 3))
if (!maybe_write(out, tmphex, 3))
return -1;
return 3;
}
@@ -156,11 +146,11 @@ static int do_esc_char(uint32_t c, unsigned char flags, char *do_quotes,
* character itself: backslash.
*/
if (chtmp == '\\' && flags & ESC_FLAGS) {
if (!io_ch(arg, "\\\\", 2))
if (!maybe_write(out, "\\\\", 2))
return -1;
return 2;
}
if (!io_ch(arg, &chtmp, 1))
if (!maybe_write(out, &chtmp, 1))
return -1;
return 1;
}
@@ -175,8 +165,7 @@ static int do_esc_char(uint32_t c, unsigned char flags, char *do_quotes,
*/
static int do_buf(unsigned char *buf, int buflen,
int type, unsigned char flags, char *quotes, char_io *io_ch,
void *arg)
int type, unsigned char flags, char *quotes, BIO *out)
{
int i, outlen, len, charwidth;
unsigned char orflags, *p, *q;
@@ -208,6 +197,8 @@ static int do_buf(unsigned char *buf, int buflen,
orflags = CHARTYPE_FIRST_ESC_2253;
else
orflags = 0;
/* TODO(davidben): Replace this with |cbs_get_ucs2_be|, etc., to check
* for invalid codepoints. */
switch (charwidth) {
case 4:
c = ((uint32_t)*p++) << 24;
@@ -248,17 +239,14 @@ static int do_buf(unsigned char *buf, int buflen,
* otherwise each character will be > 0x7f and so the
* character will never be escaped on first and last.
*/
len =
do_esc_char(utfbuf[i], (unsigned char)(flags | orflags),
quotes, io_ch, arg);
len = do_esc_char(utfbuf[i], (unsigned char)(flags | orflags),
quotes, out);
if (len < 0)
return -1;
outlen += len;
}
} else {
len =
do_esc_char(c, (unsigned char)(flags | orflags), quotes,
io_ch, arg);
len = do_esc_char(c, (unsigned char)(flags | orflags), quotes, out);
if (len < 0)
return -1;
outlen += len;
@@ -269,19 +257,18 @@ static int do_buf(unsigned char *buf, int buflen,
/* This function hex dumps a buffer of characters */
static int do_hex_dump(char_io *io_ch, void *arg, unsigned char *buf,
int buflen)
static int do_hex_dump(BIO *out, unsigned char *buf, int buflen)
{
static const char hexdig[] = "0123456789ABCDEF";
unsigned char *p, *q;
char hextmp[2];
if (arg) {
if (out) {
p = buf;
q = buf + buflen;
while (p != q) {
hextmp[0] = hexdig[*p >> 4];
hextmp[1] = hexdig[*p & 0xf];
if (!io_ch(arg, hextmp, 2))
if (!maybe_write(out, hextmp, 2))
return -1;
p++;
}
@@ -292,41 +279,55 @@ static int do_hex_dump(char_io *io_ch, void *arg, unsigned char *buf,
/*
* "dump" a string. This is done when the type is unknown, or the flags
* request it. We can either dump the content octets or the entire DER
* encoding. This uses the RFC2253 #01234 format.
* encoding. This uses the RFC 2253 #01234 format.
*/
static int do_dump(unsigned long lflags, char_io *io_ch, void *arg,
ASN1_STRING *str)
static int do_dump(unsigned long lflags, BIO *out, const ASN1_STRING *str)
{
/*
* Placing the ASN1_STRING in a temp ASN1_TYPE allows the DER encoding to
* readily obtained
*/
ASN1_TYPE t;
unsigned char *der_buf, *p;
int outlen, der_len;
if (!io_ch(arg, "#", 1))
if (!maybe_write(out, "#", 1)) {
return -1;
}
/* If we don't dump DER encoding just dump content octets */
if (!(lflags & ASN1_STRFLGS_DUMP_DER)) {
outlen = do_hex_dump(io_ch, arg, str->data, str->length);
if (outlen < 0)
int outlen = do_hex_dump(out, str->data, str->length);
if (outlen < 0) {
return -1;
}
return outlen + 1;
}
/*
* Placing the ASN1_STRING in a temporary ASN1_TYPE allows the DER encoding
* to readily obtained.
*/
ASN1_TYPE t;
t.type = str->type;
t.value.ptr = (char *)str;
der_len = i2d_ASN1_TYPE(&t, NULL);
der_buf = OPENSSL_malloc(der_len);
if (!der_buf)
/* Negative INTEGER and ENUMERATED values are the only case where
* |ASN1_STRING| and |ASN1_TYPE| types do not match.
*
* TODO(davidben): There are also some type fields which, in |ASN1_TYPE|, do
* not correspond to |ASN1_STRING|. It is unclear whether those are allowed
* in |ASN1_STRING| at all, or what the space of allowed types is.
* |ASN1_item_ex_d2i| will never produce such a value so, for now, we say
* this is an invalid input. But this corner of the library in general
* should be more robust. */
if (t.type == V_ASN1_NEG_INTEGER) {
t.type = V_ASN1_INTEGER;
} else if (t.type == V_ASN1_NEG_ENUMERATED) {
t.type = V_ASN1_ENUMERATED;
}
t.value.asn1_string = (ASN1_STRING *)str;
unsigned char *der_buf = NULL;
int der_len = i2d_ASN1_TYPE(&t, &der_buf);
if (der_len < 0) {
return -1;
p = der_buf;
i2d_ASN1_TYPE(&t, &p);
outlen = do_hex_dump(io_ch, arg, der_buf, der_len);
}
int outlen = do_hex_dump(out, der_buf, der_len);
OPENSSL_free(der_buf);
if (outlen < 0)
if (outlen < 0) {
return -1;
}
return outlen + 1;
}
@@ -353,8 +354,7 @@ static const signed char tag2nbyte[] = {
* an error occurred.
*/
static int do_print_ex(char_io *io_ch, void *arg, unsigned long lflags,
ASN1_STRING *str)
int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str, unsigned long lflags)
{
int outlen, len;
int type;
@@ -372,7 +372,7 @@ static int do_print_ex(char_io *io_ch, void *arg, unsigned long lflags,
const char *tagname;
tagname = ASN1_tag2str(type);
outlen += strlen(tagname);
if (!io_ch(arg, tagname, outlen) || !io_ch(arg, ":", 1))
if (!maybe_write(out, tagname, outlen) || !maybe_write(out, ":", 1))
return -1;
outlen++;
}
@@ -396,7 +396,7 @@ static int do_print_ex(char_io *io_ch, void *arg, unsigned long lflags,
}
if (type == -1) {
len = do_dump(lflags, io_ch, arg, str);
len = do_dump(lflags, out, str);
if (len < 0)
return -1;
outlen += len;
@@ -415,219 +415,41 @@ static int do_print_ex(char_io *io_ch, void *arg, unsigned long lflags,
type |= BUF_TYPE_CONVUTF8;
}
len = do_buf(str->data, str->length, type, flags, &quotes, io_ch, NULL);
len = do_buf(str->data, str->length, type, flags, &quotes, NULL);
if (len < 0)
return -1;
outlen += len;
if (quotes)
outlen += 2;
if (!arg)
if (!out)
return outlen;
if (quotes && !io_ch(arg, "\"", 1))
if (quotes && !maybe_write(out, "\"", 1))
return -1;
if (do_buf(str->data, str->length, type, flags, NULL, io_ch, arg) < 0)
if (do_buf(str->data, str->length, type, flags, NULL, out) < 0)
return -1;
if (quotes && !io_ch(arg, "\"", 1))
if (quotes && !maybe_write(out, "\"", 1))
return -1;
return outlen;
}
/* Used for line indenting: print 'indent' spaces */
static int do_indent(char_io *io_ch, void *arg, int indent)
int ASN1_STRING_print_ex_fp(FILE *fp, const ASN1_STRING *str,
unsigned long flags)
{
int i;
for (i = 0; i < indent; i++)
if (!io_ch(arg, " ", 1))
return 0;
return 1;
}
#define FN_WIDTH_LN 25
#define FN_WIDTH_SN 10
static int do_name_ex(char_io *io_ch, void *arg, X509_NAME *n,
int indent, unsigned long flags)
{
int i, prev = -1, orflags, cnt;
int fn_opt, fn_nid;
ASN1_OBJECT *fn;
ASN1_STRING *val;
X509_NAME_ENTRY *ent;
char objtmp[80];
const char *objbuf;
int outlen, len;
const char *sep_dn, *sep_mv, *sep_eq;
int sep_dn_len, sep_mv_len, sep_eq_len;
if (indent < 0)
indent = 0;
outlen = indent;
if (!do_indent(io_ch, arg, indent))
return -1;
switch (flags & XN_FLAG_SEP_MASK) {
case XN_FLAG_SEP_MULTILINE:
sep_dn = "\n";
sep_dn_len = 1;
sep_mv = " + ";
sep_mv_len = 3;
break;
case XN_FLAG_SEP_COMMA_PLUS:
sep_dn = ",";
sep_dn_len = 1;
sep_mv = "+";
sep_mv_len = 1;
indent = 0;
break;
case XN_FLAG_SEP_CPLUS_SPC:
sep_dn = ", ";
sep_dn_len = 2;
sep_mv = " + ";
sep_mv_len = 3;
indent = 0;
break;
case XN_FLAG_SEP_SPLUS_SPC:
sep_dn = "; ";
sep_dn_len = 2;
sep_mv = " + ";
sep_mv_len = 3;
indent = 0;
break;
default:
return -1;
}
if (flags & XN_FLAG_SPC_EQ) {
sep_eq = " = ";
sep_eq_len = 3;
} else {
sep_eq = "=";
sep_eq_len = 1;
}
fn_opt = flags & XN_FLAG_FN_MASK;
cnt = X509_NAME_entry_count(n);
for (i = 0; i < cnt; i++) {
if (flags & XN_FLAG_DN_REV)
ent = X509_NAME_get_entry(n, cnt - i - 1);
else
ent = X509_NAME_get_entry(n, i);
if (prev != -1) {
if (prev == ent->set) {
if (!io_ch(arg, sep_mv, sep_mv_len))
return -1;
outlen += sep_mv_len;
} else {
if (!io_ch(arg, sep_dn, sep_dn_len))
return -1;
outlen += sep_dn_len;
if (!do_indent(io_ch, arg, indent))
return -1;
outlen += indent;
}
}
prev = ent->set;
fn = X509_NAME_ENTRY_get_object(ent);
val = X509_NAME_ENTRY_get_data(ent);
fn_nid = OBJ_obj2nid(fn);
if (fn_opt != XN_FLAG_FN_NONE) {
int objlen, fld_len;
if ((fn_opt == XN_FLAG_FN_OID) || (fn_nid == NID_undef)) {
OBJ_obj2txt(objtmp, sizeof objtmp, fn, 1);
fld_len = 0; /* XXX: what should this be? */
objbuf = objtmp;
} else {
if (fn_opt == XN_FLAG_FN_SN) {
fld_len = FN_WIDTH_SN;
objbuf = OBJ_nid2sn(fn_nid);
} else if (fn_opt == XN_FLAG_FN_LN) {
fld_len = FN_WIDTH_LN;
objbuf = OBJ_nid2ln(fn_nid);
} else {
fld_len = 0; /* XXX: what should this be? */
objbuf = "";
}
}
objlen = strlen(objbuf);
if (!io_ch(arg, objbuf, objlen))
return -1;
if ((objlen < fld_len) && (flags & XN_FLAG_FN_ALIGN)) {
if (!do_indent(io_ch, arg, fld_len - objlen))
return -1;
outlen += fld_len - objlen;
}
if (!io_ch(arg, sep_eq, sep_eq_len))
return -1;
outlen += objlen + sep_eq_len;
}
/*
* If the field name is unknown then fix up the DER dump flag. We
* might want to limit this further so it will DER dump on anything
* other than a few 'standard' fields.
*/
if ((fn_nid == NID_undef) && (flags & XN_FLAG_DUMP_UNKNOWN_FIELDS))
orflags = ASN1_STRFLGS_DUMP_ALL;
else
orflags = 0;
len = do_print_ex(io_ch, arg, flags | orflags, val);
if (len < 0)
BIO *bio = NULL;
if (fp != NULL) {
/* If |fp| is NULL, this function returns the number of bytes without
* writing. */
bio = BIO_new_fp(fp, BIO_NOCLOSE);
if (bio == NULL) {
return -1;
outlen += len;
}
}
return outlen;
int ret = ASN1_STRING_print_ex(bio, str, flags);
BIO_free(bio);
return ret;
}
/* Wrappers round the main functions */
int X509_NAME_print_ex(BIO *out, X509_NAME *nm, int indent,
unsigned long flags)
{
if (flags == XN_FLAG_COMPAT)
return X509_NAME_print(out, nm, indent);
return do_name_ex(send_bio_chars, out, nm, indent, flags);
}
#ifndef OPENSSL_NO_FP_API
int X509_NAME_print_ex_fp(FILE *fp, X509_NAME *nm, int indent,
unsigned long flags)
{
if (flags == XN_FLAG_COMPAT) {
BIO *btmp;
int ret;
btmp = BIO_new_fp(fp, BIO_NOCLOSE);
if (!btmp)
return -1;
ret = X509_NAME_print(btmp, nm, indent);
BIO_free(btmp);
return ret;
}
return do_name_ex(send_fp_chars, fp, nm, indent, flags);
}
#endif
int ASN1_STRING_print_ex(BIO *out, ASN1_STRING *str, unsigned long flags)
{
return do_print_ex(send_bio_chars, out, flags, str);
}
#ifndef OPENSSL_NO_FP_API
int ASN1_STRING_print_ex_fp(FILE *fp, ASN1_STRING *str, unsigned long flags)
{
return do_print_ex(send_fp_chars, fp, flags, str);
}
#endif
/*
* Utility function: convert any string type to UTF8, returns number of bytes
* in output string or a negative error code
*/
int ASN1_STRING_to_UTF8(unsigned char **out, ASN1_STRING *in)
int ASN1_STRING_to_UTF8(unsigned char **out, const ASN1_STRING *in)
{
ASN1_STRING stmp, *str = &stmp;
int mbflag, type, ret;
@@ -643,11 +465,186 @@ int ASN1_STRING_to_UTF8(unsigned char **out, ASN1_STRING *in)
stmp.data = NULL;
stmp.length = 0;
stmp.flags = 0;
ret =
ASN1_mbstring_copy(&str, in->data, in->length, mbflag,
B_ASN1_UTF8STRING);
ret = ASN1_mbstring_copy(&str, in->data, in->length, mbflag,
B_ASN1_UTF8STRING);
if (ret < 0)
return ret;
*out = stmp.data;
return stmp.length;
}
int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v)
{
int i, n;
char buf[80];
const char *p;
if (v == NULL)
return (0);
n = 0;
p = (const char *)v->data;
for (i = 0; i < v->length; i++) {
if ((p[i] > '~') || ((p[i] < ' ') &&
(p[i] != '\n') && (p[i] != '\r')))
buf[n] = '.';
else
buf[n] = p[i];
n++;
if (n >= 80) {
if (BIO_write(bp, buf, n) <= 0)
return (0);
n = 0;
}
}
if (n > 0)
if (BIO_write(bp, buf, n) <= 0)
return (0);
return (1);
}
int ASN1_TIME_print(BIO *bp, const ASN1_TIME *tm)
{
if (tm->type == V_ASN1_UTCTIME)
return ASN1_UTCTIME_print(bp, tm);
if (tm->type == V_ASN1_GENERALIZEDTIME)
return ASN1_GENERALIZEDTIME_print(bp, tm);
BIO_write(bp, "Bad time value", 14);
return (0);
}
static const char *const mon[12] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
int ASN1_GENERALIZEDTIME_print(BIO *bp, const ASN1_GENERALIZEDTIME *tm)
{
char *v;
int gmt = 0;
int i;
int y = 0, M = 0, d = 0, h = 0, m = 0, s = 0;
char *f = NULL;
int f_len = 0;
i = tm->length;
v = (char *)tm->data;
if (i < 12)
goto err;
if (v[i - 1] == 'Z')
gmt = 1;
for (i = 0; i < 12; i++)
if ((v[i] > '9') || (v[i] < '0'))
goto err;
y = (v[0] - '0') * 1000 + (v[1] - '0') * 100 + (v[2] - '0') * 10 + (v[3] -
'0');
M = (v[4] - '0') * 10 + (v[5] - '0');
if ((M > 12) || (M < 1))
goto err;
d = (v[6] - '0') * 10 + (v[7] - '0');
h = (v[8] - '0') * 10 + (v[9] - '0');
m = (v[10] - '0') * 10 + (v[11] - '0');
if (tm->length >= 14 &&
(v[12] >= '0') && (v[12] <= '9') &&
(v[13] >= '0') && (v[13] <= '9')) {
s = (v[12] - '0') * 10 + (v[13] - '0');
/* Check for fractions of seconds. */
if (tm->length >= 15 && v[14] == '.') {
int l = tm->length;
f = &v[14]; /* The decimal point. */
f_len = 1;
while (14 + f_len < l && f[f_len] >= '0' && f[f_len] <= '9')
++f_len;
}
}
if (BIO_printf(bp, "%s %2d %02d:%02d:%02d%.*s %d%s",
mon[M - 1], d, h, m, s, f_len, f, y,
(gmt) ? " GMT" : "") <= 0)
return (0);
else
return (1);
err:
BIO_write(bp, "Bad time value", 14);
return (0);
}
// consume_two_digits is a helper function for ASN1_UTCTIME_print. If |*v|,
// assumed to be |*len| bytes long, has two leading digits, updates |*out| with
// their value, updates |v| and |len|, and returns one. Otherwise, returns
// zero.
static int consume_two_digits(int* out, const char **v, int *len) {
if (*len < 2|| !isdigit((*v)[0]) || !isdigit((*v)[1])) {
return 0;
}
*out = ((*v)[0] - '0') * 10 + ((*v)[1] - '0');
*len -= 2;
*v += 2;
return 1;
}
// consume_zulu_timezone is a helper function for ASN1_UTCTIME_print. If |*v|,
// assumed to be |*len| bytes long, starts with "Z" then it updates |*v| and
// |*len| and returns one. Otherwise returns zero.
static int consume_zulu_timezone(const char **v, int *len) {
if (*len == 0 || (*v)[0] != 'Z') {
return 0;
}
*len -= 1;
*v += 1;
return 1;
}
int ASN1_UTCTIME_print(BIO *bp, const ASN1_UTCTIME *tm) {
const char *v = (const char *)tm->data;
int len = tm->length;
int Y = 0, M = 0, D = 0, h = 0, m = 0, s = 0;
// YYMMDDhhmm are required to be present.
if (!consume_two_digits(&Y, &v, &len) ||
!consume_two_digits(&M, &v, &len) ||
!consume_two_digits(&D, &v, &len) ||
!consume_two_digits(&h, &v, &len) ||
!consume_two_digits(&m, &v, &len)) {
goto err;
}
// https://tools.ietf.org/html/rfc5280, section 4.1.2.5.1, requires seconds
// to be present, but historically this code has forgiven its absence.
consume_two_digits(&s, &v, &len);
// https://tools.ietf.org/html/rfc5280, section 4.1.2.5.1, specifies this
// interpretation of the year.
if (Y < 50) {
Y += 2000;
} else {
Y += 1900;
}
if (M > 12 || M == 0) {
goto err;
}
if (D > 31 || D == 0) {
goto err;
}
if (h > 23 || m > 59 || s > 60) {
goto err;
}
// https://tools.ietf.org/html/rfc5280, section 4.1.2.5.1, requires the "Z"
// to be present, but historically this code has forgiven its absence.
const int is_gmt = consume_zulu_timezone(&v, &len);
// https://tools.ietf.org/html/rfc5280, section 4.1.2.5.1, does not permit
// the specification of timezones using the +hhmm / -hhmm syntax, which is
// the only other thing that might legitimately be found at the end.
if (len) {
goto err;
}
return BIO_printf(bp, "%s %2d %02d:%02d:%02d %d%s", mon[M - 1], D, h, m, s, Y,
is_gmt ? " GMT" : "") > 0;
err:
BIO_write(bp, "Bad time value", 14);
return 0;
}
+111 -158
View File
@@ -56,98 +56,68 @@
#include <CCryptoBoringSSL_asn1.h>
#include <stdlib.h> /* For bsearch */
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_obj.h>
#include <CCryptoBoringSSL_stack.h>
DEFINE_STACK_OF(ASN1_STRING_TABLE)
#include "../internal.h"
#include "../lhash/internal.h"
#include "internal.h"
static STACK_OF(ASN1_STRING_TABLE) *stable = NULL;
static void st_free(ASN1_STRING_TABLE *tbl);
/*
* This is the global mask for the mbstring functions: this is use to mask
* out certain types (such as BMPString and UTF8String) because certain
* software (e.g. Netscape) has problems with them.
*/
DEFINE_LHASH_OF(ASN1_STRING_TABLE)
static unsigned long global_mask = B_ASN1_UTF8STRING;
static LHASH_OF(ASN1_STRING_TABLE) *string_tables = NULL;
static struct CRYPTO_STATIC_MUTEX string_tables_lock = CRYPTO_STATIC_MUTEX_INIT;
void ASN1_STRING_set_default_mask(unsigned long mask)
{
global_mask = mask;
}
unsigned long ASN1_STRING_get_default_mask(void)
{
return global_mask;
return B_ASN1_UTF8STRING;
}
/*
* This function sets the default to various "flavours" of configuration.
* based on an ASCII string. Currently this is: MASK:XXXX : a numerical mask
* value. nobmp : Don't use BMPStrings (just Printable, T61). pkix : PKIX
* recommendation in RFC2459. utf8only : only use UTF8Strings (RFC2459
* recommendation for 2004). default: the default value, Printable, T61, BMP.
*/
int ASN1_STRING_set_default_mask_asc(const char *p)
{
unsigned long mask;
char *end;
if (!strncmp(p, "MASK:", 5)) {
if (!p[5])
return 0;
mask = strtoul(p + 5, &end, 0);
if (*end)
return 0;
} else if (!strcmp(p, "nombstr"))
mask = ~((unsigned long)(B_ASN1_BMPSTRING | B_ASN1_UTF8STRING));
else if (!strcmp(p, "pkix"))
mask = ~((unsigned long)B_ASN1_T61STRING);
else if (!strcmp(p, "utf8only"))
mask = B_ASN1_UTF8STRING;
else if (!strcmp(p, "default"))
mask = 0xFFFFFFFFL;
else
return 0;
ASN1_STRING_set_default_mask(mask);
return 1;
}
static const ASN1_STRING_TABLE *asn1_string_table_get(int nid);
/*
* The following function generates an ASN1_STRING based on limits in a
* table. Frequently the types and length of an ASN1_STRING are restricted by
* a corresponding OID. For example certificates and certificate requests.
*/
ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out,
const unsigned char *in, int inlen,
int inform, int nid)
ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, const unsigned char *in,
int len, int inform, int nid)
{
ASN1_STRING_TABLE *tbl;
ASN1_STRING *str = NULL;
unsigned long mask;
int ret;
if (!out)
if (!out) {
out = &str;
tbl = ASN1_STRING_TABLE_get(nid);
if (tbl) {
mask = tbl->mask;
if (!(tbl->flags & STABLE_NO_MASK))
mask &= global_mask;
ret = ASN1_mbstring_ncopy(out, in, inlen, inform, mask,
tbl->minsize, tbl->maxsize);
} else
ret =
ASN1_mbstring_copy(out, in, inlen, inform,
DIRSTRING_TYPE & global_mask);
if (ret <= 0)
}
const ASN1_STRING_TABLE *tbl = asn1_string_table_get(nid);
if (tbl != NULL) {
unsigned long mask = tbl->mask;
if (!(tbl->flags & STABLE_NO_MASK)) {
mask &= B_ASN1_UTF8STRING;
}
ret = ASN1_mbstring_ncopy(out, in, len, inform, mask, tbl->minsize,
tbl->maxsize);
} else {
ret = ASN1_mbstring_copy(out, in, len, inform, B_ASN1_UTF8STRING);
}
if (ret <= 0) {
return NULL;
}
return *out;
}
@@ -155,15 +125,13 @@ ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out,
* Now the tables and helper functions for the string table:
*/
/* size limits: this stuff is taken straight from RFC3280 */
/* See RFC 5280. */
#define ub_name 32768
#define ub_common_name 64
#define ub_locality_name 128
#define ub_state_name 128
#define ub_organization_name 64
#define ub_organization_unit_name 64
#define ub_title 64
#define ub_email_address 128
#define ub_serial_number 64
@@ -194,120 +162,105 @@ static const ASN1_STRING_TABLE tbl_standard[] = {
{NID_ms_csp_name, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK}
};
static int sk_table_cmp(const ASN1_STRING_TABLE **a,
const ASN1_STRING_TABLE **b)
static int table_cmp(const ASN1_STRING_TABLE *a, const ASN1_STRING_TABLE *b)
{
return (*a)->nid - (*b)->nid;
if (a->nid < b->nid) {
return -1;
}
if (a->nid > b->nid) {
return 1;
}
return 0;
}
static int table_cmp(const void *in_a, const void *in_b)
static int table_cmp_void(const void *a, const void *b)
{
const ASN1_STRING_TABLE *a = in_a;
const ASN1_STRING_TABLE *b = in_b;
return a->nid - b->nid;
return table_cmp(a, b);
}
ASN1_STRING_TABLE *ASN1_STRING_TABLE_get(int nid)
static uint32_t table_hash(const ASN1_STRING_TABLE *tbl)
{
int found;
size_t idx;
ASN1_STRING_TABLE *ttmp;
ASN1_STRING_TABLE fnd;
fnd.nid = nid;
ttmp =
bsearch(&fnd, tbl_standard,
sizeof(tbl_standard) / sizeof(ASN1_STRING_TABLE),
sizeof(ASN1_STRING_TABLE), table_cmp);
if (ttmp)
return ttmp;
if (!stable)
return NULL;
sk_ASN1_STRING_TABLE_sort(stable);
found = sk_ASN1_STRING_TABLE_find(stable, &idx, &fnd);
if (!found)
return NULL;
return sk_ASN1_STRING_TABLE_value(stable, idx);
return OPENSSL_hash32(&tbl->nid, sizeof(tbl->nid));
}
int ASN1_STRING_TABLE_add(int nid,
long minsize, long maxsize, unsigned long mask,
unsigned long flags)
static const ASN1_STRING_TABLE *asn1_string_table_get(int nid)
{
ASN1_STRING_TABLE *tmp;
char new_nid = 0;
flags &= ~STABLE_FLAGS_MALLOC;
if (!stable)
stable = sk_ASN1_STRING_TABLE_new(sk_table_cmp);
if (!stable) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
ASN1_STRING_TABLE key;
key.nid = nid;
const ASN1_STRING_TABLE *tbl =
bsearch(&key, tbl_standard, OPENSSL_ARRAY_SIZE(tbl_standard),
sizeof(ASN1_STRING_TABLE), table_cmp_void);
if (tbl != NULL) {
return tbl;
}
CRYPTO_STATIC_MUTEX_lock_read(&string_tables_lock);
if (string_tables != NULL) {
tbl = lh_ASN1_STRING_TABLE_retrieve(string_tables, &key);
}
CRYPTO_STATIC_MUTEX_unlock_read(&string_tables_lock);
/* Note returning |tbl| without the lock is only safe because
* |ASN1_STRING_TABLE_add| cannot modify or delete existing entries. If we
* wish to support that, this function must copy the result under a lock. */
return tbl;
}
int ASN1_STRING_TABLE_add(int nid, long minsize, long maxsize,
unsigned long mask, unsigned long flags)
{
/* Existing entries cannot be overwritten. */
if (asn1_string_table_get(nid) != NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
if (!(tmp = ASN1_STRING_TABLE_get(nid))) {
tmp = OPENSSL_malloc(sizeof(ASN1_STRING_TABLE));
if (!tmp) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return 0;
int ret = 0;
CRYPTO_STATIC_MUTEX_lock_write(&string_tables_lock);
if (string_tables == NULL) {
string_tables = lh_ASN1_STRING_TABLE_new(table_hash, table_cmp);
if (string_tables == NULL) {
goto err;
}
tmp->flags = flags | STABLE_FLAGS_MALLOC;
tmp->nid = nid;
tmp->minsize = tmp->maxsize = -1;
new_nid = 1;
} else
tmp->flags = (tmp->flags & STABLE_FLAGS_MALLOC) | flags;
if (minsize != -1)
tmp->minsize = minsize;
if (maxsize != -1)
tmp->maxsize = maxsize;
tmp->mask = mask;
if (new_nid)
sk_ASN1_STRING_TABLE_push(stable, tmp);
return 1;
} else {
/* Check again for an existing entry. One may have been added while
* unlocked. */
ASN1_STRING_TABLE key;
key.nid = nid;
if (lh_ASN1_STRING_TABLE_retrieve(string_tables, &key) != NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
goto err;
}
}
ASN1_STRING_TABLE *tbl = OPENSSL_malloc(sizeof(ASN1_STRING_TABLE));
if (tbl == NULL) {
goto err;
}
tbl->nid = nid;
tbl->flags = flags;
tbl->minsize = minsize;
tbl->maxsize = maxsize;
tbl->mask = mask;
ASN1_STRING_TABLE *old_tbl;
if (!lh_ASN1_STRING_TABLE_insert(string_tables, &old_tbl, tbl)) {
OPENSSL_free(tbl);
goto err;
}
assert(old_tbl == NULL);
ret = 1;
err:
CRYPTO_STATIC_MUTEX_unlock_write(&string_tables_lock);
return ret;
}
void ASN1_STRING_TABLE_cleanup(void)
{
STACK_OF(ASN1_STRING_TABLE) *tmp;
tmp = stable;
if (!tmp)
return;
stable = NULL;
sk_ASN1_STRING_TABLE_pop_free(tmp, st_free);
}
static void st_free(ASN1_STRING_TABLE *tbl)
{
if (tbl->flags & STABLE_FLAGS_MALLOC)
OPENSSL_free(tbl);
void asn1_get_string_table_for_testing(const ASN1_STRING_TABLE **out_ptr,
size_t *out_len) {
*out_ptr = tbl_standard;
*out_len = OPENSSL_ARRAY_SIZE(tbl_standard);
}
#ifdef STRING_TABLE_TEST
int main(void)
{
ASN1_STRING_TABLE *tmp;
int i, last_nid = -1;
for (tmp = tbl_standard, i = 0;
i < sizeof(tbl_standard) / sizeof(ASN1_STRING_TABLE); i++, tmp++) {
if (tmp->nid < last_nid) {
last_nid = 0;
break;
}
last_nid = tmp->nid;
}
if (last_nid != 0) {
printf("Table order OK\n");
exit(0);
}
for (tmp = tbl_standard, i = 0;
i < sizeof(tbl_standard) / sizeof(ASN1_STRING_TABLE); i++, tmp++)
printf("Index %d, NID %d, Name=%s\n", i, tmp->nid,
OBJ_nid2ln(tmp->nid));
return 0;
}
#endif
@@ -63,7 +63,7 @@
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include "asn1_locl.h"
#include "internal.h"
/*
* This is an implementation of the ASN1 Time structure which is: Time ::=
@@ -73,7 +73,7 @@
IMPLEMENT_ASN1_MSTRING(ASN1_TIME, B_ASN1_TIME)
IMPLEMENT_ASN1_FUNCTIONS(ASN1_TIME)
IMPLEMENT_ASN1_FUNCTIONS_const(ASN1_TIME)
ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t t)
{
@@ -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;
@@ -200,7 +200,7 @@ static int asn1_time_to_tm(struct tm *tm, const ASN1_TIME *t)
return 0;
}
int ASN1_TIME_diff(int *pday, int *psec,
int ASN1_TIME_diff(int *out_days, int *out_seconds,
const ASN1_TIME *from, const ASN1_TIME *to)
{
struct tm tm_from, tm_to;
@@ -208,5 +208,5 @@ int ASN1_TIME_diff(int *pday, int *psec,
return 0;
if (!asn1_time_to_tm(&tm_to, to))
return 0;
return OPENSSL_gmtime_diff(pday, psec, &tm_from, &tm_to);
return OPENSSL_gmtime_diff(out_days, out_seconds, &tm_from, &tm_to);
}
+23 -11
View File
@@ -61,20 +61,33 @@
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_obj.h>
int ASN1_TYPE_get(ASN1_TYPE *a)
#include "internal.h"
int ASN1_TYPE_get(const ASN1_TYPE *a)
{
if ((a->value.ptr != NULL) || (a->type == V_ASN1_NULL))
return (a->type);
else
return (0);
if (a->type == V_ASN1_BOOLEAN || a->type == V_ASN1_NULL ||
a->value.ptr != NULL) {
return a->type;
}
return 0;
}
const void *asn1_type_value_as_pointer(const ASN1_TYPE *a)
{
if (a->type == V_ASN1_BOOLEAN) {
return a->value.boolean ? (void *)0xff : NULL;
}
if (a->type == V_ASN1_NULL) {
return NULL;
}
return a->value.ptr;
}
void ASN1_TYPE_set(ASN1_TYPE *a, int type, void *value)
{
if (a->value.ptr != NULL) {
ASN1_TYPE **tmp_a = &a;
ASN1_primitive_free((ASN1_VALUE **)tmp_a, NULL);
}
ASN1_TYPE **tmp_a = &a;
ASN1_primitive_free((ASN1_VALUE **)tmp_a, NULL);
a->type = type;
if (type == V_ASN1_BOOLEAN)
a->value.boolean = value ? 0xff : 0;
@@ -142,8 +155,7 @@ int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b)
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
default:
result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr,
(ASN1_STRING *)b->value.ptr);
result = ASN1_STRING_cmp(a->value.asn1_string, b->value.asn1_string);
break;
}
+3 -42
View File
@@ -62,7 +62,7 @@
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include "asn1_locl.h"
#include "internal.h"
int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d)
@@ -197,7 +197,7 @@ ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t,
if (s == NULL) {
free_s = 1;
s = M_ASN1_UTCTIME_new();
s = ASN1_UTCTIME_new();
}
if (s == NULL)
goto err;
@@ -234,7 +234,7 @@ ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t,
return (s);
err:
if (free_s && s)
M_ASN1_UTCTIME_free(s);
ASN1_UTCTIME_free(s);
return NULL;
}
@@ -262,42 +262,3 @@ int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t)
return -1;
return 0;
}
#if 0
time_t ASN1_UTCTIME_get(const ASN1_UTCTIME *s)
{
struct tm tm;
int offset;
OPENSSL_memset(&tm, '\0', sizeof tm);
# define g2(p) (((p)[0]-'0')*10+(p)[1]-'0')
tm.tm_year = g2(s->data);
if (tm.tm_year < 50)
tm.tm_year += 100;
tm.tm_mon = g2(s->data + 2) - 1;
tm.tm_mday = g2(s->data + 4);
tm.tm_hour = g2(s->data + 6);
tm.tm_min = g2(s->data + 8);
tm.tm_sec = g2(s->data + 10);
if (s->data[12] == 'Z')
offset = 0;
else {
offset = g2(s->data + 13) * 60 + g2(s->data + 15);
if (s->data[12] == '-')
offset = -offset;
}
# undef g2
return mktime(&tm) - offset * 60; /* FIXME: mktime assumes the current
* timezone instead of UTC, and unless
* we rewrite OpenSSL in Lisp we cannot
* locally change the timezone without
* possibly interfering with other
* parts of the program. timegm, which
* uses UTC, is non-standard. Also
* time_t is inappropriate for general
* UTC times because it may a 32 bit
* type. */
}
#endif
@@ -59,7 +59,7 @@
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include "asn1_locl.h"
#include "internal.h"
/* UTF8 utilities */
+75 -69
View File
@@ -64,6 +64,7 @@
#include <CCryptoBoringSSL_mem.h>
#include "../internal.h"
#include "internal.h"
/* Cross-module errors from crypto/x509/i2d_pr.c. */
@@ -103,8 +104,7 @@ OPENSSL_DECLARE_ERROR_REASON(ASN1, UNKNOWN_FORMAT)
OPENSSL_DECLARE_ERROR_REASON(ASN1, UNKNOWN_TAG)
OPENSSL_DECLARE_ERROR_REASON(ASN1, UNSUPPORTED_TYPE)
static int asn1_get_length(const unsigned char **pp, int *inf, long *rl,
long max);
static int asn1_get_length(const unsigned char **pp, long *rl, long max);
static void asn1_put_length(unsigned char **pp, int length);
int ASN1_get_object(const unsigned char **pp, long *plength, int *ptag,
@@ -113,7 +113,7 @@ int ASN1_get_object(const unsigned char **pp, long *plength, int *ptag,
int i, ret;
long l;
const unsigned char *p = *pp;
int tag, xclass, inf;
int tag, xclass;
long max = omax;
if (!max)
@@ -152,58 +152,43 @@ int ASN1_get_object(const unsigned char **pp, long *plength, int *ptag,
*ptag = tag;
*pclass = xclass;
if (!asn1_get_length(&p, &inf, plength, max))
if (!asn1_get_length(&p, plength, max))
goto err;
if (inf && !(ret & V_ASN1_CONSTRUCTED))
goto err;
#if 0
fprintf(stderr, "p=%d + *plength=%ld > omax=%ld + *pp=%d (%d > %d)\n",
(int)p, *plength, omax, (int)*pp, (int)(p + *plength),
(int)(omax + *pp));
#endif
if (*plength > (omax - (p - *pp))) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_TOO_LONG);
/*
* Set this so that even if things are not long enough the values are
* set correctly
*/
ret |= 0x80;
return 0x80;
}
*pp = p;
return (ret | inf);
return ret;
err:
OPENSSL_PUT_ERROR(ASN1, ASN1_R_HEADER_TOO_LONG);
return (0x80);
return 0x80;
}
static int asn1_get_length(const unsigned char **pp, int *inf, long *rl,
long max)
static int asn1_get_length(const unsigned char **pp, long *rl, long max)
{
const unsigned char *p = *pp;
unsigned long ret = 0;
unsigned long i;
if (max-- < 1)
if (max-- < 1) {
return 0;
}
if (*p == 0x80) {
*inf = 1;
ret = 0;
p++;
/* We do not support BER indefinite-length encoding. */
return 0;
}
i = *p & 0x7f;
if (*(p++) & 0x80) {
if (i > sizeof(ret) || max < (long)i)
return 0;
while (i-- > 0) {
ret <<= 8L;
ret |= *(p++);
}
} else {
*inf = 0;
i = *p & 0x7f;
if (*(p++) & 0x80) {
if (i > sizeof(ret) || max < (long)i)
return 0;
while (i-- > 0) {
ret <<= 8L;
ret |= *(p++);
}
} else
ret = i;
ret = i;
}
/*
* Bound the length to comfortably fit in an int. Lengths in this module
@@ -251,6 +236,8 @@ void ASN1_put_object(unsigned char **pp, int constructed, int length, int tag,
int ASN1_put_eoc(unsigned char **pp)
{
/* This function is no longer used in the library, but some external code
* uses it. */
unsigned char *p = *pp;
*p++ = 0;
*p++ = 0;
@@ -311,9 +298,9 @@ int ASN1_STRING_copy(ASN1_STRING *dst, const ASN1_STRING *str)
{
if (str == NULL)
return 0;
dst->type = str->type;
if (!ASN1_STRING_set(dst, str->data, str->length))
return 0;
dst->type = str->type;
dst->flags = str->flags;
return 1;
}
@@ -368,8 +355,7 @@ int ASN1_STRING_set(ASN1_STRING *str, const void *_data, int len)
void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len)
{
if (str->data)
OPENSSL_free(str->data);
OPENSSL_free(str->data);
str->data = data;
str->length = len;
}
@@ -395,52 +381,72 @@ ASN1_STRING *ASN1_STRING_type_new(int type)
return (ret);
}
void ASN1_STRING_free(ASN1_STRING *a)
void ASN1_STRING_free(ASN1_STRING *str)
{
if (a == NULL)
if (str == NULL)
return;
if (a->data && !(a->flags & ASN1_STRING_FLAG_NDEF))
OPENSSL_free(a->data);
OPENSSL_free(a);
OPENSSL_free(str->data);
OPENSSL_free(str);
}
int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b)
{
int i;
/* Capture padding bits and implicit truncation in BIT STRINGs. */
int a_length = a->length, b_length = b->length;
uint8_t a_padding = 0, b_padding = 0;
if (a->type == V_ASN1_BIT_STRING) {
a_length = asn1_bit_string_length(a, &a_padding);
}
if (b->type == V_ASN1_BIT_STRING) {
b_length = asn1_bit_string_length(b, &b_padding);
}
i = (a->length - b->length);
if (i == 0) {
i = OPENSSL_memcmp(a->data, b->data, a->length);
if (i == 0)
return (a->type - b->type);
else
return (i);
} else
return (i);
if (a_length < b_length) {
return -1;
}
if (a_length > b_length) {
return 1;
}
/* In a BIT STRING, the number of bits is 8 * length - padding. Invert this
* comparison so we compare by lengths. */
if (a_padding > b_padding) {
return -1;
}
if (a_padding < b_padding) {
return 1;
}
int ret = OPENSSL_memcmp(a->data, b->data, a_length);
if (ret != 0) {
return ret;
}
/* Comparing the type first is more natural, but this matches OpenSSL. */
if (a->type < b->type) {
return -1;
}
if (a->type > b->type) {
return 1;
}
return 0;
}
int ASN1_STRING_length(const ASN1_STRING *x)
int ASN1_STRING_length(const ASN1_STRING *str)
{
return M_ASN1_STRING_length(x);
return str->length;
}
void ASN1_STRING_length_set(ASN1_STRING *x, int len)
int ASN1_STRING_type(const ASN1_STRING *str)
{
M_ASN1_STRING_length_set(x, len);
return;
return str->type;
}
int ASN1_STRING_type(ASN1_STRING *x)
unsigned char *ASN1_STRING_data(ASN1_STRING *str)
{
return M_ASN1_STRING_type(x);
return str->data;
}
unsigned char *ASN1_STRING_data(ASN1_STRING *x)
const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *str)
{
return M_ASN1_STRING_data(x);
}
const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *x)
{
return x->data;
return str->data;
}
@@ -1,104 +0,0 @@
/* asn1t.h */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 2006.
*/
/* ====================================================================
* Copyright (c) 2006 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#ifndef OPENSSL_HEADER_ASN1_ASN1_LOCL_H
#define OPENSSL_HEADER_ASN1_ASN1_LOCL_H
#include <time.h>
#include <CCryptoBoringSSL_asn1.h>
#if defined(__cplusplus)
extern "C" {
#endif
/* Wrapper functions for time functions. */
/* OPENSSL_gmtime wraps |gmtime_r|. See the manual page for that function. */
struct tm *OPENSSL_gmtime(const time_t *time, struct tm *result);
/* OPENSSL_gmtime_adj updates |tm| by adding |offset_day| days and |offset_sec|
* seconds. */
int OPENSSL_gmtime_adj(struct tm *tm, int offset_day, long offset_sec);
/* OPENSSL_gmtime_diff calculates the difference between |from| and |to| and
* outputs the difference as a number of days and seconds in |*out_days| and
* |*out_secs|. */
int OPENSSL_gmtime_diff(int *out_days, int *out_secs, const struct tm *from,
const struct tm *to);
/* Internal ASN1 structures and functions: not for application use */
int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d);
int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d);
void asn1_item_combine_free(ASN1_VALUE **pval, const ASN1_ITEM *it,
int combine);
int UTF8_getc(const unsigned char *str, int len, uint32_t *val);
int UTF8_putc(unsigned char *str, int len, uint32_t value);
#if defined(__cplusplus)
} /* extern C */
#endif
#endif /* OPENSSL_HEADER_ASN1_ASN1_LOCL_H */
@@ -72,7 +72,7 @@ const char *ASN1_tag2str(int tag)
};
if ((tag == V_ASN1_NEG_INTEGER) || (tag == V_ASN1_NEG_ENUMERATED))
tag &= ~0x100;
tag &= ~V_ASN1_NEG;
if (tag < 0 || tag > 30)
return "(unknown)";
+31 -35
View File
@@ -59,47 +59,43 @@
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
/* ASN1_ITEM versions of the above */
ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, ASN1_STRING **oct)
ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, ASN1_STRING **out)
{
ASN1_STRING *octmp;
if (!oct || !*oct) {
if (!(octmp = ASN1_STRING_new())) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return NULL;
}
if (oct)
*oct = octmp;
} else
octmp = *oct;
if (octmp->data) {
OPENSSL_free(octmp->data);
octmp->data = NULL;
}
if (!(octmp->length = ASN1_item_i2d(obj, &octmp->data, it))) {
uint8_t *new_data = NULL;
int len = ASN1_item_i2d(obj, &new_data, it);
if (len <= 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ENCODE_ERROR);
return NULL;
}
if (!octmp->data) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return NULL;
ASN1_STRING *ret = NULL;
if (out == NULL || *out == NULL) {
ret = ASN1_STRING_new();
if (ret == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
OPENSSL_free(new_data);
return NULL;
}
} else {
ret = *out;
}
return octmp;
}
/* Extract an ASN1 object from an ASN1_STRING */
void *ASN1_item_unpack(ASN1_STRING *oct, const ASN1_ITEM *it)
{
const unsigned char *p;
void *ret;
p = oct->data;
if (!(ret = ASN1_item_d2i(NULL, &p, oct->length, it)))
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
ASN1_STRING_set0(ret, new_data, len);
if (out != NULL) {
*out = ret;
}
return ret;
}
void *ASN1_item_unpack(const ASN1_STRING *oct, const ASN1_ITEM *it)
{
const unsigned char *p = oct->data;
void *ret = ASN1_item_d2i(NULL, &p, oct->length, it);
if (ret == NULL || p != oct->data + oct->length) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
ASN1_item_free(ret, it);
return NULL;
}
return ret;
}
+6 -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";
@@ -95,3 +95,8 @@ int i2a_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *a)
err:
return (-1);
}
int i2a_ASN1_ENUMERATED(BIO *bp, const ASN1_ENUMERATED *a)
{
return i2a_ASN1_INTEGER(bp, a);
}
@@ -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";
@@ -0,0 +1,224 @@
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 2006.
*/
/* ====================================================================
* Copyright (c) 2006 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#ifndef OPENSSL_HEADER_ASN1_ASN1_LOCL_H
#define OPENSSL_HEADER_ASN1_ASN1_LOCL_H
#include <time.h>
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_asn1t.h>
#if defined(__cplusplus)
extern "C" {
#endif
/* Wrapper functions for time functions. */
/* OPENSSL_gmtime wraps |gmtime_r|. See the manual page for that function. */
struct tm *OPENSSL_gmtime(const time_t *time, struct tm *result);
/* OPENSSL_gmtime_adj updates |tm| by adding |offset_day| days and |offset_sec|
* seconds. */
int OPENSSL_gmtime_adj(struct tm *tm, int offset_day, long offset_sec);
/* OPENSSL_gmtime_diff calculates the difference between |from| and |to| and
* outputs the difference as a number of days and seconds in |*out_days| and
* |*out_secs|. */
int OPENSSL_gmtime_diff(int *out_days, int *out_secs, const struct tm *from,
const struct tm *to);
/* Internal ASN1 structures and functions: not for application use */
/* These are used internally in the ASN1_OBJECT to keep track of
* whether the names and data need to be free()ed */
#define ASN1_OBJECT_FLAG_DYNAMIC 0x01 /* internal use */
#define ASN1_OBJECT_FLAG_DYNAMIC_STRINGS 0x04 /* internal use */
#define ASN1_OBJECT_FLAG_DYNAMIC_DATA 0x08 /* internal use */
/* An asn1_object_st (aka |ASN1_OBJECT|) represents an ASN.1 OBJECT IDENTIFIER.
* Note: Mutating an |ASN1_OBJECT| is only permitted when initializing it. The
* library maintains a table of static |ASN1_OBJECT|s, which may be referenced
* by non-const |ASN1_OBJECT| pointers. Code which receives an |ASN1_OBJECT|
* pointer externally must assume it is immutable, even if the pointer is not
* const. */
struct asn1_object_st {
const char *sn, *ln;
int nid;
int length;
const unsigned char *data; /* data remains const after init */
int flags; /* Should we free this one */
};
ASN1_OBJECT *ASN1_OBJECT_new(void);
// ASN1_ENCODING structure: this is used to save the received
// encoding of an ASN1 type. This is useful to get round
// problems with invalid encodings which can break signatures.
typedef struct ASN1_ENCODING_st {
unsigned char *enc; // DER encoding
long len; // Length of encoding
int modified; // set to 1 if 'enc' is invalid
// alias_only is zero if |enc| owns the buffer that it points to
// (although |enc| may still be NULL). If one, |enc| points into a
// buffer that is owned elsewhere.
unsigned alias_only : 1;
// alias_only_on_next_parse is one iff the next parsing operation
// should avoid taking a copy of the input and rather set
// |alias_only|.
unsigned alias_only_on_next_parse : 1;
} ASN1_ENCODING;
int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d);
int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d);
void asn1_item_combine_free(ASN1_VALUE **pval, const ASN1_ITEM *it,
int combine);
int UTF8_getc(const unsigned char *str, int len, uint32_t *val);
int UTF8_putc(unsigned char *str, int len, uint32_t value);
int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it);
void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
void ASN1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt);
int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
const ASN1_ITEM *it, int tag, int aclass, char opt,
ASN1_TLC *ctx);
/* ASN1_item_ex_i2d encodes |*pval| as a value of type |it| to |out| under the
* i2d output convention. It returns a non-zero length on success and -1 on
* error. If |tag| is -1. the tag and class come from |it|. Otherwise, the tag
* number is |tag| and the class is |aclass|. This is used for implicit tagging.
* This function treats a missing value as an error, not an optional field. */
int ASN1_item_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass);
void ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
/* asn1_get_choice_selector returns the CHOICE selector value for |*pval|, which
* must of type |it|. */
int asn1_get_choice_selector(ASN1_VALUE **pval, const ASN1_ITEM *it);
int asn1_set_choice_selector(ASN1_VALUE **pval, int value, const ASN1_ITEM *it);
/* asn1_get_field_ptr returns a pointer to the field in |*pval| corresponding to
* |tt|. */
ASN1_VALUE **asn1_get_field_ptr(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt);
/* asn1_do_adb returns the |ASN1_TEMPLATE| for the ANY DEFINED BY field |tt|,
* based on the selector INTEGER or OID in |*pval|. If |tt| is not an ADB field,
* it returns |tt|. If the selector does not match any value, it returns NULL.
* If |nullerr| is non-zero, it will additionally push an error to the error
* queue when there is no match. */
const ASN1_TEMPLATE *asn1_do_adb(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt,
int nullerr);
void asn1_refcount_set_one(ASN1_VALUE **pval, const ASN1_ITEM *it);
int asn1_refcount_dec_and_test_zero(ASN1_VALUE **pval, const ASN1_ITEM *it);
void asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it);
void asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
/* asn1_enc_restore, if |*pval| has a saved encoding, writes it to |out| under
* the i2d output convention, sets |*len| to the length, and returns one. If it
* has no saved encoding, it returns zero. */
int asn1_enc_restore(int *len, unsigned char **out, ASN1_VALUE **pval,
const ASN1_ITEM *it);
int asn1_enc_save(ASN1_VALUE **pval, const unsigned char *in, int inlen,
const ASN1_ITEM *it);
/* asn1_type_value_as_pointer returns |a|'s value in pointer form. This is
* usually the value object but, for BOOLEAN values, is 0 or 0xff cast to
* a pointer. */
const void *asn1_type_value_as_pointer(const ASN1_TYPE *a);
/* asn1_is_printable returns one if |value| is a valid Unicode codepoint for an
* ASN.1 PrintableString, and zero otherwise. */
int asn1_is_printable(uint32_t value);
/* asn1_bit_string_length returns the number of bytes in |str| and sets
* |*out_padding_bits| to the number of padding bits.
*
* This function should be used instead of |ASN1_STRING_length| to correctly
* handle the non-|ASN1_STRING_FLAG_BITS_LEFT| case. */
int asn1_bit_string_length(const ASN1_BIT_STRING *str,
uint8_t *out_padding_bits);
typedef struct {
int nid;
long minsize;
long maxsize;
unsigned long mask;
unsigned long flags;
} ASN1_STRING_TABLE;
/* asn1_get_string_table_for_testing sets |*out_ptr| and |*out_len| to the table
* of built-in |ASN1_STRING_TABLE| values. It is exported for testing. */
OPENSSL_EXPORT void asn1_get_string_table_for_testing(
const ASN1_STRING_TABLE **out_ptr, size_t *out_len);
#if defined(__cplusplus)
} /* extern C */
#endif
#endif /* OPENSSL_HEADER_ASN1_ASN1_LOCL_H */
+79 -354
View File
@@ -60,11 +60,11 @@
#include <string.h>
#include <CCryptoBoringSSL_asn1t.h>
#include <CCryptoBoringSSL_buf.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include "../internal.h"
#include "internal.h"
/*
* Constructed types with a recursive definition (such as can be found in PKCS7)
@@ -75,16 +75,9 @@
#define ASN1_MAX_CONSTRUCTED_NEST 30
static int asn1_check_eoc(const unsigned char **in, long len);
static int asn1_find_end(const unsigned char **in, long len, char inf);
static int asn1_collect(BUF_MEM *buf, const unsigned char **in, long len,
char inf, int tag, int aclass, int depth);
static int collect_data(BUF_MEM *buf, const unsigned char **p, long plen);
static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
char *inf, char *cst,
const unsigned char **in, long len,
char *cst, const unsigned char **in, long len,
int exptag, int expclass, char opt, ASN1_TLC *ctx);
static int asn1_template_ex_d2i(ASN1_VALUE **pval,
@@ -95,6 +88,8 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val,
const unsigned char **in, long len,
const ASN1_TEMPLATE *tt, char opt,
ASN1_TLC *ctx, int depth);
static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
int utype, const ASN1_ITEM *it);
static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
const unsigned char **in, long len,
const ASN1_ITEM *it,
@@ -166,27 +161,18 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
char opt, ASN1_TLC *ctx, int depth)
{
const ASN1_TEMPLATE *tt, *errtt = NULL;
const ASN1_COMPAT_FUNCS *cf;
const ASN1_EXTERN_FUNCS *ef;
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb;
const unsigned char *p = NULL, *q;
unsigned char *wp = NULL; /* BIG FAT WARNING! BREAKS CONST WHERE USED */
unsigned char imphack = 0, oclass;
char seq_eoc, seq_nolen, cst, isopt;
long tmplen;
unsigned char oclass;
char cst, isopt;
int i;
int otag;
int ret = 0;
ASN1_VALUE **pchptr, *ptmpval;
ASN1_VALUE **pchptr;
int combine = aclass & ASN1_TFLG_COMBINE;
aclass &= ~ASN1_TFLG_COMBINE;
if (!pval)
return 0;
if (aux && aux->asn1_cb)
asn1_cb = aux->asn1_cb;
else
asn1_cb = 0;
/*
* Bound |len| to comfortably fit in an int. Lengths in this module often
@@ -223,9 +209,18 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
break;
case ASN1_ITYPE_MSTRING:
/*
* It never makes sense for multi-strings to have implicit tagging, so
* if tag != -1, then this looks like an error in the template.
*/
if (tag != -1) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
goto err;
}
p = *in;
/* Just read in tag and class */
ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL,
ret = asn1_check_tlen(NULL, &otag, &oclass, NULL,
&p, len, -1, 0, 1, ctx);
if (!ret) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
@@ -255,67 +250,18 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
ef = it->funcs;
return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx);
case ASN1_ITYPE_COMPAT:
/* we must resort to old style evil hackery */
cf = it->funcs;
/* If OPTIONAL see if it is there */
if (opt) {
int exptag;
p = *in;
if (tag == -1)
exptag = it->utype;
else
exptag = tag;
/*
* Don't care about anything other than presence of expected tag
*/
ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL,
&p, len, exptag, aclass, 1, ctx);
if (!ret) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
goto err;
}
if (ret == -1)
return -1;
}
case ASN1_ITYPE_CHOICE: {
/*
* This is the old style evil hack IMPLICIT handling: since the
* underlying code is expecting a tag and class other than the one
* present we change the buffer temporarily then change it back
* afterwards. This doesn't and never did work for tags > 30. Yes
* this is *horrible* but it is only needed for old style d2i which
* will hopefully not be around for much longer. FIXME: should copy
* the buffer then modify it so the input buffer can be const: we
* should *always* copy because the old style d2i might modify the
* buffer.
* It never makes sense for CHOICE types to have implicit tagging, so if
* tag != -1, then this looks like an error in the template.
*/
if (tag != -1) {
wp = *(unsigned char **)in;
imphack = *wp;
if (p == NULL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
goto err;
}
*wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED)
| it->utype);
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
goto err;
}
ptmpval = cf->asn1_d2i(pval, in, len);
if (tag != -1)
*wp = imphack;
if (ptmpval)
return 1;
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
goto err;
case ASN1_ITYPE_CHOICE:
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
@@ -369,11 +315,10 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
goto auxerr;
*in = p;
return 1;
}
case ASN1_ITYPE_NDEF_SEQUENCE:
case ASN1_ITYPE_SEQUENCE:
case ASN1_ITYPE_SEQUENCE: {
p = *in;
tmplen = len;
/* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */
if (tag == -1) {
@@ -381,20 +326,13 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
aclass = V_ASN1_UNIVERSAL;
}
/* Get SEQUENCE length and update len, p */
ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst,
ret = asn1_check_tlen(&len, NULL, NULL, &cst,
&p, len, tag, aclass, opt, ctx);
if (!ret) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
goto err;
} else if (ret == -1)
return -1;
if (aux && (aux->flags & ASN1_AFLG_BROKEN)) {
len = tmplen - (p - *in);
seq_nolen = 1;
}
/* If indefinite we don't do a length check */
else
seq_nolen = seq_eoc;
if (!cst) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
goto err;
@@ -405,6 +343,8 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
goto err;
}
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
goto auxerr;
@@ -433,15 +373,12 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
if (!len)
break;
q = p;
/* TODO(https://crbug.com/boringssl/455): Although we've removed
* indefinite-length support, this check is not quite a no-op.
* Reject [UNIVERSAL 0] in the tag parsers themselves. */
if (asn1_check_eoc(&p, len)) {
if (!seq_eoc) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_UNEXPECTED_EOC);
goto err;
}
len -= p - q;
seq_eoc = 0;
q = p;
break;
OPENSSL_PUT_ERROR(ASN1, ASN1_R_UNEXPECTED_EOC);
goto err;
}
/*
* This determines the OPTIONAL flag value. The field cannot be
@@ -473,13 +410,8 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
len -= p - q;
}
/* Check for EOC if expecting one */
if (seq_eoc && !asn1_check_eoc(&p, len)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_EOC);
goto err;
}
/* Check all data read */
if (!seq_nolen && len) {
if (len) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_SEQUENCE_LENGTH_MISMATCH);
goto err;
}
@@ -511,6 +443,7 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
goto auxerr;
*in = p;
return 1;
}
default:
return 0;
@@ -549,7 +482,6 @@ static int asn1_template_ex_d2i(ASN1_VALUE **val,
int ret;
long len;
const unsigned char *p, *q;
char exp_eoc;
if (!val)
return 0;
flags = tt->flags;
@@ -564,7 +496,7 @@ static int asn1_template_ex_d2i(ASN1_VALUE **val,
* Need to work out amount of data available to the inner content and
* where it starts: so read in EXPLICIT header to get the info.
*/
ret = asn1_check_tlen(&len, NULL, NULL, &exp_eoc, &cst,
ret = asn1_check_tlen(&len, NULL, NULL, &cst,
&p, inlen, tt->tag, aclass, opt, ctx);
q = p;
if (!ret) {
@@ -584,20 +516,10 @@ static int asn1_template_ex_d2i(ASN1_VALUE **val,
}
/* We read the field in OK so update length */
len -= p - q;
if (exp_eoc) {
/* If NDEF we must have an EOC here */
if (!asn1_check_eoc(&p, len)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_EOC);
goto err;
}
} else {
/*
* Otherwise we must hit the EXPLICIT tag end or its an error
*/
if (len) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_EXPLICIT_LENGTH_MISMATCH);
goto err;
}
/* Check for trailing data. */
if (len) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_EXPLICIT_LENGTH_MISMATCH);
goto err;
}
} else
return asn1_template_noexp_d2i(val, in, inlen, tt, opt, ctx, depth);
@@ -628,7 +550,6 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val,
if (flags & ASN1_TFLG_SK_MASK) {
/* SET OF, SEQUENCE OF */
int sktag, skaclass;
char sk_eoc;
/* First work out expected inner tag value */
if (flags & ASN1_TFLG_IMPTAG) {
sktag = tt->tag;
@@ -641,7 +562,7 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val,
sktag = V_ASN1_SEQUENCE;
}
/* Get the tag */
ret = asn1_check_tlen(&len, NULL, NULL, &sk_eoc, NULL,
ret = asn1_check_tlen(&len, NULL, NULL, NULL,
&p, len, sktag, skaclass, opt, ctx);
if (!ret) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
@@ -649,7 +570,7 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val,
} else if (ret == -1)
return -1;
if (!*val)
*val = (ASN1_VALUE *)sk_new_null();
*val = (ASN1_VALUE *)sk_ASN1_VALUE_new_null();
else {
/*
* We've got a valid STACK: free up any items present
@@ -671,15 +592,12 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val,
while (len > 0) {
ASN1_VALUE *skfield;
const unsigned char *q = p;
/* See if EOC found */
/* TODO(https://crbug.com/boringssl/455): Although we've removed
* indefinite-length support, this check is not quite a no-op.
* Reject [UNIVERSAL 0] in the tag parsers themselves. */
if (asn1_check_eoc(&p, len)) {
if (!sk_eoc) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_UNEXPECTED_EOC);
goto err;
}
len -= p - q;
sk_eoc = 0;
break;
OPENSSL_PUT_ERROR(ASN1, ASN1_R_UNEXPECTED_EOC);
goto err;
}
skfield = NULL;
if (!asn1_item_ex_d2i(&skfield, &p, len, ASN1_ITEM_ptr(tt->item),
@@ -694,10 +612,6 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val,
goto err;
}
}
if (sk_eoc) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_EOC);
goto err;
}
} else if (flags & ASN1_TFLG_IMPTAG) {
/* IMPLICIT tagging */
ret = asn1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), tt->tag,
@@ -734,9 +648,8 @@ static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
{
int ret = 0, utype;
long plen;
char cst, inf, free_cont = 0;
char cst;
const unsigned char *p;
BUF_MEM buf = {0, NULL, 0 };
const unsigned char *cont = NULL;
long len;
if (!pval) {
@@ -762,7 +675,7 @@ static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
return 0;
}
p = *in;
ret = asn1_check_tlen(NULL, &utype, &oclass, NULL, NULL,
ret = asn1_check_tlen(NULL, &utype, &oclass, NULL,
&p, inlen, -1, 0, 0, ctx);
if (!ret) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
@@ -777,7 +690,7 @@ static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
}
p = *in;
/* Check header */
ret = asn1_check_tlen(&plen, NULL, NULL, &inf, &cst,
ret = asn1_check_tlen(&plen, NULL, NULL, &cst,
&p, inlen, tag, aclass, opt, ctx);
if (!ret) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
@@ -802,43 +715,14 @@ static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
}
cont = *in;
/* If indefinite length constructed find the real end */
if (inf) {
if (!asn1_find_end(&p, plen, inf))
goto err;
len = p - cont;
} else {
len = p - cont + plen;
p += plen;
}
len = p - cont + plen;
p += plen;
} else if (cst) {
if (utype == V_ASN1_NULL || utype == V_ASN1_BOOLEAN
|| utype == V_ASN1_OBJECT || utype == V_ASN1_INTEGER
|| utype == V_ASN1_ENUMERATED) {
/* These types only have primitive encodings. */
OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_PRIMITIVE);
return 0;
}
/* Free any returned 'buf' content */
free_cont = 1;
/*
* Should really check the internal tags are correct but some things
* may get this wrong. The relevant specs say that constructed string
* types should be OCTET STRINGs internally irrespective of the type.
* So instead just check for UNIVERSAL class and ignore the tag.
*/
if (!asn1_collect(&buf, &p, plen, inf, -1, V_ASN1_UNIVERSAL, 0)) {
goto err;
}
len = buf.length;
/* Append a final null to string */
if (!BUF_MEM_grow_clean(&buf, len + 1)) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
buf.data[len] = 0;
cont = (const unsigned char *)buf.data;
/* This parser historically supported BER constructed strings. We no
* longer do and will gradually tighten this parser into a DER
* parser. BER types should use |CBS_asn1_ber_to_der|. */
OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_PRIMITIVE);
return 0;
} else {
cont = p;
len = plen;
@@ -846,33 +730,30 @@ static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
}
/* We now have content length and type: translate into a structure */
/* asn1_ex_c2i may reuse allocated buffer, and so sets free_cont to 0 */
if (!asn1_ex_c2i(pval, cont, len, utype, &free_cont, it))
if (!asn1_ex_c2i(pval, cont, len, utype, it))
goto err;
*in = p;
ret = 1;
err:
if (free_cont && buf.data)
OPENSSL_free(buf.data);
return ret;
}
/* Translate ASN1 content octets into a structure */
int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
int utype, char *free_cont, const ASN1_ITEM *it)
static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
int utype, const ASN1_ITEM *it)
{
ASN1_VALUE **opval = NULL;
ASN1_STRING *stmp;
ASN1_TYPE *typ = NULL;
int ret = 0;
const ASN1_PRIMITIVE_FUNCS *pf;
ASN1_INTEGER **tint;
pf = it->funcs;
if (pf && pf->prim_c2i)
return pf->prim_c2i(pval, cont, len, utype, free_cont, it);
/* Historically, |it->funcs| for primitive types contained an
* |ASN1_PRIMITIVE_FUNCS| table of callbacks. */
assert(it->funcs == NULL);
/* If ANY type clear type and set pointer to internal value */
if (it->utype == V_ASN1_ANY) {
if (!*pval) {
@@ -965,20 +846,11 @@ int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
stmp = (ASN1_STRING *)*pval;
stmp->type = utype;
}
/* If we've already allocated a buffer use it */
if (*free_cont) {
if (stmp->data)
OPENSSL_free(stmp->data);
stmp->data = (unsigned char *)cont; /* UGLY CAST! RL */
stmp->length = len;
*free_cont = 0;
} else {
if (!ASN1_STRING_set(stmp, cont, len)) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
ASN1_STRING_free(stmp);
*pval = NULL;
goto err;
}
if (!ASN1_STRING_set(stmp, cont, len)) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
ASN1_STRING_free(stmp);
*pval = NULL;
goto err;
}
break;
}
@@ -996,147 +868,6 @@ int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
return ret;
}
/*
* This function finds the end of an ASN1 structure when passed its maximum
* length, whether it is indefinite length and a pointer to the content. This
* is more efficient than calling asn1_collect because it does not recurse on
* each indefinite length header.
*/
static int asn1_find_end(const unsigned char **in, long len, char inf)
{
int expected_eoc;
long plen;
const unsigned char *p = *in, *q;
/* If not indefinite length constructed just add length */
if (inf == 0) {
*in += len;
return 1;
}
expected_eoc = 1;
/*
* Indefinite length constructed form. Find the end when enough EOCs are
* found. If more indefinite length constructed headers are encountered
* increment the expected eoc count otherwise just skip to the end of the
* data.
*/
while (len > 0) {
if (asn1_check_eoc(&p, len)) {
expected_eoc--;
if (expected_eoc == 0)
break;
len -= 2;
continue;
}
q = p;
/* Just read in a header: only care about the length */
if (!asn1_check_tlen(&plen, NULL, NULL, &inf, NULL, &p, len,
-1, 0, 0, NULL)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
return 0;
}
if (inf)
expected_eoc++;
else
p += plen;
len -= p - q;
}
if (expected_eoc) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_EOC);
return 0;
}
*in = p;
return 1;
}
/*
* This function collects the asn1 data from a constructred string type into
* a buffer. The values of 'in' and 'len' should refer to the contents of the
* constructed type and 'inf' should be set if it is indefinite length.
*/
#ifndef ASN1_MAX_STRING_NEST
/*
* This determines how many levels of recursion are permitted in ASN1 string
* types. If it is not limited stack overflows can occur. If set to zero no
* recursion is allowed at all. Although zero should be adequate examples
* exist that require a value of 1. So 5 should be more than enough.
*/
# define ASN1_MAX_STRING_NEST 5
#endif
static int asn1_collect(BUF_MEM *buf, const unsigned char **in, long len,
char inf, int tag, int aclass, int depth)
{
const unsigned char *p, *q;
long plen;
char cst, ininf;
p = *in;
inf &= 1;
/*
* If no buffer and not indefinite length constructed just pass over the
* encoded data
*/
if (!buf && !inf) {
*in += len;
return 1;
}
while (len > 0) {
q = p;
/* Check for EOC */
if (asn1_check_eoc(&p, len)) {
/*
* EOC is illegal outside indefinite length constructed form
*/
if (!inf) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_UNEXPECTED_EOC);
return 0;
}
inf = 0;
break;
}
if (!asn1_check_tlen(&plen, NULL, NULL, &ininf, &cst, &p,
len, tag, aclass, 0, NULL)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
return 0;
}
/* If indefinite length constructed update max length */
if (cst) {
if (depth >= ASN1_MAX_STRING_NEST) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_STRING);
return 0;
}
if (!asn1_collect(buf, &p, plen, ininf, tag, aclass, depth + 1))
return 0;
} else if (plen && !collect_data(buf, &p, plen))
return 0;
len -= p - q;
}
if (inf) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_EOC);
return 0;
}
*in = p;
return 1;
}
static int collect_data(BUF_MEM *buf, const unsigned char **p, long plen)
{
int len;
if (buf) {
len = buf->length;
if (!BUF_MEM_grow_clean(buf, len + plen)) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return 0;
}
OPENSSL_memcpy(buf->data + len, *p, plen);
}
*p += plen;
return 1;
}
/* Check for ASN1 EOC and swallow it if found */
static int asn1_check_eoc(const unsigned char **in, long len)
@@ -1153,15 +884,12 @@ static int asn1_check_eoc(const unsigned char **in, long len)
}
/*
* Check an ASN1 tag and length: a bit like ASN1_get_object but it sets the
* length for indefinite length constructed form, we don't know the exact
* length but we can set an upper bound to the amount of data available minus
* the header length just read.
* Check an ASN1 tag and length: a bit like ASN1_get_object but it handles
* the ASN1_TLC cache and checks the expected tag.
*/
static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
char *inf, char *cst,
const unsigned char **in, long len,
char *cst, const unsigned char **in, long len,
int exptag, int expclass, char opt, ASN1_TLC *ctx)
{
int i;
@@ -1187,10 +915,13 @@ static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
ctx->hdrlen = p - q;
ctx->valid = 1;
/*
* If definite length, and no error, length + header can't exceed
* total amount of data available.
* If no error, length + header can't exceed total amount of data
* available.
*
* TODO(davidben): Is this check necessary? |ASN1_get_object|
* should already guarantee this.
*/
if (!(i & 0x81) && ((plen + ctx->hdrlen) > len)) {
if (!(i & 0x80) && ((plen + ctx->hdrlen) > len)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_TOO_LONG);
asn1_tlc_clear(ctx);
return 0;
@@ -1221,12 +952,6 @@ static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
asn1_tlc_clear(ctx);
}
if (i & 1)
plen = len - (p - q);
if (inf)
*inf = i & 1;
if (cst)
*cst = i & V_ASN1_CONSTRUCTED;
+325 -279
View File
@@ -56,6 +56,7 @@
#include <CCryptoBoringSSL_asn1.h>
#include <assert.h>
#include <limits.h>
#include <string.h>
@@ -63,60 +64,50 @@
#include <CCryptoBoringSSL_mem.h>
#include "../internal.h"
#include "internal.h"
static int asn1_item_ex_i2d_opt(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass,
int optional);
static int asn1_i2d_ex_primitive(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass);
const ASN1_ITEM *it, int tag, int aclass,
int optional);
static int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cont, int *out_omit,
int *putype, const ASN1_ITEM *it);
static int asn1_set_seq_out(STACK_OF(ASN1_VALUE) *sk, unsigned char **out,
int skcontlen, const ASN1_ITEM *item,
int do_sort, int iclass);
int skcontlen, const ASN1_ITEM *item, int do_sort);
static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_TEMPLATE *tt, int tag, int aclass);
static int asn1_item_flags_i2d(ASN1_VALUE *val, unsigned char **out,
const ASN1_ITEM *it, int flags);
/*
* Top level i2d equivalents: the 'ndef' variant instructs the encoder to use
* indefinite length constructed encoding, where appropriate
* Top level i2d equivalents
*/
int ASN1_item_ndef_i2d(ASN1_VALUE *val, unsigned char **out,
const ASN1_ITEM *it)
{
return asn1_item_flags_i2d(val, out, it, ASN1_TFLG_NDEF);
}
int ASN1_item_i2d(ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it)
{
return asn1_item_flags_i2d(val, out, it, 0);
}
/*
* Encode an ASN1 item, this is use by the standard 'i2d' function. 'out'
* points to a buffer to output the data to. The new i2d has one additional
* feature. If the output buffer is NULL (i.e. *out == NULL) then a buffer is
* allocated and populated with the encoding.
*/
static int asn1_item_flags_i2d(ASN1_VALUE *val, unsigned char **out,
const ASN1_ITEM *it, int flags)
{
if (out && !*out) {
unsigned char *p, *buf;
int len;
len = ASN1_item_ex_i2d(&val, NULL, it, -1, flags);
if (len <= 0)
int len = ASN1_item_ex_i2d(&val, NULL, it, /*tag=*/-1, /*aclass=*/0);
if (len <= 0) {
return len;
}
buf = OPENSSL_malloc(len);
if (!buf)
if (!buf) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return -1;
}
p = buf;
ASN1_item_ex_i2d(&val, &p, it, -1, flags);
int len2 = ASN1_item_ex_i2d(&val, &p, it, /*tag=*/-1, /*aclass=*/0);
if (len2 <= 0) {
return len2;
}
assert(len == len2);
*out = buf;
return len;
}
return ASN1_item_ex_i2d(&val, out, it, -1, flags);
return ASN1_item_ex_i2d(&val, out, it, /*tag=*/-1, /*aclass=*/0);
}
/*
@@ -126,79 +117,102 @@ static int asn1_item_flags_i2d(ASN1_VALUE *val, unsigned char **out,
int ASN1_item_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass)
{
int ret = asn1_item_ex_i2d_opt(pval, out, it, tag, aclass, /*optional=*/0);
assert(ret != 0);
return ret;
}
/* asn1_item_ex_i2d_opt behaves like |ASN1_item_ex_i2d| but, if |optional| is
* non-zero and |*pval| is omitted, it returns zero and writes no bytes. */
int asn1_item_ex_i2d_opt(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass,
int optional)
{
const ASN1_TEMPLATE *tt = NULL;
unsigned char *p = NULL;
int i, seqcontlen, seqlen, ndef = 1;
const ASN1_COMPAT_FUNCS *cf;
const ASN1_EXTERN_FUNCS *ef;
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb = 0;
int i, seqcontlen, seqlen;
if ((it->itype != ASN1_ITYPE_PRIMITIVE) && !*pval)
return 0;
/* Historically, |aclass| was repurposed to pass additional flags into the
* encoding process. */
assert((aclass & ASN1_TFLG_TAG_CLASS) == aclass);
/* If not overridding the tag, |aclass| is ignored and should be zero. */
assert(tag != -1 || aclass == 0);
if (aux && aux->asn1_cb)
asn1_cb = aux->asn1_cb;
/* All fields are pointers, except for boolean |ASN1_ITYPE_PRIMITIVE|s.
* Optional primitives are handled later. */
if ((it->itype != ASN1_ITYPE_PRIMITIVE) && !*pval) {
if (optional) {
return 0;
}
OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_VALUE);
return -1;
}
switch (it->itype) {
case ASN1_ITYPE_PRIMITIVE:
if (it->templates)
return asn1_template_ex_i2d(pval, out, it->templates,
tag, aclass);
return asn1_i2d_ex_primitive(pval, out, it, tag, aclass);
break;
if (it->templates) {
if (it->templates->flags & ASN1_TFLG_OPTIONAL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return -1;
}
return asn1_template_ex_i2d(pval, out, it->templates, tag, aclass);
}
return asn1_i2d_ex_primitive(pval, out, it, tag, aclass, optional);
case ASN1_ITYPE_MSTRING:
return asn1_i2d_ex_primitive(pval, out, it, -1, aclass);
case ASN1_ITYPE_CHOICE:
if (asn1_cb && !asn1_cb(ASN1_OP_I2D_PRE, pval, it, NULL))
return 0;
i = asn1_get_choice_selector(pval, it);
if ((i >= 0) && (i < it->tcount)) {
ASN1_VALUE **pchval;
const ASN1_TEMPLATE *chtt;
chtt = it->templates + i;
pchval = asn1_get_field_ptr(pval, chtt);
return asn1_template_ex_i2d(pchval, out, chtt, -1, aclass);
}
/* Fixme: error condition if selector out of range */
if (asn1_cb && !asn1_cb(ASN1_OP_I2D_POST, pval, it, NULL))
return 0;
break;
case ASN1_ITYPE_EXTERN:
/* If new style i2d it does all the work */
ef = it->funcs;
return ef->asn1_ex_i2d(pval, out, it, tag, aclass);
case ASN1_ITYPE_COMPAT:
/* old style hackery... */
cf = it->funcs;
if (out)
p = *out;
i = cf->asn1_i2d(*pval, out);
/*
* Fixup for IMPLICIT tag: note this messes up for tags > 30, but so
* did the old code. Tags > 30 are very rare anyway.
* It never makes sense for multi-strings to have implicit tagging, so
* if tag != -1, then this looks like an error in the template.
*/
if (out && (tag != -1))
*p = aclass | tag | (*p & V_ASN1_CONSTRUCTED);
return i;
if (tag != -1) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return -1;
}
return asn1_i2d_ex_primitive(pval, out, it, -1, 0, optional);
case ASN1_ITYPE_NDEF_SEQUENCE:
/* Use indefinite length constructed if requested */
if (aclass & ASN1_TFLG_NDEF)
ndef = 2;
OPENSSL_FALLTHROUGH;
case ASN1_ITYPE_CHOICE: {
/*
* It never makes sense for CHOICE types to have implicit tagging, so if
* tag != -1, then this looks like an error in the template.
*/
if (tag != -1) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return -1;
}
i = asn1_get_choice_selector(pval, it);
if (i < 0 || i >= it->tcount) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NO_MATCHING_CHOICE_TYPE);
return -1;
}
const ASN1_TEMPLATE *chtt = it->templates + i;
if (chtt->flags & ASN1_TFLG_OPTIONAL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return -1;
}
ASN1_VALUE **pchval = asn1_get_field_ptr(pval, chtt);
return asn1_template_ex_i2d(pchval, out, chtt, -1, 0);
}
case ASN1_ITYPE_SEQUENCE:
case ASN1_ITYPE_EXTERN: {
/* If new style i2d it does all the work */
const ASN1_EXTERN_FUNCS *ef = it->funcs;
int ret = ef->asn1_ex_i2d(pval, out, it, tag, aclass);
if (ret == 0) {
/* |asn1_ex_i2d| should never return zero. We have already checked
* for optional values generically, and |ASN1_ITYPE_EXTERN| fields
* must be pointers. */
OPENSSL_PUT_ERROR(ASN1, ERR_R_INTERNAL_ERROR);
return -1;
}
return ret;
}
case ASN1_ITYPE_SEQUENCE: {
i = asn1_enc_restore(&seqcontlen, out, pval, it);
/* An error occurred */
if (i < 0)
return 0;
return -1;
/* We have a valid cached encoding... */
if (i > 0)
return seqcontlen;
@@ -207,12 +221,8 @@ int ASN1_item_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
/* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */
if (tag == -1) {
tag = V_ASN1_SEQUENCE;
/* Retain any other flags in aclass */
aclass = (aclass & ~ASN1_TFLG_TAG_CLASS)
| V_ASN1_UNIVERSAL;
aclass = V_ASN1_UNIVERSAL;
}
if (asn1_cb && !asn1_cb(ASN1_OP_I2D_PRE, pval, it, NULL))
return 0;
/* First work out sequence content length */
for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) {
const ASN1_TEMPLATE *seqtt;
@@ -220,60 +230,67 @@ int ASN1_item_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
int tmplen;
seqtt = asn1_do_adb(pval, tt, 1);
if (!seqtt)
return 0;
return -1;
pseqval = asn1_get_field_ptr(pval, seqtt);
tmplen = asn1_template_ex_i2d(pseqval, NULL, seqtt, -1, aclass);
tmplen = asn1_template_ex_i2d(pseqval, NULL, seqtt, -1, 0);
if (tmplen == -1 || (tmplen > INT_MAX - seqcontlen))
return -1;
seqcontlen += tmplen;
}
seqlen = ASN1_object_size(ndef, seqcontlen, tag);
seqlen = ASN1_object_size(/*constructed=*/1, seqcontlen, tag);
if (!out || seqlen == -1)
return seqlen;
/* Output SEQUENCE header */
ASN1_put_object(out, ndef, seqcontlen, tag, aclass);
ASN1_put_object(out, /*constructed=*/1, seqcontlen, tag, aclass);
for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) {
const ASN1_TEMPLATE *seqtt;
ASN1_VALUE **pseqval;
seqtt = asn1_do_adb(pval, tt, 1);
if (!seqtt)
return 0;
return -1;
pseqval = asn1_get_field_ptr(pval, seqtt);
/* FIXME: check for errors in enhanced version */
asn1_template_ex_i2d(pseqval, out, seqtt, -1, aclass);
if (asn1_template_ex_i2d(pseqval, out, seqtt, -1, 0) < 0) {
return -1;
}
}
if (ndef == 2)
ASN1_put_eoc(out);
if (asn1_cb && !asn1_cb(ASN1_OP_I2D_POST, pval, it, NULL))
return 0;
return seqlen;
}
default:
return 0;
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return -1;
}
return 0;
}
/* asn1_template_ex_i2d behaves like |asn1_item_ex_i2d_opt| but uses an
* |ASN1_TEMPLATE| instead of an |ASN1_ITEM|. An |ASN1_TEMPLATE| wraps an
* |ASN1_ITEM| with modifiers such as tagging, SEQUENCE or SET, etc. Instead of
* taking an |optional| parameter, it uses the |ASN1_TFLG_OPTIONAL| flag. */
static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_TEMPLATE *tt, int tag, int iclass)
{
int i, ret, flags, ttag, tclass, ndef;
int i, ret, flags, ttag, tclass;
size_t j;
flags = tt->flags;
/* Historically, |iclass| was repurposed to pass additional flags into the
* encoding process. */
assert((iclass & ASN1_TFLG_TAG_CLASS) == iclass);
/* If not overridding the tag, |iclass| is ignored and should be zero. */
assert(tag != -1 || iclass == 0);
/*
* Work out tag and class to use: tagging may come either from the
* template or the arguments, not both because this would create
* ambiguity. Additionally the iclass argument may contain some
* additional flags which should be noted and passed down to other
* levels.
* ambiguity.
*/
if (flags & ASN1_TFLG_TAG_MASK) {
/* Error if argument and template tagging */
if (tag != -1)
/* FIXME: error code here */
if (tag != -1) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return -1;
}
/* Get tagging from template */
ttag = tt->tag;
tclass = flags & ASN1_TFLG_TAG_CLASS;
@@ -285,22 +302,14 @@ static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
ttag = -1;
tclass = 0;
}
/*
* Remove any class mask from iflag.
*/
iclass &= ~ASN1_TFLG_TAG_CLASS;
const int optional = (flags & ASN1_TFLG_OPTIONAL) != 0;
/*
* At this point 'ttag' contains the outer tag to use, 'tclass' is the
* class and iclass is any flags passed to this function.
* At this point 'ttag' contains the outer tag to use, and 'tclass' is the
* class.
*/
/* if template and arguments require ndef, use it */
if ((flags & ASN1_TFLG_NDEF) && (iclass & ASN1_TFLG_NDEF))
ndef = 2;
else
ndef = 1;
if (flags & ASN1_TFLG_SK_MASK) {
/* SET OF, SEQUENCE OF */
STACK_OF(ASN1_VALUE) *sk = (STACK_OF(ASN1_VALUE) *)*pval;
@@ -308,16 +317,22 @@ static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
int skcontlen, sklen;
ASN1_VALUE *skitem;
if (!*pval)
return 0;
if (!*pval) {
if (optional) {
return 0;
}
OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_VALUE);
return -1;
}
if (flags & ASN1_TFLG_SET_OF) {
isset = 1;
/* 2 means we reorder */
if (flags & ASN1_TFLG_SEQUENCE_OF)
isset = 2;
} else
/* Historically, types with both bits set were mutated when
* serialized to apply the sort. We no longer support this. */
assert((flags & ASN1_TFLG_SEQUENCE_OF) == 0);
} else {
isset = 0;
}
/*
* Work out inner tag value: if EXPLICIT or no tagging use underlying
@@ -340,17 +355,17 @@ static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
int tmplen;
skitem = sk_ASN1_VALUE_value(sk, j);
tmplen = ASN1_item_ex_i2d(&skitem, NULL, ASN1_ITEM_ptr(tt->item),
-1, iclass);
-1, 0);
if (tmplen == -1 || (skcontlen > INT_MAX - tmplen))
return -1;
skcontlen += tmplen;
}
sklen = ASN1_object_size(ndef, skcontlen, sktag);
sklen = ASN1_object_size(/*constructed=*/1, skcontlen, sktag);
if (sklen == -1)
return -1;
/* If EXPLICIT need length of surrounding tag */
if (flags & ASN1_TFLG_EXPTAG)
ret = ASN1_object_size(ndef, sklen, ttag);
ret = ASN1_object_size(/*constructed=*/1, sklen, ttag);
else
ret = sklen;
@@ -360,42 +375,40 @@ static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
/* Now encode this lot... */
/* EXPLICIT tag */
if (flags & ASN1_TFLG_EXPTAG)
ASN1_put_object(out, ndef, sklen, ttag, tclass);
ASN1_put_object(out, /*constructed=*/1, sklen, ttag, tclass);
/* SET or SEQUENCE and IMPLICIT tag */
ASN1_put_object(out, ndef, skcontlen, sktag, skaclass);
ASN1_put_object(out, /*constructed=*/1, skcontlen, sktag, skaclass);
/* And the stuff itself */
asn1_set_seq_out(sk, out, skcontlen, ASN1_ITEM_ptr(tt->item),
isset, iclass);
if (ndef == 2) {
ASN1_put_eoc(out);
if (flags & ASN1_TFLG_EXPTAG)
ASN1_put_eoc(out);
if (!asn1_set_seq_out(sk, out, skcontlen, ASN1_ITEM_ptr(tt->item),
isset)) {
return -1;
}
return ret;
}
if (flags & ASN1_TFLG_EXPTAG) {
/* EXPLICIT tagging */
/* Find length of tagged item */
i = ASN1_item_ex_i2d(pval, NULL, ASN1_ITEM_ptr(tt->item), -1, iclass);
if (!i)
return 0;
i = asn1_item_ex_i2d_opt(pval, NULL, ASN1_ITEM_ptr(tt->item), -1, 0,
optional);
if (i <= 0)
return i;
/* Find length of EXPLICIT tag */
ret = ASN1_object_size(ndef, i, ttag);
ret = ASN1_object_size(/*constructed=*/1, i, ttag);
if (out && ret != -1) {
/* Output tag and item */
ASN1_put_object(out, ndef, i, ttag, tclass);
ASN1_item_ex_i2d(pval, out, ASN1_ITEM_ptr(tt->item), -1, iclass);
if (ndef == 2)
ASN1_put_eoc(out);
ASN1_put_object(out, /*constructed=*/1, i, ttag, tclass);
if (ASN1_item_ex_i2d(pval, out, ASN1_ITEM_ptr(tt->item), -1,
0) < 0) {
return -1;
}
}
return ret;
}
/* Either normal or IMPLICIT tagging: combine class and flags */
return ASN1_item_ex_i2d(pval, out, ASN1_ITEM_ptr(tt->item),
ttag, tclass | iclass);
/* Either normal or IMPLICIT tagging */
return asn1_item_ex_i2d_opt(pval, out, ASN1_ITEM_ptr(tt->item),
ttag, tclass, optional);
}
@@ -404,7 +417,6 @@ static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
typedef struct {
unsigned char *data;
int length;
ASN1_VALUE *field;
} DER_ENC;
static int der_cmp(const void *a, const void *b)
@@ -418,106 +430,96 @@ static int der_cmp(const void *a, const void *b)
return d1->length - d2->length;
}
/* Output the content octets of SET OF or SEQUENCE OF */
/* asn1_set_seq_out writes |sk| to |out| under the i2d output convention,
* excluding the tag and length. It returns one on success and zero on error.
* |skcontlen| must be the total encoded size. If |do_sort| is non-zero, the
* elements are sorted for a SET OF type. Each element of |sk| has type
* |item|. */
static int asn1_set_seq_out(STACK_OF(ASN1_VALUE) *sk, unsigned char **out,
int skcontlen, const ASN1_ITEM *item,
int do_sort, int iclass)
int skcontlen, const ASN1_ITEM *item, int do_sort)
{
size_t i;
ASN1_VALUE *skitem;
unsigned char *tmpdat = NULL, *p = NULL;
DER_ENC *derlst = NULL, *tder;
if (do_sort) {
/* Don't need to sort less than 2 items */
if (sk_ASN1_VALUE_num(sk) < 2)
do_sort = 0;
else {
derlst = OPENSSL_malloc(sk_ASN1_VALUE_num(sk)
* sizeof(*derlst));
if (!derlst)
return 0;
tmpdat = OPENSSL_malloc(skcontlen);
if (!tmpdat) {
OPENSSL_free(derlst);
/* No need to sort if there are fewer than two items. */
if (!do_sort || sk_ASN1_VALUE_num(sk) < 2) {
for (size_t i = 0; i < sk_ASN1_VALUE_num(sk); i++) {
ASN1_VALUE *skitem = sk_ASN1_VALUE_value(sk, i);
if (ASN1_item_ex_i2d(&skitem, out, item, -1, 0) < 0) {
return 0;
}
}
}
/* If not sorting just output each item */
if (!do_sort) {
for (i = 0; i < sk_ASN1_VALUE_num(sk); i++) {
skitem = sk_ASN1_VALUE_value(sk, i);
ASN1_item_ex_i2d(&skitem, out, item, -1, iclass);
}
return 1;
}
p = tmpdat;
/* Doing sort: build up a list of each member's DER encoding */
for (i = 0, tder = derlst; i < sk_ASN1_VALUE_num(sk); i++, tder++) {
skitem = sk_ASN1_VALUE_value(sk, i);
tder->data = p;
tder->length = ASN1_item_ex_i2d(&skitem, &p, item, -1, iclass);
tder->field = skitem;
if (sk_ASN1_VALUE_num(sk) > ((size_t)-1) / sizeof(DER_ENC)) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_OVERFLOW);
return 0;
}
/* Now sort them */
qsort(derlst, sk_ASN1_VALUE_num(sk), sizeof(*derlst), der_cmp);
/* Output sorted DER encoding */
int ret = 0;
unsigned char *const buf = OPENSSL_malloc(skcontlen);
DER_ENC *encoded = OPENSSL_malloc(sk_ASN1_VALUE_num(sk) * sizeof(*encoded));
if (encoded == NULL || buf == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
/* Encode all the elements into |buf| and populate |encoded|. */
unsigned char *p = buf;
for (size_t i = 0; i < sk_ASN1_VALUE_num(sk); i++) {
ASN1_VALUE *skitem = sk_ASN1_VALUE_value(sk, i);
encoded[i].data = p;
encoded[i].length = ASN1_item_ex_i2d(&skitem, &p, item, -1, 0);
if (encoded[i].length < 0) {
goto err;
}
assert(p - buf <= skcontlen);
}
qsort(encoded, sk_ASN1_VALUE_num(sk), sizeof(*encoded), der_cmp);
/* Output the elements in sorted order. */
p = *out;
for (i = 0, tder = derlst; i < sk_ASN1_VALUE_num(sk); i++, tder++) {
OPENSSL_memcpy(p, tder->data, tder->length);
p += tder->length;
for (size_t i = 0; i < sk_ASN1_VALUE_num(sk); i++) {
OPENSSL_memcpy(p, encoded[i].data, encoded[i].length);
p += encoded[i].length;
}
*out = p;
/* If do_sort is 2 then reorder the STACK */
if (do_sort == 2) {
for (i = 0, tder = derlst; i < sk_ASN1_VALUE_num(sk); i++, tder++)
(void)sk_ASN1_VALUE_set(sk, i, tder->field);
}
OPENSSL_free(derlst);
OPENSSL_free(tmpdat);
return 1;
ret = 1;
err:
OPENSSL_free(encoded);
OPENSSL_free(buf);
return ret;
}
/* asn1_i2d_ex_primitive behaves like |ASN1_item_ex_i2d| but |item| must be a
* a PRIMITIVE or MSTRING type that is not an |ASN1_ITEM_TEMPLATE|. */
static int asn1_i2d_ex_primitive(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass)
const ASN1_ITEM *it, int tag, int aclass,
int optional)
{
int len;
int utype;
int usetag;
int ndef = 0;
utype = it->utype;
/*
* Get length of content octets and maybe find out the underlying type.
*/
len = asn1_ex_i2c(pval, NULL, &utype, it);
/* Get length of content octets and maybe find out the underlying type. */
int omit;
int utype = it->utype;
int len = asn1_ex_i2c(pval, NULL, &omit, &utype, it);
if (len < 0) {
return -1;
}
if (omit) {
if (optional) {
return 0;
}
OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_VALUE);
return -1;
}
/*
* If SEQUENCE, SET or OTHER then header is included in pseudo content
* octets so don't include tag+length. We need to check here because the
* call to asn1_ex_i2c() could change utype.
*/
if ((utype == V_ASN1_SEQUENCE) || (utype == V_ASN1_SET) ||
(utype == V_ASN1_OTHER))
usetag = 0;
else
usetag = 1;
/* -1 means omit type */
if (len == -1)
return 0;
/* -2 return is special meaning use ndef */
if (len == -2) {
ndef = 2;
len = 0;
}
int usetag = utype != V_ASN1_SEQUENCE && utype != V_ASN1_SET &&
utype != V_ASN1_OTHER;
/* If not implicitly tagged get tag from underlying type */
if (tag == -1)
@@ -525,24 +527,42 @@ static int asn1_i2d_ex_primitive(ASN1_VALUE **pval, unsigned char **out,
/* Output tag+length followed by content octets */
if (out) {
if (usetag)
ASN1_put_object(out, ndef, len, tag, aclass);
asn1_ex_i2c(pval, *out, &utype, it);
if (ndef)
ASN1_put_eoc(out);
else
*out += len;
if (usetag) {
ASN1_put_object(out, /*constructed=*/0, len, tag, aclass);
}
int len2 = asn1_ex_i2c(pval, *out, &omit, &utype, it);
if (len2 < 0) {
return -1;
}
assert(len == len2);
assert(!omit);
*out += len;
}
if (usetag)
return ASN1_object_size(ndef, len, tag);
if (usetag) {
return ASN1_object_size(/*constructed=*/0, len, tag);
}
return len;
}
/* Produce content octets from a structure */
int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *putype,
const ASN1_ITEM *it)
/* asn1_ex_i2c writes the |*pval| to |cout| under the i2d output convention,
* excluding the tag and length. It returns the number of bytes written,
* possibly zero, on success or -1 on error. If |*pval| should be omitted, it
* returns zero and sets |*out_omit| to true.
*
* If |it| is an MSTRING or ANY type, it gets the underlying type from |*pval|,
* which must be an |ASN1_STRING| or |ASN1_TYPE|, respectively. It then updates
* |*putype| with the tag number of type used, or |V_ASN1_OTHER| if it was not a
* universal type. If |*putype| is set to |V_ASN1_SEQUENCE|, |V_ASN1_SET|, or
* |V_ASN1_OTHER|, it additionally outputs the tag and length, so the caller
* must not do so.
*
* Otherwise, |*putype| must contain |it->utype|.
*
* WARNING: Unlike most functions in this file, |asn1_ex_i2c| can return zero
* without omitting the element. ASN.1 values may have empty contents. */
static int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *out_omit,
int *putype, const ASN1_ITEM *it)
{
ASN1_BOOLEAN *tbool = NULL;
ASN1_STRING *strtmp;
@@ -551,28 +571,56 @@ int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *putype,
const unsigned char *cont;
unsigned char c;
int len;
const ASN1_PRIMITIVE_FUNCS *pf;
pf = it->funcs;
if (pf && pf->prim_i2c)
return pf->prim_i2c(pval, cout, putype, it);
/* Historically, |it->funcs| for primitive types contained an
* |ASN1_PRIMITIVE_FUNCS| table of callbacks. */
assert(it->funcs == NULL);
*out_omit = 0;
/* Should type be omitted? */
if ((it->itype != ASN1_ITYPE_PRIMITIVE)
|| (it->utype != V_ASN1_BOOLEAN)) {
if (!*pval)
return -1;
if (!*pval) {
*out_omit = 1;
return 0;
}
}
if (it->itype == ASN1_ITYPE_MSTRING) {
/* If MSTRING type set the underlying type */
strtmp = (ASN1_STRING *)*pval;
utype = strtmp->type;
if (utype < 0 && utype != V_ASN1_OTHER) {
/* MSTRINGs can have type -1 when default-constructed. */
OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE);
return -1;
}
/* Negative INTEGER and ENUMERATED values use |ASN1_STRING| type values
* that do not match their corresponding utype values. INTEGERs cannot
* participate in MSTRING types, but ENUMERATEDs can.
*
* TODO(davidben): Is this a bug? Although arguably one of the MSTRING
* types should contain more values, rather than less. See
* https://crbug.com/boringssl/412. But it is not possible to fit all
* possible ANY values into an |ASN1_STRING|, so matching the spec here
* is somewhat hopeless. */
if (utype == V_ASN1_NEG_INTEGER) {
utype = V_ASN1_INTEGER;
} else if (utype == V_ASN1_NEG_ENUMERATED) {
utype = V_ASN1_ENUMERATED;
}
*putype = utype;
} else if (it->utype == V_ASN1_ANY) {
/* If ANY set type and pointer to value */
ASN1_TYPE *typ;
typ = (ASN1_TYPE *)*pval;
utype = typ->type;
if (utype < 0 && utype != V_ASN1_OTHER) {
/* |ASN1_TYPE|s can have type -1 when default-constructed. */
OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE);
return -1;
}
*putype = utype;
pval = &typ->value.asn1_value;
} else
@@ -583,8 +631,11 @@ int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *putype,
otmp = (ASN1_OBJECT *)*pval;
cont = otmp->data;
len = otmp->length;
if (cont == NULL || len == 0)
if (len == 0) {
/* Some |ASN1_OBJECT|s do not have OIDs and cannot be serialized. */
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OBJECT);
return -1;
}
break;
case V_ASN1_NULL:
@@ -594,34 +645,39 @@ int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *putype,
case V_ASN1_BOOLEAN:
tbool = (ASN1_BOOLEAN *)pval;
if (*tbool == -1)
return -1;
if (*tbool == -1) {
*out_omit = 1;
return 0;
}
if (it->utype != V_ASN1_ANY) {
/*
* Default handling if value == size field then omit
*/
if (*tbool && (it->size > 0))
return -1;
if (!*tbool && !it->size)
return -1;
if ((*tbool && (it->size > 0)) ||
(!*tbool && !it->size)) {
*out_omit = 1;
return 0;
}
}
c = (unsigned char)*tbool;
c = *tbool ? 0xff : 0x00;
cont = &c;
len = 1;
break;
case V_ASN1_BIT_STRING:
return i2c_ASN1_BIT_STRING((ASN1_BIT_STRING *)*pval,
cout ? &cout : NULL);
break;
case V_ASN1_BIT_STRING: {
int ret = i2c_ASN1_BIT_STRING((ASN1_BIT_STRING *)*pval,
cout ? &cout : NULL);
/* |i2c_ASN1_BIT_STRING| returns zero on error instead of -1. */
return ret <= 0 ? -1 : ret;
}
case V_ASN1_INTEGER:
case V_ASN1_ENUMERATED:
/*
* These are all have the same content format as ASN1_INTEGER
*/
return i2c_ASN1_INTEGER((ASN1_INTEGER *)*pval, cout ? &cout : NULL);
break;
case V_ASN1_ENUMERATED: {
/* |i2c_ASN1_INTEGER| also handles ENUMERATED. */
int ret = i2c_ASN1_INTEGER((ASN1_INTEGER *)*pval, cout ? &cout : NULL);
/* |i2c_ASN1_INTEGER| returns zero on error instead of -1. */
return ret <= 0 ? -1 : ret;
}
case V_ASN1_OCTET_STRING:
case V_ASN1_NUMERICSTRING:
@@ -642,16 +698,6 @@ int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *putype,
default:
/* All based on ASN1_STRING and handled the same */
strtmp = (ASN1_STRING *)*pval;
/* Special handling for NDEF */
if ((it->size == ASN1_TFLG_NDEF)
&& (strtmp->flags & ASN1_STRING_FLAG_NDEF)) {
if (cout) {
strtmp->data = cout;
strtmp->length = 0;
}
/* Special return code */
return -2;
}
cont = strtmp->data;
len = strtmp->length;
+15 -26
View File
@@ -56,10 +56,12 @@
#include <CCryptoBoringSSL_asn1.h>
#include <assert.h>
#include <CCryptoBoringSSL_asn1t.h>
#include <CCryptoBoringSSL_mem.h>
#include "asn1_locl.h"
#include "internal.h"
/* Free up an ASN1 structure */
@@ -77,18 +79,11 @@ void asn1_item_combine_free(ASN1_VALUE **pval, const ASN1_ITEM *it, int combine)
{
const ASN1_TEMPLATE *tt = NULL, *seqtt;
const ASN1_EXTERN_FUNCS *ef;
const ASN1_COMPAT_FUNCS *cf;
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb;
int i;
if (!pval)
return;
if ((it->itype != ASN1_ITYPE_PRIMITIVE) && !*pval)
return;
if (aux && aux->asn1_cb)
asn1_cb = aux->asn1_cb;
else
asn1_cb = 0;
switch (it->itype) {
@@ -103,7 +98,9 @@ void asn1_item_combine_free(ASN1_VALUE **pval, const ASN1_ITEM *it, int combine)
ASN1_primitive_free(pval, it);
break;
case ASN1_ITYPE_CHOICE:
case ASN1_ITYPE_CHOICE: {
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
if (asn1_cb) {
i = asn1_cb(ASN1_OP_FREE_PRE, pval, it, NULL);
if (i == 2)
@@ -123,12 +120,7 @@ void asn1_item_combine_free(ASN1_VALUE **pval, const ASN1_ITEM *it, int combine)
*pval = NULL;
}
break;
case ASN1_ITYPE_COMPAT:
cf = it->funcs;
if (cf && cf->asn1_free)
cf->asn1_free(*pval);
break;
}
case ASN1_ITYPE_EXTERN:
ef = it->funcs;
@@ -136,10 +128,11 @@ void asn1_item_combine_free(ASN1_VALUE **pval, const ASN1_ITEM *it, int combine)
ef->asn1_ex_free(pval, it);
break;
case ASN1_ITYPE_NDEF_SEQUENCE:
case ASN1_ITYPE_SEQUENCE:
case ASN1_ITYPE_SEQUENCE: {
if (!asn1_refcount_dec_and_test_zero(pval, it))
return;
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
if (asn1_cb) {
i = asn1_cb(ASN1_OP_FREE_PRE, pval, it, NULL);
if (i == 2)
@@ -168,6 +161,7 @@ void asn1_item_combine_free(ASN1_VALUE **pval, const ASN1_ITEM *it, int combine)
}
break;
}
}
}
void ASN1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt)
@@ -190,20 +184,15 @@ void ASN1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt)
void ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
int utype;
if (it) {
const ASN1_PRIMITIVE_FUNCS *pf;
pf = it->funcs;
if (pf && pf->prim_free) {
pf->prim_free(pval, it);
return;
}
}
/* Historically, |it->funcs| for primitive types contained an
* |ASN1_PRIMITIVE_FUNCS| table of calbacks. */
assert(it == NULL || it->funcs == NULL);
/* Special case: if 'it' is NULL free contents of ASN1_TYPE */
if (!it) {
ASN1_TYPE *typ = (ASN1_TYPE *)*pval;
utype = typ->type;
pval = &typ->value.asn1_value;
if (!*pval)
if (utype != V_ASN1_BOOLEAN && !*pval)
return;
} else if (it->itype == ASN1_ITYPE_MSTRING) {
utype = -1;
+20 -75
View File
@@ -63,14 +63,16 @@
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_obj.h>
#include "asn1_locl.h"
#include "internal.h"
#include "../internal.h"
static int asn1_item_ex_combine_new(ASN1_VALUE **pval, const ASN1_ITEM *it,
int combine);
static void asn1_item_clear(ASN1_VALUE **pval, const ASN1_ITEM *it);
static int ASN1_template_new(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt);
static void asn1_template_clear(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt);
static int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it);
static void asn1_primitive_clear(ASN1_VALUE **pval, const ASN1_ITEM *it);
ASN1_VALUE *ASN1_item_new(const ASN1_ITEM *it)
@@ -92,21 +94,9 @@ static int asn1_item_ex_combine_new(ASN1_VALUE **pval, const ASN1_ITEM *it,
int combine)
{
const ASN1_TEMPLATE *tt = NULL;
const ASN1_COMPAT_FUNCS *cf;
const ASN1_EXTERN_FUNCS *ef;
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb;
ASN1_VALUE **pseqval;
int i;
if (aux && aux->asn1_cb)
asn1_cb = aux->asn1_cb;
else
asn1_cb = 0;
#ifdef CRYPTO_MDEBUG
if (it->sname)
CRYPTO_push_info(it->sname);
#endif
switch (it->itype) {
@@ -118,15 +108,6 @@ static int asn1_item_ex_combine_new(ASN1_VALUE **pval, const ASN1_ITEM *it,
}
break;
case ASN1_ITYPE_COMPAT:
cf = it->funcs;
if (cf && cf->asn1_new) {
*pval = cf->asn1_new();
if (!*pval)
goto memerr;
}
break;
case ASN1_ITYPE_PRIMITIVE:
if (it->templates) {
if (!ASN1_template_new(pval, it->templates))
@@ -140,16 +121,14 @@ static int asn1_item_ex_combine_new(ASN1_VALUE **pval, const ASN1_ITEM *it,
goto memerr;
break;
case ASN1_ITYPE_CHOICE:
case ASN1_ITYPE_CHOICE: {
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
if (asn1_cb) {
i = asn1_cb(ASN1_OP_NEW_PRE, pval, it, NULL);
if (!i)
goto auxerr;
if (i == 2) {
#ifdef CRYPTO_MDEBUG
if (it->sname)
CRYPTO_pop_info();
#endif
return 1;
}
}
@@ -163,18 +142,16 @@ static int asn1_item_ex_combine_new(ASN1_VALUE **pval, const ASN1_ITEM *it,
if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, NULL))
goto auxerr2;
break;
}
case ASN1_ITYPE_NDEF_SEQUENCE:
case ASN1_ITYPE_SEQUENCE:
case ASN1_ITYPE_SEQUENCE: {
const ASN1_AUX *aux = it->funcs;
ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
if (asn1_cb) {
i = asn1_cb(ASN1_OP_NEW_PRE, pval, it, NULL);
if (!i)
goto auxerr;
if (i == 2) {
#ifdef CRYPTO_MDEBUG
if (it->sname)
CRYPTO_pop_info();
#endif
return 1;
}
}
@@ -195,30 +172,19 @@ static int asn1_item_ex_combine_new(ASN1_VALUE **pval, const ASN1_ITEM *it,
goto auxerr2;
break;
}
#ifdef CRYPTO_MDEBUG
if (it->sname)
CRYPTO_pop_info();
#endif
}
return 1;
memerr2:
asn1_item_combine_free(pval, it, combine);
memerr:
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
#ifdef CRYPTO_MDEBUG
if (it->sname)
CRYPTO_pop_info();
#endif
return 0;
auxerr2:
asn1_item_combine_free(pval, it, combine);
auxerr:
OPENSSL_PUT_ERROR(ASN1, ASN1_R_AUX_ERROR);
#ifdef CRYPTO_MDEBUG
if (it->sname)
CRYPTO_pop_info();
#endif
return 0;
}
@@ -248,16 +214,14 @@ static void asn1_item_clear(ASN1_VALUE **pval, const ASN1_ITEM *it)
asn1_primitive_clear(pval, it);
break;
case ASN1_ITYPE_COMPAT:
case ASN1_ITYPE_CHOICE:
case ASN1_ITYPE_SEQUENCE:
case ASN1_ITYPE_NDEF_SEQUENCE:
*pval = NULL;
break;
}
}
int ASN1_template_new(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt)
static int ASN1_template_new(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt)
{
const ASN1_ITEM *it = ASN1_ITEM_ptr(tt->item);
int ret;
@@ -271,10 +235,6 @@ int ASN1_template_new(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt)
*pval = NULL;
return 1;
}
#ifdef CRYPTO_MDEBUG
if (tt->field_name)
CRYPTO_push_info(tt->field_name);
#endif
/* If SET OF or SEQUENCE OF, its a STACK */
if (tt->flags & ASN1_TFLG_SK_MASK) {
STACK_OF(ASN1_VALUE) *skval;
@@ -291,10 +251,6 @@ int ASN1_template_new(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt)
/* Otherwise pass it back to the item routine */
ret = asn1_item_ex_combine_new(pval, it, tt->flags & ASN1_TFLG_COMBINE);
done:
#ifdef CRYPTO_MDEBUG
if (it->sname)
CRYPTO_pop_info();
#endif
return ret;
}
@@ -312,20 +268,17 @@ static void asn1_template_clear(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt)
* all the old functions.
*/
int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it)
static int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
ASN1_TYPE *typ;
ASN1_STRING *str;
int utype;
if (!it)
return 0;
if (it->funcs) {
const ASN1_PRIMITIVE_FUNCS *pf = it->funcs;
if (pf->prim_new)
return pf->prim_new(pval, it);
}
/* Historically, |it->funcs| for primitive types contained an
* |ASN1_PRIMITIVE_FUNCS| table of calbacks. */
assert(it->funcs == NULL);
if (it->itype == ASN1_ITYPE_MSTRING)
utype = -1;
@@ -354,10 +307,7 @@ int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it)
break;
default:
str = ASN1_STRING_type_new(utype);
if (it->itype == ASN1_ITYPE_MSTRING && str)
str->flags |= ASN1_STRING_FLAG_MSTRING;
*pval = (ASN1_VALUE *)str;
*pval = (ASN1_VALUE *)ASN1_STRING_type_new(utype);
break;
}
if (*pval)
@@ -368,14 +318,9 @@ int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it)
static void asn1_primitive_clear(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
int utype;
if (it && it->funcs) {
const ASN1_PRIMITIVE_FUNCS *pf = it->funcs;
if (pf->prim_clear)
pf->prim_clear(pval, it);
else
*pval = NULL;
return;
}
/* Historically, |it->funcs| for primitive types contained an
* |ASN1_PRIMITIVE_FUNCS| table of calbacks. */
assert(it == NULL || it->funcs == NULL);
if (!it || (it->itype == ASN1_ITYPE_MSTRING))
utype = -1;
else
@@ -62,7 +62,7 @@
#define IMPLEMENT_ASN1_STRING_FUNCTIONS(sname) \
IMPLEMENT_ASN1_TYPE(sname) \
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(sname, sname, sname) \
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(sname, sname, sname) \
sname *sname##_new(void) \
{ \
return ASN1_STRING_type_new(V_##sname); \
@@ -88,7 +88,7 @@ IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_UNIVERSALSTRING)
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_BMPSTRING)
IMPLEMENT_ASN1_TYPE(ASN1_NULL)
IMPLEMENT_ASN1_FUNCTIONS(ASN1_NULL)
IMPLEMENT_ASN1_FUNCTIONS_const(ASN1_NULL)
IMPLEMENT_ASN1_TYPE(ASN1_OBJECT)
@@ -97,18 +97,20 @@ IMPLEMENT_ASN1_TYPE(ASN1_ANY)
/* Just swallow an ASN1_SEQUENCE in an ASN1_STRING */
IMPLEMENT_ASN1_TYPE(ASN1_SEQUENCE)
IMPLEMENT_ASN1_FUNCTIONS_fname(ASN1_TYPE, ASN1_ANY, ASN1_TYPE)
IMPLEMENT_ASN1_FUNCTIONS_const_fname(ASN1_TYPE, ASN1_ANY, ASN1_TYPE)
/* Multistring types */
IMPLEMENT_ASN1_MSTRING(ASN1_PRINTABLE, B_ASN1_PRINTABLE)
IMPLEMENT_ASN1_FUNCTIONS_name(ASN1_STRING, ASN1_PRINTABLE)
IMPLEMENT_ASN1_FUNCTIONS_const_fname(ASN1_STRING, ASN1_PRINTABLE,
ASN1_PRINTABLE)
IMPLEMENT_ASN1_MSTRING(DISPLAYTEXT, B_ASN1_DISPLAYTEXT)
IMPLEMENT_ASN1_FUNCTIONS_name(ASN1_STRING, DISPLAYTEXT)
IMPLEMENT_ASN1_FUNCTIONS_const_fname(ASN1_STRING, DISPLAYTEXT, DISPLAYTEXT)
IMPLEMENT_ASN1_MSTRING(DIRECTORYSTRING, B_ASN1_DIRECTORYSTRING)
IMPLEMENT_ASN1_FUNCTIONS_name(ASN1_STRING, DIRECTORYSTRING)
IMPLEMENT_ASN1_FUNCTIONS_const_fname(ASN1_STRING, DIRECTORYSTRING,
DIRECTORYSTRING)
/* Three separate BOOLEAN type: normal, DEFAULT TRUE and DEFAULT FALSE */
IMPLEMENT_ASN1_TYPE_ex(ASN1_BOOLEAN, ASN1_BOOLEAN, -1)
@@ -117,8 +119,6 @@ IMPLEMENT_ASN1_TYPE_ex(ASN1_FBOOLEAN, ASN1_BOOLEAN, 0)
/* Special, OCTET STRING with indefinite length constructed support */
IMPLEMENT_ASN1_TYPE_ex(ASN1_OCTET_STRING_NDEF, ASN1_OCTET_STRING, ASN1_TFLG_NDEF)
ASN1_ITEM_TEMPLATE(ASN1_SEQUENCE_ANY) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, ASN1_SEQUENCE_ANY, ASN1_ANY)
ASN1_ITEM_TEMPLATE_END(ASN1_SEQUENCE_ANY)
@@ -66,6 +66,7 @@
#include <CCryptoBoringSSL_thread.h>
#include "../internal.h"
#include "internal.h"
/* Utility functions for manipulating fields and offsets */
@@ -91,8 +92,7 @@ int asn1_set_choice_selector(ASN1_VALUE **pval, int value,
static CRYPTO_refcount_t *asn1_get_references(ASN1_VALUE **pval,
const ASN1_ITEM *it) {
if (it->itype != ASN1_ITYPE_SEQUENCE &&
it->itype != ASN1_ITYPE_NDEF_SEQUENCE) {
if (it->itype != ASN1_ITYPE_SEQUENCE) {
return NULL;
}
const ASN1_AUX *aux = it->funcs;
@@ -118,6 +118,7 @@ int asn1_refcount_dec_and_test_zero(ASN1_VALUE **pval, const ASN1_ITEM *it) {
}
static ASN1_ENCODING *asn1_get_enc_ptr(ASN1_VALUE **pval, const ASN1_ITEM *it) {
assert(it->itype == ASN1_ITYPE_SEQUENCE);
const ASN1_AUX *aux;
if (!pval || !*pval) {
return NULL;
@@ -59,7 +59,7 @@
#define _POSIX_C_SOURCE 201410L /* for gmtime_r */
#endif
#include "asn1_locl.h"
#include "internal.h"
#include <time.h>
@@ -122,6 +122,19 @@ int EVP_EncodedLength(size_t *out_len, size_t len) {
return 1;
}
EVP_ENCODE_CTX *EVP_ENCODE_CTX_new(void) {
EVP_ENCODE_CTX *ret = OPENSSL_malloc(sizeof(EVP_ENCODE_CTX));
if (ret == NULL) {
return NULL;
}
OPENSSL_memset(ret, 0, sizeof(EVP_ENCODE_CTX));
return ret;
}
void EVP_ENCODE_CTX_free(EVP_ENCODE_CTX *ctx) {
OPENSSL_free(ctx);
}
void EVP_EncodeInit(EVP_ENCODE_CTX *ctx) {
OPENSSL_memset(ctx, 0, sizeof(EVP_ENCODE_CTX));
}
@@ -265,14 +278,17 @@ static uint8_t base64_ascii_to_bin(uint8_t a) {
const uint8_t is_slash = constant_time_eq_8(a, '/');
const uint8_t is_equals = constant_time_eq_8(a, '=');
uint8_t ret = 0xff; // 0xff signals invalid.
ret = constant_time_select_8(is_upper, a - 'A', ret); // [0,26)
ret = constant_time_select_8(is_lower, a - 'a' + 26, ret); // [26,52)
ret = constant_time_select_8(is_digit, a - '0' + 52, ret); // [52,62)
ret = constant_time_select_8(is_plus, 62, ret);
ret = constant_time_select_8(is_slash, 63, ret);
// Padding maps to zero, to be further handled by the caller.
ret = constant_time_select_8(is_equals, 0, ret);
uint8_t ret = 0;
ret |= is_upper & (a - 'A'); // [0,26)
ret |= is_lower & (a - 'a' + 26); // [26,52)
ret |= is_digit & (a - '0' + 52); // [52,62)
ret |= is_plus & 62;
ret |= is_slash & 63;
// Invalid inputs, 'A', and '=' have all been mapped to zero. Map invalid
// inputs to 0xff. Note '=' is padding and handled separately by the caller.
const uint8_t is_valid =
is_upper | is_lower | is_digit | is_plus | is_slash | is_equals;
ret |= ~is_valid;
return ret;
}
@@ -262,6 +262,8 @@ int BIO_should_io_special(const BIO *bio) {
int BIO_get_retry_reason(const BIO *bio) { return bio->retry_reason; }
void BIO_set_retry_reason(BIO *bio, int reason) { bio->retry_reason = reason; }
void BIO_clear_flags(BIO *bio, int flags) {
bio->flags &= ~flags;
}
@@ -116,17 +116,11 @@ static int mem_new(BIO *bio) {
}
static int mem_free(BIO *bio) {
BUF_MEM *b;
if (bio == NULL) {
return 0;
}
if (!bio->shutdown || !bio->init || bio->ptr == NULL) {
return 1;
}
b = (BUF_MEM *)bio->ptr;
BUF_MEM *b = (BUF_MEM *)bio->ptr;
if (bio->flags & BIO_FLAGS_MEM_RDONLY) {
b->data = NULL;
}
@@ -320,7 +320,7 @@ static int conn_new(BIO *bio) {
bio->init = 0;
bio->num = -1;
bio->flags = 0;
bio->ptr = (char *)BIO_CONNECT_new();
bio->ptr = BIO_CONNECT_new();
return bio->ptr != NULL;
}
@@ -340,10 +340,6 @@ static void conn_close_socket(BIO *bio) {
}
static int conn_free(BIO *bio) {
if (bio == NULL) {
return 0;
}
if (bio->shutdown) {
conn_close_socket(bio);
}
-4
View File
@@ -146,10 +146,6 @@ static int fd_new(BIO *bio) {
}
static int fd_free(BIO *bio) {
if (bio == NULL) {
return 0;
}
if (bio->shutdown) {
if (bio->init) {
BORINGSSL_CLOSE(bio->num);
+1 -7
View File
@@ -126,13 +126,7 @@ BIO *BIO_new_fp(FILE *stream, int close_flag) {
return ret;
}
static int file_new(BIO *bio) { return 1; }
static int file_free(BIO *bio) {
if (bio == NULL) {
return 0;
}
if (!bio->shutdown) {
return 1;
}
@@ -279,7 +273,7 @@ static const BIO_METHOD methods_filep = {
BIO_TYPE_FILE, "FILE pointer",
file_write, file_read,
NULL /* puts */, file_gets,
file_ctrl, file_new,
file_ctrl, NULL /* create */,
file_free, NULL /* callback_ctrl */,
};
+1 -6
View File
@@ -127,12 +127,7 @@ static void bio_destroy_pair(BIO *bio) {
}
static int bio_free(BIO *bio) {
struct bio_bio_st *b;
if (bio == NULL) {
return 0;
}
b = bio->ptr;
struct bio_bio_st *b = bio->ptr;
assert(b != NULL);
+3 -17
View File
@@ -81,19 +81,7 @@ static int closesocket(int sock) {
}
#endif
static int sock_new(BIO *bio) {
bio->init = 0;
bio->num = 0;
bio->ptr = NULL;
bio->flags = 0;
return 1;
}
static int sock_free(BIO *bio) {
if (bio == NULL) {
return 0;
}
if (bio->shutdown) {
if (bio->init) {
closesocket(bio->num);
@@ -105,17 +93,15 @@ static int sock_free(BIO *bio) {
}
static int sock_read(BIO *b, char *out, int outl) {
int ret = 0;
if (out == NULL) {
return 0;
}
bio_clear_socket_error();
#if defined(OPENSSL_WINDOWS)
ret = recv(b->num, out, outl, 0);
int ret = recv(b->num, out, outl, 0);
#else
ret = read(b->num, out, outl);
int ret = read(b->num, out, outl);
#endif
BIO_clear_retry_flags(b);
if (ret <= 0) {
@@ -186,7 +172,7 @@ static const BIO_METHOD methods_sockp = {
BIO_TYPE_SOCKET, "socket",
sock_write, sock_read,
NULL /* puts */, NULL /* gets, */,
sock_ctrl, sock_new,
sock_ctrl, NULL /* create */,
sock_free, NULL /* callback_ctrl */,
};
@@ -55,7 +55,11 @@ int bio_ip_and_port_to_socket_and_addr(int *out_sock,
ret = getaddrinfo(hostname, port_str, &hint, &result);
if (ret != 0) {
OPENSSL_PUT_ERROR(SYS, 0);
#if defined(OPENSSL_WINDOWS)
ERR_add_error_data(1, gai_strerrorA(ret));
#else
ERR_add_error_data(1, gai_strerror(ret));
#endif
return 0;
}
@@ -0,0 +1,156 @@
/* Copyright (c) 2021, 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_blake2.h>
#include <CCryptoBoringSSL_type_check.h>
#include "../internal.h"
// https://tools.ietf.org/html/rfc7693#section-2.6
static const uint64_t kIV[8] = {
UINT64_C(0x6a09e667f3bcc908), UINT64_C(0xbb67ae8584caa73b),
UINT64_C(0x3c6ef372fe94f82b), UINT64_C(0xa54ff53a5f1d36f1),
UINT64_C(0x510e527fade682d1), UINT64_C(0x9b05688c2b3e6c1f),
UINT64_C(0x1f83d9abfb41bd6b), UINT64_C(0x5be0cd19137e2179),
};
// https://tools.ietf.org/html/rfc7693#section-2.7
static const uint8_t kSigma[10 * 16] = {
// clang-format off
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,
13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,
6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,
10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,
// clang-format on
};
// https://tools.ietf.org/html/rfc7693#section-3.1
static void blake2b_mix(uint64_t v[16], int a, int b, int c, int d, uint64_t x,
uint64_t y) {
v[a] = v[a] + v[b] + x;
v[d] = CRYPTO_rotr_u64(v[d] ^ v[a], 32);
v[c] = v[c] + v[d];
v[b] = CRYPTO_rotr_u64(v[b] ^ v[c], 24);
v[a] = v[a] + v[b] + y;
v[d] = CRYPTO_rotr_u64(v[d] ^ v[a], 16);
v[c] = v[c] + v[d];
v[b] = CRYPTO_rotr_u64(v[b] ^ v[c], 63);
}
static void blake2b_transform(
BLAKE2B_CTX *b2b,
const uint64_t block_words[BLAKE2B_CBLOCK / sizeof(uint64_t)],
size_t num_bytes, int is_final_block) {
// https://tools.ietf.org/html/rfc7693#section-3.2
uint64_t v[16];
OPENSSL_STATIC_ASSERT(sizeof(v) == sizeof(b2b->h) + sizeof(kIV), "");
OPENSSL_memcpy(v, b2b->h, sizeof(b2b->h));
OPENSSL_memcpy(&v[8], kIV, sizeof(kIV));
b2b->t_low += num_bytes;
if (b2b->t_low < num_bytes) {
b2b->t_high++;
}
v[12] ^= b2b->t_low;
v[13] ^= b2b->t_high;
if (is_final_block) {
v[14] = ~v[14];
}
for (int round = 0; round < 12; round++) {
const uint8_t *const s = &kSigma[16 * (round % 10)];
blake2b_mix(v, 0, 4, 8, 12, block_words[s[0]], block_words[s[1]]);
blake2b_mix(v, 1, 5, 9, 13, block_words[s[2]], block_words[s[3]]);
blake2b_mix(v, 2, 6, 10, 14, block_words[s[4]], block_words[s[5]]);
blake2b_mix(v, 3, 7, 11, 15, block_words[s[6]], block_words[s[7]]);
blake2b_mix(v, 0, 5, 10, 15, block_words[s[8]], block_words[s[9]]);
blake2b_mix(v, 1, 6, 11, 12, block_words[s[10]], block_words[s[11]]);
blake2b_mix(v, 2, 7, 8, 13, block_words[s[12]], block_words[s[13]]);
blake2b_mix(v, 3, 4, 9, 14, block_words[s[14]], block_words[s[15]]);
}
for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(b2b->h); i++) {
b2b->h[i] ^= v[i];
b2b->h[i] ^= v[i + 8];
}
}
void BLAKE2B256_Init(BLAKE2B_CTX *b2b) {
OPENSSL_memset(b2b, 0, sizeof(BLAKE2B_CTX));
OPENSSL_STATIC_ASSERT(sizeof(kIV) == sizeof(b2b->h), "");
OPENSSL_memcpy(&b2b->h, kIV, sizeof(kIV));
// https://tools.ietf.org/html/rfc7693#section-2.5
b2b->h[0] ^= 0x01010000 | BLAKE2B256_DIGEST_LENGTH;
}
void BLAKE2B256_Update(BLAKE2B_CTX *b2b, const void *in_data, size_t len) {
const uint8_t *data = (const uint8_t *)in_data;
size_t todo = sizeof(b2b->block.bytes) - b2b->block_used;
if (todo > len) {
todo = len;
}
OPENSSL_memcpy(&b2b->block.bytes[b2b->block_used], data, todo);
b2b->block_used += todo;
data += todo;
len -= todo;
if (!len) {
return;
}
// More input remains therefore we must have filled |b2b->block|.
assert(b2b->block_used == BLAKE2B_CBLOCK);
blake2b_transform(b2b, b2b->block.words, BLAKE2B_CBLOCK,
/*is_final_block=*/0);
b2b->block_used = 0;
while (len > BLAKE2B_CBLOCK) {
uint64_t block_words[BLAKE2B_CBLOCK / sizeof(uint64_t)];
OPENSSL_memcpy(block_words, data, sizeof(block_words));
blake2b_transform(b2b, block_words, BLAKE2B_CBLOCK, /*is_final_block=*/0);
data += BLAKE2B_CBLOCK;
len -= BLAKE2B_CBLOCK;
}
OPENSSL_memcpy(b2b->block.bytes, data, len);
b2b->block_used = len;
}
void BLAKE2B256_Final(uint8_t out[BLAKE2B256_DIGEST_LENGTH], BLAKE2B_CTX *b2b) {
OPENSSL_memset(&b2b->block.bytes[b2b->block_used], 0,
sizeof(b2b->block.bytes) - b2b->block_used);
blake2b_transform(b2b, b2b->block.words, b2b->block_used,
/*is_final_block=*/1);
OPENSSL_STATIC_ASSERT(BLAKE2B256_DIGEST_LENGTH <= sizeof(b2b->h), "");
memcpy(out, b2b->h, BLAKE2B256_DIGEST_LENGTH);
}
void BLAKE2B256(const uint8_t *data, size_t len,
uint8_t out[BLAKE2B256_DIGEST_LENGTH]) {
BLAKE2B_CTX ctx;
BLAKE2B256_Init(&ctx);
BLAKE2B256_Update(&ctx, data, len);
BLAKE2B256_Final(out, &ctx);
}
@@ -20,25 +20,18 @@
int BN_parse_asn1_unsigned(CBS *cbs, BIGNUM *ret) {
CBS child;
int is_negative;
if (!CBS_get_asn1(cbs, &child, CBS_ASN1_INTEGER) ||
CBS_len(&child) == 0) {
!CBS_is_valid_asn1_integer(&child, &is_negative)) {
OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING);
return 0;
}
if (CBS_data(&child)[0] & 0x80) {
if (is_negative) {
OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
return 0;
}
// INTEGERs must be minimal.
if (CBS_data(&child)[0] == 0x00 &&
CBS_len(&child) > 1 &&
!(CBS_data(&child)[1] & 0x80)) {
OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING);
return 0;
}
return BN_bin2bn(CBS_data(&child), CBS_len(&child), ret) != NULL;
}
@@ -29,8 +29,10 @@ static const unsigned kMaxDepth = 2048;
// is_string_type returns one if |tag| is a string type and zero otherwise. It
// ignores the constructed bit.
static int is_string_type(unsigned tag) {
// While BER supports constructed BIT STRINGS, OpenSSL misparses them. To
// avoid acting on an ambiguous input, we do not support constructed BIT
// STRINGS. See https://github.com/openssl/openssl/issues/12810.
switch (tag & ~CBS_ASN1_CONSTRUCTED) {
case CBS_ASN1_BITSTRING:
case CBS_ASN1_OCTETSTRING:
case CBS_ASN1_UTF8STRING:
case CBS_ASN1_NUMERICSTRING:
@@ -53,7 +55,7 @@ static int is_string_type(unsigned tag) {
// depending on whether an indefinite length element or constructed string was
// found. The value of |orig_in| is not changed. It returns one on success (i.e.
// |*ber_found| was set) and zero on error.
static int cbs_find_ber(const CBS *orig_in, char *ber_found, unsigned depth) {
static int cbs_find_ber(const CBS *orig_in, int *ber_found, unsigned depth) {
CBS in;
if (depth > kMaxDepth) {
@@ -68,14 +70,11 @@ static int cbs_find_ber(const CBS *orig_in, char *ber_found, unsigned depth) {
unsigned tag;
size_t header_len;
if (!CBS_get_any_ber_asn1_element(&in, &contents, &tag, &header_len)) {
if (!CBS_get_any_ber_asn1_element(&in, &contents, &tag, &header_len,
ber_found)) {
return 0;
}
if (CBS_len(&contents) == header_len &&
header_len > 0 &&
CBS_data(&contents)[header_len-1] == 0x80) {
// Found an indefinite-length element.
*ber_found = 1;
if (*ber_found) {
return 1;
}
if (tag & CBS_ASN1_CONSTRUCTED) {
@@ -120,9 +119,11 @@ static int cbs_convert_ber(CBS *in, CBB *out, unsigned string_tag,
CBS contents;
unsigned tag, child_string_tag = string_tag;
size_t header_len;
int ber_found;
CBB *out_contents, out_contents_storage;
if (!CBS_get_any_ber_asn1_element(in, &contents, &tag, &header_len)) {
if (!CBS_get_any_ber_asn1_element(in, &contents, &tag, &header_len,
&ber_found)) {
return 0;
}
@@ -194,7 +195,7 @@ int CBS_asn1_ber_to_der(CBS *in, CBS *out, uint8_t **out_storage) {
// First, do a quick walk to find any indefinite-length elements. Most of the
// time we hope that there aren't any and thus we can quickly return.
char conversion_needed;
int conversion_needed;
if (!cbs_find_ber(in, &conversion_needed, 0)) {
return 0;
}
@@ -404,6 +404,15 @@ int CBB_add_bytes(CBB *cbb, const uint8_t *data, size_t len) {
return 1;
}
int CBB_add_zeros(CBB *cbb, size_t len) {
uint8_t *out;
if (!CBB_add_space(cbb, &out, len)) {
return 0;
}
OPENSSL_memset(out, 0, len);
return 1;
}
int CBB_add_space(CBB *cbb, uint8_t **out_data, size_t len) {
if (!CBB_flush(cbb) ||
!cbb_buffer_add(cbb->base, out_data, len)) {
@@ -447,6 +456,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 +476,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 +487,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;
@@ -192,6 +216,14 @@ int CBS_get_u24_length_prefixed(CBS *cbs, CBS *out) {
return cbs_get_length_prefixed(cbs, out, 3);
}
int CBS_get_until_first(CBS *cbs, CBS *out, uint8_t c) {
const uint8_t *split = OPENSSL_memchr(CBS_data(cbs), c, CBS_len(cbs));
if (split == NULL) {
return 0;
}
return CBS_get_bytes(cbs, out, split - CBS_data(cbs));
}
// parse_base128_integer reads a big-endian base-128 integer from |cbs| and sets
// |*out| to the result. This is the encoding used in DER for both high tag
// number form and OID components.
@@ -230,8 +262,7 @@ static int parse_asn1_tag(CBS *cbs, unsigned *out) {
//
// If the number portion is 31 (0x1f, the largest value that fits in the
// allotted bits), then the tag is more than one byte long and the
// continuation bytes contain the tag number. This parser only supports tag
// numbers less than 31 (and thus single-byte tags).
// continuation bytes contain the tag number.
unsigned tag = ((unsigned)tag_byte & 0xe0) << CBS_ASN1_TAG_SHIFT;
unsigned tag_number = tag_byte & 0x1f;
if (tag_number == 0x1f) {
@@ -239,7 +270,7 @@ static int parse_asn1_tag(CBS *cbs, unsigned *out) {
if (!parse_base128_integer(cbs, &v) ||
// Check the tag number is within our supported bounds.
v > CBS_ASN1_TAG_NUMBER_MASK ||
// Small tag numbers should have used low tag number form.
// Small tag numbers should have used low tag number form, even in BER.
v < 0x1f) {
return 0;
}
@@ -253,13 +284,17 @@ static int parse_asn1_tag(CBS *cbs, unsigned *out) {
}
static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, unsigned *out_tag,
size_t *out_header_len, int ber_ok) {
size_t *out_header_len, int *out_ber_found,
int ber_ok) {
CBS header = *cbs;
CBS throwaway;
if (out == NULL) {
out = &throwaway;
}
if (ber_ok) {
*out_ber_found = 0;
}
unsigned tag;
if (!parse_asn1_tag(&header, &tag)) {
@@ -297,27 +332,38 @@ static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, unsigned *out_tag,
if (out_header_len != NULL) {
*out_header_len = header_len;
}
*out_ber_found = 1;
return CBS_get_bytes(cbs, out, header_len);
}
// ITU-T X.690 clause 8.1.3.5.c specifies that the value 0xff shall not be
// used as the first byte of the length. If this parser encounters that
// value, num_bytes will be parsed as 127, which will fail the check below.
// value, num_bytes will be parsed as 127, which will fail this check.
if (num_bytes == 0 || num_bytes > 4) {
return 0;
}
if (!cbs_get_u(&header, &len64, num_bytes)) {
return 0;
}
// ITU-T X.690 section 10.1 (DER length forms) requires encoding the length
// with the minimum number of octets.
// ITU-T X.690 section 10.1 (DER length forms) requires encoding the
// length with the minimum number of octets. BER could, technically, have
// 125 superfluous zero bytes. We do not attempt to handle that and still
// require that the length fit in a |uint32_t| for BER.
if (len64 < 128) {
// Length should have used short-form encoding.
return 0;
if (ber_ok) {
*out_ber_found = 1;
} else {
return 0;
}
}
if ((len64 >> ((num_bytes-1)*8)) == 0) {
if ((len64 >> ((num_bytes - 1) * 8)) == 0) {
// Length should have been at least one byte shorter.
return 0;
if (ber_ok) {
*out_ber_found = 1;
} else {
return 0;
}
}
len = len64;
if (len + header_len + num_bytes < len) {
@@ -350,13 +396,15 @@ int CBS_get_any_asn1(CBS *cbs, CBS *out, unsigned *out_tag) {
int CBS_get_any_asn1_element(CBS *cbs, CBS *out, unsigned *out_tag,
size_t *out_header_len) {
return cbs_get_any_asn1_element(cbs, out, out_tag, out_header_len,
0 /* DER only */);
NULL, 0 /* DER only */);
}
int CBS_get_any_ber_asn1_element(CBS *cbs, CBS *out, unsigned *out_tag,
size_t *out_header_len) {
return cbs_get_any_asn1_element(cbs, out, out_tag, out_header_len,
1 /* BER allowed */);
size_t *out_header_len, int *out_ber_found) {
int ber_found_temp;
return cbs_get_any_asn1_element(
cbs, out, out_tag, out_header_len,
out_ber_found ? out_ber_found : &ber_found_temp, 1 /* BER allowed */);
}
static int cbs_get_asn1(CBS *cbs, CBS *out, unsigned tag_value,
@@ -402,29 +450,14 @@ int CBS_peek_asn1_tag(const CBS *cbs, unsigned tag_value) {
int CBS_get_asn1_uint64(CBS *cbs, uint64_t *out) {
CBS bytes;
if (!CBS_get_asn1(cbs, &bytes, CBS_ASN1_INTEGER)) {
if (!CBS_get_asn1(cbs, &bytes, CBS_ASN1_INTEGER) ||
!CBS_is_unsigned_asn1_integer(&bytes)) {
return 0;
}
*out = 0;
const uint8_t *data = CBS_data(&bytes);
size_t len = CBS_len(&bytes);
if (len == 0) {
// An INTEGER is encoded with at least one octet.
return 0;
}
if ((data[0] & 0x80) != 0) {
// Negative number.
return 0;
}
if (data[0] == 0 && len > 1 && (data[1] & 0x80) == 0) {
// Extra leading zeros.
return 0;
}
for (size_t i = 0; i < len; i++) {
if ((*out >> 56) != 0) {
// Too large to represent as a uint64_t.
@@ -438,31 +471,21 @@ int CBS_get_asn1_uint64(CBS *cbs, uint64_t *out) {
}
int CBS_get_asn1_int64(CBS *cbs, int64_t *out) {
int is_negative;
CBS bytes;
if (!CBS_get_asn1(cbs, &bytes, CBS_ASN1_INTEGER)) {
if (!CBS_get_asn1(cbs, &bytes, CBS_ASN1_INTEGER) ||
!CBS_is_valid_asn1_integer(&bytes, &is_negative)) {
return 0;
}
const uint8_t *data = CBS_data(&bytes);
const size_t len = CBS_len(&bytes);
if (len == 0 || len > sizeof(int64_t)) {
// An INTEGER is encoded with at least one octet.
if (len > sizeof(int64_t)) {
return 0;
}
if (len > 1) {
if (data[0] == 0 && (data[1] & 0x80) == 0) {
return 0; // Extra leading zeros.
}
if (data[0] == 0xff && (data[1] & 0x80) != 0) {
return 0; // Extra leading 0xff.
}
}
union {
int64_t i;
uint8_t bytes[sizeof(int64_t)];
} u;
const int is_negative = (data[0] & 0x80);
memset(u.bytes, is_negative ? 0xff : 0, sizeof(u.bytes)); // Sign-extend.
for (size_t i = 0; i < len; i++) {
u.bytes[i] = data[len - i - 1];
@@ -611,6 +634,30 @@ int CBS_asn1_bitstring_has_bit(const CBS *cbs, unsigned bit) {
(CBS_data(cbs)[byte_num] & (1 << bit_num)) != 0;
}
int CBS_is_valid_asn1_integer(const CBS *cbs, int *out_is_negative) {
CBS copy = *cbs;
uint8_t first_byte, second_byte;
if (!CBS_get_u8(&copy, &first_byte)) {
return 0; // INTEGERs may not be empty.
}
if (out_is_negative != NULL) {
*out_is_negative = (first_byte & 0x80) != 0;
}
if (!CBS_get_u8(&copy, &second_byte)) {
return 1; // One byte INTEGERs are always minimal.
}
if ((first_byte == 0x00 && (second_byte & 0x80) == 0) ||
(first_byte == 0xff && (second_byte & 0x80) != 0)) {
return 0; // The value is minimal iff the first 9 bits are not all equal.
}
return 1;
}
int CBS_is_unsigned_asn1_integer(const CBS *cbs) {
int is_negative;
return CBS_is_valid_asn1_integer(cbs, &is_negative) && !is_negative;
}
static int add_decimal(CBB *out, uint64_t v) {
char buf[DECIMAL_SIZE(uint64_t) + 1];
BIO_snprintf(buf, sizeof(buf), "%" PRIu64, v);
@@ -17,6 +17,7 @@
#include <CCryptoBoringSSL_arm_arch.h>
.private_extern _OPENSSL_armcap_P
.section __TEXT,__const
@@ -35,6 +36,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 +50,7 @@ _ChaCha20_ctr32:
b.ne ChaCha20_neon
Lshort:
AARCH64_SIGN_LINK_REGISTER
stp x29,x30,[sp,#-96]!
add x29,sp,#0
@@ -260,6 +263,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 +320,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 +708,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 +818,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 +1988,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
@@ -18,6 +18,7 @@
#include <CCryptoBoringSSL_arm_arch.h>
.hidden OPENSSL_armcap_P
.section .rodata
@@ -36,6 +37,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 +51,7 @@ ChaCha20_ctr32:
b.ne ChaCha20_neon
.Lshort:
AARCH64_SIGN_LINK_REGISTER
stp x29,x30,[sp,#-96]!
add x29,sp,#0
@@ -261,6 +264,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 +321,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 +709,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 +819,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 +1989,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
@@ -1,7 +1,7 @@
#define BORINGSSL_PREFIX CCryptoBoringSSL
#if defined(__i386__) && defined(__linux__)
# This file is generated from a similarly-named Perl script in the BoringSSL
# source tree. Do not edit by hand.
// This file is generated from a similarly-named Perl script in the BoringSSL
// source tree. Do not edit by hand.
#if defined(__i386__)
#if defined(BORINGSSL_PREFIX)
@@ -0,0 +1,979 @@
#define BORINGSSL_PREFIX CCryptoBoringSSL
#if defined(__i386__) && defined(_WIN32)
// This file is generated from a similarly-named Perl script in the BoringSSL
// source tree. Do not edit by hand.
#if defined(__i386__)
#if defined(BORINGSSL_PREFIX)
#include <CCryptoBoringSSL_boringssl_prefix_symbols_asm.h>
#endif
.text
.globl _ChaCha20_ctr32
.hidden _ChaCha20_ctr32
.def _ChaCha20_ctr32; .scl 2; .type 32; .endef
.align 16
_ChaCha20_ctr32:
.L_ChaCha20_ctr32_begin:
pushl %ebp
pushl %ebx
pushl %esi
pushl %edi
xorl %eax,%eax
cmpl 28(%esp),%eax
je .L000no_data
call .Lpic_point
.Lpic_point:
popl %eax
leal _OPENSSL_ia32cap_P,%ebp
testl $16777216,(%ebp)
jz .L001x86
testl $512,4(%ebp)
jz .L001x86
jmp .Lssse3_shortcut
.L001x86:
movl 32(%esp),%esi
movl 36(%esp),%edi
subl $132,%esp
movl (%esi),%eax
movl 4(%esi),%ebx
movl 8(%esi),%ecx
movl 12(%esi),%edx
movl %eax,80(%esp)
movl %ebx,84(%esp)
movl %ecx,88(%esp)
movl %edx,92(%esp)
movl 16(%esi),%eax
movl 20(%esi),%ebx
movl 24(%esi),%ecx
movl 28(%esi),%edx
movl %eax,96(%esp)
movl %ebx,100(%esp)
movl %ecx,104(%esp)
movl %edx,108(%esp)
movl (%edi),%eax
movl 4(%edi),%ebx
movl 8(%edi),%ecx
movl 12(%edi),%edx
subl $1,%eax
movl %eax,112(%esp)
movl %ebx,116(%esp)
movl %ecx,120(%esp)
movl %edx,124(%esp)
jmp .L002entry
.align 16
.L003outer_loop:
movl %ebx,156(%esp)
movl %eax,152(%esp)
movl %ecx,160(%esp)
.L002entry:
movl $1634760805,%eax
movl $857760878,4(%esp)
movl $2036477234,8(%esp)
movl $1797285236,12(%esp)
movl 84(%esp),%ebx
movl 88(%esp),%ebp
movl 104(%esp),%ecx
movl 108(%esp),%esi
movl 116(%esp),%edx
movl 120(%esp),%edi
movl %ebx,20(%esp)
movl %ebp,24(%esp)
movl %ecx,40(%esp)
movl %esi,44(%esp)
movl %edx,52(%esp)
movl %edi,56(%esp)
movl 92(%esp),%ebx
movl 124(%esp),%edi
movl 112(%esp),%edx
movl 80(%esp),%ebp
movl 96(%esp),%ecx
movl 100(%esp),%esi
addl $1,%edx
movl %ebx,28(%esp)
movl %edi,60(%esp)
movl %edx,112(%esp)
movl $10,%ebx
jmp .L004loop
.align 16
.L004loop:
addl %ebp,%eax
movl %ebx,128(%esp)
movl %ebp,%ebx
xorl %eax,%edx
roll $16,%edx
addl %edx,%ecx
xorl %ecx,%ebx
movl 52(%esp),%edi
roll $12,%ebx
movl 20(%esp),%ebp
addl %ebx,%eax
xorl %eax,%edx
movl %eax,(%esp)
roll $8,%edx
movl 4(%esp),%eax
addl %edx,%ecx
movl %edx,48(%esp)
xorl %ecx,%ebx
addl %ebp,%eax
roll $7,%ebx
xorl %eax,%edi
movl %ecx,32(%esp)
roll $16,%edi
movl %ebx,16(%esp)
addl %edi,%esi
movl 40(%esp),%ecx
xorl %esi,%ebp
movl 56(%esp),%edx
roll $12,%ebp
movl 24(%esp),%ebx
addl %ebp,%eax
xorl %eax,%edi
movl %eax,4(%esp)
roll $8,%edi
movl 8(%esp),%eax
addl %edi,%esi
movl %edi,52(%esp)
xorl %esi,%ebp
addl %ebx,%eax
roll $7,%ebp
xorl %eax,%edx
movl %esi,36(%esp)
roll $16,%edx
movl %ebp,20(%esp)
addl %edx,%ecx
movl 44(%esp),%esi
xorl %ecx,%ebx
movl 60(%esp),%edi
roll $12,%ebx
movl 28(%esp),%ebp
addl %ebx,%eax
xorl %eax,%edx
movl %eax,8(%esp)
roll $8,%edx
movl 12(%esp),%eax
addl %edx,%ecx
movl %edx,56(%esp)
xorl %ecx,%ebx
addl %ebp,%eax
roll $7,%ebx
xorl %eax,%edi
roll $16,%edi
movl %ebx,24(%esp)
addl %edi,%esi
xorl %esi,%ebp
roll $12,%ebp
movl 20(%esp),%ebx
addl %ebp,%eax
xorl %eax,%edi
movl %eax,12(%esp)
roll $8,%edi
movl (%esp),%eax
addl %edi,%esi
movl %edi,%edx
xorl %esi,%ebp
addl %ebx,%eax
roll $7,%ebp
xorl %eax,%edx
roll $16,%edx
movl %ebp,28(%esp)
addl %edx,%ecx
xorl %ecx,%ebx
movl 48(%esp),%edi
roll $12,%ebx
movl 24(%esp),%ebp
addl %ebx,%eax
xorl %eax,%edx
movl %eax,(%esp)
roll $8,%edx
movl 4(%esp),%eax
addl %edx,%ecx
movl %edx,60(%esp)
xorl %ecx,%ebx
addl %ebp,%eax
roll $7,%ebx
xorl %eax,%edi
movl %ecx,40(%esp)
roll $16,%edi
movl %ebx,20(%esp)
addl %edi,%esi
movl 32(%esp),%ecx
xorl %esi,%ebp
movl 52(%esp),%edx
roll $12,%ebp
movl 28(%esp),%ebx
addl %ebp,%eax
xorl %eax,%edi
movl %eax,4(%esp)
roll $8,%edi
movl 8(%esp),%eax
addl %edi,%esi
movl %edi,48(%esp)
xorl %esi,%ebp
addl %ebx,%eax
roll $7,%ebp
xorl %eax,%edx
movl %esi,44(%esp)
roll $16,%edx
movl %ebp,24(%esp)
addl %edx,%ecx
movl 36(%esp),%esi
xorl %ecx,%ebx
movl 56(%esp),%edi
roll $12,%ebx
movl 16(%esp),%ebp
addl %ebx,%eax
xorl %eax,%edx
movl %eax,8(%esp)
roll $8,%edx
movl 12(%esp),%eax
addl %edx,%ecx
movl %edx,52(%esp)
xorl %ecx,%ebx
addl %ebp,%eax
roll $7,%ebx
xorl %eax,%edi
roll $16,%edi
movl %ebx,28(%esp)
addl %edi,%esi
xorl %esi,%ebp
movl 48(%esp),%edx
roll $12,%ebp
movl 128(%esp),%ebx
addl %ebp,%eax
xorl %eax,%edi
movl %eax,12(%esp)
roll $8,%edi
movl (%esp),%eax
addl %edi,%esi
movl %edi,56(%esp)
xorl %esi,%ebp
roll $7,%ebp
decl %ebx
jnz .L004loop
movl 160(%esp),%ebx
addl $1634760805,%eax
addl 80(%esp),%ebp
addl 96(%esp),%ecx
addl 100(%esp),%esi
cmpl $64,%ebx
jb .L005tail
movl 156(%esp),%ebx
addl 112(%esp),%edx
addl 120(%esp),%edi
xorl (%ebx),%eax
xorl 16(%ebx),%ebp
movl %eax,(%esp)
movl 152(%esp),%eax
xorl 32(%ebx),%ecx
xorl 36(%ebx),%esi
xorl 48(%ebx),%edx
xorl 56(%ebx),%edi
movl %ebp,16(%eax)
movl %ecx,32(%eax)
movl %esi,36(%eax)
movl %edx,48(%eax)
movl %edi,56(%eax)
movl 4(%esp),%ebp
movl 8(%esp),%ecx
movl 12(%esp),%esi
movl 20(%esp),%edx
movl 24(%esp),%edi
addl $857760878,%ebp
addl $2036477234,%ecx
addl $1797285236,%esi
addl 84(%esp),%edx
addl 88(%esp),%edi
xorl 4(%ebx),%ebp
xorl 8(%ebx),%ecx
xorl 12(%ebx),%esi
xorl 20(%ebx),%edx
xorl 24(%ebx),%edi
movl %ebp,4(%eax)
movl %ecx,8(%eax)
movl %esi,12(%eax)
movl %edx,20(%eax)
movl %edi,24(%eax)
movl 28(%esp),%ebp
movl 40(%esp),%ecx
movl 44(%esp),%esi
movl 52(%esp),%edx
movl 60(%esp),%edi
addl 92(%esp),%ebp
addl 104(%esp),%ecx
addl 108(%esp),%esi
addl 116(%esp),%edx
addl 124(%esp),%edi
xorl 28(%ebx),%ebp
xorl 40(%ebx),%ecx
xorl 44(%ebx),%esi
xorl 52(%ebx),%edx
xorl 60(%ebx),%edi
leal 64(%ebx),%ebx
movl %ebp,28(%eax)
movl (%esp),%ebp
movl %ecx,40(%eax)
movl 160(%esp),%ecx
movl %esi,44(%eax)
movl %edx,52(%eax)
movl %edi,60(%eax)
movl %ebp,(%eax)
leal 64(%eax),%eax
subl $64,%ecx
jnz .L003outer_loop
jmp .L006done
.L005tail:
addl 112(%esp),%edx
addl 120(%esp),%edi
movl %eax,(%esp)
movl %ebp,16(%esp)
movl %ecx,32(%esp)
movl %esi,36(%esp)
movl %edx,48(%esp)
movl %edi,56(%esp)
movl 4(%esp),%ebp
movl 8(%esp),%ecx
movl 12(%esp),%esi
movl 20(%esp),%edx
movl 24(%esp),%edi
addl $857760878,%ebp
addl $2036477234,%ecx
addl $1797285236,%esi
addl 84(%esp),%edx
addl 88(%esp),%edi
movl %ebp,4(%esp)
movl %ecx,8(%esp)
movl %esi,12(%esp)
movl %edx,20(%esp)
movl %edi,24(%esp)
movl 28(%esp),%ebp
movl 40(%esp),%ecx
movl 44(%esp),%esi
movl 52(%esp),%edx
movl 60(%esp),%edi
addl 92(%esp),%ebp
addl 104(%esp),%ecx
addl 108(%esp),%esi
addl 116(%esp),%edx
addl 124(%esp),%edi
movl %ebp,28(%esp)
movl 156(%esp),%ebp
movl %ecx,40(%esp)
movl 152(%esp),%ecx
movl %esi,44(%esp)
xorl %esi,%esi
movl %edx,52(%esp)
movl %edi,60(%esp)
xorl %eax,%eax
xorl %edx,%edx
.L007tail_loop:
movb (%esi,%ebp,1),%al
movb (%esp,%esi,1),%dl
leal 1(%esi),%esi
xorb %dl,%al
movb %al,-1(%ecx,%esi,1)
decl %ebx
jnz .L007tail_loop
.L006done:
addl $132,%esp
.L000no_data:
popl %edi
popl %esi
popl %ebx
popl %ebp
ret
.globl _ChaCha20_ssse3
.hidden _ChaCha20_ssse3
.def _ChaCha20_ssse3; .scl 2; .type 32; .endef
.align 16
_ChaCha20_ssse3:
.L_ChaCha20_ssse3_begin:
pushl %ebp
pushl %ebx
pushl %esi
pushl %edi
.Lssse3_shortcut:
movl 20(%esp),%edi
movl 24(%esp),%esi
movl 28(%esp),%ecx
movl 32(%esp),%edx
movl 36(%esp),%ebx
movl %esp,%ebp
subl $524,%esp
andl $-64,%esp
movl %ebp,512(%esp)
leal .Lssse3_data-.Lpic_point(%eax),%eax
movdqu (%ebx),%xmm3
cmpl $256,%ecx
jb .L0081x
movl %edx,516(%esp)
movl %ebx,520(%esp)
subl $256,%ecx
leal 384(%esp),%ebp
movdqu (%edx),%xmm7
pshufd $0,%xmm3,%xmm0
pshufd $85,%xmm3,%xmm1
pshufd $170,%xmm3,%xmm2
pshufd $255,%xmm3,%xmm3
paddd 48(%eax),%xmm0
pshufd $0,%xmm7,%xmm4
pshufd $85,%xmm7,%xmm5
psubd 64(%eax),%xmm0
pshufd $170,%xmm7,%xmm6
pshufd $255,%xmm7,%xmm7
movdqa %xmm0,64(%ebp)
movdqa %xmm1,80(%ebp)
movdqa %xmm2,96(%ebp)
movdqa %xmm3,112(%ebp)
movdqu 16(%edx),%xmm3
movdqa %xmm4,-64(%ebp)
movdqa %xmm5,-48(%ebp)
movdqa %xmm6,-32(%ebp)
movdqa %xmm7,-16(%ebp)
movdqa 32(%eax),%xmm7
leal 128(%esp),%ebx
pshufd $0,%xmm3,%xmm0
pshufd $85,%xmm3,%xmm1
pshufd $170,%xmm3,%xmm2
pshufd $255,%xmm3,%xmm3
pshufd $0,%xmm7,%xmm4
pshufd $85,%xmm7,%xmm5
pshufd $170,%xmm7,%xmm6
pshufd $255,%xmm7,%xmm7
movdqa %xmm0,(%ebp)
movdqa %xmm1,16(%ebp)
movdqa %xmm2,32(%ebp)
movdqa %xmm3,48(%ebp)
movdqa %xmm4,-128(%ebp)
movdqa %xmm5,-112(%ebp)
movdqa %xmm6,-96(%ebp)
movdqa %xmm7,-80(%ebp)
leal 128(%esi),%esi
leal 128(%edi),%edi
jmp .L009outer_loop
.align 16
.L009outer_loop:
movdqa -112(%ebp),%xmm1
movdqa -96(%ebp),%xmm2
movdqa -80(%ebp),%xmm3
movdqa -48(%ebp),%xmm5
movdqa -32(%ebp),%xmm6
movdqa -16(%ebp),%xmm7
movdqa %xmm1,-112(%ebx)
movdqa %xmm2,-96(%ebx)
movdqa %xmm3,-80(%ebx)
movdqa %xmm5,-48(%ebx)
movdqa %xmm6,-32(%ebx)
movdqa %xmm7,-16(%ebx)
movdqa 32(%ebp),%xmm2
movdqa 48(%ebp),%xmm3
movdqa 64(%ebp),%xmm4
movdqa 80(%ebp),%xmm5
movdqa 96(%ebp),%xmm6
movdqa 112(%ebp),%xmm7
paddd 64(%eax),%xmm4
movdqa %xmm2,32(%ebx)
movdqa %xmm3,48(%ebx)
movdqa %xmm4,64(%ebx)
movdqa %xmm5,80(%ebx)
movdqa %xmm6,96(%ebx)
movdqa %xmm7,112(%ebx)
movdqa %xmm4,64(%ebp)
movdqa -128(%ebp),%xmm0
movdqa %xmm4,%xmm6
movdqa -64(%ebp),%xmm3
movdqa (%ebp),%xmm4
movdqa 16(%ebp),%xmm5
movl $10,%edx
nop
.align 16
.L010loop:
paddd %xmm3,%xmm0
movdqa %xmm3,%xmm2
pxor %xmm0,%xmm6
pshufb (%eax),%xmm6
paddd %xmm6,%xmm4
pxor %xmm4,%xmm2
movdqa -48(%ebx),%xmm3
movdqa %xmm2,%xmm1
pslld $12,%xmm2
psrld $20,%xmm1
por %xmm1,%xmm2
movdqa -112(%ebx),%xmm1
paddd %xmm2,%xmm0
movdqa 80(%ebx),%xmm7
pxor %xmm0,%xmm6
movdqa %xmm0,-128(%ebx)
pshufb 16(%eax),%xmm6
paddd %xmm6,%xmm4
movdqa %xmm6,64(%ebx)
pxor %xmm4,%xmm2
paddd %xmm3,%xmm1
movdqa %xmm2,%xmm0
pslld $7,%xmm2
psrld $25,%xmm0
pxor %xmm1,%xmm7
por %xmm0,%xmm2
movdqa %xmm4,(%ebx)
pshufb (%eax),%xmm7
movdqa %xmm2,-64(%ebx)
paddd %xmm7,%xmm5
movdqa 32(%ebx),%xmm4
pxor %xmm5,%xmm3
movdqa -32(%ebx),%xmm2
movdqa %xmm3,%xmm0
pslld $12,%xmm3
psrld $20,%xmm0
por %xmm0,%xmm3
movdqa -96(%ebx),%xmm0
paddd %xmm3,%xmm1
movdqa 96(%ebx),%xmm6
pxor %xmm1,%xmm7
movdqa %xmm1,-112(%ebx)
pshufb 16(%eax),%xmm7
paddd %xmm7,%xmm5
movdqa %xmm7,80(%ebx)
pxor %xmm5,%xmm3
paddd %xmm2,%xmm0
movdqa %xmm3,%xmm1
pslld $7,%xmm3
psrld $25,%xmm1
pxor %xmm0,%xmm6
por %xmm1,%xmm3
movdqa %xmm5,16(%ebx)
pshufb (%eax),%xmm6
movdqa %xmm3,-48(%ebx)
paddd %xmm6,%xmm4
movdqa 48(%ebx),%xmm5
pxor %xmm4,%xmm2
movdqa -16(%ebx),%xmm3
movdqa %xmm2,%xmm1
pslld $12,%xmm2
psrld $20,%xmm1
por %xmm1,%xmm2
movdqa -80(%ebx),%xmm1
paddd %xmm2,%xmm0
movdqa 112(%ebx),%xmm7
pxor %xmm0,%xmm6
movdqa %xmm0,-96(%ebx)
pshufb 16(%eax),%xmm6
paddd %xmm6,%xmm4
movdqa %xmm6,96(%ebx)
pxor %xmm4,%xmm2
paddd %xmm3,%xmm1
movdqa %xmm2,%xmm0
pslld $7,%xmm2
psrld $25,%xmm0
pxor %xmm1,%xmm7
por %xmm0,%xmm2
pshufb (%eax),%xmm7
movdqa %xmm2,-32(%ebx)
paddd %xmm7,%xmm5
pxor %xmm5,%xmm3
movdqa -48(%ebx),%xmm2
movdqa %xmm3,%xmm0
pslld $12,%xmm3
psrld $20,%xmm0
por %xmm0,%xmm3
movdqa -128(%ebx),%xmm0
paddd %xmm3,%xmm1
pxor %xmm1,%xmm7
movdqa %xmm1,-80(%ebx)
pshufb 16(%eax),%xmm7
paddd %xmm7,%xmm5
movdqa %xmm7,%xmm6
pxor %xmm5,%xmm3
paddd %xmm2,%xmm0
movdqa %xmm3,%xmm1
pslld $7,%xmm3
psrld $25,%xmm1
pxor %xmm0,%xmm6
por %xmm1,%xmm3
pshufb (%eax),%xmm6
movdqa %xmm3,-16(%ebx)
paddd %xmm6,%xmm4
pxor %xmm4,%xmm2
movdqa -32(%ebx),%xmm3
movdqa %xmm2,%xmm1
pslld $12,%xmm2
psrld $20,%xmm1
por %xmm1,%xmm2
movdqa -112(%ebx),%xmm1
paddd %xmm2,%xmm0
movdqa 64(%ebx),%xmm7
pxor %xmm0,%xmm6
movdqa %xmm0,-128(%ebx)
pshufb 16(%eax),%xmm6
paddd %xmm6,%xmm4
movdqa %xmm6,112(%ebx)
pxor %xmm4,%xmm2
paddd %xmm3,%xmm1
movdqa %xmm2,%xmm0
pslld $7,%xmm2
psrld $25,%xmm0
pxor %xmm1,%xmm7
por %xmm0,%xmm2
movdqa %xmm4,32(%ebx)
pshufb (%eax),%xmm7
movdqa %xmm2,-48(%ebx)
paddd %xmm7,%xmm5
movdqa (%ebx),%xmm4
pxor %xmm5,%xmm3
movdqa -16(%ebx),%xmm2
movdqa %xmm3,%xmm0
pslld $12,%xmm3
psrld $20,%xmm0
por %xmm0,%xmm3
movdqa -96(%ebx),%xmm0
paddd %xmm3,%xmm1
movdqa 80(%ebx),%xmm6
pxor %xmm1,%xmm7
movdqa %xmm1,-112(%ebx)
pshufb 16(%eax),%xmm7
paddd %xmm7,%xmm5
movdqa %xmm7,64(%ebx)
pxor %xmm5,%xmm3
paddd %xmm2,%xmm0
movdqa %xmm3,%xmm1
pslld $7,%xmm3
psrld $25,%xmm1
pxor %xmm0,%xmm6
por %xmm1,%xmm3
movdqa %xmm5,48(%ebx)
pshufb (%eax),%xmm6
movdqa %xmm3,-32(%ebx)
paddd %xmm6,%xmm4
movdqa 16(%ebx),%xmm5
pxor %xmm4,%xmm2
movdqa -64(%ebx),%xmm3
movdqa %xmm2,%xmm1
pslld $12,%xmm2
psrld $20,%xmm1
por %xmm1,%xmm2
movdqa -80(%ebx),%xmm1
paddd %xmm2,%xmm0
movdqa 96(%ebx),%xmm7
pxor %xmm0,%xmm6
movdqa %xmm0,-96(%ebx)
pshufb 16(%eax),%xmm6
paddd %xmm6,%xmm4
movdqa %xmm6,80(%ebx)
pxor %xmm4,%xmm2
paddd %xmm3,%xmm1
movdqa %xmm2,%xmm0
pslld $7,%xmm2
psrld $25,%xmm0
pxor %xmm1,%xmm7
por %xmm0,%xmm2
pshufb (%eax),%xmm7
movdqa %xmm2,-16(%ebx)
paddd %xmm7,%xmm5
pxor %xmm5,%xmm3
movdqa %xmm3,%xmm0
pslld $12,%xmm3
psrld $20,%xmm0
por %xmm0,%xmm3
movdqa -128(%ebx),%xmm0
paddd %xmm3,%xmm1
movdqa 64(%ebx),%xmm6
pxor %xmm1,%xmm7
movdqa %xmm1,-80(%ebx)
pshufb 16(%eax),%xmm7
paddd %xmm7,%xmm5
movdqa %xmm7,96(%ebx)
pxor %xmm5,%xmm3
movdqa %xmm3,%xmm1
pslld $7,%xmm3
psrld $25,%xmm1
por %xmm1,%xmm3
decl %edx
jnz .L010loop
movdqa %xmm3,-64(%ebx)
movdqa %xmm4,(%ebx)
movdqa %xmm5,16(%ebx)
movdqa %xmm6,64(%ebx)
movdqa %xmm7,96(%ebx)
movdqa -112(%ebx),%xmm1
movdqa -96(%ebx),%xmm2
movdqa -80(%ebx),%xmm3
paddd -128(%ebp),%xmm0
paddd -112(%ebp),%xmm1
paddd -96(%ebp),%xmm2
paddd -80(%ebp),%xmm3
movdqa %xmm0,%xmm6
punpckldq %xmm1,%xmm0
movdqa %xmm2,%xmm7
punpckldq %xmm3,%xmm2
punpckhdq %xmm1,%xmm6
punpckhdq %xmm3,%xmm7
movdqa %xmm0,%xmm1
punpcklqdq %xmm2,%xmm0
movdqa %xmm6,%xmm3
punpcklqdq %xmm7,%xmm6
punpckhqdq %xmm2,%xmm1
punpckhqdq %xmm7,%xmm3
movdqu -128(%esi),%xmm4
movdqu -64(%esi),%xmm5
movdqu (%esi),%xmm2
movdqu 64(%esi),%xmm7
leal 16(%esi),%esi
pxor %xmm0,%xmm4
movdqa -64(%ebx),%xmm0
pxor %xmm1,%xmm5
movdqa -48(%ebx),%xmm1
pxor %xmm2,%xmm6
movdqa -32(%ebx),%xmm2
pxor %xmm3,%xmm7
movdqa -16(%ebx),%xmm3
movdqu %xmm4,-128(%edi)
movdqu %xmm5,-64(%edi)
movdqu %xmm6,(%edi)
movdqu %xmm7,64(%edi)
leal 16(%edi),%edi
paddd -64(%ebp),%xmm0
paddd -48(%ebp),%xmm1
paddd -32(%ebp),%xmm2
paddd -16(%ebp),%xmm3
movdqa %xmm0,%xmm6
punpckldq %xmm1,%xmm0
movdqa %xmm2,%xmm7
punpckldq %xmm3,%xmm2
punpckhdq %xmm1,%xmm6
punpckhdq %xmm3,%xmm7
movdqa %xmm0,%xmm1
punpcklqdq %xmm2,%xmm0
movdqa %xmm6,%xmm3
punpcklqdq %xmm7,%xmm6
punpckhqdq %xmm2,%xmm1
punpckhqdq %xmm7,%xmm3
movdqu -128(%esi),%xmm4
movdqu -64(%esi),%xmm5
movdqu (%esi),%xmm2
movdqu 64(%esi),%xmm7
leal 16(%esi),%esi
pxor %xmm0,%xmm4
movdqa (%ebx),%xmm0
pxor %xmm1,%xmm5
movdqa 16(%ebx),%xmm1
pxor %xmm2,%xmm6
movdqa 32(%ebx),%xmm2
pxor %xmm3,%xmm7
movdqa 48(%ebx),%xmm3
movdqu %xmm4,-128(%edi)
movdqu %xmm5,-64(%edi)
movdqu %xmm6,(%edi)
movdqu %xmm7,64(%edi)
leal 16(%edi),%edi
paddd (%ebp),%xmm0
paddd 16(%ebp),%xmm1
paddd 32(%ebp),%xmm2
paddd 48(%ebp),%xmm3
movdqa %xmm0,%xmm6
punpckldq %xmm1,%xmm0
movdqa %xmm2,%xmm7
punpckldq %xmm3,%xmm2
punpckhdq %xmm1,%xmm6
punpckhdq %xmm3,%xmm7
movdqa %xmm0,%xmm1
punpcklqdq %xmm2,%xmm0
movdqa %xmm6,%xmm3
punpcklqdq %xmm7,%xmm6
punpckhqdq %xmm2,%xmm1
punpckhqdq %xmm7,%xmm3
movdqu -128(%esi),%xmm4
movdqu -64(%esi),%xmm5
movdqu (%esi),%xmm2
movdqu 64(%esi),%xmm7
leal 16(%esi),%esi
pxor %xmm0,%xmm4
movdqa 64(%ebx),%xmm0
pxor %xmm1,%xmm5
movdqa 80(%ebx),%xmm1
pxor %xmm2,%xmm6
movdqa 96(%ebx),%xmm2
pxor %xmm3,%xmm7
movdqa 112(%ebx),%xmm3
movdqu %xmm4,-128(%edi)
movdqu %xmm5,-64(%edi)
movdqu %xmm6,(%edi)
movdqu %xmm7,64(%edi)
leal 16(%edi),%edi
paddd 64(%ebp),%xmm0
paddd 80(%ebp),%xmm1
paddd 96(%ebp),%xmm2
paddd 112(%ebp),%xmm3
movdqa %xmm0,%xmm6
punpckldq %xmm1,%xmm0
movdqa %xmm2,%xmm7
punpckldq %xmm3,%xmm2
punpckhdq %xmm1,%xmm6
punpckhdq %xmm3,%xmm7
movdqa %xmm0,%xmm1
punpcklqdq %xmm2,%xmm0
movdqa %xmm6,%xmm3
punpcklqdq %xmm7,%xmm6
punpckhqdq %xmm2,%xmm1
punpckhqdq %xmm7,%xmm3
movdqu -128(%esi),%xmm4
movdqu -64(%esi),%xmm5
movdqu (%esi),%xmm2
movdqu 64(%esi),%xmm7
leal 208(%esi),%esi
pxor %xmm0,%xmm4
pxor %xmm1,%xmm5
pxor %xmm2,%xmm6
pxor %xmm3,%xmm7
movdqu %xmm4,-128(%edi)
movdqu %xmm5,-64(%edi)
movdqu %xmm6,(%edi)
movdqu %xmm7,64(%edi)
leal 208(%edi),%edi
subl $256,%ecx
jnc .L009outer_loop
addl $256,%ecx
jz .L011done
movl 520(%esp),%ebx
leal -128(%esi),%esi
movl 516(%esp),%edx
leal -128(%edi),%edi
movd 64(%ebp),%xmm2
movdqu (%ebx),%xmm3
paddd 96(%eax),%xmm2
pand 112(%eax),%xmm3
por %xmm2,%xmm3
.L0081x:
movdqa 32(%eax),%xmm0
movdqu (%edx),%xmm1
movdqu 16(%edx),%xmm2
movdqa (%eax),%xmm6
movdqa 16(%eax),%xmm7
movl %ebp,48(%esp)
movdqa %xmm0,(%esp)
movdqa %xmm1,16(%esp)
movdqa %xmm2,32(%esp)
movdqa %xmm3,48(%esp)
movl $10,%edx
jmp .L012loop1x
.align 16
.L013outer1x:
movdqa 80(%eax),%xmm3
movdqa (%esp),%xmm0
movdqa 16(%esp),%xmm1
movdqa 32(%esp),%xmm2
paddd 48(%esp),%xmm3
movl $10,%edx
movdqa %xmm3,48(%esp)
jmp .L012loop1x
.align 16
.L012loop1x:
paddd %xmm1,%xmm0
pxor %xmm0,%xmm3
.byte 102,15,56,0,222
paddd %xmm3,%xmm2
pxor %xmm2,%xmm1
movdqa %xmm1,%xmm4
psrld $20,%xmm1
pslld $12,%xmm4
por %xmm4,%xmm1
paddd %xmm1,%xmm0
pxor %xmm0,%xmm3
.byte 102,15,56,0,223
paddd %xmm3,%xmm2
pxor %xmm2,%xmm1
movdqa %xmm1,%xmm4
psrld $25,%xmm1
pslld $7,%xmm4
por %xmm4,%xmm1
pshufd $78,%xmm2,%xmm2
pshufd $57,%xmm1,%xmm1
pshufd $147,%xmm3,%xmm3
nop
paddd %xmm1,%xmm0
pxor %xmm0,%xmm3
.byte 102,15,56,0,222
paddd %xmm3,%xmm2
pxor %xmm2,%xmm1
movdqa %xmm1,%xmm4
psrld $20,%xmm1
pslld $12,%xmm4
por %xmm4,%xmm1
paddd %xmm1,%xmm0
pxor %xmm0,%xmm3
.byte 102,15,56,0,223
paddd %xmm3,%xmm2
pxor %xmm2,%xmm1
movdqa %xmm1,%xmm4
psrld $25,%xmm1
pslld $7,%xmm4
por %xmm4,%xmm1
pshufd $78,%xmm2,%xmm2
pshufd $147,%xmm1,%xmm1
pshufd $57,%xmm3,%xmm3
decl %edx
jnz .L012loop1x
paddd (%esp),%xmm0
paddd 16(%esp),%xmm1
paddd 32(%esp),%xmm2
paddd 48(%esp),%xmm3
cmpl $64,%ecx
jb .L014tail
movdqu (%esi),%xmm4
movdqu 16(%esi),%xmm5
pxor %xmm4,%xmm0
movdqu 32(%esi),%xmm4
pxor %xmm5,%xmm1
movdqu 48(%esi),%xmm5
pxor %xmm4,%xmm2
pxor %xmm5,%xmm3
leal 64(%esi),%esi
movdqu %xmm0,(%edi)
movdqu %xmm1,16(%edi)
movdqu %xmm2,32(%edi)
movdqu %xmm3,48(%edi)
leal 64(%edi),%edi
subl $64,%ecx
jnz .L013outer1x
jmp .L011done
.L014tail:
movdqa %xmm0,(%esp)
movdqa %xmm1,16(%esp)
movdqa %xmm2,32(%esp)
movdqa %xmm3,48(%esp)
xorl %eax,%eax
xorl %edx,%edx
xorl %ebp,%ebp
.L015tail_loop:
movb (%esp,%ebp,1),%al
movb (%esi,%ebp,1),%dl
leal 1(%ebp),%ebp
xorb %dl,%al
movb %al,-1(%edi,%ebp,1)
decl %ecx
jnz .L015tail_loop
.L011done:
movl 512(%esp),%esp
popl %edi
popl %esi
popl %ebx
popl %ebp
ret
.align 64
.Lssse3_data:
.byte 2,3,0,1,6,7,4,5,10,11,8,9,14,15,12,13
.byte 3,0,1,2,7,4,5,6,11,8,9,10,15,12,13,14
.long 1634760805,857760878,2036477234,1797285236
.long 0,1,2,3
.long 4,4,4,4
.long 1,0,0,0
.long 4,0,0,0
.long 0,-1,-1,-1
.align 64
.byte 67,104,97,67,104,97,50,48,32,102,111,114,32,120,56,54
.byte 44,32,67,82,89,80,84,79,71,65,77,83,32,98,121,32
.byte 60,97,112,112,114,111,64,111,112,101,110,115,115,108,46,111
.byte 114,103,62,0
#endif
#endif // defined(__i386__) && defined(_WIN32)
#if defined(__linux__) && defined(__ELF__)
.section .note.GNU-stack,"",%progbits
#endif
@@ -1,7 +1,7 @@
#define BORINGSSL_PREFIX CCryptoBoringSSL
#if defined(__x86_64__) && defined(__linux__)
# This file is generated from a similarly-named Perl script in the BoringSSL
# source tree. Do not edit by hand.
// This file is generated from a similarly-named Perl script in the BoringSSL
// source tree. Do not edit by hand.
#if defined(__has_feature)
#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM)
@@ -1,7 +1,7 @@
#define BORINGSSL_PREFIX CCryptoBoringSSL
#if defined(__x86_64__) && defined(__APPLE__)
# This file is generated from a similarly-named Perl script in the BoringSSL
# source tree. Do not edit by hand.
// This file is generated from a similarly-named Perl script in the BoringSSL
// source tree. Do not edit by hand.
#if defined(__has_feature)
#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM)
+38 -47
View File
@@ -25,22 +25,20 @@
#include "internal.h"
#define U8TO32_LITTLE(p) \
(((uint32_t)((p)[0])) | ((uint32_t)((p)[1]) << 8) | \
((uint32_t)((p)[2]) << 16) | ((uint32_t)((p)[3]) << 24))
// sigma contains the ChaCha constants, which happen to be an ASCII string.
static const uint8_t sigma[16] = { 'e', 'x', 'p', 'a', 'n', 'd', ' ', '3',
'2', '-', 'b', 'y', 't', 'e', ' ', 'k' };
#define ROTATE(v, n) (((v) << (n)) | ((v) >> (32 - (n))))
// QUARTERROUND updates a, b, c, d with a ChaCha "quarter" round.
#define QUARTERROUND(a, b, c, d) \
x[a] += x[b]; x[d] = ROTATE(x[d] ^ x[a], 16); \
x[c] += x[d]; x[b] = ROTATE(x[b] ^ x[c], 12); \
x[a] += x[b]; x[d] = ROTATE(x[d] ^ x[a], 8); \
x[c] += x[d]; x[b] = ROTATE(x[b] ^ x[c], 7);
#define QUARTERROUND(a, b, c, d) \
x[a] += x[b]; \
x[d] = CRYPTO_rotl_u32(x[d] ^ x[a], 16); \
x[c] += x[d]; \
x[b] = CRYPTO_rotl_u32(x[b] ^ x[c], 12); \
x[a] += x[b]; \
x[d] = CRYPTO_rotl_u32(x[d] ^ x[a], 8); \
x[c] += x[d]; \
x[b] = CRYPTO_rotl_u32(x[b] ^ x[c], 7);
void CRYPTO_hchacha20(uint8_t out[32], const uint8_t key[32],
const uint8_t nonce[16]) {
@@ -71,24 +69,25 @@ void CRYPTO_chacha_20(uint8_t *out, const uint8_t *in, size_t in_len,
uint32_t counter) {
assert(!buffers_alias(out, in_len, in, in_len) || in == out);
uint32_t counter_nonce[4]; counter_nonce[0] = counter;
counter_nonce[1] = U8TO32_LITTLE(nonce + 0);
counter_nonce[2] = U8TO32_LITTLE(nonce + 4);
counter_nonce[3] = U8TO32_LITTLE(nonce + 8);
uint32_t counter_nonce[4];
counter_nonce[0] = counter;
counter_nonce[1] = CRYPTO_load_u32_le(nonce + 0);
counter_nonce[2] = CRYPTO_load_u32_le(nonce + 4);
counter_nonce[3] = CRYPTO_load_u32_le(nonce + 8);
const uint32_t *key_ptr = (const uint32_t *)key;
#if !defined(OPENSSL_X86) && !defined(OPENSSL_X86_64)
// The assembly expects the key to be four-byte aligned.
uint32_t key_u32[8];
if ((((uintptr_t)key) & 3) != 0) {
key_u32[0] = U8TO32_LITTLE(key + 0);
key_u32[1] = U8TO32_LITTLE(key + 4);
key_u32[2] = U8TO32_LITTLE(key + 8);
key_u32[3] = U8TO32_LITTLE(key + 12);
key_u32[4] = U8TO32_LITTLE(key + 16);
key_u32[5] = U8TO32_LITTLE(key + 20);
key_u32[6] = U8TO32_LITTLE(key + 24);
key_u32[7] = U8TO32_LITTLE(key + 28);
key_u32[0] = CRYPTO_load_u32_le(key + 0);
key_u32[1] = CRYPTO_load_u32_le(key + 4);
key_u32[2] = CRYPTO_load_u32_le(key + 8);
key_u32[3] = CRYPTO_load_u32_le(key + 12);
key_u32[4] = CRYPTO_load_u32_le(key + 16);
key_u32[5] = CRYPTO_load_u32_le(key + 20);
key_u32[6] = CRYPTO_load_u32_le(key + 24);
key_u32[7] = CRYPTO_load_u32_le(key + 28);
key_ptr = key_u32;
}
@@ -99,14 +98,6 @@ void CRYPTO_chacha_20(uint8_t *out, const uint8_t *in, size_t in_len,
#else
#define U32TO8_LITTLE(p, v) \
{ \
(p)[0] = (v >> 0) & 0xff; \
(p)[1] = (v >> 8) & 0xff; \
(p)[2] = (v >> 16) & 0xff; \
(p)[3] = (v >> 24) & 0xff; \
}
// chacha_core performs 20 rounds of ChaCha on the input words in
// |input| and writes the 64 output bytes to |output|.
static void chacha_core(uint8_t output[64], const uint32_t input[16]) {
@@ -129,7 +120,7 @@ static void chacha_core(uint8_t output[64], const uint32_t input[16]) {
x[i] += input[i];
}
for (i = 0; i < 16; ++i) {
U32TO8_LITTLE(output + 4 * i, x[i]);
CRYPTO_store_u32_le(output + 4 * i, x[i]);
}
}
@@ -142,25 +133,25 @@ void CRYPTO_chacha_20(uint8_t *out, const uint8_t *in, size_t in_len,
uint8_t buf[64];
size_t todo, i;
input[0] = U8TO32_LITTLE(sigma + 0);
input[1] = U8TO32_LITTLE(sigma + 4);
input[2] = U8TO32_LITTLE(sigma + 8);
input[3] = U8TO32_LITTLE(sigma + 12);
input[0] = CRYPTO_load_u32_le(sigma + 0);
input[1] = CRYPTO_load_u32_le(sigma + 4);
input[2] = CRYPTO_load_u32_le(sigma + 8);
input[3] = CRYPTO_load_u32_le(sigma + 12);
input[4] = U8TO32_LITTLE(key + 0);
input[5] = U8TO32_LITTLE(key + 4);
input[6] = U8TO32_LITTLE(key + 8);
input[7] = U8TO32_LITTLE(key + 12);
input[4] = CRYPTO_load_u32_le(key + 0);
input[5] = CRYPTO_load_u32_le(key + 4);
input[6] = CRYPTO_load_u32_le(key + 8);
input[7] = CRYPTO_load_u32_le(key + 12);
input[8] = U8TO32_LITTLE(key + 16);
input[9] = U8TO32_LITTLE(key + 20);
input[10] = U8TO32_LITTLE(key + 24);
input[11] = U8TO32_LITTLE(key + 28);
input[8] = CRYPTO_load_u32_le(key + 16);
input[9] = CRYPTO_load_u32_le(key + 20);
input[10] = CRYPTO_load_u32_le(key + 24);
input[11] = CRYPTO_load_u32_le(key + 28);
input[12] = counter;
input[13] = U8TO32_LITTLE(nonce + 0);
input[14] = U8TO32_LITTLE(nonce + 4);
input[15] = U8TO32_LITTLE(nonce + 8);
input[13] = CRYPTO_load_u32_le(nonce + 0);
input[14] = CRYPTO_load_u32_le(nonce + 4);
input[15] = CRYPTO_load_u32_le(nonce + 8);
while (in_len > 0) {
todo = sizeof(buf);
@@ -1,7 +1,7 @@
#define BORINGSSL_PREFIX CCryptoBoringSSL
#if defined(__x86_64__) && defined(__linux__)
# This file is generated from a similarly-named Perl script in the BoringSSL
# source tree. Do not edit by hand.
// This file is generated from a similarly-named Perl script in the BoringSSL
// source tree. Do not edit by hand.
#if defined(__has_feature)
#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM)
@@ -1,7 +1,7 @@
#define BORINGSSL_PREFIX CCryptoBoringSSL
#if defined(__x86_64__) && defined(__APPLE__)
# This file is generated from a similarly-named Perl script in the BoringSSL
# source tree. Do not edit by hand.
// This file is generated from a similarly-named Perl script in the BoringSSL
// source tree. Do not edit by hand.
#if defined(__has_feature)
#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -67,76 +67,60 @@
#include "../internal.h"
static const struct {
int nid;
const char *name;
const EVP_CIPHER *(*func)(void);
} kCiphers[] = {
{NID_aes_128_cbc, "aes-128-cbc", EVP_aes_128_cbc},
{NID_aes_128_ctr, "aes-128-ctr", EVP_aes_128_ctr},
{NID_aes_128_ecb, "aes-128-ecb", EVP_aes_128_ecb},
{NID_aes_128_gcm, "aes-128-gcm", EVP_aes_128_gcm},
{NID_aes_128_ofb128, "aes-128-ofb", EVP_aes_128_ofb},
{NID_aes_192_cbc, "aes-192-cbc", EVP_aes_192_cbc},
{NID_aes_192_ctr, "aes-192-ctr", EVP_aes_192_ctr},
{NID_aes_192_ecb, "aes-192-ecb", EVP_aes_192_ecb},
{NID_aes_192_gcm, "aes-192-gcm", EVP_aes_192_gcm},
{NID_aes_192_ofb128, "aes-192-ofb", EVP_aes_192_ofb},
{NID_aes_256_cbc, "aes-256-cbc", EVP_aes_256_cbc},
{NID_aes_256_ctr, "aes-256-ctr", EVP_aes_256_ctr},
{NID_aes_256_ecb, "aes-256-ecb", EVP_aes_256_ecb},
{NID_aes_256_gcm, "aes-256-gcm", EVP_aes_256_gcm},
{NID_aes_256_ofb128, "aes-256-ofb", EVP_aes_256_ofb},
{NID_des_cbc, "des-cbc", EVP_des_cbc},
{NID_des_ecb, "des-ecb", EVP_des_ecb},
{NID_des_ede_cbc, "des-ede-cbc", EVP_des_ede_cbc},
{NID_des_ede_ecb, "des-ede", EVP_des_ede},
{NID_des_ede3_cbc, "des-ede3-cbc", EVP_des_ede3_cbc},
{NID_rc2_cbc, "rc2-cbc", EVP_rc2_cbc},
{NID_rc4, "rc4", EVP_rc4},
};
const EVP_CIPHER *EVP_get_cipherbynid(int nid) {
switch (nid) {
case NID_rc2_cbc:
return EVP_rc2_cbc();
case NID_rc2_40_cbc:
return EVP_rc2_40_cbc();
case NID_des_ede3_cbc:
return EVP_des_ede3_cbc();
case NID_des_ede_cbc:
return EVP_des_cbc();
case NID_aes_128_cbc:
return EVP_aes_128_cbc();
case NID_aes_192_cbc:
return EVP_aes_192_cbc();
case NID_aes_256_cbc:
return EVP_aes_256_cbc();
default:
return NULL;
for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kCiphers); i++) {
if (kCiphers[i].nid == nid) {
return kCiphers[i].func();
}
}
return NULL;
}
const EVP_CIPHER *EVP_get_cipherbyname(const char *name) {
if (OPENSSL_strcasecmp(name, "rc4") == 0) {
return EVP_rc4();
} else if (OPENSSL_strcasecmp(name, "des-cbc") == 0) {
return EVP_des_cbc();
} else if (OPENSSL_strcasecmp(name, "des-ede3-cbc") == 0 ||
// This is not a name used by OpenSSL, but tcpdump registers it
// with |EVP_add_cipher_alias|. Our |EVP_add_cipher_alias| is a
// no-op, so we support the name here.
OPENSSL_strcasecmp(name, "3des") == 0) {
return EVP_des_ede3_cbc();
} else if (OPENSSL_strcasecmp(name, "aes-128-cbc") == 0) {
return EVP_aes_128_cbc();
} else if (OPENSSL_strcasecmp(name, "aes-192-cbc") == 0) {
return EVP_aes_192_cbc();
} else if (OPENSSL_strcasecmp(name, "aes-256-cbc") == 0) {
return EVP_aes_256_cbc();
} else if (OPENSSL_strcasecmp(name, "aes-128-ctr") == 0) {
return EVP_aes_128_ctr();
} else if (OPENSSL_strcasecmp(name, "aes-192-ctr") == 0) {
return EVP_aes_192_ctr();
} else if (OPENSSL_strcasecmp(name, "aes-256-ctr") == 0) {
return EVP_aes_256_ctr();
} else if (OPENSSL_strcasecmp(name, "aes-128-ecb") == 0) {
return EVP_aes_128_ecb();
} else if (OPENSSL_strcasecmp(name, "aes-192-ecb") == 0) {
return EVP_aes_192_ecb();
} else if (OPENSSL_strcasecmp(name, "aes-256-ecb") == 0) {
return EVP_aes_256_ecb();
} else if (OPENSSL_strcasecmp(name, "aes-128-gcm") == 0) {
return EVP_aes_128_gcm();
} else if (OPENSSL_strcasecmp(name, "aes-192-gcm") == 0) {
return EVP_aes_192_gcm();
} else if (OPENSSL_strcasecmp(name, "aes-256-gcm") == 0) {
return EVP_aes_256_gcm();
} else if (OPENSSL_strcasecmp(name, "aes-128-ofb") == 0) {
return EVP_aes_128_ofb();
} else if (OPENSSL_strcasecmp(name, "aes-192-ofb") == 0) {
return EVP_aes_192_ofb();
} else if (OPENSSL_strcasecmp(name, "aes-256-ofb") == 0) {
return EVP_aes_256_ofb();
} else if (OPENSSL_strcasecmp(name, "des-ecb") == 0) {
return EVP_des_ecb();
} else if (OPENSSL_strcasecmp(name, "des-ede") == 0) {
return EVP_des_ede();
} else if (OPENSSL_strcasecmp(name, "des-ede-cbc") == 0) {
return EVP_des_ede_cbc();
} else if (OPENSSL_strcasecmp(name, "rc2-cbc") == 0) {
return EVP_rc2_cbc();
if (name == NULL) {
return NULL;
}
// This is not a name used by OpenSSL, but tcpdump registers it with
// |EVP_add_cipher_alias|. Our |EVP_add_cipher_alias| is a no-op, so we
// support the name here.
if (OPENSSL_strcasecmp(name, "3des") == 0) {
name = "des-ede3-cbc";
}
for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kCiphers); i++) {
if (OPENSSL_strcasecmp(kCiphers[i].name, name) == 0) {
return kCiphers[i].func();
}
}
return NULL;
@@ -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)) {
@@ -18,18 +18,15 @@
#include <CCryptoBoringSSL_chacha.h>
#include <CCryptoBoringSSL_cipher.h>
#include <CCryptoBoringSSL_cpu.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_poly1305.h>
#include <CCryptoBoringSSL_type_check.h>
#include "internal.h"
#include "../chacha/internal.h"
#include "../fipsmodule/cipher/internal.h"
#include "../internal.h"
#include "../chacha/internal.h"
#define POLY1305_TAG_LEN 16
struct aead_chacha20_poly1305_ctx {
uint8_t key[32];
@@ -44,78 +41,6 @@ OPENSSL_STATIC_ASSERT(alignof(union evp_aead_ctx_st_state) >=
"AEAD state has insufficient alignment");
#endif
// For convenience (the x86_64 calling convention allows only six parameters in
// registers), the final parameter for the assembly functions is both an input
// and output parameter.
union open_data {
struct {
alignas(16) uint8_t key[32];
uint32_t counter;
uint8_t nonce[12];
} in;
struct {
uint8_t tag[POLY1305_TAG_LEN];
} out;
};
union seal_data {
struct {
alignas(16) uint8_t key[32];
uint32_t counter;
uint8_t nonce[12];
const uint8_t *extra_ciphertext;
size_t extra_ciphertext_len;
} in;
struct {
uint8_t tag[POLY1305_TAG_LEN];
} out;
};
#if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM) && \
!defined(OPENSSL_WINDOWS)
static int asm_capable(void) {
const int sse41_capable = (OPENSSL_ia32cap_P[1] & (1 << 19)) != 0;
return sse41_capable;
}
OPENSSL_STATIC_ASSERT(sizeof(union open_data) == 48, "wrong open_data size");
OPENSSL_STATIC_ASSERT(sizeof(union seal_data) == 48 + 8 + 8,
"wrong seal_data size");
// chacha20_poly1305_open is defined in chacha20_poly1305_x86_64.pl. It decrypts
// |plaintext_len| bytes from |ciphertext| and writes them to |out_plaintext|.
// Additional input parameters are passed in |aead_data->in|. On exit, it will
// write calculated tag value to |aead_data->out.tag|, which the caller must
// check.
extern void chacha20_poly1305_open(uint8_t *out_plaintext,
const uint8_t *ciphertext,
size_t plaintext_len, const uint8_t *ad,
size_t ad_len, union open_data *aead_data);
// chacha20_poly1305_open is defined in chacha20_poly1305_x86_64.pl. It encrypts
// |plaintext_len| bytes from |plaintext| and writes them to |out_ciphertext|.
// Additional input parameters are passed in |aead_data->in|. The calculated tag
// value is over the computed ciphertext concatenated with |extra_ciphertext|
// and written to |aead_data->out.tag|.
extern void chacha20_poly1305_seal(uint8_t *out_ciphertext,
const uint8_t *plaintext,
size_t plaintext_len, const uint8_t *ad,
size_t ad_len, union seal_data *aead_data);
#else
static int asm_capable(void) { return 0; }
static void chacha20_poly1305_open(uint8_t *out_plaintext,
const uint8_t *ciphertext,
size_t plaintext_len, const uint8_t *ad,
size_t ad_len, union open_data *aead_data) {}
static void chacha20_poly1305_seal(uint8_t *out_ciphertext,
const uint8_t *plaintext,
size_t plaintext_len, const uint8_t *ad,
size_t ad_len, union seal_data *aead_data) {}
#endif
static int aead_chacha20_poly1305_init(EVP_AEAD_CTX *ctx, const uint8_t *key,
size_t key_len, size_t tag_len) {
struct aead_chacha20_poly1305_ctx *c20_ctx =
@@ -238,8 +163,8 @@ static int chacha20_poly1305_seal_scatter(
}
}
union seal_data data;
if (asm_capable()) {
union chacha20_poly1305_seal_data data;
if (chacha20_poly1305_asm_capable()) {
OPENSSL_memcpy(data.in.key, key, 32);
data.in.counter = 0;
OPENSSL_memcpy(data.in.nonce, nonce, 12);
@@ -321,8 +246,8 @@ static int chacha20_poly1305_open_gather(
return 0;
}
union open_data data;
if (asm_capable()) {
union chacha20_poly1305_open_data data;
if (chacha20_poly1305_asm_capable()) {
OPENSSL_memcpy(data.in.key, key, 32);
data.in.counter = 0;
OPENSSL_memcpy(data.in.nonce, nonce, 12);
@@ -343,7 +343,7 @@ static int aead_tls_open(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len,
if (EVP_CIPHER_CTX_mode(&tls_ctx->cipher_ctx) == EVP_CIPH_CBC_MODE &&
EVP_tls_cbc_record_digest_supported(tls_ctx->hmac_ctx.md)) {
if (!EVP_tls_cbc_digest_record(tls_ctx->hmac_ctx.md, mac, &mac_len,
ad_fixed, out, data_plus_mac_len, total,
ad_fixed, out, data_len, total,
tls_ctx->mac_key, tls_ctx->mac_key_len)) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
@@ -406,14 +406,6 @@ static int aead_aes_128_cbc_sha1_tls_implicit_iv_init(
EVP_sha1(), 1);
}
static int aead_aes_128_cbc_sha256_tls_init(EVP_AEAD_CTX *ctx,
const uint8_t *key, size_t key_len,
size_t tag_len,
enum evp_aead_direction_t dir) {
return aead_tls_init(ctx, key, key_len, tag_len, dir, EVP_aes_128_cbc(),
EVP_sha256(), 0);
}
static int aead_aes_256_cbc_sha1_tls_init(EVP_AEAD_CTX *ctx, const uint8_t *key,
size_t key_len, size_t tag_len,
enum evp_aead_direction_t dir) {
@@ -428,22 +420,6 @@ static int aead_aes_256_cbc_sha1_tls_implicit_iv_init(
EVP_sha1(), 1);
}
static int aead_aes_256_cbc_sha256_tls_init(EVP_AEAD_CTX *ctx,
const uint8_t *key, size_t key_len,
size_t tag_len,
enum evp_aead_direction_t dir) {
return aead_tls_init(ctx, key, key_len, tag_len, dir, EVP_aes_256_cbc(),
EVP_sha256(), 0);
}
static int aead_aes_256_cbc_sha384_tls_init(EVP_AEAD_CTX *ctx,
const uint8_t *key, size_t key_len,
size_t tag_len,
enum evp_aead_direction_t dir) {
return aead_tls_init(ctx, key, key_len, tag_len, dir, EVP_aes_256_cbc(),
EVP_sha384(), 0);
}
static int aead_des_ede3_cbc_sha1_tls_init(EVP_AEAD_CTX *ctx,
const uint8_t *key, size_t key_len,
size_t tag_len,
@@ -513,23 +489,6 @@ static const EVP_AEAD aead_aes_128_cbc_sha1_tls_implicit_iv = {
aead_tls_tag_len,
};
static const EVP_AEAD aead_aes_128_cbc_sha256_tls = {
SHA256_DIGEST_LENGTH + 16, // key len (SHA256 + AES128)
16, // nonce len (IV)
16 + SHA256_DIGEST_LENGTH, // overhead (padding + SHA256)
SHA256_DIGEST_LENGTH, // max tag length
0, // seal_scatter_supports_extra_in
NULL, // init
aead_aes_128_cbc_sha256_tls_init,
aead_tls_cleanup,
aead_tls_open,
aead_tls_seal_scatter,
NULL, // open_gather
NULL, // get_iv
aead_tls_tag_len,
};
static const EVP_AEAD aead_aes_256_cbc_sha1_tls = {
SHA_DIGEST_LENGTH + 32, // key len (SHA1 + AES256)
16, // nonce len (IV)
@@ -564,40 +523,6 @@ static const EVP_AEAD aead_aes_256_cbc_sha1_tls_implicit_iv = {
aead_tls_tag_len,
};
static const EVP_AEAD aead_aes_256_cbc_sha256_tls = {
SHA256_DIGEST_LENGTH + 32, // key len (SHA256 + AES256)
16, // nonce len (IV)
16 + SHA256_DIGEST_LENGTH, // overhead (padding + SHA256)
SHA256_DIGEST_LENGTH, // max tag length
0, // seal_scatter_supports_extra_in
NULL, // init
aead_aes_256_cbc_sha256_tls_init,
aead_tls_cleanup,
aead_tls_open,
aead_tls_seal_scatter,
NULL, // open_gather
NULL, // get_iv
aead_tls_tag_len,
};
static const EVP_AEAD aead_aes_256_cbc_sha384_tls = {
SHA384_DIGEST_LENGTH + 32, // key len (SHA384 + AES256)
16, // nonce len (IV)
16 + SHA384_DIGEST_LENGTH, // overhead (padding + SHA384)
SHA384_DIGEST_LENGTH, // max tag length
0, // seal_scatter_supports_extra_in
NULL, // init
aead_aes_256_cbc_sha384_tls_init,
aead_tls_cleanup,
aead_tls_open,
aead_tls_seal_scatter,
NULL, // open_gather
NULL, // get_iv
aead_tls_tag_len,
};
static const EVP_AEAD aead_des_ede3_cbc_sha1_tls = {
SHA_DIGEST_LENGTH + 24, // key len (SHA1 + 3DES)
8, // nonce len (IV)
@@ -657,10 +582,6 @@ const EVP_AEAD *EVP_aead_aes_128_cbc_sha1_tls_implicit_iv(void) {
return &aead_aes_128_cbc_sha1_tls_implicit_iv;
}
const EVP_AEAD *EVP_aead_aes_128_cbc_sha256_tls(void) {
return &aead_aes_128_cbc_sha256_tls;
}
const EVP_AEAD *EVP_aead_aes_256_cbc_sha1_tls(void) {
return &aead_aes_256_cbc_sha1_tls;
}
@@ -669,14 +590,6 @@ const EVP_AEAD *EVP_aead_aes_256_cbc_sha1_tls_implicit_iv(void) {
return &aead_aes_256_cbc_sha1_tls_implicit_iv;
}
const EVP_AEAD *EVP_aead_aes_256_cbc_sha256_tls(void) {
return &aead_aes_256_cbc_sha256_tls;
}
const EVP_AEAD *EVP_aead_aes_256_cbc_sha384_tls(void) {
return &aead_aes_256_cbc_sha384_tls;
}
const EVP_AEAD *EVP_aead_des_ede3_cbc_sha1_tls(void) {
return &aead_des_ede3_cbc_sha1_tls;
}
@@ -57,7 +57,11 @@
#ifndef OPENSSL_HEADER_CIPHER_EXTRA_INTERNAL_H
#define OPENSSL_HEADER_CIPHER_EXTRA_INTERNAL_H
#include <stdlib.h>
#include <CCryptoBoringSSL_base.h>
#include <CCryptoBoringSSL_cpu.h>
#include <CCryptoBoringSSL_type_check.h>
#include "../internal.h"
@@ -95,6 +99,17 @@ void EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in,
// which EVP_tls_cbc_digest_record supports.
int EVP_tls_cbc_record_digest_supported(const EVP_MD *md);
// EVP_sha1_final_with_secret_suffix computes the result of hashing |len| bytes
// from |in| to |ctx| and writes the resulting hash to |out|. |len| is treated
// as secret and must be at most |max_len|, which is treated as public. |in|
// must point to a buffer of at least |max_len| bytes. It returns one on success
// and zero if inputs are too long.
//
// This function is exported for unit tests.
OPENSSL_EXPORT int EVP_sha1_final_with_secret_suffix(
SHA_CTX *ctx, uint8_t out[SHA_DIGEST_LENGTH], const uint8_t *in, size_t len,
size_t max_len);
// EVP_tls_cbc_digest_record computes the MAC of a decrypted, padded TLS
// record.
//
@@ -104,8 +119,8 @@ int EVP_tls_cbc_record_digest_supported(const EVP_MD *md);
// md_out_size: the number of output bytes is written here.
// header: the 13-byte, TLS record header.
// data: the record data itself
// data_plus_mac_size: the secret, reported length of the data and MAC
// once the padding has been removed.
// data_size: the secret, reported length of the data once the padding and MAC
// have been removed.
// data_plus_mac_plus_padding_size: the public length of the whole
// record, including padding.
//
@@ -115,11 +130,94 @@ int EVP_tls_cbc_record_digest_supported(const EVP_MD *md);
// padding too. )
int EVP_tls_cbc_digest_record(const EVP_MD *md, uint8_t *md_out,
size_t *md_out_size, const uint8_t header[13],
const uint8_t *data, size_t data_plus_mac_size,
const uint8_t *data, size_t data_size,
size_t data_plus_mac_plus_padding_size,
const uint8_t *mac_secret,
unsigned mac_secret_length);
#define POLY1305_TAG_LEN 16
// For convenience (the x86_64 calling convention allows only six parameters in
// registers), the final parameter for the assembly functions is both an input
// and output parameter.
union chacha20_poly1305_open_data {
struct {
alignas(16) uint8_t key[32];
uint32_t counter;
uint8_t nonce[12];
} in;
struct {
uint8_t tag[POLY1305_TAG_LEN];
} out;
};
union chacha20_poly1305_seal_data {
struct {
alignas(16) uint8_t key[32];
uint32_t counter;
uint8_t nonce[12];
const uint8_t *extra_ciphertext;
size_t extra_ciphertext_len;
} in;
struct {
uint8_t tag[POLY1305_TAG_LEN];
} out;
};
#if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM)
OPENSSL_STATIC_ASSERT(sizeof(union chacha20_poly1305_open_data) == 48,
"wrong chacha20_poly1305_open_data size");
OPENSSL_STATIC_ASSERT(sizeof(union chacha20_poly1305_seal_data) == 48 + 8 + 8,
"wrong chacha20_poly1305_seal_data size");
OPENSSL_INLINE int chacha20_poly1305_asm_capable(void) {
const int sse41_capable = (OPENSSL_ia32cap_P[1] & (1 << 19)) != 0;
return sse41_capable;
}
// chacha20_poly1305_open is defined in chacha20_poly1305_x86_64.pl. It decrypts
// |plaintext_len| bytes from |ciphertext| and writes them to |out_plaintext|.
// Additional input parameters are passed in |aead_data->in|. On exit, it will
// write calculated tag value to |aead_data->out.tag|, which the caller must
// check.
extern void chacha20_poly1305_open(uint8_t *out_plaintext,
const uint8_t *ciphertext,
size_t plaintext_len, const uint8_t *ad,
size_t ad_len,
union chacha20_poly1305_open_data *data);
// chacha20_poly1305_open is defined in chacha20_poly1305_x86_64.pl. It encrypts
// |plaintext_len| bytes from |plaintext| and writes them to |out_ciphertext|.
// Additional input parameters are passed in |aead_data->in|. The calculated tag
// value is over the computed ciphertext concatenated with |extra_ciphertext|
// and written to |aead_data->out.tag|.
extern void chacha20_poly1305_seal(uint8_t *out_ciphertext,
const uint8_t *plaintext,
size_t plaintext_len, const uint8_t *ad,
size_t ad_len,
union chacha20_poly1305_seal_data *data);
#else
OPENSSL_INLINE int chacha20_poly1305_asm_capable(void) { return 0; }
OPENSSL_INLINE void chacha20_poly1305_open(uint8_t *out_plaintext,
const uint8_t *ciphertext,
size_t plaintext_len, const uint8_t *ad,
size_t ad_len,
union chacha20_poly1305_open_data *data) {
abort();
}
OPENSSL_INLINE void chacha20_poly1305_seal(uint8_t *out_ciphertext,
const uint8_t *plaintext,
size_t plaintext_len, const uint8_t *ad,
size_t ad_len,
union chacha20_poly1305_seal_data *data) {
abort();
}
#endif
#if defined(__cplusplus)
} // extern C
@@ -62,15 +62,6 @@
#include "../fipsmodule/cipher/internal.h"
// MAX_HASH_BIT_COUNT_BYTES is the maximum number of bytes in the hash's length
// field. (SHA-384/512 have 128-bit length.)
#define MAX_HASH_BIT_COUNT_BYTES 16
// MAX_HASH_BLOCK_SIZE is the maximum hash block size that we'll support.
// Currently SHA-384/512 has a 128-byte block size and that's the largest
// supported by TLS.)
#define MAX_HASH_BLOCK_SIZE 128
int EVP_tls_cbc_remove_padding(crypto_word_t *out_padding_ok, size_t *out_len,
const uint8_t *in, size_t in_len,
size_t block_size, size_t mac_size) {
@@ -133,6 +124,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.
@@ -182,134 +174,110 @@ void EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in,
OPENSSL_memcpy(out, rotated_mac, md_size);
}
// u32toBE serialises an unsigned, 32-bit number (n) as four bytes at (p) in
// big-endian order. The value of p is advanced by four.
#define u32toBE(n, p) \
do { \
*((p)++) = (uint8_t)((n) >> 24); \
*((p)++) = (uint8_t)((n) >> 16); \
*((p)++) = (uint8_t)((n) >> 8); \
*((p)++) = (uint8_t)((n)); \
} while (0)
// u64toBE serialises an unsigned, 64-bit number (n) as eight bytes at (p) in
// big-endian order. The value of p is advanced by eight.
#define u64toBE(n, p) \
do { \
*((p)++) = (uint8_t)((n) >> 56); \
*((p)++) = (uint8_t)((n) >> 48); \
*((p)++) = (uint8_t)((n) >> 40); \
*((p)++) = (uint8_t)((n) >> 32); \
*((p)++) = (uint8_t)((n) >> 24); \
*((p)++) = (uint8_t)((n) >> 16); \
*((p)++) = (uint8_t)((n) >> 8); \
*((p)++) = (uint8_t)((n)); \
} while (0)
typedef union {
SHA_CTX sha1;
SHA256_CTX sha256;
SHA512_CTX sha512;
} HASH_CTX;
static void tls1_sha1_transform(HASH_CTX *ctx, const uint8_t *block) {
SHA1_Transform(&ctx->sha1, block);
}
static void tls1_sha256_transform(HASH_CTX *ctx, const uint8_t *block) {
SHA256_Transform(&ctx->sha256, block);
}
static void tls1_sha512_transform(HASH_CTX *ctx, const uint8_t *block) {
SHA512_Transform(&ctx->sha512, block);
}
// These functions serialize the state of a hash and thus perform the standard
// "final" operation without adding the padding and length that such a function
// typically does.
static void tls1_sha1_final_raw(HASH_CTX *ctx, uint8_t *md_out) {
SHA_CTX *sha1 = &ctx->sha1;
u32toBE(sha1->h[0], md_out);
u32toBE(sha1->h[1], md_out);
u32toBE(sha1->h[2], md_out);
u32toBE(sha1->h[3], md_out);
u32toBE(sha1->h[4], md_out);
}
static void tls1_sha256_final_raw(HASH_CTX *ctx, uint8_t *md_out) {
SHA256_CTX *sha256 = &ctx->sha256;
for (unsigned i = 0; i < 8; i++) {
u32toBE(sha256->h[i], md_out);
int EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx,
uint8_t out[SHA_DIGEST_LENGTH],
const uint8_t *in, size_t len,
size_t max_len) {
// Bound the input length so |total_bits| below fits in four bytes. This is
// redundant with TLS record size limits. This also ensures |input_idx| below
// does not overflow.
size_t max_len_bits = max_len << 3;
if (ctx->Nh != 0 ||
(max_len_bits >> 3) != max_len || // Overflow
ctx->Nl + max_len_bits < max_len_bits ||
ctx->Nl + max_len_bits > UINT32_MAX) {
return 0;
}
}
static void tls1_sha512_final_raw(HASH_CTX *ctx, uint8_t *md_out) {
SHA512_CTX *sha512 = &ctx->sha512;
for (unsigned i = 0; i < 8; i++) {
u64toBE(sha512->h[i], md_out);
// We need to hash the following into |ctx|:
//
// - ctx->data[:ctx->num]
// - in[:len]
// - A 0x80 byte
// - However many zero bytes are needed to pad up to a block.
// - Eight bytes of length.
size_t num_blocks = (ctx->num + len + 1 + 8 + SHA_CBLOCK - 1) >> 6;
size_t last_block = num_blocks - 1;
size_t max_blocks = (ctx->num + max_len + 1 + 8 + SHA_CBLOCK - 1) >> 6;
// The bounds above imply |total_bits| fits in four bytes.
size_t total_bits = ctx->Nl + (len << 3);
uint8_t length_bytes[4];
length_bytes[0] = (uint8_t)(total_bits >> 24);
length_bytes[1] = (uint8_t)(total_bits >> 16);
length_bytes[2] = (uint8_t)(total_bits >> 8);
length_bytes[3] = (uint8_t)total_bits;
// We now construct and process each expected block in constant-time.
uint8_t block[SHA_CBLOCK] = {0};
uint32_t result[5] = {0};
// input_idx is the index into |in| corresponding to the current block.
// However, we allow this index to overflow beyond |max_len|, to simplify the
// 0x80 byte.
size_t input_idx = 0;
for (size_t i = 0; i < max_blocks; i++) {
// Fill |block| with data from the partial block in |ctx| and |in|. We copy
// as if we were hashing up to |max_len| and then zero the excess later.
size_t block_start = 0;
if (i == 0) {
OPENSSL_memcpy(block, ctx->data, ctx->num);
block_start = ctx->num;
}
if (input_idx < max_len) {
size_t to_copy = SHA_CBLOCK - block_start;
if (to_copy > max_len - input_idx) {
to_copy = max_len - input_idx;
}
OPENSSL_memcpy(block + block_start, in + input_idx, to_copy);
}
// Zero any bytes beyond |len| and add the 0x80 byte.
for (size_t j = block_start; j < SHA_CBLOCK; j++) {
// input[idx] corresponds to block[j].
size_t idx = input_idx + j - block_start;
// The barriers on |len| are not strictly necessary. However, without
// them, GCC compiles this code by incorporating |len| into the loop
// counter and subtracting it out later. This is still constant-time, but
// it frustrates attempts to validate this.
uint8_t is_in_bounds = constant_time_lt_8(idx, value_barrier_w(len));
uint8_t is_padding_byte = constant_time_eq_8(idx, value_barrier_w(len));
block[j] &= is_in_bounds;
block[j] |= 0x80 & is_padding_byte;
}
input_idx += SHA_CBLOCK - block_start;
// Fill in the length if this is the last block.
crypto_word_t is_last_block = constant_time_eq_w(i, last_block);
for (size_t j = 0; j < 4; j++) {
block[SHA_CBLOCK - 4 + j] |= is_last_block & length_bytes[j];
}
// Process the block and save the hash state if it is the final value.
SHA1_Transform(ctx, block);
for (size_t j = 0; j < 5; j++) {
result[j] |= is_last_block & ctx->h[j];
}
}
// Write the output.
for (size_t i = 0; i < 5; i++) {
CRYPTO_store_u32_be(out + 4 * i, result[i]);
}
return 1;
}
int EVP_tls_cbc_record_digest_supported(const EVP_MD *md) {
switch (EVP_MD_type(md)) {
case NID_sha1:
case NID_sha256:
case NID_sha384:
return 1;
default:
return 0;
}
return EVP_MD_type(md) == NID_sha1;
}
int EVP_tls_cbc_digest_record(const EVP_MD *md, uint8_t *md_out,
size_t *md_out_size, const uint8_t header[13],
const uint8_t *data, size_t data_plus_mac_size,
const uint8_t *data, size_t data_size,
size_t data_plus_mac_plus_padding_size,
const uint8_t *mac_secret,
unsigned mac_secret_length) {
HASH_CTX md_state;
void (*md_final_raw)(HASH_CTX *ctx, uint8_t *md_out);
void (*md_transform)(HASH_CTX *ctx, const uint8_t *block);
unsigned md_size, md_block_size = 64, md_block_shift = 6;
// md_length_size is the number of bytes in the length field that terminates
// the hash.
unsigned md_length_size = 8;
// Bound the acceptable input so we can forget about many possible overflows
// later in this function. This is redundant with the record size limits in
// TLS.
if (data_plus_mac_plus_padding_size >= 1024 * 1024) {
assert(0);
return 0;
}
switch (EVP_MD_type(md)) {
case NID_sha1:
SHA1_Init(&md_state.sha1);
md_final_raw = tls1_sha1_final_raw;
md_transform = tls1_sha1_transform;
md_size = SHA_DIGEST_LENGTH;
break;
case NID_sha256:
SHA256_Init(&md_state.sha256);
md_final_raw = tls1_sha256_final_raw;
md_transform = tls1_sha256_transform;
md_size = SHA256_DIGEST_LENGTH;
break;
case NID_sha384:
SHA384_Init(&md_state.sha512);
md_final_raw = tls1_sha512_final_raw;
md_transform = tls1_sha512_transform;
md_size = SHA384_DIGEST_LENGTH;
md_block_size = 128;
md_block_shift = 7;
md_length_size = 16;
break;
default:
if (EVP_MD_type(md) != NID_sha1) {
// EVP_tls_cbc_record_digest_supported should have been called first to
// check that the hash function is supported.
assert(0);
@@ -317,175 +285,54 @@ int EVP_tls_cbc_digest_record(const EVP_MD *md, uint8_t *md_out,
return 0;
}
assert(md_length_size <= MAX_HASH_BIT_COUNT_BYTES);
assert(md_block_size <= MAX_HASH_BLOCK_SIZE);
assert(md_block_size == (1u << md_block_shift));
assert(md_size <= EVP_MAX_MD_SIZE);
static const size_t kHeaderLength = 13;
// kVarianceBlocks is the number of blocks of the hash that we have to
// calculate in constant time because they could be altered by the
// padding value.
//
// TLSv1 has MACs up to 48 bytes long (SHA-384) and the padding is not
// required to be minimal. Therefore we say that the final |kVarianceBlocks|
// blocks can vary based on the padding and on the hash used. This value
// must be derived from public information.
const size_t kVarianceBlocks =
( 255 + 1 + // maximum padding bytes + padding length
md_size + // length of hash's output
md_block_size - 1 // ceiling
) / md_block_size
+ 1; // the 0x80 marker and the encoded message length could or not
// require an extra block; since the exact value depends on the
// message length; thus, one extra block is always added to run
// in constant time.
// From now on we're dealing with the MAC, which conceptually has 13
// bytes of `header' before the start of the data.
size_t len = data_plus_mac_plus_padding_size + kHeaderLength;
// max_mac_bytes contains the maximum bytes of bytes in the MAC, including
// |header|, assuming that there's no padding.
size_t max_mac_bytes = len - md_size - 1;
// num_blocks is the maximum number of hash blocks.
size_t num_blocks =
(max_mac_bytes + 1 + md_length_size + md_block_size - 1) / md_block_size;
// In order to calculate the MAC in constant time we have to handle
// the final blocks specially because the padding value could cause the
// end to appear somewhere in the final |kVarianceBlocks| blocks and we
// can't leak where. However, |num_starting_blocks| worth of data can
// be hashed right away because no padding value can affect whether
// they are plaintext.
size_t num_starting_blocks = 0;
// k is the starting byte offset into the conceptual header||data where
// we start processing.
size_t k = 0;
// mac_end_offset is the index just past the end of the data to be MACed.
size_t mac_end_offset = data_plus_mac_size + kHeaderLength - md_size;
// c is the index of the 0x80 byte in the final hash block that contains
// application data.
size_t c = mac_end_offset & (md_block_size - 1);
// index_a is the hash block number that contains the 0x80 terminating value.
size_t index_a = mac_end_offset >> md_block_shift;
// index_b is the hash block number that contains the 64-bit hash length, in
// bits.
size_t index_b = (mac_end_offset + md_length_size) >> md_block_shift;
if (num_blocks > kVarianceBlocks) {
num_starting_blocks = num_blocks - kVarianceBlocks;
k = md_block_size * num_starting_blocks;
if (mac_secret_length > SHA_CBLOCK) {
// HMAC pads small keys with zeros and hashes large keys down. This function
// should never reach the large key case.
assert(0);
return 0;
}
// bits is the hash-length in bits. It includes the additional hash
// block for the masked HMAC key.
size_t bits = 8 * mac_end_offset; // at most 18 bits to represent
// Compute the initial HMAC block.
bits += 8 * md_block_size;
// hmac_pad is the masked HMAC key.
uint8_t hmac_pad[MAX_HASH_BLOCK_SIZE];
OPENSSL_memset(hmac_pad, 0, md_block_size);
assert(mac_secret_length <= sizeof(hmac_pad));
uint8_t hmac_pad[SHA_CBLOCK];
OPENSSL_memset(hmac_pad, 0, sizeof(hmac_pad));
OPENSSL_memcpy(hmac_pad, mac_secret, mac_secret_length);
for (size_t i = 0; i < md_block_size; i++) {
for (size_t i = 0; i < SHA_CBLOCK; i++) {
hmac_pad[i] ^= 0x36;
}
md_transform(&md_state, hmac_pad);
SHA_CTX ctx;
SHA1_Init(&ctx);
SHA1_Update(&ctx, hmac_pad, SHA_CBLOCK);
SHA1_Update(&ctx, header, 13);
// The length check means |bits| fits in four bytes.
uint8_t length_bytes[MAX_HASH_BIT_COUNT_BYTES];
OPENSSL_memset(length_bytes, 0, md_length_size - 4);
length_bytes[md_length_size - 4] = (uint8_t)(bits >> 24);
length_bytes[md_length_size - 3] = (uint8_t)(bits >> 16);
length_bytes[md_length_size - 2] = (uint8_t)(bits >> 8);
length_bytes[md_length_size - 1] = (uint8_t)bits;
if (k > 0) {
// k is a multiple of md_block_size.
uint8_t first_block[MAX_HASH_BLOCK_SIZE];
OPENSSL_memcpy(first_block, header, 13);
OPENSSL_memcpy(first_block + 13, data, md_block_size - 13);
md_transform(&md_state, first_block);
for (size_t i = 1; i < k / md_block_size; i++) {
md_transform(&md_state, data + md_block_size * i - 13);
}
// There are at most 256 bytes of padding, so we can compute the public
// minimum length for |data_size|.
size_t min_data_size = 0;
if (data_plus_mac_plus_padding_size > SHA_DIGEST_LENGTH + 256) {
min_data_size = data_plus_mac_plus_padding_size - SHA_DIGEST_LENGTH - 256;
}
uint8_t mac_out[EVP_MAX_MD_SIZE];
OPENSSL_memset(mac_out, 0, sizeof(mac_out));
// Hash the public minimum length directly. This reduces the number of blocks
// that must be computed in constant-time.
SHA1_Update(&ctx, data, min_data_size);
// We now process the final hash blocks. For each block, we construct
// it in constant time. If the |i==index_a| then we'll include the 0x80
// bytes and zero pad etc. For each block we selectively copy it, in
// constant time, to |mac_out|.
for (size_t i = num_starting_blocks;
i <= num_starting_blocks + kVarianceBlocks; i++) {
uint8_t block[MAX_HASH_BLOCK_SIZE];
uint8_t is_block_a = constant_time_eq_8(i, index_a);
uint8_t is_block_b = constant_time_eq_8(i, index_b);
for (size_t j = 0; j < md_block_size; j++) {
uint8_t b = 0;
if (k < kHeaderLength) {
b = header[k];
} else if (k < data_plus_mac_plus_padding_size + kHeaderLength) {
b = data[k - kHeaderLength];
}
k++;
uint8_t is_past_c = is_block_a & constant_time_ge_8(j, c);
uint8_t is_past_cp1 = is_block_a & constant_time_ge_8(j, c + 1);
// If this is the block containing the end of the
// application data, and we are at the offset for the
// 0x80 value, then overwrite b with 0x80.
b = constant_time_select_8(is_past_c, 0x80, b);
// If this the the block containing the end of the
// application data and we're past the 0x80 value then
// just write zero.
b = b & ~is_past_cp1;
// If this is index_b (the final block), but not
// index_a (the end of the data), then the 64-bit
// length didn't fit into index_a and we're having to
// add an extra block of zeros.
b &= ~is_block_b | is_block_a;
// The final bytes of one of the blocks contains the
// length.
if (j >= md_block_size - md_length_size) {
// If this is index_b, write a length byte.
b = constant_time_select_8(
is_block_b, length_bytes[j - (md_block_size - md_length_size)], b);
}
block[j] = b;
}
md_transform(&md_state, block);
md_final_raw(&md_state, block);
// If this is index_b, copy the hash value to |mac_out|.
for (size_t j = 0; j < md_size; j++) {
mac_out[j] |= block[j] & is_block_b;
}
}
EVP_MD_CTX md_ctx;
EVP_MD_CTX_init(&md_ctx);
if (!EVP_DigestInit_ex(&md_ctx, md, NULL /* engine */)) {
EVP_MD_CTX_cleanup(&md_ctx);
// Hash the remaining data without leaking |data_size|.
uint8_t mac_out[SHA_DIGEST_LENGTH];
if (!EVP_sha1_final_with_secret_suffix(
&ctx, mac_out, data + min_data_size, data_size - min_data_size,
data_plus_mac_plus_padding_size - min_data_size)) {
return 0;
}
// Complete the HMAC in the standard manner.
for (size_t i = 0; i < md_block_size; i++) {
SHA1_Init(&ctx);
for (size_t i = 0; i < SHA_CBLOCK; i++) {
hmac_pad[i] ^= 0x6a;
}
EVP_DigestUpdate(&md_ctx, hmac_pad, md_block_size);
EVP_DigestUpdate(&md_ctx, mac_out, md_size);
unsigned md_out_size_u;
EVP_DigestFinal(&md_ctx, md_out, &md_out_size_u);
*md_out_size = md_out_size_u;
EVP_MD_CTX_cleanup(&md_ctx);
SHA1_Update(&ctx, hmac_pad, SHA_CBLOCK);
SHA1_Update(&ctx, mac_out, SHA_DIGEST_LENGTH);
SHA1_Final(md_out, &ctx);
*md_out_size = SHA_DIGEST_LENGTH;
return 1;
}
+14 -3
View File
@@ -68,6 +68,7 @@
#include "conf_def.h"
#include "internal.h"
#include "../internal.h"
#include "../lhash/internal.h"
DEFINE_LHASH_OF(CONF_VALUE)
@@ -76,12 +77,16 @@ struct conf_st {
LHASH_OF(CONF_VALUE) *data;
};
static const char kDefaultSectionName[] = "default";
// The maximum length we can grow a value to after variable expansion. 64k
// should be more than enough for all reasonable uses.
#define MAX_CONF_VALUE_LENGTH 65536
static uint32_t conf_value_hash(const CONF_VALUE *v) {
return (lh_strhash(v->section) << 2) ^ lh_strhash(v->name);
const uint32_t section_hash = v->section ? OPENSSL_strhash(v->section) : 0;
const uint32_t name_hash = v->name ? OPENSSL_strhash(v->name) : 0;
return (section_hash << 2) ^ name_hash;
}
static int conf_value_cmp(const CONF_VALUE *a, const CONF_VALUE *b) {
@@ -155,12 +160,14 @@ static void value_free(CONF_VALUE *value) {
OPENSSL_free(value);
}
static void value_free_arg(CONF_VALUE *value, void *arg) { value_free(value); }
void NCONF_free(CONF *conf) {
if (conf == NULL || conf->data == NULL) {
return;
}
lh_CONF_VALUE_doall(conf->data, value_free);
lh_CONF_VALUE_doall_arg(conf->data, value_free_arg, NULL);
lh_CONF_VALUE_free(conf->data);
OPENSSL_free(conf);
}
@@ -390,6 +397,10 @@ const char *NCONF_get_string(const CONF *conf, const char *section,
const char *name) {
CONF_VALUE template, *value;
if (section == NULL) {
section = kDefaultSectionName;
}
OPENSSL_memset(&template, 0, sizeof(template));
template.section = (char *) section;
template.name = (char *) name;
@@ -538,7 +549,7 @@ static int def_load_bio(CONF *conf, BIO *in, long *out_error_line) {
goto err;
}
section = OPENSSL_strdup("default");
section = OPENSSL_strdup(kDefaultSectionName);
if (section == NULL) {
OPENSSL_PUT_ERROR(CONF, ERR_R_MALLOC_FAILURE);
goto err;
@@ -0,0 +1,41 @@
/* Copyright (c) 2018, Google Inc.
* Copyright (c) 2020, Arm Ltd.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#include <CCryptoBoringSSL_cpu.h>
#if defined(OPENSSL_AARCH64) && defined(OPENSSL_WINDOWS) && \
!defined(OPENSSL_STATIC_ARMCAP)
#include <windows.h>
#include <CCryptoBoringSSL_arm_arch.h>
#include "internal.h"
extern uint32_t OPENSSL_armcap_P;
void OPENSSL_cpuid_setup(void) {
// We do not need to check for the presence of NEON, as Armv8-A always has it
OPENSSL_armcap_P |= ARMV7_NEON;
if (IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE)) {
// These are all covered by one call in Windows
OPENSSL_armcap_P |= ARMV8_AES;
OPENSSL_armcap_P |= ARMV8_PMULL;
OPENSSL_armcap_P |= ARMV8_SHA1;
OPENSSL_armcap_P |= ARMV8_SHA256;
}
}
#endif
@@ -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;
@@ -173,7 +175,13 @@ void OPENSSL_cpuid_setup(void) {
hwcap = crypto_get_arm_hwcap_from_cpuinfo(&cpuinfo);
}
// Clear NEON support if known broken.
// Clear NEON support if known broken. Note, if NEON is available statically,
// the non-NEON code is dropped and this workaround is a no-op.
//
// TODO(davidben): The Android NDK now builds with NEON statically available
// by default. Cronet still has some consumers that support NEON-less devices
// (b/150371744). Get metrics on whether they still see this CPU and, if not,
// remove this check entirely.
g_has_broken_neon = crypto_cpuinfo_has_broken_neon(&cpuinfo);
if (g_has_broken_neon) {
hwcap &= ~HWCAP_NEON;
@@ -184,7 +192,10 @@ void OPENSSL_cpuid_setup(void) {
OPENSSL_armcap_P |= ARMV7_NEON;
// Some ARMv8 Android devices don't expose AT_HWCAP2. Fall back to
// /proc/cpuinfo. See https://crbug.com/596156.
// /proc/cpuinfo. See https://crbug.com/boringssl/46. As of February 2021,
// this is now rare (see Chrome's Net.NeedsHWCAP2Workaround metric), but AES
// and PMULL extensions are very useful, so we still carry the workaround
// for now.
unsigned long hwcap2 = 0;
if (getauxval != NULL) {
hwcap2 = getauxval(AT_HWCAP2);
+3 -3
View File
@@ -22,15 +22,15 @@
extern uint32_t OPENSSL_armcap_P;
char CRYPTO_is_NEON_capable_at_runtime(void) {
int CRYPTO_is_NEON_capable_at_runtime(void) {
return (OPENSSL_armcap_P & ARMV7_NEON) != 0;
}
int CRYPTO_is_ARMv8_AES_capable(void) {
int CRYPTO_is_ARMv8_AES_capable_at_runtime(void) {
return (OPENSSL_armcap_P & ARMV8_AES) != 0;
}
int CRYPTO_is_ARMv8_PMULL_capable(void) {
int CRYPTO_is_ARMv8_PMULL_capable_at_runtime(void) {
return (OPENSSL_armcap_P & ARMV8_PMULL) != 0;
}
+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
@@ -828,7 +820,7 @@ static void table_select(ge_precomp *t, int pos, signed char b) {
//
// Preconditions:
// a[31] <= 127
void x25519_ge_scalarmult_base(ge_p3 *h, const uint8_t *a) {
void x25519_ge_scalarmult_base(ge_p3 *h, const uint8_t a[32]) {
signed char e[64];
signed char carry;
ge_p1p1 r;
@@ -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)
@@ -114,7 +106,7 @@ typedef struct {
} ge_cached;
void x25519_ge_tobytes(uint8_t s[32], const ge_p2 *h);
int x25519_ge_frombytes_vartime(ge_p3 *h, const uint8_t *s);
int x25519_ge_frombytes_vartime(ge_p3 *h, const uint8_t s[32]);
void x25519_ge_p3_to_cached(ge_cached *r, const ge_p3 *p);
void x25519_ge_p1p1_to_p2(ge_p2 *r, const ge_p1p1 *p);
void x25519_ge_p1p1_to_p3(ge_p3 *r, const ge_p1p1 *p);
@@ -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
@@ -53,6 +53,8 @@
#include <CCryptoBoringSSL_dh.h>
#include <CCryptoBoringSSL_bn.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include "../fipsmodule/bn/internal.h"
@@ -91,3 +93,180 @@ BIGNUM *BN_get_rfc3526_prime_1536(BIGNUM *ret) {
return ret;
}
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.
// p=(2*q)+1 or (p-1)/2 = q
// For this case, g is a generator if
// g^((p-1)/q) mod p != 1 for values of q which are the factors of p-1.
// Since the factors of p-1 are q and 2, we just need to check
// g^2 mod p != 1 and g^q mod p != 1.
//
// Having said all that,
// there is another special case method for the generators 2, 3 and 5.
// for 2, p mod 24 == 11
// for 3, p mod 12 == 5 <<<<< does not work for safe primes.
// for 5, p mod 10 == 3 or 7
//
// Thanks to Phil Karn <karn@qualcomm.com> for the pointers about the
// special generators and for answering some of my questions.
//
// I've implemented the second simple method :-).
// Since DH should be using a safe prime (both p and q are prime),
// this generator function can take a very very long time to run.
// Actually there is no reason to insist that 'generator' be a generator.
// It's just as OK (and in some sense better) to use a generator of the
// order-q subgroup.
BIGNUM *t1, *t2;
int g, ok = 0;
BN_CTX *ctx = NULL;
ctx = BN_CTX_new();
if (ctx == NULL) {
goto err;
}
BN_CTX_start(ctx);
t1 = BN_CTX_get(ctx);
t2 = BN_CTX_get(ctx);
if (t1 == NULL || t2 == NULL) {
goto err;
}
// Make sure |dh| has the necessary elements
if (dh->p == NULL) {
dh->p = BN_new();
if (dh->p == NULL) {
goto err;
}
}
if (dh->g == NULL) {
dh->g = BN_new();
if (dh->g == NULL) {
goto err;
}
}
if (generator <= 1) {
OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
goto err;
}
if (generator == DH_GENERATOR_2) {
if (!BN_set_word(t1, 24)) {
goto err;
}
if (!BN_set_word(t2, 11)) {
goto err;
}
g = 2;
} else if (generator == DH_GENERATOR_5) {
if (!BN_set_word(t1, 10)) {
goto err;
}
if (!BN_set_word(t2, 3)) {
goto err;
}
// BN_set_word(t3,7); just have to miss
// out on these ones :-(
g = 5;
} else {
// in the general case, don't worry if 'generator' is a
// generator or not: since we are using safe primes,
// it will generate either an order-q or an order-2q group,
// which both is OK
if (!BN_set_word(t1, 2)) {
goto err;
}
if (!BN_set_word(t2, 1)) {
goto err;
}
g = generator;
}
if (!BN_generate_prime_ex(dh->p, prime_bits, 1, t1, t2, cb)) {
goto err;
}
if (!BN_GENCB_call(cb, 3, 0)) {
goto err;
}
if (!BN_set_word(dh->g, g)) {
goto err;
}
ok = 1;
err:
if (!ok) {
OPENSSL_PUT_ERROR(DH, ERR_R_BN_LIB);
}
if (ctx != NULL) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
return ok;
}
static int int_dh_bn_cpy(BIGNUM **dst, const BIGNUM *src) {
BIGNUM *a = NULL;
if (src) {
a = BN_dup(src);
if (!a) {
return 0;
}
}
BN_free(*dst);
*dst = a;
return 1;
}
static int int_dh_param_copy(DH *to, const DH *from, int is_x942) {
if (is_x942 == -1) {
is_x942 = !!from->q;
}
if (!int_dh_bn_cpy(&to->p, from->p) ||
!int_dh_bn_cpy(&to->g, from->g)) {
return 0;
}
if (!is_x942) {
return 1;
}
if (!int_dh_bn_cpy(&to->q, from->q) ||
!int_dh_bn_cpy(&to->j, from->j)) {
return 0;
}
OPENSSL_free(to->seed);
to->seed = NULL;
to->seedlen = 0;
if (from->seed) {
to->seed = OPENSSL_memdup(from->seed, from->seedlen);
if (!to->seed) {
return 0;
}
to->seedlen = from->seedlen;
}
return 1;
}
DH *DHparams_dup(const DH *dh) {
DH *ret = DH_new();
if (!ret) {
return NULL;
}
if (!int_dh_param_copy(ret, dh, -1)) {
DH_free(ret);
return NULL;
}
return ret;
}
@@ -58,11 +58,14 @@
#include <string.h>
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_blake2.h>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_obj.h>
#include <CCryptoBoringSSL_nid.h>
#include "../asn1/internal.h"
#include "../internal.h"
#include "../fipsmodule/digest/internal.h"
struct nid_to_digest {
@@ -80,6 +83,7 @@ static const struct nid_to_digest nid_to_digest_mapping[] = {
{NID_sha256, EVP_sha256, SN_sha256, LN_sha256},
{NID_sha384, EVP_sha384, SN_sha384, LN_sha384},
{NID_sha512, EVP_sha512, SN_sha512, LN_sha512},
{NID_sha512_256, EVP_sha512_256, SN_sha512_256, LN_sha512_256},
{NID_md5_sha1, EVP_md5_sha1, SN_md5_sha1, LN_md5_sha1},
// As a remnant of signing |EVP_MD|s, OpenSSL returned the corresponding
// hash function when given a signature OID. To avoid unintended lax parsing
@@ -150,13 +154,14 @@ static const EVP_MD *cbs_to_md(const CBS *cbs) {
}
const EVP_MD *EVP_get_digestbyobj(const ASN1_OBJECT *obj) {
// Handle objects with no corresponding OID.
// Handle objects with no corresponding OID. Note we don't use |OBJ_obj2nid|
// here to avoid pulling in the OID table.
if (obj->nid != NID_undef) {
return EVP_get_digestbynid(obj->nid);
}
CBS cbs;
CBS_init(&cbs, obj->data, obj->length);
CBS_init(&cbs, OBJ_get0_data(obj), OBJ_length(obj));
return cbs_to_md(&cbs);
}
@@ -238,3 +243,26 @@ const EVP_MD *EVP_get_digestbyname(const char *name) {
return NULL;
}
static void blake2b256_init(EVP_MD_CTX *ctx) { BLAKE2B256_Init(ctx->md_data); }
static void blake2b256_update(EVP_MD_CTX *ctx, const void *data, size_t len) {
BLAKE2B256_Update(ctx->md_data, data, len);
}
static void blake2b256_final(EVP_MD_CTX *ctx, uint8_t *md) {
BLAKE2B256_Final(md, ctx->md_data);
}
static const EVP_MD evp_md_blake2b256 = {
NID_undef,
BLAKE2B256_DIGEST_LENGTH,
0,
blake2b256_init,
blake2b256_update,
blake2b256_final,
BLAKE2B_CBLOCK,
sizeof(BLAKE2B_CTX),
};
const EVP_MD *EVP_blake2b256(void) { return &evp_md_blake2b256; }
+40 -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) {
@@ -541,6 +550,27 @@ void DSA_SIG_free(DSA_SIG *sig) {
OPENSSL_free(sig);
}
void DSA_SIG_get0(const DSA_SIG *sig, const BIGNUM **out_r,
const BIGNUM **out_s) {
if (out_r != NULL) {
*out_r = sig->r;
}
if (out_s != NULL) {
*out_s = sig->s;
}
}
int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s) {
if (r == NULL || s == NULL) {
return 0;
}
BN_free(sig->r);
BN_free(sig->s);
sig->r = r;
sig->s = s;
return 1;
}
// mod_mul_consttime sets |r| to |a| * |b| modulo |mont->N|, treating |a| and
// |b| as secret. This function internally uses Montgomery reduction, but
// neither inputs nor outputs are in Montgomery form.
@@ -558,23 +588,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 +682,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 +715,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:
@@ -1,4 +1,4 @@
/* Copyright (c) 2017, Google Inc.
/* 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
@@ -12,18 +12,23 @@
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#include <CCryptoBoringSSL_crypto.h>
#ifndef OPENSSL_HEADER_DSA_INTERNAL_H
#define OPENSSL_HEADER_DSA_INTERNAL_H
#include <CCryptoBoringSSL_dsa.h>
// This file exists in order to give the fipsmodule target, in non-FIPS mode,
// something to compile.
int FIPS_mode(void) {
#if defined(BORINGSSL_FIPS) && !defined(OPENSSL_ASAN)
return 1;
#else
return 0;
#if defined(__cplusplus)
extern "C" {
#endif
}
int FIPS_mode_set(int on) { return on == FIPS_mode(); }
// 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
@@ -241,21 +241,6 @@ int EC_KEY_marshal_private_key(CBB *cbb, const EC_KEY *key,
return 1;
}
// is_unsigned_integer returns one if |cbs| is a valid unsigned DER INTEGER and
// zero otherwise.
static int is_unsigned_integer(const CBS *cbs) {
if (CBS_len(cbs) == 0) {
return 0;
}
uint8_t byte = CBS_data(cbs)[0];
if ((byte & 0x80) ||
(byte == 0 && CBS_len(cbs) > 1 && (CBS_data(cbs)[1] & 0x80) == 0)) {
// Negative or not minimally-encoded.
return 0;
}
return 1;
}
// kPrimeFieldOID is the encoding of 1.2.840.10045.1.1.
static const uint8_t kPrimeField[] = {0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01};
@@ -276,7 +261,7 @@ static int parse_explicit_prime_curve(CBS *in, CBS *out_prime, CBS *out_a,
OPENSSL_memcmp(CBS_data(&field_type), kPrimeField, sizeof(kPrimeField)) !=
0 ||
!CBS_get_asn1(&field_id, out_prime, CBS_ASN1_INTEGER) ||
!is_unsigned_integer(out_prime) ||
!CBS_is_unsigned_asn1_integer(out_prime) ||
CBS_len(&field_id) != 0 ||
!CBS_get_asn1(&params, &curve, CBS_ASN1_SEQUENCE) ||
!CBS_get_asn1(&curve, out_a, CBS_ASN1_OCTETSTRING) ||
@@ -286,7 +271,7 @@ static int parse_explicit_prime_curve(CBS *in, CBS *out_prime, CBS *out_a,
CBS_len(&curve) != 0 ||
!CBS_get_asn1(&params, &base, CBS_ASN1_OCTETSTRING) ||
!CBS_get_asn1(&params, out_order, CBS_ASN1_INTEGER) ||
!is_unsigned_integer(out_order) ||
!CBS_is_unsigned_asn1_integer(out_order) ||
!CBS_get_optional_asn1(&params, &cofactor, &has_cofactor,
CBS_ASN1_INTEGER) ||
CBS_len(&params) != 0) {
@@ -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;
}
+136 -112
View File
@@ -368,84 +368,6 @@ void ERR_clear_system_error(void) {
errno = 0;
}
char *ERR_error_string(uint32_t packed_error, char *ret) {
static char buf[ERR_ERROR_STRING_BUF_LEN];
if (ret == NULL) {
// TODO(fork): remove this.
ret = buf;
}
#if !defined(NDEBUG)
// This is aimed to help catch callers who don't provide
// |ERR_ERROR_STRING_BUF_LEN| bytes of space.
OPENSSL_memset(ret, 0, ERR_ERROR_STRING_BUF_LEN);
#endif
return ERR_error_string_n(packed_error, ret, ERR_ERROR_STRING_BUF_LEN);
}
char *ERR_error_string_n(uint32_t packed_error, char *buf, size_t len) {
char lib_buf[64], reason_buf[64];
const char *lib_str, *reason_str;
unsigned lib, reason;
if (len == 0) {
return NULL;
}
lib = ERR_GET_LIB(packed_error);
reason = ERR_GET_REASON(packed_error);
lib_str = ERR_lib_error_string(packed_error);
reason_str = ERR_reason_error_string(packed_error);
if (lib_str == NULL) {
BIO_snprintf(lib_buf, sizeof(lib_buf), "lib(%u)", lib);
lib_str = lib_buf;
}
if (reason_str == NULL) {
BIO_snprintf(reason_buf, sizeof(reason_buf), "reason(%u)", reason);
reason_str = reason_buf;
}
BIO_snprintf(buf, len, "error:%08" PRIx32 ":%s:OPENSSL_internal:%s",
packed_error, lib_str, reason_str);
if (strlen(buf) == len - 1) {
// output may be truncated; make sure we always have 5 colon-separated
// fields, i.e. 4 colons.
static const unsigned num_colons = 4;
unsigned i;
char *s = buf;
if (len <= num_colons) {
// In this situation it's not possible to ensure that the correct number
// of colons are included in the output.
return buf;
}
for (i = 0; i < num_colons; i++) {
char *colon = strchr(s, ':');
char *last_pos = &buf[len - 1] - num_colons + i;
if (colon == NULL || colon > last_pos) {
// set colon |i| at last possible position (buf[len-1] is the
// terminating 0). If we're setting this colon, then all whole of the
// rest of the string must be colons in order to have the correct
// number.
OPENSSL_memset(last_pos, ':', num_colons - i);
break;
}
s = colon + 1;
}
}
return buf;
}
// err_string_cmp is a compare function for searching error values with
// |bsearch| in |err_string_lookup|.
static int err_string_cmp(const void *a, const void *b) {
@@ -495,41 +417,42 @@ 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) {
static const char *err_lib_error_string(uint32_t packed_error) {
const uint32_t lib = ERR_GET_LIB(packed_error);
if (lib >= ERR_NUM_LIBS) {
@@ -538,11 +461,16 @@ const char *ERR_lib_error_string(uint32_t packed_error) {
return kLibraryNames[lib];
}
const char *ERR_lib_error_string(uint32_t packed_error) {
const char *ret = err_lib_error_string(packed_error);
return ret == NULL ? "unknown library" : ret;
}
const char *ERR_func_error_string(uint32_t packed_error) {
return "OPENSSL_internal";
}
const char *ERR_reason_error_string(uint32_t packed_error) {
static const char *err_reason_error_string(uint32_t packed_error) {
const uint32_t lib = ERR_GET_LIB(packed_error);
const uint32_t reason = ERR_GET_REASON(packed_error);
@@ -578,6 +506,86 @@ const char *ERR_reason_error_string(uint32_t packed_error) {
kOpenSSLReasonValuesLen, kOpenSSLReasonStringData);
}
const char *ERR_reason_error_string(uint32_t packed_error) {
const char *ret = err_reason_error_string(packed_error);
return ret == NULL ? "unknown error" : ret;
}
char *ERR_error_string(uint32_t packed_error, char *ret) {
static char buf[ERR_ERROR_STRING_BUF_LEN];
if (ret == NULL) {
// TODO(fork): remove this.
ret = buf;
}
#if !defined(NDEBUG)
// This is aimed to help catch callers who don't provide
// |ERR_ERROR_STRING_BUF_LEN| bytes of space.
OPENSSL_memset(ret, 0, ERR_ERROR_STRING_BUF_LEN);
#endif
return ERR_error_string_n(packed_error, ret, ERR_ERROR_STRING_BUF_LEN);
}
char *ERR_error_string_n(uint32_t packed_error, char *buf, size_t len) {
if (len == 0) {
return NULL;
}
unsigned lib = ERR_GET_LIB(packed_error);
unsigned reason = ERR_GET_REASON(packed_error);
const char *lib_str = err_lib_error_string(packed_error);
const char *reason_str = err_reason_error_string(packed_error);
char lib_buf[64], reason_buf[64];
if (lib_str == NULL) {
BIO_snprintf(lib_buf, sizeof(lib_buf), "lib(%u)", lib);
lib_str = lib_buf;
}
if (reason_str == NULL) {
BIO_snprintf(reason_buf, sizeof(reason_buf), "reason(%u)", reason);
reason_str = reason_buf;
}
BIO_snprintf(buf, len, "error:%08" PRIx32 ":%s:OPENSSL_internal:%s",
packed_error, lib_str, reason_str);
if (strlen(buf) == len - 1) {
// output may be truncated; make sure we always have 5 colon-separated
// fields, i.e. 4 colons.
static const unsigned num_colons = 4;
unsigned i;
char *s = buf;
if (len <= num_colons) {
// In this situation it's not possible to ensure that the correct number
// of colons are included in the output.
return buf;
}
for (i = 0; i < num_colons; i++) {
char *colon = strchr(s, ':');
char *last_pos = &buf[len - 1] - num_colons + i;
if (colon == NULL || colon > last_pos) {
// set colon |i| at last possible position (buf[len-1] is the
// terminating 0). If we're setting this colon, then all whole of the
// rest of the string must be colons in order to have the correct
// number.
OPENSSL_memset(last_pos, ':', num_colons - i);
break;
}
s = colon + 1;
}
}
return buf;
}
void ERR_print_errors_cb(ERR_print_errors_callback_t callback, void *ctx) {
char buf[ERR_ERROR_STRING_BUF_LEN];
char buf2[1024];
@@ -737,6 +745,22 @@ void ERR_add_error_dataf(const char *format, ...) {
err_set_error_data(buf);
}
void ERR_set_error_data(char *data, int flags) {
if (!(flags & ERR_FLAG_STRING)) {
// We do not support non-string error data.
assert(0);
return;
}
if (flags & ERR_FLAG_MALLOCED) {
err_set_error_data(data);
} else {
char *copy = OPENSSL_strdup(data);
if (copy != NULL) {
err_set_error_data(copy);
}
}
}
int ERR_set_mark(void) {
ERR_STATE *const state = err_get_state();
Loaded 100 of 555 files, more files were not shown because too many files have changed in this diff. Show more