Compare commits

...
112 Commits
Author SHA1 Message Date
Cory Benfield cc76b89416 Update BoringSSL to 7a813621dac6878ab53b6ed7392939a8982226e8 (#215) 2024-01-08 16:41:09 +00:00
Gustavo CairoandYim Lee 3e8497753e Add cxx interop build pipeline (#212)
* Add cxx interop build pipeline

* Update docker-compose.2204.59.yaml

* Change cxx interop CI step to build separate project instead of using cxx compiler flag

* Update docker-compose for 5.10

* Fix package name in docker

* Change code root dirname and remove test target

---------

Co-authored-by: Yim Lee <yim_lee@apple.com>
2023-12-21 12:55:03 +00:00
Rick Newton-Rogers c1825df19b Add more Sendable annotations to Crypto Extras (#214)
Motivation

Add Sendable annotations to Crypto Extras to reflect current sandability
so that downstream packages can implement sendable conformance.

Modifications

* Add Sendable conformance to some missed public symbols.
* RSA public and private keys are now marked sendable with their backing storage on darwin OS marked unchecked sendable until SecKey from security framework has sendability annotations

Result

* More accurate Sendable annotations
2023-12-20 13:20:12 +00:00
Si Beaumont 09f7a993f6 Update availability annotations in tests (#213) 2023-12-19 12:00:45 -08:00
Rick Newton-Rogers ed66091040 Add Sendables annotation to Crypto Extras (#211)
Motivation

Add Sendable annotations to Crypto Extras to reflect current sandability
so that downstream packages can implement sendable conformance.

Modifications

* Add Sendable conformance to appropriate public symbols.
* RSA public and private keys are notable omissions, this is because
  they are backed by SecKey from security framework and we have no
  guarantees about their sendability

Result

* Accurate Sendable annotations
2023-12-12 15:52:13 +00:00
Timo b793a1e564 Add support for CBC without padding (#210)
Motivation:

As described in #209, I personally need this to migrate an oracle driver from a third party crypto lib to swift-crypto. I think other users might benefit from this addition too.

Modifications:

I've added an overload to the encrypt and decrypt methods of AES._CBC, allowing the user to configure if padding should be added or not. With noPadding set to true, an error will be thrown if the plaintext isn't a multiple of the block size. I've added the corresponding inline documentation.

I've also added tests to ensure both encrypting and decrypting without padding work as expected. Although those tests might not be sufficient enough, because I couldn't find good resources online. I've created a bunch of random hex strings and encrypted/decrypted them using another implementation of paddingless CBC and checked if I receive the expected results. To further validate the feature, I've tested it as part of the authentication in oracle-nio, which worked in all test scenarios I've been running.

Result:

After merging this, it will be possible to use CBC without padding. This closes #209
2023-12-05 18:23:27 +00:00
Rick Newton-Rogers f4b21dbde7 Add support for pkcs1 oaep sha256 (#206)
Motivation

Add RSA OAEP-sha256 support in addition to the increasingly aged SHA-1
implementation.

Modifications

* Add a `Digest` enum to `_RSA.Encryption.Padding`
* Add a digest associated type to the `.pkcs1_oaep` padding enum case
  to allow us to distinguish different digest hash functions.
* Add a `PKCS1_OAEP_SHA256` public static let to allow users to use the
  new hash function.
* Enable SHA-256 RSA encryption tests

Result

* Support for RSA OAEP-sha256
2023-11-06 11:25:42 +00:00
Cory Benfield 3df7fa0626 Update BoringSSL to 3309ca66385ecb0c37f1ac1be9f88712e25aa8ec (#207)
* Update perlasm

* Update BoringSSL to 3309ca66385ecb0c37f1ac1be9f88712e25aa8ec

* Update CMakeLists.txt
2023-10-30 11:38:26 +00:00
Rick Newton-Rogers 7644bdcc76 BoringSSLRSAPublicKey use EVP_PKEY API (#205)
Motivation

Increased versatility of the `BoringSSLRSAPublicKey` encrypt and decrypt
methods to make future extensions possible.

Modifications

Switch the `BoringSSLRSAPublicKey` encrypt and decrypt methods to use
the `EVP_PKEY_*` API directly rather than going through the RSA
abstractions.

Result

Increased versatility of the `BoringSSLRSAPublicKey` encrypt and decrypt
methods.
2023-10-24 19:53:14 +01:00
Brian Michel fade397763 Add extern C markers (#204)
* Add extern C markers

* Only add extern in header file.
2023-10-20 08:05:48 +01:00
BJ Homer c4f2e9938a pkcs8PEMRepresentation for RSA private keys (#203)
* Teach CryptoExtras about CRYPTO_IN_SWIFTPM_FORCE_BUILD_API

* Add pkcs8PEMRepresentation to RSA private keys
2023-10-11 13:21:18 +01:00
Rick Newton-RogersandCory Benfield b51f1d6845 Bump minimum Swift version to 5.7 (#201)
Motivation:

Now that Swift 5.9 is GM we should update the supported versions and
remove 5.6

Modifications:

* Update `Package.swift`
* Delete the 5.6 docker compose file and make a 5.10 one
* Update docs

Result:

Remove support for Swift 5.6, add 5.10

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-10-04 02:19:44 -07:00
Franz Busch faad1cf4fd Add support for AES-CBC in _CryptoExtras (#200)
# Motivation
We want to support AES-CBC for encryption and decryption purposes.

# Modification
This PR adds support AES-CBC. Furthermore, it adds wycheproof tests for it.
2023-10-03 18:42:08 +01:00
Cory Benfield 629f0b679d Update to CryptoKit 2023 final API (#199)
Motivation

This patch brings us up-to-date with CryptoKit's final 2023 API form.

Modifications

Slight tweak to exporter secrets for HPKE to match final spec.
New representation for SecureBytes when empty.

Result

We're ready for the future
2023-09-13 12:03:22 +01:00
David Nadoba 953b34a601 Use SecKeyGetBlockSize instead of kSecAttrKeySizeInBits (#198) 2023-08-17 06:53:44 -07:00
Cory BenfieldandSaleem Abdulrasool 710deacf79 Set missing Windows defines (#197)
Motivation

We need a few extra Windows defines to match what BoringSSL does, and
to suppress warnings.

Modifications

Add the missing defines.

Result

Fewer warnings.
Resolves #195.

Co-authored-by: Saleem Abdulrasool <compnerd@compnerd.org>
2023-08-15 02:50:51 -07:00
Cory Benfield a234f8a62e Update BoringSSL to 7ae2b910c13017b63f1a8bd6c8decfce692869b0 (#190)
* Update vendoring script to use docker

* Update BoringSSL to 7ae2b910c13017b63f1a8bd6c8decfce692869b0

* RSA is opaque now
2023-08-03 11:34:38 +01:00
Franz BuschandCory Benfield 9c1b699540 Switch to canImport instead of os conditions (#184)
* Rework canImport to just defines with platform conditions

* Soundness and make

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-07-20 22:31:12 +01:00
Gwynne Raskind 5ac5632286 Add API providing basic RSA pubkey encrypt and privkey decrypt (#125)
* Add basic RSA encrypt/decrypt API.

* Add test vectors and tests for RSA encryption API

* Fix build failures

* Fix soundness issue

* Remove support for RSA encryption using the unsafe PKCS1 v1.5 padding

* Fix deprecation warning about the "pointer" version of Data.withUnsafeMutableBytes() by nudging the compiler to infer the "buffer" version.

* Fix deprecation warning about String.init(bytesNoCopy:length:freeWhenDone:) by using String.init(unsafeInitializedCapacity:initializingWith:) instead.

* Make _RSA.Encryption.[Public|Private]Key their own types

* Remove _RSA.Encryption.RSA[Encrypted|Decrypted]Data and just use Data directly. Don't use intermediate Array in BoringSSL implementations.

* Document the message size limits on RSA encrypt/decrypt operations

* Mark `_RSA` visible to documentation so the new docs can actually be seen (underscored name is assumed private by default)

* Fix generic type parameter shadowing warning (new warning in Swift 5.9)

* Fix pre-5.8 build

* Un-correct switch case indentation to make it wrong
2023-07-17 17:51:49 +01:00
Joey cba358dec9 Documentation - Typos & Consistency Fixes (#186) 2023-06-29 02:20:15 -07:00
Cory Benfield c433cd3341 Bring over the WWDC 2023 CryptoKit API (#181)
Motivation

WWDC has arrived! 🎉 As part of the celebration, let's
bring Crypto up to speed with the new CryptoKit API surface.

Modifications

Substantial new docstrings
HPKE support

Result

WWDC 2023 support.
2023-06-13 18:27:01 +01:00
tomer doron 940a631a68 update code of conduct (#182)
motivation: align CoC across the swift project

changes: change CoC to link to the swift.org version
2023-06-06 10:56:39 -07:00
Joey dcf0815f8f Documentation - Typos (#179) 2023-04-24 01:50:32 -07:00
Evan Wilde 33a20e650c Set CRYPTO_IN_SWIFTPM (#177)
Needed to expose SecureEncalve through SwiftCrypto when building for
Swift-Certificates. CRYPTO_IN_SWIFTPM is set all of the time in
package.swift, while CRYPTO_IN_SWIFTPM_FORCE_BUILD_API is only set in
development. Lets enable the one that's on all of the time, and remove
the one that isn't so that we get our declarations.
2023-04-19 06:40:30 +01:00
Brandon 65f8c60ab3 ChaCha20 CTR Encryption (#169)
* OpenSSLChaCha20CTR Implementation. Wraps CCryptoBoringSSL_CRYPTO_chacha_20.

* Insecure extension implementing the ChaCha20 CTR encrypt method.

* Added ChaCha20CTR Tests based on vectors provided in RFC9001 Appendix A.5

* Corrected year in header

* Changed return type to Data. Removed redundant pointer castings. Removed unnecessary array allocations in favor of withUnsafeBytes.

* Introduced a typed ChaCha20CTR Nonce and Counter struct in order to help enforce parameter constraints and type safety.

* Formatting

* Updated tests to use new Nonce and Counter structs. Added additional test checking for invalid parameters.

* Switch to HexStrings for better readability.

* Removed empty line at top of file

* Fixed UInt32.max counter assertion.

* Moved the bindMemory calls out of the function and copied a note from a similar situation elsewhere in the codebase.

* Formatting

* Implemented an _encryptContiguous function that prevents having to use the withContiguousStorageIfAvailable method. If our DataProtocol is contiguous we encrypt directly, otherwise we consolidate before encrypting. Removed inLen param from chacha20CTR call.

* Replaced the chacha20CTR function with a direct call to CCryptoBoringSSL_CRYPTO_chacha_20.

* Counter is now backed by a UInt32 instead of Data. Removed Sequence conformance.

* Formatting

* Formatting

* Replaced unsafe code (unsafeBytes and load) with a more generic and safer UInt32 construction.

* Replaced counterAsUInt32 definitions with integer literals to avoid symmetric bugs in the load.

* Updated _CryptoExtras/CMakeList.txt
2023-04-18 10:06:55 +01:00
Cory Benfield 1863cc9dcf Drop support for Swift 5.5 (#172)
* Drop support for Swift 5.5

This patch drops support for Swift 5.5.

* Drop LinuxMain.swift
2023-04-13 16:46:47 +01:00
Cory Benfield 6d9c36b4be Update BoringSSL to abfd5ebc87ddca0fab9fca067c9d7edbc355eae8 (#171)
* Update BoringSSL vendoring scripts for new perlasm

* Update BoringSSL to abfd5ebc87ddca0fab9fca067c9d7edbc355eae8
2023-04-13 13:02:12 +01:00
Yim Lee a56d70a286 Add docker-compose file for Swift 5.8 and 5.9 (#170) 2023-04-13 09:47:52 +01:00
Alexander Cyon 3ea0bdb8fd Add five new Wycheproof ECDSA test vectors using IEEE P1363 format (#167)
* Add five new ECDSA Wycheproof test vectors with signatures on IEEE P1363 format, remove four unused Wycheproof test vectors.

* Revert unnecessary protocol extension
2023-04-11 09:07:15 +01:00
Alexander Cyon d1047c1c9a Update Wycheproof ecdsa_secp*_test.json to v1 (#166) 2023-04-06 17:43:59 +01:00
Alexander CyonandCory Benfield 401a7a8ba7 Update Wycheproof ecdh_secp521r1_ecpoint_test.json to v1 (#164)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-04-03 12:46:52 +01:00
Alexander CyonandCory Benfield 944428373d Update Wycheproof ecdh_secp521r1_test.json to v1 (#163)
* Update ASN1 test helpers to not fatalError but rather fail/throw, needed for some new tests in Wycheproof v1

* Update Wycheproof ecdh_secp521r1_test.json to v1

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-04-03 12:36:32 +01:00
Alexander CyonandCory Benfield 5a1b404183 Update Wycheproof ecdh_secp384r1_test.json to v1 (#162)
* Update ASN1 test helpers to not fatalError but rather fail/throw, needed for some new tests in Wycheproof v1

* Update Wycheproof ecdh_secp384r1_test.json to v1

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-04-03 11:50:32 +01:00
Alexander CyonandCory Benfield 3c4009af05 Update Wycheproof ecdh_secp384r1_ecpoint_test.json to v1 (#161)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-04-03 11:26:19 +01:00
Alexander CyonandCory Benfield 22a06540cc Update Wycheproof x25519_test.json to v1 (#155)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-04-03 11:14:00 +01:00
Alexander CyonandCory Benfield 7d7419ebba Update Wycheproof aes_gcm.json to v1 (#156)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-04-03 10:57:35 +01:00
Alexander CyonandCory Benfield f2125b625f Update Wycheproof chacha20_poly1305 to v1 (#157)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-04-03 10:49:41 +01:00
Alexander CyonandCory Benfield 959c1fe152 Update Wycheproof ecdh_secp256r1_ecpoint_test.json to v1 (#158)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-04-03 10:36:04 +01:00
Alexander CyonandCory Benfield 36d5ec4458 Update eddsa_test.json which has been renamed to ed25519_test.json, so we use the new name. (#159)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-04-03 10:27:26 +01:00
Alexander Cyon 6be84be0bd Update Wycheproof ecdh_secp256r1_test.json to v1 (#160) 2023-04-03 10:14:02 +01:00
Alexander Cyon 25a68d63b7 Fix broken link (#153) 2023-03-24 08:01:55 +00:00
Yim Lee 5d8b14d227 Exclude AES from CMake (#152)
* Exclude AES from CMake

SwiftPM doesn't need it and this would allow removal of CCryptoBoringSSL dependency on non-Darwin platforms, thus reducing SwiftPM size.

* Update update_cmakelists.sh to exclude AES source files
2023-03-16 09:19:55 +00:00
Cory Benfield da0fe44138 Fixup CryptoExtras RSA public key formats (#151)
Motivation

CryptoExtras RSA public keys support being exported in DER and PEM form.
These exports work great, but it turns out they are inconsistent between
the Darwin and non-Darwin implementations. Darwin platforms would export
the public keys in PKCS1 format, while non-Darwin was exporting them as
SPKI. This isn't great!

Modifications

- Make the two consistent. `.derRepresentation` should export SPKI
    formatted public keys, because that's what it does for all the EC
    keys.
- Add `.pkcs1DERRepresentation` and `.pkcs1PEMRepresentation` for those
    users that require the PKCS1 formatted key.

Result

Key export types are now consistent on all platforms.
2023-03-10 11:38:36 +00:00
Saleem Abdulrasool 80a6e3edc1 build: add ARM64 spelling for Windows (#148)
Windows uses `ARM64` for the `CMAKE_SYSTEM_PROCESSOR` which does not
match the existing spellings.  Add the special case for Darwin while in
the area.
2023-03-02 12:13:00 -08:00
Andrew BarbaandMax Desiatov a1b800581e Support SwiftWasm (#145)
Co-authored-by: Max Desiatov <m_desiatov@apple.com>
2023-02-09 06:04:16 -08:00
Yim Lee 935c74be2f Set up CMake build for _CryptoExtras (#144)
* Set up CMake build for _CryptoExtras

* Add CMakeLists.txt to exclude list
2023-01-26 10:51:20 +00:00
Cory Benfield 75ec60b8b4 Update BoringSSL to 45b8d7bbd771cbf7e116db2ba1f1cc7af959497e (#143)
* Update vendoring scripts for new BoringSSL

* Update BoringSSL to 45b8d7bbd771cbf7e116db2ba1f1cc7af959497e

* Minor tweak
2023-01-19 17:30:15 +00:00
Cory Benfield d330d21edf Add AES block function to CryptoExtras (#142)
In some cases developers have need of AES modes other than what we
support today, or need the ability to implement algorithms that require
access to the core AES permutation function. As a starting point, we can
provide access to the AES block function in CryptoExtras.
2023-01-18 16:07:44 +00:00
Saleem Abdulrasool 9cc89f0170 build: adjust linking for Crypto (#137)
The package DLL `Crypto.dll` was building the BoringSSL wrapper
(`CryptoBoringWrapper`) in the style that the user requested (static or
shared).  However, there is a single user of the library and is not
directly included by the SPM client.  Furthermore, the library was not
setup for installation which makes redistribution of it impossible.
Always build the library in a static mode to allow compaction into the
`Crypto` target.
2023-01-06 09:04:40 +00:00
Yim Lee 92a04c10fc Link Foundation (#136)
To address error seen in https://ci-external.swift.org/job/swiftpm-PR-windows/581/console:

```
FAILED: bin/CryptoBoringWrapper.dll Sources/CryptoBoringWrapper/CMakeFiles/CryptoBoringWrapper.dir/AEAD/BoringSSLAEAD.swift.obj Sources/CryptoBoringWrapper/CMakeFiles/CryptoBoringWrapper.dir/CryptoKitErrors_boring.swift.obj swift/CryptoBoringWrapper.swiftmodule lib/CryptoBoringWrapper.lib 
cmd.exe /C "cd . && T:\1\bin\swiftc.exe -output-file-map Sources\CryptoBoringWrapper\CMakeFiles\CryptoBoringWrapper.dir\Release\output-file-map.json -incremental -j 36 -emit-library -o bin\CryptoBoringWrapper.dll -module-name CryptoBoringWrapper -module-link-name CryptoBoringWrapper -emit-module -emit-module-path swift\CryptoBoringWrapper.swiftmodule -emit-dependencies -DCryptoBoringWrapper_EXPORTS -O -libc MD -I C:\Users\swift-ci\jenkins\workspace\swiftpm-PR-windows\swift-crypto\Sources\CCryptoBoringSSL\include -I C:\Users\swift-ci\jenkins\workspace\swiftpm-PR-windows\swift-crypto\Sources\CCryptoBoringSSLShims\include -I swift C:\Users\swift-ci\jenkins\workspace\swiftpm-PR-windows\swift-crypto\Sources\CryptoBoringWrapper\AEAD\BoringSSLAEAD.swift C:\Users\swift-ci\jenkins\workspace\swiftpm-PR-windows\swift-crypto\Sources\CryptoBoringWrapper\CryptoKitErrors_boring.swift    -Xlinker -implib:lib\CryptoBoringWrapper.lib -L T:\12\lib  -L T:\12\lib  -L T:\12\lib lib\CCryptoBoringSSL.lib  lib\CCryptoBoringSSLShims.lib  lib\CCryptoBoringSSL.lib && cd ."
C:\Users\swift-ci\jenkins\workspace\swiftpm-PR-windows\swift-crypto\Sources\CryptoBoringWrapper\AEAD\BoringSSLAEAD.swift:17:8: error: no such module 'Foundation'

import Foundation
```
2022-12-05 09:40:28 +00:00
Cory Benfield 71ae6adf89 Add Linux support for PKCS#1 RSA public keys (#135)
Motivation

The init(derRepresentation:) and init(pemRepresentation:) constructors
for RSA public keys support both PKCS#8 and PKCS#1 key formats on
Darwin. This support was missing from Linux, with only PKCS#8 support.
This patch brings the two platforms into parity.

Modifications

Add code to try both versions on Linux.
Add tests.

Results

PKCS#1 keys are supported on Linux too!
2022-11-21 09:45:13 -08:00
Cory Benfield f652300628 Update BoringSSL to 0faffc7a30eeb195248ea43056f4848e2a9b1c6d (#134) 2022-11-14 11:17:06 +00:00
Franz Busch d11194ad26 Provide AES-GCM-SIV in CryptoExtras (#133)
# Motivation
BoringSSL exposes AES-GCM-SIV algorithms which are in general useful to have and provide a nonce-misuse resistant mode of AES-GCM. Since, `CryptoKit` is not exposing AES-GCM-SIV we need to add this to `_CryptoExtras`

# Modification
Exposes `AES-GCM-SIV` through `_CryptoExtras`.

# Result
We can now use `AES-GCM-SIV` through `_CryptoExtras`.
2022-10-14 09:50:36 +01:00
George Barnett 1c59986eaf Raise minimum supported Swift version from 5.4 to 5.5 (#131)
Motivation:

Old Swift versions are periodically dropped. Now that 5.7 has been
released, 5.4 will be dropped.

Modifications:

- Update tools version
- Remove 5.4 docker-compose
- Update 5.7 docker-compose to use released image and move from focal to
  jammy
- Update docs

Result:

Swift 5.5 is the minimum supported Swift version
2022-09-28 09:25:21 -07:00
George Barnett d89caf3006 Update BoringSSL to cab31f65f1ad6e6daca62e95b25dd6cd805fce0b (#132) 2022-09-28 12:08:04 +01:00
Eric Miotto e5dabe7f3a build: use cctols ranlib on Darwin (#129)
This complements the change in #105 and allows to build with a CMake
newer than 3.19.6.

Addresses rdar://99435188
2022-09-02 16:57:50 +01:00
Alex Shatberashvili 30eab5ad37 Make BoringSSL wrapper match CryptoKit behaviour when working with x9.63 (#128)
* Make BoringSSL wrapper match CryptoKit behaviour when working with x963 representation

* Revert Package.swift changes

* Fix Signing tests and add test cases for invalid key lengths
2022-08-23 11:47:08 +01:00
Cory Benfield 5fdc8c4daa Validate missing imports in CI (#127) 2022-08-16 01:28:09 -07:00
Cory Benfield 4832fa0d13 Update Swift Crypto for the Ventura beta API (#123)
* Bring over API files from macOS Ventura

* Implement the new API surface

This patch implements the new API surface, and removes anything that's
no longer compatible with the expected API surface from CryptoKit
2022-06-27 14:12:38 +01:00
Saleem AbdulrasoolandCory Benfield 126981ae16 Crypto: explicitly type the array slice (#122)
Without the explicit typing, the build fails with recent toolchain
builds expecting the type to conform to an incorrect type.  This
repairs the build.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2022-06-21 08:48:03 -07:00
Cory Benfield 57a0c7dde9 Update BoringSSL to 1f51cfc7d7f54d2bee30bb5793470ef9c36a5083 (#121) 2022-06-20 14:24:03 +01:00
swiftty 9580d7e187 Fix ASN.1 serialization when content greater than or equal to 128 bytes (#120) 2022-06-17 17:09:49 +01:00
Daiki Matsudate 03399ef465 truncating for big contentLength (#119)
When contentLength is greater than 8 bits, i.e., greater than UInt8.max, the original implementation crashes.
To work around this, use UInt8.init(truncatingIfNeeded:) to truncate only the lower 8 bits.
2022-06-16 23:44:20 -07:00
Cory Benfield 30b30ef3a1 Use 5.7 nightlies (#118) 2022-06-13 13:39:40 +01:00
Tim Condon eb2d582c29 Update Python script to Python 3 (#117) 2022-05-17 10:46:02 +01:00
Cory Benfield d9825fa541 Update BoringSSL to f961de5c47ed265c3e758ec70dd15ece20809962 (#115)
This patch also cleans up an include issue. The actual code change is in
`scripts/vendor_boringssl.sh`, the rest is just the update.
2022-04-21 10:39:48 +01:00
Cory Benfield d180057628 Update BoringSSL to 2fc6d38391cb76839c76b2a462619e7d69fd998d (#113) 2022-04-20 03:50:13 -07:00
Cory Benfield 17d95a6782 Avoid unnecessary copies of BoringSSL (#94)
Motivation:

When using only the CryptoKit API on Apple platforms we have always
thunked through to the CryptoKit interface and implementation. However,
we didn't do a thorough job of preventing the BoringSSL target from
getting compiled and linked.

We can do a better job now, which will save compile times and binary
sizes in many cases.

Modifications:

- Change Package.swift to express a target specific dependency in most
  cases.
- Preserve a development mode which overrides that target specific
  dependency.
- Add the missing compile guards.

Results:

Smaller binaries and faster compiles on Apple platforms.
2022-04-20 11:47:19 +01:00
Fabian Fett 12a1784190 Drop support for Swift 5.2 and 5.3 (#111)
As outlined in a [Swift forums post in November ’21](https://forums.swift.org/t/swiftnio-swift-version-support/53232), SwiftNIO will only support the latest non-patch Swift release and the 2 immediately prior non-patch versions.

In this commit we drop support for Swift 5.2 and 5.3. We update CI for Swift 5.4 to run on bionic instead of focal to ensure that we still test bionic.
2022-04-20 08:17:41 +01:00
Fabian Fett ce8d18032f Use SPM API diff checker (#112) 2022-04-19 17:15:40 +01:00
Cory Benfield 067254c794 Update BoringSSL to 8bbefbfeee609b17622deedd100163c12f5c95dc (#110) 2022-03-22 13:43:20 +01:00
tomer doron 476397d837 ci update (#108)
motivation: 5.6 is out

changes:
* use release version of 5.6
* add docker setup for 5.7 (using nightly for now)
2022-03-16 21:30:22 -07:00
Saleem Abdulrasool facc82fbb4 build: attempt to workaround linker issues on Darwin (#105)
The use of a non-cctools librarian causes ld64 some heartburn.
Explicitly opt into using the cctools librarian.

rdar://87850031
2022-02-25 17:46:28 +00:00
Cory Benfield 3fb2ea5d41 Add 5.6 nightly CI (#103)
The 5.6 nightly images are available, let's use them.
2022-01-18 09:39:36 +00:00
Cory Benfield a8911e0fad Update BoringSSL to 295b31324f8c557dcd3c1c831857e33a7f23bc52 (#101) 2022-01-11 09:07:22 +00:00
tomer doron 172d71fdc3 Update doc generation script (#100)
motivation: source-kitten has changed how its invoked

changes:
* update docker file to install jazzy correctly
* invoke source-kitten with the correct flags
* make location of source-kitten source checkout more robust
2021-12-17 09:49:29 +00:00
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
803 changed files with 263204 additions and 140537 deletions

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@ about: If something isn't working as expected
### New Issue Checklist
- [ ] I'm using the latest version of Swift Crypto (master branch)
- [ ] 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)
+6 -1
View File
@@ -1,5 +1,6 @@
.DS_Store
/.build
/out
/Packages
/*.xcodeproj
Package.pins
@@ -10,4 +11,8 @@ Package.resolved
.podspecs
DerivedData
.swiftpm
**/gyb.pyc
**/gyb.pyc
.*.sw[nop]
.vscode
+1 -1
View File
@@ -1,6 +1,6 @@
# file options
--swiftversion 5.0
--swiftversion 5.4
--exclude .build
# format options
+52
View File
@@ -0,0 +1,52 @@
##===----------------------------------------------------------------------===##
##
## 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(CMAKE_SYSTEM_NAME STREQUAL Darwin AND NOT CMAKE_CROSSCOMPILING)
set(CMAKE_AR "/usr/bin/ar")
set(CMAKE_C_ARCHIVE_CREATE "<CMAKE_AR> crs <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_RANLIB "/usr/bin/ranlib")
endif()
if(NOT CMAKE_SYSTEM_NAME STREQUAL Darwin)
find_package(dispatch CONFIG)
find_package(Foundation CONFIG)
endif()
add_subdirectory(Sources)
add_subdirectory(cmake/modules)
+1 -53
View File
@@ -1,55 +1,3 @@
# Code of Conduct
To be a truly great community, swift-crypto needs to welcome developers from all walks of life,
with different backgrounds, and with a wide range of experience. A diverse and friendly
community will have more great ideas, more unique perspectives, and produce more great
code. We will work diligently to make the swift-crypto community welcoming to everyone.
To give clarity of what is expected of our members, swift-crypto has adopted the code of conduct
defined by [contributor-covenant.org](https://www.contributor-covenant.org). This document is used across many open source
communities, and we think it articulates our values well. The full text is copied below:
### Contributor Code of Conduct v1.3
As contributors and maintainers of this project, and in the interest of fostering an open and
welcoming community, we pledge to respect all people who contribute through reporting
issues, posting feature requests, updating documentation, submitting pull requests or patches,
and other activities.
We are committed to making participation in this project a harassment-free experience for
everyone, regardless of level of experience, gender, gender identity and expression, sexual
orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or
nationality.
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery
- Personal attacks
- Trolling or insulting/derogatory comments
- Public or private harassment
- Publishing other’s private information, such as physical or electronic addresses, without explicit permission
- Other unethical or unprofessional conduct
Project maintainers have the right and responsibility to remove, edit, or reject comments,
commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of
Conduct, or to ban temporarily or permanently any contributor for other behaviors that they
deem inappropriate, threatening, offensive, or harmful.
By adopting this Code of Conduct, project maintainers commit themselves to fairly and
consistently applying these principles to every aspect of managing this project. Project
maintainers who do not follow or enforce the Code of Conduct may be permanently removed
from the project team.
This code of conduct applies both within project spaces and in public spaces when an
individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by
contacting a project maintainer at [swift-server-conduct@group.apple.com](mailto:swift-server-conduct@group.apple.com). All complaints will be reviewed and
investigated and will result in a response that is deemed necessary and appropriate to the
circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter
of an incident.
*This policy is adapted from the Contributor Code of Conduct [version 1.3.0](https://contributor-covenant.org/version/1/3/0/).*
### Reporting
A working group of community members is committed to promptly addressing any [reported issues](mailto:swift-server-conduct@group.apple.com).
Working group members are volunteers appointed by the project lead, with a
preference for individuals with varied backgrounds and perspectives. Membership is expected
to change regularly, and may grow or shrink.
The code of conduct for this project can be found at https://swift.org/code-of-conduct.
+115 -13
View File
@@ -1,9 +1,9 @@
// swift-tools-version:5.1
// swift-tools-version:5.7
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2023 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -20,15 +20,42 @@
// Sources/CCryptoBoringSSL directory. The source repository is at
// https://boringssl.googlesource.com/boringssl.
//
// BoringSSL Commit: 67818bea6690a230e2f42e8a588e0f54949bbbf1
// BoringSSL Commit: 7a813621dac6878ab53b6ed7392939a8982226e8
import PackageDescription
let swiftSettings: [SwiftSetting] = [
.define("CRYPTO_IN_SWIFTPM"),
// To develop this on Apple platforms, uncomment this define.
// .define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API"),
]
// To develop this on Apple platforms, set this to true
let development = false
let swiftSettings: [SwiftSetting]
let dependencies: [Target.Dependency]
if development {
swiftSettings = [
.define("CRYPTO_IN_SWIFTPM"),
.define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API"),
]
dependencies = [
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
"CryptoBoringWrapper"
]
} else {
let platforms: [Platform] = [
Platform.linux,
Platform.android,
Platform.windows,
Platform.wasi,
]
swiftSettings = [
.define("CRYPTO_IN_SWIFTPM"),
.define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API", .when(platforms: platforms)),
]
dependencies = [
.target(name: "CCryptoBoringSSL", condition: .when(platforms: platforms)),
.target(name: "CCryptoBoringSSLShims", condition: .when(platforms: platforms)),
.target(name: "CryptoBoringWrapper", condition: .when(platforms: platforms))
]
}
let package = Package(
name: "swift-crypto",
@@ -40,17 +67,92 @@ 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: "CCryptoBoringSSLShims", dependencies: ["CCryptoBoringSSL"]),
.target(name: "Crypto", dependencies: ["CCryptoBoringSSL", "CCryptoBoringSSLShims"], swiftSettings: swiftSettings),
.target(name: "crypto-shasum", dependencies: ["Crypto"]),
.testTarget(name: "CryptoTests", dependencies: ["Crypto"], swiftSettings: swiftSettings),
.target(
name: "CCryptoBoringSSL",
exclude: [
"hash.txt",
"include/boringssl_prefix_symbols_nasm.inc",
"CMakeLists.txt",
/*
* These files are excluded to support WASI libc which doesn't provide <netdb.h>.
* This is safe for all platforms as we do not rely on networking features.
*/
"crypto/bio/connect.c",
"crypto/bio/socket_helper.c",
"crypto/bio/socket.c"
],
cSettings: [
// These defines come from BoringSSL's build system
.define("_HAS_EXCEPTIONS", to: "0", .when(platforms: [Platform.windows])),
.define("WIN32_LEAN_AND_MEAN", .when(platforms: [Platform.windows])),
.define("NOMINMAX", .when(platforms: [Platform.windows])),
.define("_CRT_SECURE_NO_WARNINGS", .when(platforms: [Platform.windows])),
/*
* These defines are required on Wasm/WASI, to disable use of pthread.
*/
.define("OPENSSL_NO_THREADS_CORRUPT_MEMORY_AND_LEAK_SECRETS_IF_THREADED", .when(platforms: [Platform.wasi])),
.define("OPENSSL_NO_ASM", .when(platforms: [Platform.wasi])),
]
),
.target(
name: "CCryptoBoringSSLShims",
dependencies: ["CCryptoBoringSSL"],
exclude: [
"CMakeLists.txt"
]
),
.target(
name: "Crypto",
dependencies: dependencies,
exclude: [
"CMakeLists.txt",
"AEADs/Nonces.swift.gyb",
"Digests/Digests.swift.gyb",
"Key Agreement/ECDH.swift.gyb",
"Signatures/ECDSA.swift.gyb",
],
swiftSettings: swiftSettings
),
.target(
name: "_CryptoExtras",
dependencies: [
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
"CryptoBoringWrapper",
"Crypto"
],
exclude: [
"CMakeLists.txt",
],
swiftSettings: swiftSettings
),
.target(
name: "CryptoBoringWrapper",
dependencies: [
"CCryptoBoringSSL",
"CCryptoBoringSSLShims"
],
exclude: [
"CMakeLists.txt",
]
),
.executableTarget(name: "crypto-shasum", dependencies: ["Crypto"]),
.testTarget(
name: "CryptoTests",
dependencies: ["Crypto"],
resources: [
.copy("HPKE/hpke-test-vectors.json"),
],
swiftSettings: swiftSettings
),
.testTarget(name: "_CryptoExtrasTests", dependencies: ["_CryptoExtras"]),
],
cxxLanguageStandard: .cxx11
)
+30 -2
View File
@@ -2,6 +2,18 @@
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
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.
@@ -96,16 +108,32 @@ If you believe you have identified a vulnerability in Swift Crypto, please [repo
### Swift versions
Swift Crypto supports Swift 5.1 and later.
The most recent versions of Swift Crypto support Swift 5.7 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
Swift Crypto | Minimum Swift Version
------------------|----------------------
`2.0.0 ..< 2.1.0` | 5.2
`2.1.0 ..< 2.2.0` | 5.4
`2.2.0 ..< 2.4.2` | 5.5
`2.4.2 ..< 3.1.0` | 5.6
`3.1.0 ...` | 5.7
### Compatibility
Swift Crypto follows [SemVer 2.0.0](https://semver.org/#semantic-versioning-200). Our public API is the same as that of CryptoKit (except where we lack an implementation entirely), as well as everything in the Server and Staging namespaces. We do not maintain a stable ABI, as Swift Crypto is a source-only distribution.
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 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.
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.
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.
+406
View File
@@ -0,0 +1,406 @@
##===----------------------------------------------------------------------===##
##
## 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_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_strex.c"
"crypto/asn1/a_strnid.c"
"crypto/asn1/a_time.c"
"crypto/asn1/a_type.c"
"crypto/asn1/a_utctm.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/posix_time.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/base64/base64.c"
"crypto/bio/bio.c"
"crypto/bio/bio_mem.c"
"crypto/bio/connect.c"
"crypto/bio/errno.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_aesctrhmac.c"
"crypto/cipher_extra/e_aesgcmsiv.c"
"crypto/cipher_extra/e_chacha20poly1305.c"
"crypto/cipher_extra/e_des.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/conf/conf.c"
"crypto/cpu_aarch64_apple.c"
"crypto/cpu_aarch64_fuchsia.c"
"crypto/cpu_aarch64_linux.c"
"crypto/cpu_aarch64_openbsd.c"
"crypto/cpu_aarch64_sysreg.c"
"crypto/cpu_aarch64_win.c"
"crypto/cpu_arm_freebsd.c"
"crypto/cpu_arm_linux.c"
"crypto/cpu_intel.c"
"crypto/crypto.c"
"crypto/curve25519/curve25519.c"
"crypto/curve25519/curve25519_64_adx.c"
"crypto/curve25519/spake25519.c"
"crypto/des/des.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/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_hkdf.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_aesccm.c"
"crypto/fipsmodule/cmac/cmac.c"
"crypto/fipsmodule/dh/check.c"
"crypto/fipsmodule/dh/dh.c"
"crypto/fipsmodule/digest/digest.c"
"crypto/fipsmodule/digest/digests.c"
"crypto/fipsmodule/digestsign/digestsign.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-nistz.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/hkdf/hkdf.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/service_indicator/service_indicator.c"
"crypto/fipsmodule/sha/sha1.c"
"crypto/fipsmodule/sha/sha256.c"
"crypto/fipsmodule/sha/sha512.c"
"crypto/fipsmodule/tls/kdf.c"
"crypto/hpke/hpke.c"
"crypto/hrss/hrss.c"
"crypto/keccak/keccak.c"
"crypto/kyber/kyber.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/getentropy.c"
"crypto/rand_extra/ios.c"
"crypto/rand_extra/passive.c"
"crypto/rand_extra/rand_extra.c"
"crypto/rand_extra/trusty.c"
"crypto/rand_extra/windows.c"
"crypto/rc4/rc4.c"
"crypto/refcount.c"
"crypto/rsa_extra/rsa_asn1.c"
"crypto/rsa_extra/rsa_crypt.c"
"crypto/rsa_extra/rsa_print.c"
"crypto/siphash/siphash.c"
"crypto/spx/address.c"
"crypto/spx/fors.c"
"crypto/spx/merkle.c"
"crypto/spx/spx.c"
"crypto/spx/spx_util.c"
"crypto/spx/thash.c"
"crypto/spx/wots.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/policy.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/v3_akey.c"
"crypto/x509/v3_akeya.c"
"crypto/x509/v3_alt.c"
"crypto/x509/v3_bcons.c"
"crypto/x509/v3_bitst.c"
"crypto/x509/v3_conf.c"
"crypto/x509/v3_cpols.c"
"crypto/x509/v3_crld.c"
"crypto/x509/v3_enum.c"
"crypto/x509/v3_extku.c"
"crypto/x509/v3_genn.c"
"crypto/x509/v3_ia5.c"
"crypto/x509/v3_info.c"
"crypto/x509/v3_int.c"
"crypto/x509/v3_lib.c"
"crypto/x509/v3_ncons.c"
"crypto/x509/v3_ocsp.c"
"crypto/x509/v3_pcons.c"
"crypto/x509/v3_pmaps.c"
"crypto/x509/v3_prn.c"
"crypto/x509/v3_purp.c"
"crypto/x509/v3_skey.c"
"crypto/x509/v3_utl.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_name.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")
if(CMAKE_SYSTEM_NAME STREQUAL Darwin AND CMAKE_SYSTEM_PROCESSOR MATCHES "amd64|x86_64")
target_sources(CCryptoBoringSSL PRIVATE
crypto/chacha/chacha-x86_64-mac.mac.x86_64.S
crypto/cipher_extra/aes128gcmsiv-x86_64-mac.mac.x86_64.S
crypto/cipher_extra/chacha20_poly1305_x86_64-mac.mac.x86_64.S
crypto/fipsmodule/aesni-gcm-x86_64-mac.mac.x86_64.S
crypto/fipsmodule/aesni-x86_64-mac.mac.x86_64.S
crypto/fipsmodule/ghash-ssse3-x86_64-mac.mac.x86_64.S
crypto/fipsmodule/ghash-x86_64-mac.mac.x86_64.S
crypto/fipsmodule/md5-x86_64-mac.mac.x86_64.S
crypto/fipsmodule/p256-x86_64-asm-mac.mac.x86_64.S
crypto/fipsmodule/p256_beeu-x86_64-asm-mac.mac.x86_64.S
crypto/fipsmodule/rdrand-x86_64-mac.mac.x86_64.S
crypto/fipsmodule/rsaz-avx2-mac.mac.x86_64.S
crypto/fipsmodule/sha1-x86_64-mac.mac.x86_64.S
crypto/fipsmodule/sha256-x86_64-mac.mac.x86_64.S
crypto/fipsmodule/sha512-x86_64-mac.mac.x86_64.S
crypto/fipsmodule/vpaes-x86_64-mac.mac.x86_64.S
crypto/fipsmodule/x86_64-mont-mac.mac.x86_64.S
crypto/fipsmodule/x86_64-mont5-mac.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.linux.x86_64.S
crypto/cipher_extra/aes128gcmsiv-x86_64-linux.linux.x86_64.S
crypto/cipher_extra/chacha20_poly1305_x86_64-linux.linux.x86_64.S
crypto/fipsmodule/aesni-gcm-x86_64-linux.linux.x86_64.S
crypto/fipsmodule/aesni-x86_64-linux.linux.x86_64.S
crypto/fipsmodule/ghash-ssse3-x86_64-linux.linux.x86_64.S
crypto/fipsmodule/ghash-x86_64-linux.linux.x86_64.S
crypto/fipsmodule/md5-x86_64-linux.linux.x86_64.S
crypto/fipsmodule/p256-x86_64-asm-linux.linux.x86_64.S
crypto/fipsmodule/p256_beeu-x86_64-asm-linux.linux.x86_64.S
crypto/fipsmodule/rdrand-x86_64-linux.linux.x86_64.S
crypto/fipsmodule/rsaz-avx2-linux.linux.x86_64.S
crypto/fipsmodule/sha1-x86_64-linux.linux.x86_64.S
crypto/fipsmodule/sha256-x86_64-linux.linux.x86_64.S
crypto/fipsmodule/sha512-x86_64-linux.linux.x86_64.S
crypto/fipsmodule/vpaes-x86_64-linux.linux.x86_64.S
crypto/fipsmodule/x86_64-mont-linux.linux.x86_64.S
crypto/fipsmodule/x86_64-mont5-linux.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.ios.aarch64.S
crypto/cipher_extra/chacha20_poly1305_armv8-ios.ios.aarch64.S
crypto/fipsmodule/aesv8-armv8-ios.ios.aarch64.S
crypto/fipsmodule/aesv8-gcm-armv8-ios.ios.aarch64.S
crypto/fipsmodule/armv8-mont-ios.ios.aarch64.S
crypto/fipsmodule/bn-armv8-ios.ios.aarch64.S
crypto/fipsmodule/ghash-neon-armv8-ios.ios.aarch64.S
crypto/fipsmodule/ghashv8-armv8-ios.ios.aarch64.S
crypto/fipsmodule/p256-armv8-asm-ios.ios.aarch64.S
crypto/fipsmodule/p256_beeu-armv8-asm-ios.ios.aarch64.S
crypto/fipsmodule/sha1-armv8-ios.ios.aarch64.S
crypto/fipsmodule/sha256-armv8-ios.ios.aarch64.S
crypto/fipsmodule/sha512-armv8-ios.ios.aarch64.S
crypto/fipsmodule/vpaes-armv8-ios.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.linux.aarch64.S
crypto/cipher_extra/chacha20_poly1305_armv8-linux.linux.aarch64.S
crypto/fipsmodule/aesv8-armv8-linux.linux.aarch64.S
crypto/fipsmodule/aesv8-gcm-armv8-linux.linux.aarch64.S
crypto/fipsmodule/armv8-mont-linux.linux.aarch64.S
crypto/fipsmodule/bn-armv8-linux.linux.aarch64.S
crypto/fipsmodule/ghash-neon-armv8-linux.linux.aarch64.S
crypto/fipsmodule/ghashv8-armv8-linux.linux.aarch64.S
crypto/fipsmodule/p256-armv8-asm-linux.linux.aarch64.S
crypto/fipsmodule/p256_beeu-armv8-asm-linux.linux.aarch64.S
crypto/fipsmodule/sha1-armv8-linux.linux.aarch64.S
crypto/fipsmodule/sha256-armv8-linux.linux.aarch64.S
crypto/fipsmodule/sha512-armv8-linux.linux.aarch64.S
crypto/fipsmodule/vpaes-armv8-linux.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)
+196 -183
View File
@@ -63,209 +63,222 @@
#include <CCryptoBoringSSL_mem.h>
#include "../internal.h"
#include "internal.h"
int ASN1_BIT_STRING_set(ASN1_BIT_STRING *x, unsigned char *d, int len)
{
return M_ASN1_BIT_STRING_set(x, d, len);
int ASN1_BIT_STRING_set(ASN1_BIT_STRING *x, const unsigned char *d,
ossl_ssize_t len) {
return ASN1_STRING_set(x, d, len);
}
int i2c_ASN1_BIT_STRING(const ASN1_BIT_STRING *a, unsigned char **pp)
{
int ret, j, bits, len;
unsigned char *p, *d;
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;
}
if (a == NULL)
return (0);
// 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) {
uint8_t last = str->data[len - 1];
assert(last != 0);
for (; padding_bits < 7; padding_bits++) {
if (last & (1 << padding_bits)) {
break;
}
}
}
*out_padding_bits = padding_bits;
return len;
}
len = a->length;
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;
}
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;
}
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;
int i2c_ASN1_BIT_STRING(const ASN1_BIT_STRING *a, unsigned char **pp) {
if (a == NULL) {
return 0;
}
ret = 1 + len;
if (pp == NULL)
return (ret);
uint8_t bits;
int len = asn1_bit_string_length(a, &bits);
if (len > INT_MAX - 1) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_OVERFLOW);
return 0;
}
int ret = 1 + len;
if (pp == NULL) {
return ret;
}
p = *pp;
*(p++) = (unsigned char)bits;
d = a->data;
OPENSSL_memcpy(p, d, len);
p += len;
if (len > 0)
p[-1] &= (0xff << bits);
*pp = p;
return (ret);
uint8_t *p = *pp;
*(p++) = bits;
OPENSSL_memcpy(p, a->data, len);
if (len > 0) {
p[len - 1] &= (0xff << bits);
}
p += len;
*pp = p;
return ret;
}
ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a,
const unsigned char **pp, long len)
{
ASN1_BIT_STRING *ret = NULL;
const unsigned char *p;
unsigned char *s;
int padding;
const unsigned char **pp, long len) {
ASN1_BIT_STRING *ret = NULL;
const unsigned char *p;
unsigned char *s;
int padding;
if (len < 1) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_SHORT);
goto err;
if (len < 1) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_SHORT);
goto err;
}
if (len > INT_MAX) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_LONG);
goto err;
}
if ((a == NULL) || ((*a) == NULL)) {
if ((ret = ASN1_BIT_STRING_new()) == NULL) {
return NULL;
}
} else {
ret = (*a);
}
if (len > INT_MAX) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_LONG);
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
ret->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); // clear
ret->flags |= (ASN1_STRING_FLAG_BITS_LEFT | padding); // set
if (len > 0) {
s = OPENSSL_memdup(p, len);
if (s == NULL) {
goto err;
}
p += len;
} else {
s = NULL;
}
if ((a == NULL) || ((*a) == NULL)) {
if ((ret = M_ASN1_BIT_STRING_new()) == NULL)
return (NULL);
} else
ret = (*a);
ret->length = (int)len;
OPENSSL_free(ret->data);
ret->data = s;
ret->type = V_ASN1_BIT_STRING;
if (a != NULL) {
(*a) = ret;
}
*pp = p;
return ret;
err:
if ((ret != NULL) && ((a == NULL) || (*a != ret))) {
ASN1_BIT_STRING_free(ret);
}
return NULL;
}
p = *pp;
padding = *(p++);
if (padding > 7) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);
goto err;
// These next 2 functions from Goetz Babin-Ebell <babinebell@trustcenter.de>
int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value) {
int w, v, iv;
unsigned char *c;
w = n / 8;
v = 1 << (7 - (n & 0x07));
iv = ~v;
if (!value) {
v = 0;
}
if (a == NULL) {
return 0;
}
a->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); // clear, set on write
if ((a->length < (w + 1)) || (a->data == NULL)) {
if (!value) {
return 1; // Don't need to set
}
/*
* We do this to preserve the settings. If we modify the settings, via
* the _set_bit function, we will recalculate on output
*/
ret->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); /* clear */
ret->flags |= (ASN1_STRING_FLAG_BITS_LEFT | padding); /* set */
if (len-- > 1) { /* using one because of the bits left byte */
s = (unsigned char *)OPENSSL_malloc((int)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
s = NULL;
ret->length = (int)len;
if (ret->data != NULL)
OPENSSL_free(ret->data);
ret->data = s;
ret->type = V_ASN1_BIT_STRING;
if (a != NULL)
(*a) = ret;
*pp = p;
return (ret);
err:
if ((ret != NULL) && ((a == NULL) || (*a != ret)))
M_ASN1_BIT_STRING_free(ret);
return (NULL);
}
/*
* These next 2 functions from Goetz Babin-Ebell <babinebell@trustcenter.de>
*/
int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value)
{
int w, v, iv;
unsigned char *c;
w = n / 8;
v = 1 << (7 - (n & 0x07));
iv = ~v;
if (!value)
v = 0;
if (a == NULL)
return 0;
a->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); /* clear, set on write */
if ((a->length < (w + 1)) || (a->data == NULL)) {
if (!value)
return (1); /* Don't need to set */
if (a->data == NULL)
c = (unsigned char *)OPENSSL_malloc(w + 1);
else
c = (unsigned char *)OPENSSL_realloc(a->data, w + 1);
if (c == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return 0;
}
if (w + 1 - a->length > 0)
OPENSSL_memset(c + a->length, 0, w + 1 - a->length);
a->data = c;
a->length = w + 1;
if (a->data == NULL) {
c = (unsigned char *)OPENSSL_malloc(w + 1);
} else {
c = (unsigned char *)OPENSSL_realloc(a->data, w + 1);
}
a->data[w] = ((a->data[w]) & iv) | v;
while ((a->length > 0) && (a->data[a->length - 1] == 0))
a->length--;
return (1);
}
int ASN1_BIT_STRING_get_bit(const ASN1_BIT_STRING *a, int n)
{
int w, v;
w = n / 8;
v = 1 << (7 - (n & 0x07));
if ((a == NULL) || (a->length < (w + 1)) || (a->data == NULL))
return (0);
return ((a->data[w] & v) != 0);
}
/*
* Checks if the given bit string contains only bits specified by
* the flags vector. Returns 0 if there is at least one bit set in 'a'
* which is not specified in 'flags', 1 otherwise.
* 'len' is the length of 'flags'.
*/
int ASN1_BIT_STRING_check(const ASN1_BIT_STRING *a,
unsigned char *flags, int flags_len)
{
int i, ok;
/* Check if there is one bit set at all. */
if (!a || !a->data)
return 1;
/*
* Check each byte of the internal representation of the bit string.
*/
ok = 1;
for (i = 0; i < a->length && ok; ++i) {
unsigned char mask = i < flags_len ? ~flags[i] : 0xff;
/* We are done if there is an unneeded bit set. */
ok = (a->data[i] & mask) == 0;
if (c == NULL) {
return 0;
}
return ok;
if (w + 1 - a->length > 0) {
OPENSSL_memset(c + a->length, 0, w + 1 - a->length);
}
a->data = c;
a->length = w + 1;
}
a->data[w] = ((a->data[w]) & iv) | v;
while ((a->length > 0) && (a->data[a->length - 1] == 0)) {
a->length--;
}
return 1;
}
int ASN1_BIT_STRING_get_bit(const ASN1_BIT_STRING *a, int n) {
int w, v;
w = n / 8;
v = 1 << (7 - (n & 0x07));
if ((a == NULL) || (a->length < (w + 1)) || (a->data == NULL)) {
return 0;
}
return ((a->data[w] & v) != 0);
}
// Checks if the given bit string contains only bits specified by
// the flags vector. Returns 0 if there is at least one bit set in 'a'
// which is not specified in 'flags', 1 otherwise.
// 'len' is the length of 'flags'.
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.
if (!a || !a->data) {
return 1;
}
// Check each byte of the internal representation of the bit string.
ok = 1;
for (i = 0; i < a->length && ok; ++i) {
unsigned char mask = i < flags_len ? ~flags[i] : 0xff;
// We are done if there is an unneeded bit set.
ok = (a->data[i] & mask) == 0;
}
return ok;
}
+28 -56
View File
@@ -56,68 +56,40 @@
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
int i2d_ASN1_BOOLEAN(int a, unsigned char **pp)
{
int r;
unsigned char *p, *allocated = NULL;
#include "../bytestring/internal.h"
r = ASN1_object_size(0, 1, V_ASN1_BOOLEAN);
if (pp == NULL)
return (r);
if (*pp == NULL) {
if ((p = allocated = OPENSSL_malloc(r)) == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return 0;
}
} else {
p = *pp;
}
ASN1_put_object(&p, 0, 1, V_ASN1_BOOLEAN, V_ASN1_UNIVERSAL);
*p = (unsigned char)a;
/*
* If a new buffer was allocated, just return it back.
* If not, return the incremented buffer pointer.
*/
*pp = allocated != NULL ? allocated : p + 1;
return r;
int i2d_ASN1_BOOLEAN(ASN1_BOOLEAN a, unsigned char **outp) {
CBB cbb;
if (!CBB_init(&cbb, 3) || //
!CBB_add_asn1_bool(&cbb, a != ASN1_BOOLEAN_FALSE)) {
CBB_cleanup(&cbb);
return -1;
}
return CBB_finish_i2d(&cbb, outp);
}
int d2i_ASN1_BOOLEAN(int *a, const unsigned char **pp, long length)
{
int ret = -1;
const unsigned char *p;
long len;
int inf, tag, xclass;
int i = 0;
ASN1_BOOLEAN d2i_ASN1_BOOLEAN(ASN1_BOOLEAN *out, const unsigned char **inp,
long len) {
if (len < 0) {
return ASN1_BOOLEAN_NONE;
}
p = *pp;
inf = ASN1_get_object(&p, &len, &tag, &xclass, length);
if (inf & 0x80) {
i = ASN1_R_BAD_OBJECT_HEADER;
goto err;
}
CBS cbs;
CBS_init(&cbs, *inp, (size_t)len);
int val;
if (!CBS_get_asn1_bool(&cbs, &val)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return ASN1_BOOLEAN_NONE;
}
if (tag != V_ASN1_BOOLEAN) {
i = ASN1_R_EXPECTING_A_BOOLEAN;
goto err;
}
if (len != 1) {
i = ASN1_R_BOOLEAN_IS_WRONG_LENGTH;
goto err;
}
ret = (int)*(p++);
if (a != NULL)
(*a) = ret;
*pp = p;
return (ret);
err:
OPENSSL_PUT_ERROR(ASN1, i);
return (ret);
ASN1_BOOLEAN ret = val ? ASN1_BOOLEAN_TRUE : ASN1_BOOLEAN_FALSE;
if (out != NULL) {
*out = ret;
}
*inp = CBS_data(&cbs);
return ret;
}
+21 -25
View File
@@ -63,31 +63,27 @@
#include <CCryptoBoringSSL_mem.h>
void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *x)
{
uint8_t *data;
size_t len;
// Historically, this function did not impose a limit in OpenSSL and is used
// to read CRLs, so we leave this without an external bound.
if (!BIO_read_asn1(in, &data, &len, INT_MAX)) {
return NULL;
}
const uint8_t *ptr = data;
void *ret = ASN1_item_d2i(x, &ptr, len, it);
OPENSSL_free(data);
return ret;
void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *x) {
uint8_t *data;
size_t len;
// Historically, this function did not impose a limit in OpenSSL and is used
// to read CRLs, so we leave this without an external bound.
if (!BIO_read_asn1(in, &data, &len, INT_MAX)) {
return NULL;
}
const uint8_t *ptr = data;
void *ret = ASN1_item_d2i(x, &ptr, len, it);
OPENSSL_free(data);
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);
if (b == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_BUF_LIB);
return NULL;
}
void *ret = ASN1_item_d2i_bio(it, b, x);
BIO_free(b);
return ret;
void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x) {
BIO *b = BIO_new_fp(in, BIO_NOCLOSE);
if (b == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_BUF_LIB);
return NULL;
}
void *ret = ASN1_item_d2i_bio(it, b, x);
BIO_free(b);
return ret;
}
#endif
+20 -23
View File
@@ -59,29 +59,26 @@
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
/*
* ASN1_ITEM version of dup: this follows the model above except we don't
* need to allocate the buffer. At some point this could be rewritten to
* directly dup the underlying structure instead of doing and encode and
* decode.
*/
void *ASN1_item_dup(const ASN1_ITEM *it, void *x)
{
unsigned char *b = NULL;
const unsigned char *p;
long i;
void *ret;
// ASN1_ITEM version of dup: this follows the model above except we don't
// need to allocate the buffer. At some point this could be rewritten to
// directly dup the underlying structure instead of doing and encode and
// decode.
void *ASN1_item_dup(const ASN1_ITEM *it, void *x) {
unsigned char *b = NULL;
const unsigned char *p;
long i;
void *ret;
if (x == NULL)
return (NULL);
if (x == NULL) {
return NULL;
}
i = ASN1_item_i2d(x, &b, it);
if (b == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return (NULL);
}
p = b;
ret = ASN1_item_d2i(NULL, &p, i, it);
OPENSSL_free(b);
return (ret);
i = ASN1_item_i2d(x, &b, it);
if (b == NULL) {
return NULL;
}
p = b;
ret = ASN1_item_d2i(NULL, &p, i, it);
OPENSSL_free(b);
return ret;
}
@@ -1,195 +0,0 @@
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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 acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS 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 AUTHOR OR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.] */
#include <CCryptoBoringSSL_asn1.h>
#include <limits.h>
#include <string.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include "../internal.h"
/*
* Code for ENUMERATED type: identical to INTEGER apart from a different tag.
* for comments on encoding see a_int.c
*/
int ASN1_ENUMERATED_set(ASN1_ENUMERATED *a, long v)
{
int j, k;
unsigned int i;
unsigned char buf[sizeof(long) + 1];
long d;
a->type = V_ASN1_ENUMERATED;
if (a->length < (int)(sizeof(long) + 1)) {
if (a->data != NULL)
OPENSSL_free(a->data);
if ((a->data =
(unsigned char *)OPENSSL_malloc(sizeof(long) + 1)) != NULL)
OPENSSL_memset((char *)a->data, 0, sizeof(long) + 1);
}
if (a->data == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return (0);
}
d = v;
if (d < 0) {
d = -d;
a->type = V_ASN1_NEG_ENUMERATED;
}
for (i = 0; i < sizeof(long); i++) {
if (d == 0)
break;
buf[i] = (int)d & 0xff;
d >>= 8;
}
j = 0;
for (k = i - 1; k >= 0; k--)
a->data[j++] = buf[k];
a->length = j;
return (1);
}
long ASN1_ENUMERATED_get(const ASN1_ENUMERATED *a)
{
int neg = 0, i;
if (a == NULL)
return (0L);
i = a->type;
if (i == V_ASN1_NEG_ENUMERATED)
neg = 1;
else if (i != V_ASN1_ENUMERATED)
return -1;
OPENSSL_STATIC_ASSERT(sizeof(uint64_t) >= sizeof(long),
"long larger than uint64_t");
if (a->length > (int)sizeof(uint64_t)) {
/* hmm... a bit ugly */
return -1;
}
uint64_t r64 = 0;
if (a->data != NULL) {
for (i = 0; i < a->length; i++) {
r64 <<= 8;
r64 |= (unsigned char)a->data[i];
}
if (r64 > LONG_MAX) {
return -1;
}
}
long r = (long) r64;
if (neg)
r = -r;
return r;
}
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();
else
ret = ai;
if (ret == NULL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
goto err;
}
if (BN_is_negative(bn))
ret->type = V_ASN1_NEG_ENUMERATED;
else
ret->type = V_ASN1_ENUMERATED;
j = BN_num_bits(bn);
len = ((j == 0) ? 0 : ((j / 8) + 1));
if (ret->length < len + 4) {
unsigned char *new_data = OPENSSL_realloc(ret->data, len + 4);
if (!new_data) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
ret->data = new_data;
}
ret->length = BN_bn2bin(bn, ret->data);
return (ret);
err:
if (ret != ai)
M_ASN1_ENUMERATED_free(ret);
return (NULL);
}
BIGNUM *ASN1_ENUMERATED_to_BN(const ASN1_ENUMERATED *ai, BIGNUM *bn)
{
BIGNUM *ret;
if ((ret = BN_bin2bn(ai->data, ai->length, bn)) == NULL)
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BN_LIB);
else if (ai->type == V_ASN1_NEG_ENUMERATED)
BN_set_negative(ret, 1);
return (ret);
}
+77 -187
View File
@@ -55,207 +55,97 @@
* [including the GNU Public Licence.] */
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_time.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include "internal.h"
#include "asn1_locl.h"
int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d)
{
static const int min[9] = { 0, 0, 1, 1, 0, 0, 0, 0, 0 };
static const int max[9] = { 99, 99, 12, 31, 23, 59, 59, 12, 59 };
char *a;
int n, i, l, o;
if (d->type != V_ASN1_GENERALIZEDTIME)
return (0);
l = d->length;
a = (char *)d->data;
o = 0;
/*
* GENERALIZEDTIME is similar to UTCTIME except the year is represented
* as YYYY. This stuff treats everything as a two digit field so make
* first two fields 00 to 99
*/
if (l < 13)
goto err;
for (i = 0; i < 7; i++) {
if ((i == 6) && ((a[o] == 'Z') || (a[o] == '+') || (a[o] == '-'))) {
i++;
if (tm)
tm->tm_sec = 0;
break;
}
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = a[o] - '0';
if (++o > l)
goto err;
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = (n * 10) + a[o] - '0';
if (++o > l)
goto err;
if ((n < min[i]) || (n > max[i]))
goto err;
if (tm) {
switch (i) {
case 0:
tm->tm_year = n * 100 - 1900;
break;
case 1:
tm->tm_year += n;
break;
case 2:
tm->tm_mon = n - 1;
break;
case 3:
tm->tm_mday = n;
break;
case 4:
tm->tm_hour = n;
break;
case 5:
tm->tm_min = n;
break;
case 6:
tm->tm_sec = n;
break;
}
}
}
/*
* Optional fractional seconds: decimal point followed by one or more
* digits.
*/
if (a[o] == '.') {
if (++o > l)
goto err;
i = o;
while ((a[o] >= '0') && (a[o] <= '9') && (o <= l))
o++;
/* Must have at least one digit after decimal point */
if (i == o)
goto err;
}
if (a[o] == 'Z')
o++;
else if ((a[o] == '+') || (a[o] == '-')) {
int offsign = a[o] == '-' ? 1 : -1, offset = 0;
o++;
if (o + 4 > l)
goto err;
for (i = 7; i < 9; i++) {
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = a[o] - '0';
o++;
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = (n * 10) + a[o] - '0';
if ((n < min[i]) || (n > max[i]))
goto err;
if (tm) {
if (i == 7)
offset = n * 3600;
else if (i == 8)
offset += n * 60;
}
o++;
}
if (offset && !OPENSSL_gmtime_adj(tm, 0, offset * offsign))
return 0;
} else if (a[o]) {
/* Missing time zone information. */
goto err;
}
return (o == l);
err:
return (0);
int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d) {
if (d->type != V_ASN1_GENERALIZEDTIME) {
return 0;
}
CBS cbs;
CBS_init(&cbs, d->data, (size_t)d->length);
if (!CBS_parse_generalized_time(&cbs, tm, /*allow_timezone_offset=*/0)) {
return 0;
}
return 1;
}
int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *d)
{
return asn1_generalizedtime_to_tm(NULL, d);
int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *d) {
return asn1_generalizedtime_to_tm(NULL, d);
}
int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str)
{
ASN1_GENERALIZEDTIME t;
t.type = V_ASN1_GENERALIZEDTIME;
t.length = strlen(str);
t.data = (unsigned char *)str;
if (ASN1_GENERALIZEDTIME_check(&t)) {
if (s != NULL) {
if (!ASN1_STRING_set((ASN1_STRING *)s,
(unsigned char *)str, t.length))
return 0;
s->type = V_ASN1_GENERALIZEDTIME;
}
return (1);
} else
return (0);
int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str) {
size_t len = strlen(str);
CBS cbs;
CBS_init(&cbs, (const uint8_t *)str, len);
if (!CBS_parse_generalized_time(&cbs, /*out_tm=*/NULL,
/*allow_timezone_offset=*/0)) {
return 0;
}
if (s != NULL) {
if (!ASN1_STRING_set(s, str, len)) {
return 0;
}
s->type = V_ASN1_GENERALIZEDTIME;
}
return 1;
}
ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_set(ASN1_GENERALIZEDTIME *s,
time_t t)
{
return ASN1_GENERALIZEDTIME_adj(s, t, 0, 0);
int64_t posix_time) {
return ASN1_GENERALIZEDTIME_adj(s, posix_time, 0, 0);
}
ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s,
time_t t, int offset_day,
long offset_sec)
{
char *p;
struct tm *ts;
struct tm data;
size_t len = 20;
ASN1_GENERALIZEDTIME *tmps = NULL;
if (s == NULL)
tmps = ASN1_GENERALIZEDTIME_new();
else
tmps = s;
if (tmps == NULL)
return NULL;
ts = OPENSSL_gmtime(&t, &data);
if (ts == NULL)
goto err;
if (offset_day || offset_sec) {
if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
goto err;
}
p = (char *)tmps->data;
if ((p == NULL) || ((size_t)tmps->length < len)) {
p = OPENSSL_malloc(len);
if (p == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
OPENSSL_free(tmps->data);
tmps->data = (unsigned char *)p;
}
BIO_snprintf(p, len, "%04d%02d%02d%02d%02d%02dZ", ts->tm_year + 1900,
ts->tm_mon + 1, ts->tm_mday, ts->tm_hour, ts->tm_min,
ts->tm_sec);
tmps->length = strlen(p);
tmps->type = V_ASN1_GENERALIZEDTIME;
return tmps;
err:
if (s == NULL)
ASN1_GENERALIZEDTIME_free(tmps);
int64_t posix_time, int offset_day,
long offset_sec) {
struct tm data;
if (!OPENSSL_posix_to_tm(posix_time, &data)) {
return NULL;
}
if (offset_day || offset_sec) {
if (!OPENSSL_gmtime_adj(&data, offset_day, offset_sec)) {
return NULL;
}
}
if (data.tm_year < 0 - 1900 || data.tm_year > 9999 - 1900) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_TIME_VALUE);
return NULL;
}
char buf[16];
int ret = snprintf(buf, sizeof(buf), "%04d%02d%02d%02d%02d%02dZ",
data.tm_year + 1900, data.tm_mon + 1, data.tm_mday,
data.tm_hour, data.tm_min, data.tm_sec);
if (ret != (int)(sizeof(buf) - 1)) {
abort(); // |snprintf| should neither truncate nor write fewer bytes.
}
int free_s = 0;
if (s == NULL) {
free_s = 1;
s = ASN1_UTCTIME_new();
if (s == NULL) {
return NULL;
}
}
if (!ASN1_STRING_set(s, buf, strlen(buf))) {
if (free_s) {
ASN1_UTCTIME_free(s);
}
return NULL;
}
s->type = V_ASN1_GENERALIZEDTIME;
return s;
}
+18 -21
View File
@@ -61,28 +61,25 @@
#include <CCryptoBoringSSL_mem.h>
int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, void *x)
{
BIO *b = BIO_new_fp(out, BIO_NOCLOSE);
if (b == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_BUF_LIB);
return 0;
}
int ret = ASN1_item_i2d_bio(it, b, x);
BIO_free(b);
return ret;
int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, void *x) {
BIO *b = BIO_new_fp(out, BIO_NOCLOSE);
if (b == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_BUF_LIB);
return 0;
}
int ret = ASN1_item_i2d_bio(it, b, x);
BIO_free(b);
return ret;
}
int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, void *x)
{
unsigned char *b = NULL;
int n = ASN1_item_i2d(x, &b, it);
if (b == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return 0;
}
int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, void *x) {
unsigned char *b = NULL;
int n = ASN1_item_i2d(x, &b, it);
if (b == NULL) {
return 0;
}
int ret = BIO_write_all(out, b, n);
OPENSSL_free(b);
return ret;
int ret = BIO_write_all(out, b, n);
OPENSSL_free(b);
return ret;
}
+371 -326
View File
@@ -56,365 +56,410 @@
#include <CCryptoBoringSSL_asn1.h>
#include <string.h>
#include <assert.h>
#include <limits.h>
#include <string.h>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include "../internal.h"
ASN1_INTEGER *ASN1_INTEGER_dup(const ASN1_INTEGER *x)
{
return M_ASN1_INTEGER_dup(x);
ASN1_INTEGER *ASN1_INTEGER_dup(const ASN1_INTEGER *x) {
return ASN1_STRING_dup(x);
}
int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y)
{
int neg, ret;
/* Compare signs */
neg = x->type & V_ASN1_NEG;
if (neg != (y->type & V_ASN1_NEG)) {
if (neg)
return -1;
else
return 1;
}
int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y) {
// Compare signs.
int neg = x->type & V_ASN1_NEG;
if (neg != (y->type & V_ASN1_NEG)) {
return neg ? -1 : 1;
}
ret = ASN1_STRING_cmp(x, y);
if (neg)
return -ret;
else
return ret;
}
/*
* This converts an ASN1 INTEGER into its content encoding.
* The internal representation is an ASN1_STRING whose data is a big endian
* representation of the value, ignoring the sign. The sign is determined by
* the type: V_ASN1_INTEGER for positive and V_ASN1_NEG_INTEGER for negative.
*
* Positive integers are no problem: they are almost the same as the DER
* encoding, except if the first byte is >= 0x80 we need to add a zero pad.
*
* Negative integers are a bit trickier...
* The DER representation of negative integers is in 2s complement form.
* The internal form is converted by complementing each octet and finally
* adding one to the result. This can be done less messily with a little trick.
* If the internal form has trailing zeroes then they will become FF by the
* complement and 0 by the add one (due to carry) so just copy as many trailing
* zeros to the destination as there are in the source. The carry will add one
* to the last none zero octet: so complement this octet and add one and finally
* complement any left over until you get to the start of the string.
*
* Padding is a little trickier too. If the first bytes is > 0x80 then we pad
* with 0xff. However if the first byte is 0x80 and one of the following bytes
* is non-zero we pad with 0xff. The reason for this distinction is that 0x80
* followed by optional zeros isn't padded.
*/
int i2c_ASN1_INTEGER(const ASN1_INTEGER *a, unsigned char **pp)
{
int pad = 0, ret, i, neg;
unsigned char *p, *n, pb = 0;
if (a == NULL)
return (0);
neg = a->type & V_ASN1_NEG;
if (a->length == 0)
ret = 1;
else {
ret = a->length;
i = a->data[0];
if (ret == 1 && i == 0)
neg = 0;
if (!neg && (i > 127)) {
pad = 1;
pb = 0;
} else if (neg) {
if (i > 128) {
pad = 1;
pb = 0xFF;
} else if (i == 128) {
/*
* Special case: if any other bytes non zero we pad:
* otherwise we don't.
*/
for (i = 1; i < a->length; i++)
if (a->data[i]) {
pad = 1;
pb = 0xFF;
break;
}
}
}
ret += pad;
}
if (pp == NULL)
return (ret);
p = *pp;
if (pad)
*(p++) = pb;
if (a->length == 0)
*(p++) = 0;
else if (!neg)
OPENSSL_memcpy(p, a->data, (unsigned int)a->length);
else {
/* Begin at the end of the encoding */
n = a->data + a->length - 1;
p += a->length - 1;
i = a->length;
/* Copy zeros to destination as long as source is zero */
while (!*n && i > 1) {
*(p--) = 0;
n--;
i--;
}
/* Complement and increment next octet */
*(p--) = ((*(n--)) ^ 0xff) + 1;
i--;
/* Complement any octets left */
for (; i > 0; i--)
*(p--) = *(n--) ^ 0xff;
}
*pp += ret;
return (ret);
}
/* Convert just ASN1 INTEGER content octets to ASN1_INTEGER structure */
ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp,
long len)
{
ASN1_INTEGER *ret = NULL;
const unsigned char *p, *pend;
unsigned char *to, *s;
int i;
/*
* This function can handle lengths up to INT_MAX - 1, but the rest of the
* legacy ASN.1 code mixes integer types, so avoid exposing it to
* ASN1_INTEGERS with larger lengths.
*/
if (len < 0 || len > INT_MAX / 2) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_TOO_LONG);
return NULL;
}
if ((a == NULL) || ((*a) == NULL)) {
if ((ret = M_ASN1_INTEGER_new()) == NULL)
return (NULL);
ret->type = V_ASN1_INTEGER;
} else
ret = (*a);
p = *pp;
pend = p + len;
/*
* We must OPENSSL_malloc stuff, even for 0 bytes otherwise it signifies
* a missing NULL parameter.
*/
s = (unsigned char *)OPENSSL_malloc((int)len + 1);
if (s == NULL) {
i = ERR_R_MALLOC_FAILURE;
goto err;
}
to = s;
if (!len) {
/*
* Strictly speaking this is an illegal INTEGER but we tolerate it.
*/
ret->type = V_ASN1_INTEGER;
} else if (*p & 0x80) { /* a negative number */
ret->type = V_ASN1_NEG_INTEGER;
if ((*p == 0xff) && (len != 1)) {
p++;
len--;
}
i = len;
p += i - 1;
to += i - 1;
while ((!*p) && i) {
*(to--) = 0;
i--;
p--;
}
/*
* Special case: if all zeros then the number will be of the form FF
* followed by n zero bytes: this corresponds to 1 followed by n zero
* bytes. We've already written n zeros so we just append an extra
* one and set the first byte to a 1. This is treated separately
* because it is the only case where the number of bytes is larger
* than len.
*/
if (!i) {
*s = 1;
s[len] = 0;
len++;
} else {
*(to--) = (*(p--) ^ 0xff) + 1;
i--;
for (; i > 0; i--)
*(to--) = *(p--) ^ 0xff;
}
int ret = ASN1_STRING_cmp(x, y);
if (neg) {
// This could be |-ret|, but |ASN1_STRING_cmp| is not forbidden from
// returning |INT_MIN|.
if (ret < 0) {
return 1;
} else if (ret > 0) {
return -1;
} else {
ret->type = V_ASN1_INTEGER;
if ((*p == 0) && (len != 1)) {
p++;
len--;
}
OPENSSL_memcpy(s, p, (int)len);
return 0;
}
}
if (ret->data != NULL)
OPENSSL_free(ret->data);
ret->data = s;
ret->length = (int)len;
if (a != NULL)
(*a) = ret;
*pp = pend;
return (ret);
err:
OPENSSL_PUT_ERROR(ASN1, i);
if ((ret != NULL) && ((a == NULL) || (*a != ret)))
M_ASN1_INTEGER_free(ret);
return (NULL);
return ret;
}
int ASN1_INTEGER_set(ASN1_INTEGER *a, long v)
{
if (v >= 0) {
return ASN1_INTEGER_set_uint64(a, (uint64_t) v);
}
if (!ASN1_INTEGER_set_uint64(a, 0 - (uint64_t) v)) {
return 0;
}
a->type = V_ASN1_NEG_INTEGER;
return 1;
// negate_twos_complement negates |len| bytes from |buf| in-place, interpreted
// as a signed, big-endian two's complement value.
static void negate_twos_complement(uint8_t *buf, size_t len) {
uint8_t borrow = 0;
for (size_t i = len - 1; i < len; i--) {
uint8_t t = buf[i];
buf[i] = 0u - borrow - t;
borrow |= t != 0;
}
}
int ASN1_INTEGER_set_uint64(ASN1_INTEGER *out, uint64_t v)
{
uint8_t *const newdata = OPENSSL_malloc(sizeof(uint64_t));
if (newdata == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return 0;
static int is_all_zeros(const uint8_t *in, size_t len) {
for (size_t i = 0; i < len; i++) {
if (in[i] != 0) {
return 0;
}
OPENSSL_free(out->data);
out->data = newdata;
v = CRYPTO_bswap8(v);
memcpy(out->data, &v, sizeof(v));
out->type = V_ASN1_INTEGER;
size_t leading_zeros;
for (leading_zeros = 0; leading_zeros < sizeof(uint64_t) - 1;
leading_zeros++) {
if (out->data[leading_zeros] != 0) {
break;
}
}
out->length = sizeof(uint64_t) - leading_zeros;
OPENSSL_memmove(out->data, out->data + leading_zeros, out->length);
return 1;
}
return 1;
}
long ASN1_INTEGER_get(const ASN1_INTEGER *a)
{
int neg = 0, i;
int i2c_ASN1_INTEGER(const ASN1_INTEGER *in, unsigned char **outp) {
if (in == NULL) {
return 0;
}
if (a == NULL)
return (0L);
i = a->type;
if (i == V_ASN1_NEG_INTEGER)
neg = 1;
else if (i != V_ASN1_INTEGER)
return -1;
// |ASN1_INTEGER|s should be represented minimally, but it is possible to
// construct invalid ones. Skip leading zeros so this does not produce an
// invalid encoding or break invariants.
CBS cbs;
CBS_init(&cbs, in->data, in->length);
while (CBS_len(&cbs) > 0 && CBS_data(&cbs)[0] == 0) {
CBS_skip(&cbs, 1);
}
OPENSSL_STATIC_ASSERT(sizeof(uint64_t) >= sizeof(long),
"long larger than uint64_t");
int is_negative = (in->type & V_ASN1_NEG) != 0;
size_t pad;
CBS copy = cbs;
uint8_t msb;
if (!CBS_get_u8(&copy, &msb)) {
// Zero is represented as a single byte.
is_negative = 0;
pad = 1;
} else if (is_negative) {
// 0x80...01 through 0xff...ff have a two's complement of 0x7f...ff
// through 0x00...01 and need an extra byte to be negative.
// 0x01...00 through 0x80...00 have a two's complement of 0xfe...ff
// through 0x80...00 and can be negated as-is.
pad = msb > 0x80 ||
(msb == 0x80 && !is_all_zeros(CBS_data(&copy), CBS_len(&copy)));
} else {
// If the high bit is set, the signed representation needs an extra
// byte to be positive.
pad = (msb & 0x80) != 0;
}
if (a->length > (int)sizeof(uint64_t)) {
/* hmm... a bit ugly, return all ones */
return -1;
}
if (CBS_len(&cbs) > INT_MAX - pad) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_OVERFLOW);
return 0;
}
int len = (int)(pad + CBS_len(&cbs));
assert(len > 0);
if (outp == NULL) {
return len;
}
uint64_t r64 = 0;
if (a->data != NULL) {
for (i = 0; i < a->length; i++) {
r64 <<= 8;
r64 |= (unsigned char)a->data[i];
}
if (r64 > LONG_MAX) {
return -1;
}
}
long r = (long) r64;
if (neg)
r = -r;
return r;
if (pad) {
(*outp)[0] = 0;
}
OPENSSL_memcpy(*outp + pad, CBS_data(&cbs), CBS_len(&cbs));
if (is_negative) {
negate_twos_complement(*outp, len);
assert((*outp)[0] >= 0x80);
} else {
assert((*outp)[0] < 0x80);
}
*outp += len;
return len;
}
ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai)
{
ASN1_INTEGER *ret;
int len, j;
ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **out, const unsigned char **inp,
long len) {
// This function can handle lengths up to INT_MAX - 1, but the rest of the
// legacy ASN.1 code mixes integer types, so avoid exposing it to
// ASN1_INTEGERS with larger lengths.
if (len < 0 || len > INT_MAX / 2) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_TOO_LONG);
return NULL;
}
if (ai == NULL)
ret = M_ASN1_INTEGER_new();
else
ret = ai;
CBS cbs;
CBS_init(&cbs, *inp, (size_t)len);
int is_negative;
if (!CBS_is_valid_asn1_integer(&cbs, &is_negative)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_INTEGER);
return NULL;
}
ASN1_INTEGER *ret = NULL;
if (out == NULL || *out == NULL) {
ret = ASN1_INTEGER_new();
if (ret == NULL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
goto err;
return NULL;
}
if (BN_is_negative(bn) && !BN_is_zero(bn))
ret->type = V_ASN1_NEG_INTEGER;
else
ret->type = V_ASN1_INTEGER;
j = BN_num_bits(bn);
len = ((j == 0) ? 0 : ((j / 8) + 1));
if (ret->length < len + 4) {
unsigned char *new_data = OPENSSL_realloc(ret->data, len + 4);
if (!new_data) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
ret->data = new_data;
} else {
ret = *out;
}
// Convert to |ASN1_INTEGER|'s sign-and-magnitude representation. First,
// determine the size needed for a minimal result.
if (is_negative) {
// 0xff00...01 through 0xff7f..ff have a two's complement of 0x00ff...ff
// through 0x000100...001 and need one leading zero removed. 0x8000...00
// through 0xff00...00 have a two's complement of 0x8000...00 through
// 0x0100...00 and will be minimally-encoded as-is.
if (CBS_len(&cbs) > 0 && CBS_data(&cbs)[0] == 0xff &&
!is_all_zeros(CBS_data(&cbs) + 1, CBS_len(&cbs) - 1)) {
CBS_skip(&cbs, 1);
}
ret->length = BN_bn2bin(bn, ret->data);
/* Correct zero case */
if (!ret->length) {
ret->data[0] = 0;
ret->length = 1;
} else {
// Remove the leading zero byte, if any.
if (CBS_len(&cbs) > 0 && CBS_data(&cbs)[0] == 0x00) {
CBS_skip(&cbs, 1);
}
return (ret);
err:
if (ret != ai)
M_ASN1_INTEGER_free(ret);
return (NULL);
}
if (!ASN1_STRING_set(ret, CBS_data(&cbs), CBS_len(&cbs))) {
goto err;
}
if (is_negative) {
ret->type = V_ASN1_NEG_INTEGER;
negate_twos_complement(ret->data, ret->length);
} else {
ret->type = V_ASN1_INTEGER;
}
// The value should be minimally-encoded.
assert(ret->length == 0 || ret->data[0] != 0);
// Zero is not negative.
assert(!is_negative || ret->length > 0);
*inp += len;
if (out != NULL) {
*out = ret;
}
return ret;
err:
if (ret != NULL && (out == NULL || *out != ret)) {
ASN1_INTEGER_free(ret);
}
return NULL;
}
BIGNUM *ASN1_INTEGER_to_BN(const ASN1_INTEGER *ai, BIGNUM *bn)
{
BIGNUM *ret;
int ASN1_INTEGER_set_int64(ASN1_INTEGER *a, int64_t v) {
if (v >= 0) {
return ASN1_INTEGER_set_uint64(a, (uint64_t)v);
}
if ((ret = BN_bin2bn(ai->data, ai->length, bn)) == NULL)
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BN_LIB);
else if (ai->type == V_ASN1_NEG_INTEGER)
BN_set_negative(ret, 1);
return (ret);
if (!ASN1_INTEGER_set_uint64(a, 0 - (uint64_t)v)) {
return 0;
}
a->type = V_ASN1_NEG_INTEGER;
return 1;
}
int ASN1_ENUMERATED_set_int64(ASN1_ENUMERATED *a, int64_t v) {
if (v >= 0) {
return ASN1_ENUMERATED_set_uint64(a, (uint64_t)v);
}
if (!ASN1_ENUMERATED_set_uint64(a, 0 - (uint64_t)v)) {
return 0;
}
a->type = V_ASN1_NEG_ENUMERATED;
return 1;
}
int ASN1_INTEGER_set(ASN1_INTEGER *a, long v) {
static_assert(sizeof(long) <= sizeof(int64_t), "long fits in int64_t");
return ASN1_INTEGER_set_int64(a, v);
}
int ASN1_ENUMERATED_set(ASN1_ENUMERATED *a, long v) {
static_assert(sizeof(long) <= sizeof(int64_t), "long fits in int64_t");
return ASN1_ENUMERATED_set_int64(a, v);
}
static int asn1_string_set_uint64(ASN1_STRING *out, uint64_t v, int type) {
uint8_t buf[sizeof(uint64_t)];
CRYPTO_store_u64_be(buf, v);
size_t leading_zeros;
for (leading_zeros = 0; leading_zeros < sizeof(buf); leading_zeros++) {
if (buf[leading_zeros] != 0) {
break;
}
}
if (!ASN1_STRING_set(out, buf + leading_zeros, sizeof(buf) - leading_zeros)) {
return 0;
}
out->type = type;
return 1;
}
int ASN1_INTEGER_set_uint64(ASN1_INTEGER *out, uint64_t v) {
return asn1_string_set_uint64(out, v, V_ASN1_INTEGER);
}
int ASN1_ENUMERATED_set_uint64(ASN1_ENUMERATED *out, uint64_t v) {
return asn1_string_set_uint64(out, v, V_ASN1_ENUMERATED);
}
static int asn1_string_get_abs_uint64(uint64_t *out, const ASN1_STRING *a,
int type) {
if ((a->type & ~V_ASN1_NEG) != type) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_INTEGER_TYPE);
return 0;
}
uint8_t buf[sizeof(uint64_t)] = {0};
if (a->length > (int)sizeof(buf)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_INTEGER);
return 0;
}
OPENSSL_memcpy(buf + sizeof(buf) - a->length, a->data, a->length);
*out = CRYPTO_load_u64_be(buf);
return 1;
}
static int asn1_string_get_uint64(uint64_t *out, const ASN1_STRING *a,
int type) {
if (!asn1_string_get_abs_uint64(out, a, type)) {
return 0;
}
if (a->type & V_ASN1_NEG) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_INTEGER);
return 0;
}
return 1;
}
int ASN1_INTEGER_get_uint64(uint64_t *out, const ASN1_INTEGER *a) {
return asn1_string_get_uint64(out, a, V_ASN1_INTEGER);
}
int ASN1_ENUMERATED_get_uint64(uint64_t *out, const ASN1_ENUMERATED *a) {
return asn1_string_get_uint64(out, a, V_ASN1_ENUMERATED);
}
static int asn1_string_get_int64(int64_t *out, const ASN1_STRING *a, int type) {
uint64_t v;
if (!asn1_string_get_abs_uint64(&v, a, type)) {
return 0;
}
int64_t i64;
int fits_in_i64;
// Check |v != 0| to handle manually-constructed negative zeros.
if ((a->type & V_ASN1_NEG) && v != 0) {
i64 = (int64_t)(0u - v);
fits_in_i64 = i64 < 0;
} else {
i64 = (int64_t)v;
fits_in_i64 = i64 >= 0;
}
if (!fits_in_i64) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_INTEGER);
return 0;
}
*out = i64;
return 1;
}
int ASN1_INTEGER_get_int64(int64_t *out, const ASN1_INTEGER *a) {
return asn1_string_get_int64(out, a, V_ASN1_INTEGER);
}
int ASN1_ENUMERATED_get_int64(int64_t *out, const ASN1_ENUMERATED *a) {
return asn1_string_get_int64(out, a, V_ASN1_ENUMERATED);
}
static long asn1_string_get_long(const ASN1_STRING *a, int type) {
if (a == NULL) {
return 0;
}
int64_t v;
if (!asn1_string_get_int64(&v, a, type) || //
v < LONG_MIN || v > LONG_MAX) {
// This function's return value does not distinguish overflow from -1.
ERR_clear_error();
return -1;
}
return (long)v;
}
long ASN1_INTEGER_get(const ASN1_INTEGER *a) {
return asn1_string_get_long(a, V_ASN1_INTEGER);
}
long ASN1_ENUMERATED_get(const ASN1_ENUMERATED *a) {
return asn1_string_get_long(a, V_ASN1_ENUMERATED);
}
static ASN1_STRING *bn_to_asn1_string(const BIGNUM *bn, ASN1_STRING *ai,
int type) {
ASN1_INTEGER *ret;
if (ai == NULL) {
ret = ASN1_STRING_type_new(type);
} else {
ret = ai;
}
if (ret == NULL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
goto err;
}
if (BN_is_negative(bn) && !BN_is_zero(bn)) {
ret->type = type | V_ASN1_NEG;
} else {
ret->type = type;
}
int len = BN_num_bytes(bn);
if (!ASN1_STRING_set(ret, NULL, len) ||
!BN_bn2bin_padded(ret->data, len, bn)) {
goto err;
}
return ret;
err:
if (ret != ai) {
ASN1_STRING_free(ret);
}
return NULL;
}
ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai) {
return bn_to_asn1_string(bn, ai, V_ASN1_INTEGER);
}
ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(const BIGNUM *bn, ASN1_ENUMERATED *ai) {
return bn_to_asn1_string(bn, ai, V_ASN1_ENUMERATED);
}
static BIGNUM *asn1_string_to_bn(const ASN1_STRING *ai, BIGNUM *bn, int type) {
if ((ai->type & ~V_ASN1_NEG) != type) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_INTEGER_TYPE);
return NULL;
}
BIGNUM *ret;
if ((ret = BN_bin2bn(ai->data, ai->length, bn)) == NULL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BN_LIB);
} else if (ai->type & V_ASN1_NEG) {
BN_set_negative(ret, 1);
}
return ret;
}
BIGNUM *ASN1_INTEGER_to_BN(const ASN1_INTEGER *ai, BIGNUM *bn) {
return asn1_string_to_bn(ai, bn, V_ASN1_INTEGER);
}
BIGNUM *ASN1_ENUMERATED_to_BN(const ASN1_ENUMERATED *ai, BIGNUM *bn) {
return asn1_string_to_bn(ai, bn, V_ASN1_ENUMERATED);
}
+183 -209
View File
@@ -63,243 +63,217 @@
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include "asn1_locl.h"
#include "../bytestring/internal.h"
#include "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
// (using the order Printable < IA5 < T61 < BMP < Universal < UTF8) and
// creates a string of the correct type with the supplied data. Yes this is
// horrible: it has to be :-( The 'ncopy' form checks minimum and maximum
// size limits too.
/*
* These functions take a string in UTF8, ASCII or multibyte form and a mask
* of permissible ASN1 string types. It then works out the minimal type
* (using the order Printable < IA5 < T61 < BMP < Universal < UTF8) and
* creates a string of the correct type with the supplied data. Yes this is
* horrible: it has to be :-( The 'ncopy' form checks minimum and maximum
* size limits too.
*/
int ASN1_mbstring_copy(ASN1_STRING **out, const unsigned char *in, int len,
int inform, unsigned long mask)
{
return ASN1_mbstring_ncopy(out, in, len, inform, mask, 0, 0);
int ASN1_mbstring_copy(ASN1_STRING **out, const unsigned char *in,
ossl_ssize_t len, int inform, unsigned long mask) {
return ASN1_mbstring_ncopy(out, in, len, inform, mask, /*minsize=*/0,
/*maxsize=*/0);
}
OPENSSL_DECLARE_ERROR_REASON(ASN1, INVALID_BMPSTRING)
OPENSSL_DECLARE_ERROR_REASON(ASN1, INVALID_UNIVERSALSTRING)
OPENSSL_DECLARE_ERROR_REASON(ASN1, INVALID_UTF8STRING)
int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
int inform, unsigned long mask,
long minsize, long maxsize)
{
int str_type;
char free_out;
ASN1_STRING *dest;
size_t nchar = 0;
char strbuf[32];
if (len == -1)
len = strlen((const char *)in);
if (!mask)
mask = DIRSTRING_TYPE;
int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in,
ossl_ssize_t len, int inform, unsigned long mask,
ossl_ssize_t minsize, ossl_ssize_t maxsize) {
if (len == -1) {
len = strlen((const char *)in);
}
if (!mask) {
mask = DIRSTRING_TYPE;
}
int (*decode_func)(CBS *, uint32_t*);
int error;
switch (inform) {
int (*decode_func)(CBS *, uint32_t *);
int error;
switch (inform) {
case MBSTRING_BMP:
decode_func = cbs_get_ucs2_be;
error = ASN1_R_INVALID_BMPSTRING;
break;
decode_func = CBS_get_ucs2_be;
error = ASN1_R_INVALID_BMPSTRING;
break;
case MBSTRING_UNIV:
decode_func = cbs_get_utf32_be;
error = ASN1_R_INVALID_UNIVERSALSTRING;
break;
decode_func = CBS_get_utf32_be;
error = ASN1_R_INVALID_UNIVERSALSTRING;
break;
case MBSTRING_UTF8:
decode_func = cbs_get_utf8;
error = ASN1_R_INVALID_UTF8STRING;
break;
decode_func = CBS_get_utf8;
error = ASN1_R_INVALID_UTF8STRING;
break;
case MBSTRING_ASC:
decode_func = cbs_get_latin1;
error = ERR_R_INTERNAL_ERROR; // Latin-1 inputs are never invalid.
break;
decode_func = CBS_get_latin1;
error = ERR_R_INTERNAL_ERROR; // Latin-1 inputs are never invalid.
break;
default:
OPENSSL_PUT_ERROR(ASN1, ASN1_R_UNKNOWN_FORMAT);
return -1;
OPENSSL_PUT_ERROR(ASN1, ASN1_R_UNKNOWN_FORMAT);
return -1;
}
// Check |minsize| and |maxsize| and work out the minimal type, if any.
CBS cbs;
CBS_init(&cbs, in, len);
size_t utf8_len = 0, nchar = 0;
while (CBS_len(&cbs) != 0) {
uint32_t c;
if (!decode_func(&cbs, &c)) {
OPENSSL_PUT_ERROR(ASN1, error);
return -1;
}
if (nchar == 0 && (inform == MBSTRING_BMP || inform == MBSTRING_UNIV) &&
c == 0xfeff) {
// Reject byte-order mark. We could drop it but that would mean
// adding ambiguity around whether a BOM was included or not when
// matching strings.
//
// For a little-endian UCS-2 string, the BOM will appear as 0xfffe
// and will be rejected as noncharacter, below.
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_CHARACTERS);
return -1;
}
/* Check |minsize| and |maxsize| and work out the minimal type, if any. */
CBS cbs;
CBS_init(&cbs, in, len);
size_t utf8_len = 0;
while (CBS_len(&cbs) != 0) {
uint32_t c;
if (!decode_func(&cbs, &c)) {
OPENSSL_PUT_ERROR(ASN1, error);
return -1;
}
if (nchar == 0 &&
(inform == MBSTRING_BMP || inform == MBSTRING_UNIV) &&
c == 0xfeff) {
/* Reject byte-order mark. We could drop it but that would mean
* adding ambiguity around whether a BOM was included or not when
* matching strings.
*
* For a little-endian UCS-2 string, the BOM will appear as 0xfffe
* and will be rejected as noncharacter, below. */
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_CHARACTERS);
return -1;
}
/* Update which output formats are still possible. */
if ((mask & B_ASN1_PRINTABLESTRING) && !is_printable(c)) {
mask &= ~B_ASN1_PRINTABLESTRING;
}
if ((mask & B_ASN1_IA5STRING) && (c > 127)) {
mask &= ~B_ASN1_IA5STRING;
}
if ((mask & B_ASN1_T61STRING) && (c > 0xff)) {
mask &= ~B_ASN1_T61STRING;
}
if ((mask & B_ASN1_BMPSTRING) && (c > 0xffff)) {
mask &= ~B_ASN1_BMPSTRING;
}
if (!mask) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_CHARACTERS);
return -1;
}
nchar++;
utf8_len += cbb_get_utf8_len(c);
}
if (minsize > 0 && nchar < (size_t)minsize) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_SHORT);
BIO_snprintf(strbuf, sizeof strbuf, "%ld", minsize);
ERR_add_error_data(2, "minsize=", strbuf);
return -1;
// Update which output formats are still possible.
if ((mask & B_ASN1_PRINTABLESTRING) && !asn1_is_printable(c)) {
mask &= ~B_ASN1_PRINTABLESTRING;
}
if ((mask & B_ASN1_IA5STRING) && (c > 127)) {
mask &= ~B_ASN1_IA5STRING;
}
if ((mask & B_ASN1_T61STRING) && (c > 0xff)) {
mask &= ~B_ASN1_T61STRING;
}
if ((mask & B_ASN1_BMPSTRING) && (c > 0xffff)) {
mask &= ~B_ASN1_BMPSTRING;
}
if (!mask) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_CHARACTERS);
return -1;
}
nchar++;
utf8_len += CBB_get_utf8_len(c);
if (maxsize > 0 && nchar > (size_t)maxsize) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_LONG);
BIO_snprintf(strbuf, sizeof strbuf, "%ld", maxsize);
ERR_add_error_data(2, "maxsize=", strbuf);
return -1;
OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_LONG);
ERR_add_error_dataf("maxsize=%zu", (size_t)maxsize);
return -1;
}
}
/* Now work out output format and string type */
int (*encode_func)(CBB *, uint32_t) = cbb_add_latin1;
size_t size_estimate = nchar;
int outform = MBSTRING_ASC;
if (mask & B_ASN1_PRINTABLESTRING) {
str_type = V_ASN1_PRINTABLESTRING;
} else if (mask & B_ASN1_IA5STRING) {
str_type = V_ASN1_IA5STRING;
} else if (mask & B_ASN1_T61STRING) {
str_type = V_ASN1_T61STRING;
} else if (mask & B_ASN1_BMPSTRING) {
str_type = V_ASN1_BMPSTRING;
outform = MBSTRING_BMP;
encode_func = cbb_add_ucs2_be;
size_estimate = 2 * nchar;
} else if (mask & B_ASN1_UNIVERSALSTRING) {
str_type = V_ASN1_UNIVERSALSTRING;
encode_func = cbb_add_utf32_be;
size_estimate = 4 * nchar;
outform = MBSTRING_UNIV;
} else {
str_type = V_ASN1_UTF8STRING;
outform = MBSTRING_UTF8;
encode_func = cbb_add_utf8;
size_estimate = utf8_len;
}
if (!out)
return str_type;
if (*out) {
free_out = 0;
dest = *out;
if (dest->data) {
dest->length = 0;
OPENSSL_free(dest->data);
dest->data = NULL;
}
dest->type = str_type;
} else {
free_out = 1;
dest = ASN1_STRING_type_new(str_type);
if (!dest) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return -1;
}
*out = dest;
}
/* If both the same type just copy across */
if (inform == outform) {
if (!ASN1_STRING_set(dest, in, len)) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return -1;
}
return str_type;
}
CBB cbb;
if (!CBB_init(&cbb, size_estimate + 1)) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
CBS_init(&cbs, in, len);
while (CBS_len(&cbs) != 0) {
uint32_t c;
if (!decode_func(&cbs, &c) ||
!encode_func(&cbb, c)) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_INTERNAL_ERROR);
goto err;
}
}
uint8_t *data = NULL;
size_t data_len;
if (/* OpenSSL historically NUL-terminated this value with a single byte,
* even for |MBSTRING_BMP| and |MBSTRING_UNIV|. */
!CBB_add_u8(&cbb, 0) ||
!CBB_finish(&cbb, &data, &data_len) ||
data_len < 1 ||
data_len > INT_MAX) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_INTERNAL_ERROR);
OPENSSL_free(data);
goto err;
}
dest->length = (int)(data_len - 1);
dest->data = data;
return str_type;
err:
if (free_out)
ASN1_STRING_free(dest);
CBB_cleanup(&cbb);
if (minsize > 0 && nchar < (size_t)minsize) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_SHORT);
ERR_add_error_dataf("minsize=%zu", (size_t)minsize);
return -1;
}
// Now work out output format and string type
int str_type;
int (*encode_func)(CBB *, uint32_t) = CBB_add_latin1;
size_t size_estimate = nchar;
int outform = MBSTRING_ASC;
if (mask & B_ASN1_PRINTABLESTRING) {
str_type = V_ASN1_PRINTABLESTRING;
} else if (mask & B_ASN1_IA5STRING) {
str_type = V_ASN1_IA5STRING;
} else if (mask & B_ASN1_T61STRING) {
str_type = V_ASN1_T61STRING;
} else if (mask & B_ASN1_BMPSTRING) {
str_type = V_ASN1_BMPSTRING;
outform = MBSTRING_BMP;
encode_func = CBB_add_ucs2_be;
size_estimate = 2 * nchar;
} else if (mask & B_ASN1_UNIVERSALSTRING) {
str_type = V_ASN1_UNIVERSALSTRING;
encode_func = CBB_add_utf32_be;
size_estimate = 4 * nchar;
outform = MBSTRING_UNIV;
} 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) {
return str_type;
}
int free_dest = 0;
ASN1_STRING *dest;
if (*out) {
dest = *out;
} else {
free_dest = 1;
dest = ASN1_STRING_type_new(str_type);
if (!dest) {
return -1;
}
}
CBB cbb;
CBB_zero(&cbb);
// If both the same type just copy across
if (inform == outform) {
if (!ASN1_STRING_set(dest, in, len)) {
goto err;
}
dest->type = str_type;
*out = dest;
return str_type;
}
if (!CBB_init(&cbb, size_estimate + 1)) {
goto err;
}
CBS_init(&cbs, in, len);
while (CBS_len(&cbs) != 0) {
uint32_t c;
if (!decode_func(&cbs, &c) || !encode_func(&cbb, c)) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_INTERNAL_ERROR);
goto err;
}
}
uint8_t *data = NULL;
size_t data_len;
if (// OpenSSL historically NUL-terminated this value with a single byte,
// even for |MBSTRING_BMP| and |MBSTRING_UNIV|.
!CBB_add_u8(&cbb, 0) || !CBB_finish(&cbb, &data, &data_len) ||
data_len < 1 || data_len > INT_MAX) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_INTERNAL_ERROR);
OPENSSL_free(data);
goto err;
}
dest->type = str_type;
ASN1_STRING_set0(dest, data, (int)data_len - 1);
*out = dest;
return str_type;
err:
if (free_dest) {
ASN1_STRING_free(dest);
}
CBB_cleanup(&cbb);
return -1;
}
/* Return 1 if the character is permitted in a PrintableString */
static int is_printable(uint32_t value)
{
int ch;
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;
int asn1_is_printable(uint32_t value) {
if (value > 0x7f) {
return 0;
}
return OPENSSL_isalnum(value) || //
value == ' ' || value == '\'' || value == '(' || value == ')' ||
value == '+' || value == ',' || value == '-' || value == '.' ||
value == '/' || value == ':' || value == '=' || value == '?';
}
+144 -195
View File
@@ -59,228 +59,177 @@
#include <limits.h>
#include <string.h>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_obj.h>
#include "../bytestring/internal.h"
#include "../internal.h"
#include "internal.h"
int i2d_ASN1_OBJECT(const ASN1_OBJECT *a, unsigned char **pp)
{
unsigned char *p, *allocated = NULL;
int objsize;
int i2d_ASN1_OBJECT(const ASN1_OBJECT *in, unsigned char **outp) {
if (in == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
if ((a == NULL) || (a->data == NULL))
return (0);
if (in->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)
return objsize;
CBB cbb, child;
if (!CBB_init(&cbb, (size_t)in->length + 2) ||
!CBB_add_asn1(&cbb, &child, CBS_ASN1_OBJECT) ||
!CBB_add_bytes(&child, in->data, in->length)) {
CBB_cleanup(&cbb);
return -1;
}
if (*pp == NULL) {
if ((p = allocated = OPENSSL_malloc(objsize)) == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return 0;
}
} else {
p = *pp;
}
ASN1_put_object(&p, 0, a->length, V_ASN1_OBJECT, V_ASN1_UNIVERSAL);
OPENSSL_memcpy(p, a->data, a->length);
/*
* If a new buffer was allocated, just return it back.
* If not, return the incremented buffer pointer.
*/
*pp = allocated != NULL ? allocated : p + a->length;
return objsize;
return CBB_finish_i2d(&cbb, outp);
}
int i2t_ASN1_OBJECT(char *buf, int buf_len, const ASN1_OBJECT *a)
{
return OBJ_obj2txt(buf, buf_len, a, 0);
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, const ASN1_OBJECT *a)
{
char buf[80], *p = buf;
int i;
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);
}
if (i <= 0)
return BIO_write(bp, "<INVALID>", 9);
BIO_write(bp, p, i);
if (p != buf)
OPENSSL_free(p);
return (i);
static int write_str(BIO *bp, const char *str) {
size_t len = strlen(str);
if (len > INT_MAX) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_OVERFLOW);
return -1;
}
return BIO_write(bp, str, (int)len) == (int)len ? (int)len : -1;
}
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);
if (inf & 0x80) {
i = ASN1_R_BAD_OBJECT_HEADER;
goto err;
}
int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a) {
if (a == NULL || a->data == NULL) {
return write_str(bp, "NULL");
}
if (tag != V_ASN1_OBJECT) {
i = ASN1_R_EXPECTING_AN_OBJECT;
goto err;
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;
}
ret = c2i_ASN1_OBJECT(a, &p, len);
if (ret)
*pp = p;
return ret;
err:
OPENSSL_PUT_ERROR(ASN1, i);
return (NULL);
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 *c2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp,
long len)
{
ASN1_OBJECT *ret = NULL;
const unsigned char *p;
unsigned char *data;
int i, length;
ASN1_OBJECT *d2i_ASN1_OBJECT(ASN1_OBJECT **out, const unsigned char **inp,
long len) {
if (len < 0) {
return NULL;
}
/*
* Sanity check OID encoding. Need at least one content octet. MSB must
* be clear in the last octet. can't have leading 0x80 in subidentifiers,
* see: X.690 8.19.2
*/
if (len <= 0 || len > INT_MAX || pp == NULL || (p = *pp) == NULL ||
p[len - 1] & 0x80) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_OBJECT_ENCODING);
return NULL;
}
/* Now 0 < len <= INT_MAX, so the cast is safe. */
length = (int)len;
for (i = 0; i < length; i++, p++) {
if (*p == 0x80 && (!i || !(p[-1] & 0x80))) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_OBJECT_ENCODING);
return NULL;
}
}
CBS cbs, child;
CBS_init(&cbs, *inp, (size_t)len);
if (!CBS_get_asn1(&cbs, &child, CBS_ASN1_OBJECT)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return NULL;
}
/*
* 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
ret = (*a);
p = *pp;
/* detach data from object */
data = (unsigned char *)ret->data;
ret->data = NULL;
/* once detached we can change it */
if ((data == NULL) || (ret->length < length)) {
ret->length = 0;
if (data != NULL)
OPENSSL_free(data);
data = (unsigned char *)OPENSSL_malloc(length);
if (data == NULL) {
i = ERR_R_MALLOC_FAILURE;
goto err;
}
ret->flags |= ASN1_OBJECT_FLAG_DYNAMIC_DATA;
}
OPENSSL_memcpy(data, p, length);
/* 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)
(*a) = ret;
*pp = p;
return (ret);
err:
OPENSSL_PUT_ERROR(ASN1, i);
if ((ret != NULL) && ((a == NULL) || (*a != ret)))
ASN1_OBJECT_free(ret);
return (NULL);
const uint8_t *contents = CBS_data(&child);
ASN1_OBJECT *ret = c2i_ASN1_OBJECT(out, &contents, CBS_len(&child));
if (ret != NULL) {
// |c2i_ASN1_OBJECT| should have consumed the entire input.
assert(CBS_data(&cbs) == contents);
*inp = CBS_data(&cbs);
}
return ret;
}
ASN1_OBJECT *ASN1_OBJECT_new(void)
{
ASN1_OBJECT *ret;
ASN1_OBJECT *c2i_ASN1_OBJECT(ASN1_OBJECT **out, const unsigned char **inp,
long len) {
if (len < 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_OBJECT_ENCODING);
return NULL;
}
ret = (ASN1_OBJECT *)OPENSSL_malloc(sizeof(ASN1_OBJECT));
if (ret == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return (NULL);
}
ret->length = 0;
ret->data = NULL;
ret->nid = 0;
ret->sn = NULL;
ret->ln = NULL;
ret->flags = ASN1_OBJECT_FLAG_DYNAMIC;
return (ret);
CBS cbs;
CBS_init(&cbs, *inp, (size_t)len);
if (!CBS_is_valid_asn1_oid(&cbs)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_OBJECT_ENCODING);
return NULL;
}
ASN1_OBJECT *ret = ASN1_OBJECT_create(NID_undef, *inp, (size_t)len,
/*sn=*/NULL, /*ln=*/NULL);
if (ret == NULL) {
return NULL;
}
if (out != NULL) {
ASN1_OBJECT_free(*out);
*out = ret;
}
*inp += len; // All bytes were consumed.
return ret;
}
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
a->sn = a->ln = NULL;
}
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC_DATA) {
if (a->data != NULL)
OPENSSL_free((void *)a->data);
a->data = NULL;
a->length = 0;
}
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC)
OPENSSL_free(a);
ASN1_OBJECT *ASN1_OBJECT_new(void) {
ASN1_OBJECT *ret;
ret = (ASN1_OBJECT *)OPENSSL_malloc(sizeof(ASN1_OBJECT));
if (ret == NULL) {
return NULL;
}
ret->length = 0;
ret->data = NULL;
ret->nid = 0;
ret->sn = NULL;
ret->ln = NULL;
ret->flags = ASN1_OBJECT_FLAG_DYNAMIC;
return ret;
}
ASN1_OBJECT *ASN1_OBJECT_create(int nid, unsigned char *data, int len,
const char *sn, const char *ln)
{
ASN1_OBJECT o;
o.sn = sn;
o.ln = ln;
o.data = data;
o.nid = nid;
o.length = len;
o.flags = ASN1_OBJECT_FLAG_DYNAMIC | ASN1_OBJECT_FLAG_DYNAMIC_STRINGS |
ASN1_OBJECT_FLAG_DYNAMIC_DATA;
return (OBJ_dup(&o));
void ASN1_OBJECT_free(ASN1_OBJECT *a) {
if (a == NULL) {
return;
}
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC_STRINGS) {
OPENSSL_free((void *)a->sn);
OPENSSL_free((void *)a->ln);
a->sn = a->ln = NULL;
}
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC_DATA) {
OPENSSL_free((void *)a->data);
a->data = NULL;
a->length = 0;
}
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC) {
OPENSSL_free(a);
}
}
ASN1_OBJECT *ASN1_OBJECT_create(int nid, const unsigned char *data, size_t len,
const char *sn, const char *ln) {
if (len > INT_MAX) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_LONG);
return NULL;
}
ASN1_OBJECT o;
o.sn = sn;
o.ln = ln;
o.data = data;
o.nid = nid;
o.length = (int)len;
o.flags = ASN1_OBJECT_FLAG_DYNAMIC | ASN1_OBJECT_FLAG_DYNAMIC_STRINGS |
ASN1_OBJECT_FLAG_DYNAMIC_DATA;
return OBJ_dup(&o);
}
@@ -59,19 +59,16 @@
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
ASN1_OCTET_STRING *ASN1_OCTET_STRING_dup(const ASN1_OCTET_STRING *x)
{
return M_ASN1_OCTET_STRING_dup(x);
ASN1_OCTET_STRING *ASN1_OCTET_STRING_dup(const ASN1_OCTET_STRING *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);
const ASN1_OCTET_STRING *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);
int len) {
return ASN1_STRING_set(x, d, len);
}
@@ -0,0 +1,457 @@
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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 acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS 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 AUTHOR OR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.] */
#include <CCryptoBoringSSL_asn1.h>
#include <assert.h>
#include <ctype.h>
#include <inttypes.h>
#include <limits.h>
#include <string.h>
#include <time.h>
#include <CCryptoBoringSSL_bio.h>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_mem.h>
#include "../bytestring/internal.h"
#include "../internal.h"
#include "internal.h"
#define ESC_FLAGS \
(ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_QUOTE | ASN1_STRFLGS_ESC_CTRL | \
ASN1_STRFLGS_ESC_MSB)
static int maybe_write(BIO *out, const void *buf, int len) {
// If |out| is NULL, ignore the output but report the length.
return out == NULL || BIO_write(out, buf, len) == len;
}
static int is_control_character(unsigned char c) { return c < 32 || c == 127; }
static int do_esc_char(uint32_t c, unsigned long flags, char *do_quotes,
BIO *out, int is_first, int is_last) {
// |c| is a |uint32_t| because, depending on |ASN1_STRFLGS_UTF8_CONVERT|,
// we may be escaping bytes or Unicode codepoints.
char buf[16]; // Large enough for "\\W01234567".
unsigned char u8 = (unsigned char)c;
if (c > 0xffff) {
snprintf(buf, sizeof(buf), "\\W%08" PRIX32, c);
} else if (c > 0xff) {
snprintf(buf, sizeof(buf), "\\U%04" PRIX32, c);
} else if ((flags & ASN1_STRFLGS_ESC_MSB) && c > 0x7f) {
snprintf(buf, sizeof(buf), "\\%02X", c);
} else if ((flags & ASN1_STRFLGS_ESC_CTRL) && is_control_character(c)) {
snprintf(buf, sizeof(buf), "\\%02X", c);
} else if (flags & ASN1_STRFLGS_ESC_2253) {
// See RFC 2253, sections 2.4 and 4.
if (c == '\\' || c == '"') {
// Quotes and backslashes are always escaped, quoted or not.
snprintf(buf, sizeof(buf), "\\%c", (int)c);
} else if (c == ',' || c == '+' || c == '<' || c == '>' || c == ';' ||
(is_first && (c == ' ' || c == '#')) ||
(is_last && (c == ' '))) {
if (flags & ASN1_STRFLGS_ESC_QUOTE) {
// No need to escape, just tell the caller to quote.
if (do_quotes != NULL) {
*do_quotes = 1;
}
return maybe_write(out, &u8, 1) ? 1 : -1;
}
snprintf(buf, sizeof(buf), "\\%c", (int)c);
} else {
return maybe_write(out, &u8, 1) ? 1 : -1;
}
} else if ((flags & ESC_FLAGS) && c == '\\') {
// If any escape flags are set, also escape backslashes.
snprintf(buf, sizeof(buf), "\\%c", (int)c);
} else {
return maybe_write(out, &u8, 1) ? 1 : -1;
}
static_assert(sizeof(buf) < INT_MAX, "len may not fit in int");
int len = (int)strlen(buf);
return maybe_write(out, buf, len) ? len : -1;
}
// This function sends each character in a buffer to do_esc_char(). It
// interprets the content formats and converts to or from UTF8 as
// appropriate.
static int do_buf(const unsigned char *buf, int buflen, int encoding,
unsigned long flags, char *quotes, BIO *out) {
int (*get_char)(CBS *cbs, uint32_t *out);
int get_char_error;
switch (encoding) {
case MBSTRING_UNIV:
get_char = CBS_get_utf32_be;
get_char_error = ASN1_R_INVALID_UNIVERSALSTRING;
break;
case MBSTRING_BMP:
get_char = CBS_get_ucs2_be;
get_char_error = ASN1_R_INVALID_BMPSTRING;
break;
case MBSTRING_ASC:
get_char = CBS_get_latin1;
get_char_error = ERR_R_INTERNAL_ERROR; // Should not be possible.
break;
case MBSTRING_UTF8:
get_char = CBS_get_utf8;
get_char_error = ASN1_R_INVALID_UTF8STRING;
break;
default:
assert(0);
return -1;
}
CBS cbs;
CBS_init(&cbs, buf, buflen);
int outlen = 0;
while (CBS_len(&cbs) != 0) {
const int is_first = CBS_data(&cbs) == buf;
uint32_t c;
if (!get_char(&cbs, &c)) {
OPENSSL_PUT_ERROR(ASN1, get_char_error);
return -1;
}
const int is_last = CBS_len(&cbs) == 0;
if (flags & ASN1_STRFLGS_UTF8_CONVERT) {
uint8_t utf8_buf[6];
CBB utf8_cbb;
CBB_init_fixed(&utf8_cbb, utf8_buf, sizeof(utf8_buf));
if (!CBB_add_utf8(&utf8_cbb, c)) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_INTERNAL_ERROR);
return 1;
}
size_t utf8_len = CBB_len(&utf8_cbb);
for (size_t i = 0; i < utf8_len; i++) {
int len = do_esc_char(utf8_buf[i], flags, quotes, out,
is_first && i == 0, is_last && i == utf8_len - 1);
if (len < 0) {
return -1;
}
outlen += len;
}
} else {
int len = do_esc_char(c, flags, quotes, out, is_first, is_last);
if (len < 0) {
return -1;
}
outlen += len;
}
}
return outlen;
}
// This function hex dumps a buffer of characters
static int do_hex_dump(BIO *out, unsigned char *buf, int buflen) {
static const char hexdig[] = "0123456789ABCDEF";
unsigned char *p, *q;
char hextmp[2];
if (out) {
p = buf;
q = buf + buflen;
while (p != q) {
hextmp[0] = hexdig[*p >> 4];
hextmp[1] = hexdig[*p & 0xf];
if (!maybe_write(out, hextmp, 2)) {
return -1;
}
p++;
}
}
return buflen << 1;
}
// "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 RFC 2253 #01234 format.
static int do_dump(unsigned long flags, BIO *out, const ASN1_STRING *str) {
if (!maybe_write(out, "#", 1)) {
return -1;
}
// If we don't dump DER encoding just dump content octets
if (!(flags & ASN1_STRFLGS_DUMP_DER)) {
int outlen = do_hex_dump(out, str->data, str->length);
if (outlen < 0) {
return -1;
}
return outlen + 1;
}
// Placing the ASN1_STRING in a temporary ASN1_TYPE allows the DER encoding
// to readily obtained.
ASN1_TYPE t;
OPENSSL_memset(&t, 0, sizeof(ASN1_TYPE));
asn1_type_set0_string(&t, (ASN1_STRING *)str);
unsigned char *der_buf = NULL;
int der_len = i2d_ASN1_TYPE(&t, &der_buf);
if (der_len < 0) {
return -1;
}
int outlen = do_hex_dump(out, der_buf, der_len);
OPENSSL_free(der_buf);
if (outlen < 0) {
return -1;
}
return outlen + 1;
}
// string_type_to_encoding returns the |MBSTRING_*| constant for the encoding
// used by the |ASN1_STRING| type |type|, or -1 if |tag| is not a string
// type.
static int string_type_to_encoding(int type) {
// This function is sometimes passed ASN.1 universal types and sometimes
// passed |ASN1_STRING| type values
switch (type) {
case V_ASN1_UTF8STRING:
return MBSTRING_UTF8;
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_ISO64STRING:
// |MBSTRING_ASC| refers to Latin-1, not ASCII.
return MBSTRING_ASC;
case V_ASN1_UNIVERSALSTRING:
return MBSTRING_UNIV;
case V_ASN1_BMPSTRING:
return MBSTRING_BMP;
}
return -1;
}
// This is the main function, print out an ASN1_STRING taking note of various
// escape and display options. Returns number of characters written or -1 if
// an error occurred.
int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str,
unsigned long flags) {
int type = str->type;
int outlen = 0;
if (flags & ASN1_STRFLGS_SHOW_TYPE) {
const char *tagname = ASN1_tag2str(type);
outlen += strlen(tagname);
if (!maybe_write(out, tagname, outlen) || !maybe_write(out, ":", 1)) {
return -1;
}
outlen++;
}
// Decide what to do with |str|, either dump the contents or display it.
int encoding;
if (flags & ASN1_STRFLGS_DUMP_ALL) {
// Dump everything.
encoding = -1;
} else if (flags & ASN1_STRFLGS_IGNORE_TYPE) {
// Ignore the string type and interpret the contents as Latin-1.
encoding = MBSTRING_ASC;
} else {
encoding = string_type_to_encoding(type);
if (encoding == -1 && (flags & ASN1_STRFLGS_DUMP_UNKNOWN) == 0) {
encoding = MBSTRING_ASC;
}
}
if (encoding == -1) {
int len = do_dump(flags, out, str);
if (len < 0) {
return -1;
}
outlen += len;
return outlen;
}
// Measure the length.
char quotes = 0;
int len = do_buf(str->data, str->length, encoding, flags, &quotes, NULL);
if (len < 0) {
return -1;
}
outlen += len;
if (quotes) {
outlen += 2;
}
if (!out) {
return outlen;
}
// Encode the value.
if ((quotes && !maybe_write(out, "\"", 1)) ||
do_buf(str->data, str->length, encoding, flags, NULL, out) < 0 ||
(quotes && !maybe_write(out, "\"", 1))) {
return -1;
}
return outlen;
}
int ASN1_STRING_print_ex_fp(FILE *fp, const ASN1_STRING *str,
unsigned long flags) {
BIO *bio = NULL;
if (fp != NULL) {
// If |fp| is NULL, this function returns the number of bytes without
// writing.
bio = BIO_new_fp(fp, BIO_NOCLOSE);
if (bio == NULL) {
return -1;
}
}
int ret = ASN1_STRING_print_ex(bio, str, flags);
BIO_free(bio);
return ret;
}
int ASN1_STRING_to_UTF8(unsigned char **out, const ASN1_STRING *in) {
if (!in) {
return -1;
}
int mbflag = string_type_to_encoding(in->type);
if (mbflag == -1) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_UNKNOWN_TAG);
return -1;
}
ASN1_STRING stmp, *str = &stmp;
stmp.data = NULL;
stmp.length = 0;
stmp.flags = 0;
int 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_puts(bp, "Bad time value");
return 0;
}
static const char *const mon[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
int ASN1_GENERALIZEDTIME_print(BIO *bp, const ASN1_GENERALIZEDTIME *tm) {
CBS cbs;
CBS_init(&cbs, tm->data, tm->length);
struct tm utc;
if (!CBS_parse_generalized_time(&cbs, &utc, /*allow_timezone_offset=*/0)) {
BIO_puts(bp, "Bad time value");
return 0;
}
return BIO_printf(bp, "%s %2d %02d:%02d:%02d %d GMT", mon[utc.tm_mon],
utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec,
utc.tm_year + 1900) > 0;
}
int ASN1_UTCTIME_print(BIO *bp, const ASN1_UTCTIME *tm) {
CBS cbs;
CBS_init(&cbs, tm->data, tm->length);
struct tm utc;
if (!CBS_parse_utc_time(&cbs, &utc, /*allow_timezone_offset=*/0)) {
BIO_puts(bp, "Bad time value");
return 0;
}
return BIO_printf(bp, "%s %2d %02d:%02d:%02d %d GMT", mon[utc.tm_mon],
utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec,
utc.tm_year + 1900) > 0;
}
+137 -205
View File
@@ -56,118 +56,73 @@
#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 CRYPTO_MUTEX string_tables_lock = CRYPTO_MUTEX_INIT;
void ASN1_STRING_set_default_mask(unsigned long mask)
{
global_mask = mask;
void ASN1_STRING_set_default_mask(unsigned long mask) {}
unsigned long ASN1_STRING_get_default_mask(void) { return B_ASN1_UTF8STRING; }
int ASN1_STRING_set_default_mask_asc(const char *p) { return 1; }
static const ASN1_STRING_TABLE *asn1_string_table_get(int nid);
// The following function generates an ASN1_STRING based on limits in a
// table. Frequently the types and length of an ASN1_STRING are restricted by
// a corresponding OID. For example certificates and certificate requests.
ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, const unsigned char *in,
ossl_ssize_t len, int inform, int nid) {
ASN1_STRING *str = NULL;
int ret;
if (!out) {
out = &str;
}
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;
}
unsigned long ASN1_STRING_get_default_mask(void)
{
return global_mask;
}
// Now the tables and helper functions for the string table:
/*
* 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.
*/
// 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_email_address 128
#define ub_serial_number 64
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;
}
/*
* 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_TABLE *tbl;
ASN1_STRING *str = NULL;
unsigned long mask;
int ret;
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)
return NULL;
return *out;
}
/*
* Now the tables and helper functions for the string table:
*/
/* size limits: this stuff is taken straight from RFC3280 */
#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
/* This table must be kept in NID order */
// This table must be kept in NID order
static const ASN1_STRING_TABLE tbl_standard[] = {
{NID_commonName, 1, ub_common_name, DIRSTRING_TYPE, 0},
@@ -191,123 +146,100 @@ static const ASN1_STRING_TABLE tbl_standard[] = {
{NID_name, 1, ub_name, DIRSTRING_TYPE, 0},
{NID_dnQualifier, -1, -1, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK},
{NID_domainComponent, 1, -1, B_ASN1_IA5STRING, STABLE_NO_MASK},
{NID_ms_csp_name, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK}
};
{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)
{
return (*a)->nid - (*b)->nid;
}
static int table_cmp(const void *in_a, const void *in_b)
{
const ASN1_STRING_TABLE *a = in_a;
const ASN1_STRING_TABLE *b = in_b;
return a->nid - b->nid;
}
ASN1_STRING_TABLE *ASN1_STRING_TABLE_get(int nid)
{
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);
}
int ASN1_STRING_TABLE_add(int nid,
long minsize, long maxsize, unsigned long mask,
unsigned long flags)
{
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);
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;
}
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);
static int table_cmp(const ASN1_STRING_TABLE *a, const ASN1_STRING_TABLE *b) {
if (a->nid < b->nid) {
return -1;
}
if (a->nid > b->nid) {
return 1;
}
return 0;
}
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 int table_cmp_void(const void *a, const void *b) {
return table_cmp(a, b);
}
static void st_free(ASN1_STRING_TABLE *tbl)
{
if (tbl->flags & STABLE_FLAGS_MALLOC)
OPENSSL_free(tbl);
static uint32_t table_hash(const ASN1_STRING_TABLE *tbl) {
return OPENSSL_hash32(&tbl->nid, sizeof(tbl->nid));
}
#ifdef STRING_TABLE_TEST
static const ASN1_STRING_TABLE *asn1_string_table_get(int nid) {
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;
}
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));
CRYPTO_MUTEX_lock_read(&string_tables_lock);
if (string_tables != NULL) {
tbl = lh_ASN1_STRING_TABLE_retrieve(string_tables, &key);
}
CRYPTO_MUTEX_unlock_read(&string_tables_lock);
// Note returning |tbl| without the lock is only safe because
// |ASN1_STRING_TABLE_add| cannot modify or delete existing entries. If we
// 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;
}
int ret = 0;
CRYPTO_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;
}
} 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_MUTEX_unlock_write(&string_tables_lock);
return ret;
}
#endif
void ASN1_STRING_TABLE_cleanup(void) {}
void asn1_get_string_table_for_testing(const ASN1_STRING_TABLE **out_ptr,
size_t *out_len) {
*out_ptr = tbl_standard;
*out_len = OPENSSL_ARRAY_SIZE(tbl_standard);
}
+170 -123
View File
@@ -55,158 +55,205 @@
* [including the GNU Public Licence.] */
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_time.h>
#include <string.h>
#include <time.h>
#include <CCryptoBoringSSL_asn1t.h>
#include <CCryptoBoringSSL_bytestring.h>
#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 ::=
* CHOICE { utcTime UTCTime, generalTime GeneralizedTime } written by Steve
* Henson.
*/
// This is an implementation of the ASN1 Time structure which is: Time ::=
// CHOICE { utcTime UTCTime, generalTime GeneralizedTime } written by Steve
// Henson.
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)
{
return ASN1_TIME_adj(s, t, 0, 0);
ASN1_TIME *ASN1_TIME_set_posix(ASN1_TIME *s, int64_t posix_time) {
return ASN1_TIME_adj(s, posix_time, 0, 0);
}
ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, time_t t,
int offset_day, long offset_sec)
{
struct tm *ts;
struct tm data;
ts = OPENSSL_gmtime(&t, &data);
if (ts == NULL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ERROR_GETTING_TIME);
return NULL;
}
if (offset_day || offset_sec) {
if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
return NULL;
}
if ((ts->tm_year >= 50) && (ts->tm_year < 150))
return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t time) {
return ASN1_TIME_adj(s, time, 0, 0);
}
int ASN1_TIME_check(const ASN1_TIME *t)
{
if (t->type == V_ASN1_GENERALIZEDTIME)
return ASN1_GENERALIZEDTIME_check(t);
else if (t->type == V_ASN1_UTCTIME)
return ASN1_UTCTIME_check(t);
return 0;
static int fits_in_utc_time(const struct tm *tm) {
return 50 <= tm->tm_year && tm->tm_year < 150;
}
/* Convert an ASN1_TIME structure to GeneralizedTime */
ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *t,
ASN1_GENERALIZEDTIME **out)
{
ASN1_GENERALIZEDTIME *ret = NULL;
char *str;
int newlen;
ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, int64_t posix_time, int offset_day,
long offset_sec) {
struct tm tm;
if (!ASN1_TIME_check(t))
return NULL;
if (!out || !*out) {
if (!(ret = ASN1_GENERALIZEDTIME_new()))
goto err;
} else {
ret = *out;
}
/* If already GeneralizedTime just copy across */
if (t->type == V_ASN1_GENERALIZEDTIME) {
if (!ASN1_STRING_set(ret, t->data, t->length))
goto err;
goto done;
}
/* grow the string */
if (!ASN1_STRING_set(ret, NULL, t->length + 2))
goto err;
/* ASN1_STRING_set() allocated 'len + 1' bytes. */
newlen = t->length + 2 + 1;
str = (char *)ret->data;
/* Work out the century and prepend */
if (t->data[0] >= '5')
OPENSSL_strlcpy(str, "19", newlen);
else
OPENSSL_strlcpy(str, "20", newlen);
OPENSSL_strlcat(str, (char *)t->data, newlen);
done:
if (out != NULL && *out == NULL)
*out = ret;
return ret;
err:
if (out == NULL || *out != ret)
ASN1_GENERALIZEDTIME_free(ret);
if (!OPENSSL_posix_to_tm(posix_time, &tm)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ERROR_GETTING_TIME);
return NULL;
}
if (offset_day || offset_sec) {
if (!OPENSSL_gmtime_adj(&tm, offset_day, offset_sec)) {
return NULL;
}
}
if (fits_in_utc_time(&tm)) {
return ASN1_UTCTIME_adj(s, posix_time, offset_day, offset_sec);
}
return ASN1_GENERALIZEDTIME_adj(s, posix_time, offset_day, offset_sec);
}
int ASN1_TIME_set_string(ASN1_TIME *s, const char *str)
{
ASN1_TIME t;
t.length = strlen(str);
t.data = (unsigned char *)str;
t.flags = 0;
t.type = V_ASN1_UTCTIME;
if (!ASN1_TIME_check(&t)) {
t.type = V_ASN1_GENERALIZEDTIME;
if (!ASN1_TIME_check(&t))
return 0;
}
if (s && !ASN1_STRING_copy((ASN1_STRING *)s, (ASN1_STRING *)&t))
return 0;
return 1;
int ASN1_TIME_check(const ASN1_TIME *t) {
if (t->type == V_ASN1_GENERALIZEDTIME) {
return ASN1_GENERALIZEDTIME_check(t);
} else if (t->type == V_ASN1_UTCTIME) {
return ASN1_UTCTIME_check(t);
}
return 0;
}
static int asn1_time_to_tm(struct tm *tm, const ASN1_TIME *t)
{
if (t == NULL) {
time_t now_t;
time(&now_t);
if (OPENSSL_gmtime(&now_t, tm))
return 1;
return 0;
// Convert an ASN1_TIME structure to GeneralizedTime
ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *t,
ASN1_GENERALIZEDTIME **out) {
ASN1_GENERALIZEDTIME *ret = NULL;
char *str;
int newlen;
if (!ASN1_TIME_check(t)) {
return NULL;
}
if (!out || !*out) {
if (!(ret = ASN1_GENERALIZEDTIME_new())) {
goto err;
}
} else {
ret = *out;
}
if (t->type == V_ASN1_UTCTIME)
return asn1_utctime_to_tm(tm, t);
else if (t->type == V_ASN1_GENERALIZEDTIME)
return asn1_generalizedtime_to_tm(tm, t);
// If already GeneralizedTime just copy across
if (t->type == V_ASN1_GENERALIZEDTIME) {
if (!ASN1_STRING_set(ret, t->data, t->length)) {
goto err;
}
goto done;
}
// grow the string
if (!ASN1_STRING_set(ret, NULL, t->length + 2)) {
goto err;
}
// ASN1_STRING_set() allocated 'len + 1' bytes.
newlen = t->length + 2 + 1;
str = (char *)ret->data;
// Work out the century and prepend
if (t->data[0] >= '5') {
OPENSSL_strlcpy(str, "19", newlen);
} else {
OPENSSL_strlcpy(str, "20", newlen);
}
OPENSSL_strlcat(str, (char *)t->data, newlen);
done:
if (out != NULL && *out == NULL) {
*out = ret;
}
return ret;
err:
if (out == NULL || *out != ret) {
ASN1_GENERALIZEDTIME_free(ret);
}
return NULL;
}
int ASN1_TIME_set_string(ASN1_TIME *s, const char *str) {
return ASN1_UTCTIME_set_string(s, str) ||
ASN1_GENERALIZEDTIME_set_string(s, str);
}
int ASN1_TIME_set_string_X509(ASN1_TIME *s, const char *str) {
CBS cbs;
CBS_init(&cbs, (const uint8_t*)str, strlen(str));
int type;
struct tm tm;
if (CBS_parse_utc_time(&cbs, /*out_tm=*/NULL,
/*allow_timezone_offset=*/0)) {
type = V_ASN1_UTCTIME;
} else if (CBS_parse_generalized_time(&cbs, &tm,
/*allow_timezone_offset=*/0)) {
type = V_ASN1_GENERALIZEDTIME;
if (fits_in_utc_time(&tm)) {
type = V_ASN1_UTCTIME;
CBS_skip(&cbs, 2);
}
} else {
return 0;
}
if (s != NULL) {
if (!ASN1_STRING_set(s, CBS_data(&cbs), CBS_len(&cbs))) {
return 0;
}
s->type = type;
}
return 1;
}
int ASN1_TIME_diff(int *pday, int *psec,
const ASN1_TIME *from, const ASN1_TIME *to)
{
struct tm tm_from, tm_to;
if (!asn1_time_to_tm(&tm_from, from))
return 0;
if (!asn1_time_to_tm(&tm_to, to))
return 0;
return OPENSSL_gmtime_diff(pday, psec, &tm_from, &tm_to);
static int asn1_time_to_tm(struct tm *tm, const ASN1_TIME *t,
int allow_timezone_offset) {
if (t == NULL) {
if (OPENSSL_posix_to_tm(time(NULL), tm)) {
return 1;
}
return 0;
}
if (t->type == V_ASN1_UTCTIME) {
return asn1_utctime_to_tm(tm, t, allow_timezone_offset);
} else if (t->type == V_ASN1_GENERALIZEDTIME) {
return asn1_generalizedtime_to_tm(tm, t);
}
return 0;
}
int ASN1_TIME_diff(int *out_days, int *out_seconds, const ASN1_TIME *from,
const ASN1_TIME *to) {
struct tm tm_from, tm_to;
if (!asn1_time_to_tm(&tm_from, from, /*allow_timezone_offset=*/1)) {
return 0;
}
if (!asn1_time_to_tm(&tm_to, to, /*allow_timezone_offset=*/1)) {
return 0;
}
return OPENSSL_gmtime_diff(out_days, out_seconds, &tm_from, &tm_to);
}
// The functions below do *not* permissively allow the use of four digit
// timezone offsets in UTC times, as is done elsewhere in the code. They are
// both new API, and used internally to X509_cmp_time. This is to discourage the
// use of nonstandard times in new code, and to ensure that this code behaves
// correctly in X509_cmp_time which historically did its own time validations
// slightly different than the many other copies of X.509 time validation
// sprinkled through the codebase. The custom checks in X509_cmp_time meant that
// it did not allow four digit timezone offsets in UTC times.
int ASN1_TIME_to_time_t(const ASN1_TIME *t, time_t *out_time) {
struct tm tm;
if (!asn1_time_to_tm(&tm, t, /*allow_timezone_offset=*/0)) {
return 0;
}
return OPENSSL_timegm(&tm, out_time);
}
int ASN1_TIME_to_posix(const ASN1_TIME *t, int64_t *out_time) {
struct tm tm;
if (!asn1_time_to_tm(&tm, t, /*allow_timezone_offset=*/0)) {
return 0;
}
return OPENSSL_tm_to_posix(&tm, out_time);
}
+125 -62
View File
@@ -56,71 +56,135 @@
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_asn1t.h>
#include <assert.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_obj.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);
}
#include "internal.h"
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);
}
a->type = type;
if (type == V_ASN1_BOOLEAN)
a->value.boolean = value ? 0xff : 0;
else
a->value.ptr = value;
}
int ASN1_TYPE_set1(ASN1_TYPE *a, int type, const void *value)
{
if (!value || (type == V_ASN1_BOOLEAN)) {
void *p = (void *)value;
ASN1_TYPE_set(a, type, p);
} else if (type == V_ASN1_OBJECT) {
ASN1_OBJECT *odup;
odup = OBJ_dup(value);
if (!odup)
return 0;
ASN1_TYPE_set(a, type, odup);
} else {
ASN1_STRING *sdup;
sdup = ASN1_STRING_dup(value);
if (!sdup)
return 0;
ASN1_TYPE_set(a, type, sdup);
}
return 1;
}
/* Returns 0 if they are equal, != 0 otherwise. */
int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b)
{
int result = -1;
if (!a || !b || a->type != b->type)
return -1;
switch (a->type) {
case V_ASN1_OBJECT:
result = OBJ_cmp(a->value.object, b->value.object);
break;
int ASN1_TYPE_get(const ASN1_TYPE *a) {
switch (a->type) {
case V_ASN1_NULL:
result = 0; /* They do not have content. */
break;
case V_ASN1_BOOLEAN:
result = a->value.boolean - b->value.boolean;
break;
return a->type;
case V_ASN1_OBJECT:
return a->value.object != NULL ? a->type : 0;
default:
return a->value.asn1_string != NULL ? a->type : 0;
}
}
const void *asn1_type_value_as_pointer(const ASN1_TYPE *a) {
switch (a->type) {
case V_ASN1_NULL:
return NULL;
case V_ASN1_BOOLEAN:
return a->value.boolean ? (void *)0xff : NULL;
case V_ASN1_OBJECT:
return a->value.object;
default:
return a->value.asn1_string;
}
}
void asn1_type_set0_string(ASN1_TYPE *a, ASN1_STRING *str) {
// |ASN1_STRING| types are almost the same as |ASN1_TYPE| types, except that
// the negative flag is not reflected into |ASN1_TYPE|.
int type = str->type;
if (type == V_ASN1_NEG_INTEGER) {
type = V_ASN1_INTEGER;
} else if (type == V_ASN1_NEG_ENUMERATED) {
type = V_ASN1_ENUMERATED;
}
// These types are not |ASN1_STRING| types and use a different
// representation when stored in |ASN1_TYPE|.
assert(type != V_ASN1_NULL && type != V_ASN1_OBJECT &&
type != V_ASN1_BOOLEAN);
ASN1_TYPE_set(a, type, str);
}
void asn1_type_cleanup(ASN1_TYPE *a) {
switch (a->type) {
case V_ASN1_NULL:
a->value.ptr = NULL;
break;
case V_ASN1_BOOLEAN:
a->value.boolean = ASN1_BOOLEAN_NONE;
break;
case V_ASN1_OBJECT:
ASN1_OBJECT_free(a->value.object);
a->value.object = NULL;
break;
default:
ASN1_STRING_free(a->value.asn1_string);
a->value.asn1_string = NULL;
break;
}
}
void ASN1_TYPE_set(ASN1_TYPE *a, int type, void *value) {
asn1_type_cleanup(a);
a->type = type;
switch (type) {
case V_ASN1_NULL:
a->value.ptr = NULL;
break;
case V_ASN1_BOOLEAN:
a->value.boolean = value ? ASN1_BOOLEAN_TRUE : ASN1_BOOLEAN_FALSE;
break;
case V_ASN1_OBJECT:
a->value.object = value;
break;
default:
a->value.asn1_string = value;
break;
}
}
int ASN1_TYPE_set1(ASN1_TYPE *a, int type, const void *value) {
if (!value || (type == V_ASN1_BOOLEAN)) {
void *p = (void *)value;
ASN1_TYPE_set(a, type, p);
} else if (type == V_ASN1_OBJECT) {
ASN1_OBJECT *odup;
odup = OBJ_dup(value);
if (!odup) {
return 0;
}
ASN1_TYPE_set(a, type, odup);
} else {
ASN1_STRING *sdup;
sdup = ASN1_STRING_dup(value);
if (!sdup) {
return 0;
}
ASN1_TYPE_set(a, type, sdup);
}
return 1;
}
// Returns 0 if they are equal, != 0 otherwise.
int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b) {
int result = -1;
if (!a || !b || a->type != b->type) {
return -1;
}
switch (a->type) {
case V_ASN1_OBJECT:
result = OBJ_cmp(a->value.object, b->value.object);
break;
case V_ASN1_NULL:
result = 0; // They do not have content.
break;
case V_ASN1_BOOLEAN:
result = a->value.boolean - b->value.boolean;
break;
case V_ASN1_INTEGER:
case V_ASN1_ENUMERATED:
case V_ASN1_BIT_STRING:
@@ -142,10 +206,9 @@ 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);
break;
}
result = ASN1_STRING_cmp(a->value.asn1_string, b->value.asn1_string);
break;
}
return result;
return result;
}
+109 -229
View File
@@ -55,249 +55,129 @@
* [including the GNU Public Licence.] */
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_time.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include "internal.h"
#include "asn1_locl.h"
int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d)
{
static const int min[8] = { 0, 1, 1, 0, 0, 0, 0, 0 };
static const int max[8] = { 99, 12, 31, 23, 59, 59, 12, 59 };
char *a;
int n, i, l, o;
if (d->type != V_ASN1_UTCTIME)
return (0);
l = d->length;
a = (char *)d->data;
o = 0;
if (l < 11)
goto err;
for (i = 0; i < 6; i++) {
if ((i == 5) && ((a[o] == 'Z') || (a[o] == '+') || (a[o] == '-'))) {
i++;
if (tm)
tm->tm_sec = 0;
break;
}
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = a[o] - '0';
if (++o > l)
goto err;
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = (n * 10) + a[o] - '0';
if (++o > l)
goto err;
if ((n < min[i]) || (n > max[i]))
goto err;
if (tm) {
switch (i) {
case 0:
tm->tm_year = n < 50 ? n + 100 : n;
break;
case 1:
tm->tm_mon = n - 1;
break;
case 2:
tm->tm_mday = n;
break;
case 3:
tm->tm_hour = n;
break;
case 4:
tm->tm_min = n;
break;
case 5:
tm->tm_sec = n;
break;
}
}
}
if (a[o] == 'Z')
o++;
else if ((a[o] == '+') || (a[o] == '-')) {
int offsign = a[o] == '-' ? 1 : -1, offset = 0;
o++;
if (o + 4 > l)
goto err;
for (i = 6; i < 8; i++) {
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = a[o] - '0';
o++;
if ((a[o] < '0') || (a[o] > '9'))
goto err;
n = (n * 10) + a[o] - '0';
if ((n < min[i]) || (n > max[i]))
goto err;
if (tm) {
if (i == 6)
offset = n * 3600;
else if (i == 7)
offset += n * 60;
}
o++;
}
if (offset && !OPENSSL_gmtime_adj(tm, 0, offset * offsign))
return 0;
}
return o == l;
err:
int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d,
int allow_timezone_offset) {
if (d->type != V_ASN1_UTCTIME) {
return 0;
}
CBS cbs;
CBS_init(&cbs, d->data, (size_t)d->length);
if (!CBS_parse_utc_time(&cbs, tm, allow_timezone_offset)) {
return 0;
}
return 1;
}
int ASN1_UTCTIME_check(const ASN1_UTCTIME *d)
{
return asn1_utctime_to_tm(NULL, d);
int ASN1_UTCTIME_check(const ASN1_UTCTIME *d) {
return asn1_utctime_to_tm(NULL, d, /*allow_timezone_offset=*/1);
}
int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str)
{
ASN1_UTCTIME t;
t.type = V_ASN1_UTCTIME;
t.length = strlen(str);
t.data = (unsigned char *)str;
if (ASN1_UTCTIME_check(&t)) {
if (s != NULL) {
if (!ASN1_STRING_set((ASN1_STRING *)s,
(unsigned char *)str, t.length))
return 0;
s->type = V_ASN1_UTCTIME;
}
return (1);
} else
return (0);
}
ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, time_t t)
{
return ASN1_UTCTIME_adj(s, t, 0, 0);
}
ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t,
int offset_day, long offset_sec)
{
char *p;
struct tm *ts;
struct tm data;
size_t len = 20;
int free_s = 0;
if (s == NULL) {
free_s = 1;
s = M_ASN1_UTCTIME_new();
int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str) {
// Although elsewhere we allow timezone offsets with UTCTime, to be compatible
// with some existing misissued certificates, this function is used to
// construct new certificates and can be stricter.
size_t len = strlen(str);
CBS cbs;
CBS_init(&cbs, (const uint8_t *)str, len);
if (!CBS_parse_utc_time(&cbs, /*out_tm=*/NULL,
/*allow_timezone_offset=*/0)) {
return 0;
}
if (s != NULL) {
if (!ASN1_STRING_set(s, str, len)) {
return 0;
}
if (s == NULL)
goto err;
ts = OPENSSL_gmtime(&t, &data);
if (ts == NULL)
goto err;
if (offset_day || offset_sec) {
if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
goto err;
}
if ((ts->tm_year < 50) || (ts->tm_year >= 150))
goto err;
p = (char *)s->data;
if ((p == NULL) || ((size_t)s->length < len)) {
p = OPENSSL_malloc(len);
if (p == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
if (s->data != NULL)
OPENSSL_free(s->data);
s->data = (unsigned char *)p;
}
BIO_snprintf(p, len, "%02d%02d%02d%02d%02d%02dZ", ts->tm_year % 100,
ts->tm_mon + 1, ts->tm_mday, ts->tm_hour, ts->tm_min,
ts->tm_sec);
s->length = strlen(p);
s->type = V_ASN1_UTCTIME;
return (s);
err:
if (free_s && s)
M_ASN1_UTCTIME_free(s);
}
return 1;
}
ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, int64_t posix_time) {
return ASN1_UTCTIME_adj(s, posix_time, 0, 0);
}
ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, int64_t posix_time, int offset_day,
long offset_sec) {
struct tm data;
if (!OPENSSL_posix_to_tm(posix_time, &data)) {
return NULL;
}
}
int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t)
{
struct tm stm, ttm;
int day, sec;
if (!asn1_utctime_to_tm(&stm, s))
return -2;
if (!OPENSSL_gmtime(&t, &ttm))
return -2;
if (!OPENSSL_gmtime_diff(&day, &sec, &ttm, &stm))
return -2;
if (day > 0)
return 1;
if (day < 0)
return -1;
if (sec > 0)
return 1;
if (sec < 0)
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;
if (offset_day || offset_sec) {
if (!OPENSSL_gmtime_adj(&data, offset_day, offset_sec)) {
return NULL;
}
# 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. */
if (data.tm_year < 50 || data.tm_year >= 150) {
return NULL;
}
char buf[14];
int ret = snprintf(buf, sizeof(buf), "%02d%02d%02d%02d%02d%02dZ",
data.tm_year % 100, data.tm_mon + 1, data.tm_mday,
data.tm_hour, data.tm_min, data.tm_sec);
if (ret != (int)(sizeof(buf) - 1)) {
abort(); // |snprintf| should neither truncate nor write fewer bytes.
}
int free_s = 0;
if (s == NULL) {
free_s = 1;
s = ASN1_UTCTIME_new();
if (s == NULL) {
return NULL;
}
}
if (!ASN1_STRING_set(s, buf, strlen(buf))) {
if (free_s) {
ASN1_UTCTIME_free(s);
}
return NULL;
}
s->type = V_ASN1_UTCTIME;
return s;
}
int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t) {
struct tm stm, ttm;
int day, sec;
if (!asn1_utctime_to_tm(&stm, s, /*allow_timezone_offset=*/1)) {
return -2;
}
if (!OPENSSL_posix_to_tm(t, &ttm)) {
return -2;
}
if (!OPENSSL_gmtime_diff(&day, &sec, &ttm, &stm)) {
return -2;
}
if (day > 0) {
return 1;
}
if (day < 0) {
return -1;
}
if (sec > 0) {
return 1;
}
if (sec < 0) {
return -1;
}
return 0;
}
#endif
@@ -1,236 +0,0 @@
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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 acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS 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 AUTHOR OR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.] */
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include "asn1_locl.h"
/* UTF8 utilities */
/*
* This parses a UTF8 string one character at a time. It is passed a pointer
* to the string and the length of the string. It sets 'value' to the value
* of the current character. It returns the number of characters read or a
* negative error code: -1 = string too short -2 = illegal character -3 =
* subsequent characters not of the form 10xxxxxx -4 = character encoded
* incorrectly (not minimal length).
*/
int UTF8_getc(const unsigned char *str, int len, uint32_t *val)
{
const unsigned char *p;
uint32_t value;
int ret;
if (len <= 0)
return 0;
p = str;
/* Check syntax and work out the encoded value (if correct) */
if ((*p & 0x80) == 0) {
value = *p++ & 0x7f;
ret = 1;
} else if ((*p & 0xe0) == 0xc0) {
if (len < 2)
return -1;
if ((p[1] & 0xc0) != 0x80)
return -3;
value = (*p++ & 0x1f) << 6;
value |= *p++ & 0x3f;
if (value < 0x80)
return -4;
ret = 2;
} else if ((*p & 0xf0) == 0xe0) {
if (len < 3)
return -1;
if (((p[1] & 0xc0) != 0x80)
|| ((p[2] & 0xc0) != 0x80))
return -3;
value = (*p++ & 0xf) << 12;
value |= (*p++ & 0x3f) << 6;
value |= *p++ & 0x3f;
if (value < 0x800)
return -4;
ret = 3;
} else if ((*p & 0xf8) == 0xf0) {
if (len < 4)
return -1;
if (((p[1] & 0xc0) != 0x80)
|| ((p[2] & 0xc0) != 0x80)
|| ((p[3] & 0xc0) != 0x80))
return -3;
value = ((uint32_t)(*p++ & 0x7)) << 18;
value |= (*p++ & 0x3f) << 12;
value |= (*p++ & 0x3f) << 6;
value |= *p++ & 0x3f;
if (value < 0x10000)
return -4;
ret = 4;
} else if ((*p & 0xfc) == 0xf8) {
if (len < 5)
return -1;
if (((p[1] & 0xc0) != 0x80)
|| ((p[2] & 0xc0) != 0x80)
|| ((p[3] & 0xc0) != 0x80)
|| ((p[4] & 0xc0) != 0x80))
return -3;
value = ((uint32_t)(*p++ & 0x3)) << 24;
value |= ((uint32_t)(*p++ & 0x3f)) << 18;
value |= ((uint32_t)(*p++ & 0x3f)) << 12;
value |= (*p++ & 0x3f) << 6;
value |= *p++ & 0x3f;
if (value < 0x200000)
return -4;
ret = 5;
} else if ((*p & 0xfe) == 0xfc) {
if (len < 6)
return -1;
if (((p[1] & 0xc0) != 0x80)
|| ((p[2] & 0xc0) != 0x80)
|| ((p[3] & 0xc0) != 0x80)
|| ((p[4] & 0xc0) != 0x80)
|| ((p[5] & 0xc0) != 0x80))
return -3;
value = ((uint32_t)(*p++ & 0x1)) << 30;
value |= ((uint32_t)(*p++ & 0x3f)) << 24;
value |= ((uint32_t)(*p++ & 0x3f)) << 18;
value |= ((uint32_t)(*p++ & 0x3f)) << 12;
value |= (*p++ & 0x3f) << 6;
value |= *p++ & 0x3f;
if (value < 0x4000000)
return -4;
ret = 6;
} else
return -2;
*val = value;
return ret;
}
/*
* This takes a character 'value' and writes the UTF8 encoded value in 'str'
* where 'str' is a buffer containing 'len' characters. Returns the number of
* characters written or -1 if 'len' is too small. 'str' can be set to NULL
* in which case it just returns the number of characters. It will need at
* most 6 characters.
*/
int UTF8_putc(unsigned char *str, int len, uint32_t value)
{
if (!str)
len = 6; /* Maximum we will need */
else if (len <= 0)
return -1;
if (value < 0x80) {
if (str)
*str = (unsigned char)value;
return 1;
}
if (value < 0x800) {
if (len < 2)
return -1;
if (str) {
*str++ = (unsigned char)(((value >> 6) & 0x1f) | 0xc0);
*str = (unsigned char)((value & 0x3f) | 0x80);
}
return 2;
}
if (value < 0x10000) {
if (len < 3)
return -1;
if (str) {
*str++ = (unsigned char)(((value >> 12) & 0xf) | 0xe0);
*str++ = (unsigned char)(((value >> 6) & 0x3f) | 0x80);
*str = (unsigned char)((value & 0x3f) | 0x80);
}
return 3;
}
if (value < 0x200000) {
if (len < 4)
return -1;
if (str) {
*str++ = (unsigned char)(((value >> 18) & 0x7) | 0xf0);
*str++ = (unsigned char)(((value >> 12) & 0x3f) | 0x80);
*str++ = (unsigned char)(((value >> 6) & 0x3f) | 0x80);
*str = (unsigned char)((value & 0x3f) | 0x80);
}
return 4;
}
if (value < 0x4000000) {
if (len < 5)
return -1;
if (str) {
*str++ = (unsigned char)(((value >> 24) & 0x3) | 0xf8);
*str++ = (unsigned char)(((value >> 18) & 0x3f) | 0x80);
*str++ = (unsigned char)(((value >> 12) & 0x3f) | 0x80);
*str++ = (unsigned char)(((value >> 6) & 0x3f) | 0x80);
*str = (unsigned char)((value & 0x3f) | 0x80);
}
return 5;
}
if (len < 6)
return -1;
if (str) {
*str++ = (unsigned char)(((value >> 30) & 0x1) | 0xfc);
*str++ = (unsigned char)(((value >> 24) & 0x3f) | 0x80);
*str++ = (unsigned char)(((value >> 18) & 0x3f) | 0x80);
*str++ = (unsigned char)(((value >> 12) & 0x3f) | 0x80);
*str++ = (unsigned char)(((value >> 6) & 0x3f) | 0x80);
*str = (unsigned char)((value & 0x3f) | 0x80);
}
return 6;
}
+271 -314
View File
@@ -59,26 +59,25 @@
#include <limits.h>
#include <string.h>
#include <CCryptoBoringSSL_asn1_mac.h>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include "../internal.h"
#include "internal.h"
/* Cross-module errors from crypto/x509/i2d_pr.c. */
// Cross-module errors from crypto/x509/i2d_pr.c.
OPENSSL_DECLARE_ERROR_REASON(ASN1, UNSUPPORTED_PUBLIC_KEY_TYPE)
/* Cross-module errors from crypto/x509/algorithm.c. */
// Cross-module errors from crypto/x509/algorithm.c.
OPENSSL_DECLARE_ERROR_REASON(ASN1, CONTEXT_NOT_INITIALISED)
OPENSSL_DECLARE_ERROR_REASON(ASN1, DIGEST_AND_KEY_TYPE_NOT_SUPPORTED)
OPENSSL_DECLARE_ERROR_REASON(ASN1, UNKNOWN_MESSAGE_DIGEST_ALGORITHM)
OPENSSL_DECLARE_ERROR_REASON(ASN1, UNKNOWN_SIGNATURE_ALGORITHM)
OPENSSL_DECLARE_ERROR_REASON(ASN1, WRONG_PUBLIC_KEY_TYPE)
/*
* Cross-module errors from crypto/x509/asn1_gen.c. TODO(davidben): Remove
* these once asn1_gen.c is gone.
*/
// Cross-module errors from crypto/x509/asn1_gen.c. TODO(davidben): Remove
// these once asn1_gen.c is gone.
OPENSSL_DECLARE_ERROR_REASON(ASN1, DEPTH_EXCEEDED)
OPENSSL_DECLARE_ERROR_REASON(ASN1, ILLEGAL_BITSTRING_FORMAT)
OPENSSL_DECLARE_ERROR_REASON(ASN1, ILLEGAL_BOOLEAN)
@@ -103,338 +102,296 @@ 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);
// Limit |ASN1_STRING|s to 64 MiB of data. Most of this module, as well as
// downstream code, does not correctly handle overflow. We cap string fields
// more tightly than strictly necessary to fit in |int|. This is not expected to
// impact real world uses of this field.
//
// In particular, this limit is small enough that the bit count of a BIT STRING
// comfortably fits in an |int|, with room for arithmetic.
#define ASN1_STRING_MAX (64 * 1024 * 1024)
static void asn1_put_length(unsigned char **pp, int length);
int ASN1_get_object(const unsigned char **pp, long *plength, int *ptag,
int *pclass, long omax)
{
int i, ret;
long l;
const unsigned char *p = *pp;
int tag, xclass, inf;
long max = omax;
if (!max)
goto err;
ret = (*p & V_ASN1_CONSTRUCTED);
xclass = (*p & V_ASN1_PRIVATE);
i = *p & V_ASN1_PRIMITIVE_TAG;
if (i == V_ASN1_PRIMITIVE_TAG) { /* high-tag */
p++;
if (--max == 0)
goto err;
l = 0;
while (*p & 0x80) {
l <<= 7L;
l |= *(p++) & 0x7f;
if (--max == 0)
goto err;
if (l > (INT_MAX >> 7L))
goto err;
}
l <<= 7L;
l |= *(p++) & 0x7f;
tag = (int)l;
if (--max == 0)
goto err;
} else {
tag = i;
p++;
if (--max == 0)
goto err;
}
/* To avoid ambiguity with V_ASN1_NEG, impose a limit on universal tags. */
if (xclass == V_ASN1_UNIVERSAL && tag > V_ASN1_MAX_UNIVERSAL)
goto err;
*ptag = tag;
*pclass = xclass;
if (!asn1_get_length(&p, &inf, 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;
}
*pp = p;
return (ret | inf);
err:
int ASN1_get_object(const unsigned char **inp, long *out_len, int *out_tag,
int *out_class, long in_len) {
if (in_len < 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_HEADER_TOO_LONG);
return (0x80);
return 0x80;
}
CBS_ASN1_TAG tag;
CBS cbs, body;
CBS_init(&cbs, *inp, (size_t)in_len);
if (!CBS_get_any_asn1(&cbs, &body, &tag) ||
// Bound the length to comfortably fit in an int. Lengths in this
// module often switch between int and long without overflow checks.
CBS_len(&body) > INT_MAX / 2) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_HEADER_TOO_LONG);
return 0x80;
}
// Convert between tag representations.
int tag_class = (tag & CBS_ASN1_CLASS_MASK) >> CBS_ASN1_TAG_SHIFT;
int constructed = (tag & CBS_ASN1_CONSTRUCTED) >> CBS_ASN1_TAG_SHIFT;
int tag_number = tag & CBS_ASN1_TAG_NUMBER_MASK;
// To avoid ambiguity with V_ASN1_NEG, impose a limit on universal tags.
if (tag_class == V_ASN1_UNIVERSAL && tag_number > V_ASN1_MAX_UNIVERSAL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_HEADER_TOO_LONG);
return 0x80;
}
*inp = CBS_data(&body);
*out_len = CBS_len(&body);
*out_tag = tag_number;
*out_class = tag_class;
return constructed;
}
static int asn1_get_length(const unsigned char **pp, int *inf, long *rl,
long max)
{
const unsigned char *p = *pp;
unsigned long ret = 0;
unsigned long i;
if (max-- < 1)
return 0;
if (*p == 0x80) {
*inf = 1;
ret = 0;
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;
}
/*
* Bound the length to comfortably fit in an int. Lengths in this module
* often switch between int and long without overflow checks.
*/
if (ret > INT_MAX / 2)
return 0;
*pp = p;
*rl = (long)ret;
return 1;
}
/*
* class 0 is constructed constructed == 2 for indefinite length constructed
*/
// class 0 is constructed constructed == 2 for indefinite length constructed
void ASN1_put_object(unsigned char **pp, int constructed, int length, int tag,
int xclass)
{
unsigned char *p = *pp;
int i, ttag;
int xclass) {
unsigned char *p = *pp;
int i, ttag;
i = (constructed) ? V_ASN1_CONSTRUCTED : 0;
i |= (xclass & V_ASN1_PRIVATE);
if (tag < 31)
*(p++) = i | (tag & V_ASN1_PRIMITIVE_TAG);
else {
*(p++) = i | V_ASN1_PRIMITIVE_TAG;
for (i = 0, ttag = tag; ttag > 0; i++)
ttag >>= 7;
ttag = i;
while (i-- > 0) {
p[i] = tag & 0x7f;
if (i != (ttag - 1))
p[i] |= 0x80;
tag >>= 7;
}
p += ttag;
i = (constructed) ? V_ASN1_CONSTRUCTED : 0;
i |= (xclass & V_ASN1_PRIVATE);
if (tag < 31) {
*(p++) = i | (tag & V_ASN1_PRIMITIVE_TAG);
} else {
*(p++) = i | V_ASN1_PRIMITIVE_TAG;
for (i = 0, ttag = tag; ttag > 0; i++) {
ttag >>= 7;
}
if (constructed == 2)
*(p++) = 0x80;
else
asn1_put_length(&p, length);
*pp = p;
ttag = i;
while (i-- > 0) {
p[i] = tag & 0x7f;
if (i != (ttag - 1)) {
p[i] |= 0x80;
}
tag >>= 7;
}
p += ttag;
}
if (constructed == 2) {
*(p++) = 0x80;
} else {
asn1_put_length(&p, length);
}
*pp = p;
}
int ASN1_put_eoc(unsigned char **pp)
{
unsigned char *p = *pp;
*p++ = 0;
*p++ = 0;
*pp = p;
return 2;
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;
*pp = p;
return 2;
}
static void asn1_put_length(unsigned char **pp, int length)
{
unsigned char *p = *pp;
int i, l;
if (length <= 127)
*(p++) = (unsigned char)length;
else {
l = length;
for (i = 0; l > 0; i++)
l >>= 8;
*(p++) = i | 0x80;
l = i;
while (i-- > 0) {
p[i] = length & 0xff;
length >>= 8;
}
p += l;
static void asn1_put_length(unsigned char **pp, int length) {
unsigned char *p = *pp;
int i, l;
if (length <= 127) {
*(p++) = (unsigned char)length;
} else {
l = length;
for (i = 0; l > 0; i++) {
l >>= 8;
}
*pp = p;
*(p++) = i | 0x80;
l = i;
while (i-- > 0) {
p[i] = length & 0xff;
length >>= 8;
}
p += l;
}
*pp = p;
}
int ASN1_object_size(int constructed, int length, int tag)
{
int ret = 1;
if (length < 0)
return -1;
if (tag >= 31) {
while (tag > 0) {
tag >>= 7;
ret++;
}
int ASN1_object_size(int constructed, int length, int tag) {
int ret = 1;
if (length < 0) {
return -1;
}
if (tag >= 31) {
while (tag > 0) {
tag >>= 7;
ret++;
}
if (constructed == 2) {
ret += 3;
} else {
}
if (constructed == 2) {
ret += 3;
} else {
ret++;
if (length > 127) {
int tmplen = length;
while (tmplen > 0) {
tmplen >>= 8;
ret++;
if (length > 127) {
int tmplen = length;
while (tmplen > 0) {
tmplen >>= 8;
ret++;
}
}
}
}
if (ret >= INT_MAX - length)
return -1;
return ret + length;
}
if (ret >= INT_MAX - length) {
return -1;
}
return ret + length;
}
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->flags = str->flags;
int ASN1_STRING_copy(ASN1_STRING *dst, const ASN1_STRING *str) {
if (str == NULL) {
return 0;
}
if (!ASN1_STRING_set(dst, str->data, str->length)) {
return 0;
}
dst->type = str->type;
dst->flags = str->flags;
return 1;
}
ASN1_STRING *ASN1_STRING_dup(const ASN1_STRING *str) {
ASN1_STRING *ret;
if (!str) {
return NULL;
}
ret = ASN1_STRING_new();
if (!ret) {
return NULL;
}
if (!ASN1_STRING_copy(ret, str)) {
ASN1_STRING_free(ret);
return NULL;
}
return ret;
}
int ASN1_STRING_set(ASN1_STRING *str, const void *_data, ossl_ssize_t len_s) {
const char *data = _data;
size_t len;
if (len_s < 0) {
if (data == NULL) {
return 0;
}
len = strlen(data);
} else {
len = (size_t)len_s;
}
static_assert(ASN1_STRING_MAX < INT_MAX, "len will not overflow int");
if (len > ASN1_STRING_MAX) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_OVERFLOW);
return 0;
}
if (str->length <= (int)len || str->data == NULL) {
unsigned char *c = str->data;
if (c == NULL) {
str->data = OPENSSL_malloc(len + 1);
} else {
str->data = OPENSSL_realloc(c, len + 1);
}
if (str->data == NULL) {
str->data = c;
return 0;
}
}
str->length = (int)len;
if (data != NULL) {
OPENSSL_memcpy(str->data, data, len);
// Historically, OpenSSL would NUL-terminate most (but not all)
// |ASN1_STRING|s, in case anyone accidentally passed |str->data| into a
// function expecting a C string. We retain this behavior for compatibility,
// but code must not rely on this. See CVE-2021-3712.
str->data[len] = '\0';
}
return 1;
}
void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len) {
OPENSSL_free(str->data);
str->data = data;
str->length = len;
}
ASN1_STRING *ASN1_STRING_new(void) {
return (ASN1_STRING_type_new(V_ASN1_OCTET_STRING));
}
ASN1_STRING *ASN1_STRING_type_new(int type) {
ASN1_STRING *ret;
ret = (ASN1_STRING *)OPENSSL_malloc(sizeof(ASN1_STRING));
if (ret == NULL) {
return NULL;
}
ret->length = 0;
ret->type = type;
ret->data = NULL;
ret->flags = 0;
return ret;
}
void ASN1_STRING_free(ASN1_STRING *str) {
if (str == NULL) {
return;
}
OPENSSL_free(str->data);
OPENSSL_free(str);
}
int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b) {
// Capture padding bits and implicit truncation in BIT STRINGs.
int a_length = a->length, b_length = b->length;
uint8_t a_padding = 0, b_padding = 0;
if (a->type == V_ASN1_BIT_STRING) {
a_length = asn1_bit_string_length(a, &a_padding);
}
if (b->type == V_ASN1_BIT_STRING) {
b_length = asn1_bit_string_length(b, &b_padding);
}
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;
}
ASN1_STRING *ASN1_STRING_dup(const ASN1_STRING *str)
{
ASN1_STRING *ret;
if (!str)
return NULL;
ret = ASN1_STRING_new();
if (!ret)
return NULL;
if (!ASN1_STRING_copy(ret, str)) {
ASN1_STRING_free(ret);
return NULL;
}
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_set(ASN1_STRING *str, const void *_data, int len)
{
unsigned char *c;
const char *data = _data;
int ASN1_STRING_length(const ASN1_STRING *str) { return str->length; }
if (len < 0) {
if (data == NULL)
return (0);
else
len = strlen(data);
}
if ((str->length <= len) || (str->data == NULL)) {
c = str->data;
if (c == NULL)
str->data = OPENSSL_malloc(len + 1);
else
str->data = OPENSSL_realloc(c, len + 1);
int ASN1_STRING_type(const ASN1_STRING *str) { return str->type; }
if (str->data == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
str->data = c;
return (0);
}
}
str->length = len;
if (data != NULL) {
OPENSSL_memcpy(str->data, data, len);
/* an allowance for strings :-) */
str->data[len] = '\0';
}
return (1);
}
void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len)
{
if (str->data)
OPENSSL_free(str->data);
str->data = data;
str->length = len;
}
ASN1_STRING *ASN1_STRING_new(void)
{
return (ASN1_STRING_type_new(V_ASN1_OCTET_STRING));
}
ASN1_STRING *ASN1_STRING_type_new(int type)
{
ASN1_STRING *ret;
ret = (ASN1_STRING *)OPENSSL_malloc(sizeof(ASN1_STRING));
if (ret == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return (NULL);
}
ret->length = 0;
ret->type = type;
ret->data = NULL;
ret->flags = 0;
return (ret);
}
void ASN1_STRING_free(ASN1_STRING *a)
{
if (a == NULL)
return;
if (a->data && !(a->flags & ASN1_STRING_FLAG_NDEF))
OPENSSL_free(a->data);
OPENSSL_free(a);
}
int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b)
{
int i;
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);
}
int ASN1_STRING_length(const ASN1_STRING *x)
{
return M_ASN1_STRING_length(x);
}
int ASN1_STRING_type(const ASN1_STRING *x)
{
return M_ASN1_STRING_type(x);
}
unsigned char *ASN1_STRING_data(ASN1_STRING *x)
{
return M_ASN1_STRING_data(x);
}
const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *x)
{
return x->data;
unsigned char *ASN1_STRING_data(ASN1_STRING *str) { return str->data; }
const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *str) {
return str->data;
}
@@ -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 */
+41 -18
View File
@@ -57,24 +57,47 @@
#include <CCryptoBoringSSL_asn1.h>
const char *ASN1_tag2str(int tag)
{
static const char *const tag2str[] = {
"EOC", "BOOLEAN", "INTEGER", "BIT STRING", "OCTET STRING", /* 0-4 */
"NULL", "OBJECT", "OBJECT DESCRIPTOR", "EXTERNAL", "REAL", /* 5-9 */
"ENUMERATED", "<ASN1 11>", "UTF8STRING", "<ASN1 13>", /* 10-13 */
"<ASN1 14>", "<ASN1 15>", "SEQUENCE", "SET", /* 15-17 */
"NUMERICSTRING", "PRINTABLESTRING", "T61STRING", /* 18-20 */
"VIDEOTEXSTRING", "IA5STRING", "UTCTIME", "GENERALIZEDTIME", /* 21-24
*/
"GRAPHICSTRING", "VISIBLESTRING", "GENERALSTRING", /* 25-27 */
"UNIVERSALSTRING", "<ASN1 29>", "BMPSTRING" /* 28-30 */
};
const char *ASN1_tag2str(int tag) {
static const char *const tag2str[] = {
"EOC",
"BOOLEAN",
"INTEGER",
"BIT STRING",
"OCTET STRING",
"NULL",
"OBJECT",
"OBJECT DESCRIPTOR",
"EXTERNAL",
"REAL",
"ENUMERATED",
"<ASN1 11>",
"UTF8STRING",
"<ASN1 13>",
"<ASN1 14>",
"<ASN1 15>",
"SEQUENCE",
"SET",
"NUMERICSTRING",
"PRINTABLESTRING",
"T61STRING",
"VIDEOTEXSTRING",
"IA5STRING",
"UTCTIME",
"GENERALIZEDTIME",
"GRAPHICSTRING",
"VISIBLESTRING",
"GENERALSTRING",
"UNIVERSALSTRING",
"<ASN1 29>",
"BMPSTRING",
};
if ((tag == V_ASN1_NEG_INTEGER) || (tag == V_ASN1_NEG_ENUMERATED))
tag &= ~0x100;
if ((tag == V_ASN1_NEG_INTEGER) || (tag == V_ASN1_NEG_ENUMERATED)) {
tag &= ~V_ASN1_NEG;
}
if (tag < 0 || tag > 30)
return "(unknown)";
return tag2str[tag];
if (tag < 0 || tag > 30) {
return "(unknown)";
}
return tag2str[tag];
}
+30 -37
View File
@@ -59,47 +59,40 @@
#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 *octmp;
ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, ASN1_STRING **out) {
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 (!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;
ASN1_STRING *ret = NULL;
if (out == NULL || *out == NULL) {
ret = ASN1_STRING_new();
if (ret == NULL) {
OPENSSL_free(new_data);
return NULL;
}
} else {
ret = *out;
}
if (!(octmp->length = ASN1_item_i2d(obj, &octmp->data, it))) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ENCODE_ERROR);
return NULL;
}
if (!octmp->data) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return NULL;
}
return octmp;
ASN1_STRING_set0(ret, new_data, len);
if (out != NULL) {
*out = ret;
}
return ret;
}
/* Extract an ASN1 object from an ASN1_STRING */
void *ASN1_item_unpack(const 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);
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;
}
+38 -30
View File
@@ -58,40 +58,48 @@
#include <CCryptoBoringSSL_bio.h>
int i2a_ASN1_INTEGER(BIO *bp, const ASN1_INTEGER *a)
{
int i, n = 0;
static const char *h = "0123456789ABCDEF";
char buf[2];
int i2a_ASN1_INTEGER(BIO *bp, const ASN1_INTEGER *a) {
int i, n = 0;
static const char *h = "0123456789ABCDEF";
char buf[2];
if (a == NULL)
return (0);
if (a == NULL) {
return 0;
}
if (a->type & V_ASN1_NEG) {
if (BIO_write(bp, "-", 1) != 1)
goto err;
n = 1;
if (a->type & V_ASN1_NEG) {
if (BIO_write(bp, "-", 1) != 1) {
goto err;
}
n = 1;
}
if (a->length == 0) {
if (BIO_write(bp, "00", 2) != 2)
goto err;
n += 2;
} else {
for (i = 0; i < a->length; i++) {
if ((i != 0) && (i % 35 == 0)) {
if (BIO_write(bp, "\\\n", 2) != 2)
goto err;
n += 2;
}
buf[0] = h[((unsigned char)a->data[i] >> 4) & 0x0f];
buf[1] = h[((unsigned char)a->data[i]) & 0x0f];
if (BIO_write(bp, buf, 2) != 2)
goto err;
n += 2;
if (a->length == 0) {
if (BIO_write(bp, "00", 2) != 2) {
goto err;
}
n += 2;
} else {
for (i = 0; i < a->length; i++) {
if ((i != 0) && (i % 35 == 0)) {
if (BIO_write(bp, "\\\n", 2) != 2) {
goto err;
}
n += 2;
}
buf[0] = h[((unsigned char)a->data[i] >> 4) & 0x0f];
buf[1] = h[((unsigned char)a->data[i]) & 0x0f];
if (BIO_write(bp, buf, 2) != 2) {
goto err;
}
n += 2;
}
return (n);
err:
return (-1);
}
return n;
err:
return -1;
}
int i2a_ASN1_ENUMERATED(BIO *bp, const ASN1_ENUMERATED *a) {
return i2a_ASN1_INTEGER(bp, a);
}
+30 -27
View File
@@ -58,34 +58,37 @@
#include <CCryptoBoringSSL_bio.h>
int i2a_ASN1_STRING(BIO *bp, const ASN1_STRING *a, int type)
{
int i, n = 0;
static const char *h = "0123456789ABCDEF";
char buf[2];
int i2a_ASN1_STRING(BIO *bp, const ASN1_STRING *a, int type) {
int i, n = 0;
static const char *h = "0123456789ABCDEF";
char buf[2];
if (a == NULL)
return (0);
if (a == NULL) {
return 0;
}
if (a->length == 0) {
if (BIO_write(bp, "0", 1) != 1)
goto err;
n = 1;
} else {
for (i = 0; i < a->length; i++) {
if ((i != 0) && (i % 35 == 0)) {
if (BIO_write(bp, "\\\n", 2) != 2)
goto err;
n += 2;
}
buf[0] = h[((unsigned char)a->data[i] >> 4) & 0x0f];
buf[1] = h[((unsigned char)a->data[i]) & 0x0f];
if (BIO_write(bp, buf, 2) != 2)
goto err;
n += 2;
}
if (a->length == 0) {
if (BIO_write(bp, "0", 1) != 1) {
goto err;
}
return (n);
err:
return (-1);
n = 1;
} else {
for (i = 0; i < a->length; i++) {
if ((i != 0) && (i % 35 == 0)) {
if (BIO_write(bp, "\\\n", 2) != 2) {
goto err;
}
n += 2;
}
buf[0] = h[((unsigned char)a->data[i] >> 4) & 0x0f];
buf[1] = h[((unsigned char)a->data[i]) & 0x0f];
if (BIO_write(bp, buf, 2) != 2) {
goto err;
}
n += 2;
}
}
return n;
err:
return -1;
}
@@ -0,0 +1,272 @@
/*
* 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_INTERNAL_H
#define OPENSSL_HEADER_ASN1_INTERNAL_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 converts a time_t value in |time| which must be in the range
// of year 0000 to 9999 to a broken out time value in |tm|. On success |tm| is
// returned. On failure NULL is returned.
OPENSSL_EXPORT struct tm *OPENSSL_gmtime(const time_t *time, struct tm *result);
// OPENSSL_timegm converts a time value between the years 0 and 9999 in |tm| to
// a time_t value in |out|. One is returned on success, zero is returned on
// failure. It is a failure if the converted time can not be represented in a
// time_t, or if the tm contains out of range values.
OPENSSL_EXPORT int OPENSSL_timegm(const struct tm *tm, time_t *out);
// OPENSSL_gmtime_adj returns one on success, and updates |tm| by adding
// |offset_day| days and |offset_sec| seconds. It returns zero on failure. |tm|
// must be in the range of year 0000 to 9999 both before and after the update or
// a failure will be returned.
OPENSSL_EXPORT int OPENSSL_gmtime_adj(struct tm *tm, int offset_day,
long offset_sec);
// OPENSSL_gmtime_diff calculates the difference between |from| and |to|. It
// returns one, and outputs the difference as a number of days and seconds in
// |*out_days| and |*out_secs| on success. It returns zero on failure. Both
// |from| and |to| must be in the range of year 0000 to 9999 or a failure will
// be returned.
OPENSSL_EXPORT int OPENSSL_gmtime_diff(int *out_days, int *out_secs,
const struct tm *from,
const struct tm *to);
// Internal ASN1 structures and functions: not for application use
// 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 is used to save the received encoding of an ASN.1 type. This
// avoids problems with invalid encodings that break signatures.
typedef struct ASN1_ENCODING_st {
// enc is the saved DER encoding. Its ownership is determined by |buf|.
uint8_t *enc;
// len is the length of |enc|. If zero, there is no saved encoding.
size_t len;
// buf, if non-NULL, is the |CRYPTO_BUFFER| that |enc| points into. If NULL,
// |enc| must be released with |OPENSSL_free|.
CRYPTO_BUFFER *buf;
} ASN1_ENCODING;
OPENSSL_EXPORT int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d,
int allow_timezone_offset);
OPENSSL_EXPORT int asn1_generalizedtime_to_tm(struct tm *tm,
const ASN1_GENERALIZEDTIME *d);
int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it);
void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
void ASN1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt);
// ASN1_item_ex_d2i parses |len| bytes from |*in| as a structure of type |it|
// and writes the result to |*pval|. If |tag| is non-negative, |it| is
// implicitly tagged with the tag specified by |tag| and |aclass|. If |opt| is
// non-zero, the value is optional. If |buf| is non-NULL, |*in| must point into
// |buf|.
//
// This function returns one and advances |*in| if an object was successfully
// parsed, -1 if an optional value was successfully skipped, and zero on error.
int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
const ASN1_ITEM *it, int tag, int aclass, char opt,
CRYPTO_BUFFER *buf);
// ASN1_item_ex_i2d encodes |*pval| as a value of type |it| to |out| under the
// i2d output convention. It returns a non-zero length on success and -1 on
// error. If |tag| is -1. the tag and class come from |it|. Otherwise, the tag
// number is |tag| and the class is |aclass|. This is used for implicit tagging.
// This function treats a missing value as an error, not an optional field.
int ASN1_item_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass);
void ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
// asn1_get_choice_selector returns the CHOICE selector value for |*pval|, which
// must of type |it|.
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);
// asn1_enc_save saves |inlen| bytes from |in| as |*pval|'s saved encoding. It
// returns one on success and zero on error. If |buf| is non-NULL, |in| must
// point into |buf|.
int asn1_enc_save(ASN1_VALUE **pval, const uint8_t *in, size_t inlen,
const ASN1_ITEM *it, CRYPTO_BUFFER *buf);
// asn1_encoding_clear clears the cached encoding in |enc|.
void asn1_encoding_clear(ASN1_ENCODING *enc);
// asn1_type_value_as_pointer returns |a|'s value in pointer form. This is
// usually the value object but, for BOOLEAN values, is 0 or 0xff cast to
// a pointer.
const void *asn1_type_value_as_pointer(const ASN1_TYPE *a);
// asn1_type_set0_string sets |a|'s value to the object represented by |str| and
// takes ownership of |str|.
void asn1_type_set0_string(ASN1_TYPE *a, ASN1_STRING *str);
// asn1_type_cleanup releases memory associated with |a|'s value, without
// freeing |a| itself.
void asn1_type_cleanup(ASN1_TYPE *a);
// asn1_is_printable returns one if |value| is a valid Unicode codepoint for an
// ASN.1 PrintableString, and zero otherwise.
int asn1_is_printable(uint32_t value);
// asn1_bit_string_length returns the number of bytes in |str| and sets
// |*out_padding_bits| to the number of padding bits.
//
// This function should be used instead of |ASN1_STRING_length| to correctly
// handle the non-|ASN1_STRING_FLAG_BITS_LEFT| case.
int asn1_bit_string_length(const ASN1_BIT_STRING *str,
uint8_t *out_padding_bits);
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);
typedef ASN1_VALUE *ASN1_new_func(void);
typedef void ASN1_free_func(ASN1_VALUE *a);
typedef ASN1_VALUE *ASN1_d2i_func(ASN1_VALUE **a, const unsigned char **in,
long length);
typedef int ASN1_i2d_func(ASN1_VALUE *a, unsigned char **in);
typedef int ASN1_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
const ASN1_ITEM *it, int opt, ASN1_TLC *ctx);
typedef int ASN1_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it);
typedef int ASN1_ex_new_func(ASN1_VALUE **pval, const ASN1_ITEM *it);
typedef void ASN1_ex_free_func(ASN1_VALUE **pval, const ASN1_ITEM *it);
typedef struct ASN1_EXTERN_FUNCS_st {
ASN1_ex_new_func *asn1_ex_new;
ASN1_ex_free_func *asn1_ex_free;
ASN1_ex_d2i *asn1_ex_d2i;
ASN1_ex_i2d *asn1_ex_i2d;
} ASN1_EXTERN_FUNCS;
#if defined(__cplusplus)
} // extern C
#endif
#endif // OPENSSL_HEADER_ASN1_INTERNAL_H
@@ -0,0 +1,230 @@
/* Copyright (c) 2022, 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. */
// Time conversion to/from POSIX time_t and struct tm, with no support
// for time zones other than UTC
#include <CCryptoBoringSSL_time.h>
#include <assert.h>
#include <inttypes.h>
#include <limits.h>
#include <string.h>
#include <time.h>
#include "internal.h"
#define SECS_PER_HOUR (60 * 60)
#define SECS_PER_DAY (24 * SECS_PER_HOUR)
// Is a year/month/day combination valid, in the range from year 0000
// to 9999?
static int is_valid_date(int year, int month, int day) {
if (day < 1 || month < 1 || year < 0 || year > 9999) {
return 0;
}
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return day > 0 && day <= 31;
case 4:
case 6:
case 9:
case 11:
return day > 0 && day <= 30;
case 2:
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return day > 0 && day <= 29;
} else {
return day > 0 && day <= 28;
}
default:
return 0;
}
}
// Is a time valid? Leap seconds of 60 are not considered valid, as
// the POSIX time in seconds does not include them.
static int is_valid_time(int hours, int minutes, int seconds) {
if (hours < 0 || minutes < 0 || seconds < 0 || hours > 23 || minutes > 59 ||
seconds > 59) {
return 0;
}
return 1;
}
// Is a int64 time representing a time within our expected range?
static int is_valid_epoch_time(int64_t time) {
// 0000-01-01 00:00:00 UTC to 9999-12-31 23:59:59 UTC
return (int64_t)-62167219200 <= time && time <= (int64_t)253402300799;
}
// Inspired by algorithms presented in
// https://howardhinnant.github.io/date_algorithms.html
// (Public Domain)
static int posix_time_from_utc(int year, int month, int day, int hours,
int minutes, int seconds, int64_t *out_time) {
if (!is_valid_date(year, month, day) ||
!is_valid_time(hours, minutes, seconds)) {
return 0;
}
if (month <= 2) {
year--; // Start years on Mar 1, so leap days always finish a year.
}
// At this point year will be in the range -1 and 9999.
assert(-1 <= year && year <= 9999);
int64_t era = (year >= 0 ? year : year - 399) / 400;
int64_t year_of_era = year - era * 400;
int64_t day_of_year =
(153 * (month > 2 ? month - 3 : month + 9) + 2) / 5 + day - 1;
int64_t day_of_era =
year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
int64_t posix_days = era * 146097 + day_of_era - 719468;
*out_time = posix_days * SECS_PER_DAY + hours * SECS_PER_HOUR + minutes * 60 +
seconds;
return 1;
}
// Inspired by algorithms presented in
// https://howardhinnant.github.io/date_algorithms.html
// (Public Domain)
static int utc_from_posix_time(int64_t time, int *out_year, int *out_month,
int *out_day, int *out_hours, int *out_minutes,
int *out_seconds) {
if (!is_valid_epoch_time(time)) {
return 0;
}
int64_t days = time / SECS_PER_DAY;
int64_t leftover_seconds = time % SECS_PER_DAY;
if (leftover_seconds < 0) {
days--;
leftover_seconds += SECS_PER_DAY;
}
days += 719468; // Shift to starting epoch of Mar 1 0000.
// At this point, days will be in the range -61 and 3652364.
assert(-61 <= days && days <= 3652364);
int64_t era = (days > 0 ? days : days - 146096) / 146097;
int64_t day_of_era = days - era * 146097;
int64_t year_of_era = (day_of_era - day_of_era / 1460 + day_of_era / 36524 -
day_of_era / 146096) /
365;
*out_year = (int)(year_of_era + era * 400); // Year starting on Mar 1.
int64_t day_of_year =
day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
int64_t month_of_year = (5 * day_of_year + 2) / 153;
*out_month =
(int)(month_of_year < 10 ? month_of_year + 3 : month_of_year - 9);
if (*out_month <= 2) {
(*out_year)++; // Adjust year back to Jan 1 start of year.
}
*out_day = (int)(day_of_year - (153 * month_of_year + 2) / 5 + 1);
*out_hours = (int)(leftover_seconds / SECS_PER_HOUR);
leftover_seconds %= SECS_PER_HOUR;
*out_minutes = (int)(leftover_seconds / 60);
*out_seconds = (int)(leftover_seconds % 60);
return 1;
}
int OPENSSL_tm_to_posix(const struct tm *tm, int64_t *out) {
return posix_time_from_utc(tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec, out);
}
int OPENSSL_posix_to_tm(int64_t time, struct tm *out_tm) {
memset(out_tm, 0, sizeof(struct tm));
if (!utc_from_posix_time(time, &out_tm->tm_year, &out_tm->tm_mon,
&out_tm->tm_mday, &out_tm->tm_hour, &out_tm->tm_min,
&out_tm->tm_sec)) {
return 0;
}
out_tm->tm_year -= 1900;
out_tm->tm_mon -= 1;
return 1;
}
int OPENSSL_timegm(const struct tm *tm, time_t *out) {
static_assert(
sizeof(time_t) == sizeof(int32_t) || sizeof(time_t) == sizeof(int64_t),
"time_t is broken");
int64_t posix_time;
if (!OPENSSL_tm_to_posix(tm, &posix_time)) {
return 0;
}
if (sizeof(time_t) == sizeof(int32_t) &&
(posix_time > INT32_MAX || posix_time < INT32_MIN)) {
return 0;
}
*out = (time_t)posix_time;
return 1;
}
struct tm *OPENSSL_gmtime(const time_t *time, struct tm *out_tm) {
static_assert(
sizeof(time_t) == sizeof(int32_t) || sizeof(time_t) == sizeof(int64_t),
"time_t is broken");
int64_t posix_time = *time;
if (!OPENSSL_posix_to_tm(posix_time, out_tm)) {
return NULL;
}
return out_tm;
}
int OPENSSL_gmtime_adj(struct tm *tm, int off_day, long offset_sec) {
int64_t posix_time;
if (!posix_time_from_utc(tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec, &posix_time)) {
return 0;
}
if (!utc_from_posix_time(
posix_time + (int64_t)off_day * SECS_PER_DAY + offset_sec,
&tm->tm_year, &tm->tm_mon, &tm->tm_mday, &tm->tm_hour, &tm->tm_min,
&tm->tm_sec)) {
return 0;
}
tm->tm_year -= 1900;
tm->tm_mon -= 1;
return 1;
}
int OPENSSL_gmtime_diff(int *out_days, int *out_secs, const struct tm *from,
const struct tm *to) {
int64_t time_to;
if (!posix_time_from_utc(to->tm_year + 1900, to->tm_mon + 1, to->tm_mday,
to->tm_hour, to->tm_min, to->tm_sec, &time_to)) {
return 0;
}
int64_t time_from;
if (!posix_time_from_utc(from->tm_year + 1900, from->tm_mon + 1,
from->tm_mday, from->tm_hour, from->tm_min,
from->tm_sec, &time_from)) {
return 0;
}
int64_t timediff = time_to - time_from;
int64_t daydiff = timediff / SECS_PER_DAY;
timediff %= SECS_PER_DAY;
if (daydiff > INT_MAX || daydiff < INT_MIN) {
return 0;
}
*out_secs = (int)timediff;
*out_days = (int)daydiff;
return 1;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+119 -151
View File
@@ -56,189 +56,157 @@
#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 */
// Free up an ASN1 structure
void ASN1_item_free(ASN1_VALUE *val, const ASN1_ITEM *it)
{
asn1_item_combine_free(&val, it, 0);
void ASN1_item_free(ASN1_VALUE *val, const ASN1_ITEM *it) {
ASN1_item_ex_free(&val, it);
}
void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
asn1_item_combine_free(pval, it, 0);
}
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) {
void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
const ASN1_TEMPLATE *tt = NULL, *seqtt;
const ASN1_EXTERN_FUNCS *ef;
int i;
if (!pval) {
return;
}
if ((it->itype != ASN1_ITYPE_PRIMITIVE) && !*pval) {
return;
}
switch (it->itype) {
case ASN1_ITYPE_PRIMITIVE:
if (it->templates)
ASN1_template_free(pval, it->templates);
else
ASN1_primitive_free(pval, it);
break;
if (it->templates) {
ASN1_template_free(pval, it->templates);
} else {
ASN1_primitive_free(pval, it);
}
break;
case ASN1_ITYPE_MSTRING:
ASN1_primitive_free(pval, it);
break;
ASN1_primitive_free(pval, it);
break;
case ASN1_ITYPE_CHOICE:
if (asn1_cb) {
i = asn1_cb(ASN1_OP_FREE_PRE, pval, it, NULL);
if (i == 2)
return;
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) {
return;
}
i = asn1_get_choice_selector(pval, it);
if ((i >= 0) && (i < it->tcount)) {
ASN1_VALUE **pchval;
tt = it->templates + i;
pchval = asn1_get_field_ptr(pval, tt);
ASN1_template_free(pchval, tt);
}
if (asn1_cb)
asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL);
if (!combine) {
OPENSSL_free(*pval);
*pval = NULL;
}
break;
case ASN1_ITYPE_COMPAT:
cf = it->funcs;
if (cf && cf->asn1_free)
cf->asn1_free(*pval);
break;
}
i = asn1_get_choice_selector(pval, it);
if ((i >= 0) && (i < it->tcount)) {
ASN1_VALUE **pchval;
tt = it->templates + i;
pchval = asn1_get_field_ptr(pval, tt);
ASN1_template_free(pchval, tt);
}
if (asn1_cb) {
asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL);
}
OPENSSL_free(*pval);
*pval = NULL;
break;
}
case ASN1_ITYPE_EXTERN:
ef = it->funcs;
if (ef && ef->asn1_ex_free)
ef->asn1_ex_free(pval, it);
break;
ef = it->funcs;
if (ef && ef->asn1_ex_free) {
ef->asn1_ex_free(pval, it);
}
break;
case ASN1_ITYPE_NDEF_SEQUENCE:
case ASN1_ITYPE_SEQUENCE:
if (!asn1_refcount_dec_and_test_zero(pval, it))
return;
if (asn1_cb) {
i = asn1_cb(ASN1_OP_FREE_PRE, pval, it, NULL);
if (i == 2)
return;
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) {
return;
}
asn1_enc_free(pval, it);
/*
* If we free up as normal we will invalidate any ANY DEFINED BY
* field and we wont be able to determine the type of the field it
* defines. So free up in reverse order.
*/
tt = it->templates + it->tcount - 1;
for (i = 0; i < it->tcount; tt--, i++) {
ASN1_VALUE **pseqval;
seqtt = asn1_do_adb(pval, tt, 0);
if (!seqtt)
continue;
pseqval = asn1_get_field_ptr(pval, seqtt);
ASN1_template_free(pseqval, seqtt);
}
asn1_enc_free(pval, it);
// If we free up as normal we will invalidate any ANY DEFINED BY
// field and we wont be able to determine the type of the field it
// defines. So free up in reverse order.
tt = it->templates + it->tcount - 1;
for (i = 0; i < it->tcount; tt--, i++) {
ASN1_VALUE **pseqval;
seqtt = asn1_do_adb(pval, tt, 0);
if (!seqtt) {
continue;
}
if (asn1_cb)
asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL);
if (!combine) {
OPENSSL_free(*pval);
*pval = NULL;
}
break;
pseqval = asn1_get_field_ptr(pval, seqtt);
ASN1_template_free(pseqval, seqtt);
}
if (asn1_cb) {
asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL);
}
OPENSSL_free(*pval);
*pval = NULL;
break;
}
}
}
void ASN1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt)
{
size_t i;
if (tt->flags & ASN1_TFLG_SK_MASK) {
STACK_OF(ASN1_VALUE) *sk = (STACK_OF(ASN1_VALUE) *)*pval;
for (i = 0; i < sk_ASN1_VALUE_num(sk); i++) {
ASN1_VALUE *vtmp;
vtmp = sk_ASN1_VALUE_value(sk, i);
asn1_item_combine_free(&vtmp, ASN1_ITEM_ptr(tt->item), 0);
}
sk_ASN1_VALUE_free(sk);
*pval = NULL;
} else
asn1_item_combine_free(pval, ASN1_ITEM_ptr(tt->item),
tt->flags & ASN1_TFLG_COMBINE);
void ASN1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) {
if (tt->flags & ASN1_TFLG_SK_MASK) {
STACK_OF(ASN1_VALUE) *sk = (STACK_OF(ASN1_VALUE) *)*pval;
for (size_t i = 0; i < sk_ASN1_VALUE_num(sk); i++) {
ASN1_VALUE *vtmp = sk_ASN1_VALUE_value(sk, i);
ASN1_item_ex_free(&vtmp, ASN1_ITEM_ptr(tt->item));
}
sk_ASN1_VALUE_free(sk);
*pval = NULL;
} else {
ASN1_item_ex_free(pval, ASN1_ITEM_ptr(tt->item));
}
}
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;
}
}
/* 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)
return;
} else if (it->itype == ASN1_ITYPE_MSTRING) {
utype = -1;
if (!*pval)
return;
} else {
utype = it->utype;
if ((utype != V_ASN1_BOOLEAN) && !*pval)
return;
}
void ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
// Historically, |it->funcs| for primitive types contained an
// |ASN1_PRIMITIVE_FUNCS| table of calbacks.
assert(it->funcs == NULL);
switch (utype) {
int utype = it->itype == ASN1_ITYPE_MSTRING ? -1 : it->utype;
switch (utype) {
case V_ASN1_OBJECT:
ASN1_OBJECT_free((ASN1_OBJECT *)*pval);
break;
ASN1_OBJECT_free((ASN1_OBJECT *)*pval);
break;
case V_ASN1_BOOLEAN:
if (it)
*(ASN1_BOOLEAN *)pval = it->size;
else
*(ASN1_BOOLEAN *)pval = -1;
return;
if (it) {
*(ASN1_BOOLEAN *)pval = (ASN1_BOOLEAN)it->size;
} else {
*(ASN1_BOOLEAN *)pval = ASN1_BOOLEAN_NONE;
}
return;
case V_ASN1_NULL:
break;
break;
case V_ASN1_ANY:
ASN1_primitive_free(pval, NULL);
if (*pval != NULL) {
asn1_type_cleanup((ASN1_TYPE *)*pval);
OPENSSL_free(*pval);
break;
}
break;
default:
ASN1_STRING_free((ASN1_STRING *)*pval);
*pval = NULL;
break;
}
*pval = NULL;
ASN1_STRING_free((ASN1_STRING *)*pval);
*pval = NULL;
break;
}
*pval = NULL;
}
+225 -295
View File
@@ -63,325 +63,255 @@
#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)
{
ASN1_VALUE *ret = NULL;
if (ASN1_item_ex_new(&ret, it) > 0)
return ret;
return NULL;
}
/* Allocate an ASN1 structure */
int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
return asn1_item_ex_combine_new(pval, it, 0);
}
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) {
case ASN1_ITYPE_EXTERN:
ef = it->funcs;
if (ef && ef->asn1_ex_new) {
if (!ef->asn1_ex_new(pval, it))
goto memerr;
}
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))
goto memerr;
} else if (!ASN1_primitive_new(pval, it))
goto memerr;
break;
case ASN1_ITYPE_MSTRING:
if (!ASN1_primitive_new(pval, it))
goto memerr;
break;
case ASN1_ITYPE_CHOICE:
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;
}
}
if (!combine) {
*pval = OPENSSL_malloc(it->size);
if (!*pval)
goto memerr;
OPENSSL_memset(*pval, 0, it->size);
}
asn1_set_choice_selector(pval, -1, 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:
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;
}
}
if (!combine) {
*pval = OPENSSL_malloc(it->size);
if (!*pval)
goto memerr;
OPENSSL_memset(*pval, 0, it->size);
asn1_refcount_set_one(pval, it);
asn1_enc_init(pval, it);
}
for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) {
pseqval = asn1_get_field_ptr(pval, tt);
if (!ASN1_template_new(pseqval, tt))
goto memerr2;
}
if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, NULL))
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;
}
static void asn1_item_clear(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
const ASN1_EXTERN_FUNCS *ef;
switch (it->itype) {
case ASN1_ITYPE_EXTERN:
ef = it->funcs;
if (ef && ef->asn1_ex_clear)
ef->asn1_ex_clear(pval, it);
else
*pval = NULL;
break;
case ASN1_ITYPE_PRIMITIVE:
if (it->templates)
asn1_template_clear(pval, it->templates);
else
asn1_primitive_clear(pval, it);
break;
case ASN1_ITYPE_MSTRING:
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)
{
const ASN1_ITEM *it = ASN1_ITEM_ptr(tt->item);
int ret;
if (tt->flags & ASN1_TFLG_OPTIONAL) {
asn1_template_clear(pval, tt);
return 1;
}
/* If ANY DEFINED BY nothing to do */
if (tt->flags & ASN1_TFLG_ADB_MASK) {
*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;
skval = sk_ASN1_VALUE_new_null();
if (!skval) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
ret = 0;
goto done;
}
*pval = (ASN1_VALUE *)skval;
ret = 1;
goto done;
}
/* 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
ASN1_VALUE *ASN1_item_new(const ASN1_ITEM *it) {
ASN1_VALUE *ret = NULL;
if (ASN1_item_ex_new(&ret, it) > 0) {
return ret;
}
return NULL;
}
static void asn1_template_clear(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt)
{
/* If ADB or STACK just NULL the field */
if (tt->flags & (ASN1_TFLG_ADB_MASK | ASN1_TFLG_SK_MASK))
*pval = NULL;
else
asn1_item_clear(pval, ASN1_ITEM_ptr(tt->item));
}
// Allocate an ASN1 structure
/*
* NB: could probably combine most of the real XXX_new() behaviour and junk
* all the old functions.
*/
int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) {
const ASN1_TEMPLATE *tt = NULL;
const ASN1_EXTERN_FUNCS *ef;
ASN1_VALUE **pseqval;
int i;
int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
ASN1_TYPE *typ;
ASN1_STRING *str;
int utype;
switch (it->itype) {
case ASN1_ITYPE_EXTERN:
ef = it->funcs;
if (ef && ef->asn1_ex_new) {
if (!ef->asn1_ex_new(pval, it)) {
goto memerr;
}
}
break;
if (!it)
return 0;
case ASN1_ITYPE_PRIMITIVE:
if (it->templates) {
if (!ASN1_template_new(pval, it->templates)) {
goto memerr;
}
} else if (!ASN1_primitive_new(pval, it)) {
goto memerr;
}
break;
if (it->funcs) {
const ASN1_PRIMITIVE_FUNCS *pf = it->funcs;
if (pf->prim_new)
return pf->prim_new(pval, it);
case ASN1_ITYPE_MSTRING:
if (!ASN1_primitive_new(pval, it)) {
goto memerr;
}
break;
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) {
return 1;
}
}
*pval = OPENSSL_zalloc(it->size);
if (!*pval) {
goto memerr;
}
asn1_set_choice_selector(pval, -1, it);
if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, NULL)) {
goto auxerr2;
}
break;
}
if (it->itype == ASN1_ITYPE_MSTRING)
utype = -1;
else
utype = it->utype;
switch (utype) {
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) {
return 1;
}
}
*pval = OPENSSL_zalloc(it->size);
if (!*pval) {
goto memerr;
}
asn1_refcount_set_one(pval, it);
asn1_enc_init(pval, it);
for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) {
pseqval = asn1_get_field_ptr(pval, tt);
if (!ASN1_template_new(pseqval, tt)) {
goto memerr2;
}
}
if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, NULL)) {
goto auxerr2;
}
break;
}
}
return 1;
memerr2:
ASN1_item_ex_free(pval, it);
memerr:
return 0;
auxerr2:
ASN1_item_ex_free(pval, it);
auxerr:
OPENSSL_PUT_ERROR(ASN1, ASN1_R_AUX_ERROR);
return 0;
}
static void asn1_item_clear(ASN1_VALUE **pval, const ASN1_ITEM *it) {
switch (it->itype) {
case ASN1_ITYPE_EXTERN:
*pval = NULL;
break;
case ASN1_ITYPE_PRIMITIVE:
if (it->templates) {
asn1_template_clear(pval, it->templates);
} else {
asn1_primitive_clear(pval, it);
}
break;
case ASN1_ITYPE_MSTRING:
asn1_primitive_clear(pval, it);
break;
case ASN1_ITYPE_CHOICE:
case ASN1_ITYPE_SEQUENCE:
*pval = NULL;
break;
}
}
static int ASN1_template_new(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) {
const ASN1_ITEM *it = ASN1_ITEM_ptr(tt->item);
int ret;
if (tt->flags & ASN1_TFLG_OPTIONAL) {
asn1_template_clear(pval, tt);
return 1;
}
// If ANY DEFINED BY nothing to do
if (tt->flags & ASN1_TFLG_ADB_MASK) {
*pval = NULL;
return 1;
}
// If SET OF or SEQUENCE OF, its a STACK
if (tt->flags & ASN1_TFLG_SK_MASK) {
STACK_OF(ASN1_VALUE) *skval;
skval = sk_ASN1_VALUE_new_null();
if (!skval) {
ret = 0;
goto done;
}
*pval = (ASN1_VALUE *)skval;
ret = 1;
goto done;
}
// Otherwise pass it back to the item routine
ret = ASN1_item_ex_new(pval, it);
done:
return ret;
}
static void asn1_template_clear(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) {
// If ADB or STACK just NULL the field
if (tt->flags & (ASN1_TFLG_ADB_MASK | ASN1_TFLG_SK_MASK)) {
*pval = NULL;
} else {
asn1_item_clear(pval, ASN1_ITEM_ptr(tt->item));
}
}
// NB: could probably combine most of the real XXX_new() behaviour and junk
// all the old functions.
static int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it) {
if (!it) {
return 0;
}
// Historically, |it->funcs| for primitive types contained an
// |ASN1_PRIMITIVE_FUNCS| table of calbacks.
assert(it->funcs == NULL);
int utype;
if (it->itype == ASN1_ITYPE_MSTRING) {
utype = -1;
} else {
utype = it->utype;
}
switch (utype) {
case V_ASN1_OBJECT:
*pval = (ASN1_VALUE *)OBJ_nid2obj(NID_undef);
return 1;
*pval = (ASN1_VALUE *)OBJ_get_undef();
return 1;
case V_ASN1_BOOLEAN:
*(ASN1_BOOLEAN *)pval = it->size;
return 1;
*(ASN1_BOOLEAN *)pval = (ASN1_BOOLEAN)it->size;
return 1;
case V_ASN1_NULL:
*pval = (ASN1_VALUE *)1;
return 1;
*pval = (ASN1_VALUE *)1;
return 1;
case V_ASN1_ANY:
typ = OPENSSL_malloc(sizeof(ASN1_TYPE));
if (!typ)
return 0;
typ->value.ptr = NULL;
typ->type = -1;
*pval = (ASN1_VALUE *)typ;
break;
case V_ASN1_ANY: {
ASN1_TYPE *typ = OPENSSL_malloc(sizeof(ASN1_TYPE));
if (!typ) {
return 0;
}
typ->value.ptr = NULL;
typ->type = -1;
*pval = (ASN1_VALUE *)typ;
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;
break;
}
if (*pval)
return 1;
return 0;
*pval = (ASN1_VALUE *)ASN1_STRING_type_new(utype);
break;
}
if (*pval) {
return 1;
}
return 0;
}
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;
}
if (!it || (it->itype == ASN1_ITYPE_MSTRING))
utype = -1;
else
utype = it->utype;
if (utype == V_ASN1_BOOLEAN)
*(ASN1_BOOLEAN *)pval = it->size;
else
*pval = NULL;
static void asn1_primitive_clear(ASN1_VALUE **pval, const ASN1_ITEM *it) {
int utype;
// Historically, |it->funcs| for primitive types contained an
// |ASN1_PRIMITIVE_FUNCS| table of calbacks.
assert(it == NULL || it->funcs == NULL);
if (!it || (it->itype == ASN1_ITYPE_MSTRING)) {
utype = -1;
} else {
utype = it->utype;
}
if (utype == V_ASN1_BOOLEAN) {
*(ASN1_BOOLEAN *)pval = (ASN1_BOOLEAN)it->size;
} else {
*pval = NULL;
}
}
+27 -32
View File
@@ -58,19 +58,13 @@
#include <CCryptoBoringSSL_asn1t.h>
/* Declarations for string types */
// Declarations for string types
#define IMPLEMENT_ASN1_STRING_FUNCTIONS(sname) \
IMPLEMENT_ASN1_TYPE(sname) \
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(sname, sname, sname) \
sname *sname##_new(void) \
{ \
return ASN1_STRING_type_new(V_##sname); \
} \
void sname##_free(sname *x) \
{ \
ASN1_STRING_free(x); \
}
#define IMPLEMENT_ASN1_STRING_FUNCTIONS(sname) \
IMPLEMENT_ASN1_TYPE(sname) \
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(sname, sname, sname) \
sname *sname##_new(void) { return ASN1_STRING_type_new(V_##sname); } \
void sname##_free(sname *x) { ASN1_STRING_free(x); }
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_OCTET_STRING)
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_INTEGER)
@@ -88,44 +82,45 @@ 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)
IMPLEMENT_ASN1_TYPE(ASN1_ANY)
/* Just swallow an ASN1_SEQUENCE in an ASN1_STRING */
// 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 */
// 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)
IMPLEMENT_ASN1_TYPE_ex(ASN1_TBOOLEAN, ASN1_BOOLEAN, 1)
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)
// Three separate BOOLEAN type: normal, DEFAULT TRUE and DEFAULT FALSE
IMPLEMENT_ASN1_TYPE_ex(ASN1_BOOLEAN, ASN1_BOOLEAN, ASN1_BOOLEAN_NONE)
IMPLEMENT_ASN1_TYPE_ex(ASN1_TBOOLEAN, ASN1_BOOLEAN, ASN1_BOOLEAN_TRUE)
IMPLEMENT_ASN1_TYPE_ex(ASN1_FBOOLEAN, ASN1_BOOLEAN, ASN1_BOOLEAN_FALSE)
ASN1_ITEM_TEMPLATE(ASN1_SEQUENCE_ANY) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, ASN1_SEQUENCE_ANY, ASN1_ANY)
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, ASN1_SEQUENCE_ANY, ASN1_ANY)
ASN1_ITEM_TEMPLATE_END(ASN1_SEQUENCE_ANY)
ASN1_ITEM_TEMPLATE(ASN1_SET_ANY) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SET_OF, 0, ASN1_SET_ANY, ASN1_ANY)
ASN1_ITEM_TEMPLATE(ASN1_SET_ANY) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SET_OF, 0,
ASN1_SET_ANY, ASN1_ANY)
ASN1_ITEM_TEMPLATE_END(ASN1_SET_ANY)
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(ASN1_SEQUENCE_ANY, ASN1_SEQUENCE_ANY, ASN1_SEQUENCE_ANY)
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(ASN1_SEQUENCE_ANY, ASN1_SET_ANY, ASN1_SET_ANY)
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(ASN1_SEQUENCE_ANY,
ASN1_SEQUENCE_ANY,
ASN1_SEQUENCE_ANY)
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(ASN1_SEQUENCE_ANY, ASN1_SET_ANY,
ASN1_SET_ANY)
+58 -70
View File
@@ -60,26 +60,28 @@
#include <string.h>
#include <CCryptoBoringSSL_asn1t.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_obj.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_pool.h>
#include <CCryptoBoringSSL_thread.h>
#include "../internal.h"
#include "internal.h"
/* Utility functions for manipulating fields and offsets */
// Utility functions for manipulating fields and offsets
/* Add 'offset' to 'addr' */
// Add 'offset' to 'addr'
#define offset2ptr(addr, offset) (void *)(((char *)(addr)) + (offset))
/* Given an ASN1_ITEM CHOICE type return the selector value */
// Given an ASN1_ITEM CHOICE type return the selector value
int asn1_get_choice_selector(ASN1_VALUE **pval, const ASN1_ITEM *it) {
int *sel = offset2ptr(*pval, it->utype);
return *sel;
}
/* Given an ASN1_ITEM CHOICE type set the selector value, return old value. */
// Given an ASN1_ITEM CHOICE type set the selector value, return old value.
int asn1_set_choice_selector(ASN1_VALUE **pval, int value,
const ASN1_ITEM *it) {
int *sel, ret;
@@ -91,8 +93,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 +119,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;
@@ -130,68 +132,62 @@ static ASN1_ENCODING *asn1_get_enc_ptr(ASN1_VALUE **pval, const ASN1_ITEM *it) {
}
void asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it) {
ASN1_ENCODING *enc;
enc = asn1_get_enc_ptr(pval, it);
ASN1_ENCODING *enc = asn1_get_enc_ptr(pval, it);
if (enc) {
enc->enc = NULL;
enc->len = 0;
enc->alias_only = 0;
enc->alias_only_on_next_parse = 0;
enc->modified = 1;
enc->buf = NULL;
}
}
void asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
ASN1_ENCODING *enc;
enc = asn1_get_enc_ptr(pval, it);
ASN1_ENCODING *enc = asn1_get_enc_ptr(pval, it);
if (enc) {
if (enc->enc && !enc->alias_only) {
OPENSSL_free(enc->enc);
}
enc->enc = NULL;
enc->len = 0;
enc->alias_only = 0;
enc->alias_only_on_next_parse = 0;
enc->modified = 1;
asn1_encoding_clear(enc);
}
}
int asn1_enc_save(ASN1_VALUE **pval, const unsigned char *in, int inlen,
const ASN1_ITEM *it) {
int asn1_enc_save(ASN1_VALUE **pval, const uint8_t *in, size_t in_len,
const ASN1_ITEM *it, CRYPTO_BUFFER *buf) {
ASN1_ENCODING *enc;
enc = asn1_get_enc_ptr(pval, it);
if (!enc) {
return 1;
}
if (!enc->alias_only) {
OPENSSL_free(enc->enc);
}
enc->alias_only = enc->alias_only_on_next_parse;
enc->alias_only_on_next_parse = 0;
if (enc->alias_only) {
enc->enc = (uint8_t *) in;
asn1_encoding_clear(enc);
if (buf != NULL) {
assert(CRYPTO_BUFFER_data(buf) <= in &&
in + in_len <= CRYPTO_BUFFER_data(buf) + CRYPTO_BUFFER_len(buf));
CRYPTO_BUFFER_up_ref(buf);
enc->buf = buf;
enc->enc = (uint8_t *)in;
} else {
enc->enc = OPENSSL_malloc(inlen);
enc->enc = OPENSSL_memdup(in, in_len);
if (!enc->enc) {
return 0;
}
OPENSSL_memcpy(enc->enc, in, inlen);
}
enc->len = inlen;
enc->modified = 0;
enc->len = in_len;
return 1;
}
void asn1_encoding_clear(ASN1_ENCODING *enc) {
if (enc->buf != NULL) {
CRYPTO_BUFFER_free(enc->buf);
} else {
OPENSSL_free(enc->enc);
}
enc->enc = NULL;
enc->len = 0;
enc->buf = NULL;
}
int asn1_enc_restore(int *len, unsigned char **out, ASN1_VALUE **pval,
const ASN1_ITEM *it) {
ASN1_ENCODING *enc;
enc = asn1_get_enc_ptr(pval, it);
if (!enc || enc->modified) {
ASN1_ENCODING *enc = asn1_get_enc_ptr(pval, it);
if (!enc || enc->len == 0) {
return 0;
}
if (out) {
@@ -204,38 +200,33 @@ int asn1_enc_restore(int *len, unsigned char **out, ASN1_VALUE **pval,
return 1;
}
/* Given an ASN1_TEMPLATE get a pointer to a field */
// Given an ASN1_TEMPLATE get a pointer to a field
ASN1_VALUE **asn1_get_field_ptr(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) {
ASN1_VALUE **pvaltmp;
if (tt->flags & ASN1_TFLG_COMBINE) {
return pval;
}
pvaltmp = offset2ptr(*pval, tt->offset);
/* NOTE for BOOLEAN types the field is just a plain int so we can't return
* int **, so settle for (int *). */
ASN1_VALUE **pvaltmp = offset2ptr(*pval, tt->offset);
// NOTE for BOOLEAN types the field is just a plain int so we can't return
// int **, so settle for (int *).
return pvaltmp;
}
/* Handle ANY DEFINED BY template, find the selector, look up the relevant
* ASN1_TEMPLATE in the table and return it. */
// Handle ANY DEFINED BY template, find the selector, look up the relevant
// ASN1_TEMPLATE in the table and return it.
const ASN1_TEMPLATE *asn1_do_adb(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt,
int nullerr) {
const ASN1_ADB *adb;
const ASN1_ADB_TABLE *atbl;
long selector;
ASN1_VALUE **sfld;
int i;
if (!(tt->flags & ASN1_TFLG_ADB_MASK)) {
return tt;
}
/* Else ANY DEFINED BY ... get the table */
// Else ANY DEFINED BY ... get the table
adb = ASN1_ADB_ptr(tt->item);
/* Get the selector field */
// Get the selector field
sfld = offset2ptr(*pval, adb->offset);
/* Check if NULL */
// Check if NULL
if (*sfld == NULL) {
if (!adb->null_tt) {
goto err;
@@ -243,19 +234,16 @@ const ASN1_TEMPLATE *asn1_do_adb(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt,
return adb->null_tt;
}
/* Convert type to a long:
* NB: don't check for NID_undef here because it
* might be a legitimate value in the table */
if (tt->flags & ASN1_TFLG_ADB_OID) {
selector = OBJ_obj2nid((ASN1_OBJECT *)*sfld);
} else {
selector = ASN1_INTEGER_get((ASN1_INTEGER *)*sfld);
}
// Convert type to a NID:
// NB: don't check for NID_undef here because it
// might be a legitimate value in the table
assert(tt->flags & ASN1_TFLG_ADB_OID);
int selector = OBJ_obj2nid((ASN1_OBJECT *)*sfld);
/* Try to find matching entry in table Maybe should check application types
* first to allow application override? Might also be useful to have a flag
* which indicates table is sorted and we can do a binary search. For now
* stick to a linear search. */
// Try to find matching entry in table Maybe should check application types
// first to allow application override? Might also be useful to have a flag
// which indicates table is sorted and we can do a binary search. For now
// stick to a linear search.
for (atbl = adb->tbl, i = 0; i < adb->tblcount; i++, atbl++) {
if (atbl->value == selector) {
@@ -263,16 +251,16 @@ const ASN1_TEMPLATE *asn1_do_adb(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt,
}
}
/* FIXME: need to search application table too */
// FIXME: need to search application table too
/* No match, return default type */
// No match, return default type
if (!adb->default_tt) {
goto err;
}
return adb->default_tt;
err:
/* FIXME: should log the value or OID of unsupported type */
// FIXME: should log the value or OID of unsupported type
if (nullerr) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE);
}
@@ -1,206 +0,0 @@
/* Written by Richard Levitte (richard@levitte.org) for the OpenSSL
* project 2001.
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
* project 2008.
*/
/* ====================================================================
* Copyright (c) 2001 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). */
#if !defined(_POSIX_C_SOURCE)
#define _POSIX_C_SOURCE 201410L /* for gmtime_r */
#endif
#include "asn1_locl.h"
#include <time.h>
#define SECS_PER_DAY (24 * 60 * 60)
struct tm *OPENSSL_gmtime(const time_t *time, struct tm *result) {
#if defined(OPENSSL_WINDOWS)
if (gmtime_s(result, time)) {
return NULL;
}
return result;
#else
return gmtime_r(time, result);
#endif
}
/* Convert date to and from julian day Uses Fliegel & Van Flandern algorithm */
static long date_to_julian(int y, int m, int d) {
return (1461 * (y + 4800 + (m - 14) / 12)) / 4 +
(367 * (m - 2 - 12 * ((m - 14) / 12))) / 12 -
(3 * ((y + 4900 + (m - 14) / 12) / 100)) / 4 + d - 32075;
}
static void julian_to_date(long jd, int *y, int *m, int *d) {
long L = jd + 68569;
long n = (4 * L) / 146097;
long i, j;
L = L - (146097 * n + 3) / 4;
i = (4000 * (L + 1)) / 1461001;
L = L - (1461 * i) / 4 + 31;
j = (80 * L) / 2447;
*d = L - (2447 * j) / 80;
L = j / 11;
*m = j + 2 - (12 * L);
*y = 100 * (n - 49) + i + L;
}
/* Convert tm structure and offset into julian day and seconds */
static int julian_adj(const struct tm *tm, int off_day, long offset_sec,
long *pday, int *psec) {
int offset_hms, offset_day;
long time_jd;
int time_year, time_month, time_day;
/* split offset into days and day seconds */
offset_day = offset_sec / SECS_PER_DAY;
/* Avoid sign issues with % operator */
offset_hms = offset_sec - (offset_day * SECS_PER_DAY);
offset_day += off_day;
/* Add current time seconds to offset */
offset_hms += tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
/* Adjust day seconds if overflow */
if (offset_hms >= SECS_PER_DAY) {
offset_day++;
offset_hms -= SECS_PER_DAY;
} else if (offset_hms < 0) {
offset_day--;
offset_hms += SECS_PER_DAY;
}
/* Convert date of time structure into a Julian day number. */
time_year = tm->tm_year + 1900;
time_month = tm->tm_mon + 1;
time_day = tm->tm_mday;
time_jd = date_to_julian(time_year, time_month, time_day);
/* Work out Julian day of new date */
time_jd += offset_day;
if (time_jd < 0) {
return 0;
}
*pday = time_jd;
*psec = offset_hms;
return 1;
}
int OPENSSL_gmtime_adj(struct tm *tm, int off_day, long offset_sec) {
int time_sec, time_year, time_month, time_day;
long time_jd;
/* Convert time and offset into julian day and seconds */
if (!julian_adj(tm, off_day, offset_sec, &time_jd, &time_sec)) {
return 0;
}
/* Convert Julian day back to date */
julian_to_date(time_jd, &time_year, &time_month, &time_day);
if (time_year < 1900 || time_year > 9999) {
return 0;
}
/* Update tm structure */
tm->tm_year = time_year - 1900;
tm->tm_mon = time_month - 1;
tm->tm_mday = time_day;
tm->tm_hour = time_sec / 3600;
tm->tm_min = (time_sec / 60) % 60;
tm->tm_sec = time_sec % 60;
return 1;
}
int OPENSSL_gmtime_diff(int *out_days, int *out_secs, const struct tm *from,
const struct tm *to) {
int from_sec, to_sec, diff_sec;
long from_jd, to_jd, diff_day;
if (!julian_adj(from, 0, 0, &from_jd, &from_sec)) {
return 0;
}
if (!julian_adj(to, 0, 0, &to_jd, &to_sec)) {
return 0;
}
diff_day = to_jd - from_jd;
diff_sec = to_sec - from_sec;
/* Adjust differences so both positive or both negative */
if (diff_day > 0 && diff_sec < 0) {
diff_day--;
diff_sec += SECS_PER_DAY;
}
if (diff_day < 0 && diff_sec > 0) {
diff_day++;
diff_sec -= SECS_PER_DAY;
}
if (out_days) {
*out_days = (int)diff_day;
}
if (out_secs) {
*out_secs = diff_sec;
}
return 1;
}
+21 -12
View File
@@ -60,8 +60,6 @@
#include <limits.h>
#include <string.h>
#include <CCryptoBoringSSL_type_check.h>
#include "../internal.h"
@@ -98,8 +96,8 @@ static uint8_t conv_bin2ascii(uint8_t a) {
return ret;
}
OPENSSL_STATIC_ASSERT(sizeof(((EVP_ENCODE_CTX *)(NULL))->data) % 3 == 0,
"data length must be a multiple of base64 chunk size");
static_assert(sizeof(((EVP_ENCODE_CTX *)(NULL))->data) % 3 == 0,
"data length must be a multiple of base64 chunk size");
int EVP_EncodedLength(size_t *out_len, size_t len) {
if (len + 2 < len) {
@@ -122,6 +120,14 @@ int EVP_EncodedLength(size_t *out_len, size_t len) {
return 1;
}
EVP_ENCODE_CTX *EVP_ENCODE_CTX_new(void) {
return OPENSSL_zalloc(sizeof(EVP_ENCODE_CTX));
}
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 +271,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;
}
+49 -18
View File
@@ -69,17 +69,19 @@
#include "../internal.h"
static CRYPTO_EX_DATA_CLASS g_ex_data_class =
CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA;
BIO *BIO_new(const BIO_METHOD *method) {
BIO *ret = OPENSSL_malloc(sizeof(BIO));
BIO *ret = OPENSSL_zalloc(sizeof(BIO));
if (ret == NULL) {
OPENSSL_PUT_ERROR(BIO, ERR_R_MALLOC_FAILURE);
return NULL;
}
OPENSSL_memset(ret, 0, sizeof(BIO));
ret->method = method;
ret->shutdown = 1;
ret->references = 1;
CRYPTO_new_ex_data(&ret->ex_data);
if (method->create != NULL && !method->create(ret)) {
OPENSSL_free(ret);
@@ -103,6 +105,7 @@ int BIO_free(BIO *bio) {
bio->method->destroy(bio);
}
CRYPTO_free_ex_data(&g_ex_data_class, bio, &bio->ex_data);
OPENSSL_free(bio);
}
return 1;
@@ -192,11 +195,17 @@ int BIO_write_all(BIO *bio, const void *data, size_t len) {
}
int BIO_puts(BIO *bio, const char *in) {
return BIO_write(bio, in, strlen(in));
size_t len = strlen(in);
if (len > INT_MAX) {
// |BIO_write| and the return value both assume the string fits in |int|.
OPENSSL_PUT_ERROR(BIO, ERR_R_OVERFLOW);
return -1;
}
return BIO_write(bio, in, (int)len);
}
int BIO_flush(BIO *bio) {
return BIO_ctrl(bio, BIO_CTRL_FLUSH, 0, NULL);
return (int)BIO_ctrl(bio, BIO_CTRL_FLUSH, 0, NULL);
}
long BIO_ctrl(BIO *bio, int cmd, long larg, void *parg) {
@@ -229,11 +238,11 @@ long BIO_int_ctrl(BIO *b, int cmd, long larg, int iarg) {
}
int BIO_reset(BIO *bio) {
return BIO_ctrl(bio, BIO_CTRL_RESET, 0, NULL);
return (int)BIO_ctrl(bio, BIO_CTRL_RESET, 0, NULL);
}
int BIO_eof(BIO *bio) {
return BIO_ctrl(bio, BIO_CTRL_EOF, 0, NULL);
return (int)BIO_ctrl(bio, BIO_CTRL_EOF, 0, NULL);
}
void BIO_set_flags(BIO *bio, int flags) {
@@ -262,6 +271,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;
}
@@ -331,7 +342,7 @@ size_t BIO_wpending(const BIO *bio) {
}
int BIO_set_close(BIO *bio, int close_flag) {
return BIO_ctrl(bio, BIO_CTRL_SET_CLOSE, close_flag, NULL);
return (int)BIO_ctrl(bio, BIO_CTRL_SET_CLOSE, close_flag, NULL);
}
OPENSSL_EXPORT size_t BIO_number_read(const BIO *bio) {
@@ -416,7 +427,7 @@ int BIO_indent(BIO *bio, unsigned indent, unsigned max_indent) {
}
static int print_bio(const char *str, size_t len, void *bio) {
return BIO_write((BIO *)bio, str, len);
return BIO_write_all((BIO *)bio, str, len);
}
void ERR_print_errors(BIO *bio) {
@@ -455,9 +466,11 @@ static int bio_read_all(BIO *bio, uint8_t **out, size_t *out_len,
OPENSSL_free(*out);
return 0;
}
const size_t todo = len - done;
assert(todo < INT_MAX);
const int n = BIO_read(bio, *out + done, todo);
size_t todo = len - done;
if (todo > INT_MAX) {
todo = INT_MAX;
}
const int n = BIO_read(bio, *out + done, (int)todo);
if (n == 0) {
*out_len = done;
return 1;
@@ -601,7 +614,6 @@ int BIO_read_asn1(BIO *bio, uint8_t **out, size_t *out_len, size_t max_len) {
*out = OPENSSL_malloc(len);
if (*out == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return 0;
}
OPENSSL_memcpy(*out, header, header_len);
@@ -620,23 +632,22 @@ void BIO_set_retry_special(BIO *bio) {
int BIO_set_write_buffer_size(BIO *bio, int buffer_size) { return 0; }
static struct CRYPTO_STATIC_MUTEX g_index_lock = CRYPTO_STATIC_MUTEX_INIT;
static CRYPTO_MUTEX g_index_lock = CRYPTO_MUTEX_INIT;
static int g_index = BIO_TYPE_START;
int BIO_get_new_index(void) {
CRYPTO_STATIC_MUTEX_lock_write(&g_index_lock);
CRYPTO_MUTEX_lock_write(&g_index_lock);
// If |g_index| exceeds 255, it will collide with the flags bits.
int ret = g_index > 255 ? -1 : g_index++;
CRYPTO_STATIC_MUTEX_unlock_write(&g_index_lock);
CRYPTO_MUTEX_unlock_write(&g_index_lock);
return ret;
}
BIO_METHOD *BIO_meth_new(int type, const char *name) {
BIO_METHOD *method = OPENSSL_malloc(sizeof(BIO_METHOD));
BIO_METHOD *method = OPENSSL_zalloc(sizeof(BIO_METHOD));
if (method == NULL) {
return NULL;
}
OPENSSL_memset(method, 0, sizeof(BIO_METHOD));
method->type = type;
method->name = name;
return method;
@@ -698,3 +709,23 @@ int BIO_meth_set_puts(BIO_METHOD *method, int (*puts)(BIO *, const char *)) {
// Ignore the parameter. We implement |BIO_puts| using |BIO_write|.
return 1;
}
int BIO_get_ex_new_index(long argl, void *argp,
CRYPTO_EX_unused *unused,
CRYPTO_EX_dup *dup_unused,
CRYPTO_EX_free *free_func) {
int index;
if (!CRYPTO_get_ex_new_index(&g_ex_data_class, &index, argl, argp,
free_func)) {
return -1;
}
return index;
}
int BIO_set_ex_data(BIO *bio, int idx, void *data) {
return CRYPTO_set_ex_data(&bio->ex_data, idx, data);
}
void *BIO_get_ex_data(const BIO *bio, int idx) {
return CRYPTO_get_ex_data(&bio->ex_data, idx);
}
+44 -65
View File
@@ -66,7 +66,7 @@
#include "../internal.h"
BIO *BIO_new_mem_buf(const void *buf, int len) {
BIO *BIO_new_mem_buf(const void *buf, ossl_ssize_t len) {
BIO *ret;
BUF_MEM *b;
const size_t size = len < 0 ? strlen((char *)buf) : (size_t)len;
@@ -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;
}
@@ -136,13 +130,15 @@ static int mem_free(BIO *bio) {
}
static int mem_read(BIO *bio, char *out, int outl) {
int ret;
BUF_MEM *b = (BUF_MEM*) bio->ptr;
BIO_clear_retry_flags(bio);
ret = outl;
if (b->length < INT_MAX && ret > (int)b->length) {
ret = b->length;
if (outl <= 0) {
return 0;
}
BUF_MEM *b = bio->ptr;
int ret = outl;
if ((size_t)ret > b->length) {
ret = (int)b->length;
}
if (ret > 0) {
@@ -163,70 +159,53 @@ static int mem_read(BIO *bio, char *out, int outl) {
}
static int mem_write(BIO *bio, const char *in, int inl) {
int ret = -1;
int blen;
BUF_MEM *b;
b = (BUF_MEM *)bio->ptr;
BIO_clear_retry_flags(bio);
if (inl <= 0) {
return 0; // Successfully write zero bytes.
}
if (bio->flags & BIO_FLAGS_MEM_RDONLY) {
OPENSSL_PUT_ERROR(BIO, BIO_R_WRITE_TO_READ_ONLY_BIO);
goto err;
return -1;
}
BIO_clear_retry_flags(bio);
blen = b->length;
if (INT_MAX - blen < inl) {
goto err;
BUF_MEM *b = bio->ptr;
if (!BUF_MEM_append(b, in, inl)) {
return -1;
}
if (BUF_MEM_grow_clean(b, blen + inl) != ((size_t) blen) + inl) {
goto err;
}
OPENSSL_memcpy(&b->data[blen], in, inl);
ret = inl;
err:
return ret;
return inl;
}
static int mem_gets(BIO *bio, char *buf, int size) {
int i, j;
char *p;
BUF_MEM *b = (BUF_MEM *)bio->ptr;
BIO_clear_retry_flags(bio);
j = b->length;
if (size - 1 < j) {
j = size - 1;
}
if (j <= 0) {
if (size > 0) {
*buf = 0;
}
if (size <= 0) {
return 0;
}
p = b->data;
for (i = 0; i < j; i++) {
if (p[i] == '\n') {
i++;
break;
}
// The buffer size includes space for the trailing NUL, so we can read at most
// one fewer byte.
BUF_MEM *b = bio->ptr;
int ret = size - 1;
if ((size_t)ret > b->length) {
ret = (int)b->length;
}
// i is now the max num of bytes to copy, either j or up to and including the
// first newline
i = mem_read(bio, buf, i);
if (i > 0) {
buf[i] = '\0';
// Stop at the first newline.
const char *newline = OPENSSL_memchr(b->data, '\n', ret);
if (newline != NULL) {
ret = (int)(newline - b->data + 1);
}
return i;
ret = mem_read(bio, buf, ret);
if (ret >= 0) {
buf[ret] = '\0';
}
return ret;
}
static long mem_ctrl(BIO *bio, int cmd, long num, void *ptr) {
long ret = 1;
char **pptr;
BUF_MEM *b = (BUF_MEM *)bio->ptr;
@@ -252,8 +231,8 @@ static long mem_ctrl(BIO *bio, int cmd, long num, void *ptr) {
case BIO_CTRL_INFO:
ret = (long)b->length;
if (ptr != NULL) {
pptr = (char **)ptr;
*pptr = (char *)&b->data[0];
char **pptr = ptr;
*pptr = b->data;
}
break;
case BIO_C_SET_BUF_MEM:
@@ -263,8 +242,8 @@ static long mem_ctrl(BIO *bio, int cmd, long num, void *ptr) {
break;
case BIO_C_GET_BUF_MEM_PTR:
if (ptr != NULL) {
pptr = (char **)ptr;
*pptr = (char *)b;
BUF_MEM **pptr = ptr;
*pptr = b;
}
break;
case BIO_CTRL_GET_CLOSE:
@@ -314,17 +293,17 @@ int BIO_mem_contents(const BIO *bio, const uint8_t **out_contents,
}
long BIO_get_mem_data(BIO *bio, char **contents) {
return BIO_ctrl(bio, BIO_CTRL_INFO, 0, (char *) contents);
return BIO_ctrl(bio, BIO_CTRL_INFO, 0, contents);
}
int BIO_get_mem_ptr(BIO *bio, BUF_MEM **out) {
return BIO_ctrl(bio, BIO_C_GET_BUF_MEM_PTR, 0, (char *) out);
return (int)BIO_ctrl(bio, BIO_C_GET_BUF_MEM_PTR, 0, out);
}
int BIO_set_mem_buf(BIO *bio, BUF_MEM *b, int take_ownership) {
return BIO_ctrl(bio, BIO_C_SET_BUF_MEM, take_ownership, (char *) b);
return (int)BIO_ctrl(bio, BIO_C_SET_BUF_MEM, take_ownership, b);
}
int BIO_set_mem_eof_return(BIO *bio, int eof_value) {
return BIO_ctrl(bio, BIO_C_SET_BUF_MEM_EOF_RETURN, eof_value, NULL);
return (int)BIO_ctrl(bio, BIO_C_SET_BUF_MEM_EOF_RETURN, eof_value, NULL);
}
+24 -25
View File
@@ -56,7 +56,7 @@
#include <CCryptoBoringSSL_bio.h>
#if !defined(OPENSSL_TRUSTY)
#if !defined(OPENSSL_NO_SOCK)
#include <assert.h>
#include <errno.h>
@@ -117,7 +117,8 @@ static int closesocket(int sock) {
// split_host_and_port sets |*out_host| and |*out_port| to the host and port
// parsed from |name|. It returns one on success or zero on error. Even when
// successful, |*out_port| may be NULL on return if no port was specified.
static int split_host_and_port(char **out_host, char **out_port, const char *name) {
static int split_host_and_port(char **out_host, char **out_port,
const char *name) {
const char *host, *port = NULL;
size_t host_len = 0;
@@ -232,7 +233,7 @@ static int conn_state(BIO *bio, BIO_CONNECT *c) {
BIO_clear_retry_flags(bio);
ret = connect(bio->num, (struct sockaddr*) &c->them, c->them_length);
if (ret < 0) {
if (bio_fd_should_retry(ret)) {
if (bio_socket_should_retry(ret)) {
BIO_set_flags(bio, (BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY));
c->state = BIO_CONN_S_BLOCKED_CONNECT;
bio->retry_reason = BIO_RR_CONNECT;
@@ -251,7 +252,7 @@ static int conn_state(BIO *bio, BIO_CONNECT *c) {
case BIO_CONN_S_BLOCKED_CONNECT:
i = bio_sock_error(bio->num);
if (i) {
if (bio_fd_should_retry(ret)) {
if (bio_socket_should_retry(ret)) {
BIO_set_flags(bio, (BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY));
c->state = BIO_CONN_S_BLOCKED_CONNECT;
bio->retry_reason = BIO_RR_CONNECT;
@@ -295,13 +296,10 @@ end:
}
static BIO_CONNECT *BIO_CONNECT_new(void) {
BIO_CONNECT *ret = OPENSSL_malloc(sizeof(BIO_CONNECT));
BIO_CONNECT *ret = OPENSSL_zalloc(sizeof(BIO_CONNECT));
if (ret == NULL) {
return NULL;
}
OPENSSL_memset(ret, 0, sizeof(BIO_CONNECT));
ret->state = BIO_CONN_S_BEFORE;
return ret;
}
@@ -320,7 +318,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 +338,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);
}
@@ -366,10 +360,10 @@ static int conn_read(BIO *bio, char *out, int out_len) {
}
bio_clear_socket_error();
ret = recv(bio->num, out, out_len, 0);
ret = (int)recv(bio->num, out, out_len, 0);
BIO_clear_retry_flags(bio);
if (ret <= 0) {
if (bio_fd_should_retry(ret)) {
if (bio_socket_should_retry(ret)) {
BIO_set_retry_read(bio);
}
}
@@ -390,10 +384,10 @@ static int conn_write(BIO *bio, const char *in, int in_len) {
}
bio_clear_socket_error();
ret = send(bio->num, in, in_len, 0);
ret = (int)send(bio->num, in, in_len, 0);
BIO_clear_retry_flags(bio);
if (ret <= 0) {
if (bio_fd_should_retry(ret)) {
if (bio_socket_should_retry(ret)) {
BIO_set_retry_write(bio);
}
}
@@ -470,8 +464,7 @@ static long conn_ctrl(BIO *bio, int cmd, long num, void *ptr) {
case BIO_CTRL_FLUSH:
break;
case BIO_CTRL_GET_CALLBACK: {
int (**fptr)(const BIO *bio, int state, int xret);
fptr = (int (**)(const BIO *bio, int state, int xret))ptr;
int (**fptr)(const BIO *bio, int state, int xret) = ptr;
*fptr = data->info_callback;
} break;
default:
@@ -489,7 +482,13 @@ static long conn_callback_ctrl(BIO *bio, int cmd, bio_info_cb fp) {
switch (cmd) {
case BIO_CTRL_SET_CALLBACK:
// This is the actual type signature of |fp|. The caller is expected to
// cast it to |bio_info_cb| due to the |BIO_callback_ctrl| calling
// convention.
OPENSSL_MSVC_PRAGMA(warning(push))
OPENSSL_MSVC_PRAGMA(warning(disable : 4191))
data->info_callback = (int (*)(const struct bio_st *, int, int))fp;
OPENSSL_MSVC_PRAGMA(warning(pop))
break;
default:
ret = 0;
@@ -521,25 +520,25 @@ static const BIO_METHOD methods_connectp = {
const BIO_METHOD *BIO_s_connect(void) { return &methods_connectp; }
int BIO_set_conn_hostname(BIO *bio, const char *name) {
return BIO_ctrl(bio, BIO_C_SET_CONNECT, 0, (void*) name);
return (int)BIO_ctrl(bio, BIO_C_SET_CONNECT, 0, (void*) name);
}
int BIO_set_conn_port(BIO *bio, const char *port_str) {
return BIO_ctrl(bio, BIO_C_SET_CONNECT, 1, (void*) port_str);
return (int)BIO_ctrl(bio, BIO_C_SET_CONNECT, 1, (void*) port_str);
}
int BIO_set_conn_int_port(BIO *bio, const int *port) {
char buf[DECIMAL_SIZE(int) + 1];
BIO_snprintf(buf, sizeof(buf), "%d", *port);
snprintf(buf, sizeof(buf), "%d", *port);
return BIO_set_conn_port(bio, buf);
}
int BIO_set_nbio(BIO *bio, int on) {
return BIO_ctrl(bio, BIO_C_SET_NBIO, on, NULL);
return (int)BIO_ctrl(bio, BIO_C_SET_NBIO, on, NULL);
}
int BIO_do_connect(BIO *bio) {
return BIO_ctrl(bio, BIO_C_DO_STATE_MACHINE, 0, NULL);
return (int)BIO_ctrl(bio, BIO_C_DO_STATE_MACHINE, 0, NULL);
}
#endif // OPENSSL_TRUSTY
#endif // OPENSSL_NO_SOCK
@@ -54,40 +54,39 @@
* copied and put under another distribution licence
* [including the GNU Public Licence.] */
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_bio.h>
/* Based on a_int.c: equivalent ENUMERATED functions */
#include <errno.h>
int i2a_ASN1_ENUMERATED(BIO *bp, const ASN1_ENUMERATED *a)
{
int i, n = 0;
static const char *h = "0123456789ABCDEF";
char buf[2];
#include "internal.h"
if (a == NULL)
return (0);
if (a->length == 0) {
if (BIO_write(bp, "00", 2) != 2)
goto err;
n = 2;
} else {
for (i = 0; i < a->length; i++) {
if ((i != 0) && (i % 35 == 0)) {
if (BIO_write(bp, "\\\n", 2) != 2)
goto err;
n += 2;
}
buf[0] = h[((unsigned char)a->data[i] >> 4) & 0x0f];
buf[1] = h[((unsigned char)a->data[i]) & 0x0f];
if (BIO_write(bp, buf, 2) != 2)
goto err;
n += 2;
}
}
return (n);
err:
return (-1);
int bio_errno_should_retry(int return_value) {
if (return_value != -1) {
return 0;
}
return
#ifdef EWOULDBLOCK
errno == EWOULDBLOCK ||
#endif
#ifdef ENOTCONN
errno == ENOTCONN ||
#endif
#ifdef EINTR
errno == EINTR ||
#endif
#ifdef EAGAIN
errno == EAGAIN ||
#endif
#ifdef EPROTO
errno == EPROTO ||
#endif
#ifdef EINPROGRESS
errno == EINPROGRESS ||
#endif
#ifdef EALREADY
errno == EALREADY ||
#endif
0;
}
+18 -62
View File
@@ -56,7 +56,7 @@
#include <CCryptoBoringSSL_bio.h>
#if !defined(OPENSSL_TRUSTY)
#if !defined(OPENSSL_NO_POSIX_IO)
#include <errno.h>
#include <string.h>
@@ -65,9 +65,6 @@
#include <unistd.h>
#else
#include <io.h>
OPENSSL_MSVC_PRAGMA(warning(push, 3))
#include <windows.h>
OPENSSL_MSVC_PRAGMA(warning(pop))
#endif
#include <CCryptoBoringSSL_err.h>
@@ -77,59 +74,18 @@ OPENSSL_MSVC_PRAGMA(warning(pop))
#include "../internal.h"
static int bio_fd_non_fatal_error(int err) {
if (
#ifdef EWOULDBLOCK
err == EWOULDBLOCK ||
#endif
#ifdef WSAEWOULDBLOCK
err == WSAEWOULDBLOCK ||
#endif
#ifdef ENOTCONN
err == ENOTCONN ||
#endif
#ifdef EINTR
err == EINTR ||
#endif
#ifdef EAGAIN
err == EAGAIN ||
#endif
#ifdef EPROTO
err == EPROTO ||
#endif
#ifdef EINPROGRESS
err == EINPROGRESS ||
#endif
#ifdef EALREADY
err == EALREADY ||
#endif
0) {
return 1;
}
return 0;
}
#if defined(OPENSSL_WINDOWS)
#define BORINGSSL_ERRNO (int)GetLastError()
#define BORINGSSL_CLOSE _close
#define BORINGSSL_LSEEK _lseek
#define BORINGSSL_READ _read
#define BORINGSSL_WRITE _write
#else
#define BORINGSSL_ERRNO errno
#define BORINGSSL_CLOSE close
#define BORINGSSL_LSEEK lseek
#define BORINGSSL_READ read
#define BORINGSSL_WRITE write
#endif
int bio_fd_should_retry(int i) {
if (i == -1) {
return bio_fd_non_fatal_error(BORINGSSL_ERRNO);
}
return 0;
}
BIO *BIO_new_fd(int fd, int close_flag) {
BIO *ret = BIO_new(BIO_s_fd());
if (ret == NULL) {
@@ -146,10 +102,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);
@@ -162,10 +114,10 @@ static int fd_free(BIO *bio) {
static int fd_read(BIO *b, char *out, int outl) {
int ret = 0;
ret = BORINGSSL_READ(b->num, out, outl);
ret = (int)BORINGSSL_READ(b->num, out, outl);
BIO_clear_retry_flags(b);
if (ret <= 0) {
if (bio_fd_should_retry(ret)) {
if (bio_errno_should_retry(ret)) {
BIO_set_retry_read(b);
}
}
@@ -174,10 +126,10 @@ static int fd_read(BIO *b, char *out, int outl) {
}
static int fd_write(BIO *b, const char *in, int inl) {
int ret = BORINGSSL_WRITE(b->num, in, inl);
int ret = (int)BORINGSSL_WRITE(b->num, in, inl);
BIO_clear_retry_flags(b);
if (ret <= 0) {
if (bio_fd_should_retry(ret)) {
if (bio_errno_should_retry(ret)) {
BIO_set_retry_write(b);
}
}
@@ -245,20 +197,24 @@ static long fd_ctrl(BIO *b, int cmd, long num, void *ptr) {
}
static int fd_gets(BIO *bp, char *buf, int size) {
char *ptr = buf;
char *end = buf + size - 1;
if (size <= 0) {
return 0;
}
while (ptr < end && fd_read(bp, ptr, 1) > 0 && ptr[0] != '\n') {
char *ptr = buf;
char *end = buf + size - 1;
while (ptr < end && fd_read(bp, ptr, 1) > 0) {
char c = ptr[0];
ptr++;
if (c == '\n') {
break;
}
}
ptr[0] = '\0';
return ptr - buf;
// The output length is bounded by |size|.
return (int)(ptr - buf);
}
static const BIO_METHOD methods_fdp = {
@@ -268,12 +224,12 @@ static const BIO_METHOD methods_fdp = {
const BIO_METHOD *BIO_s_fd(void) { return &methods_fdp; }
#endif // OPENSSL_NO_POSIX_IO
int BIO_set_fd(BIO *bio, int fd, int close_flag) {
return BIO_int_ctrl(bio, BIO_C_SET_FD, close_flag, fd);
return (int)BIO_int_ctrl(bio, BIO_C_SET_FD, close_flag, fd);
}
int BIO_get_fd(BIO *bio, int *out_fd) {
return BIO_ctrl(bio, BIO_C_GET_FD, 0, (char *) out_fd);
return (int)BIO_ctrl(bio, BIO_C_GET_FD, 0, (char *) out_fd);
}
#endif // OPENSSL_TRUSTY
+40 -38
View File
@@ -73,8 +73,6 @@
#include <CCryptoBoringSSL_bio.h>
#if !defined(OPENSSL_TRUSTY)
#include <errno.h>
#include <stdio.h>
#include <string.h>
@@ -89,11 +87,20 @@
#define BIO_FP_WRITE 0x04
#define BIO_FP_APPEND 0x08
#if !defined(OPENSSL_NO_FILESYSTEM)
#define fopen_if_available fopen
#else
static FILE *fopen_if_available(const char *path, const char *mode) {
errno = ENOENT;
return NULL;
}
#endif
BIO *BIO_new_file(const char *filename, const char *mode) {
BIO *ret;
FILE *file;
file = fopen(filename, mode);
file = fopen_if_available(filename, mode);
if (file == NULL) {
OPENSSL_PUT_SYSTEM_ERROR();
@@ -126,13 +133,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;
}
@@ -163,13 +164,11 @@ static int file_read(BIO *b, char *out, int outl) {
}
static int file_write(BIO *b, const char *in, int inl) {
int ret = 0;
if (!b->init) {
return 0;
}
ret = fwrite(in, inl, 1, (FILE *)b->ptr);
int ret = (int)fwrite(in, inl, 1, (FILE *)b->ptr);
if (ret > 0) {
ret = inl;
}
@@ -180,7 +179,6 @@ static long file_ctrl(BIO *b, int cmd, long num, void *ptr) {
long ret = 1;
FILE *fp = (FILE *)b->ptr;
FILE **fpp;
char p[4];
switch (cmd) {
case BIO_CTRL_RESET:
@@ -205,27 +203,28 @@ static long file_ctrl(BIO *b, int cmd, long num, void *ptr) {
case BIO_C_SET_FILENAME:
file_free(b);
b->shutdown = (int)num & BIO_CLOSE;
const char *mode;
if (num & BIO_FP_APPEND) {
if (num & BIO_FP_READ) {
OPENSSL_strlcpy(p, "a+", sizeof(p));
mode = "a+";
} else {
OPENSSL_strlcpy(p, "a", sizeof(p));
mode = "a";
}
} else if ((num & BIO_FP_READ) && (num & BIO_FP_WRITE)) {
OPENSSL_strlcpy(p, "r+", sizeof(p));
mode = "r+";
} else if (num & BIO_FP_WRITE) {
OPENSSL_strlcpy(p, "w", sizeof(p));
mode = "w";
} else if (num & BIO_FP_READ) {
OPENSSL_strlcpy(p, "r", sizeof(p));
mode = "r";
} else {
OPENSSL_PUT_ERROR(BIO, BIO_R_BAD_FOPEN_MODE);
ret = 0;
break;
}
fp = fopen(ptr, p);
fp = fopen_if_available(ptr, mode);
if (fp == NULL) {
OPENSSL_PUT_SYSTEM_ERROR();
ERR_add_error_data(5, "fopen('", ptr, "','", p, "')");
ERR_add_error_data(5, "fopen('", ptr, "','", mode, "')");
OPENSSL_PUT_ERROR(BIO, ERR_R_SYS_LIB);
ret = 0;
break;
@@ -259,27 +258,25 @@ static long file_ctrl(BIO *b, int cmd, long num, void *ptr) {
}
static int file_gets(BIO *bp, char *buf, int size) {
int ret = 0;
if (size == 0) {
return 0;
}
if (!fgets(buf, size, (FILE *)bp->ptr)) {
buf[0] = 0;
goto err;
// TODO(davidben): This doesn't distinguish error and EOF. This should check
// |ferror| as in |file_read|.
return 0;
}
ret = strlen(buf);
err:
return ret;
return (int)strlen(buf);
}
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 */,
};
@@ -287,31 +284,36 @@ const BIO_METHOD *BIO_s_file(void) { return &methods_filep; }
int BIO_get_fp(BIO *bio, FILE **out_file) {
return BIO_ctrl(bio, BIO_C_GET_FILE_PTR, 0, (char*) out_file);
return (int)BIO_ctrl(bio, BIO_C_GET_FILE_PTR, 0, (char *)out_file);
}
int BIO_set_fp(BIO *bio, FILE *file, int close_flag) {
return BIO_ctrl(bio, BIO_C_SET_FILE_PTR, close_flag, (char *) file);
return (int)BIO_ctrl(bio, BIO_C_SET_FILE_PTR, close_flag, (char *)file);
}
int BIO_read_filename(BIO *bio, const char *filename) {
return BIO_ctrl(bio, BIO_C_SET_FILENAME, BIO_CLOSE | BIO_FP_READ,
(char *)filename);
return (int)BIO_ctrl(bio, BIO_C_SET_FILENAME, BIO_CLOSE | BIO_FP_READ,
(char *)filename);
}
int BIO_write_filename(BIO *bio, const char *filename) {
return BIO_ctrl(bio, BIO_C_SET_FILENAME, BIO_CLOSE | BIO_FP_WRITE,
(char *)filename);
return (int)BIO_ctrl(bio, BIO_C_SET_FILENAME, BIO_CLOSE | BIO_FP_WRITE,
(char *)filename);
}
int BIO_append_filename(BIO *bio, const char *filename) {
return BIO_ctrl(bio, BIO_C_SET_FILENAME, BIO_CLOSE | BIO_FP_APPEND,
(char *)filename);
return (int)BIO_ctrl(bio, BIO_C_SET_FILENAME, BIO_CLOSE | BIO_FP_APPEND,
(char *)filename);
}
int BIO_rw_filename(BIO *bio, const char *filename) {
return BIO_ctrl(bio, BIO_C_SET_FILENAME,
BIO_CLOSE | BIO_FP_READ | BIO_FP_WRITE, (char *)filename);
return (int)BIO_ctrl(bio, BIO_C_SET_FILENAME,
BIO_CLOSE | BIO_FP_READ | BIO_FP_WRITE,
(char *)filename);
}
#endif // OPENSSL_TRUSTY
long BIO_tell(BIO *bio) { return BIO_ctrl(bio, BIO_C_FILE_TELL, 0, NULL); }
long BIO_seek(BIO *bio, long offset) {
return BIO_ctrl(bio, BIO_C_FILE_SEEK, offset, NULL);
}
+16 -6
View File
@@ -59,6 +59,7 @@
#include <CCryptoBoringSSL_base.h>
#if !defined(OPENSSL_NO_SOCK)
#if !defined(OPENSSL_WINDOWS)
#if defined(OPENSSL_PNACL)
// newlib uses u_short in socket.h without defining it.
@@ -72,13 +73,16 @@ OPENSSL_MSVC_PRAGMA(warning(push, 3))
OPENSSL_MSVC_PRAGMA(warning(pop))
typedef int socklen_t;
#endif
#endif // !OPENSSL_NO_SOCK
#if defined(__cplusplus)
extern "C" {
#endif
// BIO_ip_and_port_to_socket_and_addr creates a socket and fills in |*out_addr|
#if !defined(OPENSSL_NO_SOCK)
// bio_ip_and_port_to_socket_and_addr creates a socket and fills in |*out_addr|
// and |*out_addr_length| with the correct values for connecting to |hostname|
// on |port_str|. It returns one on success or zero on error.
int bio_ip_and_port_to_socket_and_addr(int *out_sock,
@@ -87,21 +91,27 @@ int bio_ip_and_port_to_socket_and_addr(int *out_sock,
const char *hostname,
const char *port_str);
// BIO_socket_nbio sets whether |sock| is non-blocking. It returns one on
// bio_socket_nbio sets whether |sock| is non-blocking. It returns one on
// success and zero otherwise.
int bio_socket_nbio(int sock, int on);
// BIO_clear_socket_error clears the last system socket error.
// bio_clear_socket_error clears the last system socket error.
//
// TODO(fork): remove all callers of this.
void bio_clear_socket_error(void);
// BIO_sock_error returns the last socket error on |sock|.
// bio_sock_error returns the last socket error on |sock|.
int bio_sock_error(int sock);
// BIO_fd_should_retry returns non-zero if |return_value| indicates an error
// bio_socket_should_retry returns non-zero if |return_value| indicates an error
// and the last socket error indicates that it's non-fatal.
int bio_socket_should_retry(int return_value);
#endif // !OPENSSL_NO_SOCK
// bio_errno_should_retry returns non-zero if |return_value| indicates an error
// and |errno| indicates that it's non-fatal.
int bio_fd_should_retry(int return_value);
int bio_errno_should_retry(int return_value);
#if defined(__cplusplus)
+7 -15
View File
@@ -81,13 +81,10 @@ struct bio_bio_st {
};
static int bio_new(BIO *bio) {
struct bio_bio_st *b;
b = OPENSSL_malloc(sizeof *b);
struct bio_bio_st *b = OPENSSL_zalloc(sizeof *b);
if (b == NULL) {
return 0;
}
OPENSSL_memset(b, 0, sizeof(struct bio_bio_st));
b->size = 17 * 1024; // enough for one TLS record (just a default)
bio->ptr = b;
@@ -127,12 +124,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);
@@ -226,7 +218,8 @@ static int bio_read(BIO *bio, char *buf, int size_) {
rest -= chunk;
} while (rest);
return size;
// |size| is bounded by the buffer size, which fits in |int|.
return (int)size;
}
static int bio_write(BIO *bio, const char *buf, int num_) {
@@ -298,7 +291,8 @@ static int bio_write(BIO *bio, const char *buf, int num_) {
buf += chunk;
} while (rest);
return num;
// |num| is bounded by the buffer size, which fits in |int|.
return (int)num;
}
static int bio_make_pair(BIO *bio1, BIO *bio2, size_t writebuf1_len,
@@ -322,7 +316,6 @@ static int bio_make_pair(BIO *bio1, BIO *bio2, size_t writebuf1_len,
}
b1->buf = OPENSSL_malloc(b1->size);
if (b1->buf == NULL) {
OPENSSL_PUT_ERROR(BIO, ERR_R_MALLOC_FAILURE);
return 0;
}
b1->len = 0;
@@ -335,7 +328,6 @@ static int bio_make_pair(BIO *bio1, BIO *bio2, size_t writebuf1_len,
}
b2->buf = OPENSSL_malloc(b2->size);
if (b2->buf == NULL) {
OPENSSL_PUT_ERROR(BIO, ERR_R_MALLOC_FAILURE);
return 0;
}
b2->len = 0;
@@ -484,5 +476,5 @@ size_t BIO_ctrl_get_write_guarantee(BIO *bio) {
}
int BIO_shutdown_wr(BIO *bio) {
return BIO_ctrl(bio, BIO_C_SHUTDOWN_WR, 0, NULL);
return (int)BIO_ctrl(bio, BIO_C_SHUTDOWN_WR, 0, NULL);
}
@@ -71,18 +71,6 @@ int BIO_printf(BIO *bio, const char *format, ...) {
va_start(args, format);
out_len = vsnprintf(buf, sizeof(buf), format, args);
va_end(args);
#if defined(OPENSSL_WINDOWS)
// On Windows, vsnprintf returns -1 rather than the requested length on
// truncation
if (out_len < 0) {
va_start(args, format);
out_len = _vscprintf(format, args);
va_end(args);
assert(out_len >= (int)sizeof(buf));
}
#endif
if (out_len < 0) {
return -1;
}
@@ -95,7 +83,6 @@ int BIO_printf(BIO *bio, const char *format, ...) {
out = OPENSSL_malloc(requested_len + 1);
out_malloced = 1;
if (out == NULL) {
OPENSSL_PUT_ERROR(BIO, ERR_R_MALLOC_FAILURE);
return -1;
}
va_start(args, format);
+9 -26
View File
@@ -1,4 +1,3 @@
/* crypto/bio/bss_sock.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
@@ -57,7 +56,7 @@
#include <CCryptoBoringSSL_bio.h>
#if !defined(OPENSSL_TRUSTY)
#if !defined(OPENSSL_NO_SOCK)
#include <fcntl.h>
#include <string.h>
@@ -81,19 +80,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,21 +92,19 @@ 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 = (int)read(b->num, out, outl);
#endif
BIO_clear_retry_flags(b);
if (ret <= 0) {
if (bio_fd_should_retry(ret)) {
if (bio_socket_should_retry(ret)) {
BIO_set_retry_read(b);
}
}
@@ -127,17 +112,15 @@ static int sock_read(BIO *b, char *out, int outl) {
}
static int sock_write(BIO *b, const char *in, int inl) {
int ret;
bio_clear_socket_error();
#if defined(OPENSSL_WINDOWS)
ret = send(b->num, in, inl, 0);
int ret = send(b->num, in, inl, 0);
#else
ret = write(b->num, in, inl);
int ret = (int)write(b->num, in, inl);
#endif
BIO_clear_retry_flags(b);
if (ret <= 0) {
if (bio_fd_should_retry(ret)) {
if (bio_socket_should_retry(ret)) {
BIO_set_retry_write(b);
}
}
@@ -186,7 +169,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 */,
};
@@ -203,4 +186,4 @@ BIO *BIO_new_socket(int fd, int close_flag) {
return ret;
}
#endif // OPENSSL_TRUSTY
#endif // OPENSSL_NO_SOCK
@@ -12,13 +12,15 @@
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#if defined(__linux__)
#undef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200112L
#endif
#include <CCryptoBoringSSL_bio.h>
#include <CCryptoBoringSSL_err.h>
#if !defined(OPENSSL_TRUSTY)
#if !defined(OPENSSL_NO_SOCK)
#include <fcntl.h>
#include <string.h>
@@ -55,7 +57,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;
}
@@ -115,4 +121,13 @@ int bio_sock_error(int sock) {
return error;
}
#endif // OPENSSL_TRUSTY
int bio_socket_should_retry(int return_value) {
#if defined(OPENSSL_WINDOWS)
return return_value == -1 && WSAGetLastError() == WSAEWOULDBLOCK;
#else
// On POSIX platforms, sockets and fds are the same.
return bio_errno_should_retry(return_value);
#endif
}
#endif // OPENSSL_NO_SOCK
@@ -0,0 +1,169 @@
/* 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 <assert.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 uint64_t blake2b_load(const uint8_t block[BLAKE2B_CBLOCK], size_t i) {
return CRYPTO_load_u64_le(block + 8 * i);
}
static void blake2b_transform(BLAKE2B_CTX *b2b,
const uint8_t block[BLAKE2B_CBLOCK],
size_t num_bytes, int is_final_block) {
// https://tools.ietf.org/html/rfc7693#section-3.2
uint64_t v[16];
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, blake2b_load(block, s[0]),
blake2b_load(block, s[1]));
blake2b_mix(v, 1, 5, 9, 13, blake2b_load(block, s[2]),
blake2b_load(block, s[3]));
blake2b_mix(v, 2, 6, 10, 14, blake2b_load(block, s[4]),
blake2b_load(block, s[5]));
blake2b_mix(v, 3, 7, 11, 15, blake2b_load(block, s[6]),
blake2b_load(block, s[7]));
blake2b_mix(v, 0, 5, 10, 15, blake2b_load(block, s[8]),
blake2b_load(block, s[9]));
blake2b_mix(v, 1, 6, 11, 12, blake2b_load(block, s[10]),
blake2b_load(block, s[11]));
blake2b_mix(v, 2, 7, 8, 13, blake2b_load(block, s[12]),
blake2b_load(block, s[13]));
blake2b_mix(v, 3, 4, 9, 14, blake2b_load(block, s[14]),
blake2b_load(block, 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));
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) {
if (len == 0) {
// Work around a C language bug. See https://crbug.com/1019588.
return;
}
const uint8_t *data = in_data;
size_t todo = sizeof(b2b->block) - b2b->block_used;
if (todo > len) {
todo = len;
}
OPENSSL_memcpy(&b2b->block[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, BLAKE2B_CBLOCK,
/*is_final_block=*/0);
b2b->block_used = 0;
while (len > BLAKE2B_CBLOCK) {
blake2b_transform(b2b, data, BLAKE2B_CBLOCK, /*is_final_block=*/0);
data += BLAKE2B_CBLOCK;
len -= BLAKE2B_CBLOCK;
}
OPENSSL_memcpy(b2b->block, data, len);
b2b->block_used = len;
}
void BLAKE2B256_Final(uint8_t out[BLAKE2B256_DIGEST_LENGTH], BLAKE2B_CTX *b2b) {
OPENSSL_memset(&b2b->block[b2b->block_used], 0,
sizeof(b2b->block) - b2b->block_used);
blake2b_transform(b2b, b2b->block, b2b->block_used,
/*is_final_block=*/1);
static_assert(BLAKE2B256_DIGEST_LENGTH <= sizeof(b2b->h), "");
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;
}
@@ -81,7 +81,6 @@ char *BN_bn2hex(const BIGNUM *bn) {
char *buf = OPENSSL_malloc(1 /* leading '-' */ + 1 /* zero is non-empty */ +
width * BN_BYTES * 2 + 1 /* trailing NUL */);
if (buf == NULL) {
OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
return NULL;
}
@@ -133,18 +132,9 @@ static int decode_hex(BIGNUM *bn, const char *in, int in_len) {
BN_ULONG word = 0;
int j;
for (j = todo; j > 0; j--) {
char c = in[in_len - j];
BN_ULONG hex;
if (c >= '0' && c <= '9') {
hex = c - '0';
} else if (c >= 'a' && c <= 'f') {
hex = c - 'a' + 10;
} else if (c >= 'A' && c <= 'F') {
hex = c - 'A' + 10;
} else {
hex = 0;
// This shouldn't happen. The caller checks |isxdigit|.
uint8_t hex = 0;
if (!OPENSSL_fromxdigit(&hex, in[in_len - j])) {
// This shouldn't happen. The caller checks |OPENSSL_isxdigit|.
assert(0);
}
word = (word << 4) | hex;
@@ -240,7 +230,7 @@ err:
}
int BN_hex2bn(BIGNUM **outp, const char *in) {
return bn_x2bn(outp, in, decode_hex, isxdigit);
return bn_x2bn(outp, in, decode_hex, OPENSSL_isxdigit);
}
char *BN_bn2dec(const BIGNUM *a) {
@@ -250,12 +240,12 @@ char *BN_bn2dec(const BIGNUM *a) {
CBB cbb;
if (!CBB_init(&cbb, 16) ||
!CBB_add_u8(&cbb, 0 /* trailing NUL */)) {
goto cbb_err;
goto err;
}
if (BN_is_zero(a)) {
if (!CBB_add_u8(&cbb, '0')) {
goto cbb_err;
goto err;
}
} else {
copy = BN_dup(a);
@@ -272,7 +262,7 @@ char *BN_bn2dec(const BIGNUM *a) {
const int add_leading_zeros = !BN_is_zero(copy);
for (int i = 0; i < BN_DEC_NUM && (add_leading_zeros || word != 0); i++) {
if (!CBB_add_u8(&cbb, '0' + word % 10)) {
goto cbb_err;
goto err;
}
word /= 10;
}
@@ -282,13 +272,13 @@ char *BN_bn2dec(const BIGNUM *a) {
if (BN_is_negative(a) &&
!CBB_add_u8(&cbb, '-')) {
goto cbb_err;
goto err;
}
uint8_t *data;
size_t len;
if (!CBB_finish(&cbb, &data, &len)) {
goto cbb_err;
goto err;
}
// Reverse the buffer.
@@ -301,8 +291,6 @@ char *BN_bn2dec(const BIGNUM *a) {
BN_free(copy);
return (char *)data;
cbb_err:
OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
err:
BN_free(copy);
CBB_cleanup(&cbb);
@@ -310,7 +298,7 @@ err:
}
int BN_dec2bn(BIGNUM **outp, const char *in) {
return bn_x2bn(outp, in, decode_dec, isdigit);
return bn_x2bn(outp, in, decode_dec, OPENSSL_isdigit);
}
int BN_asc2bn(BIGNUM **outp, const char *in) {
@@ -436,7 +424,6 @@ BIGNUM *BN_mpi2bn(const uint8_t *in, size_t len, BIGNUM *out) {
if (out == NULL) {
out = BN_new();
if (out == NULL) {
OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
return NULL;
}
out_is_alloced = 1;
@@ -468,3 +455,11 @@ int BN_bn2binpad(const BIGNUM *in, uint8_t *out, int len) {
}
return len;
}
int BN_bn2lebinpad(const BIGNUM *in, uint8_t *out, int len) {
if (len < 0 ||
!BN_bn2le_padded(out, (size_t)len, in)) {
return -1;
}
return len;
}
+3 -17
View File
@@ -64,18 +64,7 @@
#include "../internal.h"
BUF_MEM *BUF_MEM_new(void) {
BUF_MEM *ret;
ret = OPENSSL_malloc(sizeof(BUF_MEM));
if (ret == NULL) {
OPENSSL_PUT_ERROR(BUF, ERR_R_MALLOC_FAILURE);
return NULL;
}
OPENSSL_memset(ret, 0, sizeof(BUF_MEM));
return ret;
}
BUF_MEM *BUF_MEM_new(void) { return OPENSSL_zalloc(sizeof(BUF_MEM)); }
void BUF_MEM_free(BUF_MEM *buf) {
if (buf == NULL) {
@@ -93,21 +82,18 @@ int BUF_MEM_reserve(BUF_MEM *buf, size_t cap) {
size_t n = cap + 3;
if (n < cap) {
// overflow
OPENSSL_PUT_ERROR(BUF, ERR_R_MALLOC_FAILURE);
OPENSSL_PUT_ERROR(BUF, ERR_R_OVERFLOW);
return 0;
}
n = n / 3;
size_t alloc_size = n * 4;
if (alloc_size / 4 != n) {
// overflow
OPENSSL_PUT_ERROR(BUF, ERR_R_MALLOC_FAILURE);
OPENSSL_PUT_ERROR(BUF, ERR_R_OVERFLOW);
return 0;
}
char *new_buf = OPENSSL_realloc(buf->data, alloc_size);
if (new_buf == NULL) {
OPENSSL_PUT_ERROR(BUF, ERR_R_MALLOC_FAILURE);
return 0;
}
@@ -26,7 +26,8 @@
int CBB_finish_i2d(CBB *cbb, uint8_t **outp) {
assert(cbb->base->can_resize);
assert(!cbb->is_child);
assert(cbb->u.base.can_resize);
uint8_t *der;
size_t der_len;
@@ -24,13 +24,15 @@
// kMaxDepth is a just a sanity limit. The code should be such that the length
// of the input being processes always decreases. None the less, a very large
// input could otherwise cause the stack to overflow.
static const unsigned kMaxDepth = 2048;
static const uint32_t 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) {
static int is_string_type(CBS_ASN1_TAG 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, uint32_t depth) {
CBS in;
if (depth > kMaxDepth) {
@@ -65,17 +67,14 @@ static int cbs_find_ber(const CBS *orig_in, char *ber_found, unsigned depth) {
while (CBS_len(&in) > 0) {
CBS contents;
unsigned tag;
CBS_ASN1_TAG tag;
size_t header_len;
if (!CBS_get_any_ber_asn1_element(&in, &contents, &tag, &header_len)) {
int indefinite;
if (!CBS_get_any_ber_asn1_element(&in, &contents, &tag, &header_len,
ber_found, &indefinite)) {
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) {
@@ -94,11 +93,14 @@ static int cbs_find_ber(const CBS *orig_in, char *ber_found, unsigned depth) {
return 1;
}
// is_eoc returns true if |header_len| and |contents|, as returned by
// |CBS_get_any_ber_asn1_element|, indicate an "end of contents" (EOC) value.
static char is_eoc(size_t header_len, CBS *contents) {
return header_len == 2 && CBS_len(contents) == 2 &&
OPENSSL_memcmp(CBS_data(contents), "\x00\x00", 2) == 0;
// cbs_get_eoc returns one if |cbs| begins with an "end of contents" (EOC) value
// and zero otherwise. If an EOC was found, it advances |cbs| past it.
static int cbs_get_eoc(CBS *cbs) {
if (CBS_len(cbs) >= 2 &&
CBS_data(cbs)[0] == 0 && CBS_data(cbs)[1] == 0) {
return CBS_skip(cbs, 2);
}
return 0;
}
// cbs_convert_ber reads BER data from |in| and writes DER data to |out|. If
@@ -108,8 +110,8 @@ static char is_eoc(size_t header_len, CBS *contents) {
// constructed string. If |looking_for_eoc| is set then any EOC elements found
// will cause the function to return after consuming it. It returns one on
// success and zero on error.
static int cbs_convert_ber(CBS *in, CBB *out, unsigned string_tag,
char looking_for_eoc, unsigned depth) {
static int cbs_convert_ber(CBS *in, CBB *out, CBS_ASN1_TAG string_tag,
int looking_for_eoc, uint32_t depth) {
assert(!(string_tag & CBS_ASN1_CONSTRUCTED));
if (depth > kMaxDepth) {
@@ -117,17 +119,18 @@ static int cbs_convert_ber(CBS *in, CBB *out, unsigned string_tag,
}
while (CBS_len(in) > 0) {
CBS contents;
unsigned tag, child_string_tag = string_tag;
size_t header_len;
CBB *out_contents, out_contents_storage;
if (!CBS_get_any_ber_asn1_element(in, &contents, &tag, &header_len)) {
return 0;
if (looking_for_eoc && cbs_get_eoc(in)) {
return 1;
}
if (is_eoc(header_len, &contents)) {
return looking_for_eoc;
CBS contents;
CBS_ASN1_TAG tag, child_string_tag = string_tag;
size_t header_len;
int indefinite;
CBB *out_contents, out_contents_storage;
if (!CBS_get_any_ber_asn1_element(in, &contents, &tag, &header_len,
/*out_ber_found=*/NULL, &indefinite)) {
return 0;
}
if (string_tag != 0) {
@@ -139,7 +142,7 @@ static int cbs_convert_ber(CBS *in, CBB *out, unsigned string_tag,
}
out_contents = out;
} else {
unsigned out_tag = tag;
CBS_ASN1_TAG out_tag = tag;
if ((tag & CBS_ASN1_CONSTRUCTED) && is_string_type(tag)) {
// If a constructed string, clear the constructed bit and inform
// children to concatenate bodies.
@@ -152,11 +155,9 @@ static int cbs_convert_ber(CBS *in, CBB *out, unsigned string_tag,
out_contents = &out_contents_storage;
}
if (CBS_len(&contents) == header_len && header_len > 0 &&
CBS_data(&contents)[header_len - 1] == 0x80) {
// This is an indefinite length element.
if (indefinite) {
if (!cbs_convert_ber(in, out_contents, child_string_tag,
1 /* looking for eoc */, depth + 1) ||
/*looking_for_eoc=*/1, depth + 1) ||
!CBB_flush(out)) {
return 0;
}
@@ -170,7 +171,7 @@ static int cbs_convert_ber(CBS *in, CBB *out, unsigned string_tag,
if (tag & CBS_ASN1_CONSTRUCTED) {
// Recurse into children.
if (!cbs_convert_ber(&contents, out_contents, child_string_tag,
0 /* not looking for eoc */, depth + 1)) {
/*looking_for_eoc=*/0, depth + 1)) {
return 0;
}
} else {
@@ -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;
}
@@ -220,7 +221,8 @@ int CBS_asn1_ber_to_der(CBS *in, CBS *out, uint8_t **out_storage) {
}
int CBS_get_asn1_implicit_string(CBS *in, CBS *out, uint8_t **out_storage,
unsigned outer_tag, unsigned inner_tag) {
CBS_ASN1_TAG outer_tag,
CBS_ASN1_TAG inner_tag) {
assert(!(outer_tag & CBS_ASN1_CONSTRUCTED));
assert(!(inner_tag & CBS_ASN1_CONSTRUCTED));
assert(is_string_type(inner_tag));
+213 -214
View File
@@ -19,6 +19,7 @@
#include <string.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_err.h>
#include "../internal.h"
@@ -27,24 +28,14 @@ void CBB_zero(CBB *cbb) {
OPENSSL_memset(cbb, 0, sizeof(CBB));
}
static int cbb_init(CBB *cbb, uint8_t *buf, size_t cap) {
// This assumes that |cbb| has already been zeroed.
struct cbb_buffer_st *base;
base = OPENSSL_malloc(sizeof(struct cbb_buffer_st));
if (base == NULL) {
return 0;
}
base->buf = buf;
base->len = 0;
base->cap = cap;
base->can_resize = 1;
base->error = 0;
cbb->base = base;
static void cbb_init(CBB *cbb, uint8_t *buf, size_t cap, int can_resize) {
cbb->is_child = 0;
return 1;
cbb->child = NULL;
cbb->u.base.buf = buf;
cbb->u.base.len = 0;
cbb->u.base.cap = cap;
cbb->u.base.can_resize = can_resize;
cbb->u.base.error = 0;
}
int CBB_init(CBB *cbb, size_t initial_capacity) {
@@ -55,22 +46,13 @@ int CBB_init(CBB *cbb, size_t initial_capacity) {
return 0;
}
if (!cbb_init(cbb, buf, initial_capacity)) {
OPENSSL_free(buf);
return 0;
}
cbb_init(cbb, buf, initial_capacity, /*can_resize=*/1);
return 1;
}
int CBB_init_fixed(CBB *cbb, uint8_t *buf, size_t len) {
CBB_zero(cbb);
if (!cbb_init(cbb, buf, len)) {
return 0;
}
cbb->base->can_resize = 0;
cbb_init(cbb, buf, len, /*can_resize=*/0);
return 1;
}
@@ -82,41 +64,35 @@ void CBB_cleanup(CBB *cbb) {
return;
}
if (cbb->base) {
if (cbb->base->can_resize) {
OPENSSL_free(cbb->base->buf);
}
OPENSSL_free(cbb->base);
if (cbb->u.base.can_resize) {
OPENSSL_free(cbb->u.base.buf);
}
cbb->base = NULL;
}
static int cbb_buffer_reserve(struct cbb_buffer_st *base, uint8_t **out,
size_t len) {
size_t newlen;
if (base == NULL) {
return 0;
}
newlen = base->len + len;
size_t newlen = base->len + len;
if (newlen < base->len) {
// Overflow
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW);
goto err;
}
if (newlen > base->cap) {
size_t newcap = base->cap * 2;
uint8_t *newbuf;
if (!base->can_resize) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW);
goto err;
}
size_t newcap = base->cap * 2;
if (newcap < base->cap || newcap < newlen) {
newcap = newlen;
}
newbuf = OPENSSL_realloc(base->buf, newcap);
uint8_t *newbuf = OPENSSL_realloc(base->buf, newcap);
if (newbuf == NULL) {
goto err;
}
@@ -146,32 +122,9 @@ static int cbb_buffer_add(struct cbb_buffer_st *base, uint8_t **out,
return 1;
}
static int cbb_buffer_add_u(struct cbb_buffer_st *base, uint64_t v,
size_t len_len) {
if (len_len == 0) {
return 1;
}
uint8_t *buf;
if (!cbb_buffer_add(base, &buf, len_len)) {
return 0;
}
for (size_t i = len_len - 1; i < len_len; i--) {
buf[i] = v;
v >>= 8;
}
if (v != 0) {
base->error = 1;
return 0;
}
return 1;
}
int CBB_finish(CBB *cbb, uint8_t **out_data, size_t *out_len) {
if (cbb->is_child) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
@@ -179,59 +132,93 @@ int CBB_finish(CBB *cbb, uint8_t **out_data, size_t *out_len) {
return 0;
}
if (cbb->base->can_resize && (out_data == NULL || out_len == NULL)) {
if (cbb->u.base.can_resize && (out_data == NULL || out_len == NULL)) {
// |out_data| and |out_len| can only be NULL if the CBB is fixed.
return 0;
}
if (out_data != NULL) {
*out_data = cbb->base->buf;
*out_data = cbb->u.base.buf;
}
if (out_len != NULL) {
*out_len = cbb->base->len;
*out_len = cbb->u.base.len;
}
cbb->base->buf = NULL;
cbb->u.base.buf = NULL;
CBB_cleanup(cbb);
return 1;
}
static struct cbb_buffer_st *cbb_get_base(CBB *cbb) {
if (cbb->is_child) {
return cbb->u.child.base;
}
return &cbb->u.base;
}
static void cbb_on_error(CBB *cbb) {
// Due to C's lack of destructors and |CBB|'s auto-flushing API, a failing
// |CBB|-taking function may leave a dangling pointer to a child |CBB|. As a
// result, the convention is callers may not write to |CBB|s that have failed.
// But, as a safety measure, we lock the |CBB| into an error state. Once the
// error bit is set, |cbb->child| will not be read.
//
// TODO(davidben): This still isn't quite ideal. A |CBB| function *outside*
// this file may originate an error while the |CBB| points to a local child.
// In that case we don't set the error bit and are reliant on the error
// convention. Perhaps we allow |CBB_cleanup| on child |CBB|s and make every
// child's |CBB_cleanup| set the error bit if unflushed. That will be
// convenient for C++ callers, but very tedious for C callers. So C callers
// perhaps should get a |CBB_on_error| function that can be, less tediously,
// stuck in a |goto err| block.
cbb_get_base(cbb)->error = 1;
// Clearing the pointer is not strictly necessary, but GCC's dangling pointer
// warning does not know |cbb->child| will not be read once |error| is set
// above.
cbb->child = NULL;
}
// CBB_flush recurses and then writes out any pending length prefix. The
// current length of the underlying base is taken to be the length of the
// length-prefixed data.
int CBB_flush(CBB *cbb) {
size_t child_start, i, len;
// If |cbb->base| has hit an error, the buffer is in an undefined state, so
// If |base| has hit an error, the buffer is in an undefined state, so
// fail all following calls. In particular, |cbb->child| may point to invalid
// memory.
if (cbb->base == NULL || cbb->base->error) {
struct cbb_buffer_st *base = cbb_get_base(cbb);
if (base == NULL || base->error) {
return 0;
}
if (cbb->child == NULL || cbb->child->pending_len_len == 0) {
if (cbb->child == NULL) {
// Nothing to flush.
return 1;
}
child_start = cbb->child->offset + cbb->child->pending_len_len;
assert(cbb->child->is_child);
struct cbb_child_st *child = &cbb->child->u.child;
assert(child->base == base);
size_t child_start = child->offset + child->pending_len_len;
if (!CBB_flush(cbb->child) ||
child_start < cbb->child->offset ||
cbb->base->len < child_start) {
child_start < child->offset ||
base->len < child_start) {
goto err;
}
len = cbb->base->len - child_start;
size_t len = base->len - child_start;
if (cbb->child->pending_is_asn1) {
if (child->pending_is_asn1) {
// For ASN.1 we assume that we'll only need a single byte for the length.
// If that turned out to be incorrect, we have to move the contents along
// in order to make space.
uint8_t len_len;
uint8_t initial_length_byte;
assert (cbb->child->pending_len_len == 1);
assert (child->pending_len_len == 1);
if (len > 0xfffffffe) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW);
// Too large.
goto err;
} else if (len > 0xffffff) {
@@ -255,70 +242,86 @@ int CBB_flush(CBB *cbb) {
if (len_len != 1) {
// We need to move the contents along in order to make space.
size_t extra_bytes = len_len - 1;
if (!cbb_buffer_add(cbb->base, NULL, extra_bytes)) {
if (!cbb_buffer_add(base, NULL, extra_bytes)) {
goto err;
}
OPENSSL_memmove(cbb->base->buf + child_start + extra_bytes,
cbb->base->buf + child_start, len);
OPENSSL_memmove(base->buf + child_start + extra_bytes,
base->buf + child_start, len);
}
cbb->base->buf[cbb->child->offset++] = initial_length_byte;
cbb->child->pending_len_len = len_len - 1;
base->buf[child->offset++] = initial_length_byte;
child->pending_len_len = len_len - 1;
}
for (i = cbb->child->pending_len_len - 1; i < cbb->child->pending_len_len;
i--) {
cbb->base->buf[cbb->child->offset + i] = (uint8_t)len;
for (size_t i = child->pending_len_len - 1; i < child->pending_len_len; i--) {
base->buf[child->offset + i] = (uint8_t)len;
len >>= 8;
}
if (len != 0) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW);
goto err;
}
cbb->child->base = NULL;
child->base = NULL;
cbb->child = NULL;
return 1;
err:
cbb->base->error = 1;
cbb_on_error(cbb);
return 0;
}
const uint8_t *CBB_data(const CBB *cbb) {
assert(cbb->child == NULL);
return cbb->base->buf + cbb->offset + cbb->pending_len_len;
if (cbb->is_child) {
return cbb->u.child.base->buf + cbb->u.child.offset +
cbb->u.child.pending_len_len;
}
return cbb->u.base.buf;
}
size_t CBB_len(const CBB *cbb) {
assert(cbb->child == NULL);
assert(cbb->offset + cbb->pending_len_len <= cbb->base->len);
if (cbb->is_child) {
assert(cbb->u.child.offset + cbb->u.child.pending_len_len <=
cbb->u.child.base->len);
return cbb->u.child.base->len - cbb->u.child.offset -
cbb->u.child.pending_len_len;
}
return cbb->u.base.len;
}
return cbb->base->len - cbb->offset - cbb->pending_len_len;
static int cbb_add_child(CBB *cbb, CBB *out_child, uint8_t len_len,
int is_asn1) {
assert(cbb->child == NULL);
assert(!is_asn1 || len_len == 1);
struct cbb_buffer_st *base = cbb_get_base(cbb);
size_t offset = base->len;
// Reserve space for the length prefix.
uint8_t *prefix_bytes;
if (!cbb_buffer_add(base, &prefix_bytes, len_len)) {
return 0;
}
OPENSSL_memset(prefix_bytes, 0, len_len);
CBB_zero(out_child);
out_child->is_child = 1;
out_child->u.child.base = base;
out_child->u.child.offset = offset;
out_child->u.child.pending_len_len = len_len;
out_child->u.child.pending_is_asn1 = is_asn1;
cbb->child = out_child;
return 1;
}
static int cbb_add_length_prefixed(CBB *cbb, CBB *out_contents,
uint8_t len_len) {
uint8_t *prefix_bytes;
if (!CBB_flush(cbb)) {
return 0;
}
size_t offset = cbb->base->len;
if (!cbb_buffer_add(cbb->base, &prefix_bytes, len_len)) {
return 0;
}
OPENSSL_memset(prefix_bytes, 0, len_len);
OPENSSL_memset(out_contents, 0, sizeof(CBB));
out_contents->base = cbb->base;
out_contents->is_child = 1;
cbb->child = out_contents;
cbb->child->offset = offset;
cbb->child->pending_len_len = len_len;
cbb->child->pending_is_asn1 = 0;
return 1;
return cbb_add_child(cbb, out_contents, len_len, /*is_asn1=*/0);
}
int CBB_add_u8_length_prefixed(CBB *cbb, CBB *out_contents) {
@@ -359,14 +362,14 @@ static int add_base128_integer(CBB *cbb, uint64_t v) {
return 1;
}
int CBB_add_asn1(CBB *cbb, CBB *out_contents, unsigned tag) {
int CBB_add_asn1(CBB *cbb, CBB *out_contents, CBS_ASN1_TAG tag) {
if (!CBB_flush(cbb)) {
return 0;
}
// Split the tag into leading bits and tag number.
uint8_t tag_bits = (tag >> CBS_ASN1_TAG_SHIFT) & 0xe0;
unsigned tag_number = tag & CBS_ASN1_TAG_NUMBER_MASK;
CBS_ASN1_TAG tag_number = tag & CBS_ASN1_TAG_NUMBER_MASK;
if (tag_number >= 0x1f) {
// Set all the bits in the tag number to signal high tag number form.
if (!CBB_add_u8(cbb, tag_bits | 0x1f) ||
@@ -377,36 +380,31 @@ int CBB_add_asn1(CBB *cbb, CBB *out_contents, unsigned tag) {
return 0;
}
size_t offset = cbb->base->len;
if (!CBB_add_u8(cbb, 0)) {
return 0;
}
OPENSSL_memset(out_contents, 0, sizeof(CBB));
out_contents->base = cbb->base;
out_contents->is_child = 1;
cbb->child = out_contents;
cbb->child->offset = offset;
cbb->child->pending_len_len = 1;
cbb->child->pending_is_asn1 = 1;
return 1;
// Reserve one byte of length prefix. |CBB_flush| will finish it later.
return cbb_add_child(cbb, out_contents, /*len_len=*/1, /*is_asn1=*/1);
}
int CBB_add_bytes(CBB *cbb, const uint8_t *data, size_t len) {
uint8_t *dest;
if (!CBB_flush(cbb) ||
!cbb_buffer_add(cbb->base, &dest, len)) {
uint8_t *out;
if (!CBB_add_space(cbb, &out, len)) {
return 0;
}
OPENSSL_memcpy(dest, data, len);
OPENSSL_memcpy(out, data, 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)) {
!cbb_buffer_add(cbb_get_base(cbb), out_data, len)) {
return 0;
}
return 1;
@@ -414,37 +412,50 @@ int CBB_add_space(CBB *cbb, uint8_t **out_data, size_t len) {
int CBB_reserve(CBB *cbb, uint8_t **out_data, size_t len) {
if (!CBB_flush(cbb) ||
!cbb_buffer_reserve(cbb->base, out_data, len)) {
!cbb_buffer_reserve(cbb_get_base(cbb), out_data, len)) {
return 0;
}
return 1;
}
int CBB_did_write(CBB *cbb, size_t len) {
size_t newlen = cbb->base->len + len;
struct cbb_buffer_st *base = cbb_get_base(cbb);
size_t newlen = base->len + len;
if (cbb->child != NULL ||
newlen < cbb->base->len ||
newlen > cbb->base->cap) {
newlen < base->len ||
newlen > base->cap) {
return 0;
}
cbb->base->len = newlen;
base->len = newlen;
return 1;
}
static int cbb_add_u(CBB *cbb, uint64_t v, size_t len_len) {
uint8_t *buf;
if (!CBB_add_space(cbb, &buf, len_len)) {
return 0;
}
for (size_t i = len_len - 1; i < len_len; i--) {
buf[i] = v;
v >>= 8;
}
// |v| must fit in |len_len| bytes.
if (v != 0) {
cbb_on_error(cbb);
return 0;
}
return 1;
}
int CBB_add_u8(CBB *cbb, uint8_t value) {
if (!CBB_flush(cbb)) {
return 0;
}
return cbb_buffer_add_u(cbb->base, value, 1);
return cbb_add_u(cbb, value, 1);
}
int CBB_add_u16(CBB *cbb, uint16_t value) {
if (!CBB_flush(cbb)) {
return 0;
}
return cbb_buffer_add_u(cbb->base, value, 2);
return cbb_add_u(cbb, value, 2);
}
int CBB_add_u16le(CBB *cbb, uint16_t value) {
@@ -452,19 +463,11 @@ int CBB_add_u16le(CBB *cbb, uint16_t value) {
}
int CBB_add_u24(CBB *cbb, uint32_t value) {
if (!CBB_flush(cbb)) {
return 0;
}
return cbb_buffer_add_u(cbb->base, value, 3);
return cbb_add_u(cbb, value, 3);
}
int CBB_add_u32(CBB *cbb, uint32_t value) {
if (!CBB_flush(cbb)) {
return 0;
}
return cbb_buffer_add_u(cbb->base, value, 4);
return cbb_add_u(cbb, value, 4);
}
int CBB_add_u32le(CBB *cbb, uint32_t value) {
@@ -472,10 +475,7 @@ int CBB_add_u32le(CBB *cbb, uint32_t value) {
}
int CBB_add_u64(CBB *cbb, uint64_t value) {
if (!CBB_flush(cbb)) {
return 0;
}
return cbb_buffer_add_u(cbb->base, value, 8);
return cbb_add_u(cbb, value, 8);
}
int CBB_add_u64le(CBB *cbb, uint64_t value) {
@@ -487,20 +487,25 @@ void CBB_discard_child(CBB *cbb) {
return;
}
cbb->base->len = cbb->child->offset;
struct cbb_buffer_st *base = cbb_get_base(cbb);
assert(cbb->child->is_child);
base->len = cbb->child->u.child.offset;
cbb->child->base = NULL;
cbb->child->u.child.base = NULL;
cbb->child = NULL;
}
int CBB_add_asn1_uint64(CBB *cbb, uint64_t value) {
CBB child;
int started = 0;
return CBB_add_asn1_uint64_with_tag(cbb, value, CBS_ASN1_INTEGER);
}
if (!CBB_add_asn1(cbb, &child, CBS_ASN1_INTEGER)) {
return 0;
int CBB_add_asn1_uint64_with_tag(CBB *cbb, uint64_t value, CBS_ASN1_TAG tag) {
CBB child;
if (!CBB_add_asn1(cbb, &child, tag)) {
goto err;
}
int started = 0;
for (size_t i = 0; i < 8; i++) {
uint8_t byte = (value >> 8*(7-i)) & 0xff;
if (!started) {
@@ -511,49 +516,58 @@ int CBB_add_asn1_uint64(CBB *cbb, uint64_t value) {
// If the high bit is set, add a padding byte to make it
// unsigned.
if ((byte & 0x80) && !CBB_add_u8(&child, 0)) {
return 0;
goto err;
}
started = 1;
}
if (!CBB_add_u8(&child, byte)) {
return 0;
goto err;
}
}
// 0 is encoded as a single 0, not the empty string.
if (!started && !CBB_add_u8(&child, 0)) {
return 0;
goto err;
}
return CBB_flush(cbb);
err:
cbb_on_error(cbb);
return 0;
}
int CBB_add_asn1_int64(CBB *cbb, int64_t value) {
return CBB_add_asn1_int64_with_tag(cbb, value, CBS_ASN1_INTEGER);
}
int CBB_add_asn1_int64_with_tag(CBB *cbb, int64_t value, CBS_ASN1_TAG tag) {
if (value >= 0) {
return CBB_add_asn1_uint64(cbb, value);
return CBB_add_asn1_uint64_with_tag(cbb, (uint64_t)value, tag);
}
union {
int64_t i;
uint8_t bytes[sizeof(int64_t)];
} u;
u.i = value;
uint8_t bytes[sizeof(int64_t)];
memcpy(bytes, &value, sizeof(value));
int start = 7;
// Skip leading sign-extension bytes unless they are necessary.
while (start > 0 && (u.bytes[start] == 0xff && (u.bytes[start - 1] & 0x80))) {
while (start > 0 && (bytes[start] == 0xff && (bytes[start - 1] & 0x80))) {
start--;
}
CBB child;
if (!CBB_add_asn1(cbb, &child, CBS_ASN1_INTEGER)) {
return 0;
if (!CBB_add_asn1(cbb, &child, tag)) {
goto err;
}
for (int i = start; i >= 0; i--) {
if (!CBB_add_u8(&child, u.bytes[i])) {
return 0;
if (!CBB_add_u8(&child, bytes[i])) {
goto err;
}
}
return CBB_flush(cbb);
err:
cbb_on_error(cbb);
return 0;
}
int CBB_add_asn1_octet_string(CBB *cbb, const uint8_t *data, size_t data_len) {
@@ -561,6 +575,7 @@ int CBB_add_asn1_octet_string(CBB *cbb, const uint8_t *data, size_t data_len) {
if (!CBB_add_asn1(cbb, &child, CBS_ASN1_OCTETSTRING) ||
!CBB_add_bytes(&child, data, data_len) ||
!CBB_flush(cbb)) {
cbb_on_error(cbb);
return 0;
}
@@ -572,6 +587,7 @@ int CBB_add_asn1_bool(CBB *cbb, int value) {
if (!CBB_add_asn1(cbb, &child, CBS_ASN1_BOOLEAN) ||
!CBB_add_u8(&child, value != 0 ? 0xff : 0) ||
!CBB_flush(cbb)) {
cbb_on_error(cbb);
return 0;
}
@@ -583,30 +599,15 @@ int CBB_add_asn1_bool(CBB *cbb, int value) {
// component and the dot, so |cbs| may be passed into the function again for the
// next value.
static int parse_dotted_decimal(CBS *cbs, uint64_t *out) {
*out = 0;
int seen_digit = 0;
for (;;) {
// Valid terminators for a component are the end of the string or a
// non-terminal dot. If the string ends with a dot, this is not a valid OID
// string.
uint8_t u;
if (!CBS_get_u8(cbs, &u) ||
(u == '.' && CBS_len(cbs) > 0)) {
break;
}
if (u < '0' || u > '9' ||
// Forbid stray leading zeros.
(seen_digit && *out == 0) ||
// Check for overflow.
*out > UINT64_MAX / 10 ||
*out * 10 > UINT64_MAX - (u - '0')) {
return 0;
}
*out = *out * 10 + (u - '0');
seen_digit = 1;
if (!CBS_get_u64_decimal(cbs, out)) {
return 0;
}
// The empty string is not a legal OID component.
return seen_digit;
// The integer must have either ended at the end of the string, or a
// non-terminal dot, which should be consumed. If the string ends with a dot,
// this is not a valid OID string.
uint8_t dot;
return !CBS_get_u8(cbs, &dot) || (dot == '.' && CBS_len(cbs) > 0);
}
int CBB_add_asn1_oid_from_text(CBB *cbb, const char *text, size_t len) {
@@ -672,6 +673,7 @@ int CBB_flush_asn1_set_of(CBB *cbb) {
CBS_init(&cbs, CBB_data(cbb), CBB_len(cbb));
while (CBS_len(&cbs) != 0) {
if (!CBS_get_any_asn1_element(&cbs, NULL, NULL, NULL)) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
num_children++;
@@ -680,16 +682,13 @@ int CBB_flush_asn1_set_of(CBB *cbb) {
if (num_children < 2) {
return 1; // Nothing to do. This is the common case for X.509.
}
if (num_children > ((size_t)-1) / sizeof(CBS)) {
return 0; // Overflow.
}
// Parse out the children and sort. We alias them into a copy of so they
// remain valid as we rewrite |cbb|.
int ret = 0;
size_t buf_len = CBB_len(cbb);
uint8_t *buf = OPENSSL_memdup(CBB_data(cbb), buf_len);
CBS *children = OPENSSL_malloc(num_children * sizeof(CBS));
CBS *children = OPENSSL_calloc(num_children, sizeof(CBS));
if (buf == NULL || children == NULL) {
goto err;
}
@@ -701,14 +700,14 @@ int CBB_flush_asn1_set_of(CBB *cbb) {
}
qsort(children, num_children, sizeof(CBS), compare_set_of_element);
// Rewind |cbb| and write the contents back in the new order.
cbb->base->len = cbb->offset + cbb->pending_len_len;
// Write the contents back in the new order.
uint8_t *out = (uint8_t *)CBB_data(cbb);
size_t offset = 0;
for (size_t i = 0; i < num_children; i++) {
if (!CBB_add_bytes(cbb, CBS_data(&children[i]), CBS_len(&children[i]))) {
goto err;
}
OPENSSL_memcpy(out + offset, CBS_data(&children[i]), CBS_len(&children[i]));
offset += CBS_len(&children[i]);
}
assert(CBB_len(cbb) == buf_len);
assert(offset == buf_len);
ret = 1;
+319 -81
View File
@@ -12,15 +12,18 @@
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_mem.h>
#include <assert.h>
#include <ctype.h>
#include <inttypes.h>
#include <string.h>
#include "internal.h"
#include "../asn1/internal.h"
#include "../internal.h"
#include "internal.h"
void CBS_init(CBS *cbs, const uint8_t *data, size_t len) {
@@ -133,7 +136,7 @@ int CBS_get_u24(CBS *cbs, uint32_t *out) {
if (!cbs_get_u(cbs, &v, 3)) {
return 0;
}
*out = v;
*out = (uint32_t)v;
return 1;
}
@@ -142,7 +145,7 @@ int CBS_get_u32(CBS *cbs, uint32_t *out) {
if (!cbs_get_u(cbs, &v, 4)) {
return 0;
}
*out = v;
*out = (uint32_t)v;
return 1;
}
@@ -216,6 +219,38 @@ 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));
}
int CBS_get_u64_decimal(CBS *cbs, uint64_t *out) {
uint64_t v = 0;
int seen_digit = 0;
while (CBS_len(cbs) != 0) {
uint8_t c = CBS_data(cbs)[0];
if (!OPENSSL_isdigit(c)) {
break;
}
CBS_skip(cbs, 1);
if (// Forbid stray leading zeros.
(v == 0 && seen_digit) ||
// Check for overflow.
v > UINT64_MAX / 10 || //
v * 10 > UINT64_MAX - (c - '0')) {
return 0;
}
v = v * 10 + (c - '0');
seen_digit = 1;
}
*out = v;
return seen_digit;
}
// parse_base128_integer reads a big-endian base-128 integer from |cbs| and sets
// |*out| to the result. This is the encoding used in DER for both high tag
// number form and OID components.
@@ -243,7 +278,7 @@ static int parse_base128_integer(CBS *cbs, uint64_t *out) {
return 1;
}
static int parse_asn1_tag(CBS *cbs, unsigned *out) {
static int parse_asn1_tag(CBS *cbs, CBS_ASN1_TAG *out) {
uint8_t tag_byte;
if (!CBS_get_u8(cbs, &tag_byte)) {
return 0;
@@ -254,38 +289,52 @@ 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).
unsigned tag = ((unsigned)tag_byte & 0xe0) << CBS_ASN1_TAG_SHIFT;
unsigned tag_number = tag_byte & 0x1f;
// continuation bytes contain the tag number.
CBS_ASN1_TAG tag = ((CBS_ASN1_TAG)tag_byte & 0xe0) << CBS_ASN1_TAG_SHIFT;
CBS_ASN1_TAG tag_number = tag_byte & 0x1f;
if (tag_number == 0x1f) {
uint64_t v;
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;
}
tag_number = (unsigned)v;
tag_number = (CBS_ASN1_TAG)v;
}
tag |= tag_number;
// Tag [UNIVERSAL 0] is reserved for use by the encoding. Reject it here to
// avoid some ambiguity around ANY values and BER indefinite-length EOCs. See
// https://crbug.com/boringssl/455.
if ((tag & ~CBS_ASN1_CONSTRUCTED) == 0) {
return 0;
}
*out = tag;
return 1;
}
static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, unsigned *out_tag,
size_t *out_header_len, int ber_ok) {
static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag,
size_t *out_header_len, int *out_ber_found,
int *out_indefinite, int ber_ok) {
CBS header = *cbs;
CBS throwaway;
if (out == NULL) {
out = &throwaway;
}
if (ber_ok) {
*out_ber_found = 0;
*out_indefinite = 0;
} else {
assert(out_ber_found == NULL);
assert(out_indefinite == NULL);
}
unsigned tag;
CBS_ASN1_TAG tag;
if (!parse_asn1_tag(&header, &tag)) {
return 0;
}
@@ -321,27 +370,39 @@ 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;
*out_indefinite = 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) {
@@ -357,7 +418,7 @@ static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, unsigned *out_tag,
return CBS_get_bytes(cbs, out, len);
}
int CBS_get_any_asn1(CBS *cbs, CBS *out, unsigned *out_tag) {
int CBS_get_any_asn1(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag) {
size_t header_len;
if (!CBS_get_any_asn1_element(cbs, out, out_tag, &header_len)) {
return 0;
@@ -371,22 +432,26 @@ int CBS_get_any_asn1(CBS *cbs, CBS *out, unsigned *out_tag) {
return 1;
}
int CBS_get_any_asn1_element(CBS *cbs, CBS *out, unsigned *out_tag,
int CBS_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag,
size_t *out_header_len) {
return cbs_get_any_asn1_element(cbs, out, out_tag, out_header_len,
0 /* DER only */);
return cbs_get_any_asn1_element(cbs, out, out_tag, out_header_len, NULL, NULL,
/*ber_ok=*/0);
}
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 */);
int CBS_get_any_ber_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag,
size_t *out_header_len, int *out_ber_found,
int *out_indefinite) {
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, out_indefinite,
/*ber_ok=*/1);
}
static int cbs_get_asn1(CBS *cbs, CBS *out, unsigned tag_value,
static int cbs_get_asn1(CBS *cbs, CBS *out, CBS_ASN1_TAG tag_value,
int skip_header) {
size_t header_len;
unsigned tag;
CBS_ASN1_TAG tag;
CBS throwaway;
if (out == NULL) {
@@ -406,49 +471,30 @@ static int cbs_get_asn1(CBS *cbs, CBS *out, unsigned tag_value,
return 1;
}
int CBS_get_asn1(CBS *cbs, CBS *out, unsigned tag_value) {
int CBS_get_asn1(CBS *cbs, CBS *out, CBS_ASN1_TAG tag_value) {
return cbs_get_asn1(cbs, out, tag_value, 1 /* skip header */);
}
int CBS_get_asn1_element(CBS *cbs, CBS *out, unsigned tag_value) {
int CBS_get_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG tag_value) {
return cbs_get_asn1(cbs, out, tag_value, 0 /* include header */);
}
int CBS_peek_asn1_tag(const CBS *cbs, unsigned tag_value) {
if (CBS_len(cbs) < 1) {
return 0;
}
int CBS_peek_asn1_tag(const CBS *cbs, CBS_ASN1_TAG tag_value) {
CBS copy = *cbs;
unsigned actual_tag;
CBS_ASN1_TAG actual_tag;
return parse_asn1_tag(&copy, &actual_tag) && tag_value == actual_tag;
}
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.
@@ -462,36 +508,23 @@ 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.
uint8_t sign_extend[sizeof(int64_t)];
memset(sign_extend, is_negative ? 0xff : 0, sizeof(sign_extend));
for (size_t i = 0; i < len; i++) {
u.bytes[i] = data[len - i - 1];
sign_extend[i] = data[len - i - 1];
}
*out = u.i;
memcpy(out, sign_extend, sizeof(sign_extend));
return 1;
}
@@ -511,7 +544,7 @@ int CBS_get_asn1_bool(CBS *cbs, int *out) {
return 1;
}
int CBS_get_optional_asn1(CBS *cbs, CBS *out, int *out_present, unsigned tag) {
int CBS_get_optional_asn1(CBS *cbs, CBS *out, int *out_present, CBS_ASN1_TAG tag) {
int present = 0;
if (CBS_peek_asn1_tag(cbs, tag)) {
@@ -529,7 +562,7 @@ int CBS_get_optional_asn1(CBS *cbs, CBS *out, int *out_present, unsigned tag) {
}
int CBS_get_optional_asn1_octet_string(CBS *cbs, CBS *out, int *out_present,
unsigned tag) {
CBS_ASN1_TAG tag) {
CBS child;
int present;
if (!CBS_get_optional_asn1(cbs, &child, &present, tag)) {
@@ -550,7 +583,7 @@ int CBS_get_optional_asn1_octet_string(CBS *cbs, CBS *out, int *out_present,
return 1;
}
int CBS_get_optional_asn1_uint64(CBS *cbs, uint64_t *out, unsigned tag,
int CBS_get_optional_asn1_uint64(CBS *cbs, uint64_t *out, CBS_ASN1_TAG tag,
uint64_t default_value) {
CBS child;
int present;
@@ -568,7 +601,7 @@ int CBS_get_optional_asn1_uint64(CBS *cbs, uint64_t *out, unsigned tag,
return 1;
}
int CBS_get_optional_asn1_bool(CBS *cbs, int *out, unsigned tag,
int CBS_get_optional_asn1_bool(CBS *cbs, int *out, CBS_ASN1_TAG tag,
int default_value) {
CBS child, child2;
int present;
@@ -635,12 +668,59 @@ 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);
snprintf(buf, sizeof(buf), "%" PRIu64, v);
return CBB_add_bytes(out, (const uint8_t *)buf, strlen(buf));
}
int CBS_is_valid_asn1_oid(const CBS *cbs) {
if (CBS_len(cbs) == 0) {
return 0; // OID encodings cannot be empty.
}
CBS copy = *cbs;
uint8_t v, prev = 0;
while (CBS_get_u8(&copy, &v)) {
// OID encodings are a sequence of minimally-encoded base-128 integers (see
// |parse_base128_integer|). If |prev|'s MSB was clear, it was the last byte
// of an integer (or |v| is the first byte). |v| is then the first byte of
// the next integer. If first byte of an integer is 0x80, it is not
// minimally-encoded.
if ((prev & 0x80) == 0 && v == 0x80) {
return 0;
}
prev = v;
}
// The last byte should must end an integer encoding.
return (prev & 0x80) == 0;
}
char *CBS_asn1_oid_to_text(const CBS *cbs) {
CBB cbb;
if (!CBB_init(&cbb, 32)) {
@@ -686,3 +766,161 @@ err:
CBB_cleanup(&cbb);
return NULL;
}
static int cbs_get_two_digits(CBS *cbs, int *out) {
uint8_t first_digit, second_digit;
if (!CBS_get_u8(cbs, &first_digit)) {
return 0;
}
if (!OPENSSL_isdigit(first_digit)) {
return 0;
}
if (!CBS_get_u8(cbs, &second_digit)) {
return 0;
}
if (!OPENSSL_isdigit(second_digit)) {
return 0;
}
*out = (first_digit - '0') * 10 + (second_digit - '0');
return 1;
}
static int is_valid_day(int year, int month, int day) {
if (day < 1) {
return 0;
}
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return day <= 31;
case 4:
case 6:
case 9:
case 11:
return day <= 30;
case 2:
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return day <= 29;
} else {
return day <= 28;
}
default:
return 0;
}
}
static int CBS_parse_rfc5280_time_internal(const CBS *cbs, int is_gentime,
int allow_timezone_offset,
struct tm *out_tm) {
int year, month, day, hour, min, sec, tmp;
CBS copy = *cbs;
uint8_t tz;
if (is_gentime) {
if (!cbs_get_two_digits(&copy, &tmp)) {
return 0;
}
year = tmp * 100;
if (!cbs_get_two_digits(&copy, &tmp)) {
return 0;
}
year += tmp;
} else {
year = 1900;
if (!cbs_get_two_digits(&copy, &tmp)) {
return 0;
}
year += tmp;
if (year < 1950) {
year += 100;
}
if (year >= 2050) {
return 0; // A Generalized time must be used.
}
}
if (!cbs_get_two_digits(&copy, &month) || month < 1 ||
month > 12 || // Reject invalid months.
!cbs_get_two_digits(&copy, &day) ||
!is_valid_day(year, month, day) || // Reject invalid days.
!cbs_get_two_digits(&copy, &hour) ||
hour > 23 || // Reject invalid hours.
!cbs_get_two_digits(&copy, &min) ||
min > 59 || // Reject invalid minutes.
!cbs_get_two_digits(&copy, &sec) || sec > 59 || !CBS_get_u8(&copy, &tz)) {
return 0;
}
int offset_sign = 0;
switch (tz) {
case 'Z':
break; // We correctly have 'Z' on the end as per spec.
case '+':
offset_sign = 1;
break; // Should not be allowed per RFC 5280.
case '-':
offset_sign = -1;
break; // Should not be allowed per RFC 5280.
default:
return 0; // Reject anything else after the time.
}
// If allow_timezone_offset is non-zero, allow for a four digit timezone
// offset to be specified even though this is not allowed by RFC 5280. We are
// permissive of this for UTCTimes due to the unfortunate existence of
// artisinally rolled long lived certificates that were baked into places that
// are now difficult to change. These certificates were generated with the
// 'openssl' command that permissively allowed the creation of certificates
// with notBefore and notAfter times specified as strings for direct
// certificate inclusion on the command line. For context see cl/237068815.
//
// TODO(bbe): This has been expunged from public web-pki as the ecosystem has
// managed to encourage CA compliance with standards. We should find a way to
// get rid of this or make it off by default.
int offset_seconds = 0;
if (offset_sign != 0) {
if (!allow_timezone_offset) {
return 0;
}
int offset_hours, offset_minutes;
if (!cbs_get_two_digits(&copy, &offset_hours) ||
offset_hours > 23 || // Reject invalid hours.
!cbs_get_two_digits(&copy, &offset_minutes) ||
offset_minutes > 59) { // Reject invalid minutes.
return 0;
}
offset_seconds = offset_sign * (offset_hours * 3600 + offset_minutes * 60);
}
if (CBS_len(&copy) != 0) {
return 0; // Reject invalid lengths.
}
if (out_tm != NULL) {
// Fill in the tm fields corresponding to what we validated.
out_tm->tm_year = year - 1900;
out_tm->tm_mon = month - 1;
out_tm->tm_mday = day;
out_tm->tm_hour = hour;
out_tm->tm_min = min;
out_tm->tm_sec = sec;
if (offset_seconds && !OPENSSL_gmtime_adj(out_tm, 0, offset_seconds)) {
return 0;
}
}
return 1;
}
int CBS_parse_generalized_time(const CBS *cbs, struct tm *out_tm,
int allow_timezone_offset) {
return CBS_parse_rfc5280_time_internal(cbs, 1, allow_timezone_offset, out_tm);
}
int CBS_parse_utc_time(const CBS *cbs, struct tm *out_tm,
int allow_timezone_offset) {
return CBS_parse_rfc5280_time_internal(cbs, 0, allow_timezone_offset, out_tm);
}
@@ -54,8 +54,8 @@ OPENSSL_EXPORT int CBS_asn1_ber_to_der(CBS *in, CBS *out,
// It returns one on success and zero otherwise.
OPENSSL_EXPORT int CBS_get_asn1_implicit_string(CBS *in, CBS *out,
uint8_t **out_storage,
unsigned outer_tag,
unsigned inner_tag);
CBS_ASN1_TAG outer_tag,
CBS_ASN1_TAG inner_tag);
// CBB_finish_i2d calls |CBB_finish| on |cbb| which must have been initialized
// with |CBB_init|. If |outp| is not NULL then the result is written to |*outp|
@@ -67,28 +67,6 @@ OPENSSL_EXPORT int CBS_get_asn1_implicit_string(CBS *in, CBS *out,
int CBB_finish_i2d(CBB *cbb, uint8_t **outp);
// Unicode utilities.
// The following functions read one Unicode code point from |cbs| with the
// corresponding encoding and store it in |*out|. They return one on success and
// zero on error.
OPENSSL_EXPORT int cbs_get_utf8(CBS *cbs, uint32_t *out);
OPENSSL_EXPORT int cbs_get_latin1(CBS *cbs, uint32_t *out);
OPENSSL_EXPORT int cbs_get_ucs2_be(CBS *cbs, uint32_t *out);
OPENSSL_EXPORT int cbs_get_utf32_be(CBS *cbs, uint32_t *out);
// cbb_get_utf8_len returns the number of bytes needed to represent |u| in
// UTF-8.
OPENSSL_EXPORT size_t cbb_get_utf8_len(uint32_t u);
// The following functions encode |u| to |cbb| with the corresponding
// encoding. They return one on success and zero on error.
OPENSSL_EXPORT int cbb_add_utf8(CBB *cbb, uint32_t u);
OPENSSL_EXPORT int cbb_add_latin1(CBB *cbb, uint32_t u);
OPENSSL_EXPORT int cbb_add_ucs2_be(CBB *cbb, uint32_t u);
OPENSSL_EXPORT int cbb_add_utf32_be(CBB *cbb, uint32_t u);
#if defined(__cplusplus)
} // extern C
#endif
@@ -38,7 +38,7 @@ static int is_valid_code_point(uint32_t v) {
// TOP_BITS returns a byte with the top |n| bits set.
#define TOP_BITS(n) ((uint8_t)~BOTTOM_BITS(8 - (n)))
int cbs_get_utf8(CBS *cbs, uint32_t *out) {
int CBS_get_utf8(CBS *cbs, uint32_t *out) {
uint8_t c;
if (!CBS_get_u8(cbs, &c)) {
return 0;
@@ -80,7 +80,7 @@ int cbs_get_utf8(CBS *cbs, uint32_t *out) {
return 1;
}
int cbs_get_latin1(CBS *cbs, uint32_t *out) {
int CBS_get_latin1(CBS *cbs, uint32_t *out) {
uint8_t c;
if (!CBS_get_u8(cbs, &c)) {
return 0;
@@ -89,7 +89,7 @@ int cbs_get_latin1(CBS *cbs, uint32_t *out) {
return 1;
}
int cbs_get_ucs2_be(CBS *cbs, uint32_t *out) {
int CBS_get_ucs2_be(CBS *cbs, uint32_t *out) {
// Note UCS-2 (used by BMPString) does not support surrogates.
uint16_t c;
if (!CBS_get_u16(cbs, &c) ||
@@ -100,11 +100,11 @@ int cbs_get_ucs2_be(CBS *cbs, uint32_t *out) {
return 1;
}
int cbs_get_utf32_be(CBS *cbs, uint32_t *out) {
int CBS_get_utf32_be(CBS *cbs, uint32_t *out) {
return CBS_get_u32(cbs, out) && is_valid_code_point(*out);
}
size_t cbb_get_utf8_len(uint32_t u) {
size_t CBB_get_utf8_len(uint32_t u) {
if (u <= 0x7f) {
return 1;
}
@@ -117,7 +117,7 @@ size_t cbb_get_utf8_len(uint32_t u) {
return 4;
}
int cbb_add_utf8(CBB *cbb, uint32_t u) {
int CBB_add_utf8(CBB *cbb, uint32_t u) {
if (!is_valid_code_point(u)) {
return 0;
}
@@ -142,14 +142,14 @@ int cbb_add_utf8(CBB *cbb, uint32_t u) {
return 0;
}
int cbb_add_latin1(CBB *cbb, uint32_t u) {
int CBB_add_latin1(CBB *cbb, uint32_t u) {
return u <= 0xff && CBB_add_u8(cbb, (uint8_t)u);
}
int cbb_add_ucs2_be(CBB *cbb, uint32_t u) {
int CBB_add_ucs2_be(CBB *cbb, uint32_t u) {
return u <= 0xffff && is_valid_code_point(u) && CBB_add_u16(cbb, (uint16_t)u);
}
int cbb_add_utf32_be(CBB *cbb, uint32_t u) {
int CBB_add_utf32_be(CBB *cbb, uint32_t u) {
return is_valid_code_point(u) && CBB_add_u32(cbb, u);
}
@@ -3,17 +3,9 @@
// This file is generated from a similarly-named Perl script in the BoringSSL
// source tree. Do not edit by hand.
#if !defined(__has_feature)
#define __has_feature(x) 0
#endif
#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM)
#define OPENSSL_NO_ASM
#endif
#include <CCryptoBoringSSL_asm_base.h>
#if !defined(OPENSSL_NO_ASM)
#if defined(BORINGSSL_PREFIX)
#include <CCryptoBoringSSL_boringssl_prefix_symbols_asm.h>
#endif
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_ARM) && defined(__APPLE__)
#include <CCryptoBoringSSL_arm_arch.h>
@ Silence ARMv8 deprecated IT instruction warnings. This file is used by both
@@ -39,49 +31,19 @@ Lsigma:
.long 0x61707865,0x3320646e,0x79622d32,0x6b206574 @ endian-neutral
Lone:
.long 1,0,0,0
#if __ARM_MAX_ARCH__>=7
LOPENSSL_armcap:
.word OPENSSL_armcap_P-LChaCha20_ctr32
#else
.word -1
#endif
.globl _ChaCha20_ctr32
.private_extern _ChaCha20_ctr32
.globl _ChaCha20_ctr32_nohw
.private_extern _ChaCha20_ctr32_nohw
#ifdef __thumb2__
.thumb_func _ChaCha20_ctr32
.thumb_func _ChaCha20_ctr32_nohw
#endif
.align 5
_ChaCha20_ctr32:
LChaCha20_ctr32:
_ChaCha20_ctr32_nohw:
ldr r12,[sp,#0] @ pull pointer to counter and nonce
stmdb sp!,{r0,r1,r2,r4-r11,lr}
#if __ARM_ARCH__<7 && !defined(__thumb2__)
sub r14,pc,#16 @ _ChaCha20_ctr32
#else
adr r14,LChaCha20_ctr32
#endif
cmp r2,#0 @ len==0?
#ifdef __thumb2__
itt eq
#endif
addeq sp,sp,#4*3
beq Lno_data
#if __ARM_MAX_ARCH__>=7
cmp r2,#192 @ test len
bls Lshort
ldr r4,[r14,#-32]
ldr r4,[r14,r4]
# ifdef __APPLE__
ldr r4,[r4]
# endif
tst r4,#ARMV7_NEON
bne LChaCha20_neon
Lshort:
#endif
adr r14,Lsigma
ldmia r12,{r4,r5,r6,r7} @ load counter and nonce
sub sp,sp,#4*(16) @ off-load area
sub r14,r14,#64 @ Lsigma
stmdb sp!,{r4,r5,r6,r7} @ copy counter and nonce
ldmia r3,{r4,r5,r6,r7,r8,r9,r10,r11} @ load key
ldmia r14,{r0,r1,r2,r3} @ load sigma
@@ -242,8 +204,8 @@ Loop:
ldr r8,[sp,#4*(0)] @ load key material
ldr r9,[sp,#4*(1)]
#if __ARM_ARCH__>=6 || !defined(__ARMEB__)
# if __ARM_ARCH__<7
#if __ARM_ARCH>=6 || !defined(__ARMEB__)
# if __ARM_ARCH<7
orr r10,r12,r14
tst r10,#3 @ are input and output aligned?
ldr r10,[sp,#4*(2)]
@@ -269,7 +231,7 @@ Loop:
# endif
ldrhs r10,[r12,#-8]
ldrhs r11,[r12,#-4]
# if __ARM_ARCH__>=6 && defined(__ARMEB__)
# if __ARM_ARCH>=6 && defined(__ARMEB__)
rev r0,r0
rev r1,r1
rev r2,r2
@@ -306,7 +268,7 @@ Loop:
# endif
ldrhs r10,[r12,#-8]
ldrhs r11,[r12,#-4]
# if __ARM_ARCH__>=6 && defined(__ARMEB__)
# if __ARM_ARCH>=6 && defined(__ARMEB__)
rev r4,r4
rev r5,r5
rev r6,r6
@@ -351,7 +313,7 @@ Loop:
# endif
ldrhs r10,[r12,#-8]
ldrhs r11,[r12,#-4]
# if __ARM_ARCH__>=6 && defined(__ARMEB__)
# if __ARM_ARCH>=6 && defined(__ARMEB__)
rev r0,r0
rev r1,r1
rev r2,r2
@@ -393,7 +355,7 @@ Loop:
# endif
ldrhs r10,[r12,#-8]
ldrhs r11,[r12,#-4]
# if __ARM_ARCH__>=6 && defined(__ARMEB__)
# if __ARM_ARCH>=6 && defined(__ARMEB__)
rev r4,r4
rev r5,r5
rev r6,r6
@@ -424,7 +386,7 @@ Loop:
bhi Loop_outer
beq Ldone
# if __ARM_ARCH__<7
# if __ARM_ARCH<7
b Ltail
.align 4
@@ -432,7 +394,7 @@ Lunaligned:@ unaligned endian-neutral path
cmp r11,#64 @ restore flags
# endif
#endif
#if __ARM_ARCH__<7
#if __ARM_ARCH<7
ldr r11,[sp,#4*(3)]
add r0,r0,r8 @ accumulate key material
add r1,r1,r9
@@ -808,21 +770,21 @@ Loop_tail:
Ldone:
add sp,sp,#4*(32+3)
Lno_data:
ldmia sp!,{r4,r5,r6,r7,r8,r9,r10,r11,pc}
#if __ARM_MAX_ARCH__>=7
.globl _ChaCha20_ctr32_neon
.private_extern _ChaCha20_ctr32_neon
#ifdef __thumb2__
.thumb_func ChaCha20_neon
.thumb_func _ChaCha20_ctr32_neon
#endif
.align 5
ChaCha20_neon:
_ChaCha20_ctr32_neon:
ldr r12,[sp,#0] @ pull pointer to counter and nonce
stmdb sp!,{r0,r1,r2,r4-r11,lr}
LChaCha20_neon:
adr r14,Lsigma
vstmdb sp!,{d8,d9,d10,d11,d12,d13,d14,d15} @ ABI spec says so
stmdb sp!,{r0,r1,r2,r3}
@@ -1491,13 +1453,8 @@ Ldone_neon:
add sp,sp,#4*(16+3)
ldmia sp!,{r4,r5,r6,r7,r8,r9,r10,r11,pc}
.comm _OPENSSL_armcap_P,4
.non_lazy_symbol_pointer
OPENSSL_armcap_P:
.indirect_symbol _OPENSSL_armcap_P
.long 0
#endif
#endif // !OPENSSL_NO_ASM
#endif // !OPENSSL_NO_ASM && defined(OPENSSL_ARM) && defined(__APPLE__)
#endif // defined(__arm__) && defined(__APPLE__)
#if defined(__linux__) && defined(__ELF__)
.section .note.GNU-stack,"",%progbits
@@ -3,18 +3,9 @@
// This file is generated from a similarly-named Perl script in the BoringSSL
// source tree. Do not edit by hand.
#if !defined(__has_feature)
#define __has_feature(x) 0
#endif
#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM)
#define OPENSSL_NO_ASM
#endif
#include <CCryptoBoringSSL_asm_base.h>
#if !defined(OPENSSL_NO_ASM)
#if defined(__arm__)
#if defined(BORINGSSL_PREFIX)
#include <CCryptoBoringSSL_boringssl_prefix_symbols_asm.h>
#endif
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_ARM) && defined(__ELF__)
#include <CCryptoBoringSSL_arm_arch.h>
@ Silence ARMv8 deprecated IT instruction warnings. This file is used by both
@@ -40,47 +31,17 @@
.long 0x61707865,0x3320646e,0x79622d32,0x6b206574 @ endian-neutral
.Lone:
.long 1,0,0,0
#if __ARM_MAX_ARCH__>=7
.LOPENSSL_armcap:
.word OPENSSL_armcap_P-.LChaCha20_ctr32
#else
.word -1
#endif
.globl ChaCha20_ctr32
.hidden ChaCha20_ctr32
.type ChaCha20_ctr32,%function
.globl ChaCha20_ctr32_nohw
.hidden ChaCha20_ctr32_nohw
.type ChaCha20_ctr32_nohw,%function
.align 5
ChaCha20_ctr32:
.LChaCha20_ctr32:
ChaCha20_ctr32_nohw:
ldr r12,[sp,#0] @ pull pointer to counter and nonce
stmdb sp!,{r0,r1,r2,r4-r11,lr}
#if __ARM_ARCH__<7 && !defined(__thumb2__)
sub r14,pc,#16 @ ChaCha20_ctr32
#else
adr r14,.LChaCha20_ctr32
#endif
cmp r2,#0 @ len==0?
#ifdef __thumb2__
itt eq
#endif
addeq sp,sp,#4*3
beq .Lno_data
#if __ARM_MAX_ARCH__>=7
cmp r2,#192 @ test len
bls .Lshort
ldr r4,[r14,#-32]
ldr r4,[r14,r4]
# ifdef __APPLE__
ldr r4,[r4]
# endif
tst r4,#ARMV7_NEON
bne .LChaCha20_neon
.Lshort:
#endif
adr r14,.Lsigma
ldmia r12,{r4,r5,r6,r7} @ load counter and nonce
sub sp,sp,#4*(16) @ off-load area
sub r14,r14,#64 @ .Lsigma
stmdb sp!,{r4,r5,r6,r7} @ copy counter and nonce
ldmia r3,{r4,r5,r6,r7,r8,r9,r10,r11} @ load key
ldmia r14,{r0,r1,r2,r3} @ load sigma
@@ -241,8 +202,8 @@ ChaCha20_ctr32:
ldr r8,[sp,#4*(0)] @ load key material
ldr r9,[sp,#4*(1)]
#if __ARM_ARCH__>=6 || !defined(__ARMEB__)
# if __ARM_ARCH__<7
#if __ARM_ARCH>=6 || !defined(__ARMEB__)
# if __ARM_ARCH<7
orr r10,r12,r14
tst r10,#3 @ are input and output aligned?
ldr r10,[sp,#4*(2)]
@@ -268,7 +229,7 @@ ChaCha20_ctr32:
# endif
ldrhs r10,[r12,#-8]
ldrhs r11,[r12,#-4]
# if __ARM_ARCH__>=6 && defined(__ARMEB__)
# if __ARM_ARCH>=6 && defined(__ARMEB__)
rev r0,r0
rev r1,r1
rev r2,r2
@@ -305,7 +266,7 @@ ChaCha20_ctr32:
# endif
ldrhs r10,[r12,#-8]
ldrhs r11,[r12,#-4]
# if __ARM_ARCH__>=6 && defined(__ARMEB__)
# if __ARM_ARCH>=6 && defined(__ARMEB__)
rev r4,r4
rev r5,r5
rev r6,r6
@@ -350,7 +311,7 @@ ChaCha20_ctr32:
# endif
ldrhs r10,[r12,#-8]
ldrhs r11,[r12,#-4]
# if __ARM_ARCH__>=6 && defined(__ARMEB__)
# if __ARM_ARCH>=6 && defined(__ARMEB__)
rev r0,r0
rev r1,r1
rev r2,r2
@@ -392,7 +353,7 @@ ChaCha20_ctr32:
# endif
ldrhs r10,[r12,#-8]
ldrhs r11,[r12,#-4]
# if __ARM_ARCH__>=6 && defined(__ARMEB__)
# if __ARM_ARCH>=6 && defined(__ARMEB__)
rev r4,r4
rev r5,r5
rev r6,r6
@@ -423,7 +384,7 @@ ChaCha20_ctr32:
bhi .Loop_outer
beq .Ldone
# if __ARM_ARCH__<7
# if __ARM_ARCH<7
b .Ltail
.align 4
@@ -431,7 +392,7 @@ ChaCha20_ctr32:
cmp r11,#64 @ restore flags
# endif
#endif
#if __ARM_ARCH__<7
#if __ARM_ARCH<7
ldr r11,[sp,#4*(3)]
add r0,r0,r8 @ accumulate key material
add r1,r1,r9
@@ -807,19 +768,19 @@ ChaCha20_ctr32:
.Ldone:
add sp,sp,#4*(32+3)
.Lno_data:
ldmia sp!,{r4,r5,r6,r7,r8,r9,r10,r11,pc}
.size ChaCha20_ctr32,.-ChaCha20_ctr32
.size ChaCha20_ctr32_nohw,.-ChaCha20_ctr32_nohw
#if __ARM_MAX_ARCH__>=7
.arch armv7-a
.fpu neon
.type ChaCha20_neon,%function
.globl ChaCha20_ctr32_neon
.hidden ChaCha20_ctr32_neon
.type ChaCha20_ctr32_neon,%function
.align 5
ChaCha20_neon:
ChaCha20_ctr32_neon:
ldr r12,[sp,#0] @ pull pointer to counter and nonce
stmdb sp!,{r0,r1,r2,r4-r11,lr}
.LChaCha20_neon:
adr r14,.Lsigma
vstmdb sp!,{d8,d9,d10,d11,d12,d13,d14,d15} @ ABI spec says so
stmdb sp!,{r0,r1,r2,r3}
@@ -1487,12 +1448,9 @@ ChaCha20_neon:
vldmia sp,{d8,d9,d10,d11,d12,d13,d14,d15}
add sp,sp,#4*(16+3)
ldmia sp!,{r4,r5,r6,r7,r8,r9,r10,r11,pc}
.size ChaCha20_neon,.-ChaCha20_neon
.comm OPENSSL_armcap_P,4,4
.size ChaCha20_ctr32_neon,.-ChaCha20_ctr32_neon
#endif
#endif
#endif // !OPENSSL_NO_ASM
.section .note.GNU-stack,"",%progbits
#endif // !OPENSSL_NO_ASM && defined(OPENSSL_ARM) && defined(__ELF__)
#endif // defined(__arm__) && defined(__linux__)
#if defined(__linux__) && defined(__ELF__)
.section .note.GNU-stack,"",%progbits
@@ -3,21 +3,11 @@
// This file is generated from a similarly-named Perl script in the BoringSSL
// source tree. Do not edit by hand.
#if !defined(__has_feature)
#define __has_feature(x) 0
#endif
#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM)
#define OPENSSL_NO_ASM
#endif
#include <CCryptoBoringSSL_asm_base.h>
#if !defined(OPENSSL_NO_ASM)
#if defined(BORINGSSL_PREFIX)
#include <CCryptoBoringSSL_boringssl_prefix_symbols_asm.h>
#endif
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_AARCH64) && defined(__APPLE__)
#include <CCryptoBoringSSL_arm_arch.h>
.section __TEXT,__const
.align 5
@@ -30,25 +20,11 @@ Lone:
.text
.globl _ChaCha20_ctr32
.private_extern _ChaCha20_ctr32
.globl _ChaCha20_ctr32_nohw
.private_extern _ChaCha20_ctr32_nohw
.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
#else
adrp x5,_OPENSSL_armcap_P@PAGE
#endif
cmp x2,#192
b.lo Lshort
ldr w17,[x5,_OPENSSL_armcap_P@PAGEOFF]
tst w17,#ARMV7_NEON
b.ne ChaCha20_neon
Lshort:
_ChaCha20_ctr32_nohw:
AARCH64_SIGN_LINK_REGISTER
stp x29,x30,[sp,#-96]!
add x29,sp,#0
@@ -66,7 +42,7 @@ Lshort:
ldp x24,x25,[x3] // load key
ldp x26,x27,[x3,#16]
ldp x28,x30,[x4] // load counter
#ifdef __ARMEB__
#ifdef __AARCH64EB__
ror x24,x24,#32
ror x25,x25,#32
ror x26,x26,#32
@@ -227,7 +203,7 @@ Loop:
add x20,x20,x21,lsl#32
ldp x19,x21,[x1,#48]
add x1,x1,#64
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev x5,x5
rev x7,x7
rev x9,x9
@@ -263,7 +239,6 @@ Loop:
ldp x27,x28,[x29,#80]
ldp x29,x30,[sp],#96
AARCH64_VALIDATE_LINK_REGISTER
Labort:
ret
.align 4
@@ -284,7 +259,7 @@ Less_than_64:
add x15,x15,x16,lsl#32
add x17,x17,x19,lsl#32
add x20,x20,x21,lsl#32
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev x5,x5
rev x7,x7
rev x9,x9
@@ -323,9 +298,11 @@ Loop_tail:
ret
.globl _ChaCha20_ctr32_neon
.private_extern _ChaCha20_ctr32_neon
.align 5
ChaCha20_neon:
_ChaCha20_ctr32_neon:
AARCH64_SIGN_LINK_REGISTER
stp x29,x30,[sp,#-96]!
add x29,sp,#0
@@ -350,7 +327,7 @@ ChaCha20_neon:
ldp x28,x30,[x4] // load counter
ld1 {v27.4s},[x4]
ld1 {v31.4s},[x5]
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev64 v24.4s,v24.4s
ror x24,x24,#32
ror x25,x25,#32
@@ -648,7 +625,7 @@ Loop_neon:
add x20,x20,x21,lsl#32
ldp x19,x21,[x1,#48]
add x1,x1,#64
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev x5,x5
rev x7,x7
rev x9,x9
@@ -728,7 +705,7 @@ Ltail_neon:
add x20,x20,x21,lsl#32
ldp x19,x21,[x1,#48]
add x1,x1,#64
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev x5,x5
rev x7,x7
rev x9,x9
@@ -846,7 +823,7 @@ L512_or_more_neon:
ldp x28,x30,[x4] // load counter
ld1 {v27.4s},[x4]
ld1 {v31.4s},[x5]
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev64 v24.4s,v24.4s
ror x24,x24,#32
ror x25,x25,#32
@@ -1359,7 +1336,7 @@ Loop_upper_neon:
add x20,x20,x21,lsl#32
ldp x19,x21,[x1,#48]
add x1,x1,#64
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev x5,x5
rev x7,x7
rev x9,x9
@@ -1873,7 +1850,7 @@ Loop_lower_neon:
add x1,x1,#64
add v21.4s,v21.4s,v25.4s
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev x5,x5
rev x7,x7
rev x9,x9
@@ -1990,7 +1967,7 @@ Ldone_512_neon:
AARCH64_VALIDATE_LINK_REGISTER
ret
#endif // !OPENSSL_NO_ASM
#endif // !OPENSSL_NO_ASM && defined(OPENSSL_AARCH64) && defined(__APPLE__)
#endif // defined(__aarch64__) && defined(__APPLE__)
#if defined(__linux__) && defined(__ELF__)
.section .note.GNU-stack,"",%progbits
@@ -3,22 +3,11 @@
// This file is generated from a similarly-named Perl script in the BoringSSL
// source tree. Do not edit by hand.
#if !defined(__has_feature)
#define __has_feature(x) 0
#endif
#if __has_feature(memory_sanitizer) && !defined(OPENSSL_NO_ASM)
#define OPENSSL_NO_ASM
#endif
#include <CCryptoBoringSSL_asm_base.h>
#if !defined(OPENSSL_NO_ASM)
#if defined(__aarch64__)
#if defined(BORINGSSL_PREFIX)
#include <CCryptoBoringSSL_boringssl_prefix_symbols_asm.h>
#endif
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_AARCH64) && defined(__ELF__)
#include <CCryptoBoringSSL_arm_arch.h>
.section .rodata
.align 5
@@ -31,25 +20,11 @@
.text
.globl ChaCha20_ctr32
.hidden ChaCha20_ctr32
.type ChaCha20_ctr32,%function
.globl ChaCha20_ctr32_nohw
.hidden ChaCha20_ctr32_nohw
.type ChaCha20_ctr32_nohw,%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
#else
adrp x5,OPENSSL_armcap_P
#endif
cmp x2,#192
b.lo .Lshort
ldr w17,[x5,:lo12:OPENSSL_armcap_P]
tst w17,#ARMV7_NEON
b.ne ChaCha20_neon
.Lshort:
ChaCha20_ctr32_nohw:
AARCH64_SIGN_LINK_REGISTER
stp x29,x30,[sp,#-96]!
add x29,sp,#0
@@ -67,7 +42,7 @@ ChaCha20_ctr32:
ldp x24,x25,[x3] // load key
ldp x26,x27,[x3,#16]
ldp x28,x30,[x4] // load counter
#ifdef __ARMEB__
#ifdef __AARCH64EB__
ror x24,x24,#32
ror x25,x25,#32
ror x26,x26,#32
@@ -228,7 +203,7 @@ ChaCha20_ctr32:
add x20,x20,x21,lsl#32
ldp x19,x21,[x1,#48]
add x1,x1,#64
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev x5,x5
rev x7,x7
rev x9,x9
@@ -264,7 +239,6 @@ ChaCha20_ctr32:
ldp x27,x28,[x29,#80]
ldp x29,x30,[sp],#96
AARCH64_VALIDATE_LINK_REGISTER
.Labort:
ret
.align 4
@@ -285,7 +259,7 @@ ChaCha20_ctr32:
add x15,x15,x16,lsl#32
add x17,x17,x19,lsl#32
add x20,x20,x21,lsl#32
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev x5,x5
rev x7,x7
rev x9,x9
@@ -322,11 +296,13 @@ ChaCha20_ctr32:
ldp x29,x30,[sp],#96
AARCH64_VALIDATE_LINK_REGISTER
ret
.size ChaCha20_ctr32,.-ChaCha20_ctr32
.size ChaCha20_ctr32_nohw,.-ChaCha20_ctr32_nohw
.type ChaCha20_neon,%function
.globl ChaCha20_ctr32_neon
.hidden ChaCha20_ctr32_neon
.type ChaCha20_ctr32_neon,%function
.align 5
ChaCha20_neon:
ChaCha20_ctr32_neon:
AARCH64_SIGN_LINK_REGISTER
stp x29,x30,[sp,#-96]!
add x29,sp,#0
@@ -351,7 +327,7 @@ ChaCha20_neon:
ldp x28,x30,[x4] // load counter
ld1 {v27.4s},[x4]
ld1 {v31.4s},[x5]
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev64 v24.4s,v24.4s
ror x24,x24,#32
ror x25,x25,#32
@@ -649,7 +625,7 @@ ChaCha20_neon:
add x20,x20,x21,lsl#32
ldp x19,x21,[x1,#48]
add x1,x1,#64
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev x5,x5
rev x7,x7
rev x9,x9
@@ -729,7 +705,7 @@ ChaCha20_neon:
add x20,x20,x21,lsl#32
ldp x19,x21,[x1,#48]
add x1,x1,#64
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev x5,x5
rev x7,x7
rev x9,x9
@@ -820,7 +796,7 @@ ChaCha20_neon:
ldp x29,x30,[sp],#96
AARCH64_VALIDATE_LINK_REGISTER
ret
.size ChaCha20_neon,.-ChaCha20_neon
.size ChaCha20_ctr32_neon,.-ChaCha20_ctr32_neon
.type ChaCha20_512_neon,%function
.align 5
ChaCha20_512_neon:
@@ -847,7 +823,7 @@ ChaCha20_512_neon:
ldp x28,x30,[x4] // load counter
ld1 {v27.4s},[x4]
ld1 {v31.4s},[x5]
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev64 v24.4s,v24.4s
ror x24,x24,#32
ror x25,x25,#32
@@ -1360,7 +1336,7 @@ ChaCha20_512_neon:
add x20,x20,x21,lsl#32
ldp x19,x21,[x1,#48]
add x1,x1,#64
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev x5,x5
rev x7,x7
rev x9,x9
@@ -1874,7 +1850,7 @@ ChaCha20_512_neon:
add x1,x1,#64
add v21.4s,v21.4s,v25.4s
#ifdef __ARMEB__
#ifdef __AARCH64EB__
rev x5,x5
rev x7,x7
rev x9,x9
@@ -1991,9 +1967,7 @@ ChaCha20_512_neon:
AARCH64_VALIDATE_LINK_REGISTER
ret
.size ChaCha20_512_neon,.-ChaCha20_512_neon
#endif
#endif // !OPENSSL_NO_ASM
.section .note.GNU-stack,"",%progbits
#endif // !OPENSSL_NO_ASM && defined(OPENSSL_AARCH64) && defined(__ELF__)
#endif // defined(__aarch64__) && defined(__linux__)
#if defined(__linux__) && defined(__ELF__)
.section .note.GNU-stack,"",%progbits
@@ -1,12 +1,11 @@
#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)
#include <CCryptoBoringSSL_boringssl_prefix_symbols_asm.h>
#endif
#include <CCryptoBoringSSL_asm_base.h>
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86) && defined(__ELF__)
.text
.globl ChaCha20_ctr32
.hidden ChaCha20_ctr32
@@ -973,8 +972,7 @@ ChaCha20_ssse3:
.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
.section .note.GNU-stack,"",@progbits
#endif // !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86) && defined(__ELF__)
#endif // defined(__i386__) && defined(__linux__)
#if defined(__linux__) && defined(__ELF__)
.section .note.GNU-stack,"",%progbits
@@ -0,0 +1,987 @@
#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.
%ifdef BORINGSSL_PREFIX
%include "boringssl_prefix_symbols_nasm.inc"
%endif
%ifidn __OUTPUT_FORMAT__, win32
%ifidn __OUTPUT_FORMAT__,obj
section code use32 class=code align=64
%elifidn __OUTPUT_FORMAT__,win32
$@feat.00 equ 1
section .text code align=64
%else
section .text code
%endif
global _ChaCha20_ctr32
align 16
_ChaCha20_ctr32:
L$_ChaCha20_ctr32_begin:
push ebp
push ebx
push esi
push edi
xor eax,eax
cmp eax,DWORD [28+esp]
je NEAR L$000no_data
call L$pic_point
L$pic_point:
pop eax
lea ebp,[_OPENSSL_ia32cap_P]
test DWORD [ebp],16777216
jz NEAR L$001x86
test DWORD [4+ebp],512
jz NEAR L$001x86
jmp NEAR L$ssse3_shortcut
L$001x86:
mov esi,DWORD [32+esp]
mov edi,DWORD [36+esp]
sub esp,132
mov eax,DWORD [esi]
mov ebx,DWORD [4+esi]
mov ecx,DWORD [8+esi]
mov edx,DWORD [12+esi]
mov DWORD [80+esp],eax
mov DWORD [84+esp],ebx
mov DWORD [88+esp],ecx
mov DWORD [92+esp],edx
mov eax,DWORD [16+esi]
mov ebx,DWORD [20+esi]
mov ecx,DWORD [24+esi]
mov edx,DWORD [28+esi]
mov DWORD [96+esp],eax
mov DWORD [100+esp],ebx
mov DWORD [104+esp],ecx
mov DWORD [108+esp],edx
mov eax,DWORD [edi]
mov ebx,DWORD [4+edi]
mov ecx,DWORD [8+edi]
mov edx,DWORD [12+edi]
sub eax,1
mov DWORD [112+esp],eax
mov DWORD [116+esp],ebx
mov DWORD [120+esp],ecx
mov DWORD [124+esp],edx
jmp NEAR L$002entry
align 16
L$003outer_loop:
mov DWORD [156+esp],ebx
mov DWORD [152+esp],eax
mov DWORD [160+esp],ecx
L$002entry:
mov eax,1634760805
mov DWORD [4+esp],857760878
mov DWORD [8+esp],2036477234
mov DWORD [12+esp],1797285236
mov ebx,DWORD [84+esp]
mov ebp,DWORD [88+esp]
mov ecx,DWORD [104+esp]
mov esi,DWORD [108+esp]
mov edx,DWORD [116+esp]
mov edi,DWORD [120+esp]
mov DWORD [20+esp],ebx
mov DWORD [24+esp],ebp
mov DWORD [40+esp],ecx
mov DWORD [44+esp],esi
mov DWORD [52+esp],edx
mov DWORD [56+esp],edi
mov ebx,DWORD [92+esp]
mov edi,DWORD [124+esp]
mov edx,DWORD [112+esp]
mov ebp,DWORD [80+esp]
mov ecx,DWORD [96+esp]
mov esi,DWORD [100+esp]
add edx,1
mov DWORD [28+esp],ebx
mov DWORD [60+esp],edi
mov DWORD [112+esp],edx
mov ebx,10
jmp NEAR L$004loop
align 16
L$004loop:
add eax,ebp
mov DWORD [128+esp],ebx
mov ebx,ebp
xor edx,eax
rol edx,16
add ecx,edx
xor ebx,ecx
mov edi,DWORD [52+esp]
rol ebx,12
mov ebp,DWORD [20+esp]
add eax,ebx
xor edx,eax
mov DWORD [esp],eax
rol edx,8
mov eax,DWORD [4+esp]
add ecx,edx
mov DWORD [48+esp],edx
xor ebx,ecx
add eax,ebp
rol ebx,7
xor edi,eax
mov DWORD [32+esp],ecx
rol edi,16
mov DWORD [16+esp],ebx
add esi,edi
mov ecx,DWORD [40+esp]
xor ebp,esi
mov edx,DWORD [56+esp]
rol ebp,12
mov ebx,DWORD [24+esp]
add eax,ebp
xor edi,eax
mov DWORD [4+esp],eax
rol edi,8
mov eax,DWORD [8+esp]
add esi,edi
mov DWORD [52+esp],edi
xor ebp,esi
add eax,ebx
rol ebp,7
xor edx,eax
mov DWORD [36+esp],esi
rol edx,16
mov DWORD [20+esp],ebp
add ecx,edx
mov esi,DWORD [44+esp]
xor ebx,ecx
mov edi,DWORD [60+esp]
rol ebx,12
mov ebp,DWORD [28+esp]
add eax,ebx
xor edx,eax
mov DWORD [8+esp],eax
rol edx,8
mov eax,DWORD [12+esp]
add ecx,edx
mov DWORD [56+esp],edx
xor ebx,ecx
add eax,ebp
rol ebx,7
xor edi,eax
rol edi,16
mov DWORD [24+esp],ebx
add esi,edi
xor ebp,esi
rol ebp,12
mov ebx,DWORD [20+esp]
add eax,ebp
xor edi,eax
mov DWORD [12+esp],eax
rol edi,8
mov eax,DWORD [esp]
add esi,edi
mov edx,edi
xor ebp,esi
add eax,ebx
rol ebp,7
xor edx,eax
rol edx,16
mov DWORD [28+esp],ebp
add ecx,edx
xor ebx,ecx
mov edi,DWORD [48+esp]
rol ebx,12
mov ebp,DWORD [24+esp]
add eax,ebx
xor edx,eax
mov DWORD [esp],eax
rol edx,8
mov eax,DWORD [4+esp]
add ecx,edx
mov DWORD [60+esp],edx
xor ebx,ecx
add eax,ebp
rol ebx,7
xor edi,eax
mov DWORD [40+esp],ecx
rol edi,16
mov DWORD [20+esp],ebx
add esi,edi
mov ecx,DWORD [32+esp]
xor ebp,esi
mov edx,DWORD [52+esp]
rol ebp,12
mov ebx,DWORD [28+esp]
add eax,ebp
xor edi,eax
mov DWORD [4+esp],eax
rol edi,8
mov eax,DWORD [8+esp]
add esi,edi
mov DWORD [48+esp],edi
xor ebp,esi
add eax,ebx
rol ebp,7
xor edx,eax
mov DWORD [44+esp],esi
rol edx,16
mov DWORD [24+esp],ebp
add ecx,edx
mov esi,DWORD [36+esp]
xor ebx,ecx
mov edi,DWORD [56+esp]
rol ebx,12
mov ebp,DWORD [16+esp]
add eax,ebx
xor edx,eax
mov DWORD [8+esp],eax
rol edx,8
mov eax,DWORD [12+esp]
add ecx,edx
mov DWORD [52+esp],edx
xor ebx,ecx
add eax,ebp
rol ebx,7
xor edi,eax
rol edi,16
mov DWORD [28+esp],ebx
add esi,edi
xor ebp,esi
mov edx,DWORD [48+esp]
rol ebp,12
mov ebx,DWORD [128+esp]
add eax,ebp
xor edi,eax
mov DWORD [12+esp],eax
rol edi,8
mov eax,DWORD [esp]
add esi,edi
mov DWORD [56+esp],edi
xor ebp,esi
rol ebp,7
dec ebx
jnz NEAR L$004loop
mov ebx,DWORD [160+esp]
add eax,1634760805
add ebp,DWORD [80+esp]
add ecx,DWORD [96+esp]
add esi,DWORD [100+esp]
cmp ebx,64
jb NEAR L$005tail
mov ebx,DWORD [156+esp]
add edx,DWORD [112+esp]
add edi,DWORD [120+esp]
xor eax,DWORD [ebx]
xor ebp,DWORD [16+ebx]
mov DWORD [esp],eax
mov eax,DWORD [152+esp]
xor ecx,DWORD [32+ebx]
xor esi,DWORD [36+ebx]
xor edx,DWORD [48+ebx]
xor edi,DWORD [56+ebx]
mov DWORD [16+eax],ebp
mov DWORD [32+eax],ecx
mov DWORD [36+eax],esi
mov DWORD [48+eax],edx
mov DWORD [56+eax],edi
mov ebp,DWORD [4+esp]
mov ecx,DWORD [8+esp]
mov esi,DWORD [12+esp]
mov edx,DWORD [20+esp]
mov edi,DWORD [24+esp]
add ebp,857760878
add ecx,2036477234
add esi,1797285236
add edx,DWORD [84+esp]
add edi,DWORD [88+esp]
xor ebp,DWORD [4+ebx]
xor ecx,DWORD [8+ebx]
xor esi,DWORD [12+ebx]
xor edx,DWORD [20+ebx]
xor edi,DWORD [24+ebx]
mov DWORD [4+eax],ebp
mov DWORD [8+eax],ecx
mov DWORD [12+eax],esi
mov DWORD [20+eax],edx
mov DWORD [24+eax],edi
mov ebp,DWORD [28+esp]
mov ecx,DWORD [40+esp]
mov esi,DWORD [44+esp]
mov edx,DWORD [52+esp]
mov edi,DWORD [60+esp]
add ebp,DWORD [92+esp]
add ecx,DWORD [104+esp]
add esi,DWORD [108+esp]
add edx,DWORD [116+esp]
add edi,DWORD [124+esp]
xor ebp,DWORD [28+ebx]
xor ecx,DWORD [40+ebx]
xor esi,DWORD [44+ebx]
xor edx,DWORD [52+ebx]
xor edi,DWORD [60+ebx]
lea ebx,[64+ebx]
mov DWORD [28+eax],ebp
mov ebp,DWORD [esp]
mov DWORD [40+eax],ecx
mov ecx,DWORD [160+esp]
mov DWORD [44+eax],esi
mov DWORD [52+eax],edx
mov DWORD [60+eax],edi
mov DWORD [eax],ebp
lea eax,[64+eax]
sub ecx,64
jnz NEAR L$003outer_loop
jmp NEAR L$006done
L$005tail:
add edx,DWORD [112+esp]
add edi,DWORD [120+esp]
mov DWORD [esp],eax
mov DWORD [16+esp],ebp
mov DWORD [32+esp],ecx
mov DWORD [36+esp],esi
mov DWORD [48+esp],edx
mov DWORD [56+esp],edi
mov ebp,DWORD [4+esp]
mov ecx,DWORD [8+esp]
mov esi,DWORD [12+esp]
mov edx,DWORD [20+esp]
mov edi,DWORD [24+esp]
add ebp,857760878
add ecx,2036477234
add esi,1797285236
add edx,DWORD [84+esp]
add edi,DWORD [88+esp]
mov DWORD [4+esp],ebp
mov DWORD [8+esp],ecx
mov DWORD [12+esp],esi
mov DWORD [20+esp],edx
mov DWORD [24+esp],edi
mov ebp,DWORD [28+esp]
mov ecx,DWORD [40+esp]
mov esi,DWORD [44+esp]
mov edx,DWORD [52+esp]
mov edi,DWORD [60+esp]
add ebp,DWORD [92+esp]
add ecx,DWORD [104+esp]
add esi,DWORD [108+esp]
add edx,DWORD [116+esp]
add edi,DWORD [124+esp]
mov DWORD [28+esp],ebp
mov ebp,DWORD [156+esp]
mov DWORD [40+esp],ecx
mov ecx,DWORD [152+esp]
mov DWORD [44+esp],esi
xor esi,esi
mov DWORD [52+esp],edx
mov DWORD [60+esp],edi
xor eax,eax
xor edx,edx
L$007tail_loop:
mov al,BYTE [ebp*1+esi]
mov dl,BYTE [esi*1+esp]
lea esi,[1+esi]
xor al,dl
mov BYTE [esi*1+ecx-1],al
dec ebx
jnz NEAR L$007tail_loop
L$006done:
add esp,132
L$000no_data:
pop edi
pop esi
pop ebx
pop ebp
ret
global _ChaCha20_ssse3
align 16
_ChaCha20_ssse3:
L$_ChaCha20_ssse3_begin:
push ebp
push ebx
push esi
push edi
L$ssse3_shortcut:
mov edi,DWORD [20+esp]
mov esi,DWORD [24+esp]
mov ecx,DWORD [28+esp]
mov edx,DWORD [32+esp]
mov ebx,DWORD [36+esp]
mov ebp,esp
sub esp,524
and esp,-64
mov DWORD [512+esp],ebp
lea eax,[(L$ssse3_data-L$pic_point)+eax]
movdqu xmm3,[ebx]
cmp ecx,256
jb NEAR L$0081x
mov DWORD [516+esp],edx
mov DWORD [520+esp],ebx
sub ecx,256
lea ebp,[384+esp]
movdqu xmm7,[edx]
pshufd xmm0,xmm3,0
pshufd xmm1,xmm3,85
pshufd xmm2,xmm3,170
pshufd xmm3,xmm3,255
paddd xmm0,[48+eax]
pshufd xmm4,xmm7,0
pshufd xmm5,xmm7,85
psubd xmm0,[64+eax]
pshufd xmm6,xmm7,170
pshufd xmm7,xmm7,255
movdqa [64+ebp],xmm0
movdqa [80+ebp],xmm1
movdqa [96+ebp],xmm2
movdqa [112+ebp],xmm3
movdqu xmm3,[16+edx]
movdqa [ebp-64],xmm4
movdqa [ebp-48],xmm5
movdqa [ebp-32],xmm6
movdqa [ebp-16],xmm7
movdqa xmm7,[32+eax]
lea ebx,[128+esp]
pshufd xmm0,xmm3,0
pshufd xmm1,xmm3,85
pshufd xmm2,xmm3,170
pshufd xmm3,xmm3,255
pshufd xmm4,xmm7,0
pshufd xmm5,xmm7,85
pshufd xmm6,xmm7,170
pshufd xmm7,xmm7,255
movdqa [ebp],xmm0
movdqa [16+ebp],xmm1
movdqa [32+ebp],xmm2
movdqa [48+ebp],xmm3
movdqa [ebp-128],xmm4
movdqa [ebp-112],xmm5
movdqa [ebp-96],xmm6
movdqa [ebp-80],xmm7
lea esi,[128+esi]
lea edi,[128+edi]
jmp NEAR L$009outer_loop
align 16
L$009outer_loop:
movdqa xmm1,[ebp-112]
movdqa xmm2,[ebp-96]
movdqa xmm3,[ebp-80]
movdqa xmm5,[ebp-48]
movdqa xmm6,[ebp-32]
movdqa xmm7,[ebp-16]
movdqa [ebx-112],xmm1
movdqa [ebx-96],xmm2
movdqa [ebx-80],xmm3
movdqa [ebx-48],xmm5
movdqa [ebx-32],xmm6
movdqa [ebx-16],xmm7
movdqa xmm2,[32+ebp]
movdqa xmm3,[48+ebp]
movdqa xmm4,[64+ebp]
movdqa xmm5,[80+ebp]
movdqa xmm6,[96+ebp]
movdqa xmm7,[112+ebp]
paddd xmm4,[64+eax]
movdqa [32+ebx],xmm2
movdqa [48+ebx],xmm3
movdqa [64+ebx],xmm4
movdqa [80+ebx],xmm5
movdqa [96+ebx],xmm6
movdqa [112+ebx],xmm7
movdqa [64+ebp],xmm4
movdqa xmm0,[ebp-128]
movdqa xmm6,xmm4
movdqa xmm3,[ebp-64]
movdqa xmm4,[ebp]
movdqa xmm5,[16+ebp]
mov edx,10
nop
align 16
L$010loop:
paddd xmm0,xmm3
movdqa xmm2,xmm3
pxor xmm6,xmm0
pshufb xmm6,[eax]
paddd xmm4,xmm6
pxor xmm2,xmm4
movdqa xmm3,[ebx-48]
movdqa xmm1,xmm2
pslld xmm2,12
psrld xmm1,20
por xmm2,xmm1
movdqa xmm1,[ebx-112]
paddd xmm0,xmm2
movdqa xmm7,[80+ebx]
pxor xmm6,xmm0
movdqa [ebx-128],xmm0
pshufb xmm6,[16+eax]
paddd xmm4,xmm6
movdqa [64+ebx],xmm6
pxor xmm2,xmm4
paddd xmm1,xmm3
movdqa xmm0,xmm2
pslld xmm2,7
psrld xmm0,25
pxor xmm7,xmm1
por xmm2,xmm0
movdqa [ebx],xmm4
pshufb xmm7,[eax]
movdqa [ebx-64],xmm2
paddd xmm5,xmm7
movdqa xmm4,[32+ebx]
pxor xmm3,xmm5
movdqa xmm2,[ebx-32]
movdqa xmm0,xmm3
pslld xmm3,12
psrld xmm0,20
por xmm3,xmm0
movdqa xmm0,[ebx-96]
paddd xmm1,xmm3
movdqa xmm6,[96+ebx]
pxor xmm7,xmm1
movdqa [ebx-112],xmm1
pshufb xmm7,[16+eax]
paddd xmm5,xmm7
movdqa [80+ebx],xmm7
pxor xmm3,xmm5
paddd xmm0,xmm2
movdqa xmm1,xmm3
pslld xmm3,7
psrld xmm1,25
pxor xmm6,xmm0
por xmm3,xmm1
movdqa [16+ebx],xmm5
pshufb xmm6,[eax]
movdqa [ebx-48],xmm3
paddd xmm4,xmm6
movdqa xmm5,[48+ebx]
pxor xmm2,xmm4
movdqa xmm3,[ebx-16]
movdqa xmm1,xmm2
pslld xmm2,12
psrld xmm1,20
por xmm2,xmm1
movdqa xmm1,[ebx-80]
paddd xmm0,xmm2
movdqa xmm7,[112+ebx]
pxor xmm6,xmm0
movdqa [ebx-96],xmm0
pshufb xmm6,[16+eax]
paddd xmm4,xmm6
movdqa [96+ebx],xmm6
pxor xmm2,xmm4
paddd xmm1,xmm3
movdqa xmm0,xmm2
pslld xmm2,7
psrld xmm0,25
pxor xmm7,xmm1
por xmm2,xmm0
pshufb xmm7,[eax]
movdqa [ebx-32],xmm2
paddd xmm5,xmm7
pxor xmm3,xmm5
movdqa xmm2,[ebx-48]
movdqa xmm0,xmm3
pslld xmm3,12
psrld xmm0,20
por xmm3,xmm0
movdqa xmm0,[ebx-128]
paddd xmm1,xmm3
pxor xmm7,xmm1
movdqa [ebx-80],xmm1
pshufb xmm7,[16+eax]
paddd xmm5,xmm7
movdqa xmm6,xmm7
pxor xmm3,xmm5
paddd xmm0,xmm2
movdqa xmm1,xmm3
pslld xmm3,7
psrld xmm1,25
pxor xmm6,xmm0
por xmm3,xmm1
pshufb xmm6,[eax]
movdqa [ebx-16],xmm3
paddd xmm4,xmm6
pxor xmm2,xmm4
movdqa xmm3,[ebx-32]
movdqa xmm1,xmm2
pslld xmm2,12
psrld xmm1,20
por xmm2,xmm1
movdqa xmm1,[ebx-112]
paddd xmm0,xmm2
movdqa xmm7,[64+ebx]
pxor xmm6,xmm0
movdqa [ebx-128],xmm0
pshufb xmm6,[16+eax]
paddd xmm4,xmm6
movdqa [112+ebx],xmm6
pxor xmm2,xmm4
paddd xmm1,xmm3
movdqa xmm0,xmm2
pslld xmm2,7
psrld xmm0,25
pxor xmm7,xmm1
por xmm2,xmm0
movdqa [32+ebx],xmm4
pshufb xmm7,[eax]
movdqa [ebx-48],xmm2
paddd xmm5,xmm7
movdqa xmm4,[ebx]
pxor xmm3,xmm5
movdqa xmm2,[ebx-16]
movdqa xmm0,xmm3
pslld xmm3,12
psrld xmm0,20
por xmm3,xmm0
movdqa xmm0,[ebx-96]
paddd xmm1,xmm3
movdqa xmm6,[80+ebx]
pxor xmm7,xmm1
movdqa [ebx-112],xmm1
pshufb xmm7,[16+eax]
paddd xmm5,xmm7
movdqa [64+ebx],xmm7
pxor xmm3,xmm5
paddd xmm0,xmm2
movdqa xmm1,xmm3
pslld xmm3,7
psrld xmm1,25
pxor xmm6,xmm0
por xmm3,xmm1
movdqa [48+ebx],xmm5
pshufb xmm6,[eax]
movdqa [ebx-32],xmm3
paddd xmm4,xmm6
movdqa xmm5,[16+ebx]
pxor xmm2,xmm4
movdqa xmm3,[ebx-64]
movdqa xmm1,xmm2
pslld xmm2,12
psrld xmm1,20
por xmm2,xmm1
movdqa xmm1,[ebx-80]
paddd xmm0,xmm2
movdqa xmm7,[96+ebx]
pxor xmm6,xmm0
movdqa [ebx-96],xmm0
pshufb xmm6,[16+eax]
paddd xmm4,xmm6
movdqa [80+ebx],xmm6
pxor xmm2,xmm4
paddd xmm1,xmm3
movdqa xmm0,xmm2
pslld xmm2,7
psrld xmm0,25
pxor xmm7,xmm1
por xmm2,xmm0
pshufb xmm7,[eax]
movdqa [ebx-16],xmm2
paddd xmm5,xmm7
pxor xmm3,xmm5
movdqa xmm0,xmm3
pslld xmm3,12
psrld xmm0,20
por xmm3,xmm0
movdqa xmm0,[ebx-128]
paddd xmm1,xmm3
movdqa xmm6,[64+ebx]
pxor xmm7,xmm1
movdqa [ebx-80],xmm1
pshufb xmm7,[16+eax]
paddd xmm5,xmm7
movdqa [96+ebx],xmm7
pxor xmm3,xmm5
movdqa xmm1,xmm3
pslld xmm3,7
psrld xmm1,25
por xmm3,xmm1
dec edx
jnz NEAR L$010loop
movdqa [ebx-64],xmm3
movdqa [ebx],xmm4
movdqa [16+ebx],xmm5
movdqa [64+ebx],xmm6
movdqa [96+ebx],xmm7
movdqa xmm1,[ebx-112]
movdqa xmm2,[ebx-96]
movdqa xmm3,[ebx-80]
paddd xmm0,[ebp-128]
paddd xmm1,[ebp-112]
paddd xmm2,[ebp-96]
paddd xmm3,[ebp-80]
movdqa xmm6,xmm0
punpckldq xmm0,xmm1
movdqa xmm7,xmm2
punpckldq xmm2,xmm3
punpckhdq xmm6,xmm1
punpckhdq xmm7,xmm3
movdqa xmm1,xmm0
punpcklqdq xmm0,xmm2
movdqa xmm3,xmm6
punpcklqdq xmm6,xmm7
punpckhqdq xmm1,xmm2
punpckhqdq xmm3,xmm7
movdqu xmm4,[esi-128]
movdqu xmm5,[esi-64]
movdqu xmm2,[esi]
movdqu xmm7,[64+esi]
lea esi,[16+esi]
pxor xmm4,xmm0
movdqa xmm0,[ebx-64]
pxor xmm5,xmm1
movdqa xmm1,[ebx-48]
pxor xmm6,xmm2
movdqa xmm2,[ebx-32]
pxor xmm7,xmm3
movdqa xmm3,[ebx-16]
movdqu [edi-128],xmm4
movdqu [edi-64],xmm5
movdqu [edi],xmm6
movdqu [64+edi],xmm7
lea edi,[16+edi]
paddd xmm0,[ebp-64]
paddd xmm1,[ebp-48]
paddd xmm2,[ebp-32]
paddd xmm3,[ebp-16]
movdqa xmm6,xmm0
punpckldq xmm0,xmm1
movdqa xmm7,xmm2
punpckldq xmm2,xmm3
punpckhdq xmm6,xmm1
punpckhdq xmm7,xmm3
movdqa xmm1,xmm0
punpcklqdq xmm0,xmm2
movdqa xmm3,xmm6
punpcklqdq xmm6,xmm7
punpckhqdq xmm1,xmm2
punpckhqdq xmm3,xmm7
movdqu xmm4,[esi-128]
movdqu xmm5,[esi-64]
movdqu xmm2,[esi]
movdqu xmm7,[64+esi]
lea esi,[16+esi]
pxor xmm4,xmm0
movdqa xmm0,[ebx]
pxor xmm5,xmm1
movdqa xmm1,[16+ebx]
pxor xmm6,xmm2
movdqa xmm2,[32+ebx]
pxor xmm7,xmm3
movdqa xmm3,[48+ebx]
movdqu [edi-128],xmm4
movdqu [edi-64],xmm5
movdqu [edi],xmm6
movdqu [64+edi],xmm7
lea edi,[16+edi]
paddd xmm0,[ebp]
paddd xmm1,[16+ebp]
paddd xmm2,[32+ebp]
paddd xmm3,[48+ebp]
movdqa xmm6,xmm0
punpckldq xmm0,xmm1
movdqa xmm7,xmm2
punpckldq xmm2,xmm3
punpckhdq xmm6,xmm1
punpckhdq xmm7,xmm3
movdqa xmm1,xmm0
punpcklqdq xmm0,xmm2
movdqa xmm3,xmm6
punpcklqdq xmm6,xmm7
punpckhqdq xmm1,xmm2
punpckhqdq xmm3,xmm7
movdqu xmm4,[esi-128]
movdqu xmm5,[esi-64]
movdqu xmm2,[esi]
movdqu xmm7,[64+esi]
lea esi,[16+esi]
pxor xmm4,xmm0
movdqa xmm0,[64+ebx]
pxor xmm5,xmm1
movdqa xmm1,[80+ebx]
pxor xmm6,xmm2
movdqa xmm2,[96+ebx]
pxor xmm7,xmm3
movdqa xmm3,[112+ebx]
movdqu [edi-128],xmm4
movdqu [edi-64],xmm5
movdqu [edi],xmm6
movdqu [64+edi],xmm7
lea edi,[16+edi]
paddd xmm0,[64+ebp]
paddd xmm1,[80+ebp]
paddd xmm2,[96+ebp]
paddd xmm3,[112+ebp]
movdqa xmm6,xmm0
punpckldq xmm0,xmm1
movdqa xmm7,xmm2
punpckldq xmm2,xmm3
punpckhdq xmm6,xmm1
punpckhdq xmm7,xmm3
movdqa xmm1,xmm0
punpcklqdq xmm0,xmm2
movdqa xmm3,xmm6
punpcklqdq xmm6,xmm7
punpckhqdq xmm1,xmm2
punpckhqdq xmm3,xmm7
movdqu xmm4,[esi-128]
movdqu xmm5,[esi-64]
movdqu xmm2,[esi]
movdqu xmm7,[64+esi]
lea esi,[208+esi]
pxor xmm4,xmm0
pxor xmm5,xmm1
pxor xmm6,xmm2
pxor xmm7,xmm3
movdqu [edi-128],xmm4
movdqu [edi-64],xmm5
movdqu [edi],xmm6
movdqu [64+edi],xmm7
lea edi,[208+edi]
sub ecx,256
jnc NEAR L$009outer_loop
add ecx,256
jz NEAR L$011done
mov ebx,DWORD [520+esp]
lea esi,[esi-128]
mov edx,DWORD [516+esp]
lea edi,[edi-128]
movd xmm2,DWORD [64+ebp]
movdqu xmm3,[ebx]
paddd xmm2,[96+eax]
pand xmm3,[112+eax]
por xmm3,xmm2
L$0081x:
movdqa xmm0,[32+eax]
movdqu xmm1,[edx]
movdqu xmm2,[16+edx]
movdqa xmm6,[eax]
movdqa xmm7,[16+eax]
mov DWORD [48+esp],ebp
movdqa [esp],xmm0
movdqa [16+esp],xmm1
movdqa [32+esp],xmm2
movdqa [48+esp],xmm3
mov edx,10
jmp NEAR L$012loop1x
align 16
L$013outer1x:
movdqa xmm3,[80+eax]
movdqa xmm0,[esp]
movdqa xmm1,[16+esp]
movdqa xmm2,[32+esp]
paddd xmm3,[48+esp]
mov edx,10
movdqa [48+esp],xmm3
jmp NEAR L$012loop1x
align 16
L$012loop1x:
paddd xmm0,xmm1
pxor xmm3,xmm0
db 102,15,56,0,222
paddd xmm2,xmm3
pxor xmm1,xmm2
movdqa xmm4,xmm1
psrld xmm1,20
pslld xmm4,12
por xmm1,xmm4
paddd xmm0,xmm1
pxor xmm3,xmm0
db 102,15,56,0,223
paddd xmm2,xmm3
pxor xmm1,xmm2
movdqa xmm4,xmm1
psrld xmm1,25
pslld xmm4,7
por xmm1,xmm4
pshufd xmm2,xmm2,78
pshufd xmm1,xmm1,57
pshufd xmm3,xmm3,147
nop
paddd xmm0,xmm1
pxor xmm3,xmm0
db 102,15,56,0,222
paddd xmm2,xmm3
pxor xmm1,xmm2
movdqa xmm4,xmm1
psrld xmm1,20
pslld xmm4,12
por xmm1,xmm4
paddd xmm0,xmm1
pxor xmm3,xmm0
db 102,15,56,0,223
paddd xmm2,xmm3
pxor xmm1,xmm2
movdqa xmm4,xmm1
psrld xmm1,25
pslld xmm4,7
por xmm1,xmm4
pshufd xmm2,xmm2,78
pshufd xmm1,xmm1,147
pshufd xmm3,xmm3,57
dec edx
jnz NEAR L$012loop1x
paddd xmm0,[esp]
paddd xmm1,[16+esp]
paddd xmm2,[32+esp]
paddd xmm3,[48+esp]
cmp ecx,64
jb NEAR L$014tail
movdqu xmm4,[esi]
movdqu xmm5,[16+esi]
pxor xmm0,xmm4
movdqu xmm4,[32+esi]
pxor xmm1,xmm5
movdqu xmm5,[48+esi]
pxor xmm2,xmm4
pxor xmm3,xmm5
lea esi,[64+esi]
movdqu [edi],xmm0
movdqu [16+edi],xmm1
movdqu [32+edi],xmm2
movdqu [48+edi],xmm3
lea edi,[64+edi]
sub ecx,64
jnz NEAR L$013outer1x
jmp NEAR L$011done
L$014tail:
movdqa [esp],xmm0
movdqa [16+esp],xmm1
movdqa [32+esp],xmm2
movdqa [48+esp],xmm3
xor eax,eax
xor edx,edx
xor ebp,ebp
L$015tail_loop:
mov al,BYTE [ebp*1+esp]
mov dl,BYTE [ebp*1+esi]
lea ebp,[1+ebp]
xor al,dl
mov BYTE [ebp*1+edi-1],al
dec ecx
jnz NEAR L$015tail_loop
L$011done:
mov esp,DWORD [512+esp]
pop edi
pop esi
pop ebx
pop ebp
ret
align 64
L$ssse3_data:
db 2,3,0,1,6,7,4,5,10,11,8,9,14,15,12,13
db 3,0,1,2,7,4,5,6,11,8,9,10,15,12,13,14
dd 1634760805,857760878,2036477234,1797285236
dd 0,1,2,3
dd 4,4,4,4
dd 1,0,0,0
dd 4,0,0,0
dd 0,-1,-1,-1
align 64
db 67,104,97,67,104,97,50,48,32,102,111,114,32,120,56,54
db 44,32,67,82,89,80,84,79,71,65,77,83,32,98,121,32
db 60,97,112,112,114,111,64,111,112,101,110,115,115,108,46,111
db 114,103,62,0
segment .bss
common _OPENSSL_ia32cap_P 16
%else
; Work around https://bugzilla.nasm.us/show_bug.cgi?id=3392738
ret
%endif
#endif // defined(__i386__) && defined(_WIN32)
#if defined(__linux__) && defined(__ELF__)
.section .note.GNU-stack,"",%progbits
#endif
@@ -1,23 +1,17 @@
#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)
#define OPENSSL_NO_ASM
#endif
#endif
#include <CCryptoBoringSSL_asm_base.h>
#if defined(__x86_64__) && !defined(OPENSSL_NO_ASM)
#if defined(BORINGSSL_PREFIX)
#include <CCryptoBoringSSL_boringssl_prefix_symbols_asm.h>
#endif
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) && defined(__ELF__)
.text
.extern OPENSSL_ia32cap_P
.hidden OPENSSL_ia32cap_P
.section .rodata
.align 64
.Lzero:
.long 0,0,0,0
@@ -47,12 +41,14 @@
.Lsixteen:
.long 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16
.byte 67,104,97,67,104,97,50,48,32,102,111,114,32,120,56,54,95,54,52,44,32,67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97,112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103,62,0
.text
.globl ChaCha20_ctr32
.hidden ChaCha20_ctr32
.type ChaCha20_ctr32,@function
.align 64
ChaCha20_ctr32:
.cfi_startproc
_CET_ENDBR
cmpq $0,%rdx
je .Lno_data
movq OPENSSL_ia32cap_P+4(%rip),%r10
@@ -333,7 +329,7 @@ ChaCha20_ctr32:
leaq (%rsi),%rsp
.cfi_adjust_cfa_offset -136
.Lno_data:
.byte 0xf3,0xc3
ret
.cfi_endproc
.size ChaCha20_ctr32,.-ChaCha20_ctr32
.type ChaCha20_ssse3,@function
@@ -470,7 +466,7 @@ ChaCha20_ssse3:
leaq (%r9),%rsp
.cfi_def_cfa_register rsp
.Lssse3_epilogue:
.byte 0xf3,0xc3
ret
.cfi_endproc
.size ChaCha20_ssse3,.-ChaCha20_ssse3
.type ChaCha20_4x,@function
@@ -1022,7 +1018,7 @@ ChaCha20_4x:
leaq (%r9),%rsp
.cfi_def_cfa_register rsp
.L4x_epilogue:
.byte 0xf3,0xc3
ret
.cfi_endproc
.size ChaCha20_4x,.-ChaCha20_4x
.type ChaCha20_8x,@function
@@ -1628,11 +1624,10 @@ ChaCha20_8x:
leaq (%r9),%rsp
.cfi_def_cfa_register rsp
.L8x_epilogue:
.byte 0xf3,0xc3
ret
.cfi_endproc
.size ChaCha20_8x,.-ChaCha20_8x
#endif
.section .note.GNU-stack,"",@progbits
#endif // defined(__x86_64__) && defined(__linux__)
#if defined(__linux__) && defined(__ELF__)
.section .note.GNU-stack,"",%progbits
@@ -1,22 +1,16 @@
#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)
#define OPENSSL_NO_ASM
#endif
#endif
#include <CCryptoBoringSSL_asm_base.h>
#if defined(__x86_64__) && !defined(OPENSSL_NO_ASM)
#if defined(BORINGSSL_PREFIX)
#include <CCryptoBoringSSL_boringssl_prefix_symbols_asm.h>
#endif
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) && defined(__APPLE__)
.text
.section __DATA,__const
.p2align 6
L$zero:
.long 0,0,0,0
@@ -46,12 +40,14 @@ L$incz:
L$sixteen:
.long 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16
.byte 67,104,97,67,104,97,50,48,32,102,111,114,32,120,56,54,95,54,52,44,32,67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97,112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103,62,0
.text
.globl _ChaCha20_ctr32
.private_extern _ChaCha20_ctr32
.p2align 6
_ChaCha20_ctr32:
_CET_ENDBR
cmpq $0,%rdx
je L$no_data
movq _OPENSSL_ia32cap_P+4(%rip),%r10
@@ -326,7 +322,7 @@ L$done:
leaq (%rsi),%rsp
L$no_data:
.byte 0xf3,0xc3
ret
@@ -463,7 +459,7 @@ L$done_ssse3:
leaq (%r9),%rsp
L$ssse3_epilogue:
.byte 0xf3,0xc3
ret
@@ -1015,7 +1011,7 @@ L$done4x:
leaq (%r9),%rsp
L$4x_epilogue:
.byte 0xf3,0xc3
ret
@@ -1621,7 +1617,7 @@ L$done8x:
leaq (%r9),%rsp
L$8x_epilogue:
.byte 0xf3,0xc3
ret
#endif
+73 -51
View File
@@ -19,28 +19,24 @@
#include <assert.h>
#include <string.h>
#include <CCryptoBoringSSL_cpu.h>
#include "../internal.h"
#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]) {
@@ -64,49 +60,75 @@ void CRYPTO_hchacha20(uint8_t out[32], const uint8_t key[32],
OPENSSL_memcpy(&out[16], &x[12], sizeof(uint32_t) * 4);
}
#if defined(CHACHA20_ASM)
#if defined(CHACHA20_ASM_NOHW)
static void ChaCha20_ctr32(uint8_t *out, const uint8_t *in, size_t in_len,
const uint32_t key[8], const uint32_t counter[4]) {
#if defined(CHACHA20_ASM_NEON)
if (ChaCha20_ctr32_neon_capable(in_len)) {
ChaCha20_ctr32_neon(out, in, in_len, key, counter);
return;
}
#endif
if (in_len > 0) {
ChaCha20_ctr32_nohw(out, in, in_len, key, counter);
}
}
#endif
#if defined(CHACHA20_ASM) || defined(CHACHA20_ASM_NOHW)
void CRYPTO_chacha_20(uint8_t *out, const uint8_t *in, size_t in_len,
const uint8_t key[32], const uint8_t nonce[12],
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;
}
#endif
ChaCha20_ctr32(out, in, in_len, key_ptr, counter_nonce);
while (in_len > 0) {
// The assembly functions do not have defined overflow behavior. While
// overflow is almost always a bug in the caller, we prefer our functions to
// behave the same across platforms, so divide into multiple calls to avoid
// this case.
uint64_t todo = 64 * ((UINT64_C(1) << 32) - counter_nonce[0]);
if (todo > in_len) {
todo = in_len;
}
ChaCha20_ctr32(out, in, (size_t)todo, key_ptr, counter_nonce);
in += todo;
out += todo;
in_len -= todo;
// We're either done and will next break out of the loop, or we stopped at
// the wraparound point and the counter should continue at zero.
counter_nonce[0] = 0;
}
}
#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 +151,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 +164,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);
@@ -17,6 +17,8 @@
#include <CCryptoBoringSSL_base.h>
#include "../internal.h"
#if defined(__cplusplus)
extern "C" {
#endif
@@ -27,16 +29,43 @@ extern "C" {
void CRYPTO_hchacha20(uint8_t out[32], const uint8_t key[32],
const uint8_t nonce[16]);
#if !defined(OPENSSL_NO_ASM) && \
(defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || \
defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64))
#if !defined(OPENSSL_NO_ASM) && \
(defined(OPENSSL_X86) || defined(OPENSSL_X86_64))
#define CHACHA20_ASM
// ChaCha20_ctr32 is defined in asm/chacha-*.pl.
#elif !defined(OPENSSL_NO_ASM) && \
(defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64))
#define CHACHA20_ASM_NOHW
#define CHACHA20_ASM_NEON
OPENSSL_INLINE int ChaCha20_ctr32_neon_capable(size_t len) {
return (len >= 192) && CRYPTO_is_NEON_capable();
}
void ChaCha20_ctr32_neon(uint8_t *out, const uint8_t *in, size_t in_len,
const uint32_t key[8], const uint32_t counter[4]);
#endif
#if defined(CHACHA20_ASM)
// ChaCha20_ctr32 encrypts |in_len| bytes from |in| and writes the result to
// |out|. If |in| and |out| alias, they must be equal.
//
// |counter[0]| is the initial 32-bit block counter, and the remainder is the
// 96-bit nonce. If the counter overflows, the output is undefined. The function
// will produce output, but the output may vary by machine and may not be
// self-consistent. (On some architectures, the assembly implements a mix of
// 64-bit and 32-bit counters.)
void ChaCha20_ctr32(uint8_t *out, const uint8_t *in, size_t in_len,
const uint32_t key[8], const uint32_t counter[4]);
#endif
#if defined(CHACHA20_ASM_NOHW)
// ChaCha20_ctr32_nohw is like |ChaCha20_ctr32| except |in_len| must be nonzero.
void ChaCha20_ctr32_nohw(uint8_t *out, const uint8_t *in, size_t in_len,
const uint32_t key[8], const uint32_t counter[4]);
#endif
#if defined(__cplusplus)
} // extern C
@@ -1,19 +1,12 @@
#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)
#define OPENSSL_NO_ASM
#endif
#endif
#include <CCryptoBoringSSL_asm_base.h>
#if defined(__x86_64__) && !defined(OPENSSL_NO_ASM)
#if defined(BORINGSSL_PREFIX)
#include <CCryptoBoringSSL_boringssl_prefix_symbols_asm.h>
#endif
.data
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) && defined(__ELF__)
.section .rodata
.align 16
one:
@@ -71,7 +64,7 @@ GFMUL:
vpxor %xmm4,%xmm3,%xmm2
vpxor %xmm5,%xmm2,%xmm0
.byte 0xf3,0xc3
ret
.cfi_endproc
.size GFMUL, .-GFMUL
.globl aesgcmsiv_htable_init
@@ -80,6 +73,7 @@ GFMUL:
.align 16
aesgcmsiv_htable_init:
.cfi_startproc
_CET_ENDBR
vmovdqa (%rsi),%xmm0
vmovdqa %xmm0,%xmm1
vmovdqa %xmm0,(%rdi)
@@ -97,7 +91,7 @@ aesgcmsiv_htable_init:
vmovdqa %xmm0,96(%rdi)
call GFMUL
vmovdqa %xmm0,112(%rdi)
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aesgcmsiv_htable_init, .-aesgcmsiv_htable_init
.globl aesgcmsiv_htable6_init
@@ -106,6 +100,7 @@ aesgcmsiv_htable_init:
.align 16
aesgcmsiv_htable6_init:
.cfi_startproc
_CET_ENDBR
vmovdqa (%rsi),%xmm0
vmovdqa %xmm0,%xmm1
vmovdqa %xmm0,(%rdi)
@@ -119,7 +114,7 @@ aesgcmsiv_htable6_init:
vmovdqa %xmm0,64(%rdi)
call GFMUL
vmovdqa %xmm0,80(%rdi)
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aesgcmsiv_htable6_init, .-aesgcmsiv_htable6_init
.globl aesgcmsiv_htable_polyval
@@ -128,9 +123,10 @@ aesgcmsiv_htable6_init:
.align 16
aesgcmsiv_htable_polyval:
.cfi_startproc
_CET_ENDBR
testq %rdx,%rdx
jnz .Lhtable_polyval_start
.byte 0xf3,0xc3
ret
.Lhtable_polyval_start:
vzeroall
@@ -336,7 +332,7 @@ aesgcmsiv_htable_polyval:
vmovdqu %xmm1,(%rcx)
vzeroupper
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aesgcmsiv_htable_polyval,.-aesgcmsiv_htable_polyval
.globl aesgcmsiv_polyval_horner
@@ -345,9 +341,10 @@ aesgcmsiv_htable_polyval:
.align 16
aesgcmsiv_polyval_horner:
.cfi_startproc
_CET_ENDBR
testq %rcx,%rcx
jnz .Lpolyval_horner_start
.byte 0xf3,0xc3
ret
.Lpolyval_horner_start:
@@ -369,7 +366,7 @@ aesgcmsiv_polyval_horner:
vmovdqa %xmm0,(%rdi)
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aesgcmsiv_polyval_horner,.-aesgcmsiv_polyval_horner
.globl aes128gcmsiv_aes_ks
@@ -378,6 +375,7 @@ aesgcmsiv_polyval_horner:
.align 16
aes128gcmsiv_aes_ks:
.cfi_startproc
_CET_ENDBR
vmovdqu (%rdi),%xmm1
vmovdqa %xmm1,(%rsi)
@@ -425,7 +423,7 @@ aes128gcmsiv_aes_ks:
vpxor %xmm3,%xmm1,%xmm1
vpxor %xmm2,%xmm1,%xmm1
vmovdqa %xmm1,32(%rsi)
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aes128gcmsiv_aes_ks,.-aes128gcmsiv_aes_ks
.globl aes256gcmsiv_aes_ks
@@ -434,6 +432,7 @@ aes128gcmsiv_aes_ks:
.align 16
aes256gcmsiv_aes_ks:
.cfi_startproc
_CET_ENDBR
vmovdqu (%rdi),%xmm1
vmovdqu 16(%rdi),%xmm3
vmovdqa %xmm1,(%rsi)
@@ -473,7 +472,7 @@ aes256gcmsiv_aes_ks:
vpxor %xmm4,%xmm1,%xmm1
vpxor %xmm2,%xmm1,%xmm1
vmovdqa %xmm1,32(%rsi)
.byte 0xf3,0xc3
ret
.cfi_endproc
.globl aes128gcmsiv_aes_ks_enc_x1
.hidden aes128gcmsiv_aes_ks_enc_x1
@@ -481,6 +480,7 @@ aes256gcmsiv_aes_ks:
.align 16
aes128gcmsiv_aes_ks_enc_x1:
.cfi_startproc
_CET_ENDBR
vmovdqa (%rcx),%xmm1
vmovdqa 0(%rdi),%xmm4
@@ -614,7 +614,7 @@ aes128gcmsiv_aes_ks_enc_x1:
vmovdqa %xmm4,0(%rsi)
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aes128gcmsiv_aes_ks_enc_x1,.-aes128gcmsiv_aes_ks_enc_x1
.globl aes128gcmsiv_kdf
@@ -623,6 +623,7 @@ aes128gcmsiv_aes_ks_enc_x1:
.align 16
aes128gcmsiv_kdf:
.cfi_startproc
_CET_ENDBR
@@ -707,7 +708,7 @@ aes128gcmsiv_kdf:
vmovdqa %xmm10,16(%rsi)
vmovdqa %xmm11,32(%rsi)
vmovdqa %xmm12,48(%rsi)
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aes128gcmsiv_kdf,.-aes128gcmsiv_kdf
.globl aes128gcmsiv_enc_msg_x4
@@ -716,9 +717,10 @@ aes128gcmsiv_kdf:
.align 16
aes128gcmsiv_enc_msg_x4:
.cfi_startproc
_CET_ENDBR
testq %r8,%r8
jnz .L128_enc_msg_x4_start
.byte 0xf3,0xc3
ret
.L128_enc_msg_x4_start:
pushq %r12
@@ -886,7 +888,7 @@ aes128gcmsiv_enc_msg_x4:
popq %r12
.cfi_adjust_cfa_offset -8
.cfi_restore %r12
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aes128gcmsiv_enc_msg_x4,.-aes128gcmsiv_enc_msg_x4
.globl aes128gcmsiv_enc_msg_x8
@@ -895,9 +897,10 @@ aes128gcmsiv_enc_msg_x4:
.align 16
aes128gcmsiv_enc_msg_x8:
.cfi_startproc
_CET_ENDBR
testq %r8,%r8
jnz .L128_enc_msg_x8_start
.byte 0xf3,0xc3
ret
.L128_enc_msg_x8_start:
pushq %r12
@@ -1147,7 +1150,7 @@ aes128gcmsiv_enc_msg_x8:
popq %r12
.cfi_adjust_cfa_offset -8
.cfi_restore %r12
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aes128gcmsiv_enc_msg_x8,.-aes128gcmsiv_enc_msg_x8
.globl aes128gcmsiv_dec
@@ -1156,9 +1159,10 @@ aes128gcmsiv_enc_msg_x8:
.align 16
aes128gcmsiv_dec:
.cfi_startproc
_CET_ENDBR
testq $~15,%r9
jnz .L128_dec_start
.byte 0xf3,0xc3
ret
.L128_dec_start:
vzeroupper
@@ -1639,7 +1643,7 @@ aes128gcmsiv_dec:
.L128_dec_out:
vmovdqu %xmm0,(%rdx)
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aes128gcmsiv_dec, .-aes128gcmsiv_dec
.globl aes128gcmsiv_ecb_enc_block
@@ -1648,6 +1652,7 @@ aes128gcmsiv_dec:
.align 16
aes128gcmsiv_ecb_enc_block:
.cfi_startproc
_CET_ENDBR
vmovdqa (%rdi),%xmm1
vpxor (%rdx),%xmm1,%xmm1
@@ -1664,7 +1669,7 @@ aes128gcmsiv_ecb_enc_block:
vmovdqa %xmm1,(%rsi)
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aes128gcmsiv_ecb_enc_block,.-aes128gcmsiv_ecb_enc_block
.globl aes256gcmsiv_aes_ks_enc_x1
@@ -1673,6 +1678,7 @@ aes128gcmsiv_ecb_enc_block:
.align 16
aes256gcmsiv_aes_ks_enc_x1:
.cfi_startproc
_CET_ENDBR
vmovdqa con1(%rip),%xmm0
vmovdqa mask(%rip),%xmm15
vmovdqa (%rdi),%xmm8
@@ -1847,7 +1853,7 @@ aes256gcmsiv_aes_ks_enc_x1:
vmovdqu %xmm1,224(%rdx)
vmovdqa %xmm8,(%rsi)
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aes256gcmsiv_aes_ks_enc_x1,.-aes256gcmsiv_aes_ks_enc_x1
.globl aes256gcmsiv_ecb_enc_block
@@ -1856,6 +1862,7 @@ aes256gcmsiv_aes_ks_enc_x1:
.align 16
aes256gcmsiv_ecb_enc_block:
.cfi_startproc
_CET_ENDBR
vmovdqa (%rdi),%xmm1
vpxor (%rdx),%xmm1,%xmm1
vaesenc 16(%rdx),%xmm1,%xmm1
@@ -1873,7 +1880,7 @@ aes256gcmsiv_ecb_enc_block:
vaesenc 208(%rdx),%xmm1,%xmm1
vaesenclast 224(%rdx),%xmm1,%xmm1
vmovdqa %xmm1,(%rsi)
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aes256gcmsiv_ecb_enc_block,.-aes256gcmsiv_ecb_enc_block
.globl aes256gcmsiv_enc_msg_x4
@@ -1882,9 +1889,10 @@ aes256gcmsiv_ecb_enc_block:
.align 16
aes256gcmsiv_enc_msg_x4:
.cfi_startproc
_CET_ENDBR
testq %r8,%r8
jnz .L256_enc_msg_x4_start
.byte 0xf3,0xc3
ret
.L256_enc_msg_x4_start:
movq %r8,%r10
@@ -2074,7 +2082,7 @@ aes256gcmsiv_enc_msg_x4:
jne .L256_enc_msg_x4_loop2
.L256_enc_msg_x4_out:
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aes256gcmsiv_enc_msg_x4,.-aes256gcmsiv_enc_msg_x4
.globl aes256gcmsiv_enc_msg_x8
@@ -2083,9 +2091,10 @@ aes256gcmsiv_enc_msg_x4:
.align 16
aes256gcmsiv_enc_msg_x8:
.cfi_startproc
_CET_ENDBR
testq %r8,%r8
jnz .L256_enc_msg_x8_start
.byte 0xf3,0xc3
ret
.L256_enc_msg_x8_start:
@@ -2362,7 +2371,7 @@ aes256gcmsiv_enc_msg_x8:
jnz .L256_enc_msg_x8_loop2
.L256_enc_msg_x8_out:
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aes256gcmsiv_enc_msg_x8,.-aes256gcmsiv_enc_msg_x8
@@ -2372,9 +2381,10 @@ aes256gcmsiv_enc_msg_x8:
.align 16
aes256gcmsiv_dec:
.cfi_startproc
_CET_ENDBR
testq $~15,%r9
jnz .L256_dec_start
.byte 0xf3,0xc3
ret
.L256_dec_start:
vzeroupper
@@ -2923,7 +2933,7 @@ aes256gcmsiv_dec:
.L256_dec_out:
vmovdqu %xmm0,(%rdx)
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aes256gcmsiv_dec, .-aes256gcmsiv_dec
.globl aes256gcmsiv_kdf
@@ -2932,6 +2942,7 @@ aes256gcmsiv_dec:
.align 16
aes256gcmsiv_kdf:
.cfi_startproc
_CET_ENDBR
@@ -3074,11 +3085,10 @@ aes256gcmsiv_kdf:
vmovdqa %xmm11,48(%rsi)
vmovdqa %xmm12,64(%rsi)
vmovdqa %xmm13,80(%rsi)
.byte 0xf3,0xc3
ret
.cfi_endproc
.size aes256gcmsiv_kdf, .-aes256gcmsiv_kdf
#endif
.section .note.GNU-stack,"",@progbits
#endif // defined(__x86_64__) && defined(__linux__)
#if defined(__linux__) && defined(__ELF__)
.section .note.GNU-stack,"",%progbits
@@ -1,19 +1,12 @@
#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)
#define OPENSSL_NO_ASM
#endif
#endif
#include <CCryptoBoringSSL_asm_base.h>
#if defined(__x86_64__) && !defined(OPENSSL_NO_ASM)
#if defined(BORINGSSL_PREFIX)
#include <CCryptoBoringSSL_boringssl_prefix_symbols_asm.h>
#endif
.data
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) && defined(__APPLE__)
.section __DATA,__const
.p2align 4
one:
@@ -71,7 +64,7 @@ GFMUL:
vpxor %xmm4,%xmm3,%xmm2
vpxor %xmm5,%xmm2,%xmm0
.byte 0xf3,0xc3
ret
.globl _aesgcmsiv_htable_init
@@ -80,6 +73,7 @@ GFMUL:
.p2align 4
_aesgcmsiv_htable_init:
_CET_ENDBR
vmovdqa (%rsi),%xmm0
vmovdqa %xmm0,%xmm1
vmovdqa %xmm0,(%rdi)
@@ -97,7 +91,7 @@ _aesgcmsiv_htable_init:
vmovdqa %xmm0,96(%rdi)
call GFMUL
vmovdqa %xmm0,112(%rdi)
.byte 0xf3,0xc3
ret
.globl _aesgcmsiv_htable6_init
@@ -106,6 +100,7 @@ _aesgcmsiv_htable_init:
.p2align 4
_aesgcmsiv_htable6_init:
_CET_ENDBR
vmovdqa (%rsi),%xmm0
vmovdqa %xmm0,%xmm1
vmovdqa %xmm0,(%rdi)
@@ -119,7 +114,7 @@ _aesgcmsiv_htable6_init:
vmovdqa %xmm0,64(%rdi)
call GFMUL
vmovdqa %xmm0,80(%rdi)
.byte 0xf3,0xc3
ret
.globl _aesgcmsiv_htable_polyval
@@ -128,9 +123,10 @@ _aesgcmsiv_htable6_init:
.p2align 4
_aesgcmsiv_htable_polyval:
_CET_ENDBR
testq %rdx,%rdx
jnz L$htable_polyval_start
.byte 0xf3,0xc3
ret
L$htable_polyval_start:
vzeroall
@@ -336,7 +332,7 @@ L$htable_polyval_out:
vmovdqu %xmm1,(%rcx)
vzeroupper
.byte 0xf3,0xc3
ret
.globl _aesgcmsiv_polyval_horner
@@ -345,9 +341,10 @@ L$htable_polyval_out:
.p2align 4
_aesgcmsiv_polyval_horner:
_CET_ENDBR
testq %rcx,%rcx
jnz L$polyval_horner_start
.byte 0xf3,0xc3
ret
L$polyval_horner_start:
@@ -369,7 +366,7 @@ L$polyval_horner_loop:
vmovdqa %xmm0,(%rdi)
.byte 0xf3,0xc3
ret
.globl _aes128gcmsiv_aes_ks
@@ -378,6 +375,7 @@ L$polyval_horner_loop:
.p2align 4
_aes128gcmsiv_aes_ks:
_CET_ENDBR
vmovdqu (%rdi),%xmm1
vmovdqa %xmm1,(%rsi)
@@ -425,7 +423,7 @@ L$ks128_loop:
vpxor %xmm3,%xmm1,%xmm1
vpxor %xmm2,%xmm1,%xmm1
vmovdqa %xmm1,32(%rsi)
.byte 0xf3,0xc3
ret
.globl _aes256gcmsiv_aes_ks
@@ -434,6 +432,7 @@ L$ks128_loop:
.p2align 4
_aes256gcmsiv_aes_ks:
_CET_ENDBR
vmovdqu (%rdi),%xmm1
vmovdqu 16(%rdi),%xmm3
vmovdqa %xmm1,(%rsi)
@@ -473,7 +472,7 @@ L$ks256_loop:
vpxor %xmm4,%xmm1,%xmm1
vpxor %xmm2,%xmm1,%xmm1
vmovdqa %xmm1,32(%rsi)
.byte 0xf3,0xc3
ret
.globl _aes128gcmsiv_aes_ks_enc_x1
.private_extern _aes128gcmsiv_aes_ks_enc_x1
@@ -481,6 +480,7 @@ L$ks256_loop:
.p2align 4
_aes128gcmsiv_aes_ks_enc_x1:
_CET_ENDBR
vmovdqa (%rcx),%xmm1
vmovdqa 0(%rdi),%xmm4
@@ -614,7 +614,7 @@ _aes128gcmsiv_aes_ks_enc_x1:
vmovdqa %xmm4,0(%rsi)
.byte 0xf3,0xc3
ret
.globl _aes128gcmsiv_kdf
@@ -623,6 +623,7 @@ _aes128gcmsiv_aes_ks_enc_x1:
.p2align 4
_aes128gcmsiv_kdf:
_CET_ENDBR
@@ -707,7 +708,7 @@ _aes128gcmsiv_kdf:
vmovdqa %xmm10,16(%rsi)
vmovdqa %xmm11,32(%rsi)
vmovdqa %xmm12,48(%rsi)
.byte 0xf3,0xc3
ret
.globl _aes128gcmsiv_enc_msg_x4
@@ -716,9 +717,10 @@ _aes128gcmsiv_kdf:
.p2align 4
_aes128gcmsiv_enc_msg_x4:
_CET_ENDBR
testq %r8,%r8
jnz L$128_enc_msg_x4_start
.byte 0xf3,0xc3
ret
L$128_enc_msg_x4_start:
pushq %r12
@@ -882,7 +884,7 @@ L$128_enc_msg_x4_out:
popq %r12
.byte 0xf3,0xc3
ret
.globl _aes128gcmsiv_enc_msg_x8
@@ -891,9 +893,10 @@ L$128_enc_msg_x4_out:
.p2align 4
_aes128gcmsiv_enc_msg_x8:
_CET_ENDBR
testq %r8,%r8
jnz L$128_enc_msg_x8_start
.byte 0xf3,0xc3
ret
L$128_enc_msg_x8_start:
pushq %r12
@@ -1137,7 +1140,7 @@ L$128_enc_msg_x8_out:
popq %r12
.byte 0xf3,0xc3
ret
.globl _aes128gcmsiv_dec
@@ -1146,9 +1149,10 @@ L$128_enc_msg_x8_out:
.p2align 4
_aes128gcmsiv_dec:
_CET_ENDBR
testq $~15,%r9
jnz L$128_dec_start
.byte 0xf3,0xc3
ret
L$128_dec_start:
vzeroupper
@@ -1629,7 +1633,7 @@ L$128_dec_loop2:
L$128_dec_out:
vmovdqu %xmm0,(%rdx)
.byte 0xf3,0xc3
ret
.globl _aes128gcmsiv_ecb_enc_block
@@ -1638,6 +1642,7 @@ L$128_dec_out:
.p2align 4
_aes128gcmsiv_ecb_enc_block:
_CET_ENDBR
vmovdqa (%rdi),%xmm1
vpxor (%rdx),%xmm1,%xmm1
@@ -1654,7 +1659,7 @@ _aes128gcmsiv_ecb_enc_block:
vmovdqa %xmm1,(%rsi)
.byte 0xf3,0xc3
ret
.globl _aes256gcmsiv_aes_ks_enc_x1
@@ -1663,6 +1668,7 @@ _aes128gcmsiv_ecb_enc_block:
.p2align 4
_aes256gcmsiv_aes_ks_enc_x1:
_CET_ENDBR
vmovdqa con1(%rip),%xmm0
vmovdqa mask(%rip),%xmm15
vmovdqa (%rdi),%xmm8
@@ -1837,7 +1843,7 @@ _aes256gcmsiv_aes_ks_enc_x1:
vmovdqu %xmm1,224(%rdx)
vmovdqa %xmm8,(%rsi)
.byte 0xf3,0xc3
ret
.globl _aes256gcmsiv_ecb_enc_block
@@ -1846,6 +1852,7 @@ _aes256gcmsiv_aes_ks_enc_x1:
.p2align 4
_aes256gcmsiv_ecb_enc_block:
_CET_ENDBR
vmovdqa (%rdi),%xmm1
vpxor (%rdx),%xmm1,%xmm1
vaesenc 16(%rdx),%xmm1,%xmm1
@@ -1863,7 +1870,7 @@ _aes256gcmsiv_ecb_enc_block:
vaesenc 208(%rdx),%xmm1,%xmm1
vaesenclast 224(%rdx),%xmm1,%xmm1
vmovdqa %xmm1,(%rsi)
.byte 0xf3,0xc3
ret
.globl _aes256gcmsiv_enc_msg_x4
@@ -1872,9 +1879,10 @@ _aes256gcmsiv_ecb_enc_block:
.p2align 4
_aes256gcmsiv_enc_msg_x4:
_CET_ENDBR
testq %r8,%r8
jnz L$256_enc_msg_x4_start
.byte 0xf3,0xc3
ret
L$256_enc_msg_x4_start:
movq %r8,%r10
@@ -2064,7 +2072,7 @@ L$256_enc_msg_x4_loop2:
jne L$256_enc_msg_x4_loop2
L$256_enc_msg_x4_out:
.byte 0xf3,0xc3
ret
.globl _aes256gcmsiv_enc_msg_x8
@@ -2073,9 +2081,10 @@ L$256_enc_msg_x4_out:
.p2align 4
_aes256gcmsiv_enc_msg_x8:
_CET_ENDBR
testq %r8,%r8
jnz L$256_enc_msg_x8_start
.byte 0xf3,0xc3
ret
L$256_enc_msg_x8_start:
@@ -2352,7 +2361,7 @@ L$256_enc_msg_x8_loop2:
jnz L$256_enc_msg_x8_loop2
L$256_enc_msg_x8_out:
.byte 0xf3,0xc3
ret
@@ -2362,9 +2371,10 @@ L$256_enc_msg_x8_out:
.p2align 4
_aes256gcmsiv_dec:
_CET_ENDBR
testq $~15,%r9
jnz L$256_dec_start
.byte 0xf3,0xc3
ret
L$256_dec_start:
vzeroupper
@@ -2913,7 +2923,7 @@ L$256_dec_loop2:
L$256_dec_out:
vmovdqu %xmm0,(%rdx)
.byte 0xf3,0xc3
ret
.globl _aes256gcmsiv_kdf
@@ -2922,6 +2932,7 @@ L$256_dec_out:
.p2align 4
_aes256gcmsiv_kdf:
_CET_ENDBR
@@ -3064,7 +3075,7 @@ _aes256gcmsiv_kdf:
vmovdqa %xmm11,48(%rsi)
vmovdqa %xmm12,64(%rsi)
vmovdqa %xmm13,80(%rsi)
.byte 0xf3,0xc3
ret
#endif
@@ -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;
@@ -69,12 +69,12 @@ int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md,
unsigned count, uint8_t *key, uint8_t *iv) {
EVP_MD_CTX c;
uint8_t md_buf[EVP_MAX_MD_SIZE];
unsigned niv, nkey, addmd = 0;
unsigned addmd = 0;
unsigned mds = 0, i;
int rv = 0;
nkey = type->key_len;
niv = type->iv_len;
unsigned nkey = EVP_CIPHER_key_length(type);
unsigned niv = EVP_CIPHER_iv_length(type);
assert(nkey <= EVP_MAX_KEY_LENGTH);
assert(niv <= EVP_MAX_IV_LENGTH);
@@ -143,7 +143,7 @@ int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md,
break;
}
}
rv = type->key_len;
rv = EVP_CIPHER_key_length(type);
err:
EVP_MD_CTX_cleanup(&c);
@@ -13,6 +13,9 @@
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#include <CCryptoBoringSSL_aead.h>
#include <assert.h>
#include <CCryptoBoringSSL_cipher.h>
#include <CCryptoBoringSSL_crypto.h>
#include <CCryptoBoringSSL_err.h>
@@ -35,14 +38,12 @@ struct aead_aes_ctr_hmac_sha256_ctx {
SHA256_CTX outer_init_state;
};
OPENSSL_STATIC_ASSERT(sizeof(((EVP_AEAD_CTX *)NULL)->state) >=
sizeof(struct aead_aes_ctr_hmac_sha256_ctx),
"AEAD state is too small");
#if defined(__GNUC__) || defined(__clang__)
OPENSSL_STATIC_ASSERT(alignof(union evp_aead_ctx_st_state) >=
alignof(struct aead_aes_ctr_hmac_sha256_ctx),
"AEAD state has insufficient alignment");
#endif
static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) >=
sizeof(struct aead_aes_ctr_hmac_sha256_ctx),
"AEAD state is too small");
static_assert(alignof(union evp_aead_ctx_st_state) >=
alignof(struct aead_aes_ctr_hmac_sha256_ctx),
"AEAD state has insufficient alignment");
static void hmac_init(SHA256_CTX *out_inner, SHA256_CTX *out_outer,
const uint8_t hmac_key[32]) {
@@ -17,11 +17,11 @@
#include <assert.h>
#include <CCryptoBoringSSL_cipher.h>
#include <CCryptoBoringSSL_cpu.h>
#include <CCryptoBoringSSL_crypto.h>
#include <CCryptoBoringSSL_err.h>
#include "../fipsmodule/cipher/internal.h"
#include "../internal.h"
#define EVP_AEAD_AES_GCM_SIV_NONCE_LEN 12
@@ -42,13 +42,11 @@ struct aead_aes_gcm_siv_asm_ctx {
// The assembly code assumes 8-byte alignment of the EVP_AEAD_CTX's state, and
// aligns to 16 bytes itself.
OPENSSL_STATIC_ASSERT(sizeof(((EVP_AEAD_CTX *)NULL)->state) + 8 >=
sizeof(struct aead_aes_gcm_siv_asm_ctx),
"AEAD state is too small");
#if defined(__GNUC__) || defined(__clang__)
OPENSSL_STATIC_ASSERT(alignof(union evp_aead_ctx_st_state) >= 8,
"AEAD state has insufficient alignment");
#endif
static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) + 8 >=
sizeof(struct aead_aes_gcm_siv_asm_ctx),
"AEAD state is too small");
static_assert(alignof(union evp_aead_ctx_st_state) >= 8,
"AEAD state has insufficient alignment");
// asm_ctx_from_ctx returns a 16-byte aligned context pointer from |ctx|.
static struct aead_aes_gcm_siv_asm_ctx *asm_ctx_from_ctx(
@@ -262,17 +260,10 @@ static void gcm_siv_asm_polyval(uint8_t out_tag[16], const uint8_t *in,
aesgcmsiv_polyval_horner(out_tag, auth_key, scratch, 1);
}
union {
uint8_t c[16];
struct {
uint64_t ad;
uint64_t in;
} bitlens;
} length_block;
length_block.bitlens.ad = ad_len * 8;
length_block.bitlens.in = in_len * 8;
aesgcmsiv_polyval_horner(out_tag, auth_key, length_block.c, 1);
uint8_t length_block[16];
CRYPTO_store_u64_le(length_block, ad_len * 8);
CRYPTO_store_u64_le(length_block + 8, in_len * 8);
aesgcmsiv_polyval_horner(out_tag, auth_key, length_block, 1);
for (size_t i = 0; i < 12; i++) {
out_tag[i] ^= nonce[i];
@@ -289,18 +280,15 @@ static void aead_aes_gcm_siv_asm_crypt_last_block(
int is_128_bit, uint8_t *out, const uint8_t *in, size_t in_len,
const uint8_t tag[16],
const struct aead_aes_gcm_siv_asm_ctx *enc_key_expanded) {
alignas(16) union {
uint8_t c[16];
uint32_t u32[4];
} counter;
alignas(16) uint8_t counter[16];
OPENSSL_memcpy(&counter, tag, sizeof(counter));
counter.c[15] |= 0x80;
counter.u32[0] += in_len / 16;
counter[15] |= 0x80;
CRYPTO_store_u32_le(counter, CRYPTO_load_u32_le(counter) + in_len / 16);
if (is_128_bit) {
aes128gcmsiv_ecb_enc_block(&counter.c[0], &counter.c[0], enc_key_expanded);
aes128gcmsiv_ecb_enc_block(counter, counter, enc_key_expanded);
} else {
aes256gcmsiv_ecb_enc_block(&counter.c[0], &counter.c[0], enc_key_expanded);
aes256gcmsiv_ecb_enc_block(counter, counter, enc_key_expanded);
}
const size_t last_bytes_offset = in_len & ~15;
@@ -308,7 +296,7 @@ static void aead_aes_gcm_siv_asm_crypt_last_block(
uint8_t *last_bytes_out = &out[last_bytes_offset];
const uint8_t *last_bytes_in = &in[last_bytes_offset];
for (size_t i = 0; i < last_bytes_len; i++) {
last_bytes_out[i] = last_bytes_in[i] ^ counter.c[i];
last_bytes_out[i] = last_bytes_in[i] ^ counter[i];
}
}
@@ -489,18 +477,11 @@ static int aead_aes_gcm_siv_asm_open(const EVP_AEAD_CTX *ctx, uint8_t *out,
scratch, 1);
}
union {
uint8_t c[16];
struct {
uint64_t ad;
uint64_t in;
} bitlens;
} length_block;
length_block.bitlens.ad = ad_len * 8;
length_block.bitlens.in = plaintext_len * 8;
uint8_t length_block[16];
CRYPTO_store_u64_le(length_block, ad_len * 8);
CRYPTO_store_u64_le(length_block + 8, plaintext_len * 8);
aesgcmsiv_polyval_horner(calculated_tag, (const uint8_t *)record_auth_key,
length_block.c, 1);
length_block, 1);
for (size_t i = 0; i < 12; i++) {
calculated_tag[i] ^= nonce[i];
@@ -569,14 +550,12 @@ struct aead_aes_gcm_siv_ctx {
unsigned is_256:1;
};
OPENSSL_STATIC_ASSERT(sizeof(((EVP_AEAD_CTX *)NULL)->state) >=
sizeof(struct aead_aes_gcm_siv_ctx),
"AEAD state is too small");
#if defined(__GNUC__) || defined(__clang__)
OPENSSL_STATIC_ASSERT(alignof(union evp_aead_ctx_st_state) >=
alignof(struct aead_aes_gcm_siv_ctx),
"AEAD state has insufficient alignment");
#endif
static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) >=
sizeof(struct aead_aes_gcm_siv_ctx),
"AEAD state is too small");
static_assert(alignof(union evp_aead_ctx_st_state) >=
alignof(struct aead_aes_gcm_siv_ctx),
"AEAD state has insufficient alignment");
static int aead_aes_gcm_siv_init(EVP_AEAD_CTX *ctx, const uint8_t *key,
size_t key_len, size_t tag_len) {
@@ -619,18 +598,15 @@ static void aead_aes_gcm_siv_cleanup(EVP_AEAD_CTX *ctx) {}
static void gcm_siv_crypt(uint8_t *out, const uint8_t *in, size_t in_len,
const uint8_t initial_counter[AES_BLOCK_SIZE],
block128_f enc_block, const AES_KEY *key) {
union {
uint32_t w[4];
uint8_t c[16];
} counter;
uint8_t counter[16];
OPENSSL_memcpy(counter.c, initial_counter, AES_BLOCK_SIZE);
counter.c[15] |= 0x80;
OPENSSL_memcpy(counter, initial_counter, AES_BLOCK_SIZE);
counter[15] |= 0x80;
for (size_t done = 0; done < in_len;) {
uint8_t keystream[AES_BLOCK_SIZE];
enc_block(counter.c, keystream, key);
counter.w[0]++;
enc_block(counter, keystream, key);
CRYPTO_store_u32_le(counter, CRYPTO_load_u32_le(counter) + 1);
size_t todo = AES_BLOCK_SIZE;
if (in_len - done < todo) {
@@ -670,17 +646,10 @@ static void gcm_siv_polyval(
CRYPTO_POLYVAL_update_blocks(&polyval_ctx, scratch, sizeof(scratch));
}
union {
uint8_t c[16];
struct {
uint64_t ad;
uint64_t in;
} bitlens;
} length_block;
length_block.bitlens.ad = ad_len * 8;
length_block.bitlens.in = in_len * 8;
CRYPTO_POLYVAL_update_blocks(&polyval_ctx, length_block.c,
uint8_t length_block[16];
CRYPTO_store_u64_le(length_block, ad_len * 8);
CRYPTO_store_u64_le(length_block + 8, in_len * 8);
CRYPTO_POLYVAL_update_blocks(&polyval_ctx, length_block,
sizeof(length_block));
CRYPTO_POLYVAL_finish(&polyval_ctx, out_tag);
@@ -857,22 +826,15 @@ static const EVP_AEAD aead_aes_256_gcm_siv = {
#if defined(AES_GCM_SIV_ASM)
static char avx_aesni_capable(void) {
const uint32_t ecx = OPENSSL_ia32cap_P[1];
return (ecx & (1 << (57 - 32))) != 0 /* AESNI */ &&
(ecx & (1 << 28)) != 0 /* AVX */;
}
const EVP_AEAD *EVP_aead_aes_128_gcm_siv(void) {
if (avx_aesni_capable()) {
if (CRYPTO_is_AVX_capable() && CRYPTO_is_AESNI_capable()) {
return &aead_aes_128_gcm_siv_asm;
}
return &aead_aes_128_gcm_siv;
}
const EVP_AEAD *EVP_aead_aes_256_gcm_siv(void) {
if (avx_aesni_capable()) {
if (CRYPTO_is_AVX_capable() && CRYPTO_is_AESNI_capable()) {
return &aead_aes_256_gcm_siv_asm;
}
return &aead_aes_256_gcm_siv;
@@ -14,107 +14,30 @@
#include <CCryptoBoringSSL_aead.h>
#include <assert.h>
#include <string.h>
#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];
};
OPENSSL_STATIC_ASSERT(sizeof(((EVP_AEAD_CTX *)NULL)->state) >=
sizeof(struct aead_chacha20_poly1305_ctx),
"AEAD state is too small");
#if defined(__GNUC__) || defined(__clang__)
OPENSSL_STATIC_ASSERT(alignof(union evp_aead_ctx_st_state) >=
alignof(struct aead_chacha20_poly1305_ctx),
"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_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) >=
sizeof(struct aead_chacha20_poly1305_ctx),
"AEAD state is too small");
static_assert(alignof(union evp_aead_ctx_st_state) >=
alignof(struct aead_chacha20_poly1305_ctx),
"AEAD state has insufficient alignment");
static int aead_chacha20_poly1305_init(EVP_AEAD_CTX *ctx, const uint8_t *key,
size_t key_len, size_t tag_len) {
@@ -222,7 +145,7 @@ static int chacha20_poly1305_seal_scatter(
// encrypted byte-by-byte first.
if (extra_in_len) {
static const size_t kChaChaBlockSize = 64;
uint32_t block_counter = 1 + (in_len / kChaChaBlockSize);
uint32_t block_counter = (uint32_t)(1 + (in_len / kChaChaBlockSize));
size_t offset = in_len % kChaChaBlockSize;
uint8_t block[64 /* kChaChaBlockSize */];
@@ -238,8 +161,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 +244,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);
@@ -58,8 +58,8 @@
#include <CCryptoBoringSSL_des.h>
#include <CCryptoBoringSSL_nid.h>
#include "../fipsmodule/cipher/internal.h"
#include "internal.h"
#include "../delocate.h"
typedef struct {
@@ -88,17 +88,21 @@ static int des_cbc_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in,
return 1;
}
DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_des_cbc) {
memset(out, 0, sizeof(EVP_CIPHER));
out->nid = NID_des_cbc;
out->block_size = 8;
out->key_len = 8;
out->iv_len = 8;
out->ctx_size = sizeof(EVP_DES_KEY);
out->flags = EVP_CIPH_CBC_MODE;
out->init = des_init_key;
out->cipher = des_cbc_cipher;
}
static const EVP_CIPHER evp_des_cbc = {
/* nid = */ NID_des_cbc,
/* block_size = */ 8,
/* key_len = */ 8,
/* iv_len = */ 8,
/* ctx_size = */ sizeof(EVP_DES_KEY),
/* flags = */ EVP_CIPH_CBC_MODE,
/* app_data = */ NULL,
/* init = */ des_init_key,
/* cipher = */ des_cbc_cipher,
/* cleanup = */ NULL,
/* ctrl = */ NULL,
};
const EVP_CIPHER *EVP_des_cbc(void) { return &evp_des_cbc; }
static int des_ecb_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in,
size_t in_len) {
@@ -107,25 +111,29 @@ static int des_ecb_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in,
}
in_len -= ctx->cipher->block_size;
EVP_DES_KEY *dat = (EVP_DES_KEY *) ctx->cipher_data;
EVP_DES_KEY *dat = (EVP_DES_KEY *)ctx->cipher_data;
for (size_t i = 0; i <= in_len; i += ctx->cipher->block_size) {
DES_ecb_encrypt((DES_cblock *) (in + i), (DES_cblock *) (out + i),
DES_ecb_encrypt((DES_cblock *)(in + i), (DES_cblock *)(out + i),
&dat->ks.ks, ctx->encrypt);
}
return 1;
}
DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_des_ecb) {
memset(out, 0, sizeof(EVP_CIPHER));
out->nid = NID_des_ecb;
out->block_size = 8;
out->key_len = 8;
out->iv_len = 0;
out->ctx_size = sizeof(EVP_DES_KEY);
out->flags = EVP_CIPH_ECB_MODE;
out->init = des_init_key;
out->cipher = des_ecb_cipher;
}
static const EVP_CIPHER evp_des_ecb = {
/* nid = */ NID_des_ecb,
/* block_size = */ 8,
/* key_len = */ 8,
/* iv_len = */ 0,
/* ctx_size = */ sizeof(EVP_DES_KEY),
/* flags = */ EVP_CIPH_ECB_MODE,
/* app_data = */ NULL,
/* init = */ des_init_key,
/* cipher = */ des_ecb_cipher,
/* cleanup = */ NULL,
/* ctrl = */ NULL,
};
const EVP_CIPHER *EVP_des_ecb(void) { return &evp_des_ecb; }
typedef struct {
union {
@@ -137,7 +145,7 @@ typedef struct {
static int des_ede3_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key,
const uint8_t *iv, int enc) {
DES_cblock *deskey = (DES_cblock *)key;
DES_EDE_KEY *dat = (DES_EDE_KEY*) ctx->cipher_data;
DES_EDE_KEY *dat = (DES_EDE_KEY *)ctx->cipher_data;
DES_set_key(&deskey[0], &dat->ks.ks[0]);
DES_set_key(&deskey[1], &dat->ks.ks[1]);
@@ -147,8 +155,8 @@ static int des_ede3_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key,
}
static int des_ede3_cbc_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out,
const uint8_t *in, size_t in_len) {
DES_EDE_KEY *dat = (DES_EDE_KEY*) ctx->cipher_data;
const uint8_t *in, size_t in_len) {
DES_EDE_KEY *dat = (DES_EDE_KEY *)ctx->cipher_data;
DES_ede3_cbc_encrypt(in, out, in_len, &dat->ks.ks[0], &dat->ks.ks[1],
&dat->ks.ks[2], (DES_cblock *)ctx->iv, ctx->encrypt);
@@ -156,22 +164,26 @@ static int des_ede3_cbc_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out,
return 1;
}
DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_des_ede3_cbc) {
memset(out, 0, sizeof(EVP_CIPHER));
out->nid = NID_des_ede3_cbc;
out->block_size = 8;
out->key_len = 24;
out->iv_len = 8;
out->ctx_size = sizeof(DES_EDE_KEY);
out->flags = EVP_CIPH_CBC_MODE;
out->init = des_ede3_init_key;
out->cipher = des_ede3_cbc_cipher;
}
static const EVP_CIPHER evp_des_ede3_cbc = {
/* nid = */ NID_des_ede3_cbc,
/* block_size = */ 8,
/* key_len = */ 24,
/* iv_len = */ 8,
/* ctx_size = */ sizeof(DES_EDE_KEY),
/* flags = */ EVP_CIPH_CBC_MODE,
/* app_data = */ NULL,
/* init = */ des_ede3_init_key,
/* cipher = */ des_ede3_cbc_cipher,
/* cleanup = */ NULL,
/* ctrl = */ NULL,
};
const EVP_CIPHER *EVP_des_ede3_cbc(void) { return &evp_des_ede3_cbc; }
static int des_ede_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key,
const uint8_t *iv, int enc) {
DES_cblock *deskey = (DES_cblock *) key;
DES_EDE_KEY *dat = (DES_EDE_KEY *) ctx->cipher_data;
const uint8_t *iv, int enc) {
DES_cblock *deskey = (DES_cblock *)key;
DES_EDE_KEY *dat = (DES_EDE_KEY *)ctx->cipher_data;
DES_set_key(&deskey[0], &dat->ks.ks[0]);
DES_set_key(&deskey[1], &dat->ks.ks[1]);
@@ -180,17 +192,21 @@ static int des_ede_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key,
return 1;
}
DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_des_ede_cbc) {
memset(out, 0, sizeof(EVP_CIPHER));
out->nid = NID_des_ede_cbc;
out->block_size = 8;
out->key_len = 16;
out->iv_len = 8;
out->ctx_size = sizeof(DES_EDE_KEY);
out->flags = EVP_CIPH_CBC_MODE;
out->init = des_ede_init_key;
out->cipher = des_ede3_cbc_cipher;
}
static const EVP_CIPHER evp_des_ede_cbc = {
/* nid = */ NID_des_ede_cbc,
/* block_size = */ 8,
/* key_len = */ 16,
/* iv_len = */ 8,
/* ctx_size = */ sizeof(DES_EDE_KEY),
/* flags = */ EVP_CIPH_CBC_MODE,
/* app_data = */ NULL,
/* init = */ des_ede_init_key,
/* cipher = */ des_ede3_cbc_cipher,
/* cleanup = */ NULL,
/* ctrl = */ NULL,
};
const EVP_CIPHER *EVP_des_ede_cbc(void) { return &evp_des_ede_cbc; }
static int des_ede_ecb_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out,
const uint8_t *in, size_t in_len) {
@@ -208,30 +224,36 @@ static int des_ede_ecb_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out,
return 1;
}
DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_des_ede) {
memset(out, 0, sizeof(EVP_CIPHER));
out->nid = NID_des_ede_ecb;
out->block_size = 8;
out->key_len = 16;
out->iv_len = 0;
out->ctx_size = sizeof(DES_EDE_KEY);
out->flags = EVP_CIPH_ECB_MODE;
out->init = des_ede_init_key;
out->cipher = des_ede_ecb_cipher;
}
static const EVP_CIPHER evp_des_ede = {
/* nid = */ NID_des_ede_ecb,
/* block_size = */ 8,
/* key_len = */ 16,
/* iv_len = */ 0,
/* ctx_size = */ sizeof(DES_EDE_KEY),
/* flags = */ EVP_CIPH_ECB_MODE,
/* app_data = */ NULL,
/* init = */ des_ede_init_key,
/* cipher = */ des_ede_ecb_cipher,
/* cleanup = */ NULL,
/* ctrl = */ NULL,
};
DEFINE_METHOD_FUNCTION(EVP_CIPHER, EVP_des_ede3) {
memset(out, 0, sizeof(EVP_CIPHER));
out->nid = NID_des_ede3_ecb;
out->block_size = 8;
out->key_len = 24;
out->iv_len = 0;
out->ctx_size = sizeof(DES_EDE_KEY);
out->flags = EVP_CIPH_ECB_MODE;
out->init = des_ede3_init_key;
out->cipher = des_ede_ecb_cipher;
}
const EVP_CIPHER *EVP_des_ede(void) { return &evp_des_ede; }
const EVP_CIPHER* EVP_des_ede3_ecb(void) {
return EVP_des_ede3();
}
static const EVP_CIPHER evp_des_ede3 = {
/* nid = */ NID_des_ede3_ecb,
/* block_size = */ 8,
/* key_len = */ 24,
/* iv_len = */ 0,
/* ctx_size = */ sizeof(DES_EDE_KEY),
/* flags = */ EVP_CIPH_ECB_MODE,
/* app_data = */ NULL,
/* init = */ des_ede3_init_key,
/* cipher = */ des_ede_ecb_cipher,
/* cleanup = */ NULL,
/* ctrl = */ NULL,
};
const EVP_CIPHER *EVP_des_ede3(void) { return &evp_des_ede3; }
const EVP_CIPHER *EVP_des_ede3_ecb(void) { return EVP_des_ede3(); }
@@ -60,6 +60,7 @@
#include <CCryptoBoringSSL_nid.h>
#include "../fipsmodule/cipher/internal.h"
#include "../internal.h"
@@ -57,6 +57,7 @@
#include <CCryptoBoringSSL_cipher.h>
#include <CCryptoBoringSSL_nid.h>
#include "../fipsmodule/cipher/internal.h"
#include "../internal.h"
@@ -61,6 +61,8 @@
#include <CCryptoBoringSSL_nid.h>
#include <CCryptoBoringSSL_rc4.h>
#include "../fipsmodule/cipher/internal.h"
static int rc4_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key,
const uint8_t *iv, int enc) {
@@ -23,7 +23,6 @@
#include <CCryptoBoringSSL_md5.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_sha.h>
#include <CCryptoBoringSSL_type_check.h>
#include "../fipsmodule/cipher/internal.h"
#include "../internal.h"
@@ -42,17 +41,12 @@ typedef struct {
char implicit_iv;
} AEAD_TLS_CTX;
OPENSSL_STATIC_ASSERT(EVP_MAX_MD_SIZE < 256,
"mac_key_len does not fit in uint8_t");
static_assert(EVP_MAX_MD_SIZE < 256, "mac_key_len does not fit in uint8_t");
OPENSSL_STATIC_ASSERT(sizeof(((EVP_AEAD_CTX *)NULL)->state) >=
sizeof(AEAD_TLS_CTX),
"AEAD state is too small");
#if defined(__GNUC__) || defined(__clang__)
OPENSSL_STATIC_ASSERT(alignof(union evp_aead_ctx_st_state) >=
alignof(AEAD_TLS_CTX),
"AEAD state has insufficient alignment");
#endif
static_assert(sizeof(((EVP_AEAD_CTX *)NULL)->state) >= sizeof(AEAD_TLS_CTX),
"AEAD state is too small");
static_assert(alignof(union evp_aead_ctx_st_state) >= alignof(AEAD_TLS_CTX),
"AEAD state has insufficient alignment");
static void aead_tls_cleanup(EVP_AEAD_CTX *ctx) {
AEAD_TLS_CTX *tls_ctx = (AEAD_TLS_CTX *)&ctx->state;
@@ -343,7 +337,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;
@@ -428,22 +422,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,
@@ -472,13 +450,6 @@ static int aead_tls_get_iv(const EVP_AEAD_CTX *ctx, const uint8_t **out_iv,
return 1;
}
static int aead_null_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) {
return aead_tls_init(ctx, key, key_len, tag_len, dir, EVP_enc_null(),
EVP_sha1(), 1 /* implicit iv */);
}
static const EVP_AEAD aead_aes_128_cbc_sha1_tls = {
SHA_DIGEST_LENGTH + 16, // key len (SHA1 + AES128)
16, // nonce len (IV)
@@ -564,40 +535,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)
@@ -632,23 +569,6 @@ static const EVP_AEAD aead_des_ede3_cbc_sha1_tls_implicit_iv = {
aead_tls_tag_len,
};
static const EVP_AEAD aead_null_sha1_tls = {
SHA_DIGEST_LENGTH, // key len
0, // nonce len
SHA_DIGEST_LENGTH, // overhead (SHA1)
SHA_DIGEST_LENGTH, // max tag length
0, // seal_scatter_supports_extra_in
NULL, // init
aead_null_sha1_tls_init,
aead_tls_cleanup,
aead_tls_open,
aead_tls_seal_scatter,
NULL, // open_gather
NULL, // get_iv
aead_tls_tag_len,
};
const EVP_AEAD *EVP_aead_aes_128_cbc_sha1_tls(void) {
return &aead_aes_128_cbc_sha1_tls;
}
@@ -669,14 +589,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;
}
@@ -684,5 +596,3 @@ const EVP_AEAD *EVP_aead_des_ede3_cbc_sha1_tls(void) {
const EVP_AEAD *EVP_aead_des_ede3_cbc_sha1_tls_implicit_iv(void) {
return &aead_des_ede3_cbc_sha1_tls_implicit_iv;
}
const EVP_AEAD *EVP_aead_null_sha1_tls(void) { return &aead_null_sha1_tls; }
@@ -57,6 +57,9 @@
#ifndef OPENSSL_HEADER_CIPHER_EXTRA_INTERNAL_H
#define OPENSSL_HEADER_CIPHER_EXTRA_INTERNAL_H
#include <assert.h>
#include <stdlib.h>
#include <CCryptoBoringSSL_base.h>
#include "../internal.h"
@@ -95,6 +98,25 @@ 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_sha256_final_with_secret_suffix acts like
// |EVP_sha1_final_with_secret_suffix|, but for SHA-256.
//
// This function is exported for unit tests.
OPENSSL_EXPORT int EVP_sha256_final_with_secret_suffix(
SHA256_CTX *ctx, uint8_t out[SHA256_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 +126,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 +137,98 @@ 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_AARCH64)) && \
!defined(OPENSSL_NO_ASM)
static_assert(sizeof(union chacha20_poly1305_open_data) == 48,
"wrong chacha20_poly1305_open_data size");
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) {
#if defined(OPENSSL_X86_64)
return CRYPTO_is_SSE4_1_capable();
#elif defined(OPENSSL_AARCH64)
return CRYPTO_is_NEON_capable();
#endif
}
// chacha20_poly1305_open is defined in chacha20_poly1305_*.pl. It decrypts
// |plaintext_len| bytes from |ciphertext| and writes them to |out_plaintext|.
// Additional input parameters are passed in |aead_data->in|. On exit, it will
// write calculated tag value to |aead_data->out.tag|, which the caller must
// 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_*.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) {
@@ -183,132 +174,335 @@ 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;
}
// 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;
}
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);
int EVP_sha256_final_with_secret_suffix(SHA256_CTX *ctx,
uint8_t out[SHA256_DIGEST_LENGTH],
const uint8_t *in, size_t len,
size_t max_len) {
// Bound the input length so |total_bits| below fits in four bytes. This is
// redundant with TLS record size limits. This also ensures |input_idx| below
// 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;
}
// 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 + SHA256_CBLOCK - 1) >> 6;
size_t last_block = num_blocks - 1;
size_t max_blocks = (ctx->num + max_len + 1 + 8 + SHA256_CBLOCK - 1) >> 6;
// The bounds above imply |total_bits| fits in four bytes.
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[SHA256_CBLOCK] = {0};
uint32_t result[8] = {0};
// input_idx is the index into |in| corresponding to the current block.
// However, we allow this index to overflow beyond |max_len|, to simplify the
// 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 = SHA256_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 < SHA256_CBLOCK; j++) {
// input[idx] corresponds to block[j].
size_t idx = input_idx + j - block_start;
// The barriers on |len| are not strictly necessary. However, without
// them, GCC compiles this code by incorporating |len| into the loop
// 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 += SHA256_CBLOCK - block_start;
// Fill in the length if this is the last block.
crypto_word_t is_last_block = constant_time_eq_w(i, last_block);
for (size_t j = 0; j < 4; j++) {
block[SHA256_CBLOCK - 4 + j] |= is_last_block & length_bytes[j];
}
// Process the block and save the hash state if it is the final value.
SHA256_Transform(ctx, block);
for (size_t j = 0; j < 8; j++) {
result[j] |= is_last_block & ctx->h[j];
}
}
// Write the output.
for (size_t i = 0; i < 8; 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;
}
}
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,
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) {
static int tls_cbc_digest_record_sha1(uint8_t *md_out, size_t *md_out_size,
const uint8_t header[13],
const uint8_t *data, size_t data_size,
size_t data_plus_mac_plus_padding_size,
const uint8_t *mac_secret,
unsigned mac_secret_length) {
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;
}
// Compute the initial HMAC block.
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 < SHA_CBLOCK; i++) {
hmac_pad[i] ^= 0x36;
}
SHA_CTX ctx;
SHA1_Init(&ctx);
SHA1_Update(&ctx, hmac_pad, SHA_CBLOCK);
SHA1_Update(&ctx, header, 13);
// There are at most 256 bytes of padding, so we can compute the public
// minimum length for |data_size|.
size_t min_data_size = 0;
if (data_plus_mac_plus_padding_size > SHA_DIGEST_LENGTH + 256) {
min_data_size = data_plus_mac_plus_padding_size - SHA_DIGEST_LENGTH - 256;
}
// 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);
// 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.
SHA1_Init(&ctx);
for (size_t i = 0; i < SHA_CBLOCK; i++) {
hmac_pad[i] ^= 0x6a;
}
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;
}
static int tls_cbc_digest_record_sha256(uint8_t *md_out, size_t *md_out_size,
const uint8_t header[13],
const uint8_t *data, size_t data_size,
size_t data_plus_mac_plus_padding_size,
const uint8_t *mac_secret,
unsigned mac_secret_length) {
if (mac_secret_length > SHA256_CBLOCK) {
// HMAC pads small keys with zeros and hashes large keys down. This function
// should never reach the large key case.
assert(0);
return 0;
}
// Compute the initial HMAC block.
uint8_t hmac_pad[SHA256_CBLOCK];
OPENSSL_memset(hmac_pad, 0, sizeof(hmac_pad));
OPENSSL_memcpy(hmac_pad, mac_secret, mac_secret_length);
for (size_t i = 0; i < SHA256_CBLOCK; i++) {
hmac_pad[i] ^= 0x36;
}
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, hmac_pad, SHA256_CBLOCK);
SHA256_Update(&ctx, header, 13);
// There are at most 256 bytes of padding, so we can compute the public
// minimum length for |data_size|.
size_t min_data_size = 0;
if (data_plus_mac_plus_padding_size > SHA256_DIGEST_LENGTH + 256) {
min_data_size =
data_plus_mac_plus_padding_size - SHA256_DIGEST_LENGTH - 256;
}
// Hash the public minimum length directly. This reduces the number of blocks
// that must be computed in constant-time.
SHA256_Update(&ctx, data, min_data_size);
// Hash the remaining data without leaking |data_size|.
uint8_t mac_out[SHA256_DIGEST_LENGTH];
if (!EVP_sha256_final_with_secret_suffix(
&ctx, mac_out, data + min_data_size, data_size - min_data_size,
data_plus_mac_plus_padding_size - min_data_size)) {
return 0;
}
// Complete the HMAC in the standard manner.
SHA256_Init(&ctx);
for (size_t i = 0; i < SHA256_CBLOCK; i++) {
hmac_pad[i] ^= 0x6a;
}
SHA256_Update(&ctx, hmac_pad, SHA256_CBLOCK);
SHA256_Update(&ctx, mac_out, SHA256_DIGEST_LENGTH);
SHA256_Final(md_out, &ctx);
*md_out_size = SHA256_DIGEST_LENGTH;
return 1;
}
int EVP_tls_cbc_digest_record(const EVP_MD *md, uint8_t *md_out,
size_t *md_out_size, const uint8_t header[13],
const uint8_t *data, size_t data_size,
size_t data_plus_mac_plus_padding_size,
const uint8_t *mac_secret,
unsigned mac_secret_length) {
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;
return tls_cbc_digest_record_sha1(
md_out, md_out_size, header, data, data_size,
data_plus_mac_plus_padding_size, mac_secret, mac_secret_length);
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;
return tls_cbc_digest_record_sha256(
md_out, md_out_size, header, data, data_size,
data_plus_mac_plus_padding_size, mac_secret, mac_secret_length);
default:
// EVP_tls_cbc_record_digest_supported should have been called first to
@@ -317,176 +511,4 @@ int EVP_tls_cbc_digest_record(const EVP_MD *md, uint8_t *md_out,
*md_out_size = 0;
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;
}
// 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));
OPENSSL_memcpy(hmac_pad, mac_secret, mac_secret_length);
for (size_t i = 0; i < md_block_size; i++) {
hmac_pad[i] ^= 0x36;
}
md_transform(&md_state, hmac_pad);
// 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);
}
}
uint8_t mac_out[EVP_MAX_MD_SIZE];
OPENSSL_memset(mac_out, 0, sizeof(mac_out));
// 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);
return 0;
}
// Complete the HMAC in the standard manner.
for (size_t i = 0; i < md_block_size; 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);
return 1;
}
+50 -211
View File
@@ -70,18 +70,12 @@
#include "../internal.h"
DEFINE_LHASH_OF(CONF_VALUE)
struct conf_st {
LHASH_OF(CONF_VALUE) *data;
};
// 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 const char kDefaultSectionName[] = "default";
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) {
@@ -124,43 +118,36 @@ CONF *NCONF_new(void *method) {
return conf;
}
CONF_VALUE *CONF_VALUE_new(void) {
CONF_VALUE *v = OPENSSL_malloc(sizeof(CONF_VALUE));
if (!v) {
OPENSSL_PUT_ERROR(CONF, ERR_R_MALLOC_FAILURE);
return NULL;
}
OPENSSL_memset(v, 0, sizeof(CONF_VALUE));
return v;
}
CONF_VALUE *CONF_VALUE_new(void) { return OPENSSL_zalloc(sizeof(CONF_VALUE)); }
static void value_free_contents(CONF_VALUE *value) {
if (value->section) {
OPENSSL_free(value->section);
}
OPENSSL_free(value->section);
if (value->name) {
OPENSSL_free(value->name);
if (value->value) {
OPENSSL_free(value->value);
}
OPENSSL_free(value->value);
} else {
if (value->value) {
sk_CONF_VALUE_free((STACK_OF(CONF_VALUE)*)value->value);
}
// TODO(davidben): When |value->name| is NULL, |CONF_VALUE| is actually an
// entirely different structure. This is fragile and confusing. Make a
// proper |CONF_SECTION| type that doesn't require this.
sk_CONF_VALUE_free((STACK_OF(CONF_VALUE) *)value->value);
}
}
static void value_free(CONF_VALUE *value) {
value_free_contents(value);
OPENSSL_free(value);
if (value != NULL) {
value_free_contents(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);
}
@@ -186,28 +173,21 @@ static CONF_VALUE *NCONF_new_section(const CONF *conf, const char *section) {
if (!lh_CONF_VALUE_insert(conf->data, &old_value, v)) {
goto err;
}
if (old_value) {
value_free(old_value);
}
value_free(old_value);
ok = 1;
err:
if (!ok) {
if (sk != NULL) {
sk_CONF_VALUE_free(sk);
}
if (v != NULL) {
OPENSSL_free(v);
}
sk_CONF_VALUE_free(sk);
OPENSSL_free(v);
v = NULL;
}
return v;
}
static int str_copy(CONF *conf, char *section, char **pto, char *from) {
int q, r, rr = 0, to = 0, len = 0;
char *s, *e, *rp, *rrp, *np, *cp, v;
const char *p;
int q, to = 0, len = 0;
char v;
BUF_MEM *buf;
buf = BUF_MEM_new();
@@ -236,22 +216,6 @@ static int str_copy(CONF *conf, char *section, char **pto, char *from) {
if (*from == q) {
from++;
}
} else if (IS_DQUOTE(conf, *from)) {
q = *from;
from++;
while (!IS_EOF(conf, *from)) {
if (*from == q) {
if (*(from + 1) == q) {
from++;
} else {
break;
}
}
buf->data[to++] = *(from++);
}
if (*from == q) {
from++;
}
} else if (IS_ESC(conf, *from)) {
from++;
v = *(from++);
@@ -270,103 +234,23 @@ static int str_copy(CONF *conf, char *section, char **pto, char *from) {
} else if (IS_EOF(conf, *from)) {
break;
} else if (*from == '$') {
// try to expand it
rrp = NULL;
s = &(from[1]);
if (*s == '{') {
q = '}';
} else if (*s == '(') {
q = ')';
} else {
q = 0;
}
if (q) {
s++;
}
cp = section;
e = np = s;
while (IS_ALPHA_NUMERIC(conf, *e)) {
e++;
}
if (e[0] == ':' && e[1] == ':') {
cp = np;
rrp = e;
rr = *e;
*rrp = '\0';
e += 2;
np = e;
while (IS_ALPHA_NUMERIC(conf, *e)) {
e++;
}
}
r = *e;
*e = '\0';
rp = e;
if (q) {
if (r != q) {
OPENSSL_PUT_ERROR(CONF, CONF_R_NO_CLOSE_BRACE);
goto err;
}
e++;
}
// So at this point we have
// np which is the start of the name string which is
// '\0' terminated.
// cp which is the start of the section string which is
// '\0' terminated.
// e is the 'next point after'.
// r and rr are the chars replaced by the '\0'
// rp and rrp is where 'r' and 'rr' came from.
p = NCONF_get_string(conf, cp, np);
if (rrp != NULL) {
*rrp = rr;
}
*rp = r;
if (p == NULL) {
OPENSSL_PUT_ERROR(CONF, CONF_R_VARIABLE_HAS_NO_VALUE);
goto err;
}
size_t newsize = strlen(p) + buf->length - (e - from);
if (newsize > MAX_CONF_VALUE_LENGTH) {
OPENSSL_PUT_ERROR(CONF, CONF_R_VARIABLE_EXPANSION_TOO_LONG);
goto err;
}
if (!BUF_MEM_grow_clean(buf, newsize)) {
OPENSSL_PUT_ERROR(CONF, ERR_R_MALLOC_FAILURE);
goto err;
}
while (*p) {
buf->data[to++] = *(p++);
}
/* Since we change the pointer 'from', we also have
to change the perceived length of the string it
points at. /RL */
len -= e - from;
from = e;
/* In case there were no braces or parenthesis around
the variable reference, we have to put back the
character that was replaced with a '\0'. /RL */
*rp = r;
// Historically, $foo would expand to a previously-parsed value. This
// feature has been removed as it was unused and is a DoS vector.
OPENSSL_PUT_ERROR(CONF, CONF_R_VARIABLE_EXPANSION_NOT_SUPPORTED);
goto err;
} else {
buf->data[to++] = *(from++);
}
}
buf->data[to] = '\0';
if (*pto != NULL) {
OPENSSL_free(*pto);
}
OPENSSL_free(*pto);
*pto = buf->data;
OPENSSL_free(buf);
return 1;
err:
if (buf != NULL) {
BUF_MEM_free(buf);
}
BUF_MEM_free(buf);
return 0;
}
@@ -378,8 +262,9 @@ static CONF_VALUE *get_section(const CONF *conf, const char *section) {
return lh_CONF_VALUE_retrieve(conf->data, &template);
}
STACK_OF(CONF_VALUE) *NCONF_get_section(const CONF *conf, const char *section) {
CONF_VALUE *section_value = get_section(conf, section);
const STACK_OF(CONF_VALUE) *NCONF_get_section(const CONF *conf,
const char *section) {
const CONF_VALUE *section_value = get_section(conf, section);
if (section_value == NULL) {
return NULL;
}
@@ -390,6 +275,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;
@@ -462,33 +351,8 @@ static char *scan_quote(CONF *conf, char *p) {
return p;
}
static char *scan_dquote(CONF *conf, char *p) {
int q = *p;
p++;
while (!(IS_EOF(conf, *p))) {
if (*p == q) {
if (*(p + 1) == q) {
p++;
} else {
break;
}
}
p++;
}
if (*p == q) {
p++;
}
return p;
}
static void clear_comments(CONF *conf, char *p) {
for (;;) {
if (IS_FCOMMENT(conf, *p)) {
*p = '\0';
return;
}
if (!IS_WS(conf, *p)) {
break;
}
@@ -500,10 +364,6 @@ static void clear_comments(CONF *conf, char *p) {
*p = '\0';
return;
}
if (IS_DQUOTE(conf, *p)) {
p = scan_dquote(conf, p);
continue;
}
if (IS_QUOTE(conf, *p)) {
p = scan_quote(conf, p);
continue;
@@ -520,7 +380,7 @@ static void clear_comments(CONF *conf, char *p) {
}
}
static int def_load_bio(CONF *conf, BIO *in, long *out_error_line) {
int NCONF_load_bio(CONF *conf, BIO *in, long *out_error_line) {
static const size_t CONFBUFSIZE = 512;
int bufnum = 0, i, ii;
BUF_MEM *buff = NULL;
@@ -538,9 +398,8 @@ 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;
}
@@ -675,7 +534,6 @@ static int def_load_bio(CONF *conf, BIO *in, long *out_error_line) {
}
v->name = OPENSSL_strdup(pname);
if (v->name == NULL) {
OPENSSL_PUT_ERROR(CONF, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!str_copy(conf, psection, &(v->value), start)) {
@@ -694,43 +552,28 @@ static int def_load_bio(CONF *conf, BIO *in, long *out_error_line) {
tv = sv;
}
if (add_string(conf, tv, v) == 0) {
OPENSSL_PUT_ERROR(CONF, ERR_R_MALLOC_FAILURE);
goto err;
}
v = NULL;
}
}
if (buff != NULL) {
BUF_MEM_free(buff);
}
if (section != NULL) {
OPENSSL_free(section);
}
BUF_MEM_free(buff);
OPENSSL_free(section);
return 1;
err:
if (buff != NULL) {
BUF_MEM_free(buff);
}
if (section != NULL) {
OPENSSL_free(section);
}
BUF_MEM_free(buff);
OPENSSL_free(section);
if (out_error_line != NULL) {
*out_error_line = eline;
}
BIO_snprintf(btmp, sizeof btmp, "%ld", eline);
snprintf(btmp, sizeof btmp, "%ld", eline);
ERR_add_error_data(2, "line ", btmp);
if (v != NULL) {
if (v->name != NULL) {
OPENSSL_free(v->name);
}
if (v->value != NULL) {
OPENSSL_free(v->value);
}
if (v != NULL) {
OPENSSL_free(v);
}
OPENSSL_free(v->name);
OPENSSL_free(v->value);
OPENSSL_free(v);
}
return 0;
}
@@ -744,18 +587,14 @@ int NCONF_load(CONF *conf, const char *filename, long *out_error_line) {
return 0;
}
ret = def_load_bio(conf, in, out_error_line);
ret = NCONF_load_bio(conf, in, out_error_line);
BIO_free(in);
return ret;
}
int NCONF_load_bio(CONF *conf, BIO *bio, long *out_error_line) {
return def_load_bio(conf, bio, out_error_line);
}
int CONF_parse_list(const char *list, char sep, int remove_whitespace,
int (*list_cb)(const char *elem, int len, void *usr),
int (*list_cb)(const char *elem, size_t len, void *usr),
void *arg) {
int ret;
const char *lstart, *tmpend, *p;
@@ -768,7 +607,7 @@ int CONF_parse_list(const char *list, char sep, int remove_whitespace,
lstart = list;
for (;;) {
if (remove_whitespace) {
while (*lstart && isspace((unsigned char)*lstart)) {
while (*lstart && OPENSSL_isspace((unsigned char)*lstart)) {
lstart++;
}
}
@@ -782,7 +621,7 @@ int CONF_parse_list(const char *list, char sep, int remove_whitespace,
tmpend = lstart + strlen(lstart) - 1;
}
if (remove_whitespace) {
while (isspace((unsigned char)*tmpend)) {
while (OPENSSL_isspace((unsigned char)*tmpend)) {
tmpend--;
}
}
@@ -1,4 +1,3 @@
/* crypto/conf/conf_def.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
@@ -56,8 +55,9 @@
* [including the GNU Public Licence.]
*/
/* THIS FILE WAS AUTOMAGICALLY GENERATED!
Please modify and use keysets.pl to regenerate it. */
// This file was historically generated by keysets.pl in OpenSSL.
//
// TODO(davidben): Replace it with something more readable.
#define CONF_NUMBER 1
#define CONF_UPPER 2
@@ -67,9 +67,7 @@
#define CONF_WS 16
#define CONF_ESC 32
#define CONF_QUOTE 64
#define CONF_DQUOTE 1024
#define CONF_COMMENT 128
#define CONF_FCOMMENT 2048
#define CONF_EOF 8
#define CONF_HIGHBIT 4096
#define CONF_ALPHA (CONF_UPPER|CONF_LOWER)
@@ -79,7 +77,6 @@
#define KEYTYPES(c) CONF_type_default
#define IS_COMMENT(c,a) (KEYTYPES(c)[(a)&0xff]&CONF_COMMENT)
#define IS_FCOMMENT(c,a) (KEYTYPES(c)[(a)&0xff]&CONF_FCOMMENT)
#define IS_EOF(c,a) (KEYTYPES(c)[(a)&0xff]&CONF_EOF)
#define IS_ESC(c,a) (KEYTYPES(c)[(a)&0xff]&CONF_ESC)
#define IS_NUMBER(c,a) (KEYTYPES(c)[(a)&0xff]&CONF_NUMBER)
@@ -88,8 +85,6 @@
#define IS_ALPHA_NUMERIC_PUNCT(c,a) \
(KEYTYPES(c)[(a)&0xff]&CONF_ALPHA_NUMERIC_PUNCT)
#define IS_QUOTE(c,a) (KEYTYPES(c)[(a)&0xff]&CONF_QUOTE)
#define IS_DQUOTE(c,a) (KEYTYPES(c)[(a)&0xff]&CONF_DQUOTE)
#define IS_HIGHBIT(c,a) (KEYTYPES(c)[(a)&0xff]&CONF_HIGHBIT)
static const unsigned short CONF_type_default[256]={
0x0008,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
@@ -15,14 +15,34 @@
#ifndef OPENSSL_HEADER_CRYPTO_CONF_INTERNAL_H
#define OPENSSL_HEADER_CRYPTO_CONF_INTERNAL_H
#include <CCryptoBoringSSL_base.h>
#include "../lhash/internal.h"
#if defined(__cplusplus)
extern "C" {
#endif
DEFINE_LHASH_OF(CONF_VALUE)
struct conf_st {
LHASH_OF(CONF_VALUE) *data;
};
// CONF_VALUE_new returns a freshly allocated and zeroed |CONF_VALUE|.
CONF_VALUE *CONF_VALUE_new(void);
// CONF_parse_list takes a list separated by 'sep' and calls |list_cb| giving
// the start and length of each member, optionally stripping leading and
// trailing whitespace. This can be used to parse comma separated lists for
// example. If |list_cb| returns <= 0, then the iteration is halted and that
// value is returned immediately. Otherwise it returns one. Note that |list_cb|
// may be called on an empty member.
OPENSSL_EXPORT int CONF_parse_list(
const char *list, char sep, int remove_whitespace,
int (*list_cb)(const char *elem, size_t len, void *usr), void *arg);
#if defined(__cplusplus)
} // extern C
@@ -0,0 +1,75 @@
/* 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 "internal.h"
#if defined(OPENSSL_AARCH64) && defined(OPENSSL_APPLE) && \
!defined(OPENSSL_STATIC_ARMCAP)
#include <sys/sysctl.h>
#include <sys/types.h>
#include <CCryptoBoringSSL_arm_arch.h>
static int has_hw_feature(const char *name) {
int value;
size_t len = sizeof(value);
if (sysctlbyname(name, &value, &len, NULL, 0) != 0) {
return 0;
}
if (len != sizeof(int)) {
// This should not happen. All the values queried should be integer-valued.
assert(0);
return 0;
}
// Per sys/sysctl.h:
//
// Selectors that return errors are not support on the system. Supported
// features will return 1 if they are recommended or 0 if they are supported
// but are not expected to help performance. Future versions of these
// selectors may return larger values as necessary so it is best to test for
// non zero.
return value != 0;
}
void OPENSSL_cpuid_setup(void) {
// Apple ARM64 platforms have NEON and cryptography extensions available
// statically, so we do not need to query them. In particular, there sometimes
// are no sysctls corresponding to such features. See below.
#if !defined(__ARM_NEON) || !defined(__ARM_FEATURE_AES) || \
!defined(__ARM_FEATURE_SHA2)
#error "NEON and crypto extensions should be statically available."
#endif
OPENSSL_armcap_P =
ARMV7_NEON | ARMV8_AES | ARMV8_PMULL | ARMV8_SHA1 | ARMV8_SHA256;
// See Apple's documentation for sysctl names:
// https://developer.apple.com/documentation/kernel/1387446-sysctlbyname/determining_instruction_set_characteristics
//
// The new feature names, e.g. "hw.optional.arm.FEAT_SHA512", are only
// available in macOS 12. For compatibility with macOS 11, we also support
// the old names. The old names don't have values for features like FEAT_AES,
// so instead we detect them statically above.
//
// If querying new sysctls, update the Chromium sandbox definition. See
// https://crrev.com/c/4415225.
if (has_hw_feature("hw.optional.arm.FEAT_SHA512") ||
has_hw_feature("hw.optional.armv8_2_sha512")) {
OPENSSL_armcap_P |= ARMV8_SHA512;
}
}
#endif // OPENSSL_AARCH64 && OPENSSL_APPLE && !OPENSSL_STATIC_ARMCAP
@@ -12,7 +12,7 @@
* 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>
#include "internal.h"
#if defined(OPENSSL_AARCH64) && defined(OPENSSL_FUCHSIA) && \
!defined(OPENSSL_STATIC_ARMCAP)
@@ -23,16 +23,13 @@
#include <CCryptoBoringSSL_arm_arch.h>
#include "internal.h"
extern uint32_t OPENSSL_armcap_P;
void OPENSSL_cpuid_setup(void) {
uint32_t hwcap;
zx_status_t rc = zx_system_get_features(ZX_FEATURE_KIND_CPU, &hwcap);
if (rc != ZX_OK || (hwcap & ZX_ARM64_FEATURE_ISA_ASIMD) == 0) {
// Matching OpenSSL, if NEON/ASIMD is missing, don't report other features
// either.
// If NEON/ASIMD is missing, don't report other features either. This
// matches OpenSSL, and the other features depend on SIMD registers.
return;
}
@@ -47,9 +44,12 @@ void OPENSSL_cpuid_setup(void) {
if (hwcap & ZX_ARM64_FEATURE_ISA_SHA1) {
OPENSSL_armcap_P |= ARMV8_SHA1;
}
if (hwcap & ZX_ARM64_FEATURE_ISA_SHA2) {
if (hwcap & ZX_ARM64_FEATURE_ISA_SHA256) {
OPENSSL_armcap_P |= ARMV8_SHA256;
}
if (hwcap & ZX_ARM64_FEATURE_ISA_SHA512) {
OPENSSL_armcap_P |= ARMV8_SHA512;
}
}
#endif // OPENSSL_AARCH64 && !OPENSSL_STATIC_ARMCAP
#endif // OPENSSL_AARCH64 && OPENSSL_FUCHSIA && !OPENSSL_STATIC_ARMCAP
@@ -12,7 +12,7 @@
* 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>
#include "internal.h"
#if defined(OPENSSL_AARCH64) && defined(OPENSSL_LINUX) && \
!defined(OPENSSL_STATIC_ARMCAP)
@@ -21,10 +21,6 @@
#include <CCryptoBoringSSL_arm_arch.h>
#include "internal.h"
extern uint32_t OPENSSL_armcap_P;
void OPENSSL_cpuid_setup(void) {
unsigned long hwcap = getauxval(AT_HWCAP);
@@ -36,6 +32,7 @@ void OPENSSL_cpuid_setup(void) {
static const unsigned long kPMULL = 1 << 4;
static const unsigned long kSHA1 = 1 << 5;
static const unsigned long kSHA256 = 1 << 6;
static const unsigned long kSHA512 = 1 << 21;
if ((hwcap & kNEON) == 0) {
// Matching OpenSSL, if NEON is missing, don't report other features
@@ -57,6 +54,9 @@ void OPENSSL_cpuid_setup(void) {
if (hwcap & kSHA256) {
OPENSSL_armcap_P |= ARMV8_SHA256;
}
if (hwcap & kSHA512) {
OPENSSL_armcap_P |= ARMV8_SHA512;
}
}
#endif // OPENSSL_AARCH64 && !OPENSSL_STATIC_ARMCAP
#endif // OPENSSL_AARCH64 && OPENSSL_LINUX && !OPENSSL_STATIC_ARMCAP
@@ -0,0 +1,61 @@
/* Copyright (c) 2022, Robert Nagy <robert.nagy@gmail.com>
*
* 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_OPENBSD) && \
!defined(OPENSSL_STATIC_ARMCAP)
#include <sys/sysctl.h>
#include <machine/cpu.h>
#include <machine/armreg.h>
#include <CCryptoBoringSSL_arm_arch.h>
#include "internal.h"
void OPENSSL_cpuid_setup(void) {
int isar0_mib[] = { CTL_MACHDEP, CPU_ID_AA64ISAR0 };
uint64_t cpu_id = 0;
size_t len = sizeof(cpu_id);
if (sysctl(isar0_mib, 2, &cpu_id, &len, NULL, 0) < 0) {
return;
}
OPENSSL_armcap_P |= ARMV7_NEON;
if (ID_AA64ISAR0_AES(cpu_id) >= ID_AA64ISAR0_AES_BASE) {
OPENSSL_armcap_P |= ARMV8_AES;
}
if (ID_AA64ISAR0_AES(cpu_id) >= ID_AA64ISAR0_AES_PMULL) {
OPENSSL_armcap_P |= ARMV8_PMULL;
}
if (ID_AA64ISAR0_SHA1(cpu_id) >= ID_AA64ISAR0_SHA1_BASE) {
OPENSSL_armcap_P |= ARMV8_SHA1;
}
if (ID_AA64ISAR0_SHA2(cpu_id) >= ID_AA64ISAR0_SHA2_BASE) {
OPENSSL_armcap_P |= ARMV8_SHA256;
}
if (ID_AA64ISAR0_SHA2(cpu_id) >= ID_AA64ISAR0_SHA2_512) {
OPENSSL_armcap_P |= ARMV8_SHA512;
}
}
#endif // OPENSSL_AARCH64 && OPENSSL_OPENBSD && !OPENSSL_STATIC_ARMCAP
@@ -0,0 +1,93 @@
/* Copyright (c) 2023, 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 "internal.h"
// While Arm system registers are normally not available to userspace, FreeBSD
// expects userspace to simply read them. It traps the reads and fills in CPU
// capabilities.
#if defined(OPENSSL_AARCH64) && !defined(OPENSSL_STATIC_ARMCAP) && \
(defined(ANDROID_BAREMETAL) || defined(OPENSSL_FREEBSD))
#include <CCryptoBoringSSL_arm_arch.h>
#define ID_AA64PFR0_EL1_ADVSIMD 5
#define ID_AA64ISAR0_EL1_AES 1
#define ID_AA64ISAR0_EL1_SHA1 2
#define ID_AA64ISAR0_EL1_SHA2 3
#define NBITS_ID_FIELD 4
#define READ_SYSREG(name) \
({ \
uint64_t _r; \
__asm__("mrs %0, " name : "=r"(_r)); \
_r; \
})
static unsigned get_id_field(uint64_t reg, unsigned field) {
return (reg >> (field * NBITS_ID_FIELD)) & ((1 << NBITS_ID_FIELD) - 1);
}
static int get_signed_id_field(uint64_t reg, unsigned field) {
unsigned value = get_id_field(reg, field);
if (value & (1 << (NBITS_ID_FIELD - 1))) {
return (int)(value | (UINT64_MAX << NBITS_ID_FIELD));
} else {
return (int)value;
}
}
static uint32_t read_armcap(void) {
uint32_t armcap = ARMV7_NEON;
uint64_t id_aa64pfr0_el1 = READ_SYSREG("id_aa64pfr0_el1");
if (get_signed_id_field(id_aa64pfr0_el1, ID_AA64PFR0_EL1_ADVSIMD) < 0) {
// If AdvSIMD ("NEON") is missing, don't report other features either.
// This matches OpenSSL.
return 0;
}
uint64_t id_aa64isar0_el1 = READ_SYSREG("id_aa64isar0_el1");
unsigned aes = get_id_field(id_aa64isar0_el1, ID_AA64ISAR0_EL1_AES);
if (aes > 0) {
armcap |= ARMV8_AES;
}
if (aes > 1) {
armcap |= ARMV8_PMULL;
}
unsigned sha1 = get_id_field(id_aa64isar0_el1, ID_AA64ISAR0_EL1_SHA1);
if (sha1 > 0) {
armcap |= ARMV8_SHA1;
}
unsigned sha2 = get_id_field(id_aa64isar0_el1, ID_AA64ISAR0_EL1_SHA2);
if (sha2 > 0) {
armcap |= ARMV8_SHA256;
}
if (sha2 > 1) {
armcap |= ARMV8_SHA512;
}
return armcap;
}
void OPENSSL_cpuid_setup(void) { OPENSSL_armcap_P |= read_armcap(); }
#endif // OPENSSL_AARCH64 && !OPENSSL_STATIC_ARMCAP &&
// (ANDROID_BAREMETAL || OPENSSL_FREEBSD)
@@ -1,4 +1,5 @@
/* Copyright (c) 2014, Google Inc.
/* 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
@@ -12,27 +13,29 @@
* 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>
#include "internal.h"
#if (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) && \
#if defined(OPENSSL_AARCH64) && defined(OPENSSL_WINDOWS) && \
!defined(OPENSSL_STATIC_ARMCAP)
#include <windows.h>
#include <CCryptoBoringSSL_arm_arch.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;
char CRYPTO_is_NEON_capable_at_runtime(void) {
return (OPENSSL_armcap_P & ARMV7_NEON) != 0;
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;
}
// As of writing, Windows does not have a |PF_*| value for ARMv8.2 SHA-512
// extensions. When it does, add it here.
}
int CRYPTO_is_ARMv8_AES_capable(void) {
return (OPENSSL_armcap_P & ARMV8_AES) != 0;
}
int CRYPTO_is_ARMv8_PMULL_capable(void) {
return (OPENSSL_armcap_P & ARMV8_PMULL) != 0;
}
#endif /* (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) &&
!defined(OPENSSL_STATIC_ARMCAP) */
#endif // OPENSSL_AARCH64 && OPENSSL_WINDOWS && !OPENSSL_STATIC_ARMCAP
Loaded 100 of 803 files, more files were not shown because too many files have changed in this diff. Show more