Compare commits

...
82 Commits
Author SHA1 Message Date
Kyle 06dc63c6d8 Fix WASI platform build issue (#291) 2024-10-30 13:36:45 +00:00
Paul ToffoloniandCory Benfield 62958ed575 Fix Windows CI (#289)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-10-29 14:29:05 +00:00
Franz Busch e9d46e7bf9 [CI] Enable Windows CI (#288) 2024-10-29 13:57:41 +00:00
finagolfin 8fa345c208 Add support for new Android overlay, swiftlang/swift#74758 (#286) 2024-10-21 15:30:06 +00:00
Adam Kopeć 7cb61135cb New API Proposal: Password based KDF (#98)
Motivation:

I've added a proposed implementation of PBKDF2, as per proposal in issue #59 to allow easy creation of SymmetricKey from relatively low entropy data sets, such as user provided passwords.

Importance:

This API change is attempting to simplify the creation of SymmetricKeys from user entered passwords.
It uses an ageing algorithm – PBKDF2, but it is still widely supported and popular. A newer algorithm – scrypt is added as a better, more secure alternative.

Modifications:

I've proposed a new API:  KDF namespace with Scrypt struct and an Insecure namespace with PBKDF2 struct with associated hash function and a single static method which takes a passphrase and salt, the size of the resulting key in bytes and optionally the number of rounds to use in the PBKDF2 algorithm.
In the case of scrypt algorithm there is no associated hash function due to the nature of the algorithm, the single static method takes passphrase and salt, the size of the resulting key in bytes and optionally: the number of rounds, block size and parallelism factor.
I implemented this functions using both CommonCrypto and BoringSSL where available.
The function names and parameters are heavily influenced by current HKDF implementation.

Additionally, I've added test cases to test the proposed API. I've decided to use test vectors described in RFC6070 for PBKDF2 and test vectors described in RFC7914 for scrypt.

Result:

This will add a new API to _CryptoKitExtras.
It follows the naming conventions from CryptoKit's HKDF implementation.
2024-10-18 17:16:05 +00:00
Cory Benfield 4518e5e680 Fix windows build and update BoringSSL to 2587c4974dbe9872451151c8e975f58567a1ce0d (#279)
* Update vendoring script

* Update BoringSSL to 2587c4974dbe9872451151c8e975f58567a1ce0d
2024-10-17 12:26:13 +00:00
Si Beaumont 4324b40570 wrapper: Add modular arithmetic functions to ArbitraryPrecisionInteger (#284) 2024-10-17 12:23:48 +00:00
Si Beaumont f98e46e42a wrapper: Move EC types and random bytes into CryptoBoringWrapper (#277)
* wrapper: Remove _boring suffix from files in CryptoBoringWrapper

* wrapper: Move EC types and random bytes into CryptoBoringWrapper

* tests: Remove unused conditional compilation conditions in wrapper tests
2024-10-17 10:03:07 +01:00
Franz Busch ae321d29be [CI] Adopt GitHub actions (#280) 2024-10-16 18:04:07 +01:00
Si Beaumont 21f7878f2b Refactor and adopt package access to remove symlinked files (#265) 2024-10-08 14:10:48 +01:00
Cory Benfield 735a29ccf7 Update BoringSSL to 76968bb3d53982560bcf08bcd0ba3e1865fe15cd (#271)
Also fixes the build issues on Windows, resolves #262
2024-10-07 10:19:12 +01:00
Gautier Delorme b639b5bd1f Support loading RSAPSS public keys with parameters (#268)
* Support loading RSAPSS public keys with parameters

Parameters are stripped and the key is treated as a regular public key.

* address review + reset algorithm as well

* run update_cmakelists.sh

* attempt to fix the cmake build

* include FetchContent

* early return for non-PSS keys

* simplify code
2024-10-03 18:33:02 +01:00
Si Beaumont ffca28be3c crypto: Equatable and Hashable conformance for CryptoKitError and CryptoKitASN1Error (#266) 2024-10-02 09:59:06 +01:00
Si Beaumont 35703579f6 Drop support for Swift 5.8 (#259) 2024-09-19 13:55:18 +01:00
George Barnett a24950b8aa Only include privacy manifest on Darwin (#257)
Motivation:

The privacy manifest is only required on Darwin. It's currently included
on all platforms which results in build warnings.

Modifications:

- Only include manifest on Darwin
- Exclude the privacy manifest from the build on other platforms

Result:

- Fewer warnings
- Resolves #256
2024-09-18 17:21:21 +01:00
Paul Toffoloni e8f2ddd49e extras: Add API to create RSA keys with random primes (#250)
This adds a _createFromNumbers API which creates an RSA key generating p and q primes based on n, e and d

Motivation:

There might be cases where private RSA keys have to be generated based on their raw elements (modulus n, exponent e and private exponent d) without p and q. These are random primes which are integral parts of the key but can be generated based on the former numbers, and are not always included when representing RSA keys, for example these parameters are not required in JWKs

Modifications:

This adds a static _createFromNumbers method which creates a new RSA key given its raw modulus, exponent and private exponent, generating the needed p and q primes without having to provide them as parameters. The algorithm to generate primes is based on a hybrid approach of the Miller Rabin primality test and the proof of Fact 1 in Dan Boneh's Twenty Years of Attacks on the RSA Cryptosystem paper. To write this algorithm, some additions had to be made to the ArbitraryPrecisionInteger

Result:

Private RSA keys can now be generated without providing p and q
2024-09-16 13:52:23 +01:00
Paul ToffoloniandCory Benfield 55201a8f83 extras: Add RSA primitives decoding API (#249)
Motivation:

At times we might need to get the raw elements of an RSA key, e.g when debugging.

Modifications:

Add a getKeyPrimitives method to the RSA (public and private) key structures that returns the elements.
To do this we leverage the built in BoringSSL methods (CCryptoBoringSSL_RSA_get0_n etc.) which return the raw elements of the key. In the Security version of the key we convert the key to a BoringSSL one and just call the BoringSSL method.

Once we get ASN.1 support in _CryptoExtras it might make sense switching the implementation of this method to decode the ASN.1 structure and returns the elements from there.

Result:

New APIs to fetch the key primitives.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-09-16 04:34:21 -07:00
Cory Benfield 81bee98e70 Update BoringSSL to 6a2ccdcc2ed1d37a43a2183658d2ae61fd5ce208 (#255) 2024-09-16 10:02:51 +01:00
Franz Busch ce204da6f6 Add release.yml (#253) 2024-09-06 13:57:39 +01:00
Si Beaumont 9f95b4d033 Add support for AES CFB mode in _CryptoExtras (#252) 2024-09-03 09:28:28 +01:00
Jake Petroules a53a7e8f85 Convert PrivacyInfo.xcprivacy symlinks to files (#251)
It is expected behavior of the swift-build build system to copy links as-is, so presenting these as symlinks results in broken symlinks being present in the produced resource bundles, which won't work properly.

On Windows, it even causes the build entirely to fail due to a related bug: https://github.com/apple/swift-foundation/issues/845

Convert these to flat files instead.
2024-08-13 07:53:29 +01:00
Si BeaumontandCory Benfield 8dafe0fdce extras: Provide initializers for RSA keys from RSA numbers as bytes (#247)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-07-22 04:01:44 -07:00
Nicolas BachschmidtandCory Benfield e2dd5a547b Reduce the number of heap allocations when computing hash digests (#238)
* Remove array allocation when computing digest

Instead of creating a temporary array, the digest bytes are stored in a temporary stack-allocated buffer.

This reduces the number of heap allocations needed to hash a message from 7 to 6.

* Store digest context inline

This reduces the number of heap allocations needed to hash a message from 6 to 2.

Before:
  1. the DigestContext object is created
  2. the EVP_MD_CTX struct is allocated by EVP_MD_CTX_new
  3. md_data is allocated when initializing the context

After:
  1. the DigestContext object is created

In both cases, the number is doubled because COW happens during finalize().

* Use temporary variable to finalize context

This reduces the number of heap allocations needed to hash a message from 2 to 1.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-07-18 08:34:52 -07:00
Si Beaumont 46072478ca build: Revert to using @_implementationOnly for all BoringSSL modules (#246) 2024-07-03 14:37:23 +01:00
Si BeaumontandCory Benfield c370ad81a1 symbols (#245)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-07-02 11:10:27 -07:00
Si Beaumont 33f65a3cbc Change inclusiveMin param of ArbitraryPrecisionInteger.random from UInt64 to UInt (#242) 2024-06-27 15:01:40 +01:00
Si Beaumont fdfdc11707 extras: Add APIs for RSA Blind Signatures (#232)
* API for RSA blind signing and verification from RFC 9474

* Add blind signing backend for Security framework

* Hide PSSZERO variants from public API for now

* Update CMakeLists.txt

* Verify signature produced within SecurityRSAPrivateKey.blindSignature(_:)

* Update API: bake params  into key, use wrappers for intermidiate values

* Throw specific error when message too large for key modulus

* Drop Security framework backend and support all variants

* Factor out withNewBignumContext helper

* Align parameter names and labels in internal functions with public API

* Fix typo in doc comments: public -> private

* Implement client operations for RSA Blind Signatures

* Remove the BlindedMessage type

* Move prepare function to public key method

* Throw (internal) errors defined in the RFC

* Fix test function names for Linux test discovery

* Factor saltLength into a computed property on Parameters

* Improve allocations for temporary bytes

* Fixup documentation typos

* Parameters are Sendable, regardless of H type parameter

* PublicKey and PrivateKey are also Sendable, regardless of H

* Wrap internal errors in most appropriate CryptoKitError

* Factor code differently

* Tweak API to return BlindingResult nominal type instead of tuple

* Prefer withUnsafeTemporaryAllocation(of:capacity:_:) to Array.init(unsafeUnitializedCapacity:_:)

* Move unsafe temporary allocations into BlindSigningHelpers methods

* Replace hand-rolled BN ops with ArbitraryPrecisionInteger and FFAC

* Fixup placement of paren in guards with closures

* Replace closure invocation let binding with looped var

* Use ERR_peek_last_error, not ERR_get_error
2024-06-26 13:20:43 +01:00
Si BeaumontandCory Benfield a3866d45d9 Move ArbitraryPrecisionInteger type to CryptoBoringWrapper module (#236)
* Move ArbitraryPrecisionInteger_boring.swift to CryptoBoringWrapper

* Remove conditional compilation guards for ArbitraryPrecisionInteger

* Throw CryptoBoringWrapperError.internalBoringSSLError instead of CryptoKitError.internalBoringSSLError

* Make most operations public and add raw pointer APIs

* Move ArbitraryPrecisionIntegerTests to new CryptoBoringWrapperTests target

* rename some files

* Remove @_implementationOnly from imports and raw pointer APIs

* Also move over FiniteFieldArithmeticContext to CryptoBoringWrapper

* Add FiniteFieldArithmeticContext.inverse

* Remove conditional compilation guards for FFAC

* Update CMakeLists.txt for moved files

* Revert "Add FiniteFieldArithmeticContext.inverse"

This reverts commit e02700e07c.

* Fix CMakeLists.txt

* Make most public symbols @inlinable

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-06-21 16:35:50 +01:00
Neil Jones 5fb3819b51 add support for riscv64 (#240) 2024-06-17 12:34:29 -07:00
Rick Newton-Rogers 3c060cc4af update README recommended versions (#233) 2024-05-23 03:57:01 -07:00
Si Beaumont c36d19a064 Fix broken DataProtocol.hexString test utility (#230) 2024-05-21 11:09:20 +01:00
Si Beaumont bc1c29221f Use BoringSSL implementation for AES_CTR (#229) 2024-05-07 16:10:20 +01:00
Cory Benfield 2adec617e6 Add empty privacy manifest files (#226)
BoringSSL distributions need to be covered by privacy manifest files,
so we add one here.
2024-03-26 13:25:06 +00:00
Paul ToffoloniandCory Benfield 89876ab72c Update lower bound for RSA key sizes (#218)
* Update lower bound for RSA key sizes

* Add unsafe initialiser for smaller keys

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-03-25 12:42:29 +00:00
Cory Benfield f0525da24d Update BoringSSL to dbad745811195c00b729efd0ee0a09b7d9fce1d2 (#222)
* Update vendoring script for changed layout

* Update BoringSSL to dbad745811195c00b729efd0ee0a09b7d9fce1d2
2024-03-12 10:50:25 +00:00
George Barnett 52d0d9f15a Raise minimum Swift version to 5.7 (#221) 2024-03-12 10:40:24 +00:00
Cory Benfield 9960a73340 Add support for AES CTR mode in _CryptoExtras (#220) 2024-03-08 09:47:06 +00:00
David Benjamin 606608da08 Remove dtls1.h as part of removing libssl (#217)
It's just an empty compatibility header at this point, but as nominally
a part of libssl, remove it with the rest.
2024-01-26 08:17:28 +00:00
coldjugular 029eeacda4 Update macOS development instructions (#216)
Update the macOS local development instructions to correspond to the change made in commit 17d95a6782.
2024-01-24 01:51:38 -08:00
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
825 changed files with 224506 additions and 137715 deletions

No files matched your search

+1 -1
View File
@@ -9,7 +9,7 @@ about: If something isn't working as expected
### New Issue Checklist
- [ ] I'm using the latest version of Swift Crypto (`main` branch)
- [ ] I read the [Contribution Guidelines](https://github.com/apple/swift-crypto/blob/master/CONTRIBUTING.md)
- [ ] I read the [Contribution Guidelines](https://github.com/apple/swift-crypto/blob/main/CONTRIBUTING.md)
- [ ] I searched for [existing GitHub issues](https://github.com/apple/swift-crypto/issues)
### Expected behavior
+2 -2
View File
@@ -6,8 +6,8 @@ about: Not sure how something works or how to implement some functionality? Ask
### Question Checklist
- [ ] I'm using the latest version of Swift Crypto (master branch)
- [ ] I read the [Contribution Guidelines](https://github.com/apple/swift-crypto/blob/master/CONTRIBUTING.md)
- [ ] I'm using the latest version of Swift Crypto (main branch)
- [ ] I read the [Contribution Guidelines](https://github.com/apple/swift-crypto/blob/main/CONTRIBUTING.md)
- [ ] I searched for [existing GitHub issues](https://github.com/apple/swift-crypto/issues)
### Question Subject
+2 -2
View File
@@ -8,8 +8,8 @@ about: If a recent release broke a feature (Please make sure you know the last k
### New Regression Checklist
- [ ] I'm using the latest version of Swift Crypto (master branch)
- [ ] I read the [Contribution Guidelines](https://github.com/apple/swift-crypto/blob/master/CONTRIBUTING.md)
- [ ] I'm using the latest version of Swift Crypto (main branch)
- [ ] I read the [Contribution Guidelines](https://github.com/apple/swift-crypto/blob/main/CONTRIBUTING.md)
- [ ] I searched for [existing GitHub issues](https://github.com/apple/swift-crypto/issues)
### Regression Information
+14
View File
@@ -0,0 +1,14 @@
changelog:
categories:
- title: SemVer Major
labels:
- ⚠️ semver/major
- title: SemVer Minor
labels:
- semver/minor
- title: SemVer Patch
labels:
- semver/patch
- title: Other Changes
labels:
- semver/none
+22
View File
@@ -0,0 +1,22 @@
name: Main
on:
push:
branches: [main]
schedule:
- cron: "0 8,20 * * *"
jobs:
unit-tests:
name: Unit tests
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
with:
linux_5_9_arguments_override: "--explicit-target-dependency-import-check error"
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_0_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_6_0_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
cxx-interop:
name: Cxx interop
uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main
+40
View File
@@ -0,0 +1,40 @@
name: PR
on:
pull_request:
types: [opened, reopened, synchronize]
jobs:
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
with:
license_header_check_project_name: "SwiftCrypto"
format_check_enabled: false
cmake-lists:
name: Check cmake lists
uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main
with:
name: "Check cmake lists"
matrix_linux_command: ./scripts/check-cmake-lists.sh
unit-tests:
name: Unit tests
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
with:
linux_5_9_arguments_override: "--explicit-target-dependency-import-check error"
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_0_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_6_0_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_0_enabled: true
windows_nightly_6_0_enabled: true
windows_nightly_main_enabled: true
windows_6_0_arguments_override: "--explicit-target-dependency-import-check error"
windows_nightly_6_0_arguments_override: "--explicit-target-dependency-import-check error"
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
cxx-interop:
name: Cxx interop
uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main
+18
View File
@@ -0,0 +1,18 @@
name: PR label
on:
pull_request:
types: [labeled, unlabeled, opened, reopened, synchronize]
jobs:
semver-label-check:
name: Semantic Version label check
runs-on: ubuntu-latest
timeout-minutes: 1
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
persist-credentials: false
- name: Check for Semantic Version label
uses: apple/swift-nio/.github/actions/pull_request_semver_label_checker@main
+1
View File
@@ -15,3 +15,4 @@ DerivedData
.*.sw[nop]
.vscode
+48
View File
@@ -0,0 +1,48 @@
.gitignore
**/.gitignore
.licenseignore
.unacceptablelanguageignore
.gitattributes
.git-blame-ignore-revs
.mailfilter
.mailmap
.spi.yml
.swift-format
.editorconfig
.github/*
*.md
*.txt
*.yml
*.yaml
*.json
Package.swift
**/Package.swift
Package@-*.swift
**/Package@-*.swift
Package.resolved
**/Package.resolved
Makefile
*.modulemap
**/*.modulemap
**/*.docc/*
*.xcprivacy
**/*.xcprivacy
*.symlink
**/*.symlink
Dockerfile
**/Dockerfile
Snippets/*
dev/git.commit.template
dev/update-benchmark-thresholds
*.crt
**/*.crt
*.pem
**/*.pem
*.der
**/*.der
.swiftformat
Sources/CCryptoBoringSSL/*
**/*.swift.gyb
scripts/*.patch
scripts/gyb
scripts/gyb.py
+1
View File
@@ -0,0 +1 @@
Sources/CCryptoBoringSSL/*
-5
View File
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array/>
</plist>
+15 -1
View File
@@ -6,7 +6,7 @@
## Licensed under Apache License v2.0
##
## See LICENSE.txt for license information
## See CONTRIBUTORS.md for the list of SwiftCrypto project authors
## See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
##
## SPDX-License-Identifier: Apache-2.0
##
@@ -31,6 +31,10 @@ endif()
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift)
set(SWIFT_CRYPTO_COMPILE_OPTIONS
-package-name com.apple.swift-crypto
)
option(BUILD_SHARED_LIBS "Build shared libraries by default" YES)
if(BUILD_SHARED_LIBS)
@@ -48,5 +52,15 @@ if(NOT CMAKE_SYSTEM_NAME STREQUAL Darwin)
find_package(Foundation CONFIG)
endif()
include(FetchContent)
find_package(SwiftASN1 CONFIG)
if(NOT SwiftASN1_FOUND)
message("-- Vending swift-asn1")
FetchContent_Declare(ASN1
GIT_REPOSITORY https://github.com/apple/swift-asn1
GIT_TAG 1.1.0)
FetchContent_MakeAvailable(ASN1)
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.
File renamed without changes.
+1 -1
View File
@@ -28,7 +28,7 @@ components that this product depends on.
This product contains test vectors from Google's wycheproof project.
* LICENSE (Apache License 2.0):
* https://github.com/google/wycheproof/blob/master/LICENSE
* https://github.com/C2SP/wycheproof/blob/31387e2cd596587c859c611027b6a44d2e2b65ff/LICENSE
* HOMEPAGE:
* https://github.com/google/wycheproof
+52 -23
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.5
// swift-tools-version:5.9
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
@@ -7,7 +7,7 @@
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
@@ -20,7 +20,7 @@
// Sources/CCryptoBoringSSL directory. The source repository is at
// https://boringssl.googlesource.com/boringssl.
//
// BoringSSL Commit: 45b8d7bbd771cbf7e116db2ba1f1cc7af959497e
// BoringSSL Commit: 2587c4974dbe9872451151c8e975f58567a1ce0d
import PackageDescription
@@ -40,15 +40,16 @@ if development {
"CryptoBoringWrapper"
]
} else {
swiftSettings = [
.define("CRYPTO_IN_SWIFTPM"),
]
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)),
@@ -56,6 +57,18 @@ if development {
]
}
// This doesn't work when cross-compiling: the privacy manifest will be included in the Bundle and
// Foundation will be linked. This is, however, strictly better than unconditionally adding the
// resource.
#if canImport(Darwin)
let privacyManifestExclude: [String] = []
let privacyManifestResource: [PackageDescription.Resource] = [.copy("PrivacyInfo.xcprivacy")]
#else
// Exclude on other platforms to avoid build warnings.
let privacyManifestExclude: [String] = ["PrivacyInfo.xcprivacy"]
let privacyManifestResource: [PackageDescription.Resource] = []
#endif
let package = Package(
name: "swift-crypto",
platforms: [
@@ -71,11 +84,13 @@ let package = Package(
.library(name: "CCryptoBoringSSL", type: .static, targets: ["CCryptoBoringSSL"]),
MANGLE_END */
],
dependencies: [],
dependencies: [
.package(url: "https://github.com/apple/swift-asn1.git", from: "1.2.0")
],
targets: [
.target(
name: "CCryptoBoringSSL",
exclude: [
exclude: privacyManifestExclude + [
"hash.txt",
"include/boringssl_prefix_symbols_nasm.inc",
"CMakeLists.txt",
@@ -87,13 +102,13 @@ let package = Package(
"crypto/bio/socket_helper.c",
"crypto/bio/socket.c"
],
resources: privacyManifestResource,
cSettings: [
/*
* This define is required on Windows, but because we need older
* versions of SPM, we cannot conditionally define this on Windows
* only. Unconditionally define it instead.
*/
.define("WIN32_LEAN_AND_MEAN"),
// 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.
*/
@@ -104,20 +119,22 @@ let package = Package(
.target(
name: "CCryptoBoringSSLShims",
dependencies: ["CCryptoBoringSSL"],
exclude: [
exclude: privacyManifestExclude + [
"CMakeLists.txt"
]
],
resources: privacyManifestResource
),
.target(
name: "Crypto",
dependencies: dependencies,
exclude: [
exclude: privacyManifestExclude + [
"CMakeLists.txt",
"AEADs/Nonces.swift.gyb",
"Digests/Digests.swift.gyb",
"Key Agreement/ECDH.swift.gyb",
"Signatures/ECDSA.swift.gyb",
],
resources: privacyManifestResource,
swiftSettings: swiftSettings
),
.target(
@@ -126,11 +143,14 @@ let package = Package(
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
"CryptoBoringWrapper",
"Crypto"
"Crypto",
.product(name: "SwiftASN1", package: "swift-asn1")
],
exclude: [
exclude: privacyManifestExclude + [
"CMakeLists.txt",
]
],
resources: privacyManifestResource,
swiftSettings: swiftSettings
),
.target(
name: "CryptoBoringWrapper",
@@ -138,13 +158,22 @@ let package = Package(
"CCryptoBoringSSL",
"CCryptoBoringSSLShims"
],
exclude: [
exclude: privacyManifestExclude + [
"CMakeLists.txt",
]
],
resources: privacyManifestResource
),
.executableTarget(name: "crypto-shasum", dependencies: ["Crypto"]),
.testTarget(name: "CryptoTests", dependencies: ["Crypto"], swiftSettings: swiftSettings),
.testTarget(
name: "CryptoTests",
dependencies: ["Crypto"],
resources: [
.copy("HPKE/hpke-test-vectors.json"),
],
swiftSettings: swiftSettings
),
.testTarget(name: "_CryptoExtrasTests", dependencies: ["_CryptoExtras"]),
.testTarget(name: "CryptoBoringWrapperTests", dependencies: ["CryptoBoringWrapper"]),
],
cxxLanguageStandard: .cxx11
)
+10 -6
View File
@@ -7,9 +7,9 @@ Swift Crypto is an open-source implementation of a substantial portion of the AP
Swift Crypto is available as a Swift Package Manager package. To use it, add the following dependency in your `Package.swift`:
```swift
// swift-crypto 1.x 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"),
// swift-crypto 1.x, 2.x and 3.x are almost API compatible, so most clients
// should allow any of them
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "4.0.0"),
```
and to your target, add `Crypto` to your dependencies. You can then `import Crypto` to get access to Swift Crypto's functionality.
@@ -108,13 +108,17 @@ If you believe you have identified a vulnerability in Swift Crypto, please [repo
### Swift versions
The most recent versions of Swift Crypto support Swift 5.5 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
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 ...` | 5.5
`2.2.0 ..< 2.4.2` | 5.5
`2.4.2 ..< 3.1.0` | 5.6
`3.1.0 ..< 3.3.0` | 5.7
`3.3.0 ..< 3.8.0` | 5.8
`3.8.0 ...` | 5.9
### Compatibility
@@ -134,5 +138,5 @@ To do so, please use the following dependency in your `Package.swift`:
### 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.
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`, change `let development = false` to `let development = true`, as this will force Swift Crypto to build its public API.
+126 -179
View File
@@ -6,7 +6,7 @@
## Licensed under Apache License v2.0
##
## See LICENSE.txt for license information
## See CONTRIBUTORS.md for the list of SwiftCrypto project authors
## See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
##
## SPDX-License-Identifier: Apache-2.0
##
@@ -44,6 +44,7 @@ add_library(CCryptoBoringSSL STATIC
"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"
@@ -74,22 +75,23 @@ add_library(CCryptoBoringSSL STATIC
"crypto/cipher_extra/tls_cbc.c"
"crypto/conf/conf.c"
"crypto/cpu_aarch64_apple.c"
"crypto/cpu_aarch64_freebsd.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.c"
"crypto/cpu_arm_freebsd.c"
"crypto/cpu_arm_linux.c"
"crypto/cpu_intel.c"
"crypto/cpu_ppc64le.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/dilithium/dilithium.c"
"crypto/dsa/dsa.c"
"crypto/dsa/dsa_asn1.c"
"crypto/ec_extra/ec_asn1.c"
@@ -99,10 +101,11 @@ add_library(CCryptoBoringSSL STATIC
"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_dh.c"
"crypto/evp/p_dh_asn1.c"
"crypto/evp/p_dsa_asn1.c"
"crypto/evp/p_ec.c"
"crypto/evp/p_ec_asn1.c"
@@ -118,88 +121,17 @@ add_library(CCryptoBoringSSL STATIC
"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/bcm.c"
"crypto/fipsmodule/fips_shared_support.c"
"crypto/fipsmodule/hmac/hmac.c"
"crypto/fipsmodule/md4/md4.c"
"crypto/fipsmodule/md5/md5.c"
"crypto/fipsmodule/modes/cbc.c"
"crypto/fipsmodule/modes/cfb.c"
"crypto/fipsmodule/modes/ctr.c"
"crypto/fipsmodule/modes/gcm.c"
"crypto/fipsmodule/modes/gcm_nohw.c"
"crypto/fipsmodule/modes/ofb.c"
"crypto/fipsmodule/modes/polyval.c"
"crypto/fipsmodule/rand/ctrdrbg.c"
"crypto/fipsmodule/rand/fork_detect.c"
"crypto/fipsmodule/rand/rand.c"
"crypto/fipsmodule/rand/urandom.c"
"crypto/fipsmodule/rsa/blinding.c"
"crypto/fipsmodule/rsa/padding.c"
"crypto/fipsmodule/rsa/rsa.c"
"crypto/fipsmodule/rsa/rsa_impl.c"
"crypto/fipsmodule/self_check/fips.c"
"crypto/fipsmodule/self_check/self_check.c"
"crypto/fipsmodule/service_indicator/service_indicator.c"
"crypto/fipsmodule/sha/sha1-altivec.c"
"crypto/fipsmodule/sha/sha1.c"
"crypto/fipsmodule/sha/sha256.c"
"crypto/fipsmodule/sha/sha512.c"
"crypto/fipsmodule/tls/kdf.c"
"crypto/hkdf/hkdf.c"
"crypto/hpke/hpke.c"
"crypto/hrss/hrss.c"
"crypto/keccak/keccak.c"
"crypto/kyber/kyber.c"
"crypto/lhash/lhash.c"
"crypto/md4/md4.c"
"crypto/md5/md5.c"
"crypto/mem.c"
"crypto/mldsa/mldsa.c"
"crypto/obj/obj.c"
"crypto/obj/obj_xref.c"
"crypto/pem/pem_all.c"
@@ -220,17 +152,37 @@ add_library(CCryptoBoringSSL STATIC
"crypto/poly1305/poly1305_vec.c"
"crypto/pool/pool.c"
"crypto/rand_extra/deterministic.c"
"crypto/rand_extra/fork_detect.c"
"crypto/rand_extra/forkunsafe.c"
"crypto/rand_extra/fuchsia.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/urandom.c"
"crypto/rand_extra/windows.c"
"crypto/rc4/rc4.c"
"crypto/refcount_c11.c"
"crypto/refcount_lock.c"
"crypto/refcount.c"
"crypto/rsa_extra/rsa_asn1.c"
"crypto/rsa_extra/rsa_crypt.c"
"crypto/rsa_extra/rsa_extra.c"
"crypto/rsa_extra/rsa_print.c"
"crypto/sha/sha1.c"
"crypto/sha/sha256.c"
"crypto/sha/sha512.c"
"crypto/siphash/siphash.c"
"crypto/slhdsa/fors.c"
"crypto/slhdsa/merkle.c"
"crypto/slhdsa/slhdsa.c"
"crypto/slhdsa/thash.c"
"crypto/slhdsa/wots.c"
"crypto/spx/spx.c"
"crypto/spx/spx_address.c"
"crypto/spx/spx_fors.c"
"crypto/spx/spx_merkle.c"
"crypto/spx/spx_thash.c"
"crypto/spx/spx_util.c"
"crypto/spx/spx_wots.c"
"crypto/stack/stack.c"
"crypto/thread.c"
"crypto/thread_none.c"
@@ -248,11 +200,35 @@ add_library(CCryptoBoringSSL STATIC
"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"
@@ -277,9 +253,7 @@ add_library(CCryptoBoringSSL STATIC
"crypto/x509/x_attrib.c"
"crypto/x509/x_crl.c"
"crypto/x509/x_exten.c"
"crypto/x509/x_info.c"
"crypto/x509/x_name.c"
"crypto/x509/x_pkey.c"
"crypto/x509/x_pubkey.c"
"crypto/x509/x_req.c"
"crypto/x509/x_sig.c"
@@ -287,107 +261,80 @@ add_library(CCryptoBoringSSL STATIC
"crypto/x509/x_val.c"
"crypto/x509/x_x509.c"
"crypto/x509/x_x509a.c"
"crypto/x509v3/pcy_cache.c"
"crypto/x509v3/pcy_data.c"
"crypto/x509v3/pcy_map.c"
"crypto/x509v3/pcy_node.c"
"crypto/x509v3/pcy_tree.c"
"crypto/x509v3/v3_akey.c"
"crypto/x509v3/v3_akeya.c"
"crypto/x509v3/v3_alt.c"
"crypto/x509v3/v3_bcons.c"
"crypto/x509v3/v3_bitst.c"
"crypto/x509v3/v3_conf.c"
"crypto/x509v3/v3_cpols.c"
"crypto/x509v3/v3_crld.c"
"crypto/x509v3/v3_enum.c"
"crypto/x509v3/v3_extku.c"
"crypto/x509v3/v3_genn.c"
"crypto/x509v3/v3_ia5.c"
"crypto/x509v3/v3_info.c"
"crypto/x509v3/v3_int.c"
"crypto/x509v3/v3_lib.c"
"crypto/x509v3/v3_ncons.c"
"crypto/x509v3/v3_ocsp.c"
"crypto/x509v3/v3_pci.c"
"crypto/x509v3/v3_pcia.c"
"crypto/x509v3/v3_pcons.c"
"crypto/x509v3/v3_pmaps.c"
"crypto/x509v3/v3_prn.c"
"crypto/x509v3/v3_purp.c"
"crypto/x509v3/v3_skey.c"
"crypto/x509v3/v3_utl.c")
"gen/crypto/err_data.c")
if(CMAKE_SYSTEM_NAME STREQUAL Darwin AND CMAKE_SYSTEM_PROCESSOR MATCHES "amd64|x86_64")
target_sources(CCryptoBoringSSL PRIVATE
crypto/chacha/chacha-x86_64.mac.x86_64.S
crypto/cipher_extra/aes128gcmsiv-x86_64.mac.x86_64.S
crypto/cipher_extra/chacha20_poly1305_x86_64.mac.x86_64.S
crypto/fipsmodule/aesni-gcm-x86_64.mac.x86_64.S
crypto/fipsmodule/aesni-x86_64.mac.x86_64.S
crypto/fipsmodule/ghash-ssse3-x86_64.mac.x86_64.S
crypto/fipsmodule/ghash-x86_64.mac.x86_64.S
crypto/fipsmodule/md5-x86_64.mac.x86_64.S
crypto/fipsmodule/p256-x86_64-asm.mac.x86_64.S
crypto/fipsmodule/p256_beeu-x86_64-asm.mac.x86_64.S
crypto/fipsmodule/rdrand-x86_64.mac.x86_64.S
crypto/fipsmodule/rsaz-avx2.mac.x86_64.S
crypto/fipsmodule/sha1-x86_64.mac.x86_64.S
crypto/fipsmodule/sha256-x86_64.mac.x86_64.S
crypto/fipsmodule/sha512-x86_64.mac.x86_64.S
crypto/fipsmodule/vpaes-x86_64.mac.x86_64.S
crypto/fipsmodule/x86_64-mont.mac.x86_64.S
crypto/fipsmodule/x86_64-mont5.mac.x86_64.S)
gen/bcm/aesni-gcm-x86_64-apple.S
gen/bcm/aesni-x86_64-apple.S
gen/bcm/ghash-ssse3-x86_64-apple.S
gen/bcm/ghash-x86_64-apple.S
gen/bcm/p256-x86_64-asm-apple.S
gen/bcm/p256_beeu-x86_64-asm-apple.S
gen/bcm/rdrand-x86_64-apple.S
gen/bcm/rsaz-avx2-apple.S
gen/bcm/sha1-x86_64-apple.S
gen/bcm/sha256-x86_64-apple.S
gen/bcm/sha512-x86_64-apple.S
gen/bcm/vpaes-x86_64-apple.S
gen/bcm/x86_64-mont-apple.S
gen/bcm/x86_64-mont5-apple.S
gen/crypto/aes128gcmsiv-x86_64-apple.S
gen/crypto/chacha-x86_64-apple.S
gen/crypto/chacha20_poly1305_x86_64-apple.S
gen/crypto/md5-x86_64-apple.S)
elseif(CMAKE_SYSTEM_NAME MATCHES "Linux|Android" AND CMAKE_SYSTEM_PROCESSOR MATCHES "amd64|x86_64")
target_sources(CCryptoBoringSSL PRIVATE
crypto/chacha/chacha-x86_64.linux.x86_64.S
crypto/cipher_extra/aes128gcmsiv-x86_64.linux.x86_64.S
crypto/cipher_extra/chacha20_poly1305_x86_64.linux.x86_64.S
crypto/fipsmodule/aesni-gcm-x86_64.linux.x86_64.S
crypto/fipsmodule/aesni-x86_64.linux.x86_64.S
crypto/fipsmodule/ghash-ssse3-x86_64.linux.x86_64.S
crypto/fipsmodule/ghash-x86_64.linux.x86_64.S
crypto/fipsmodule/md5-x86_64.linux.x86_64.S
crypto/fipsmodule/p256-x86_64-asm.linux.x86_64.S
crypto/fipsmodule/p256_beeu-x86_64-asm.linux.x86_64.S
crypto/fipsmodule/rdrand-x86_64.linux.x86_64.S
crypto/fipsmodule/rsaz-avx2.linux.x86_64.S
crypto/fipsmodule/sha1-x86_64.linux.x86_64.S
crypto/fipsmodule/sha256-x86_64.linux.x86_64.S
crypto/fipsmodule/sha512-x86_64.linux.x86_64.S
crypto/fipsmodule/vpaes-x86_64.linux.x86_64.S
crypto/fipsmodule/x86_64-mont.linux.x86_64.S
crypto/fipsmodule/x86_64-mont5.linux.x86_64.S)
gen/bcm/aesni-gcm-x86_64-linux.S
gen/bcm/aesni-x86_64-linux.S
gen/bcm/ghash-ssse3-x86_64-linux.S
gen/bcm/ghash-x86_64-linux.S
gen/bcm/p256-x86_64-asm-linux.S
gen/bcm/p256_beeu-x86_64-asm-linux.S
gen/bcm/rdrand-x86_64-linux.S
gen/bcm/rsaz-avx2-linux.S
gen/bcm/sha1-x86_64-linux.S
gen/bcm/sha256-x86_64-linux.S
gen/bcm/sha512-x86_64-linux.S
gen/bcm/vpaes-x86_64-linux.S
gen/bcm/x86_64-mont-linux.S
gen/bcm/x86_64-mont5-linux.S
gen/crypto/aes128gcmsiv-x86_64-linux.S
gen/crypto/chacha-x86_64-linux.S
gen/crypto/chacha20_poly1305_x86_64-linux.S
gen/crypto/md5-x86_64-linux.S)
elseif(CMAKE_SYSTEM_NAME STREQUAL Darwin AND CMAKE_SYSTEM_PROCESSOR MATCHES "arm64|aarch64")
target_sources(CCryptoBoringSSL PRIVATE
crypto/chacha/chacha-armv8.ios.aarch64.S
crypto/cipher_extra/chacha20_poly1305_armv8.ios.aarch64.S
crypto/fipsmodule/aesv8-armx64.ios.aarch64.S
crypto/fipsmodule/aesv8-gcm-armv8.ios.aarch64.S
crypto/fipsmodule/armv8-mont.ios.aarch64.S
crypto/fipsmodule/ghash-neon-armv8.ios.aarch64.S
crypto/fipsmodule/ghashv8-armx64.ios.aarch64.S
crypto/fipsmodule/p256-armv8-asm.ios.aarch64.S
crypto/fipsmodule/p256_beeu-armv8-asm.ios.aarch64.S
crypto/fipsmodule/sha1-armv8.ios.aarch64.S
crypto/fipsmodule/sha256-armv8.ios.aarch64.S
crypto/fipsmodule/sha512-armv8.ios.aarch64.S
crypto/fipsmodule/vpaes-armv8.ios.aarch64.S)
gen/bcm/aesv8-armv8-apple.S
gen/bcm/aesv8-gcm-armv8-apple.S
gen/bcm/armv8-mont-apple.S
gen/bcm/bn-armv8-apple.S
gen/bcm/ghash-neon-armv8-apple.S
gen/bcm/ghashv8-armv8-apple.S
gen/bcm/p256-armv8-asm-apple.S
gen/bcm/p256_beeu-armv8-asm-apple.S
gen/bcm/sha1-armv8-apple.S
gen/bcm/sha256-armv8-apple.S
gen/bcm/sha512-armv8-apple.S
gen/bcm/vpaes-armv8-apple.S
gen/crypto/chacha-armv8-apple.S
gen/crypto/chacha20_poly1305_armv8-apple.S)
elseif(CMAKE_SYSTEM_NAME MATCHES "Linux|Android" AND CMAKE_SYSTEM_PROCESSOR MATCHES "arm64|aarch64")
target_sources(CCryptoBoringSSL PRIVATE
crypto/chacha/chacha-armv8.linux.aarch64.S
crypto/cipher_extra/chacha20_poly1305_armv8.linux.aarch64.S
crypto/fipsmodule/aesv8-armx64.linux.aarch64.S
crypto/fipsmodule/aesv8-gcm-armv8.linux.aarch64.S
crypto/fipsmodule/armv8-mont.linux.aarch64.S
crypto/fipsmodule/ghash-neon-armv8.linux.aarch64.S
crypto/fipsmodule/ghashv8-armx64.linux.aarch64.S
crypto/fipsmodule/p256-armv8-asm.linux.aarch64.S
crypto/fipsmodule/p256_beeu-armv8-asm.linux.aarch64.S
crypto/fipsmodule/sha1-armv8.linux.aarch64.S
crypto/fipsmodule/sha256-armv8.linux.aarch64.S
crypto/fipsmodule/sha512-armv8.linux.aarch64.S
crypto/fipsmodule/vpaes-armv8.linux.aarch64.S)
gen/bcm/aesv8-armv8-linux.S
gen/bcm/aesv8-gcm-armv8-linux.S
gen/bcm/armv8-mont-linux.S
gen/bcm/bn-armv8-linux.S
gen/bcm/ghash-neon-armv8-linux.S
gen/bcm/ghashv8-armv8-linux.S
gen/bcm/p256-armv8-asm-linux.S
gen/bcm/p256_beeu-armv8-asm-linux.S
gen/bcm/sha1-armv8-linux.S
gen/bcm/sha256-armv8-linux.S
gen/bcm/sha512-armv8-linux.S
gen/bcm/vpaes-armv8-linux.S
gen/crypto/chacha-armv8-linux.S
gen/crypto/chacha20_poly1305_armv8-linux.S)
endif()
target_include_directories(CCryptoBoringSSL PUBLIC
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyTracking</key>
<false/>
<key>NSPrivacyAccessedAPITypes</key>
<array/>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyTrackingDomains</key>
<array/>
</dict>
</plist>
@@ -184,7 +184,6 @@ ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a,
if (len > 0) {
s = OPENSSL_memdup(p, len);
if (s == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
p += len;
@@ -236,7 +235,6 @@ int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value) {
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) {
+24 -49
View File
@@ -56,65 +56,40 @@
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
int i2d_ASN1_BOOLEAN(ASN1_BOOLEAN 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;
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;
}
if (*pp == NULL) {
if ((p = allocated = OPENSSL_malloc(r)) == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return -1;
}
} else {
p = *pp;
}
ASN1_put_object(&p, 0, 1, V_ASN1_BOOLEAN, V_ASN1_UNIVERSAL);
*p = a ? 0xff : 0x00;
// 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;
return CBB_finish_i2d(&cbb, outp);
}
ASN1_BOOLEAN d2i_ASN1_BOOLEAN(ASN1_BOOLEAN *a, const unsigned char **pp,
long length) {
const unsigned char *p = *pp;
long len;
int inf, tag, xclass;
inf = ASN1_get_object(&p, &len, &tag, &xclass, length);
if (inf & 0x80) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_OBJECT_HEADER);
return -1;
ASN1_BOOLEAN d2i_ASN1_BOOLEAN(ASN1_BOOLEAN *out, const unsigned char **inp,
long len) {
if (len < 0) {
return ASN1_BOOLEAN_NONE;
}
if (inf & V_ASN1_CONSTRUCTED) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_PRIMITIVE);
return -1;
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 || xclass != V_ASN1_UNIVERSAL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_EXPECTING_A_BOOLEAN);
return -1;
ASN1_BOOLEAN ret = val ? ASN1_BOOLEAN_TRUE : ASN1_BOOLEAN_FALSE;
if (out != NULL) {
*out = ret;
}
if (len != 1) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
return -1;
}
ASN1_BOOLEAN ret = (ASN1_BOOLEAN) * (p++);
if (a != NULL) {
(*a) = ret;
}
*pp = p;
*inp = CBS_data(&cbs);
return ret;
}
@@ -75,7 +75,6 @@ void *ASN1_item_dup(const ASN1_ITEM *it, void *x) {
i = ASN1_item_i2d(x, &b, it);
if (b == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return NULL;
}
p = b;
+12 -7
View File
@@ -58,7 +58,9 @@
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_posix_time.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
@@ -98,15 +100,15 @@ int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str) {
}
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,
int64_t posix_time, int offset_day,
long offset_sec) {
struct tm data;
if (!OPENSSL_gmtime(&t, &data)) {
if (!OPENSSL_posix_to_tm(posix_time, &data)) {
return NULL;
}
@@ -122,9 +124,12 @@ ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s,
}
char buf[16];
BIO_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);
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) {
@@ -76,7 +76,6 @@ 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;
}
+14 -12
View File
@@ -122,14 +122,17 @@ int i2c_ASN1_INTEGER(const ASN1_INTEGER *in, unsigned char **outp) {
// |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.
int start = 0;
while (start < in->length && in->data[start] == 0) {
start++;
CBS cbs;
CBS_init(&cbs, in->data, in->length);
while (CBS_len(&cbs) > 0 && CBS_data(&cbs)[0] == 0) {
CBS_skip(&cbs, 1);
}
int is_negative = (in->type & V_ASN1_NEG) != 0;
int pad;
if (start >= in->length) {
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;
@@ -138,20 +141,19 @@ int i2c_ASN1_INTEGER(const ASN1_INTEGER *in, unsigned char **outp) {
// 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 = in->data[start] > 0x80 ||
(in->data[start] == 0x80 &&
!is_all_zeros(in->data + start + 1, in->length - start - 1));
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 = (in->data[start] & 0x80) != 0;
pad = (msb & 0x80) != 0;
}
if (in->length - start > INT_MAX - pad) {
if (CBS_len(&cbs) > INT_MAX - pad) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_OVERFLOW);
return 0;
}
int len = pad + in->length - start;
int len = (int)(pad + CBS_len(&cbs));
assert(len > 0);
if (outp == NULL) {
return len;
@@ -160,7 +162,7 @@ int i2c_ASN1_INTEGER(const ASN1_INTEGER *in, unsigned char **outp) {
if (pad) {
(*outp)[0] = 0;
}
OPENSSL_memcpy(*outp + pad, in->data + start, in->length - start);
OPENSSL_memcpy(*outp + pad, CBS_data(&cbs), CBS_len(&cbs));
if (is_negative) {
negate_twos_complement(*outp, len);
assert((*outp)[0] >= 0x80);
+43 -57
View File
@@ -73,23 +73,19 @@
// 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];
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);
}
@@ -101,22 +97,22 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
int error;
switch (inform) {
case MBSTRING_BMP:
decode_func = cbs_get_ucs2_be;
decode_func = CBS_get_ucs2_be;
error = ASN1_R_INVALID_BMPSTRING;
break;
case MBSTRING_UNIV:
decode_func = cbs_get_utf32_be;
decode_func = CBS_get_utf32_be;
error = ASN1_R_INVALID_UNIVERSALSTRING;
break;
case MBSTRING_UTF8:
decode_func = cbs_get_utf8;
decode_func = CBS_get_utf8;
error = ASN1_R_INVALID_UTF8STRING;
break;
case MBSTRING_ASC:
decode_func = cbs_get_latin1;
decode_func = CBS_get_latin1;
error = ERR_R_INTERNAL_ERROR; // Latin-1 inputs are never invalid.
break;
@@ -128,7 +124,7 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
// Check |minsize| and |maxsize| and work out the minimal type, if any.
CBS cbs;
CBS_init(&cbs, in, len);
size_t utf8_len = 0;
size_t utf8_len = 0, nchar = 0;
while (CBS_len(&cbs) != 0) {
uint32_t c;
if (!decode_func(&cbs, &c)) {
@@ -166,25 +162,23 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
}
nchar++;
utf8_len += cbb_get_utf8_len(c);
utf8_len += CBB_get_utf8_len(c);
if (maxsize > 0 && nchar > (size_t)maxsize) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_STRING_TOO_LONG);
ERR_add_error_dataf("maxsize=%zu", (size_t)maxsize);
return -1;
}
}
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;
}
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);
ERR_add_error_dataf("minsize=%zu", (size_t)minsize);
return -1;
}
// Now work out output format and string type
int (*encode_func)(CBB *, uint32_t) = cbb_add_latin1;
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) {
@@ -196,17 +190,17 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
} else if (mask & B_ASN1_BMPSTRING) {
str_type = V_ASN1_BMPSTRING;
outform = MBSTRING_BMP;
encode_func = cbb_add_ucs2_be;
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;
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;
encode_func = CBB_add_utf8;
size_estimate = utf8_len;
} else {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_CHARACTERS);
@@ -216,37 +210,31 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
if (!out) {
return str_type;
}
int free_dest = 0;
ASN1_STRING *dest;
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;
free_dest = 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;
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)) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
CBS_init(&cbs, in, len);
@@ -267,12 +255,13 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
OPENSSL_free(data);
goto err;
}
dest->length = (int)(data_len - 1);
dest->data = data;
dest->type = str_type;
ASN1_STRING_set0(dest, data, (int)data_len - 1);
*out = dest;
return str_type;
err:
if (free_out) {
if (free_dest) {
ASN1_STRING_free(dest);
}
CBB_cleanup(&cbb);
@@ -283,10 +272,7 @@ int asn1_is_printable(uint32_t value) {
if (value > 0x7f) {
return 0;
}
// Note we cannot use |isalnum| because it is locale-dependent.
return ('a' <= value && value <= 'z') || //
('A' <= value && value <= 'Z') || //
('0' <= value && value <= '9') || //
return OPENSSL_isalnum(value) || //
value == ' ' || value == '\'' || value == '(' || value == ')' ||
value == '+' || value == ',' || value == '-' || value == '.' ||
value == '/' || value == ':' || value == '=' || value == '?';
+49 -108
View File
@@ -59,47 +59,36 @@
#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) {
if (a == NULL) {
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->length == 0) {
if (in->length <= 0) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OBJECT);
return -1;
}
int 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;
}
unsigned char *p, *allocated = NULL;
if (*pp == NULL) {
if ((p = allocated = OPENSSL_malloc(objsize)) == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return -1;
}
} 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) {
@@ -141,106 +130,55 @@ int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a) {
return ret;
}
ASN1_OBJECT *d2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp,
long length) {
long len;
int tag, xclass;
const unsigned char *p = *pp;
int inf = ASN1_get_object(&p, &len, &tag, &xclass, length);
if (inf & 0x80) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_OBJECT_HEADER);
ASN1_OBJECT *d2i_ASN1_OBJECT(ASN1_OBJECT **out, const unsigned char **inp,
long len) {
if (len < 0) {
return NULL;
}
if (inf & V_ASN1_CONSTRUCTED) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_PRIMITIVE);
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;
}
if (tag != V_ASN1_OBJECT || xclass != V_ASN1_UNIVERSAL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_EXPECTING_AN_OBJECT);
return NULL;
}
ASN1_OBJECT *ret = c2i_ASN1_OBJECT(a, &p, len);
if (ret) {
*pp = p;
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 *c2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp,
ASN1_OBJECT *c2i_ASN1_OBJECT(ASN1_OBJECT **out, const unsigned char **inp,
long len) {
ASN1_OBJECT *ret = NULL;
const unsigned char *p;
unsigned char *data;
int i, length;
// 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) {
if (len < 0) {
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;
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;
}
if ((a == NULL) || ((*a) == NULL) ||
!((*a)->flags & ASN1_OBJECT_FLAG_DYNAMIC)) {
if ((ret = ASN1_OBJECT_new()) == NULL) {
return NULL;
}
} else {
ret = (*a);
ASN1_OBJECT *ret = ASN1_OBJECT_create(NID_undef, *inp, (size_t)len,
/*sn=*/NULL, /*ln=*/NULL);
if (ret == NULL) {
return NULL;
}
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;
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;
if (out != NULL) {
ASN1_OBJECT_free(*out);
*out = ret;
}
OPENSSL_memcpy(data, p, length);
// If there are dynamic strings, free them here, and clear the flag
if ((ret->flags & ASN1_OBJECT_FLAG_DYNAMIC_STRINGS) != 0) {
OPENSSL_free((char *)ret->sn);
OPENSSL_free((char *)ret->ln);
ret->flags &= ~ASN1_OBJECT_FLAG_DYNAMIC_STRINGS;
}
// reattach data to object, after which it remains const
ret->data = data;
ret->length = length;
ret->sn = NULL;
ret->ln = NULL;
p += length;
if (a != NULL) {
(*a) = ret;
}
*pp = p;
*inp += len; // All bytes were consumed.
return ret;
err:
OPENSSL_PUT_ERROR(ASN1, i);
if ((ret != NULL) && ((a == NULL) || (*a != ret))) {
ASN1_OBJECT_free(ret);
}
return NULL;
}
ASN1_OBJECT *ASN1_OBJECT_new(void) {
@@ -248,7 +186,6 @@ ASN1_OBJECT *ASN1_OBJECT_new(void) {
ret = (ASN1_OBJECT *)OPENSSL_malloc(sizeof(ASN1_OBJECT));
if (ret == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return NULL;
}
ret->length = 0;
@@ -279,16 +216,20 @@ void ASN1_OBJECT_free(ASN1_OBJECT *a) {
}
}
ASN1_OBJECT *ASN1_OBJECT_create(int nid, const unsigned char *data, int len,
ASN1_OBJECT *ASN1_OBJECT_create(int nid, const unsigned char *data, size_t len,
const char *sn, const char *ln) {
ASN1_OBJECT o;
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 = len;
o.length = (int)len;
o.flags = ASN1_OBJECT_FLAG_DYNAMIC | ASN1_OBJECT_FLAG_DYNAMIC_STRINGS |
ASN1_OBJECT_FLAG_DYNAMIC_DATA;
return (OBJ_dup(&o));
return OBJ_dup(&o);
}
+15 -28
View File
@@ -68,6 +68,7 @@
#include <CCryptoBoringSSL_mem.h>
#include "../bytestring/internal.h"
#include "../internal.h"
#include "internal.h"
@@ -89,18 +90,18 @@ static int do_esc_char(uint32_t c, unsigned long flags, char *do_quotes,
char buf[16]; // Large enough for "\\W01234567".
unsigned char u8 = (unsigned char)c;
if (c > 0xffff) {
BIO_snprintf(buf, sizeof(buf), "\\W%08" PRIX32, c);
snprintf(buf, sizeof(buf), "\\W%08" PRIX32, c);
} else if (c > 0xff) {
BIO_snprintf(buf, sizeof(buf), "\\U%04" PRIX32, c);
snprintf(buf, sizeof(buf), "\\U%04" PRIX32, c);
} else if ((flags & ASN1_STRFLGS_ESC_MSB) && c > 0x7f) {
BIO_snprintf(buf, sizeof(buf), "\\%02X", c);
snprintf(buf, sizeof(buf), "\\%02X", c);
} else if ((flags & ASN1_STRFLGS_ESC_CTRL) && is_control_character(c)) {
BIO_snprintf(buf, sizeof(buf), "\\%02X", 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.
BIO_snprintf(buf, sizeof(buf), "\\%c", (int)c);
snprintf(buf, sizeof(buf), "\\%c", (int)c);
} else if (c == ',' || c == '+' || c == '<' || c == '>' || c == ';' ||
(is_first && (c == ' ' || c == '#')) ||
(is_last && (c == ' '))) {
@@ -111,13 +112,13 @@ static int do_esc_char(uint32_t c, unsigned long flags, char *do_quotes,
}
return maybe_write(out, &u8, 1) ? 1 : -1;
}
BIO_snprintf(buf, sizeof(buf), "\\%c", (int)c);
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.
BIO_snprintf(buf, sizeof(buf), "\\%c", (int)c);
snprintf(buf, sizeof(buf), "\\%c", (int)c);
} else {
return maybe_write(out, &u8, 1) ? 1 : -1;
}
@@ -137,19 +138,19 @@ static int do_buf(const unsigned char *buf, int buflen, int encoding,
int get_char_error;
switch (encoding) {
case MBSTRING_UNIV:
get_char = cbs_get_utf32_be;
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 = CBS_get_ucs2_be;
get_char_error = ASN1_R_INVALID_BMPSTRING;
break;
case MBSTRING_ASC:
get_char = cbs_get_latin1;
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 = CBS_get_utf8;
get_char_error = ASN1_R_INVALID_UTF8STRING;
break;
default:
@@ -172,7 +173,7 @@ static int do_buf(const unsigned char *buf, int buflen, int encoding,
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)) {
if (!CBB_add_utf8(&utf8_cbb, c)) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_INTERNAL_ERROR);
return 1;
}
@@ -238,22 +239,8 @@ static int do_dump(unsigned long flags, BIO *out, const ASN1_STRING *str) {
// Placing the ASN1_STRING in a temporary ASN1_TYPE allows the DER encoding
// to readily obtained.
ASN1_TYPE t;
t.type = str->type;
// Negative INTEGER and ENUMERATED values are the only case where
// |ASN1_STRING| and |ASN1_TYPE| types do not match.
//
// TODO(davidben): There are also some type fields which, in |ASN1_TYPE|, do
// not correspond to |ASN1_STRING|. It is unclear whether those are allowed
// in |ASN1_STRING| at all, or what the space of allowed types is.
// |ASN1_item_ex_d2i| will never produce such a value so, for now, we say
// this is an invalid input. But this corner of the library in general
// should be more robust.
if (t.type == V_ASN1_NEG_INTEGER) {
t.type = V_ASN1_INTEGER;
} else if (t.type == V_ASN1_NEG_ENUMERATED) {
t.type = V_ASN1_ENUMERATED;
}
t.value.asn1_string = (ASN1_STRING *)str;
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) {
@@ -72,7 +72,7 @@
DEFINE_LHASH_OF(ASN1_STRING_TABLE)
static LHASH_OF(ASN1_STRING_TABLE) *string_tables = NULL;
static struct CRYPTO_STATIC_MUTEX string_tables_lock = CRYPTO_STATIC_MUTEX_INIT;
static CRYPTO_MUTEX string_tables_lock = CRYPTO_MUTEX_INIT;
void ASN1_STRING_set_default_mask(unsigned long mask) {}
@@ -87,7 +87,7 @@ static const ASN1_STRING_TABLE *asn1_string_table_get(int nid);
// a corresponding OID. For example certificates and certificate requests.
ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, const unsigned char *in,
int len, int inform, int nid) {
ossl_ssize_t len, int inform, int nid) {
ASN1_STRING *str = NULL;
int ret;
if (!out) {
@@ -176,11 +176,11 @@ static const ASN1_STRING_TABLE *asn1_string_table_get(int nid) {
return tbl;
}
CRYPTO_STATIC_MUTEX_lock_read(&string_tables_lock);
CRYPTO_MUTEX_lock_read(&string_tables_lock);
if (string_tables != NULL) {
tbl = lh_ASN1_STRING_TABLE_retrieve(string_tables, &key);
}
CRYPTO_STATIC_MUTEX_unlock_read(&string_tables_lock);
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.
@@ -196,7 +196,7 @@ int ASN1_STRING_TABLE_add(int nid, long minsize, long maxsize,
}
int ret = 0;
CRYPTO_STATIC_MUTEX_lock_write(&string_tables_lock);
CRYPTO_MUTEX_lock_write(&string_tables_lock);
if (string_tables == NULL) {
string_tables = lh_ASN1_STRING_TABLE_new(table_hash, table_cmp);
@@ -232,7 +232,7 @@ int ASN1_STRING_TABLE_add(int nid, long minsize, long maxsize,
ret = 1;
err:
CRYPTO_STATIC_MUTEX_unlock_write(&string_tables_lock);
CRYPTO_MUTEX_unlock_write(&string_tables_lock);
return ret;
}
+49 -16
View File
@@ -55,12 +55,13 @@
* [including the GNU Public Licence.] */
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_time.h>
#include <CCryptoBoringSSL_posix_time.h>
#include <string.h>
#include <time.h>
#include <CCryptoBoringSSL_asn1t.h>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
@@ -74,29 +75,35 @@ IMPLEMENT_ASN1_MSTRING(ASN1_TIME, B_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;
ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t time) {
return ASN1_TIME_adj(s, time, 0, 0);
}
ts = OPENSSL_gmtime(&t, &data);
if (ts == NULL) {
static int fits_in_utc_time(const struct tm *tm) {
return 50 <= tm->tm_year && tm->tm_year < 150;
}
ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, int64_t posix_time, int offset_day,
long offset_sec) {
struct tm tm;
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(ts, offset_day, offset_sec)) {
if (!OPENSSL_gmtime_adj(&tm, 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);
if (fits_in_utc_time(&tm)) {
return ASN1_UTCTIME_adj(s, posix_time, offset_day, offset_sec);
}
return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
return ASN1_GENERALIZEDTIME_adj(s, posix_time, offset_day, offset_sec);
}
int ASN1_TIME_check(const ASN1_TIME *t) {
@@ -169,12 +176,38 @@ int ASN1_TIME_set_string(ASN1_TIME *s, const char *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;
}
static int asn1_time_to_tm(struct tm *tm, const ASN1_TIME *t,
int allow_timezone_offset) {
if (t == NULL) {
time_t now_t;
time(&now_t);
if (OPENSSL_gmtime(&now_t, tm)) {
if (OPENSSL_posix_to_tm(time(NULL), tm)) {
return 1;
}
return 0;
+68 -16
View File
@@ -56,7 +56,8 @@
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_asn1t.h>
#include <assert.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_obj.h>
@@ -65,31 +66,82 @@
int ASN1_TYPE_get(const ASN1_TYPE *a) {
if (a->type == V_ASN1_BOOLEAN || a->type == V_ASN1_NULL ||
a->value.ptr != NULL) {
return a->type;
switch (a->type) {
case V_ASN1_NULL:
case V_ASN1_BOOLEAN:
return a->type;
case V_ASN1_OBJECT:
return a->value.object != NULL ? a->type : 0;
default:
return a->value.asn1_string != NULL ? a->type : 0;
}
return 0;
}
const void *asn1_type_value_as_pointer(const ASN1_TYPE *a) {
if (a->type == V_ASN1_BOOLEAN) {
return a->value.boolean ? (void *)0xff : NULL;
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;
}
if (a->type == V_ASN1_NULL) {
return NULL;
}
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;
}
return a->value.ptr;
}
void ASN1_TYPE_set(ASN1_TYPE *a, int type, void *value) {
ASN1_TYPE **tmp_a = &a;
ASN1_primitive_free((ASN1_VALUE **)tmp_a, NULL);
asn1_type_cleanup(a);
a->type = type;
if (type == V_ASN1_BOOLEAN) {
a->value.boolean = value ? 0xff : 0;
} else {
a->value.ptr = value;
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;
}
}
+17 -9
View File
@@ -58,7 +58,9 @@
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_posix_time.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
@@ -82,11 +84,14 @@ int ASN1_UTCTIME_check(const ASN1_UTCTIME *d) {
}
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=*/1)) {
/*allow_timezone_offset=*/0)) {
return 0;
}
if (s != NULL) {
@@ -98,14 +103,14 @@ int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str) {
return 1;
}
ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, time_t t) {
return ASN1_UTCTIME_adj(s, t, 0, 0);
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, time_t t, int offset_day,
ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, int64_t posix_time, int offset_day,
long offset_sec) {
struct tm data;
if (!OPENSSL_gmtime(&t, &data)) {
if (!OPENSSL_posix_to_tm(posix_time, &data)) {
return NULL;
}
@@ -120,9 +125,12 @@ ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t, int offset_day,
}
char buf[14];
BIO_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);
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) {
@@ -151,7 +159,7 @@ int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t) {
return -2;
}
if (!OPENSSL_gmtime(&t, &ttm)) {
if (!OPENSSL_posix_to_tm(t, &ttm)) {
return -2;
}
+12 -16
View File
@@ -102,6 +102,15 @@ OPENSSL_DECLARE_ERROR_REASON(ASN1, UNKNOWN_FORMAT)
OPENSSL_DECLARE_ERROR_REASON(ASN1, UNKNOWN_TAG)
OPENSSL_DECLARE_ERROR_REASON(ASN1, UNSUPPORTED_TYPE)
// Limit |ASN1_STRING|s to 64 MiB of data. Most of this module, as well as
// 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 **inp, long *out_len, int *out_tag,
@@ -111,20 +120,10 @@ int ASN1_get_object(const unsigned char **inp, long *out_len, int *out_tag,
return 0x80;
}
// TODO(https://crbug.com/boringssl/354): This should use |CBS_get_asn1| to
// reject non-minimal lengths, which are only allowed in BER. However,
// Android sometimes needs allow a non-minimal length in certificate
// signature fields (see b/18228011). Make this only apply to that field,
// while requiring DER elsewhere. Better yet, it should be limited to an
// preprocessing step in that part of Android.
CBS_ASN1_TAG tag;
size_t header_len;
int indefinite;
CBS cbs, body;
CBS_init(&cbs, *inp, (size_t)in_len);
if (!CBS_get_any_ber_asn1_element(&cbs, &body, &tag, &header_len,
/*out_ber_found=*/NULL, &indefinite) ||
indefinite || !CBS_skip(&body, header_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) {
@@ -283,9 +282,8 @@ int ASN1_STRING_set(ASN1_STRING *str, const void *_data, ossl_ssize_t len_s) {
len = (size_t)len_s;
}
// |ASN1_STRING| cannot represent strings that exceed |int|, and we must
// reserve space for a trailing NUL below.
if (len > INT_MAX || len + 1 < len) {
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;
}
@@ -299,7 +297,6 @@ int ASN1_STRING_set(ASN1_STRING *str, const void *_data, ossl_ssize_t len_s) {
}
if (str->data == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
str->data = c;
return 0;
}
@@ -331,7 +328,6 @@ ASN1_STRING *ASN1_STRING_type_new(int type) {
ret = (ASN1_STRING *)OPENSSL_malloc(sizeof(ASN1_STRING));
if (ret == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return NULL;
}
ret->length = 0;
@@ -72,7 +72,6 @@ ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, ASN1_STRING **out) {
if (out == NULL || *out == NULL) {
ret = ASN1_STRING_new();
if (ret == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
OPENSSL_free(new_data);
return NULL;
}
+57 -29
View File
@@ -56,8 +56,8 @@
*
*/
#ifndef OPENSSL_HEADER_ASN1_ASN1_LOCL_H
#define OPENSSL_HEADER_ASN1_ASN1_LOCL_H
#ifndef OPENSSL_HEADER_ASN1_INTERNAL_H
#define OPENSSL_HEADER_ASN1_INTERNAL_H
#include <time.h>
@@ -76,18 +76,12 @@ extern "C" {
// 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);
int64_t 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
@@ -122,20 +116,16 @@ struct asn1_object_st {
ASN1_OBJECT *ASN1_OBJECT_new(void);
// ASN1_ENCODING structure: this is used to save the received
// encoding of an ASN1 type. This is useful to get round
// problems with invalid encodings which can break signatures.
// 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 {
unsigned char *enc; // DER encoding
long len; // Length of encoding, or zero if not present.
// alias_only is zero if |enc| owns the buffer that it points to
// (although |enc| may still be NULL). If one, |enc| points into a
// buffer that is owned elsewhere.
unsigned alias_only : 1;
// alias_only_on_next_parse is one iff the next parsing operation
// should avoid taking a copy of the input and rather set
// |alias_only|.
unsigned alias_only_on_next_parse : 1;
// 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,
@@ -143,16 +133,22 @@ OPENSSL_EXPORT int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d,
OPENSSL_EXPORT 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 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,
ASN1_TLC *ctx);
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
@@ -194,8 +190,11 @@ void asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
int asn1_enc_restore(int *len, unsigned char **out, ASN1_VALUE **pval,
const ASN1_ITEM *it);
int asn1_enc_save(ASN1_VALUE **pval, const unsigned char *in, int inlen,
const ASN1_ITEM *it);
// asn1_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);
@@ -205,6 +204,14 @@ void asn1_encoding_clear(ASN1_ENCODING *enc);
// 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);
@@ -230,9 +237,30 @@ typedef struct {
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_ASN1_LOCL_H
#endif // OPENSSL_HEADER_ASN1_INTERNAL_H
@@ -15,7 +15,7 @@
// Time conversion to/from POSIX time_t and struct tm, with no support
// for time zones other than UTC
#include <CCryptoBoringSSL_time.h>
#include <CCryptoBoringSSL_posix_time.h>
#include <assert.h>
#include <inttypes.h>
@@ -26,12 +26,12 @@
#include "internal.h"
#define SECS_PER_HOUR (60 * 60)
#define SECS_PER_DAY (24 * SECS_PER_HOUR)
#define SECS_PER_DAY (INT64_C(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) {
static int is_valid_date(int64_t year, int64_t month, int64_t day) {
if (day < 1 || month < 1 || year < 0 || year > 9999) {
return 0;
}
@@ -62,7 +62,7 @@ static int is_valid_date(int year, int month, int day) {
// 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) {
static int is_valid_time(int64_t hours, int64_t minutes, int64_t seconds) {
if (hours < 0 || minutes < 0 || seconds < 0 || hours > 23 || minutes > 59 ||
seconds > 59) {
return 0;
@@ -70,17 +70,22 @@ static int is_valid_time(int hours, int minutes, int seconds) {
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;
// 0000-01-01 00:00:00 UTC
#define MIN_POSIX_TIME INT64_C(-62167219200)
// 9999-12-31 23:59:59 UTC
#define MAX_POSIX_TIME INT64_C(253402300799)
// Is an int64 time within our expected range?
static int is_valid_posix_time(int64_t time) {
return MIN_POSIX_TIME <= time && time <= MAX_POSIX_TIME;
}
// 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) {
static int posix_time_from_utc(int64_t year, int64_t month, int64_t day,
int64_t hours, int64_t minutes, int64_t seconds,
int64_t *out_time) {
if (!is_valid_date(year, month, day) ||
!is_valid_time(hours, minutes, seconds)) {
return 0;
@@ -108,7 +113,7 @@ static int posix_time_from_utc(int year, int month, int day, int hours,
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)) {
if (!is_valid_posix_time(time)) {
return 0;
}
int64_t days = time / SECS_PER_DAY;
@@ -143,19 +148,21 @@ static int utc_from_posix_time(int64_t time, int *out_year, int *out_month,
}
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);
return posix_time_from_utc(tm->tm_year + INT64_C(1900),
tm->tm_mon + INT64_C(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)) {
struct tm tmp_tm = {0};
if (!utc_from_posix_time(time, &tmp_tm.tm_year, &tmp_tm.tm_mon,
&tmp_tm.tm_mday, &tmp_tm.tm_hour, &tmp_tm.tm_min,
&tmp_tm.tm_sec)) {
return 0;
}
out_tm->tm_year -= 1900;
out_tm->tm_mon -= 1;
tmp_tm.tm_year -= 1900;
tmp_tm.tm_mon -= 1;
*out_tm = tmp_tm;
return 1;
}
@@ -187,43 +194,47 @@ struct tm *OPENSSL_gmtime(const time_t *time, struct tm *out_tm) {
return out_tm;
}
int OPENSSL_gmtime_adj(struct tm *tm, int off_day, long offset_sec) {
int OPENSSL_gmtime_adj(struct tm *tm, int offset_day, int64_t 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)) {
if (!OPENSSL_tm_to_posix(tm, &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)) {
static_assert(INT_MAX <= INT64_MAX / SECS_PER_DAY,
"day offset in seconds cannot overflow");
static_assert(MAX_POSIX_TIME <= INT64_MAX - INT_MAX * SECS_PER_DAY,
"addition cannot overflow");
static_assert(MIN_POSIX_TIME >= INT64_MIN - INT_MIN * SECS_PER_DAY,
"addition cannot underflow");
posix_time += offset_day * SECS_PER_DAY;
if (posix_time > 0 && offset_sec > INT64_MAX - posix_time) {
return 0;
}
if (posix_time < 0 && offset_sec < INT64_MIN - posix_time) {
return 0;
}
posix_time += offset_sec;
if (!OPENSSL_posix_to_tm(posix_time, tm)) {
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)) {
int64_t time_to, time_from;
if (!OPENSSL_tm_to_posix(to, &time_to) ||
!OPENSSL_tm_to_posix(from, &time_from)) {
return 0;
}
// Times are in range, so these calculations can not overflow.
static_assert(SECS_PER_DAY <= INT_MAX, "seconds per day does not fit in int");
static_assert((MAX_POSIX_TIME - MIN_POSIX_TIME) / SECS_PER_DAY <= INT_MAX,
"range of valid POSIX times, in days, does not fit in int");
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;
+89 -45
View File
@@ -59,7 +59,9 @@
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_pool.h>
#include <assert.h>
#include <limits.h>
#include <string.h>
@@ -79,18 +81,18 @@ static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
long len, const ASN1_TEMPLATE *tt, char opt,
int depth);
CRYPTO_BUFFER *buf, int depth);
static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in,
long len, const ASN1_TEMPLATE *tt, char opt,
int depth);
static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
CRYPTO_BUFFER *buf, int depth);
static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, long len,
int utype, const ASN1_ITEM *it);
static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in,
long len, const ASN1_ITEM *it, int tag,
int aclass, char opt);
static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
long len, const ASN1_ITEM *it, int tag, int aclass,
char opt, int depth);
char opt, CRYPTO_BUFFER *buf, int depth);
// Table to convert tags to bit values, used for MSTRING type
static const unsigned long tag2bit[31] = {
@@ -134,6 +136,23 @@ unsigned long ASN1_tag2bit(int tag) {
return tag2bit[tag];
}
static int is_supported_universal_type(int tag, int aclass) {
if (aclass != V_ASN1_UNIVERSAL) {
return 0;
}
return tag == V_ASN1_OBJECT || tag == V_ASN1_NULL || tag == V_ASN1_BOOLEAN ||
tag == V_ASN1_BIT_STRING || tag == V_ASN1_INTEGER ||
tag == V_ASN1_ENUMERATED || tag == V_ASN1_OCTET_STRING ||
tag == V_ASN1_NUMERICSTRING || tag == V_ASN1_PRINTABLESTRING ||
tag == V_ASN1_T61STRING || tag == V_ASN1_VIDEOTEXSTRING ||
tag == V_ASN1_IA5STRING || tag == V_ASN1_UTCTIME ||
tag == V_ASN1_GENERALIZEDTIME || tag == V_ASN1_GRAPHICSTRING ||
tag == V_ASN1_VISIBLESTRING || tag == V_ASN1_GENERALSTRING ||
tag == V_ASN1_UNIVERSALSTRING || tag == V_ASN1_BMPSTRING ||
tag == V_ASN1_UTF8STRING || tag == V_ASN1_SET ||
tag == V_ASN1_SEQUENCE;
}
// Macro to initialize and invalidate the cache
// Decode an ASN1 item, this currently behaves just like a standard 'd2i'
@@ -143,25 +162,40 @@ unsigned long ASN1_tag2bit(int tag) {
ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
const ASN1_ITEM *it) {
ASN1_VALUE *ptmpval = NULL;
if (!pval) {
pval = &ptmpval;
ASN1_VALUE *ret = NULL;
if (asn1_item_ex_d2i(&ret, in, len, it, /*tag=*/-1, /*aclass=*/0, /*opt=*/0,
/*buf=*/NULL, /*depth=*/0) <= 0) {
// Clean up, in case the caller left a partial object.
//
// TODO(davidben): I don't think it can leave one, but the codepaths below
// are a bit inconsistent. Revisit this when rewriting this function.
ASN1_item_ex_free(&ret, it);
}
if (asn1_item_ex_d2i(pval, in, len, it, -1, 0, 0, 0) > 0) {
return *pval;
// If the caller supplied an output pointer, free the old one and replace it
// with |ret|. This differs from OpenSSL slightly in that we don't support
// object reuse. We run this on both success and failure. On failure, even
// with object reuse, OpenSSL destroys the previous object.
if (pval != NULL) {
ASN1_item_ex_free(pval, it);
*pval = ret;
}
return NULL;
return ret;
}
// Decode an item, taking care of IMPLICIT tagging, if any. If 'opt' set and
// tag mismatch return -1 to handle OPTIONAL
//
// TODO(davidben): Historically, all functions in this file had to account for
// |*pval| containing an arbitrary existing value. This is no longer the case
// because |ASN1_item_d2i| now always starts from NULL. As part of rewriting
// this function, take the simplified assumptions into account. Though we must
// still account for the internal calls to |ASN1_item_ex_new|.
static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
long len, const ASN1_ITEM *it, int tag, int aclass,
char opt, int depth) {
char opt, CRYPTO_BUFFER *buf, int depth) {
const ASN1_TEMPLATE *tt, *errtt = NULL;
const ASN1_EXTERN_FUNCS *ef;
const unsigned char *p = NULL, *q;
unsigned char oclass;
char cst, isopt;
@@ -169,12 +203,15 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
int otag;
int ret = 0;
ASN1_VALUE **pchptr;
int combine = aclass & ASN1_TFLG_COMBINE;
aclass &= ~ASN1_TFLG_COMBINE;
if (!pval) {
return 0;
}
if (buf != NULL) {
assert(CRYPTO_BUFFER_data(buf) <= *in &&
*in + len <= CRYPTO_BUFFER_data(buf) + CRYPTO_BUFFER_len(buf));
}
// Bound |len| to comfortably fit in an int. Lengths in this module often
// switch between int and long without overflow checks.
if (len > INT_MAX / 2) {
@@ -197,7 +234,8 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
goto err;
}
return asn1_template_ex_d2i(pval, in, len, it->templates, opt, depth);
return asn1_template_ex_d2i(pval, in, len, it->templates, opt, buf,
depth);
}
return asn1_d2i_ex_primitive(pval, in, len, it, tag, aclass, opt);
break;
@@ -238,10 +276,15 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
}
return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0);
case ASN1_ITYPE_EXTERN:
// Use new style d2i
ef = it->funcs;
return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, NULL);
case ASN1_ITYPE_EXTERN: {
// We don't support implicit tagging with external types.
if (tag != -1) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
goto err;
}
const ASN1_EXTERN_FUNCS *ef = it->funcs;
return ef->asn1_ex_d2i(pval, in, len, it, opt, NULL);
}
case ASN1_ITYPE_CHOICE: {
// It never makes sense for CHOICE types to have implicit tagging, so if
@@ -275,7 +318,7 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
pchptr = asn1_get_field_ptr(pval, tt);
// We mark field as OPTIONAL so its absence can be recognised.
ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, depth);
ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, buf, depth);
// If field not present, try the next one
if (ret == -1) {
continue;
@@ -381,7 +424,7 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
}
// attempt to read in field, allowing each to be OPTIONAL
ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, depth);
ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, buf, depth);
if (!ret) {
errtt = seqtt;
goto err;
@@ -420,7 +463,7 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
}
}
// Save encoding
if (!asn1_enc_save(pval, *in, p - *in, it)) {
if (!asn1_enc_save(pval, *in, p - *in, it, buf)) {
goto auxerr;
}
if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) {
@@ -436,9 +479,7 @@ static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
auxerr:
OPENSSL_PUT_ERROR(ASN1, ASN1_R_AUX_ERROR);
err:
if (combine == 0) {
ASN1_item_ex_free(pval, it);
}
ASN1_item_ex_free(pval, it);
if (errtt) {
ERR_add_error_data(4, "Field=", errtt->field_name, ", Type=", it->sname);
} else {
@@ -449,8 +490,9 @@ err:
int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
const ASN1_ITEM *it, int tag, int aclass, char opt,
ASN1_TLC *ctx) {
return asn1_item_ex_d2i(pval, in, len, it, tag, aclass, opt, 0);
CRYPTO_BUFFER *buf) {
return asn1_item_ex_d2i(pval, in, len, it, tag, aclass, opt, buf,
/*depth=*/0);
}
// Templates are handled with two separate functions. One handles any
@@ -458,7 +500,7 @@ int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
static int asn1_template_ex_d2i(ASN1_VALUE **val, const unsigned char **in,
long inlen, const ASN1_TEMPLATE *tt, char opt,
int depth) {
CRYPTO_BUFFER *buf, int depth) {
int aclass;
int ret;
long len;
@@ -490,7 +532,7 @@ static int asn1_template_ex_d2i(ASN1_VALUE **val, const unsigned char **in,
return 0;
}
// We've found the field so it can't be OPTIONAL now
ret = asn1_template_noexp_d2i(val, &p, len, tt, 0, depth);
ret = asn1_template_noexp_d2i(val, &p, len, tt, /*opt=*/0, buf, depth);
if (!ret) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
return 0;
@@ -503,7 +545,7 @@ static int asn1_template_ex_d2i(ASN1_VALUE **val, const unsigned char **in,
goto err;
}
} else {
return asn1_template_noexp_d2i(val, in, inlen, tt, opt, depth);
return asn1_template_noexp_d2i(val, in, inlen, tt, opt, buf, depth);
}
*in = p;
@@ -516,7 +558,7 @@ err:
static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in,
long len, const ASN1_TEMPLATE *tt, char opt,
int depth) {
CRYPTO_BUFFER *buf, int depth) {
int aclass;
int ret;
const unsigned char *p;
@@ -565,7 +607,6 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in,
}
if (!*val) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
@@ -574,22 +615,21 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in,
ASN1_VALUE *skfield;
const unsigned char *q = p;
skfield = NULL;
if (!asn1_item_ex_d2i(&skfield, &p, len, ASN1_ITEM_ptr(tt->item), -1, 0,
0, depth)) {
if (!asn1_item_ex_d2i(&skfield, &p, len, ASN1_ITEM_ptr(tt->item),
/*tag=*/-1, /*aclass=*/0, /*opt=*/0, buf, depth)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
goto err;
}
len -= p - q;
if (!sk_ASN1_VALUE_push((STACK_OF(ASN1_VALUE) *)*val, skfield)) {
ASN1_item_ex_free(&skfield, ASN1_ITEM_ptr(tt->item));
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
}
} else if (flags & ASN1_TFLG_IMPTAG) {
// IMPLICIT tagging
ret = asn1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), tt->tag,
aclass, opt, depth);
aclass, opt, buf, depth);
if (!ret) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
goto err;
@@ -598,8 +638,8 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in,
}
} else {
// Nothing special
ret = asn1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), -1,
tt->flags & ASN1_TFLG_COMBINE, opt, depth);
ret = asn1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), /*tag=*/-1,
/*aclass=*/0, opt, buf, depth);
if (!ret) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
goto err;
@@ -654,7 +694,7 @@ static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in,
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
return 0;
}
if (oclass != V_ASN1_UNIVERSAL) {
if (!is_supported_universal_type(utype, oclass)) {
utype = V_ASN1_OTHER;
}
}
@@ -709,7 +749,7 @@ err:
// Translate ASN1 content octets into a structure
static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, long len,
int utype, const ASN1_ITEM *it) {
ASN1_VALUE **opval = NULL;
ASN1_STRING *stmp;
@@ -798,13 +838,19 @@ static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
case V_ASN1_OTHER:
case V_ASN1_SET:
case V_ASN1_SEQUENCE:
// TODO(crbug.com/boringssl/412): This default case should be removed, now
// that we've resolved https://crbug.com/boringssl/561. However, it is still
// needed to support some edge cases in |ASN1_PRINTABLE|. |ASN1_PRINTABLE|
// broadly doesn't tolerate unrecognized universal tags, but except for
// eight values that map to |B_ASN1_UNKNOWN| instead of zero. See the
// X509Test.NameAttributeValues test.
default: {
CBS cbs;
CBS_init(&cbs, cont, (size_t)len);
if (utype == V_ASN1_BMPSTRING) {
while (CBS_len(&cbs) != 0) {
uint32_t c;
if (!cbs_get_ucs2_be(&cbs, &c)) {
if (!CBS_get_ucs2_be(&cbs, &c)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BMPSTRING);
goto err;
}
@@ -813,7 +859,7 @@ static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
if (utype == V_ASN1_UNIVERSALSTRING) {
while (CBS_len(&cbs) != 0) {
uint32_t c;
if (!cbs_get_utf32_be(&cbs, &c)) {
if (!CBS_get_utf32_be(&cbs, &c)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_UNIVERSALSTRING);
goto err;
}
@@ -822,7 +868,7 @@ static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
if (utype == V_ASN1_UTF8STRING) {
while (CBS_len(&cbs) != 0) {
uint32_t c;
if (!cbs_get_utf8(&cbs, &c)) {
if (!CBS_get_utf8(&cbs, &c)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_UTF8STRING);
goto err;
}
@@ -847,7 +893,6 @@ static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
if (!*pval) {
stmp = ASN1_STRING_type_new(utype);
if (!stmp) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
*pval = (ASN1_VALUE *)stmp;
@@ -856,7 +901,6 @@ static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
stmp->type = utype;
}
if (!ASN1_STRING_set(stmp, cont, len)) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
ASN1_STRING_free(stmp);
*pval = NULL;
goto err;
+36 -21
View File
@@ -78,7 +78,8 @@ static int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cont, int *out_omit,
static int asn1_set_seq_out(STACK_OF(ASN1_VALUE) *sk, unsigned char **out,
int skcontlen, const ASN1_ITEM *item, int do_sort);
static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_TEMPLATE *tt, int tag, int aclass);
const ASN1_TEMPLATE *tt, int tag, int aclass,
int optional);
// Top level i2d equivalents
@@ -91,12 +92,12 @@ int ASN1_item_i2d(ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it) {
}
buf = OPENSSL_malloc(len);
if (!buf) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return -1;
}
p = buf;
int len2 = ASN1_item_ex_i2d(&val, &p, it, /*tag=*/-1, /*aclass=*/0);
if (len2 <= 0) {
OPENSSL_free(buf);
return len2;
}
assert(len == len2);
@@ -144,11 +145,13 @@ int asn1_item_ex_i2d_opt(ASN1_VALUE **pval, unsigned char **out,
switch (it->itype) {
case ASN1_ITYPE_PRIMITIVE:
if (it->templates) {
// This is an |ASN1_ITEM_TEMPLATE|.
if (it->templates->flags & ASN1_TFLG_OPTIONAL) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return -1;
}
return asn1_template_ex_i2d(pval, out, it->templates, tag, aclass);
return asn1_template_ex_i2d(pval, out, it->templates, tag, aclass,
optional);
}
return asn1_i2d_ex_primitive(pval, out, it, tag, aclass, optional);
@@ -179,13 +182,17 @@ int asn1_item_ex_i2d_opt(ASN1_VALUE **pval, unsigned char **out,
return -1;
}
ASN1_VALUE **pchval = asn1_get_field_ptr(pval, chtt);
return asn1_template_ex_i2d(pchval, out, chtt, -1, 0);
return asn1_template_ex_i2d(pchval, out, chtt, -1, 0, /*optional=*/0);
}
case ASN1_ITYPE_EXTERN: {
// If new style i2d it does all the work
// We don't support implicit tagging with external types.
if (tag != -1) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
return -1;
}
const ASN1_EXTERN_FUNCS *ef = it->funcs;
int ret = ef->asn1_ex_i2d(pval, out, it, tag, aclass);
int ret = ef->asn1_ex_i2d(pval, out, it);
if (ret == 0) {
// |asn1_ex_i2d| should never return zero. We have already checked
// for optional values generically, and |ASN1_ITYPE_EXTERN| fields
@@ -223,7 +230,8 @@ int asn1_item_ex_i2d_opt(ASN1_VALUE **pval, unsigned char **out,
return -1;
}
pseqval = asn1_get_field_ptr(pval, seqtt);
tmplen = asn1_template_ex_i2d(pseqval, NULL, seqtt, -1, 0);
tmplen =
asn1_template_ex_i2d(pseqval, NULL, seqtt, -1, 0, /*optional=*/0);
if (tmplen == -1 || (tmplen > INT_MAX - seqcontlen)) {
return -1;
}
@@ -244,7 +252,8 @@ int asn1_item_ex_i2d_opt(ASN1_VALUE **pval, unsigned char **out,
return -1;
}
pseqval = asn1_get_field_ptr(pval, seqtt);
if (asn1_template_ex_i2d(pseqval, out, seqtt, -1, 0) < 0) {
if (asn1_template_ex_i2d(pseqval, out, seqtt, -1, 0, /*optional=*/0) <
0) {
return -1;
}
}
@@ -259,10 +268,10 @@ int asn1_item_ex_i2d_opt(ASN1_VALUE **pval, unsigned char **out,
// asn1_template_ex_i2d behaves like |asn1_item_ex_i2d_opt| but uses an
// |ASN1_TEMPLATE| instead of an |ASN1_ITEM|. An |ASN1_TEMPLATE| wraps an
// |ASN1_ITEM| with modifiers such as tagging, SEQUENCE or SET, etc. Instead of
// taking an |optional| parameter, it uses the |ASN1_TFLG_OPTIONAL| flag.
// |ASN1_ITEM| with modifiers such as tagging, SEQUENCE or SET, etc.
static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_TEMPLATE *tt, int tag, int iclass) {
const ASN1_TEMPLATE *tt, int tag, int iclass,
int optional) {
int i, ret, ttag, tclass;
size_t j;
uint32_t flags = tt->flags;
@@ -294,7 +303,12 @@ static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
tclass = 0;
}
const int optional = (flags & ASN1_TFLG_OPTIONAL) != 0;
// The template may itself by marked as optional, or this may be the template
// of an |ASN1_ITEM_TEMPLATE| type which was contained inside an outer
// optional template. (They cannot both be true because the
// |ASN1_ITEM_TEMPLATE| codepath rejects optional templates.)
assert(!optional || (flags & ASN1_TFLG_OPTIONAL) == 0);
optional = optional || (flags & ASN1_TFLG_OPTIONAL) != 0;
// At this point 'ttag' contains the outer tag to use, and 'tclass' is the
// class.
@@ -438,16 +452,10 @@ static int asn1_set_seq_out(STACK_OF(ASN1_VALUE) *sk, unsigned char **out,
return 1;
}
if (sk_ASN1_VALUE_num(sk) > ((size_t)-1) / sizeof(DER_ENC)) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_OVERFLOW);
return 0;
}
int ret = 0;
unsigned char *const buf = OPENSSL_malloc(skcontlen);
DER_ENC *encoded = OPENSSL_malloc(sk_ASN1_VALUE_num(sk) * sizeof(*encoded));
DER_ENC *encoded = OPENSSL_calloc(sk_ASN1_VALUE_num(sk), sizeof(*encoded));
if (encoded == NULL || buf == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
goto err;
}
@@ -631,7 +639,7 @@ static int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *out_omit,
case V_ASN1_BOOLEAN:
tbool = (ASN1_BOOLEAN *)pval;
if (*tbool == -1) {
if (*tbool == ASN1_BOOLEAN_NONE) {
*out_omit = 1;
return 0;
}
@@ -678,12 +686,19 @@ static int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *out_omit,
case V_ASN1_UTF8STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
// This is not a valid |ASN1_ITEM| type, but it appears in |ASN1_TYPE|.
case V_ASN1_OTHER:
// TODO(crbug.com/boringssl/412): This default case should be removed, now
// that we've resolved https://crbug.com/boringssl/561. However, it is still
// needed to support some edge cases in |ASN1_PRINTABLE|. |ASN1_PRINTABLE|
// broadly doesn't tolerate unrecognized universal tags, but except for
// eight values that map to |B_ASN1_UNKNOWN| instead of zero. See the
// X509Test.NameAttributeValues test.
default:
// All based on ASN1_STRING and handled the same
strtmp = (ASN1_STRING *)*pval;
cont = strtmp->data;
len = strtmp->length;
break;
}
if (cout && len) {
+16 -45
View File
@@ -66,15 +66,10 @@
// Free up an ASN1 structure
void ASN1_item_free(ASN1_VALUE *val, const ASN1_ITEM *it) {
asn1_item_combine_free(&val, it, 0);
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;
int i;
@@ -117,10 +112,8 @@ void asn1_item_combine_free(ASN1_VALUE **pval, const ASN1_ITEM *it,
if (asn1_cb) {
asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL);
}
if (!combine) {
OPENSSL_free(*pval);
*pval = NULL;
}
OPENSSL_free(*pval);
*pval = NULL;
break;
}
@@ -160,57 +153,33 @@ void asn1_item_combine_free(ASN1_VALUE **pval, const ASN1_ITEM *it,
if (asn1_cb) {
asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL);
}
if (!combine) {
OPENSSL_free(*pval);
*pval = 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);
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_combine_free(pval, ASN1_ITEM_ptr(tt->item),
tt->flags & ASN1_TFLG_COMBINE);
ASN1_item_ex_free(pval, ASN1_ITEM_ptr(tt->item));
}
}
void ASN1_primitive_free(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);
// 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 (utype != V_ASN1_BOOLEAN && !*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;
}
}
assert(it->funcs == NULL);
int utype = it->itype == ASN1_ITYPE_MSTRING ? -1 : it->utype;
switch (utype) {
case V_ASN1_OBJECT:
ASN1_OBJECT_free((ASN1_OBJECT *)*pval);
@@ -220,7 +189,7 @@ void ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
if (it) {
*(ASN1_BOOLEAN *)pval = (ASN1_BOOLEAN)it->size;
} else {
*(ASN1_BOOLEAN *)pval = -1;
*(ASN1_BOOLEAN *)pval = ASN1_BOOLEAN_NONE;
}
return;
@@ -228,8 +197,10 @@ void ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
break;
case V_ASN1_ANY:
ASN1_primitive_free(pval, NULL);
OPENSSL_free(*pval);
if (*pval != NULL) {
asn1_type_cleanup((ASN1_TYPE *)*pval);
OPENSSL_free(*pval);
}
break;
default:
+13 -35
View File
@@ -67,8 +67,6 @@
#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);
@@ -86,11 +84,6 @@ ASN1_VALUE *ASN1_item_new(const ASN1_ITEM *it) {
// 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_EXTERN_FUNCS *ef;
ASN1_VALUE **pseqval;
@@ -134,12 +127,9 @@ static int asn1_item_ex_combine_new(ASN1_VALUE **pval, const ASN1_ITEM *it,
return 1;
}
}
if (!combine) {
*pval = OPENSSL_malloc(it->size);
if (!*pval) {
goto memerr;
}
OPENSSL_memset(*pval, 0, it->size);
*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)) {
@@ -160,15 +150,12 @@ static int asn1_item_ex_combine_new(ASN1_VALUE **pval, const ASN1_ITEM *it,
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);
*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)) {
@@ -184,29 +171,21 @@ static int asn1_item_ex_combine_new(ASN1_VALUE **pval, const ASN1_ITEM *it,
return 1;
memerr2:
asn1_item_combine_free(pval, it, combine);
ASN1_item_ex_free(pval, it);
memerr:
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return 0;
auxerr2:
asn1_item_combine_free(pval, it, combine);
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) {
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;
}
*pval = NULL;
break;
case ASN1_ITYPE_PRIMITIVE:
@@ -246,7 +225,6 @@ static int ASN1_template_new(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) {
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;
}
@@ -255,7 +233,7 @@ static int ASN1_template_new(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) {
goto done;
}
// Otherwise pass it back to the item routine
ret = asn1_item_ex_combine_new(pval, it, tt->flags & ASN1_TFLG_COMBINE);
ret = ASN1_item_ex_new(pval, it);
done:
return ret;
}
@@ -289,7 +267,7 @@ static int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it) {
}
switch (utype) {
case V_ASN1_OBJECT:
*pval = (ASN1_VALUE *)OBJ_nid2obj(NID_undef);
*pval = (ASN1_VALUE *)OBJ_get_undef();
return 1;
case V_ASN1_BOOLEAN:
@@ -107,9 +107,9 @@ 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)
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)
+17 -22
View File
@@ -63,6 +63,7 @@
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_obj.h>
#include <CCryptoBoringSSL_pool.h>
#include <CCryptoBoringSSL_thread.h>
#include "../internal.h"
@@ -135,8 +136,7 @@ void asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it) {
if (enc) {
enc->enc = NULL;
enc->len = 0;
enc->alias_only = 0;
enc->alias_only_on_next_parse = 0;
enc->buf = NULL;
}
}
@@ -147,42 +147,41 @@ void asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it) {
}
}
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) {
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_memdup(in, inlen);
enc->enc = OPENSSL_memdup(in, in_len);
if (!enc->enc) {
return 0;
}
}
enc->len = inlen;
enc->len = in_len;
return 1;
}
void asn1_encoding_clear(ASN1_ENCODING *enc) {
if (!enc->alias_only) {
if (enc->buf != NULL) {
CRYPTO_BUFFER_free(enc->buf);
} else {
OPENSSL_free(enc->enc);
}
enc->enc = NULL;
enc->len = 0;
enc->alias_only = 0;
enc->alias_only_on_next_parse = 0;
enc->buf = NULL;
}
int asn1_enc_restore(int *len, unsigned char **out, ASN1_VALUE **pval,
@@ -203,11 +202,7 @@ int asn1_enc_restore(int *len, unsigned char **out, ASN1_VALUE **pval,
// 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);
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;
@@ -121,12 +121,7 @@ int EVP_EncodedLength(size_t *out_len, size_t len) {
}
EVP_ENCODE_CTX *EVP_ENCODE_CTX_new(void) {
EVP_ENCODE_CTX *ret = OPENSSL_malloc(sizeof(EVP_ENCODE_CTX));
if (ret == NULL) {
return NULL;
}
OPENSSL_memset(ret, 0, sizeof(EVP_ENCODE_CTX));
return ret;
return OPENSSL_zalloc(sizeof(EVP_ENCODE_CTX));
}
void EVP_ENCODE_CTX_free(EVP_ENCODE_CTX *ctx) {
@@ -312,6 +307,10 @@ static int base64_decode_quad(uint8_t *out, size_t *out_num_bytes,
(in[2] == '=') << 1 |
(in[3] == '=');
// In presence of padding, the lowest bits of v are unused. Canonical encoding
// (RFC 4648, section 3.5) requires that these bits all be set to zero. Common
// PEM parsers accept noncanonical base64, adding to the malleability of the
// format. This decoder follows OpenSSL's and Go's PEM parsers and accepts it.
switch (padding_pattern) {
case 0:
// The common case of no padding.
@@ -0,0 +1,119 @@
/* Copyright (c) 2024, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#ifndef OPENSSL_HEADER_CRYPTO_BCM_SUPPORT_H
#define OPENSSL_HEADER_CRYPTO_BCM_SUPPORT_H
#include <CCryptoBoringSSL_base.h>
#include <stdio.h>
// Provided by libcrypto, called from BCM
#if defined(__cplusplus)
extern "C" {
#endif
#if defined(OPENSSL_LINUX)
// On linux we use MADVISE instead of pthread_atfork(), due
// to concerns about clone() being used for address space
// duplication.
#define OPENSSL_FORK_DETECTION
#define OPENSSL_FORK_DETECTION_MADVISE
#elif defined(OPENSSL_MACOS) || defined(OPENSSL_IOS) || \
defined(OPENSSL_OPENBSD) || defined(OPENSSL_FREEBSD)
// These platforms may detect address space duplication with pthread_atfork.
// iOS doesn't normally allow fork in apps, but it's there.
#define OPENSSL_FORK_DETECTION
#define OPENSSL_FORK_DETECTION_PTHREAD_ATFORK
#elif defined(OPENSSL_WINDOWS) || defined(OPENSSL_TRUSTY) || \
defined(__ZEPHYR__) || defined(CROS_EC)
// These platforms do not fork.
#define OPENSSL_DOES_NOT_FORK
#endif
#if defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE)
#define OPENSSL_RAND_DETERMINISTIC
#elif defined(OPENSSL_TRUSTY)
#define OPENSSL_RAND_TRUSTY
#elif defined(OPENSSL_WINDOWS)
#define OPENSSL_RAND_WINDOWS
#elif defined(OPENSSL_LINUX)
#define OPENSSL_RAND_URANDOM
#elif defined(OPENSSL_APPLE) && !defined(OPENSSL_MACOS)
// Unlike macOS, iOS and similar hide away getentropy().
#define OPENSSL_RAND_IOS
#else
// By default if you are integrating BoringSSL we expect you to
// provide getentropy from the <unistd.h> header file.
#define OPENSSL_RAND_GETENTROPY
#endif
// Provided by libcrypto, called from BCM
// CRYPTO_init_sysrand initializes long-lived resources needed to draw entropy
// from the operating system, if the operating system requires initialization.
void CRYPTO_init_sysrand(void);
// CRYPTO_sysrand fills |len| bytes at |buf| with entropy from the operating
// system.
void CRYPTO_sysrand(uint8_t *buf, size_t len);
// CRYPTO_sysrand_if_available fills |len| bytes at |buf| with entropy from the
// operating system, or early /dev/urandom data, and returns 1, _if_ the entropy
// pool is initialized or if getrandom() is not available and not in FIPS mode.
// Otherwise it will not block and will instead fill |buf| with all zeros and
// return 0.
int CRYPTO_sysrand_if_available(uint8_t *buf, size_t len);
// CRYPTO_sysrand_for_seed fills |len| bytes at |buf| with entropy from the
// operating system. It may draw from the |GRND_RANDOM| pool on Android,
// depending on the vendor's configuration.
void CRYPTO_sysrand_for_seed(uint8_t *buf, size_t len);
// RAND_need_entropy is called whenever the BCM module has stopped because it
// has run out of entropy.
void RAND_need_entropy(size_t bytes_needed);
// crypto_get_fork_generation returns the fork generation number for the current
// process, or zero if not supported on the platform. The fork generation number
// is a non-zero, strictly-monotonic counter with the property that, if queried
// in an address space and then again in a subsequently forked copy, the forked
// address space will observe a greater value.
//
// This function may be used to clear cached values across a fork. When
// initializing a cache, record the fork generation. Before using the cache,
// check if the fork generation has changed. If so, drop the cache and update
// the save fork generation. Note this logic transparently handles platforms
// which always return zero.
//
// This is not reliably supported on all platforms which implement |fork|, so it
// should only be used as a hardening measure.
OPENSSL_EXPORT uint64_t CRYPTO_get_fork_generation(void);
// CRYPTO_fork_detect_force_madv_wipeonfork_for_testing is an internal detail
// used for testing purposes.
OPENSSL_EXPORT void CRYPTO_fork_detect_force_madv_wipeonfork_for_testing(
int on);
// CRYPTO_get_stderr returns stderr. This function exists to avoid BCM needing
// a data dependency on libc.
FILE *CRYPTO_get_stderr(void);
#if defined(__cplusplus)
} // extern C
#endif
#endif // OPENSSL_HEADER_CRYPTO_BCM_SUPPORT_H
+45 -27
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;
@@ -342,11 +345,11 @@ int BIO_set_close(BIO *bio, int close_flag) {
return (int)BIO_ctrl(bio, BIO_CTRL_SET_CLOSE, close_flag, NULL);
}
OPENSSL_EXPORT size_t BIO_number_read(const BIO *bio) {
OPENSSL_EXPORT uint64_t BIO_number_read(const BIO *bio) {
return bio->num_read;
}
OPENSSL_EXPORT size_t BIO_number_written(const BIO *bio) {
OPENSSL_EXPORT uint64_t BIO_number_written(const BIO *bio) {
return bio->num_write;
}
@@ -424,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) {
@@ -463,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;
@@ -609,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);
@@ -628,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;
@@ -655,38 +658,38 @@ void BIO_meth_free(BIO_METHOD *method) {
}
int BIO_meth_set_create(BIO_METHOD *method,
int (*create)(BIO *)) {
method->create = create;
int (*create_func)(BIO *)) {
method->create = create_func;
return 1;
}
int BIO_meth_set_destroy(BIO_METHOD *method,
int (*destroy)(BIO *)) {
method->destroy = destroy;
int (*destroy_func)(BIO *)) {
method->destroy = destroy_func;
return 1;
}
int BIO_meth_set_write(BIO_METHOD *method,
int (*write)(BIO *, const char *, int)) {
method->bwrite = write;
int (*write_func)(BIO *, const char *, int)) {
method->bwrite = write_func;
return 1;
}
int BIO_meth_set_read(BIO_METHOD *method,
int (*read)(BIO *, char *, int)) {
method->bread = read;
int (*read_func)(BIO *, char *, int)) {
method->bread = read_func;
return 1;
}
int BIO_meth_set_gets(BIO_METHOD *method,
int (*gets)(BIO *, char *, int)) {
method->bgets = gets;
int (*gets_func)(BIO *, char *, int)) {
method->bgets = gets_func;
return 1;
}
int BIO_meth_set_ctrl(BIO_METHOD *method,
long (*ctrl)(BIO *, int, long, void *)) {
method->ctrl = ctrl;
long (*ctrl_func)(BIO *, int, long, void *)) {
method->ctrl = ctrl_func;
return 1;
}
@@ -706,3 +709,18 @@ 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) {
return CRYPTO_get_ex_new_index_ex(&g_ex_data_class, argl, argp, free_func);
}
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);
}
+41 -56
View File
@@ -130,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) {
@@ -157,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;
@@ -246,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:
@@ -257,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:
@@ -308,15 +293,15 @@ 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 (int)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 (int)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) {
+12 -11
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>
@@ -233,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;
@@ -252,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;
@@ -296,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;
}
@@ -366,7 +363,7 @@ static int conn_read(BIO *bio, char *out, int out_len) {
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,7 +387,7 @@ static int conn_write(BIO *bio, const char *in, int in_len) {
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);
}
}
@@ -490,7 +487,11 @@ static long conn_callback_ctrl(BIO *bio, int cmd, bio_info_cb fp) {
// convention.
OPENSSL_MSVC_PRAGMA(warning(push))
OPENSSL_MSVC_PRAGMA(warning(disable : 4191))
OPENSSL_CLANG_PRAGMA("clang diagnostic push")
OPENSSL_CLANG_PRAGMA("clang diagnostic ignored \"-Wunknown-warning-option\"")
OPENSSL_CLANG_PRAGMA("clang diagnostic ignored \"-Wcast-function-type\"")
data->info_callback = (int (*)(const struct bio_st *, int, int))fp;
OPENSSL_CLANG_PRAGMA("clang diagnostic pop")
OPENSSL_MSVC_PRAGMA(warning(pop))
break;
default:
@@ -532,7 +533,7 @@ int BIO_set_conn_port(BIO *bio, const char *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);
}
@@ -544,4 +545,4 @@ int BIO_do_connect(BIO *bio) {
return (int)BIO_ctrl(bio, BIO_C_DO_STATE_MACHINE, 0, NULL);
}
#endif // OPENSSL_TRUSTY
#endif // OPENSSL_NO_SOCK
@@ -54,48 +54,39 @@
* copied and put under another distribution licence
* [including the GNU Public Licence.] */
#include <CCryptoBoringSSL_x509.h>
#include <CCryptoBoringSSL_bio.h>
#include <CCryptoBoringSSL_asn1.h>
#include <CCryptoBoringSSL_err.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_thread.h>
#include <errno.h>
X509_INFO *X509_INFO_new(void) {
X509_INFO *ret = NULL;
#include "internal.h"
ret = (X509_INFO *)OPENSSL_malloc(sizeof(X509_INFO));
if (ret == NULL) {
OPENSSL_PUT_ERROR(X509, ERR_R_MALLOC_FAILURE);
return NULL;
int bio_errno_should_retry(int return_value) {
if (return_value != -1) {
return 0;
}
ret->enc_cipher.cipher = NULL;
ret->enc_len = 0;
ret->enc_data = NULL;
ret->x509 = NULL;
ret->crl = NULL;
ret->x_pkey = NULL;
return ret;
}
void X509_INFO_free(X509_INFO *x) {
if (x == NULL) {
return;
}
if (x->x509 != NULL) {
X509_free(x->x509);
}
if (x->crl != NULL) {
X509_CRL_free(x->crl);
}
if (x->x_pkey != NULL) {
X509_PKEY_free(x->x_pkey);
}
if (x->enc_data != NULL) {
OPENSSL_free(x->enc_data);
}
OPENSSL_free(x);
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;
}
+14 -54
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) {
@@ -161,7 +117,7 @@ static int fd_read(BIO *b, char *out, int 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);
}
}
@@ -173,7 +129,7 @@ static int fd_write(BIO *b, const char *in, int 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);
}
}
@@ -241,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 = {
@@ -264,6 +224,8 @@ 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 (int)BIO_int_ctrl(bio, BIO_C_SET_FD, close_flag, fd);
}
@@ -271,5 +233,3 @@ int BIO_set_fd(BIO *bio, int fd, int close_flag) {
int BIO_get_fd(BIO *bio, int *out_fd) {
return (int)BIO_ctrl(bio, BIO_C_GET_FD, 0, (char *) out_fd);
}
#endif // OPENSSL_TRUSTY
+43 -27
View File
@@ -73,8 +73,7 @@
#include <CCryptoBoringSSL_bio.h>
#if !defined(OPENSSL_TRUSTY)
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
@@ -84,16 +83,29 @@
#include "../internal.h"
#if defined(OPENSSL_WINDOWS)
#include <fcntl.h>
#include <io.h>
#endif
#define BIO_FP_READ 0x02
#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();
@@ -115,14 +127,13 @@ BIO *BIO_new_file(const char *filename, const char *mode) {
return ret;
}
BIO *BIO_new_fp(FILE *stream, int close_flag) {
BIO *BIO_new_fp(FILE *stream, int flags) {
BIO *ret = BIO_new(BIO_s_file());
if (ret == NULL) {
return NULL;
}
BIO_set_fp(ret, stream, close_flag);
BIO_set_fp(ret, stream, flags);
return ret;
}
@@ -157,13 +168,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;
}
@@ -174,7 +183,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:
@@ -192,6 +200,17 @@ static long file_ctrl(BIO *b, int cmd, long num, void *ptr) {
break;
case BIO_C_SET_FILE_PTR:
file_free(b);
static_assert((BIO_CLOSE & BIO_FP_TEXT) == 0,
"BIO_CLOSE and BIO_FP_TEXT must not collide");
#if defined(OPENSSL_WINDOWS)
// If |BIO_FP_TEXT| is not set, OpenSSL will switch the file to binary
// mode. BoringSSL intentionally diverges here because it means code
// tested under POSIX will inadvertently change the state of |FILE|
// objects when wrapping them in a |BIO|.
if (num & BIO_FP_TEXT) {
_setmode(_fileno(ptr), _O_TEXT);
}
#endif
b->shutdown = (int)num & BIO_CLOSE;
b->ptr = ptr;
b->init = 1;
@@ -199,27 +218,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 = "ab+";
} else {
OPENSSL_strlcpy(p, "a", sizeof(p));
mode = "ab";
}
} else if ((num & BIO_FP_READ) && (num & BIO_FP_WRITE)) {
OPENSSL_strlcpy(p, "r+", sizeof(p));
mode = "rb+";
} else if (num & BIO_FP_WRITE) {
OPENSSL_strlcpy(p, "w", sizeof(p));
mode = "wb";
} else if (num & BIO_FP_READ) {
OPENSSL_strlcpy(p, "r", sizeof(p));
mode = "rb";
} 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;
@@ -253,20 +273,18 @@ 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 = {
@@ -284,8 +302,8 @@ int BIO_get_fp(BIO *bio, FILE **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 (int)BIO_ctrl(bio, BIO_C_SET_FILE_PTR, close_flag, (char *)file);
int BIO_set_fp(BIO *bio, FILE *file, int flags) {
return (int)BIO_ctrl(bio, BIO_C_SET_FILE_PTR, flags, (char *)file);
}
int BIO_read_filename(BIO *bio, const char *filename) {
@@ -314,5 +332,3 @@ 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);
}
#endif // OPENSSL_TRUSTY
+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)
+5 -8
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;
@@ -221,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_) {
@@ -293,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,
@@ -317,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;
@@ -330,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;
@@ -83,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);
+4 -4
View File
@@ -56,7 +56,7 @@
#include <CCryptoBoringSSL_bio.h>
#if !defined(OPENSSL_TRUSTY)
#if !defined(OPENSSL_NO_SOCK)
#include <fcntl.h>
#include <string.h>
@@ -104,7 +104,7 @@ static int sock_read(BIO *b, char *out, int 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);
}
}
@@ -120,7 +120,7 @@ static int sock_write(BIO *b, const char *in, int 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,4 +186,4 @@ BIO *BIO_new_socket(int fd, int close_flag) {
return ret;
}
#endif // OPENSSL_TRUSTY
#endif // OPENSSL_NO_SOCK
@@ -20,7 +20,7 @@
#include <CCryptoBoringSSL_bio.h>
#include <CCryptoBoringSSL_err.h>
#if !defined(OPENSSL_TRUSTY)
#if !defined(OPENSSL_NO_SOCK)
#include <fcntl.h>
#include <string.h>
@@ -121,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
+36 -23
View File
@@ -55,10 +55,13 @@ static void blake2b_mix(uint64_t v[16], int a, int b, int c, int d, uint64_t x,
v[b] = CRYPTO_rotr_u64(v[b] ^ v[c], 63);
}
static void blake2b_transform(
BLAKE2B_CTX *b2b,
const uint64_t block_words[BLAKE2B_CBLOCK / sizeof(uint64_t)],
size_t num_bytes, int is_final_block) {
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), "");
@@ -78,14 +81,22 @@ static void blake2b_transform(
for (int round = 0; round < 12; round++) {
const uint8_t *const s = &kSigma[16 * (round % 10)];
blake2b_mix(v, 0, 4, 8, 12, block_words[s[0]], block_words[s[1]]);
blake2b_mix(v, 1, 5, 9, 13, block_words[s[2]], block_words[s[3]]);
blake2b_mix(v, 2, 6, 10, 14, block_words[s[4]], block_words[s[5]]);
blake2b_mix(v, 3, 7, 11, 15, block_words[s[6]], block_words[s[7]]);
blake2b_mix(v, 0, 5, 10, 15, block_words[s[8]], block_words[s[9]]);
blake2b_mix(v, 1, 6, 11, 12, block_words[s[10]], block_words[s[11]]);
blake2b_mix(v, 2, 7, 8, 13, block_words[s[12]], block_words[s[13]]);
blake2b_mix(v, 3, 4, 9, 14, block_words[s[14]], block_words[s[15]]);
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++) {
@@ -105,13 +116,17 @@ void BLAKE2B256_Init(BLAKE2B_CTX *b2b) {
}
void BLAKE2B256_Update(BLAKE2B_CTX *b2b, const void *in_data, size_t len) {
const uint8_t *data = (const uint8_t *)in_data;
if (len == 0) {
// Work around a C language bug. See https://crbug.com/1019588.
return;
}
size_t todo = sizeof(b2b->block.bytes) - b2b->block_used;
const uint8_t *data = in_data;
size_t todo = sizeof(b2b->block) - b2b->block_used;
if (todo > len) {
todo = len;
}
OPENSSL_memcpy(&b2b->block.bytes[b2b->block_used], data, todo);
OPENSSL_memcpy(&b2b->block[b2b->block_used], data, todo);
b2b->block_used += todo;
data += todo;
len -= todo;
@@ -122,26 +137,24 @@ void BLAKE2B256_Update(BLAKE2B_CTX *b2b, const void *in_data, size_t len) {
// More input remains therefore we must have filled |b2b->block|.
assert(b2b->block_used == BLAKE2B_CBLOCK);
blake2b_transform(b2b, b2b->block.words, BLAKE2B_CBLOCK,
blake2b_transform(b2b, b2b->block, BLAKE2B_CBLOCK,
/*is_final_block=*/0);
b2b->block_used = 0;
while (len > BLAKE2B_CBLOCK) {
uint64_t block_words[BLAKE2B_CBLOCK / sizeof(uint64_t)];
OPENSSL_memcpy(block_words, data, sizeof(block_words));
blake2b_transform(b2b, block_words, BLAKE2B_CBLOCK, /*is_final_block=*/0);
blake2b_transform(b2b, data, BLAKE2B_CBLOCK, /*is_final_block=*/0);
data += BLAKE2B_CBLOCK;
len -= BLAKE2B_CBLOCK;
}
OPENSSL_memcpy(b2b->block.bytes, data, len);
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.bytes[b2b->block_used], 0,
sizeof(b2b->block.bytes) - b2b->block_used);
blake2b_transform(b2b, b2b->block.words, b2b->block_used,
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);
@@ -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;
}
@@ -18,13 +18,10 @@
#include <string.h>
#include "internal.h"
#include "../internal.h"
// 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 uint32_t kMaxDepth = 2048;
// kMaxDepth limits the recursion depth to avoid overflowing the stack.
static const uint32_t kMaxDepth = 128;
// is_string_type returns one if |tag| is a string type and zero otherwise. It
// ignores the constructed bit.
@@ -56,13 +53,11 @@ static int is_string_type(CBS_ASN1_TAG tag) {
// found. The value of |orig_in| is not changed. It returns one on success (i.e.
// |*ber_found| was set) and zero on error.
static int cbs_find_ber(const CBS *orig_in, int *ber_found, uint32_t depth) {
CBS in;
if (depth > kMaxDepth) {
return 0;
}
CBS_init(&in, CBS_data(orig_in), CBS_len(orig_in));
CBS in = *orig_in;
*ber_found = 0;
while (CBS_len(&in) > 0) {
@@ -87,6 +82,10 @@ static int cbs_find_ber(const CBS *orig_in, int *ber_found, uint32_t depth) {
!cbs_find_ber(&contents, ber_found, depth + 1)) {
return 0;
}
if (*ber_found) {
// We already found BER. No need to continue parsing.
return 1;
}
}
}
@@ -19,6 +19,7 @@
#include <string.h>
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_err.h>
#include "../internal.h"
@@ -77,11 +78,13 @@ static int cbb_buffer_reserve(struct cbb_buffer_st *base, uint8_t **out,
size_t newlen = base->len + len;
if (newlen < base->len) {
// Overflow
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW);
goto err;
}
if (newlen > base->cap) {
if (!base->can_resize) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW);
goto err;
}
@@ -121,6 +124,7 @@ static int cbb_buffer_add(struct cbb_buffer_st *base, uint8_t **out,
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;
}
@@ -151,6 +155,29 @@ static struct cbb_buffer_st *cbb_get_base(CBB *cbb) {
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.
@@ -191,6 +218,7 @@ int CBB_flush(CBB *cbb) {
assert (child->pending_len_len == 1);
if (len > 0xfffffffe) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW);
// Too large.
goto err;
} else if (len > 0xffffff) {
@@ -229,6 +257,7 @@ int CBB_flush(CBB *cbb) {
len >>= 8;
}
if (len != 0) {
OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW);
goto err;
}
@@ -238,7 +267,7 @@ int CBB_flush(CBB *cbb) {
return 1;
err:
base->error = 1;
cbb_on_error(cbb);
return 0;
}
@@ -414,7 +443,7 @@ static int cbb_add_u(CBB *cbb, uint64_t v, size_t len_len) {
// |v| must fit in |len_len| bytes.
if (v != 0) {
cbb_get_base(cbb)->error = 1;
cbb_on_error(cbb);
return 0;
}
@@ -473,7 +502,7 @@ int CBB_add_asn1_uint64(CBB *cbb, uint64_t value) {
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)) {
return 0;
goto err;
}
int started = 0;
@@ -487,21 +516,25 @@ int CBB_add_asn1_uint64_with_tag(CBB *cbb, uint64_t value, CBS_ASN1_TAG tag) {
// 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) {
@@ -523,14 +556,18 @@ int CBB_add_asn1_int64_with_tag(CBB *cbb, int64_t value, CBS_ASN1_TAG tag) {
CBB child;
if (!CBB_add_asn1(cbb, &child, tag)) {
return 0;
goto err;
}
for (int i = start; i >= 0; i--) {
if (!CBB_add_u8(&child, bytes[i])) {
return 0;
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) {
@@ -538,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;
}
@@ -549,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;
}
@@ -560,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) {
@@ -649,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++;
@@ -657,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;
}
@@ -26,11 +26,6 @@
#include "internal.h"
void CBS_init(CBS *cbs, const uint8_t *data, size_t len) {
cbs->data = data;
cbs->len = len;
}
static int cbs_get(CBS *cbs, const uint8_t **p, size_t n) {
if (cbs->len < n) {
return 0;
@@ -47,14 +42,6 @@ int CBS_skip(CBS *cbs, size_t len) {
return cbs_get(cbs, &dummy, len);
}
const uint8_t *CBS_data(const CBS *cbs) {
return cbs->data;
}
size_t CBS_len(const CBS *cbs) {
return cbs->len;
}
int CBS_stow(const CBS *cbs, uint8_t **out_ptr, size_t *out_len) {
OPENSSL_free(*out_ptr);
*out_ptr = NULL;
@@ -227,6 +214,30 @@ int CBS_get_until_first(CBS *cbs, CBS *out, uint8_t c) {
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.
@@ -456,10 +467,6 @@ int CBS_get_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG tag_value) {
}
int CBS_peek_asn1_tag(const CBS *cbs, CBS_ASN1_TAG tag_value) {
if (CBS_len(cbs) < 1) {
return 0;
}
CBS copy = *cbs;
CBS_ASN1_TAG actual_tag;
return parse_asn1_tag(&copy, &actual_tag) && tag_value == actual_tag;
@@ -500,11 +507,9 @@ int CBS_get_asn1_int64(CBS *cbs, int64_t *out) {
return 0;
}
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++) {
sign_extend[i] = data[len - i - 1];
}
memcpy(out, sign_extend, sizeof(sign_extend));
OPENSSL_memset(sign_extend, is_negative ? 0xff : 0, sizeof(sign_extend));
OPENSSL_memcpy(sign_extend + sizeof(int64_t) - len, data, len);
*out = CRYPTO_load_u64_be(sign_extend);
return 1;
}
@@ -674,10 +679,33 @@ int CBS_is_unsigned_asn1_integer(const CBS *cbs) {
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)) {
@@ -729,13 +757,13 @@ static int cbs_get_two_digits(CBS *cbs, int *out) {
if (!CBS_get_u8(cbs, &first_digit)) {
return 0;
}
if (!isdigit(first_digit)) {
if (!OPENSSL_isdigit(first_digit)) {
return 0;
}
if (!CBS_get_u8(cbs, &second_digit)) {
return 0;
}
if (!isdigit(second_digit)) {
if (!OPENSSL_isdigit(second_digit)) {
return 0;
}
*out = (first_digit - '0') * 10 + (second_digit - '0');
@@ -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
@@ -18,11 +18,12 @@
static int is_valid_code_point(uint32_t v) {
// References in the following are to Unicode 9.0.0.
// References in the following are to Unicode 15.0.0.
if (// The Unicode space runs from zero to 0x10ffff (3.4 D9).
v > 0x10ffff ||
// Values 0x...fffe, 0x...ffff, and 0xfdd0-0xfdef are permanently reserved
// (3.4 D14)
// as noncharacters (3.4 D14). See also 23.7. As our APIs are intended for
// "open interchange", such as ASN.1, we reject them.
(v & 0xfffe) == 0xfffe ||
(v >= 0xfdd0 && v <= 0xfdef) ||
// Surrogate code points are invalid (3.2 C1).
@@ -38,7 +39,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 +81,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 +90,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 +101,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 +118,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 +143,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);
}
File diff suppressed because it is too large. Load diff
@@ -1,984 +0,0 @@
#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
%endif
#endif // defined(__i386__) && defined(_WIN32)
#if defined(__linux__) && defined(__ELF__)
.section .note.GNU-stack,"",%progbits
#endif
@@ -60,7 +60,40 @@ 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 defined(CHACHA20_ASM_AVX2)
if (ChaCha20_ctr32_avx2_capable(in_len)) {
ChaCha20_ctr32_avx2(out, in, in_len, key, counter);
return;
}
#endif
#if defined(CHACHA20_ASM_SSSE3_4X)
if (ChaCha20_ctr32_ssse3_4x_capable(in_len)) {
ChaCha20_ctr32_ssse3_4x(out, in, in_len, key, counter);
return;
}
#endif
#if defined(CHACHA20_ASM_SSSE3)
if (ChaCha20_ctr32_ssse3_capable(in_len)) {
ChaCha20_ctr32_ssse3(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_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],
@@ -91,7 +124,25 @@ void CRYPTO_chacha_20(uint8_t *out, const uint8_t *in, size_t in_len,
}
#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
@@ -17,6 +17,8 @@
#include <CCryptoBoringSSL_base.h>
#include "../internal.h"
#if defined(__cplusplus)
extern "C" {
#endif
@@ -27,14 +29,69 @@ 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))
#define CHACHA20_ASM
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86)
// ChaCha20_ctr32 is defined in asm/chacha-*.pl.
void ChaCha20_ctr32(uint8_t *out, const uint8_t *in, size_t in_len,
const uint32_t key[8], const uint32_t counter[4]);
#define CHACHA20_ASM_NOHW
#define CHACHA20_ASM_SSSE3
OPENSSL_INLINE int ChaCha20_ctr32_ssse3_capable(size_t len) {
// Unlike the x86_64 version, the x86 SSSE3 routine runs for all non-zero
// lengths.
return len > 0 && CRYPTO_is_SSSE3_capable() && CRYPTO_is_FXSR_capable();
}
void ChaCha20_ctr32_ssse3(uint8_t *out, const uint8_t *in, size_t in_len,
const uint32_t key[8], const uint32_t counter[4]);
#elif !defined(OPENSSL_NO_ASM) && \
(defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64))
#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]);
#elif !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64)
#define CHACHA20_ASM_NOHW
#define CHACHA20_ASM_AVX2
OPENSSL_INLINE int ChaCha20_ctr32_avx2_capable(size_t len) {
return len > 128 && CRYPTO_is_AVX2_capable();
}
void ChaCha20_ctr32_avx2(uint8_t *out, const uint8_t *in, size_t in_len,
const uint32_t key[8], const uint32_t counter[4]);
#define CHACHA20_ASM_SSSE3_4X
OPENSSL_INLINE int ChaCha20_ctr32_ssse3_4x_capable(size_t len) {
int capable = len > 128 && CRYPTO_is_SSSE3_capable();
int faster = len > 192 || !CRYPTO_cpu_perf_is_like_silvermont();
return capable && faster;
}
void ChaCha20_ctr32_ssse3_4x(uint8_t *out, const uint8_t *in, size_t in_len,
const uint32_t key[8], const uint32_t counter[4]);
#define CHACHA20_ASM_SSSE3
OPENSSL_INLINE int ChaCha20_ctr32_ssse3_capable(size_t len) {
return len > 128 && CRYPTO_is_SSSE3_capable();
}
void ChaCha20_ctr32_ssse3(uint8_t *out, const uint8_t *in, size_t in_len,
const uint32_t key[8], const uint32_t counter[4]);
#endif
#if defined(CHACHA20_ASM_NOHW)
// ChaCha20_ctr32_nohw encrypts |in_len| bytes from |in| and writes the result
// to |out|. If |in| and |out| alias, they must be equal. |in_len| may not be
// zero.
//
// |counter[0]| is the initial 32-bit block counter, and the remainder is the
// 96-bit nonce. If the counter overflows, the output is undefined. The function
// will produce output, but the output may vary by machine and may not be
// self-consistent. (On some architectures, the assembly implements a mix of
// 64-bit and 32-bit counters.)
void ChaCha20_ctr32_nohw(uint8_t *out, const uint8_t *in, size_t in_len,
const uint32_t key[8], const uint32_t counter[4]);
#endif
@@ -126,16 +126,16 @@ extern void aesgcmsiv_htable_polyval(const uint8_t htable[16 * 8],
uint8_t in_out_poly[16]);
// aes128gcmsiv_dec decrypts |in_len| & ~15 bytes from |out| and writes them to
// |in|. (The full value of |in_len| is still used to find the authentication
// tag appended to the ciphertext, however, so must not be pre-masked.)
// |in|. |in| and |out| may be equal, but must not otherwise alias.
//
// |in| and |out| may be equal, but must not otherwise overlap.
// |in_out_calculated_tag_and_scratch|, on entry, must contain:
// 1. The current value of the calculated tag, which will be updated during
// decryption and written back to the beginning of this buffer on exit.
// 2. The claimed tag, which is needed to derive counter values.
//
// While decrypting, it updates the POLYVAL value found at the beginning of
// |in_out_calculated_tag_and_scratch| and writes the updated value back before
// return. During executation, it may use the whole of this space for other
// purposes. In order to decrypt and update the POLYVAL value, it uses the
// expanded key from |key| and the table of powers in |htable|.
// While decrypting, the whole of |in_out_calculated_tag_and_scratch| may be
// used for other purposes. In order to decrypt and update the POLYVAL value, it
// uses the expanded key from |key| and the table of powers in |htable|.
extern void aes128gcmsiv_dec(const uint8_t *in, uint8_t *out,
uint8_t in_out_calculated_tag_and_scratch[16 * 8],
const uint8_t htable[16 * 6],
@@ -393,14 +393,10 @@ static int aead_aes_gcm_siv_asm_seal_scatter(
return 1;
}
// TODO(martinkr): Add aead_aes_gcm_siv_asm_open_gather. N.B. aes128gcmsiv_dec
// expects ciphertext and tag in a contiguous buffer.
static int aead_aes_gcm_siv_asm_open(const EVP_AEAD_CTX *ctx, uint8_t *out,
size_t *out_len, size_t max_out_len,
const uint8_t *nonce, size_t nonce_len,
const uint8_t *in, size_t in_len,
const uint8_t *ad, size_t ad_len) {
static int aead_aes_gcm_siv_asm_open_gather(
const EVP_AEAD_CTX *ctx, uint8_t *out, const uint8_t *nonce,
size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *in_tag,
size_t in_tag_len, const uint8_t *ad, size_t ad_len) {
const uint64_t ad_len_64 = ad_len;
if (ad_len_64 >= (UINT64_C(1) << 61)) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE);
@@ -408,8 +404,8 @@ static int aead_aes_gcm_siv_asm_open(const EVP_AEAD_CTX *ctx, uint8_t *out,
}
const uint64_t in_len_64 = in_len;
if (in_len < EVP_AEAD_AES_GCM_SIV_TAG_LEN ||
in_len_64 > (UINT64_C(1) << 36) + AES_BLOCK_SIZE) {
if (in_len_64 > UINT64_C(1) << 36 ||
in_tag_len != EVP_AEAD_AES_GCM_SIV_TAG_LEN) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
@@ -420,13 +416,6 @@ static int aead_aes_gcm_siv_asm_open(const EVP_AEAD_CTX *ctx, uint8_t *out,
}
const struct aead_aes_gcm_siv_asm_ctx *gcm_siv_ctx = asm_ctx_from_ctx(ctx);
const size_t plaintext_len = in_len - EVP_AEAD_AES_GCM_SIV_TAG_LEN;
const uint8_t *const given_tag = in + plaintext_len;
if (max_out_len < plaintext_len) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL);
return 0;
}
alignas(16) uint64_t record_auth_key[2];
alignas(16) uint64_t record_enc_key[4];
@@ -459,27 +448,27 @@ static int aead_aes_gcm_siv_asm_open(const EVP_AEAD_CTX *ctx, uint8_t *out,
alignas(16) uint8_t htable[16 * 6];
aesgcmsiv_htable6_init(htable, (const uint8_t *)record_auth_key);
// aes[128|256]gcmsiv_dec needs access to the claimed tag. So it's put into
// its scratch space.
memcpy(calculated_tag + 16, in_tag, EVP_AEAD_AES_GCM_SIV_TAG_LEN);
if (gcm_siv_ctx->is_128_bit) {
aes128gcmsiv_dec(in, out, calculated_tag, htable, &expanded_key,
plaintext_len);
aes128gcmsiv_dec(in, out, calculated_tag, htable, &expanded_key, in_len);
} else {
aes256gcmsiv_dec(in, out, calculated_tag, htable, &expanded_key,
plaintext_len);
aes256gcmsiv_dec(in, out, calculated_tag, htable, &expanded_key, in_len);
}
if (plaintext_len & 15) {
if (in_len & 15) {
aead_aes_gcm_siv_asm_crypt_last_block(gcm_siv_ctx->is_128_bit, out, in,
plaintext_len, given_tag,
&expanded_key);
in_len, in_tag, &expanded_key);
OPENSSL_memset(scratch, 0, sizeof(scratch));
OPENSSL_memcpy(scratch, out + (plaintext_len & ~15), plaintext_len & 15);
OPENSSL_memcpy(scratch, out + (in_len & ~15), in_len & 15);
aesgcmsiv_polyval_horner(calculated_tag, (const uint8_t *)record_auth_key,
scratch, 1);
}
uint8_t length_block[16];
CRYPTO_store_u64_le(length_block, ad_len * 8);
CRYPTO_store_u64_le(length_block + 8, plaintext_len * 8);
CRYPTO_store_u64_le(length_block + 8, in_len * 8);
aesgcmsiv_polyval_horner(calculated_tag, (const uint8_t *)record_auth_key,
length_block, 1);
@@ -495,13 +484,12 @@ static int aead_aes_gcm_siv_asm_open(const EVP_AEAD_CTX *ctx, uint8_t *out,
aes256gcmsiv_ecb_enc_block(calculated_tag, calculated_tag, &expanded_key);
}
if (CRYPTO_memcmp(calculated_tag, given_tag, EVP_AEAD_AES_GCM_SIV_TAG_LEN) !=
if (CRYPTO_memcmp(calculated_tag, in_tag, EVP_AEAD_AES_GCM_SIV_TAG_LEN) !=
0) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
*out_len = in_len - EVP_AEAD_AES_GCM_SIV_TAG_LEN;
return 1;
}
@@ -515,9 +503,9 @@ static const EVP_AEAD aead_aes_128_gcm_siv_asm = {
aead_aes_gcm_siv_asm_init,
NULL /* init_with_direction */,
aead_aes_gcm_siv_asm_cleanup,
aead_aes_gcm_siv_asm_open,
NULL /* open */,
aead_aes_gcm_siv_asm_seal_scatter,
NULL /* open_gather */,
aead_aes_gcm_siv_asm_open_gather,
NULL /* get_iv */,
NULL /* tag_len */,
};
@@ -532,9 +520,9 @@ static const EVP_AEAD aead_aes_256_gcm_siv_asm = {
aead_aes_gcm_siv_asm_init,
NULL /* init_with_direction */,
aead_aes_gcm_siv_asm_cleanup,
aead_aes_gcm_siv_asm_open,
NULL /* open */,
aead_aes_gcm_siv_asm_seal_scatter,
NULL /* open_gather */,
aead_aes_gcm_siv_asm_open_gather,
NULL /* get_iv */,
NULL /* tag_len */,
};
@@ -647,8 +635,8 @@ static void gcm_siv_polyval(
}
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_store_u64_le(length_block, ((uint64_t) ad_len) * 8);
CRYPTO_store_u64_le(length_block + 8, ((uint64_t) in_len) * 8);
CRYPTO_POLYVAL_update_blocks(&polyval_ctx, length_block,
sizeof(length_block));
@@ -58,6 +58,7 @@
#include <CCryptoBoringSSL_des.h>
#include <CCryptoBoringSSL_nid.h>
#include "../des/internal.h"
#include "../fipsmodule/cipher/internal.h"
#include "internal.h"
@@ -71,35 +72,27 @@ typedef struct {
static int des_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key,
const uint8_t *iv, int enc) {
DES_cblock *deskey = (DES_cblock *)key;
EVP_DES_KEY *dat = (EVP_DES_KEY *)ctx->cipher_data;
DES_set_key(deskey, &dat->ks.ks);
DES_set_key_ex(key, &dat->ks.ks);
return 1;
}
static int des_cbc_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in,
size_t in_len) {
EVP_DES_KEY *dat = (EVP_DES_KEY *)ctx->cipher_data;
DES_ncbc_encrypt(in, out, in_len, &dat->ks.ks, (DES_cblock *)ctx->iv,
ctx->encrypt);
DES_ncbc_encrypt_ex(in, out, in_len, &dat->ks.ks, ctx->iv, ctx->encrypt);
return 1;
}
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,
.nid = NID_des_cbc,
.block_size = 8,
.key_len = 8,
.iv_len = 8,
.ctx_size = sizeof(EVP_DES_KEY),
.flags = EVP_CIPH_CBC_MODE,
.init = des_init_key,
.cipher = des_cbc_cipher,
};
const EVP_CIPHER *EVP_des_cbc(void) { return &evp_des_cbc; }
@@ -113,24 +106,20 @@ static int des_ecb_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in,
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),
&dat->ks.ks, ctx->encrypt);
DES_ecb_encrypt_ex(in + i, out + i, &dat->ks.ks, ctx->encrypt);
}
return 1;
}
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,
.nid = NID_des_ecb,
.block_size = 8,
.key_len = 8,
.iv_len = 0,
.ctx_size = sizeof(EVP_DES_KEY),
.flags = EVP_CIPH_ECB_MODE,
.init = des_init_key,
.cipher = des_ecb_cipher,
};
const EVP_CIPHER *EVP_des_ecb(void) { return &evp_des_ecb; }
@@ -144,66 +133,53 @@ 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_set_key(&deskey[0], &dat->ks.ks[0]);
DES_set_key(&deskey[1], &dat->ks.ks[1]);
DES_set_key(&deskey[2], &dat->ks.ks[2]);
DES_set_key_ex(key, &dat->ks.ks[0]);
DES_set_key_ex(key + 8, &dat->ks.ks[1]);
DES_set_key_ex(key + 16, &dat->ks.ks[2]);
return 1;
}
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;
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);
DES_ede3_cbc_encrypt_ex(in, out, in_len, &dat->ks.ks[0], &dat->ks.ks[1],
&dat->ks.ks[2], ctx->iv, ctx->encrypt);
return 1;
}
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,
.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,
.init = des_ede3_init_key,
.cipher = des_ede3_cbc_cipher,
};
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;
DES_set_key(&deskey[0], &dat->ks.ks[0]);
DES_set_key(&deskey[1], &dat->ks.ks[1]);
DES_set_key(&deskey[0], &dat->ks.ks[2]);
// 2-DES is 3-DES with the first key used twice.
DES_set_key_ex(key, &dat->ks.ks[0]);
DES_set_key_ex(key + 8, &dat->ks.ks[1]);
DES_set_key_ex(key, &dat->ks.ks[2]);
return 1;
}
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,
.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,
.init = des_ede_init_key,
.cipher = des_ede3_cbc_cipher,
};
const EVP_CIPHER *EVP_des_ede_cbc(void) { return &evp_des_ede_cbc; }
@@ -217,41 +193,34 @@ static int des_ede_ecb_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out,
DES_EDE_KEY *dat = (DES_EDE_KEY *) ctx->cipher_data;
for (size_t i = 0; i <= in_len; i += ctx->cipher->block_size) {
DES_ecb3_encrypt((DES_cblock *) (in + i), (DES_cblock *) (out + i),
&dat->ks.ks[0], &dat->ks.ks[1], &dat->ks.ks[2],
ctx->encrypt);
DES_ecb3_encrypt_ex(in + i, out + i, &dat->ks.ks[0], &dat->ks.ks[1],
&dat->ks.ks[2], ctx->encrypt);
}
return 1;
}
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,
.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,
.init = des_ede_init_key,
.cipher = des_ede_ecb_cipher,
};
const EVP_CIPHER *EVP_des_ede(void) { return &evp_des_ede; }
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,
.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,
.init = des_ede3_init_key,
.cipher = des_ede_ecb_cipher,
};
const EVP_CIPHER *EVP_des_ede3(void) { return &evp_des_ede3; }
@@ -78,9 +78,13 @@ static int null_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out,
}
static const EVP_CIPHER n_cipher = {
NID_undef, 1 /* block size */, 0 /* key_len */, 0 /* iv_len */,
0 /* ctx_size */, 0 /* flags */, NULL /* app_data */, null_init_key,
null_cipher, NULL /* cleanup */, NULL /* ctrl */,
.nid = NID_undef,
.block_size = 1,
.key_len = 0,
.iv_len = 0,
.ctx_size = 0,
.init = null_init_key,
.cipher = null_cipher,
};
const EVP_CIPHER *EVP_enc_null(void) { return &n_cipher; }
@@ -427,37 +427,29 @@ static int rc2_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) {
}
static const EVP_CIPHER rc2_40_cbc = {
NID_rc2_40_cbc,
8 /* block size */,
5 /* 40 bit */,
8 /* iv len */,
sizeof(EVP_RC2_KEY),
EVP_CIPH_CBC_MODE | EVP_CIPH_VARIABLE_LENGTH | EVP_CIPH_CTRL_INIT,
NULL /* app_data */,
rc2_init_key,
rc2_cbc_cipher,
NULL,
rc2_ctrl,
.nid = NID_rc2_40_cbc,
.block_size = 8,
.key_len = 5 /* 40 bit */,
.iv_len = 8,
.ctx_size = sizeof(EVP_RC2_KEY),
.flags = EVP_CIPH_CBC_MODE | EVP_CIPH_VARIABLE_LENGTH | EVP_CIPH_CTRL_INIT,
.init = rc2_init_key,
.cipher = rc2_cbc_cipher,
.ctrl = rc2_ctrl,
};
const EVP_CIPHER *EVP_rc2_40_cbc(void) {
return &rc2_40_cbc;
}
const EVP_CIPHER *EVP_rc2_40_cbc(void) { return &rc2_40_cbc; }
static const EVP_CIPHER rc2_cbc = {
NID_rc2_cbc,
8 /* block size */,
16 /* 128 bit */,
8 /* iv len */,
sizeof(EVP_RC2_KEY),
EVP_CIPH_CBC_MODE | EVP_CIPH_VARIABLE_LENGTH | EVP_CIPH_CTRL_INIT,
NULL /* app_data */,
rc2_init_key,
rc2_cbc_cipher,
NULL,
rc2_ctrl,
.nid = NID_rc2_cbc,
.block_size = 8,
.key_len = 16 /* 128 bit */,
.iv_len = 8,
.ctx_size = sizeof(EVP_RC2_KEY),
.flags = EVP_CIPH_CBC_MODE | EVP_CIPH_VARIABLE_LENGTH | EVP_CIPH_CTRL_INIT,
.init = rc2_init_key,
.cipher = rc2_cbc_cipher,
.ctrl = rc2_ctrl,
};
const EVP_CIPHER *EVP_rc2_cbc(void) {
return &rc2_cbc;
}
const EVP_CIPHER *EVP_rc2_cbc(void) { return &rc2_cbc; }
@@ -81,9 +81,14 @@ static int rc4_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in,
}
static const EVP_CIPHER rc4 = {
NID_rc4, 1 /* block_size */, 16 /* key_size */,
0 /* iv_len */, sizeof(RC4_KEY), EVP_CIPH_VARIABLE_LENGTH,
NULL /* app_data */, rc4_init_key, rc4_cipher,
NULL /* cleanup */, NULL /* ctrl */, };
.nid = NID_rc4,
.block_size = 1,
.key_len = 16,
.iv_len = 0,
.ctx_size = sizeof(RC4_KEY),
.flags = EVP_CIPH_VARIABLE_LENGTH,
.init = rc4_init_key,
.cipher = rc4_cipher,
};
const EVP_CIPHER *EVP_rc4(void) { return &rc4; }
@@ -400,6 +400,14 @@ static int aead_aes_128_cbc_sha1_tls_implicit_iv_init(
EVP_sha1(), 1);
}
static int aead_aes_128_cbc_sha256_tls_init(EVP_AEAD_CTX *ctx,
const uint8_t *key, size_t key_len,
size_t tag_len,
enum evp_aead_direction_t dir) {
return aead_tls_init(ctx, key, key_len, tag_len, dir, EVP_aes_128_cbc(),
EVP_sha256(), 0);
}
static int aead_aes_256_cbc_sha1_tls_init(EVP_AEAD_CTX *ctx, const uint8_t *key,
size_t key_len, size_t tag_len,
enum evp_aead_direction_t dir) {
@@ -434,6 +442,7 @@ static int aead_tls_get_iv(const EVP_AEAD_CTX *ctx, const uint8_t **out_iv,
const AEAD_TLS_CTX *tls_ctx = (AEAD_TLS_CTX *)&ctx->state;
const size_t iv_len = EVP_CIPHER_CTX_iv_length(&tls_ctx->cipher_ctx);
if (iv_len <= 1) {
OPENSSL_PUT_ERROR(CIPHER, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return 0;
}
@@ -442,13 +451,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)
@@ -483,6 +485,23 @@ static const EVP_AEAD aead_aes_128_cbc_sha1_tls_implicit_iv = {
aead_tls_tag_len,
};
static const EVP_AEAD aead_aes_128_cbc_sha256_tls = {
SHA256_DIGEST_LENGTH + 16, // key len (SHA256 + AES128)
16, // nonce len (IV)
16 + SHA256_DIGEST_LENGTH, // overhead (padding + SHA256)
SHA256_DIGEST_LENGTH, // max tag length
0, // seal_scatter_supports_extra_in
NULL, // init
aead_aes_128_cbc_sha256_tls_init,
aead_tls_cleanup,
aead_tls_open,
aead_tls_seal_scatter,
NULL, // open_gather
NULL, // get_iv
aead_tls_tag_len,
};
static const EVP_AEAD aead_aes_256_cbc_sha1_tls = {
SHA_DIGEST_LENGTH + 32, // key len (SHA1 + AES256)
16, // nonce len (IV)
@@ -551,23 +570,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;
}
@@ -576,6 +578,10 @@ const EVP_AEAD *EVP_aead_aes_128_cbc_sha1_tls_implicit_iv(void) {
return &aead_aes_128_cbc_sha1_tls_implicit_iv;
}
const EVP_AEAD *EVP_aead_aes_128_cbc_sha256_tls(void) {
return &aead_aes_128_cbc_sha256_tls;
}
const EVP_AEAD *EVP_aead_aes_256_cbc_sha1_tls(void) {
return &aead_aes_256_cbc_sha1_tls;
}
@@ -591,5 +597,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; }
@@ -109,6 +109,14 @@ 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.
//
@@ -184,22 +192,65 @@ OPENSSL_INLINE int chacha20_poly1305_asm_capable(void) {
// Additional input parameters are passed in |aead_data->in|. On exit, it will
// write calculated tag value to |aead_data->out.tag|, which the caller must
// check.
#if defined(OPENSSL_X86_64)
extern void chacha20_poly1305_open_nohw(
uint8_t *out_plaintext, const uint8_t *ciphertext, size_t plaintext_len,
const uint8_t *ad, size_t ad_len, union chacha20_poly1305_open_data *data);
extern void chacha20_poly1305_open_avx2(
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);
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) {
if (CRYPTO_is_AVX2_capable() && CRYPTO_is_BMI2_capable()) {
chacha20_poly1305_open_avx2(out_plaintext, ciphertext, plaintext_len, ad,
ad_len, data);
} else {
chacha20_poly1305_open_nohw(out_plaintext, ciphertext, plaintext_len, ad,
ad_len, data);
}
}
#else
extern void chacha20_poly1305_open(uint8_t *out_plaintext,
const uint8_t *ciphertext,
size_t plaintext_len, const uint8_t *ad,
size_t ad_len,
union chacha20_poly1305_open_data *data);
#endif
// chacha20_poly1305_open is defined in chacha20_poly1305_*.pl. It encrypts
// |plaintext_len| bytes from |plaintext| and writes them to |out_ciphertext|.
// Additional input parameters are passed in |aead_data->in|. The calculated tag
// value is over the computed ciphertext concatenated with |extra_ciphertext|
// and written to |aead_data->out.tag|.
#if defined(OPENSSL_X86_64)
extern void chacha20_poly1305_seal_nohw(
uint8_t *out_ciphertext, const uint8_t *plaintext, size_t plaintext_len,
const uint8_t *ad, size_t ad_len, union chacha20_poly1305_seal_data *data);
extern void chacha20_poly1305_seal_avx2(
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);
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) {
if (CRYPTO_is_AVX2_capable() && CRYPTO_is_BMI2_capable()) {
chacha20_poly1305_seal_avx2(out_ciphertext, plaintext, plaintext_len, ad,
ad_len, data);
} else {
chacha20_poly1305_seal_nohw(out_ciphertext, plaintext, plaintext_len, ad,
ad_len, data);
}
}
#else
extern void chacha20_poly1305_seal(uint8_t *out_ciphertext,
const uint8_t *plaintext,
size_t plaintext_len, const uint8_t *ad,
size_t ad_len,
union chacha20_poly1305_seal_data *data);
#endif
#else
OPENSSL_INLINE int chacha20_poly1305_asm_capable(void) { return 0; }
@@ -121,8 +121,8 @@ void EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in,
size_t mac_end = in_len;
size_t mac_start = mac_end - md_size;
assert(orig_len >= in_len);
assert(in_len >= md_size);
declassify_assert(orig_len >= in_len);
declassify_assert(in_len >= md_size);
assert(md_size <= EVP_MAX_MD_SIZE);
assert(md_size > 0);
@@ -267,24 +267,115 @@ int EVP_sha1_final_with_secret_suffix(SHA_CTX *ctx,
return 1;
}
int EVP_tls_cbc_record_digest_supported(const EVP_MD *md) {
return EVP_MD_type(md) == NID_sha1;
}
int EVP_tls_cbc_digest_record(const EVP_MD *md, uint8_t *md_out,
size_t *md_out_size, const uint8_t header[13],
const uint8_t *data, size_t data_size,
size_t data_plus_mac_plus_padding_size,
const uint8_t *mac_secret,
unsigned mac_secret_length) {
if (EVP_MD_type(md) != NID_sha1) {
// EVP_tls_cbc_record_digest_supported should have been called first to
// check that the hash function is supported.
assert(0);
*md_out_size = 0;
return 0;
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:
return 1;
default:
return 0;
}
}
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.
@@ -336,3 +427,88 @@ int EVP_tls_cbc_digest_record(const EVP_MD *md, uint8_t *md_out,
*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:
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:
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
// check that the hash function is supported.
assert(0);
*md_out_size = 0;
return 0;
}
}
+169 -319
View File
@@ -56,6 +56,7 @@
#include <CCryptoBoringSSL_conf.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
@@ -65,156 +66,146 @@
#include <CCryptoBoringSSL_lhash.h>
#include <CCryptoBoringSSL_mem.h>
#include "conf_def.h"
#include "internal.h"
#include "../internal.h"
#include "../lhash/internal.h"
DEFINE_LHASH_OF(CONF_VALUE)
struct conf_st {
LHASH_OF(CONF_VALUE) *data;
struct conf_section_st {
char *name;
// values contains non-owning pointers to the values in the section.
STACK_OF(CONF_VALUE) *values;
};
static const char kDefaultSectionName[] = "default";
// The maximum length we can grow a value to after variable expansion. 64k
// should be more than enough for all reasonable uses.
#define MAX_CONF_VALUE_LENGTH 65536
static uint32_t conf_section_hash(const CONF_SECTION *s) {
return OPENSSL_strhash(s->name);
}
static int conf_section_cmp(const CONF_SECTION *a, const CONF_SECTION *b) {
return strcmp(a->name, b->name);
}
static uint32_t conf_value_hash(const CONF_VALUE *v) {
const uint32_t section_hash = v->section ? OPENSSL_strhash(v->section) : 0;
const uint32_t name_hash = v->name ? OPENSSL_strhash(v->name) : 0;
const uint32_t section_hash = OPENSSL_strhash(v->section);
const uint32_t name_hash = OPENSSL_strhash(v->name);
return (section_hash << 2) ^ name_hash;
}
static int conf_value_cmp(const CONF_VALUE *a, const CONF_VALUE *b) {
int i;
if (a->section != b->section) {
i = strcmp(a->section, b->section);
if (i) {
return i;
}
int cmp = strcmp(a->section, b->section);
if (cmp != 0) {
return cmp;
}
if (a->name != NULL && b->name != NULL) {
return strcmp(a->name, b->name);
} else if (a->name == b->name) {
return 0;
} else {
return (a->name == NULL) ? -1 : 1;
}
return strcmp(a->name, b->name);
}
CONF *NCONF_new(void *method) {
CONF *conf;
if (method != NULL) {
return NULL;
}
conf = OPENSSL_malloc(sizeof(CONF));
CONF *conf = OPENSSL_malloc(sizeof(CONF));
if (conf == NULL) {
return NULL;
}
conf->data = lh_CONF_VALUE_new(conf_value_hash, conf_value_cmp);
if (conf->data == NULL) {
OPENSSL_free(conf);
conf->sections = lh_CONF_SECTION_new(conf_section_hash, conf_section_cmp);
conf->values = lh_CONF_VALUE_new(conf_value_hash, conf_value_cmp);
if (conf->sections == NULL || conf->values == NULL) {
NCONF_free(conf);
return NULL;
}
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;
}
static void value_free_contents(CONF_VALUE *value) {
if (value->section) {
OPENSSL_free(value->section);
}
if (value->name) {
OPENSSL_free(value->name);
if (value->value) {
OPENSSL_free(value->value);
}
} else {
if (value->value) {
sk_CONF_VALUE_free((STACK_OF(CONF_VALUE)*)value->value);
}
}
}
CONF_VALUE *CONF_VALUE_new(void) { return OPENSSL_zalloc(sizeof(CONF_VALUE)); }
static void value_free(CONF_VALUE *value) {
value_free_contents(value);
if (value == NULL) {
return;
}
OPENSSL_free(value->section);
OPENSSL_free(value->name);
OPENSSL_free(value->value);
OPENSSL_free(value);
}
static void section_free(CONF_SECTION *section) {
if (section == NULL) {
return;
}
OPENSSL_free(section->name);
sk_CONF_VALUE_free(section->values);
OPENSSL_free(section);
}
static void value_free_arg(CONF_VALUE *value, void *arg) { value_free(value); }
static void section_free_arg(CONF_SECTION *section, void *arg) {
section_free(section);
}
void NCONF_free(CONF *conf) {
if (conf == NULL || conf->data == NULL) {
if (conf == NULL) {
return;
}
lh_CONF_VALUE_doall_arg(conf->data, value_free_arg, NULL);
lh_CONF_VALUE_free(conf->data);
lh_CONF_SECTION_doall_arg(conf->sections, section_free_arg, NULL);
lh_CONF_SECTION_free(conf->sections);
lh_CONF_VALUE_doall_arg(conf->values, value_free_arg, NULL);
lh_CONF_VALUE_free(conf->values);
OPENSSL_free(conf);
}
static CONF_VALUE *NCONF_new_section(const CONF *conf, const char *section) {
STACK_OF(CONF_VALUE) *sk = NULL;
int ok = 0;
CONF_VALUE *v = NULL, *old_value;
sk = sk_CONF_VALUE_new_null();
v = CONF_VALUE_new();
if (sk == NULL || v == NULL) {
goto err;
static CONF_SECTION *NCONF_new_section(const CONF *conf, const char *section) {
CONF_SECTION *s = OPENSSL_malloc(sizeof(CONF_SECTION));
if (!s) {
return NULL;
}
v->section = OPENSSL_strdup(section);
if (v->section == NULL) {
s->name = OPENSSL_strdup(section);
s->values = sk_CONF_VALUE_new_null();
if (s->name == NULL || s->values == NULL) {
goto err;
}
v->name = NULL;
v->value = (char *)sk;
if (!lh_CONF_VALUE_insert(conf->data, &old_value, v)) {
CONF_SECTION *old_section;
if (!lh_CONF_SECTION_insert(conf->sections, &old_section, s)) {
goto err;
}
if (old_value) {
value_free(old_value);
}
ok = 1;
section_free(old_section);
return s;
err:
if (!ok) {
if (sk != NULL) {
sk_CONF_VALUE_free(sk);
}
if (v != NULL) {
OPENSSL_free(v);
}
v = NULL;
}
return v;
section_free(s);
return NULL;
}
static int is_comment(char c) { return c == '#'; }
static int is_quote(char c) { return c == '"' || c == '\'' || c == '`'; }
static int is_esc(char c) { return c == '\\'; }
static int is_conf_ws(char c) {
// This differs from |OPENSSL_isspace| in that CONF does not accept '\v' and
// '\f' as whitespace.
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}
static int is_name_char(char c) {
// Alphanumeric characters, and a handful of symbols, may appear in value and
// section names without escaping.
return OPENSSL_isalnum(c) || c == '_' || c == '!' || c == '.' || c == '%' ||
c == '&' || c == '*' || c == '+' || c == ',' || c == '/' || c == ';' ||
c == '?' || c == '@' || c == '^' || c == '~' || c == '|' || c == '-';
}
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();
@@ -228,13 +219,13 @@ static int str_copy(CONF *conf, char *section, char **pto, char *from) {
}
for (;;) {
if (IS_QUOTE(conf, *from)) {
if (is_quote(*from)) {
q = *from;
from++;
while (!IS_EOF(conf, *from) && (*from != q)) {
if (IS_ESC(conf, *from)) {
while (*from != '\0' && *from != q) {
if (is_esc(*from)) {
from++;
if (IS_EOF(conf, *from)) {
if (*from == '\0') {
break;
}
}
@@ -243,26 +234,10 @@ 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)) {
} else if (is_esc(*from)) {
from++;
v = *(from++);
if (IS_EOF(conf, v)) {
if (v == '\0') {
break;
} else if (v == 'r') {
v = '\r';
@@ -274,124 +249,45 @@ static int str_copy(CONF *conf, char *section, char **pto, char *from) {
v = '\t';
}
buf->data[to++] = v;
} else if (IS_EOF(conf, *from)) {
} else if (*from == '\0') {
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. If
// trying to embed '$' in a line, either escape it or wrap the value in
// quotes.
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;
}
static CONF_VALUE *get_section(const CONF *conf, const char *section) {
CONF_VALUE template;
static CONF_SECTION *get_section(const CONF *conf, const char *section) {
CONF_SECTION template;
OPENSSL_memset(&template, 0, sizeof(template));
template.section = (char *) section;
return lh_CONF_VALUE_retrieve(conf->data, &template);
template.name = (char *) section;
return lh_CONF_SECTION_retrieve(conf->sections, &template);
}
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) {
const CONF_SECTION *section_obj = get_section(conf, section);
if (section_obj == NULL) {
return NULL;
}
return (STACK_OF(CONF_VALUE)*) section_value->value;
return section_obj->values;
}
const char *NCONF_get_string(const CONF *conf, const char *section,
@@ -403,66 +299,74 @@ const char *NCONF_get_string(const CONF *conf, const char *section,
}
OPENSSL_memset(&template, 0, sizeof(template));
template.section = (char *) section;
template.name = (char *) name;
value = lh_CONF_VALUE_retrieve(conf->data, &template);
template.section = (char *)section;
template.name = (char *)name;
value = lh_CONF_VALUE_retrieve(conf->values, &template);
if (value == NULL) {
return NULL;
}
return value->value;
}
static int add_string(const CONF *conf, CONF_VALUE *section,
static int add_string(const CONF *conf, CONF_SECTION *section,
CONF_VALUE *value) {
STACK_OF(CONF_VALUE) *section_stack = (STACK_OF(CONF_VALUE)*) section->value;
CONF_VALUE *old_value;
value->section = OPENSSL_strdup(section->section);
if (!sk_CONF_VALUE_push(section_stack, value)) {
value->section = OPENSSL_strdup(section->name);
if (value->section == NULL) {
return 0;
}
if (!lh_CONF_VALUE_insert(conf->data, &old_value, value)) {
if (!sk_CONF_VALUE_push(section->values, value)) {
return 0;
}
CONF_VALUE *old_value;
if (!lh_CONF_VALUE_insert(conf->values, &old_value, value)) {
// Remove |value| from |section->values|, so we do not leave a dangling
// pointer.
sk_CONF_VALUE_pop(section->values);
return 0;
}
if (old_value != NULL) {
(void)sk_CONF_VALUE_delete_ptr(section_stack, old_value);
(void)sk_CONF_VALUE_delete_ptr(section->values, old_value);
value_free(old_value);
}
return 1;
}
static char *eat_ws(CONF *conf, char *p) {
while (IS_WS(conf, *p) && !IS_EOF(conf, *p)) {
static char *eat_ws(char *p) {
while (*p != '\0' && is_conf_ws(*p)) {
p++;
}
return p;
}
#define scan_esc(conf, p) (((IS_EOF((conf), (p)[1])) ? ((p) + 1) : ((p) + 2)))
static char *scan_esc(char *p) {
assert(p[0] == '\\');
return p[1] == '\0' ? p + 1 : p + 2;
}
static char *eat_alpha_numeric(CONF *conf, char *p) {
static char *eat_name(char *p) {
for (;;) {
if (IS_ESC(conf, *p)) {
p = scan_esc(conf, p);
if (is_esc(*p)) {
p = scan_esc(p);
continue;
}
if (!IS_ALPHA_NUMERIC_PUNCT(conf, *p)) {
if (!is_name_char(*p)) {
return p;
}
p++;
}
}
static char *scan_quote(CONF *conf, char *p) {
static char *scan_quote(char *p) {
int q = *p;
p++;
while (!IS_EOF(conf, *p) && *p != q) {
if (IS_ESC(conf, *p)) {
while (*p != '\0' && *p != q) {
if (is_esc(*p)) {
p++;
if (IS_EOF(conf, *p)) {
if (*p == '\0') {
return p;
}
}
@@ -474,57 +378,28 @@ 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) {
static void clear_comments(char *p) {
for (;;) {
if (IS_FCOMMENT(conf, *p)) {
*p = '\0';
return;
}
if (!IS_WS(conf, *p)) {
if (!is_conf_ws(*p)) {
break;
}
p++;
}
for (;;) {
if (IS_COMMENT(conf, *p)) {
if (is_comment(*p)) {
*p = '\0';
return;
}
if (IS_DQUOTE(conf, *p)) {
p = scan_dquote(conf, p);
if (is_quote(*p)) {
p = scan_quote(p);
continue;
}
if (IS_QUOTE(conf, *p)) {
p = scan_quote(conf, p);
if (is_esc(*p)) {
p = scan_esc(p);
continue;
}
if (IS_ESC(conf, *p)) {
p = scan_esc(conf, p);
continue;
}
if (IS_EOF(conf, *p)) {
if (*p == '\0') {
return;
} else {
p++;
@@ -532,7 +407,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;
@@ -540,8 +415,8 @@ static int def_load_bio(CONF *conf, BIO *in, long *out_error_line) {
int again;
long eline = 0;
char btmp[DECIMAL_SIZE(eline) + 1];
CONF_VALUE *v = NULL, *tv;
CONF_VALUE *sv = NULL;
CONF_VALUE *v = NULL;
CONF_SECTION *sv = NULL;
char *section = NULL, *buf;
char *start, *psection, *pname;
@@ -552,7 +427,6 @@ static int def_load_bio(CONF *conf, BIO *in, long *out_error_line) {
section = OPENSSL_strdup(kDefaultSectionName);
if (section == NULL) {
OPENSSL_PUT_ERROR(CONF, ERR_R_MALLOC_FAILURE);
goto err;
}
@@ -605,7 +479,7 @@ static int def_load_bio(CONF *conf, BIO *in, long *out_error_line) {
// If we have bytes and the last char '\\' and
// second last char is not '\\'
p = &(buff->data[bufnum - 1]);
if (IS_ESC(conf, p[0]) && ((bufnum <= 1) || !IS_ESC(conf, p[-1]))) {
if (is_esc(p[0]) && ((bufnum <= 1) || !is_esc(p[-1]))) {
bufnum--;
again = 1;
}
@@ -616,20 +490,20 @@ static int def_load_bio(CONF *conf, BIO *in, long *out_error_line) {
bufnum = 0;
buf = buff->data;
clear_comments(conf, buf);
s = eat_ws(conf, buf);
if (IS_EOF(conf, *s)) {
clear_comments(buf);
s = eat_ws(buf);
if (*s == '\0') {
continue; // blank line
}
if (*s == '[') {
char *ss;
s++;
start = eat_ws(conf, s);
start = eat_ws(s);
ss = start;
again:
end = eat_alpha_numeric(conf, ss);
p = eat_ws(conf, end);
end = eat_name(ss);
p = eat_ws(end);
if (*p != ']') {
if (*p != '\0' && ss != p) {
ss = p;
@@ -653,27 +527,27 @@ static int def_load_bio(CONF *conf, BIO *in, long *out_error_line) {
} else {
pname = s;
psection = NULL;
end = eat_alpha_numeric(conf, s);
end = eat_name(s);
if ((end[0] == ':') && (end[1] == ':')) {
*end = '\0';
end += 2;
psection = pname;
pname = end;
end = eat_alpha_numeric(conf, end);
end = eat_name(end);
}
p = eat_ws(conf, end);
p = eat_ws(end);
if (*p != '=') {
OPENSSL_PUT_ERROR(CONF, CONF_R_MISSING_EQUAL_SIGN);
goto err;
}
*end = '\0';
p++;
start = eat_ws(conf, p);
while (!IS_EOF(conf, *p)) {
start = eat_ws(p);
while (*p != '\0') {
p++;
}
p--;
while ((p != start) && (IS_WS(conf, *p))) {
while (p != start && is_conf_ws(*p)) {
p--;
}
p++;
@@ -687,13 +561,13 @@ 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)) {
goto err;
}
CONF_SECTION *tv;
if (strcmp(psection, section) != 0) {
if ((tv = get_section(conf, psection)) == NULL) {
tv = NCONF_new_section(conf, psection);
@@ -706,44 +580,24 @@ 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);
}
}
value_free(v);
return 0;
}
@@ -756,16 +610,12 @@ 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, size_t len, void *usr),
void *arg) {
@@ -780,7 +630,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++;
}
}
@@ -794,7 +644,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,126 +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.]
*/
/* THIS FILE WAS AUTOMAGICALLY GENERATED!
Please modify and use keysets.pl to regenerate it. */
#define CONF_NUMBER 1
#define CONF_UPPER 2
#define CONF_LOWER 4
#define CONF_UNDER 256
#define CONF_PUNCTUATION 512
#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)
#define CONF_ALPHA_NUMERIC (CONF_ALPHA|CONF_NUMBER|CONF_UNDER)
#define CONF_ALPHA_NUMERIC_PUNCT (CONF_ALPHA|CONF_NUMBER|CONF_UNDER| \
CONF_PUNCTUATION)
#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)
#define IS_WS(c,a) (KEYTYPES(c)[(a)&0xff]&CONF_WS)
#define IS_ALPHA_NUMERIC(c,a) (KEYTYPES(c)[(a)&0xff]&CONF_ALPHA_NUMERIC)
#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,
0x0000,0x0010,0x0010,0x0000,0x0000,0x0010,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0010,0x0200,0x0040,0x0080,0x0000,0x0200,0x0200,0x0040,
0x0000,0x0000,0x0200,0x0200,0x0200,0x0200,0x0200,0x0200,
0x0001,0x0001,0x0001,0x0001,0x0001,0x0001,0x0001,0x0001,
0x0001,0x0001,0x0000,0x0200,0x0000,0x0000,0x0000,0x0200,
0x0200,0x0002,0x0002,0x0002,0x0002,0x0002,0x0002,0x0002,
0x0002,0x0002,0x0002,0x0002,0x0002,0x0002,0x0002,0x0002,
0x0002,0x0002,0x0002,0x0002,0x0002,0x0002,0x0002,0x0002,
0x0002,0x0002,0x0002,0x0000,0x0020,0x0000,0x0200,0x0100,
0x0040,0x0004,0x0004,0x0004,0x0004,0x0004,0x0004,0x0004,
0x0004,0x0004,0x0004,0x0004,0x0004,0x0004,0x0004,0x0004,
0x0004,0x0004,0x0004,0x0004,0x0004,0x0004,0x0004,0x0004,
0x0004,0x0004,0x0004,0x0000,0x0200,0x0000,0x0200,0x0000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,
};
@@ -17,11 +17,23 @@
#include <CCryptoBoringSSL_base.h>
#include "../lhash/internal.h"
#if defined(__cplusplus)
extern "C" {
#endif
typedef struct conf_section_st CONF_SECTION;
DEFINE_LHASH_OF(CONF_SECTION)
DEFINE_LHASH_OF(CONF_VALUE)
struct conf_st {
LHASH_OF(CONF_VALUE) *values;
LHASH_OF(CONF_SECTION) *sections;
};
// CONF_VALUE_new returns a freshly allocated and zeroed |CONF_VALUE|.
CONF_VALUE *CONF_VALUE_new(void);
@@ -15,7 +15,7 @@
#include "internal.h"
#if defined(OPENSSL_AARCH64) && defined(OPENSSL_APPLE) && \
!defined(OPENSSL_STATIC_ARMCAP)
!defined(OPENSSL_STATIC_ARMCAP) && !defined(OPENSSL_NO_ASM)
#include <sys/sysctl.h>
#include <sys/types.h>
@@ -23,8 +23,6 @@
#include <CCryptoBoringSSL_arm_arch.h>
extern uint32_t OPENSSL_armcap_P;
static int has_hw_feature(const char *name) {
int value;
size_t len = sizeof(value);
@@ -65,6 +63,9 @@ void OPENSSL_cpuid_setup(void) {
// available in macOS 12. For compatibility with macOS 11, we also support
// the old names. The old names don't have values for features like FEAT_AES,
// so instead we detect them statically above.
//
// If querying new sysctls, update the Chromium sandbox definition. See
// https://crrev.com/c/4415225.
if (has_hw_feature("hw.optional.arm.FEAT_SHA512") ||
has_hw_feature("hw.optional.armv8_2_sha512")) {
OPENSSL_armcap_P |= ARMV8_SHA512;
@@ -15,7 +15,7 @@
#include "internal.h"
#if defined(OPENSSL_AARCH64) && defined(OPENSSL_FUCHSIA) && \
!defined(OPENSSL_STATIC_ARMCAP)
!defined(OPENSSL_STATIC_ARMCAP) && !defined(OPENSSL_NO_ASM)
#include <zircon/features.h>
#include <zircon/syscalls.h>
@@ -23,7 +23,6 @@
#include <CCryptoBoringSSL_arm_arch.h>
extern uint32_t OPENSSL_armcap_P;
void OPENSSL_cpuid_setup(void) {
uint32_t hwcap;
@@ -15,15 +15,13 @@
#include "internal.h"
#if defined(OPENSSL_AARCH64) && defined(OPENSSL_LINUX) && \
!defined(OPENSSL_STATIC_ARMCAP)
!defined(OPENSSL_STATIC_ARMCAP) && !defined(OPENSSL_NO_ASM)
#include <sys/auxv.h>
#include <CCryptoBoringSSL_arm_arch.h>
extern uint32_t OPENSSL_armcap_P;
void OPENSSL_cpuid_setup(void) {
unsigned long hwcap = getauxval(AT_HWCAP);
@@ -1,4 +1,4 @@
/* Copyright (c) 2022, Google Inc.
/* 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
@@ -12,51 +12,50 @@
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#include "internal.h"
#include <CCryptoBoringSSL_cpu.h>
#if defined(OPENSSL_AARCH64) && defined(OPENSSL_FREEBSD) && \
!defined(OPENSSL_STATIC_ARMCAP)
#if defined(OPENSSL_AARCH64) && defined(OPENSSL_OPENBSD) && \
!defined(OPENSSL_STATIC_ARMCAP) && !defined(OPENSSL_NO_ASM)
#include <machine/armreg.h>
#include <sys/types.h>
#include <machine/cpu.h>
#include <sys/sysctl.h>
#include <CCryptoBoringSSL_arm_arch.h>
extern uint32_t OPENSSL_armcap_P;
#include "internal.h"
// ID_AA64ISAR0_*_VAL are defined starting FreeBSD 13.0. When FreeBSD
// 12.x is out of support, these compatibility macros can be removed.
#ifndef ID_AA64ISAR0_AES_VAL
#define ID_AA64ISAR0_AES_VAL ID_AA64ISAR0_AES
#endif
#ifndef ID_AA64ISAR0_SHA1_VAL
#define ID_AA64ISAR0_SHA1_VAL ID_AA64ISAR0_SHA1
#endif
#ifndef ID_AA64ISAR0_SHA2_VAL
#define ID_AA64ISAR0_SHA2_VAL ID_AA64ISAR0_SHA2
#endif
void OPENSSL_cpuid_setup(void) {
uint64_t id_aa64isar0 = READ_SPECIALREG(id_aa64isar0_el1);
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_VAL(id_aa64isar0) >= ID_AA64ISAR0_AES_BASE) {
if (ID_AA64ISAR0_AES(cpu_id) >= ID_AA64ISAR0_AES_BASE) {
OPENSSL_armcap_P |= ARMV8_AES;
}
if (ID_AA64ISAR0_AES_VAL(id_aa64isar0) >= ID_AA64ISAR0_AES_PMULL) {
if (ID_AA64ISAR0_AES(cpu_id) >= ID_AA64ISAR0_AES_PMULL) {
OPENSSL_armcap_P |= ARMV8_PMULL;
}
if (ID_AA64ISAR0_SHA1_VAL(id_aa64isar0) >= ID_AA64ISAR0_SHA1_BASE) {
if (ID_AA64ISAR0_SHA1(cpu_id) >= ID_AA64ISAR0_SHA1_BASE) {
OPENSSL_armcap_P |= ARMV8_SHA1;
}
if (ID_AA64ISAR0_SHA2_VAL(id_aa64isar0) >= ID_AA64ISAR0_SHA2_BASE) {
if (ID_AA64ISAR0_SHA2(cpu_id) >= ID_AA64ISAR0_SHA2_BASE) {
OPENSSL_armcap_P |= ARMV8_SHA256;
}
if (ID_AA64ISAR0_SHA2_VAL(id_aa64isar0) >= ID_AA64ISAR0_SHA2_512) {
if (ID_AA64ISAR0_SHA2(cpu_id) >= ID_AA64ISAR0_SHA2_512) {
OPENSSL_armcap_P |= ARMV8_SHA512;
}
}
#endif // OPENSSL_AARCH64 && OPENSSL_FREEBSD && !OPENSSL_STATIC_ARMCAP
#endif // OPENSSL_AARCH64 && OPENSSL_OPENBSD && !OPENSSL_STATIC_ARMCAP
@@ -0,0 +1,94 @@
/* 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)) && \
!defined(OPENSSL_NO_ASM)
#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)
@@ -16,13 +16,13 @@
#include "internal.h"
#if defined(OPENSSL_AARCH64) && defined(OPENSSL_WINDOWS) && \
!defined(OPENSSL_STATIC_ARMCAP)
!defined(OPENSSL_STATIC_ARMCAP) && !defined(OPENSSL_NO_ASM)
#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;
@@ -22,7 +22,6 @@
#include <CCryptoBoringSSL_arm_arch.h>
#include <CCryptoBoringSSL_mem.h>
extern uint32_t OPENSSL_armcap_P;
void OPENSSL_cpuid_setup(void) {
unsigned long hwcap = 0, hwcap2 = 0;
+10 -89
View File
@@ -18,6 +18,7 @@
!defined(OPENSSL_STATIC_ARMCAP)
#include <errno.h>
#include <fcntl.h>
#include <sys/auxv.h>
#include <sys/types.h>
#include <unistd.h>
@@ -26,13 +27,6 @@
#include "cpu_arm_linux.h"
#define AT_HWCAP 16
#define AT_HWCAP2 26
// |getauxval| is not available on Android until API level 20. Link it as a weak
// symbol and use other methods as fallback.
unsigned long getauxval(unsigned long type) __attribute__((weak));
static int open_eintr(const char *path, int flags) {
int ret;
do {
@@ -49,21 +43,6 @@ static ssize_t read_eintr(int fd, void *out, size_t len) {
return ret;
}
// read_full reads exactly |len| bytes from |fd| to |out|. On error or end of
// file, it returns zero.
static int read_full(int fd, void *out, size_t len) {
char *outp = out;
while (len > 0) {
ssize_t ret = read_eintr(fd, outp, len);
if (ret <= 0) {
return 0;
}
outp += ret;
len -= ret;
}
return 1;
}
// read_file opens |path| and reads until end-of-file. On success, it returns
// one and sets |*out_ptr| and |*out_len| to a newly-allocated buffer with the
// contents. Otherwise, it returns zero.
@@ -116,41 +95,12 @@ err:
return ret;
}
// getauxval_proc behaves like |getauxval| but reads from /proc/self/auxv.
static unsigned long getauxval_proc(unsigned long type) {
int fd = open_eintr("/proc/self/auxv", O_RDONLY);
if (fd < 0) {
return 0;
}
struct {
unsigned long tag;
unsigned long value;
} entry;
for (;;) {
if (!read_full(fd, &entry, sizeof(entry)) ||
(entry.tag == 0 && entry.value == 0)) {
break;
}
if (entry.tag == type) {
close(fd);
return entry.value;
}
}
close(fd);
return 0;
}
extern uint32_t OPENSSL_armcap_P;
static int g_has_broken_neon, g_needs_hwcap2_workaround;
static int g_needs_hwcap2_workaround;
void OPENSSL_cpuid_setup(void) {
// We ignore the return value of |read_file| and proceed with an empty
// /proc/cpuinfo on error. If |getauxval| works, we will still detect
// capabilities. There may be a false positive due to
// |crypto_cpuinfo_has_broken_neon|, but this is now rare.
// capabilities.
char *cpuinfo_data = NULL;
size_t cpuinfo_len = 0;
read_file(&cpuinfo_data, &cpuinfo_len, "/proc/cpuinfo");
@@ -158,37 +108,8 @@ void OPENSSL_cpuid_setup(void) {
cpuinfo.data = cpuinfo_data;
cpuinfo.len = cpuinfo_len;
// |getauxval| is not available on Android until API level 20. If it is
// unavailable, read from /proc/self/auxv as a fallback. This is unreadable
// on some versions of Android, so further fall back to /proc/cpuinfo.
//
// See
// https://android.googlesource.com/platform/ndk/+/882ac8f3392858991a0e1af33b4b7387ec856bd2
// and b/13679666 (Google-internal) for details.
unsigned long hwcap = 0;
if (getauxval != NULL) {
hwcap = getauxval(AT_HWCAP);
}
if (hwcap == 0) {
hwcap = getauxval_proc(AT_HWCAP);
}
if (hwcap == 0) {
hwcap = crypto_get_arm_hwcap_from_cpuinfo(&cpuinfo);
}
// Clear NEON support if known broken. Note, if NEON is available statically,
// the non-NEON code is dropped and this workaround is a no-op.
//
// TODO(davidben): The Android NDK now builds with NEON statically available
// by default. Cronet still has some consumers that support NEON-less devices
// (b/150371744). Get metrics on whether they still see this CPU and, if not,
// remove this check entirely.
g_has_broken_neon = crypto_cpuinfo_has_broken_neon(&cpuinfo);
if (g_has_broken_neon) {
hwcap &= ~HWCAP_NEON;
}
// Matching OpenSSL, only report other features if NEON is present.
unsigned long hwcap = getauxval(AT_HWCAP);
if (hwcap & HWCAP_NEON) {
OPENSSL_armcap_P |= ARMV7_NEON;
@@ -197,10 +118,7 @@ void OPENSSL_cpuid_setup(void) {
// this is now rare (see Chrome's Net.NeedsHWCAP2Workaround metric), but AES
// and PMULL extensions are very useful, so we still carry the workaround
// for now.
unsigned long hwcap2 = 0;
if (getauxval != NULL) {
hwcap2 = getauxval(AT_HWCAP2);
}
unsigned long hwcap2 = getauxval(AT_HWCAP2);
if (hwcap2 == 0) {
hwcap2 = crypto_get_arm_hwcap2_from_cpuinfo(&cpuinfo);
g_needs_hwcap2_workaround = hwcap2 != 0;
@@ -223,8 +141,11 @@ void OPENSSL_cpuid_setup(void) {
OPENSSL_free(cpuinfo_data);
}
int CRYPTO_has_broken_NEON(void) { return g_has_broken_neon; }
int CRYPTO_has_broken_NEON(void) { return 0; }
int CRYPTO_needs_hwcap2_workaround(void) { return g_needs_hwcap2_workaround; }
int CRYPTO_needs_hwcap2_workaround(void) {
OPENSSL_init_cpuid();
return g_needs_hwcap2_workaround;
}
#endif // OPENSSL_ARM && OPENSSL_LINUX && !OPENSSL_STATIC_ARMCAP
@@ -118,13 +118,6 @@ static int extract_cpuinfo_field(STRING_PIECE *out, const STRING_PIECE *in,
return 0;
}
static int cpuinfo_field_equals(const STRING_PIECE *cpuinfo, const char *field,
const char *value) {
STRING_PIECE extracted;
return extract_cpuinfo_field(&extracted, cpuinfo, field) &&
STRING_PIECE_equals(&extracted, value);
}
// has_list_item treats |list| as a space-separated list of items and returns
// one if |item| is contained in |list| and zero otherwise.
static int has_list_item(const STRING_PIECE *list, const char *item) {
@@ -137,27 +130,6 @@ static int has_list_item(const STRING_PIECE *list, const char *item) {
return 0;
}
// crypto_get_arm_hwcap_from_cpuinfo returns an equivalent ARM |AT_HWCAP| value
// from |cpuinfo|.
static unsigned long crypto_get_arm_hwcap_from_cpuinfo(
const STRING_PIECE *cpuinfo) {
if (cpuinfo_field_equals(cpuinfo, "CPU architecture", "8")) {
// This is a 32-bit ARM binary running on a 64-bit kernel. NEON is always
// available on ARMv8. Linux omits required features, so reading the
// "Features" line does not work. (For simplicity, use strict equality. We
// assume everything running on future ARM architectures will have a
// working |getauxval|.)
return HWCAP_NEON;
}
STRING_PIECE features;
if (extract_cpuinfo_field(&features, cpuinfo, "Features") &&
has_list_item(&features, "neon")) {
return HWCAP_NEON;
}
return 0;
}
// crypto_get_arm_hwcap2_from_cpuinfo returns an equivalent ARM |AT_HWCAP2|
// value from |cpuinfo|.
static unsigned long crypto_get_arm_hwcap2_from_cpuinfo(
@@ -183,16 +155,6 @@ static unsigned long crypto_get_arm_hwcap2_from_cpuinfo(
return ret;
}
// crypto_cpuinfo_has_broken_neon returns one if |cpuinfo| matches a CPU known
// to have broken NEON unit and zero otherwise. See https://crbug.com/341598.
static int crypto_cpuinfo_has_broken_neon(const STRING_PIECE *cpuinfo) {
return cpuinfo_field_equals(cpuinfo, "CPU implementer", "0x51") &&
cpuinfo_field_equals(cpuinfo, "CPU architecture", "7") &&
cpuinfo_field_equals(cpuinfo, "CPU variant", "0x1") &&
cpuinfo_field_equals(cpuinfo, "CPU part", "0x04d") &&
cpuinfo_field_equals(cpuinfo, "CPU revision", "0");
}
#if defined(__cplusplus)
} // extern C
+71 -35
View File
@@ -173,20 +173,21 @@ void OPENSSL_cpuid_setup(void) {
OPENSSL_cpuid(&eax, &ebx, &ecx, &edx, 1);
const uint32_t base_family = (eax >> 8) & 15;
const uint32_t base_model = (eax >> 4) & 15;
uint32_t family = base_family;
uint32_t model = base_model;
if (base_family == 15) {
const uint32_t ext_family = (eax >> 20) & 255;
family += ext_family;
}
if (base_family == 6 || base_family == 15) {
const uint32_t ext_model = (eax >> 16) & 15;
model |= ext_model << 4;
}
if (is_amd) {
// See https://www.amd.com/system/files/TechDocs/25481.pdf, page 10.
const uint32_t base_family = (eax >> 8) & 15;
const uint32_t base_model = (eax >> 4) & 15;
uint32_t family = base_family;
uint32_t model = base_model;
if (base_family == 0xf) {
const uint32_t ext_family = (eax >> 20) & 255;
family += ext_family;
const uint32_t ext_model = (eax >> 16) & 15;
model |= ext_model << 4;
}
if (family < 0x17 || (family == 0x17 && 0x70 <= model && model <= 0x7f)) {
// Disable RDRAND on AMD families before 0x17 (Zen) due to reported
// failures after suspend.
@@ -208,14 +209,6 @@ void OPENSSL_cpuid_setup(void) {
// Reserved bit #30 is repurposed to signal an Intel CPU.
if (is_intel) {
edx |= (1u << 30);
// Clear the XSAVE bit on Knights Landing to mimic Silvermont. This enables
// some Silvermont-specific codepaths which perform better. See OpenSSL
// commit 64d92d74985ebb3d0be58a9718f9e080a14a8e7f.
if ((eax & 0x0fff0ff0) == 0x00050670 /* Knights Landing */ ||
(eax & 0x0fff0ff0) == 0x00080650 /* Knights Mill (per SDE) */) {
ecx &= ~(1u << 26);
}
} else {
edx &= ~(1u << 30);
}
@@ -235,24 +228,67 @@ void OPENSSL_cpuid_setup(void) {
ecx &= ~(1u << 28); // AVX
ecx &= ~(1u << 12); // FMA
ecx &= ~(1u << 11); // AMD XOP
// Clear AVX2 and AVX512* bits.
//
// TODO(davidben): Should bits 17 and 26-28 also be cleared? Upstream
// doesn't clear those.
extended_features[0] &=
~((1u << 5) | (1u << 16) | (1u << 21) | (1u << 30) | (1u << 31));
extended_features[0] &= ~(1u << 5); // AVX2
extended_features[1] &= ~(1u << 9); // VAES
extended_features[1] &= ~(1u << 10); // VPCLMULQDQ
}
// See Intel manual, volume 1, section 15.2.
// See Intel manual, volume 1, sections 15.2 ("Detection of AVX-512 Foundation
// Instructions") through 15.4 ("Detection of Intel AVX-512 Instruction Groups
// Operating at 256 and 128-bit Vector Lengths").
if ((xcr0 & 0xe6) != 0xe6) {
// Clear AVX512F. Note we don't touch other AVX512 extensions because they
// can be used with YMM.
extended_features[0] &= ~(1u << 16);
// Without XCR0.111xx11x, no AVX512 feature can be used. This includes ZMM
// registers, masking, SIMD registers 16-31 (even if accessed as YMM or
// XMM), and EVEX-coded instructions (even on YMM or XMM). Even if only
// XCR0.ZMM_Hi256 is missing, it isn't valid to use AVX512 features on
// shorter vectors, since AVX512 ties everything to the availability of
// 512-bit vectors. See the above-mentioned sections of the Intel manual,
// which say that *all* these XCR0 bits must be checked even when just using
// 128-bit or 256-bit vectors, and also volume 2a section 2.7.11 ("#UD
// Equations for EVEX") which says that all EVEX-coded instructions raise an
// undefined-instruction exception if any of these XCR0 bits is zero.
//
// AVX10 fixes this by reorganizing the features that used to be part of
// "AVX512" and allowing them to be used independently of 512-bit support.
// TODO: add AVX10 detection.
extended_features[0] &= ~(1u << 16); // AVX512F
extended_features[0] &= ~(1u << 17); // AVX512DQ
extended_features[0] &= ~(1u << 21); // AVX512IFMA
extended_features[0] &= ~(1u << 26); // AVX512PF
extended_features[0] &= ~(1u << 27); // AVX512ER
extended_features[0] &= ~(1u << 28); // AVX512CD
extended_features[0] &= ~(1u << 30); // AVX512BW
extended_features[0] &= ~(1u << 31); // AVX512VL
extended_features[1] &= ~(1u << 1); // AVX512VBMI
extended_features[1] &= ~(1u << 6); // AVX512VBMI2
extended_features[1] &= ~(1u << 11); // AVX512VNNI
extended_features[1] &= ~(1u << 12); // AVX512BITALG
extended_features[1] &= ~(1u << 14); // AVX512VPOPCNTDQ
}
// Disable ADX instructions on Knights Landing. See OpenSSL commit
// 64d92d74985ebb3d0be58a9718f9e080a14a8e7f.
if ((ecx & (1u << 26)) == 0) {
extended_features[0] &= ~(1u << 19);
// Repurpose the bit for the removed MPX feature to indicate when using zmm
// registers should be avoided even when they are supported. (When set, AVX512
// features can still be used, but only using ymm or xmm registers.) Skylake
// suffered from severe downclocking when zmm registers were used, which
// affected unrelated code running on the system, making zmm registers not too
// useful outside of benchmarks. The situation improved significantly by Ice
// Lake, but a small amount of downclocking remained. (See
// https://lore.kernel.org/linux-crypto/e8ce1146-3952-6977-1d0e-a22758e58914@intel.com/)
// We take a conservative approach of not allowing zmm registers until after
// Ice Lake and Tiger Lake, i.e. until Sapphire Rapids on the server side.
//
// AMD CPUs, which support AVX512 starting with Zen 4, have not been reported
// to have any downclocking problem when zmm registers are used.
if (is_intel && family == 6 &&
(model == 85 || // Skylake, Cascade Lake, Cooper Lake (server)
model == 106 || // Ice Lake (server)
model == 108 || // Ice Lake (micro server)
model == 125 || // Ice Lake (client)
model == 126 || // Ice Lake (mobile)
model == 140 || // Tiger Lake (mobile)
model == 141)) { // Tiger Lake (client)
extended_features[0] |= 1u << 14;
} else {
extended_features[0] &= ~(1u << 14);
}
OPENSSL_ia32cap_P[0] = edx;
+18 -65
View File
@@ -15,35 +15,16 @@
#include <CCryptoBoringSSL_crypto.h>
#include <assert.h>
#include <stdio.h>
#include "fipsmodule/rand/fork_detect.h"
#include "fipsmodule/rand/internal.h"
#include "bcm_support.h"
#include "internal.h"
static_assert(sizeof(ossl_ssize_t) == sizeof(size_t),
"ossl_ssize_t should be the same size as size_t");
#if !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_STATIC_ARMCAP) && \
(defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || \
defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64) || \
defined(OPENSSL_PPC64LE))
// x86, x86_64, the ARMs and ppc64le need to record the result of a
// cpuid/getauxval call for the asm to work correctly, unless compiled without
// asm code.
#define NEED_CPUID
#else
// Otherwise, don't emit a static initialiser.
#if !defined(BORINGSSL_NO_STATIC_INITIALIZER)
#define BORINGSSL_NO_STATIC_INITIALIZER
#endif
#endif // !NO_ASM && !STATIC_ARMCAP &&
// (X86 || X86_64 || ARM || AARCH64 || PPC64LE)
// Our assembly does not use the GOT to reference symbols, which means
// references to visible symbols will often require a TEXTREL. This is
@@ -81,9 +62,10 @@ HIDDEN uint8_t BORINGSSL_function_hit[7] = {0};
// This value must be explicitly initialized to zero. See similar comment above.
HIDDEN uint32_t OPENSSL_ia32cap_P[4] = {0};
#elif defined(OPENSSL_PPC64LE)
HIDDEN unsigned long OPENSSL_ppc64le_hwcap2 = 0;
uint32_t OPENSSL_get_ia32cap(int idx) {
OPENSSL_init_cpuid();
return OPENSSL_ia32cap_P[idx];
}
#elif defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)
@@ -123,54 +105,24 @@ HIDDEN uint32_t OPENSSL_armcap_P =
HIDDEN uint32_t OPENSSL_armcap_P = 0;
uint32_t *OPENSSL_get_armcap_pointer_for_test(void) {
OPENSSL_init_cpuid();
return &OPENSSL_armcap_P;
}
#endif
uint32_t OPENSSL_get_armcap(void) {
OPENSSL_init_cpuid();
return OPENSSL_armcap_P;
}
#endif
#if defined(BORINGSSL_FIPS)
// In FIPS mode, the power-on self-test function calls |CRYPTO_library_init|
// because we have to ensure that CPUID detection occurs first.
#define BORINGSSL_NO_STATIC_INITIALIZER
#endif
#if defined(OPENSSL_WINDOWS) && !defined(BORINGSSL_NO_STATIC_INITIALIZER)
#define OPENSSL_CDECL __cdecl
#else
#define OPENSSL_CDECL
#endif
#if defined(BORINGSSL_NO_STATIC_INITIALIZER)
static CRYPTO_once_t once = CRYPTO_ONCE_INIT;
#elif defined(_MSC_VER)
#pragma section(".CRT$XCU", read)
static void __cdecl do_library_init(void);
__declspec(allocate(".CRT$XCU")) void(*library_init_constructor)(void) =
do_library_init;
#else
static void do_library_init(void) __attribute__ ((constructor));
#endif
// do_library_init is the actual initialization function. If
// BORINGSSL_NO_STATIC_INITIALIZER isn't defined, this is set as a static
// initializer. Otherwise, it is called by CRYPTO_library_init.
static void OPENSSL_CDECL do_library_init(void) {
// WARNING: this function may only configure the capability variables. See the
// note above about the linker bug.
#if defined(NEED_CPUID)
OPENSSL_cpuid_setup();
static CRYPTO_once_t once = CRYPTO_ONCE_INIT;
void OPENSSL_init_cpuid(void) { CRYPTO_once(&once, OPENSSL_cpuid_setup); }
#endif
}
void CRYPTO_library_init(void) {
// TODO(davidben): It would be tidier if this build knob could be replaced
// with an internal lazy-init mechanism that would handle things correctly
// in-library. https://crbug.com/542879
#if defined(BORINGSSL_NO_STATIC_INITIALIZER)
CRYPTO_once(&once, do_library_init);
#endif
}
void CRYPTO_library_init(void) {}
int CRYPTO_is_confidential_build(void) {
#if defined(BORINGSSL_CONFIDENTIAL)
@@ -190,7 +142,7 @@ int CRYPTO_has_asm(void) {
void CRYPTO_pre_sandbox_init(void) {
// Read from /proc/cpuinfo if needed.
CRYPTO_library_init();
OPENSSL_init_cpuid();
// Open /dev/urandom if needed.
CRYPTO_init_sysrand();
// Set up MADV_WIPEONFORK state if needed.
@@ -231,8 +183,9 @@ int ENGINE_register_all_complete(void) { return 1; }
void OPENSSL_load_builtin_modules(void) {}
int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings) {
CRYPTO_library_init();
return 1;
}
void OPENSSL_cleanup(void) {}
FILE *CRYPTO_get_stderr(void) { return stderr; }
@@ -19,17 +19,9 @@
* domain licensed but the standard ISC license is included above to keep
* licensing simple. */
#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(OPENSSL_NO_ASM) && defined(__ARMEL__) && defined(__ELF__)
#if defined(BORINGSSL_PREFIX)
#include <CCryptoBoringSSL_boringssl_prefix_symbols_asm.h>
#endif
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_ARM) && defined(__ELF__)
.fpu neon
.text
@@ -2131,11 +2123,7 @@ mov sp,r12
vpop {q4,q5,q6,q7}
bx lr
#endif /* !OPENSSL_NO_ASM && __ARMEL__ && __ELF__ */
#if defined(__ELF__)
.section .note.GNU-stack,"",%progbits
#endif
#endif /* !OPENSSL_NO_ASM && OPENSSL_ARM && __ELF__ */
#endif // defined(__arm__) && defined(__linux__)
#if defined(__linux__) && defined(__ELF__)
.section .note.GNU-stack,"",%progbits
@@ -19,8 +19,6 @@
//
// The field functions are shared by Ed25519 and X25519 where possible.
#include <CCryptoBoringSSL_curve25519.h>
#include <assert.h>
#include <string.h>
@@ -31,19 +29,16 @@
#include "internal.h"
#include "../internal.h"
// Various pre-computed constants.
#include "./curve25519_tables.h"
#if defined(OPENSSL_NO_ASM)
#define FIAT_25519_NO_ASM
#endif
#if defined(BORINGSSL_CURVE25519_64BIT)
#if defined(BORINGSSL_HAS_UINT128)
#include "../../third_party/fiat/curve25519_64.h"
#elif defined(OPENSSL_64_BIT)
#include "../../third_party/fiat/curve25519_64_msvc.h"
#else
#include "../../third_party/fiat/curve25519_32.h"
#endif // BORINGSSL_CURVE25519_64BIT
#endif
// Low-level intrinsic operations
@@ -68,7 +63,7 @@ static uint64_t load_4(const uint8_t *in) {
// Field operations.
#if defined(BORINGSSL_CURVE25519_64BIT)
#if defined(OPENSSL_64_BIT)
typedef uint64_t fe_limb_t;
#define FE_NUM_LIMBS 5
@@ -86,7 +81,7 @@ typedef uint64_t fe_limb_t;
#define assert_fe(f) \
do { \
for (unsigned _assert_fe_i = 0; _assert_fe_i < 5; _assert_fe_i++) { \
assert(f[_assert_fe_i] <= UINT64_C(0x8cccccccccccc)); \
declassify_assert(f[_assert_fe_i] <= UINT64_C(0x8cccccccccccc)); \
} \
} while (0)
@@ -103,7 +98,7 @@ typedef uint64_t fe_limb_t;
#define assert_fe_loose(f) \
do { \
for (unsigned _assert_fe_i = 0; _assert_fe_i < 5; _assert_fe_i++) { \
assert(f[_assert_fe_i] <= UINT64_C(0x1a666666666664)); \
declassify_assert(f[_assert_fe_i] <= UINT64_C(0x1a666666666664)); \
} \
} while (0)
@@ -125,8 +120,8 @@ typedef uint32_t fe_limb_t;
#define assert_fe(f) \
do { \
for (unsigned _assert_fe_i = 0; _assert_fe_i < 10; _assert_fe_i++) { \
assert(f[_assert_fe_i] <= \
((_assert_fe_i & 1) ? 0x2333333u : 0x4666666u)); \
declassify_assert(f[_assert_fe_i] <= \
((_assert_fe_i & 1) ? 0x2333333u : 0x4666666u)); \
} \
} while (0)
@@ -143,19 +138,19 @@ typedef uint32_t fe_limb_t;
#define assert_fe_loose(f) \
do { \
for (unsigned _assert_fe_i = 0; _assert_fe_i < 10; _assert_fe_i++) { \
assert(f[_assert_fe_i] <= \
((_assert_fe_i & 1) ? 0x6999999u : 0xd333332u)); \
declassify_assert(f[_assert_fe_i] <= \
((_assert_fe_i & 1) ? 0x6999999u : 0xd333332u)); \
} \
} while (0)
#endif // BORINGSSL_CURVE25519_64BIT
#endif // OPENSSL_64_BIT
static_assert(sizeof(fe) == sizeof(fe_limb_t) * FE_NUM_LIMBS,
"fe_limb_t[FE_NUM_LIMBS] is inconsistent with fe");
static void fe_frombytes_strict(fe *h, const uint8_t s[32]) {
// |fiat_25519_from_bytes| requires the top-most bit be clear.
assert((s[31] & 0x80) == 0);
declassify_assert((s[31] & 0x80) == 0);
fiat_25519_from_bytes(h->v, s);
assert_fe(h->v);
}
@@ -317,11 +312,6 @@ static void fe_copy_lt(fe_loose *h, const fe *f) {
static_assert(sizeof(fe_loose) == sizeof(fe), "fe and fe_loose mismatch");
OPENSSL_memmove(h, f, sizeof(fe));
}
#if !defined(OPENSSL_SMALL)
static void fe_copy_ll(fe_loose *h, const fe_loose *f) {
OPENSSL_memmove(h, f, sizeof(fe_loose));
}
#endif // !defined(OPENSSL_SMALL)
static void fe_loose_invert(fe *out, const fe_loose *z) {
fe t0;
@@ -700,16 +690,6 @@ void x25519_ge_sub(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) {
fe_add(&r->T, &trZ, &trT);
}
static uint8_t equal(signed char b, signed char c) {
uint8_t ub = b;
uint8_t uc = c;
uint8_t x = ub ^ uc; // 0: yes; 1..255: no
uint32_t y = x; // 0: yes; 1..255: no
y -= 1; // 4294967295: yes; 0..254: no
y >>= 31; // 1: yes; 0: no
return y;
}
static void cmov(ge_precomp *t, const ge_precomp *u, uint8_t b) {
fe_cmov(&t->yplusx, &u->yplusx, b);
fe_cmov(&t->yminusx, &u->yminusx, b);
@@ -756,7 +736,7 @@ void x25519_ge_scalarmult_small_precomp(
ge_precomp_0(&e);
for (j = 1; j < 16; j++) {
cmov(&e, &multiples[j-1], equal(index, j));
cmov(&e, &multiples[j-1], 1&constant_time_eq_w(index, j));
}
ge_cached cached;
@@ -778,35 +758,36 @@ void x25519_ge_scalarmult_base(ge_p3 *h, const uint8_t a[32]) {
#else
static uint8_t negative(signed char b) {
uint32_t x = b;
x >>= 31; // 1: yes; 0: no
return x;
}
static void table_select(ge_precomp *t, const int pos, const signed char b) {
uint8_t bnegative = constant_time_msb_w(b);
uint8_t babs = b - ((bnegative & b) << 1);
uint8_t t_bytes[3][32] = {
{constant_time_is_zero_w(b) & 1}, {constant_time_is_zero_w(b) & 1}, {0}};
#if defined(__clang__) // materialize for vectorization, 6% speedup
__asm__("" : "+m" (t_bytes) : /*no inputs*/);
#endif
static_assert(sizeof(t_bytes) == sizeof(k25519Precomp[pos][0]), "");
for (int i = 0; i < 8; i++) {
constant_time_conditional_memxor(t_bytes, k25519Precomp[pos][i],
sizeof(t_bytes),
constant_time_eq_w(babs, 1 + i));
}
fe yplusx, yminusx, xy2d;
fe_frombytes_strict(&yplusx, t_bytes[0]);
fe_frombytes_strict(&yminusx, t_bytes[1]);
fe_frombytes_strict(&xy2d, t_bytes[2]);
fe_copy_lt(&t->yplusx, &yplusx);
fe_copy_lt(&t->yminusx, &yminusx);
fe_copy_lt(&t->xy2d, &xy2d);
static void table_select(ge_precomp *t, int pos, signed char b) {
ge_precomp minust;
uint8_t bnegative = negative(b);
uint8_t babs = b - ((uint8_t)((-bnegative) & b) << 1);
ge_precomp_0(t);
cmov(t, &k25519Precomp[pos][0], equal(babs, 1));
cmov(t, &k25519Precomp[pos][1], equal(babs, 2));
cmov(t, &k25519Precomp[pos][2], equal(babs, 3));
cmov(t, &k25519Precomp[pos][3], equal(babs, 4));
cmov(t, &k25519Precomp[pos][4], equal(babs, 5));
cmov(t, &k25519Precomp[pos][5], equal(babs, 6));
cmov(t, &k25519Precomp[pos][6], equal(babs, 7));
cmov(t, &k25519Precomp[pos][7], equal(babs, 8));
fe_copy_ll(&minust.yplusx, &t->yminusx);
fe_copy_ll(&minust.yminusx, &t->yplusx);
// NOTE: the input table is canonical, but types don't encode it
fe tmp;
fe_carry(&tmp, &t->xy2d);
fe_neg(&minust.xy2d, &tmp);
cmov(t, &minust, bnegative);
fe_copy_lt(&minust.yplusx, &yminusx);
fe_copy_lt(&minust.yminusx, &yplusx);
fe_neg(&minust.xy2d, &xy2d);
cmov(t, &minust, bnegative>>7);
}
// h = a * B
@@ -816,6 +797,18 @@ static void table_select(ge_precomp *t, int pos, signed char b) {
// Preconditions:
// a[31] <= 127
void x25519_ge_scalarmult_base(ge_p3 *h, const uint8_t a[32]) {
#if defined(BORINGSSL_FE25519_ADX)
if (CRYPTO_is_BMI1_capable() && CRYPTO_is_BMI2_capable() &&
CRYPTO_is_ADX_capable()) {
uint8_t t[4][32];
x25519_ge_scalarmult_base_adx(t, a);
fiat_25519_from_bytes(h->X.v, t[0]);
fiat_25519_from_bytes(h->Y.v, t[1]);
fiat_25519_from_bytes(h->Z.v, t[2]);
fiat_25519_from_bytes(h->T.v, t[3]);
return;
}
#endif
signed char e[64];
signed char carry;
ge_p1p1 r;
@@ -918,7 +911,7 @@ void x25519_ge_scalarmult(ge_p2 *r, const uint8_t *scalar, const ge_p3 *A) {
ge_cached selected;
ge_cached_0(&selected);
for (j = 0; j < 16; j++) {
cmov_cached(&selected, &Ai[j], equal(j, index));
cmov_cached(&selected, &Ai[j], 1&constant_time_eq_w(index, j));
}
x25519_ge_add(&t, &u, &selected);
@@ -1913,6 +1906,8 @@ int ED25519_sign(uint8_t out_sig[64], const uint8_t *message,
x25519_sc_reduce(hram);
sc_muladd(out_sig + 32, hram, az, nonce);
// The signature is computed from the private key, but is public.
CONSTTIME_DECLASSIFY(out_sig, 64);
return 1;
}
@@ -1990,6 +1985,8 @@ void ED25519_keypair_from_seed(uint8_t out_public_key[32],
ge_p3 A;
x25519_ge_scalarmult_base(&A, az);
ge_p3_tobytes(out_public_key, &A);
// The public key is derived from the private key, but it is public.
CONSTTIME_DECLASSIFY(out_public_key, 32);
OPENSSL_memcpy(out_private_key, seed, 32);
OPENSSL_memcpy(out_private_key + 32, out_public_key, 32);
@@ -2085,6 +2082,12 @@ static void x25519_scalar_mult(uint8_t out[32], const uint8_t scalar[32],
x25519_NEON(out, scalar, point);
return;
}
#elif defined(BORINGSSL_FE25519_ADX)
if (CRYPTO_is_BMI1_capable() && CRYPTO_is_BMI2_capable() &&
CRYPTO_is_ADX_capable()) {
x25519_scalar_mult_adx(out, scalar, point);
return;
}
#endif
x25519_scalar_mult_generic(out, scalar, point);
@@ -2118,7 +2121,8 @@ int X25519(uint8_t out_shared_key[32], const uint8_t private_key[32],
static const uint8_t kZeros[32] = {0};
x25519_scalar_mult(out_shared_key, private_key, peer_public_value);
// The all-zero output results when the input is a point of small order.
return CRYPTO_memcmp(kZeros, out_shared_key, 32) != 0;
return constant_time_declassify_int(
CRYPTO_memcmp(kZeros, out_shared_key, 32)) != 0;
}
void X25519_public_from_private(uint8_t out_public_value[32],
@@ -2149,4 +2153,5 @@ void X25519_public_from_private(uint8_t out_public_value[32],
fe_loose_invert(&zminusy_inv, &zminusy);
fe_mul_tlt(&zminusy_inv, &zplusy, &zminusy_inv);
fe_tobytes(out_public_value, &zminusy_inv);
CONSTTIME_DECLASSIFY(out_public_value, 32);
}
@@ -1,4 +1,4 @@
/* Copyright (c) 2016, Google Inc.
/* 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
@@ -12,27 +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_base.h>
#if defined(OPENSSL_PPC64LE)
#include <sys/auxv.h>
#include "internal.h"
#if !defined(PPC_FEATURE2_HAS_VCRYPTO)
// PPC_FEATURE2_HAS_VCRYPTO was taken from section 4.1.2.3 of the “OpenPOWER
// ABI for Linux Supplement”.
#define PPC_FEATURE2_HAS_VCRYPTO 0x02000000
#if defined(BORINGSSL_FE25519_ADX)
#include "../../third_party/fiat/curve25519_64_adx.h"
#endif
void OPENSSL_cpuid_setup(void) {
OPENSSL_ppc64le_hwcap2 = getauxval(AT_HWCAP2);
}
int CRYPTO_is_PPC64LE_vcrypto_capable(void) {
return (OPENSSL_ppc64le_hwcap2 & PPC_FEATURE2_HAS_VCRYPTO) != 0;
}
#endif // OPENSSL_PPC64LE
File diff suppressed because it is too large. Load diff
@@ -15,14 +15,13 @@
#ifndef OPENSSL_HEADER_CURVE25519_INTERNAL_H
#define OPENSSL_HEADER_CURVE25519_INTERNAL_H
#if defined(__cplusplus)
extern "C" {
#endif
#include <CCryptoBoringSSL_base.h>
#include <CCryptoBoringSSL_curve25519.h>
#include "../internal.h"
#if defined(__cplusplus)
extern "C" {
#endif
#if defined(OPENSSL_ARM) && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_APPLE)
#define BORINGSSL_X25519_NEON
@@ -32,11 +31,28 @@ void x25519_NEON(uint8_t out[32], const uint8_t scalar[32],
const uint8_t point[32]);
#endif
#if defined(BORINGSSL_HAS_UINT128)
#define BORINGSSL_CURVE25519_64BIT
#if !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_SMALL) && \
defined(__GNUC__) && defined(__x86_64__) && !defined(OPENSSL_WINDOWS)
#define BORINGSSL_FE25519_ADX
// fiat_curve25519_adx_mul is defined in
// third_party/fiat/asm/fiat_curve25519_adx_mul.S
void __attribute__((sysv_abi))
fiat_curve25519_adx_mul(uint64_t out[4], const uint64_t in1[4],
const uint64_t in2[4]);
// fiat_curve25519_adx_square is defined in
// third_party/fiat/asm/fiat_curve25519_adx_square.S
void __attribute__((sysv_abi))
fiat_curve25519_adx_square(uint64_t out[4], const uint64_t in[4]);
// x25519_scalar_mult_adx is defined in third_party/fiat/curve25519_64_adx.h
void x25519_scalar_mult_adx(uint8_t out[32], const uint8_t scalar[32],
const uint8_t point[32]);
void x25519_ge_scalarmult_base_adx(uint8_t h[4][32], const uint8_t a[32]);
#endif
#if defined(BORINGSSL_CURVE25519_64BIT)
#if defined(OPENSSL_64_BIT)
// fe means field element. Here the field is \Z/(2^255-19). An element t,
// entries t[0]...t[4], represents the integer t[0]+2^51 t[1]+2^102 t[2]+2^153
// t[3]+2^204 t[4].
@@ -139,6 +155,8 @@ struct spake2_ctx_st {
};
extern const uint8_t k25519Precomp[32][8][3][32];
#if defined(__cplusplus)
} // extern C
#endif
@@ -272,12 +272,11 @@ static const uint8_t kSpakeMSmallPrecomp[15 * 2 * 32] = {
SPAKE2_CTX *SPAKE2_CTX_new(enum spake2_role_t my_role,
const uint8_t *my_name, size_t my_name_len,
const uint8_t *their_name, size_t their_name_len) {
SPAKE2_CTX *ctx = OPENSSL_malloc(sizeof(SPAKE2_CTX));
SPAKE2_CTX *ctx = OPENSSL_zalloc(sizeof(SPAKE2_CTX));
if (ctx == NULL) {
return NULL;
}
OPENSSL_memset(ctx, 0, sizeof(SPAKE2_CTX));
ctx->my_role = my_role;
CBS my_name_cbs, their_name_cbs;
+150 -63
View File
@@ -61,6 +61,91 @@
#include "internal.h"
/* IP and FP
* The problem is more of a geometric problem that random bit fiddling.
0 1 2 3 4 5 6 7 62 54 46 38 30 22 14 6
8 9 10 11 12 13 14 15 60 52 44 36 28 20 12 4
16 17 18 19 20 21 22 23 58 50 42 34 26 18 10 2
24 25 26 27 28 29 30 31 to 56 48 40 32 24 16 8 0
32 33 34 35 36 37 38 39 63 55 47 39 31 23 15 7
40 41 42 43 44 45 46 47 61 53 45 37 29 21 13 5
48 49 50 51 52 53 54 55 59 51 43 35 27 19 11 3
56 57 58 59 60 61 62 63 57 49 41 33 25 17 9 1
The output has been subject to swaps of the form
0 1 -> 3 1 but the odd and even bits have been put into
2 3 2 0
different words. The main trick is to remember that
t=((l>>size)^r)&(mask);
r^=t;
l^=(t<<size);
can be used to swap and move bits between words.
So l = 0 1 2 3 r = 16 17 18 19
4 5 6 7 20 21 22 23
8 9 10 11 24 25 26 27
12 13 14 15 28 29 30 31
becomes (for size == 2 and mask == 0x3333)
t = 2^16 3^17 -- -- l = 0 1 16 17 r = 2 3 18 19
6^20 7^21 -- -- 4 5 20 21 6 7 22 23
10^24 11^25 -- -- 8 9 24 25 10 11 24 25
14^28 15^29 -- -- 12 13 28 29 14 15 28 29
Thanks for hints from Richard Outerbridge - he told me IP&FP
could be done in 15 xor, 10 shifts and 5 ands.
When I finally started to think of the problem in 2D
I first got ~42 operations without xors. When I remembered
how to use xors :-) I got it to its final state.
*/
#define PERM_OP(a, b, t, n, m) \
do { \
(t) = ((((a) >> (n)) ^ (b)) & (m)); \
(b) ^= (t); \
(a) ^= ((t) << (n)); \
} while (0)
#define IP(l, r) \
do { \
uint32_t tt; \
PERM_OP(r, l, tt, 4, 0x0f0f0f0fL); \
PERM_OP(l, r, tt, 16, 0x0000ffffL); \
PERM_OP(r, l, tt, 2, 0x33333333L); \
PERM_OP(l, r, tt, 8, 0x00ff00ffL); \
PERM_OP(r, l, tt, 1, 0x55555555L); \
} while (0)
#define FP(l, r) \
do { \
uint32_t tt; \
PERM_OP(l, r, tt, 1, 0x55555555L); \
PERM_OP(r, l, tt, 8, 0x00ff00ffL); \
PERM_OP(l, r, tt, 2, 0x33333333L); \
PERM_OP(r, l, tt, 16, 0x0000ffffL); \
PERM_OP(l, r, tt, 4, 0x0f0f0f0fL); \
} while (0)
#define LOAD_DATA(ks, R, S, u, t, E0, E1) \
do { \
(u) = (R) ^ (ks)->subkeys[S][0]; \
(t) = (R) ^ (ks)->subkeys[S][1]; \
} while (0)
#define D_ENCRYPT(ks, LL, R, S) \
do { \
LOAD_DATA(ks, R, S, u, t, E0, E1); \
t = CRYPTO_rotr_u32(t, 4); \
(LL) ^= \
DES_SPtrans[0][(u >> 2L) & 0x3f] ^ DES_SPtrans[2][(u >> 10L) & 0x3f] ^ \
DES_SPtrans[4][(u >> 18L) & 0x3f] ^ \
DES_SPtrans[6][(u >> 26L) & 0x3f] ^ DES_SPtrans[1][(t >> 2L) & 0x3f] ^ \
DES_SPtrans[3][(t >> 10L) & 0x3f] ^ \
DES_SPtrans[5][(t >> 18L) & 0x3f] ^ DES_SPtrans[7][(t >> 26L) & 0x3f]; \
} while (0)
#define ITERATIONS 16
#define HALF_ITERATIONS 8
static const uint32_t des_skb[8][64] = {
{ // for C bits (numbered as per FIPS 46) 1 2 3 4 5 6
0x00000000, 0x00000010, 0x20000000, 0x20000010, 0x00010000,
@@ -294,13 +379,17 @@ static const uint32_t DES_SPtrans[8][64] = {
(a) = (a) ^ (t) ^ ((t) >> (16 - (n))))
void DES_set_key(const DES_cblock *key, DES_key_schedule *schedule) {
DES_set_key_ex(key->bytes, schedule);
}
void DES_set_key_ex(const uint8_t key[8], DES_key_schedule *schedule) {
static const int shifts2[16] = {0, 0, 1, 1, 1, 1, 1, 1,
0, 1, 1, 1, 1, 1, 1, 0};
uint32_t c, d, t, s, t2;
const uint8_t *in;
int i;
in = key->bytes;
in = key;
c2l(in, c);
c2l(in, d);
@@ -378,7 +467,8 @@ void DES_set_odd_parity(DES_cblock *key) {
}
}
static void DES_encrypt1(uint32_t *data, const DES_key_schedule *ks, int enc) {
static void DES_encrypt1(uint32_t data[2], const DES_key_schedule *ks,
int enc) {
uint32_t l, r, t, u;
r = data[0];
@@ -442,7 +532,8 @@ static void DES_encrypt1(uint32_t *data, const DES_key_schedule *ks, int enc) {
data[1] = r;
}
static void DES_encrypt2(uint32_t *data, const DES_key_schedule *ks, int enc) {
static void DES_encrypt2(uint32_t data[2], const DES_key_schedule *ks,
int enc) {
uint32_t l, r, t, u;
r = data[0];
@@ -499,7 +590,7 @@ static void DES_encrypt2(uint32_t *data, const DES_key_schedule *ks, int enc) {
data[1] = CRYPTO_rotr_u32(r, 3);
}
void DES_encrypt3(uint32_t *data, const DES_key_schedule *ks1,
void DES_encrypt3(uint32_t data[2], const DES_key_schedule *ks1,
const DES_key_schedule *ks2, const DES_key_schedule *ks3) {
uint32_t l, r;
@@ -508,9 +599,9 @@ void DES_encrypt3(uint32_t *data, const DES_key_schedule *ks1,
IP(l, r);
data[0] = l;
data[1] = r;
DES_encrypt2((uint32_t *)data, ks1, DES_ENCRYPT);
DES_encrypt2((uint32_t *)data, ks2, DES_DECRYPT);
DES_encrypt2((uint32_t *)data, ks3, DES_ENCRYPT);
DES_encrypt2(data, ks1, DES_ENCRYPT);
DES_encrypt2(data, ks2, DES_DECRYPT);
DES_encrypt2(data, ks3, DES_ENCRYPT);
l = data[0];
r = data[1];
FP(r, l);
@@ -518,7 +609,7 @@ void DES_encrypt3(uint32_t *data, const DES_key_schedule *ks1,
data[1] = r;
}
void DES_decrypt3(uint32_t *data, const DES_key_schedule *ks1,
void DES_decrypt3(uint32_t data[2], const DES_key_schedule *ks1,
const DES_key_schedule *ks2, const DES_key_schedule *ks3) {
uint32_t l, r;
@@ -527,9 +618,9 @@ void DES_decrypt3(uint32_t *data, const DES_key_schedule *ks1,
IP(l, r);
data[0] = l;
data[1] = r;
DES_encrypt2((uint32_t *)data, ks3, DES_DECRYPT);
DES_encrypt2((uint32_t *)data, ks2, DES_ENCRYPT);
DES_encrypt2((uint32_t *)data, ks1, DES_DECRYPT);
DES_encrypt2(data, ks3, DES_DECRYPT);
DES_encrypt2(data, ks2, DES_ENCRYPT);
DES_encrypt2(data, ks1, DES_DECRYPT);
l = data[0];
r = data[1];
FP(r, l);
@@ -539,32 +630,34 @@ void DES_decrypt3(uint32_t *data, const DES_key_schedule *ks1,
void DES_ecb_encrypt(const DES_cblock *in_block, DES_cblock *out_block,
const DES_key_schedule *schedule, int is_encrypt) {
uint32_t l;
uint32_t ll[2];
const uint8_t *in = in_block->bytes;
uint8_t *out = out_block->bytes;
DES_ecb_encrypt_ex(in_block->bytes, out_block->bytes, schedule, is_encrypt);
}
c2l(in, l);
ll[0] = l;
c2l(in, l);
ll[1] = l;
void DES_ecb_encrypt_ex(const uint8_t in[8], uint8_t out[8],
const DES_key_schedule *schedule, int is_encrypt) {
uint32_t ll[2];
ll[0] = CRYPTO_load_u32_le(in);
ll[1] = CRYPTO_load_u32_le(in + 4);
DES_encrypt1(ll, schedule, is_encrypt);
l = ll[0];
l2c(l, out);
l = ll[1];
l2c(l, out);
ll[0] = ll[1] = 0;
CRYPTO_store_u32_le(out, ll[0]);
CRYPTO_store_u32_le(out + 4, ll[1]);
}
void DES_ncbc_encrypt(const uint8_t *in, uint8_t *out, size_t len,
const DES_key_schedule *schedule, DES_cblock *ivec,
int enc) {
DES_ncbc_encrypt_ex(in, out, len, schedule, ivec->bytes, enc);
}
void DES_ncbc_encrypt_ex(const uint8_t *in, uint8_t *out, size_t len,
const DES_key_schedule *schedule, uint8_t ivec[8],
int enc) {
uint32_t tin0, tin1;
uint32_t tout0, tout1, xor0, xor1;
uint32_t tin[2];
unsigned char *iv;
iv = ivec->bytes;
iv = ivec;
if (enc) {
c2l(iv, tout0);
@@ -576,7 +669,7 @@ void DES_ncbc_encrypt(const uint8_t *in, uint8_t *out, size_t len,
tin[0] = tin0;
tin1 ^= tout1;
tin[1] = tin1;
DES_encrypt1((uint32_t *)tin, schedule, DES_ENCRYPT);
DES_encrypt1(tin, schedule, DES_ENCRYPT);
tout0 = tin[0];
l2c(tout0, out);
tout1 = tin[1];
@@ -588,13 +681,13 @@ void DES_ncbc_encrypt(const uint8_t *in, uint8_t *out, size_t len,
tin[0] = tin0;
tin1 ^= tout1;
tin[1] = tin1;
DES_encrypt1((uint32_t *)tin, schedule, DES_ENCRYPT);
DES_encrypt1(tin, schedule, DES_ENCRYPT);
tout0 = tin[0];
l2c(tout0, out);
tout1 = tin[1];
l2c(tout1, out);
}
iv = ivec->bytes;
iv = ivec;
l2c(tout0, iv);
l2c(tout1, iv);
} else {
@@ -605,7 +698,7 @@ void DES_ncbc_encrypt(const uint8_t *in, uint8_t *out, size_t len,
tin[0] = tin0;
c2l(in, tin1);
tin[1] = tin1;
DES_encrypt1((uint32_t *)tin, schedule, DES_DECRYPT);
DES_encrypt1(tin, schedule, DES_DECRYPT);
tout0 = tin[0] ^ xor0;
tout1 = tin[1] ^ xor1;
l2c(tout0, out);
@@ -618,14 +711,14 @@ void DES_ncbc_encrypt(const uint8_t *in, uint8_t *out, size_t len,
tin[0] = tin0;
c2l(in, tin1);
tin[1] = tin1;
DES_encrypt1((uint32_t *)tin, schedule, DES_DECRYPT);
DES_encrypt1(tin, schedule, DES_DECRYPT);
tout0 = tin[0] ^ xor0;
tout1 = tin[1] ^ xor1;
l2cn(tout0, tout1, out, len);
xor0 = tin0;
xor1 = tin1;
}
iv = ivec->bytes;
iv = ivec;
l2c(xor0, iv);
l2c(xor1, iv);
}
@@ -635,24 +728,23 @@ void DES_ncbc_encrypt(const uint8_t *in, uint8_t *out, size_t len,
void DES_ecb3_encrypt(const DES_cblock *input, DES_cblock *output,
const DES_key_schedule *ks1, const DES_key_schedule *ks2,
const DES_key_schedule *ks3, int enc) {
uint32_t l0, l1;
uint32_t ll[2];
const uint8_t *in = input->bytes;
uint8_t *out = output->bytes;
DES_ecb3_encrypt_ex(input->bytes, output->bytes, ks1, ks2, ks3, enc);
}
c2l(in, l0);
c2l(in, l1);
ll[0] = l0;
ll[1] = l1;
void DES_ecb3_encrypt_ex(const uint8_t in[8], uint8_t out[8],
const DES_key_schedule *ks1,
const DES_key_schedule *ks2,
const DES_key_schedule *ks3, int enc) {
uint32_t ll[2];
ll[0] = CRYPTO_load_u32_le(in);
ll[1] = CRYPTO_load_u32_le(in + 4);
if (enc) {
DES_encrypt3(ll, ks1, ks2, ks3);
} else {
DES_decrypt3(ll, ks1, ks2, ks3);
}
l0 = ll[0];
l1 = ll[1];
l2c(l0, out);
l2c(l1, out);
CRYPTO_store_u32_le(out, ll[0]);
CRYPTO_store_u32_le(out + 4, ll[1]);
}
void DES_ede3_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len,
@@ -660,12 +752,20 @@ void DES_ede3_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len,
const DES_key_schedule *ks2,
const DES_key_schedule *ks3, DES_cblock *ivec,
int enc) {
DES_ede3_cbc_encrypt_ex(in, out, len, ks1, ks2, ks3, ivec->bytes, enc);
}
void DES_ede3_cbc_encrypt_ex(const uint8_t *in, uint8_t *out, size_t len,
const DES_key_schedule *ks1,
const DES_key_schedule *ks2,
const DES_key_schedule *ks3, uint8_t ivec[8],
int enc) {
uint32_t tin0, tin1;
uint32_t tout0, tout1, xor0, xor1;
uint32_t tin[2];
uint8_t *iv;
iv = ivec->bytes;
iv = ivec;
if (enc) {
c2l(iv, tout0);
@@ -678,7 +778,7 @@ void DES_ede3_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len,
tin[0] = tin0;
tin[1] = tin1;
DES_encrypt3((uint32_t *)tin, ks1, ks2, ks3);
DES_encrypt3(tin, ks1, ks2, ks3);
tout0 = tin[0];
tout1 = tin[1];
@@ -692,14 +792,14 @@ void DES_ede3_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len,
tin[0] = tin0;
tin[1] = tin1;
DES_encrypt3((uint32_t *)tin, ks1, ks2, ks3);
DES_encrypt3(tin, ks1, ks2, ks3);
tout0 = tin[0];
tout1 = tin[1];
l2c(tout0, out);
l2c(tout1, out);
}
iv = ivec->bytes;
iv = ivec;
l2c(tout0, iv);
l2c(tout1, iv);
} else {
@@ -716,7 +816,7 @@ void DES_ede3_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len,
tin[0] = tin0;
tin[1] = tin1;
DES_decrypt3((uint32_t *)tin, ks1, ks2, ks3);
DES_decrypt3(tin, ks1, ks2, ks3);
tout0 = tin[0];
tout1 = tin[1];
@@ -736,7 +836,7 @@ void DES_ede3_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len,
tin[0] = tin0;
tin[1] = tin1;
DES_decrypt3((uint32_t *)tin, ks1, ks2, ks3);
DES_decrypt3(tin, ks1, ks2, ks3);
tout0 = tin[0];
tout1 = tin[1];
@@ -747,7 +847,7 @@ void DES_ede3_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len,
xor1 = t1;
}
iv = ivec->bytes;
iv = ivec;
l2c(xor0, iv);
l2c(xor1, iv);
}
@@ -769,16 +869,3 @@ void DES_ede2_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len,
void DES_set_key_unchecked(const DES_cblock *key, DES_key_schedule *schedule) {
DES_set_key(key, schedule);
}
#undef HPERM_OP
#undef c2l
#undef l2c
#undef c2ln
#undef l2cn
#undef PERM_OP
#undef IP
#undef FP
#undef LOAD_DATA
#undef D_ENCRYPT
#undef ITERATIONS
#undef HALF_ITERATIONS
+31 -78
View File
@@ -58,6 +58,7 @@
#define OPENSSL_HEADER_DES_INTERNAL_H
#include <CCryptoBoringSSL_base.h>
#include <CCryptoBoringSSL_des.h>
#include "../internal.h"
@@ -66,6 +67,9 @@ extern "C" {
#endif
// TODO(davidben): Ideally these macros would be replaced with
// |CRYPTO_load_u32_le| and |CRYPTO_store_u32_le|.
#define c2l(c, l) \
do { \
(l) = ((uint32_t)(*((c)++))); \
@@ -145,90 +149,39 @@ extern "C" {
} \
} while (0)
/* IP and FP
* The problem is more of a geometric problem that random bit fiddling.
0 1 2 3 4 5 6 7 62 54 46 38 30 22 14 6
8 9 10 11 12 13 14 15 60 52 44 36 28 20 12 4
16 17 18 19 20 21 22 23 58 50 42 34 26 18 10 2
24 25 26 27 28 29 30 31 to 56 48 40 32 24 16 8 0
32 33 34 35 36 37 38 39 63 55 47 39 31 23 15 7
40 41 42 43 44 45 46 47 61 53 45 37 29 21 13 5
48 49 50 51 52 53 54 55 59 51 43 35 27 19 11 3
56 57 58 59 60 61 62 63 57 49 41 33 25 17 9 1
// Correctly-typed versions of DES functions.
//
// See https://crbug.com/boringssl/683.
The output has been subject to swaps of the form
0 1 -> 3 1 but the odd and even bits have been put into
2 3 2 0
different words. The main trick is to remember that
t=((l>>size)^r)&(mask);
r^=t;
l^=(t<<size);
can be used to swap and move bits between words.
void DES_set_key_ex(const uint8_t key[8], DES_key_schedule *schedule);
void DES_ecb_encrypt_ex(const uint8_t in[8], uint8_t out[8],
const DES_key_schedule *schedule, int is_encrypt);
void DES_ncbc_encrypt_ex(const uint8_t *in, uint8_t *out, size_t len,
const DES_key_schedule *schedule, uint8_t ivec[8],
int enc);
void DES_ecb3_encrypt_ex(const uint8_t input[8], uint8_t output[8],
const DES_key_schedule *ks1,
const DES_key_schedule *ks2,
const DES_key_schedule *ks3, int enc);
void DES_ede3_cbc_encrypt_ex(const uint8_t *in, uint8_t *out, size_t len,
const DES_key_schedule *ks1,
const DES_key_schedule *ks2,
const DES_key_schedule *ks3, uint8_t ivec[8],
int enc);
So l = 0 1 2 3 r = 16 17 18 19
4 5 6 7 20 21 22 23
8 9 10 11 24 25 26 27
12 13 14 15 28 29 30 31
becomes (for size == 2 and mask == 0x3333)
t = 2^16 3^17 -- -- l = 0 1 16 17 r = 2 3 18 19
6^20 7^21 -- -- 4 5 20 21 6 7 22 23
10^24 11^25 -- -- 8 9 24 25 10 11 24 25
14^28 15^29 -- -- 12 13 28 29 14 15 28 29
Thanks for hints from Richard Outerbridge - he told me IP&FP
could be done in 15 xor, 10 shifts and 5 ands.
When I finally started to think of the problem in 2D
I first got ~42 operations without xors. When I remembered
how to use xors :-) I got it to its final state.
*/
#define PERM_OP(a, b, t, n, m) \
do { \
(t) = ((((a) >> (n)) ^ (b)) & (m)); \
(b) ^= (t); \
(a) ^= ((t) << (n)); \
} while (0)
// Private functions.
//
// These functions are only exported for use in |decrepit|.
#define IP(l, r) \
do { \
uint32_t tt; \
PERM_OP(r, l, tt, 4, 0x0f0f0f0fL); \
PERM_OP(l, r, tt, 16, 0x0000ffffL); \
PERM_OP(r, l, tt, 2, 0x33333333L); \
PERM_OP(l, r, tt, 8, 0x00ff00ffL); \
PERM_OP(r, l, tt, 1, 0x55555555L); \
} while (0)
OPENSSL_EXPORT void DES_decrypt3(uint32_t data[2], const DES_key_schedule *ks1,
const DES_key_schedule *ks2,
const DES_key_schedule *ks3);
#define FP(l, r) \
do { \
uint32_t tt; \
PERM_OP(l, r, tt, 1, 0x55555555L); \
PERM_OP(r, l, tt, 8, 0x00ff00ffL); \
PERM_OP(l, r, tt, 2, 0x33333333L); \
PERM_OP(r, l, tt, 16, 0x0000ffffL); \
PERM_OP(l, r, tt, 4, 0x0f0f0f0fL); \
} while (0)
#define LOAD_DATA(ks, R, S, u, t, E0, E1) \
do { \
(u) = (R) ^ (ks)->subkeys[S][0]; \
(t) = (R) ^ (ks)->subkeys[S][1]; \
} while (0)
#define D_ENCRYPT(ks, LL, R, S) \
do { \
LOAD_DATA(ks, R, S, u, t, E0, E1); \
t = CRYPTO_rotr_u32(t, 4); \
(LL) ^= \
DES_SPtrans[0][(u >> 2L) & 0x3f] ^ DES_SPtrans[2][(u >> 10L) & 0x3f] ^ \
DES_SPtrans[4][(u >> 18L) & 0x3f] ^ \
DES_SPtrans[6][(u >> 26L) & 0x3f] ^ DES_SPtrans[1][(t >> 2L) & 0x3f] ^ \
DES_SPtrans[3][(t >> 10L) & 0x3f] ^ \
DES_SPtrans[5][(t >> 18L) & 0x3f] ^ DES_SPtrans[7][(t >> 26L) & 0x3f]; \
} while (0)
#define ITERATIONS 16
#define HALF_ITERATIONS 8
OPENSSL_EXPORT void DES_encrypt3(uint32_t data[2], const DES_key_schedule *ks1,
const DES_key_schedule *ks2,
const DES_key_schedule *ks3);
#if defined(__cplusplus)
@@ -110,6 +110,10 @@ DH *DH_parse_parameters(CBS *cbs) {
goto err;
}
if (!dh_check_params_fast(ret)) {
goto err;
}
return ret;
err:
@@ -337,6 +337,11 @@ int DH_generate_parameters_ex(DH *dh, int prime_bits, int generator,
// It's just as OK (and in some sense better) to use a generator of the
// order-q subgroup.
if (prime_bits <= 0 || prime_bits > OPENSSL_DH_MAX_MODULUS_BITS) {
OPENSSL_PUT_ERROR(DH, DH_R_MODULUS_TOO_LARGE);
return 0;
}
BIGNUM *t1, *t2;
int g, ok = 0;
BN_CTX *ctx = NULL;
@@ -61,6 +61,8 @@
#include <CCryptoBoringSSL_blake2.h>
#include <CCryptoBoringSSL_bytestring.h>
#include <CCryptoBoringSSL_obj.h>
#include <CCryptoBoringSSL_md4.h>
#include <CCryptoBoringSSL_md5.h>
#include <CCryptoBoringSSL_nid.h>
#include "../asn1/internal.h"
@@ -200,7 +202,6 @@ int EVP_marshal_digest_algorithm(CBB *cbb, const EVP_MD *md) {
CBB algorithm, oid, null;
if (!CBB_add_asn1(cbb, &algorithm, CBS_ASN1_SEQUENCE) ||
!CBB_add_asn1(&algorithm, &oid, CBS_ASN1_OBJECT)) {
OPENSSL_PUT_ERROR(DIGEST, ERR_R_MALLOC_FAILURE);
return 0;
}
@@ -209,7 +210,6 @@ int EVP_marshal_digest_algorithm(CBB *cbb, const EVP_MD *md) {
for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kMDOIDs); i++) {
if (nid == kMDOIDs[i].nid) {
if (!CBB_add_bytes(&oid, kMDOIDs[i].oid, kMDOIDs[i].oid_len)) {
OPENSSL_PUT_ERROR(DIGEST, ERR_R_MALLOC_FAILURE);
return 0;
}
found = 1;
@@ -222,9 +222,9 @@ int EVP_marshal_digest_algorithm(CBB *cbb, const EVP_MD *md) {
return 0;
}
// TODO(crbug.com/boringssl/710): Is this correct? See RFC 4055, section 2.1.
if (!CBB_add_asn1(&algorithm, &null, CBS_ASN1_NULL) ||
!CBB_flush(cbb)) {
OPENSSL_PUT_ERROR(DIGEST, ERR_R_MALLOC_FAILURE);
return 0;
}
@@ -266,3 +266,90 @@ static const EVP_MD evp_md_blake2b256 = {
};
const EVP_MD *EVP_blake2b256(void) { return &evp_md_blake2b256; }
static void md4_init(EVP_MD_CTX *ctx) {
BSSL_CHECK(MD4_Init(ctx->md_data));
}
static void md4_update(EVP_MD_CTX *ctx, const void *data, size_t count) {
BSSL_CHECK(MD4_Update(ctx->md_data, data, count));
}
static void md4_final(EVP_MD_CTX *ctx, uint8_t *out) {
BSSL_CHECK(MD4_Final(out, ctx->md_data));
}
static const EVP_MD evp_md_md4 = {
NID_md4,
MD4_DIGEST_LENGTH,
0,
md4_init,
md4_update,
md4_final,
64,
sizeof(MD4_CTX),
};
const EVP_MD *EVP_md4(void) { return &evp_md_md4; }
static void md5_init(EVP_MD_CTX *ctx) {
BSSL_CHECK(MD5_Init(ctx->md_data));
}
static void md5_update(EVP_MD_CTX *ctx, const void *data, size_t count) {
BSSL_CHECK(MD5_Update(ctx->md_data, data, count));
}
static void md5_final(EVP_MD_CTX *ctx, uint8_t *out) {
BSSL_CHECK(MD5_Final(out, ctx->md_data));
}
static const EVP_MD evp_md_md5 = {
NID_md5,
MD5_DIGEST_LENGTH,
0,
md5_init,
md5_update,
md5_final,
64,
sizeof(MD5_CTX),
};
const EVP_MD *EVP_md5(void) { return &evp_md_md5; }
typedef struct {
MD5_CTX md5;
SHA_CTX sha1;
} MD5_SHA1_CTX;
static void md5_sha1_init(EVP_MD_CTX *md_ctx) {
MD5_SHA1_CTX *ctx = md_ctx->md_data;
BSSL_CHECK(MD5_Init(&ctx->md5) && SHA1_Init(&ctx->sha1));
}
static void md5_sha1_update(EVP_MD_CTX *md_ctx, const void *data,
size_t count) {
MD5_SHA1_CTX *ctx = md_ctx->md_data;
BSSL_CHECK(MD5_Update(&ctx->md5, data, count) &&
SHA1_Update(&ctx->sha1, data, count));
}
static void md5_sha1_final(EVP_MD_CTX *md_ctx, uint8_t *out) {
MD5_SHA1_CTX *ctx = md_ctx->md_data;
BSSL_CHECK(MD5_Final(out, &ctx->md5) &&
SHA1_Final(out + MD5_DIGEST_LENGTH, &ctx->sha1));
}
const EVP_MD evp_md_md5_sha1 = {
NID_md5_sha1,
MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH,
0,
md5_sha1_init,
md5_sha1_update,
md5_sha1_final,
64,
sizeof(MD5_SHA1_CTX),
};
const EVP_MD *EVP_md5_sha1(void) { return &evp_md_md5_sha1; }
Loaded 100 of 825 files, more files were not shown because too many files have changed in this diff. Show more